idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
54,100
def ends_to_curve ( start_node , end_node ) : if is_first ( start_node . interior_curve ) : if end_node . index_first != start_node . index_first : raise ValueError ( _WRONG_CURVE ) return start_node . index_first , start_node . s , end_node . s elif is_second ( start_node . interior_curve ) : if end_node . index_secon...
Convert a pair of intersection nodes to a curve segment .
54,101
def no_intersections ( nodes1 , degree1 , nodes2 , degree2 ) : r from bezier import _surface_intersection located = _surface_intersection . locate_point ( nodes2 , degree2 , nodes1 [ 0 , 0 ] , nodes1 [ 1 , 0 ] ) if located is not None : return None , True located = _surface_intersection . locate_point ( nodes1 , degree...
r Determine if one surface is in the other .
54,102
def tangent_only_intersections ( all_types ) : if len ( all_types ) != 1 : raise ValueError ( "Unexpected value, types should all match" , all_types ) point_type = all_types . pop ( ) if point_type == CLASSIFICATION_T . OPPOSED : return [ ] , None elif point_type == CLASSIFICATION_T . IGNORED_CORNER : return [ ] , None...
Determine intersection in the case of only - tangent intersections .
54,103
def basic_interior_combine ( intersections , max_edges = 10 ) : unused = intersections [ : ] result = [ ] while unused : start = unused . pop ( ) curr_node = start next_node = get_next ( curr_node , intersections , unused ) edge_ends = [ ( curr_node , next_node ) ] while next_node is not start : curr_node = to_front ( ...
Combine intersections that don t involve tangencies .
54,104
def _evaluate_barycentric ( nodes , degree , lambda1 , lambda2 , lambda3 ) : r dimension , num_nodes = nodes . shape binom_val = 1.0 result = np . zeros ( ( dimension , 1 ) , order = "F" ) index = num_nodes - 1 result [ : , 0 ] += nodes [ : , index ] lambda1 = np . asfortranarray ( [ lambda1 ] ) lambda2 = np . asfortra...
r Compute a point on a surface .
54,105
def _compute_edge_nodes ( nodes , degree ) : dimension , _ = np . shape ( nodes ) nodes1 = np . empty ( ( dimension , degree + 1 ) , order = "F" ) nodes2 = np . empty ( ( dimension , degree + 1 ) , order = "F" ) nodes3 = np . empty ( ( dimension , degree + 1 ) , order = "F" ) curr2 = degree curr3 = - 1 for i in six . m...
Compute the nodes of each edges of a surface .
54,106
def shoelace_for_area ( nodes ) : r _ , num_nodes = nodes . shape if num_nodes == 2 : shoelace = SHOELACE_LINEAR scale_factor = 2.0 elif num_nodes == 3 : shoelace = SHOELACE_QUADRATIC scale_factor = 6.0 elif num_nodes == 4 : shoelace = SHOELACE_CUBIC scale_factor = 20.0 elif num_nodes == 5 : shoelace = SHOELACE_QUARTIC...
r Compute an auxiliary shoelace sum used to compute area .
54,107
def save_image ( figure , filename ) : path = os . path . join ( IMAGES_DIR , filename ) figure . savefig ( path , bbox_inches = "tight" ) plt . close ( figure )
Save an image to the docs images directory .
54,108
def stack1d ( * points ) : result = np . empty ( ( 2 , len ( points ) ) , order = "F" ) for index , point in enumerate ( points ) : result [ : , index ] = point return result
Fill out the columns of matrix with a series of points .
54,109
def _edges_classify_intersection9 ( ) : edges1 = ( bezier . Curve . from_nodes ( np . asfortranarray ( [ [ 32.0 , 30.0 ] , [ 20.0 , 25.0 ] ] ) ) , bezier . Curve . from_nodes ( np . asfortranarray ( [ [ 30.0 , 25.0 , 20.0 ] , [ 25.0 , 20.0 , 20.0 ] ] ) ) , bezier . Curve . from_nodes ( np . asfortranarray ( [ [ 20.0 , ...
The edges for the curved polygon intersection used below .
54,110
def update_locate_candidates ( candidate , next_candidates , x_val , y_val , degree ) : centroid_x , centroid_y , width , candidate_nodes = candidate point = np . asfortranarray ( [ x_val , y_val ] ) if not _helpers . contains_nd ( candidate_nodes , point ) : return nodes_a , nodes_b , nodes_c , nodes_d = _surface_help...
Update list of candidate surfaces during geometric search for a point .
54,111
def mean_centroid ( candidates ) : sum_x = 0.0 sum_y = 0.0 for centroid_x , centroid_y , _ , _ in candidates : sum_x += centroid_x sum_y += centroid_y denom = 3.0 * len ( candidates ) return sum_x / denom , sum_y / denom
Take the mean of all centroids in set of reference triangles .
54,112
def _locate_point ( nodes , degree , x_val , y_val ) : r candidates = [ ( 1.0 , 1.0 , 1.0 , nodes ) ] for _ in six . moves . xrange ( MAX_LOCATE_SUBDIVISIONS + 1 ) : next_candidates = [ ] for candidate in candidates : update_locate_candidates ( candidate , next_candidates , x_val , y_val , degree ) candidates = next_ca...
r Locate a point on a surface .
54,113
def same_intersection ( intersection1 , intersection2 , wiggle = 0.5 ** 40 ) : if intersection1 . index_first != intersection2 . index_first : return False if intersection1 . index_second != intersection2 . index_second : return False return np . allclose ( [ intersection1 . s , intersection1 . t ] , [ intersection2 . ...
Check if two intersections are close to machine precision .
54,114
def verify_duplicates ( duplicates , uniques ) : for uniq1 , uniq2 in itertools . combinations ( uniques , 2 ) : if same_intersection ( uniq1 , uniq2 ) : raise ValueError ( "Non-unique intersection" ) counter = collections . Counter ( ) for dupe in duplicates : matches = [ ] for index , uniq in enumerate ( uniques ) : ...
Verify that a set of intersections had expected duplicates .
54,115
def verify_edge_segments ( edge_infos ) : if edge_infos is None : return for edge_info in edge_infos : num_segments = len ( edge_info ) for index in six . moves . xrange ( - 1 , num_segments - 1 ) : index1 , start1 , end1 = edge_info [ index ] if not 0.0 <= start1 < end1 <= 1.0 : raise ValueError ( BAD_SEGMENT_PARAMS ,...
Verify that the edge segments in an intersection are valid .
54,116
def add_edge_end_unused ( intersection , duplicates , intersections ) : found = None for other in intersections : if ( intersection . index_first == other . index_first and intersection . index_second == other . index_second ) : if intersection . s == 0.0 and other . s == 0.0 : found = other break if intersection . t =...
Add intersection that is COINCIDENT_UNUSED but on an edge end .
54,117
def check_unused ( intersection , duplicates , intersections ) : for other in intersections : if ( other . interior_curve == UNUSED_T and intersection . index_first == other . index_first and intersection . index_second == other . index_second ) : if intersection . s == 0.0 and other . s == 0.0 : duplicates . append ( ...
Check if a valid intersection is already in intersections .
54,118
def classify_coincident ( st_vals , coincident ) : r if not coincident : return None if st_vals [ 0 , 0 ] >= st_vals [ 0 , 1 ] or st_vals [ 1 , 0 ] >= st_vals [ 1 , 1 ] : return UNUSED_T else : return CLASSIFICATION_T . COINCIDENT
r Determine if coincident parameters are unused .
54,119
def should_use ( intersection ) : if intersection . interior_curve in ACCEPTABLE_CLASSIFICATIONS : return True if intersection . interior_curve in TANGENT_CLASSIFICATIONS : return intersection . s == 0.0 or intersection . t == 0.0 return False
Check if an intersection can be used as part of a curved polygon .
54,120
def surface_intersections ( edge_nodes1 , edge_nodes2 , all_intersections ) : intersections = [ ] duplicates = [ ] for index1 , nodes1 in enumerate ( edge_nodes1 ) : for index2 , nodes2 in enumerate ( edge_nodes2 ) : st_vals , coincident = all_intersections ( nodes1 , nodes2 ) interior_curve = classify_coincident ( st_...
Find all intersections among edges of two surfaces .
54,121
def modify_path ( ) : if os . name != "nt" : return path = os . environ . get ( "PATH" ) if path is None : return try : extra_dll_dir = pkg_resources . resource_filename ( "bezier" , "extra-dll" ) if os . path . isdir ( extra_dll_dir ) : os . environ [ "PATH" ] = path + os . pathsep + extra_dll_dir except ImportError :...
Modify the module search path .
54,122
def handle_import_error ( caught_exc , name ) : for template in TEMPLATES : expected_msg = template . format ( name ) if caught_exc . args == ( expected_msg , ) : return raise caught_exc
Allow or re - raise an import error .
54,123
def is_macos_gfortran ( f90_compiler ) : from numpy . distutils . fcompiler import gnu if sys . platform != MAC_OS : return False if not isinstance ( f90_compiler , gnu . Gnu95FCompiler ) : return False return True
Checks if the current build is gfortran on macOS .
54,124
def _make_intersection ( edge_info , all_edge_nodes ) : edges = [ ] for index , start , end in edge_info : nodes = all_edge_nodes [ index ] new_nodes = _curve_helpers . specialize_curve ( nodes , start , end ) degree = new_nodes . shape [ 1 ] - 1 edge = _curve_mod . Curve ( new_nodes , degree , _copy = False ) edges . ...
Convert a description of edges into a curved polygon .
54,125
def _get_degree ( num_nodes ) : d_float = 0.5 * ( np . sqrt ( 8.0 * num_nodes + 1.0 ) - 3.0 ) d_int = int ( np . round ( d_float ) ) if ( d_int + 1 ) * ( d_int + 2 ) == 2 * num_nodes : return d_int else : raise ValueError ( num_nodes , "not a triangular number" )
Get the degree of the current surface .
54,126
def area ( self ) : r if self . _dimension != 2 : raise NotImplementedError ( "2D is the only supported dimension" , "Current dimension" , self . _dimension , ) edge1 , edge2 , edge3 = self . _get_edges ( ) return _surface_helpers . compute_area ( ( edge1 . _nodes , edge2 . _nodes , edge3 . _nodes ) )
r The area of the current surface .
54,127
def _compute_edges ( self ) : nodes1 , nodes2 , nodes3 = _surface_helpers . compute_edge_nodes ( self . _nodes , self . _degree ) edge1 = _curve_mod . Curve ( nodes1 , self . _degree , _copy = False ) edge2 = _curve_mod . Curve ( nodes2 , self . _degree , _copy = False ) edge3 = _curve_mod . Curve ( nodes3 , self . _de...
Compute the edges of the current surface .
54,128
def _get_edges ( self ) : if self . _edges is None : self . _edges = self . _compute_edges ( ) return self . _edges
Get the edges for the current surface .
54,129
def edges ( self ) : edge1 , edge2 , edge3 = self . _get_edges ( ) edge1 = edge1 . _copy ( ) edge2 = edge2 . _copy ( ) edge3 = edge3 . _copy ( ) return edge1 , edge2 , edge3
The edges of the surface .
54,130
def _verify_barycentric ( lambda1 , lambda2 , lambda3 ) : weights_total = lambda1 + lambda2 + lambda3 if not np . allclose ( weights_total , 1.0 , atol = 0.0 ) : raise ValueError ( "Weights do not sum to 1" , lambda1 , lambda2 , lambda3 ) if lambda1 < 0.0 or lambda2 < 0.0 or lambda3 < 0.0 : raise ValueError ( "Weights ...
Verifies that weights are barycentric and on the reference triangle .
54,131
def _verify_cartesian ( s , t ) : if s < 0.0 or t < 0.0 or s + t > 1.0 : raise ValueError ( "Point lies outside reference triangle" , s , t )
Verifies that a point is in the reference triangle .
54,132
def plot ( self , pts_per_edge , color = None , ax = None , with_nodes = False ) : if self . _dimension != 2 : raise NotImplementedError ( "2D is the only supported dimension" , "Current dimension" , self . _dimension , ) if ax is None : ax = _plot_helpers . new_axis ( ) _plot_helpers . add_patch ( ax , color , pts_per...
Plot the current surface .
54,133
def subdivide ( self ) : r nodes_a , nodes_b , nodes_c , nodes_d = _surface_helpers . subdivide_nodes ( self . _nodes , self . _degree ) return ( Surface ( nodes_a , self . _degree , _copy = False ) , Surface ( nodes_b , self . _degree , _copy = False ) , Surface ( nodes_c , self . _degree , _copy = False ) , Surface (...
r Split the surface into four sub - surfaces .
54,134
def _compute_valid ( self ) : r if self . _dimension != 2 : raise NotImplementedError ( "Validity check only implemented in R^2" ) poly_sign = None if self . _degree == 1 : first_deriv = self . _nodes [ : , 1 : ] - self . _nodes [ : , : - 1 ] poly_sign = _SIGN ( np . linalg . det ( first_deriv ) ) elif self . _degree =...
r Determines if the current surface is valid .
54,135
def locate ( self , point , _verify = True ) : r if _verify : if self . _dimension != 2 : raise NotImplementedError ( "Only 2D surfaces supported." ) if point . shape != ( self . _dimension , 1 ) : point_dimensions = " x " . join ( str ( dimension ) for dimension in point . shape ) msg = _LOCATE_ERROR_TEMPLATE . format...
r Find a point on the current surface .
54,136
def intersect ( self , other , strategy = _STRATEGY . GEOMETRIC , _verify = True ) : if _verify : if not isinstance ( other , Surface ) : raise TypeError ( "Can only intersect with another surface" , "Received" , other , ) if self . _dimension != 2 or other . _dimension != 2 : raise NotImplementedError ( "Intersection ...
Find the common intersection with another surface .
54,137
def elevate ( self ) : r _ , num_nodes = self . _nodes . shape num_new = num_nodes + self . _degree + 2 new_nodes = np . zeros ( ( self . _dimension , num_new ) , order = "F" ) index = 0 parent_i1 = 0 parent_i2 = 1 parent_i3 = self . _degree + 2 for k in six . moves . xrange ( self . _degree + 1 ) : for j in six . move...
r Return a degree - elevated version of the current surface .
54,138
def _newton_refine ( s , nodes1 , t , nodes2 ) : r func_val = _curve_helpers . evaluate_multi ( nodes2 , np . asfortranarray ( [ t ] ) ) - _curve_helpers . evaluate_multi ( nodes1 , np . asfortranarray ( [ s ] ) ) if np . all ( func_val == 0.0 ) : return s , t jac_mat = np . empty ( ( 2 , 2 ) , order = "F" ) jac_mat [ ...
r Apply one step of 2D Newton s method .
54,139
def newton_iterate ( evaluate_fn , s , t ) : r norm_update_prev = None norm_update = None linear_updates = 0 current_s = s current_t = t for index in six . moves . xrange ( MAX_NEWTON_ITERATIONS ) : jacobian , func_val = evaluate_fn ( current_s , current_t ) if jacobian is None : return True , current_s , current_t sin...
r Perform a Newton iteration .
54,140
def gfortran_search_path ( library_dirs ) : cmd = ( "gfortran" , "-print-search-dirs" ) process = subprocess . Popen ( cmd , stdout = subprocess . PIPE ) return_code = process . wait ( ) if return_code != 0 : return library_dirs cmd_output = process . stdout . read ( ) . decode ( "utf-8" ) search_lines = cmd_output . s...
Get the library directory paths for gfortran .
54,141
def _update_flags ( compiler_flags , remove_flags = ( ) ) : for flag in GFORTRAN_SHARED_FLAGS : if flag not in compiler_flags : compiler_flags . append ( flag ) if DEBUG_ENV in os . environ : to_add = GFORTRAN_DEBUG_FLAGS to_remove = GFORTRAN_OPTIMIZE_FLAGS else : to_add = GFORTRAN_OPTIMIZE_FLAGS if os . environ . get ...
Update a given set of compiler flags .
54,142
def patch_f90_compiler ( f90_compiler ) : from numpy . distutils . fcompiler import gnu if not isinstance ( f90_compiler , gnu . Gnu95FCompiler ) : return False f90_compiler . compiler_f77 [ : ] = _update_flags ( f90_compiler . compiler_f77 , remove_flags = ( "-Werror" , ) ) f90_compiler . compiler_f90 [ : ] = _update_...
Patch up f90_compiler .
54,143
def start_journaling ( self ) : import numpy . distutils . ccompiler if self . journal_file is None : return def journaled_spawn ( patched_self , cmd , display = None ) : self . commands . append ( cmd ) return numpy . distutils . ccompiler . CCompiler_spawn ( patched_self , cmd , display = None ) numpy . distutils . c...
Capture calls to the system by compilers .
54,144
def save_journal ( self ) : if self . journal_file is None : return try : as_text = self . _commands_to_text ( ) with open ( self . journal_file , "w" ) as file_obj : file_obj . write ( as_text ) except Exception as exc : msg = BAD_JOURNAL . format ( exc ) print ( msg , file = sys . stderr )
Save journaled commands to file .
54,145
def _verify_pair ( prev , curr ) : if prev . _dimension != 2 : raise ValueError ( "Curve not in R^2" , prev ) end = prev . _nodes [ : , - 1 ] start = curr . _nodes [ : , 0 ] if not _helpers . vector_close ( end , start ) : raise ValueError ( "Not sufficiently close" , "Consecutive sides do not have common endpoint" , p...
Verify a pair of sides share an endpoint .
54,146
def _verify ( self ) : if self . _num_sides < 2 : raise ValueError ( "At least two sides required." ) for prev , curr in six . moves . zip ( self . _edges , self . _edges [ 1 : ] ) : self . _verify_pair ( prev , curr ) prev = self . _edges [ - 1 ] curr = self . _edges [ 0 ] self . _verify_pair ( prev , curr )
Verify that the edges define a curved polygon .
54,147
def area ( self ) : r edges = tuple ( edge . _nodes for edge in self . _edges ) return _surface_helpers . compute_area ( edges )
r The area of the current curved polygon .
54,148
def plot ( self , pts_per_edge , color = None , ax = None ) : if ax is None : ax = _plot_helpers . new_axis ( ) _plot_helpers . add_patch ( ax , color , pts_per_edge , * self . _edges ) return ax
Plot the current curved polygon .
54,149
def compute_implicit_line ( nodes ) : delta = nodes [ : , - 1 ] - nodes [ : , 0 ] length = np . linalg . norm ( delta , ord = 2 ) coeff_a = - delta [ 1 ] / length coeff_b = delta [ 0 ] / length coeff_c = ( delta [ 1 ] * nodes [ 0 , 0 ] - delta [ 0 ] * nodes [ 1 , 0 ] ) / length return coeff_a , coeff_b , coeff_c
Compute the implicit form of the line connecting curve endpoints .
54,150
def compute_fat_line ( nodes ) : coeff_a , coeff_b , coeff_c = compute_implicit_line ( nodes ) _ , num_nodes = nodes . shape d_min = 0.0 d_max = 0.0 for index in six . moves . xrange ( 1 , num_nodes - 1 ) : curr_dist = ( coeff_a * nodes [ 0 , index ] + coeff_b * nodes [ 1 , index ] + coeff_c ) if curr_dist < d_min : d_...
Compute the fat line around a B |eacute| zier curve .
54,151
def _update_parameters ( s_min , s_max , start0 , end0 , start1 , end1 ) : s , t , success = _geometric_intersection . segment_intersection ( start0 , end0 , start1 , end1 ) if not success : raise NotImplementedError ( NO_PARALLEL ) if _helpers . in_interval ( t , 0.0 , 1.0 ) : if _helpers . in_interval ( s , 0.0 , s_m...
Update clipped parameter range .
54,152
def _check_parameter_range ( s_min , s_max ) : r if s_min == DEFAULT_S_MIN : return 0.0 , 1.0 if s_max == DEFAULT_S_MAX : return s_min , s_min return s_min , s_max
r Performs a final check on a clipped parameter range .
54,153
def clip_range ( nodes1 , nodes2 ) : r coeff_a , coeff_b , coeff_c , d_min , d_max = compute_fat_line ( nodes1 ) _ , num_nodes2 = nodes2 . shape polynomial = np . empty ( ( 2 , num_nodes2 ) , order = "F" ) denominator = float ( num_nodes2 - 1 ) for index in six . moves . xrange ( num_nodes2 ) : polynomial [ 0 , index ]...
r Reduce the parameter range where two curves can intersect .
54,154
def post_process_travis_macos ( journal_filename ) : travis_build_dir = os . environ . get ( "TRAVIS_BUILD_DIR" , "" ) with open ( journal_filename , "r" ) as file_obj : content = file_obj . read ( ) processed = content . replace ( travis_build_dir , "${TRAVIS_BUILD_DIR}" ) with open ( journal_filename , "w" ) as file_...
Post - process a generated journal file on Travis macOS .
54,155
def get_diff ( value1 , value2 , name1 , name2 ) : lines1 = [ line + "\n" for line in value1 . splitlines ( ) ] lines2 = [ line + "\n" for line in value2 . splitlines ( ) ] diff_lines = difflib . context_diff ( lines1 , lines2 , fromfile = name1 , tofile = name2 ) return "" . join ( diff_lines )
Get a diff between two strings .
54,156
def populate_readme ( revision , rtd_version , ** extra_kwargs ) : with open ( TEMPLATE_FILE , "r" ) as file_obj : template = file_obj . read ( ) img_prefix = IMG_PREFIX . format ( revision = revision ) extra_links = EXTRA_LINKS . format ( rtd_version = rtd_version , revision = revision ) docs_img = DOCS_IMG . format (...
Populate README template with values .
54,157
def readme_verify ( ) : expected = populate_readme ( REVISION , RTD_VERSION ) with open ( README_FILE , "r" ) as file_obj : contents = file_obj . read ( ) if contents != expected : err_msg = "\n" + get_diff ( contents , expected , "README.rst.actual" , "README.rst.expected" ) raise ValueError ( err_msg ) else : print (...
Populate the template and compare to README .
54,158
def release_readme_verify ( ) : version = "{version}" expected = populate_readme ( version , version , pypi = "" , pypi_img = "" , versions = "\n\n" , versions_img = "" , circleci_badge = CIRCLECI_BADGE_RELEASE , circleci_path = "/{circleci_build}" , travis_badge = TRAVIS_BADGE_RELEASE , travis_path = "/builds/{travis_...
Specialize the template to a PyPI release template .
54,159
def _index_verify ( index_file , ** extra_kwargs ) : side_effect = extra_kwargs . pop ( "side_effect" , None ) with open ( TEMPLATE_FILE , "r" ) as file_obj : template = file_obj . read ( ) template_kwargs = { "code_block1" : SPHINX_CODE_BLOCK1 , "code_block2" : SPHINX_CODE_BLOCK2 , "code_block3" : SPHINX_CODE_BLOCK3 ,...
Populate the template and compare to documentation index file .
54,160
def release_docs_side_effect ( content ) : result = content . replace ( "{" , "{{" ) . replace ( "}" , "}}" ) result = result . replace ( "{{version}}" , "{version}" ) result = result . replace ( "{{circleci_build}}" , "{circleci_build}" ) result = result . replace ( "{{travis_build}}" , "{travis_build}" ) result = res...
Updates the template so that curly braces are escaped correctly .
54,161
def development_verify ( ) : with open ( DEVELOPMENT_TEMPLATE , "r" ) as file_obj : template = file_obj . read ( ) expected = template . format ( revision = REVISION , rtd_version = RTD_VERSION ) with open ( DEVELOPMENT_FILE , "r" ) as file_obj : contents = file_obj . read ( ) if contents != expected : err_msg = "\n" +...
Populate template and compare to DEVELOPMENT . rst
54,162
def native_libraries_verify ( ) : with open ( BINARY_EXT_TEMPLATE , "r" ) as file_obj : template = file_obj . read ( ) expected = template . format ( revision = REVISION ) with open ( BINARY_EXT_FILE , "r" ) as file_obj : contents = file_obj . read ( ) if contents != expected : err_msg = "\n" + get_diff ( contents , ex...
Populate the template and compare to binary - extension . rst .
54,163
def evaluate ( nodes , x_val , y_val ) : r _ , num_nodes = nodes . shape if num_nodes == 1 : raise ValueError ( "A point cannot be implicitized" ) elif num_nodes == 2 : return ( nodes [ 0 , 0 ] - x_val ) * ( nodes [ 1 , 1 ] - y_val ) - ( nodes [ 0 , 1 ] - x_val ) * ( nodes [ 1 , 0 ] - y_val ) elif num_nodes == 3 : val_...
r Evaluate the implicitized bivariate polynomial containing the curve .
54,164
def _get_sigma_coeffs ( coeffs ) : r num_nodes , = coeffs . shape degree = num_nodes - 1 effective_degree = None for index in six . moves . range ( degree , - 1 , - 1 ) : if coeffs [ index ] != 0.0 : effective_degree = index break if effective_degree is None : return None , 0 , 0 if effective_degree == 0 : return None ...
r Compute transformed form of polynomial in Bernstein form .
54,165
def bernstein_companion ( coeffs ) : r sigma_coeffs , degree , effective_degree = _get_sigma_coeffs ( coeffs ) if effective_degree == 0 : return np . empty ( ( 0 , 0 ) , order = "F" ) , degree , 0 companion = np . zeros ( ( effective_degree , effective_degree ) , order = "F" ) companion . flat [ effective_degree : : ef...
r Compute a companion matrix for a polynomial in Bernstein basis .
54,166
def bezier_roots ( coeffs ) : r companion , degree , effective_degree = bernstein_companion ( coeffs ) if effective_degree : sigma_roots = np . linalg . eigvals ( companion ) to_keep = np . abs ( sigma_roots + 1.0 ) > _SIGMA_THRESHOLD sigma_roots = sigma_roots [ to_keep ] s_vals = sigma_roots / ( 1.0 + sigma_roots ) el...
r Compute polynomial roots from a polynomial in the Bernstein basis .
54,167
def _reciprocal_condition_number ( lu_mat , one_norm ) : r if _scipy_lapack is None : raise OSError ( "This function requires SciPy for calling into LAPACK." ) rcond , info = _scipy_lapack . dgecon ( lu_mat , one_norm ) if info != 0 : raise RuntimeError ( "The reciprocal 1-norm condition number could not be computed." ...
r Compute reciprocal condition number of a matrix .
54,168
def bezier_value_check ( coeffs , s_val , rhs_val = 0.0 ) : r if s_val == 1.0 : return coeffs [ - 1 ] == rhs_val shifted_coeffs = coeffs - rhs_val sigma_coeffs , _ , effective_degree = _get_sigma_coeffs ( shifted_coeffs ) if effective_degree == 0 : return shifted_coeffs [ 0 ] == 0.0 sigma_val = s_val / ( 1.0 - s_val ) ...
r Check if a polynomial in the Bernstein basis evaluates to a value .
54,169
def roots_in_unit_interval ( coeffs ) : r all_roots = polynomial . polyroots ( coeffs ) all_roots = all_roots [ ( _UNIT_INTERVAL_WIGGLE_START < all_roots . real ) & ( all_roots . real < _UNIT_INTERVAL_WIGGLE_END ) ] real_inds = np . abs ( all_roots . imag ) < _IMAGINARY_WIGGLE return all_roots [ real_inds ] . real
r Compute roots of a polynomial in the unit interval .
54,170
def _strip_leading_zeros ( coeffs , threshold = _COEFFICIENT_THRESHOLD ) : r while np . abs ( coeffs [ - 1 ] ) < threshold : coeffs = coeffs [ : - 1 ] return coeffs
r Strip leading zero coefficients from a polynomial .
54,171
def _check_non_simple ( coeffs ) : r coeffs = _strip_leading_zeros ( coeffs ) num_coeffs , = coeffs . shape if num_coeffs < 3 : return deriv_poly = polynomial . polyder ( coeffs ) companion = polynomial . polycompanion ( deriv_poly ) companion = companion . T num_companion , _ = companion . shape id_mat = np . eye ( nu...
r Checks that a polynomial has no non - simple roots .
54,172
def _resolve_and_add ( nodes1 , s_val , final_s , nodes2 , t_val , final_t ) : s_val , t_val = _intersection_helpers . newton_refine ( s_val , nodes1 , t_val , nodes2 ) s_val , success_s = _helpers . wiggle_interval ( s_val ) t_val , success_t = _helpers . wiggle_interval ( t_val ) if not ( success_s and success_t ) : ...
Resolve a computed intersection and add to lists .
54,173
def intersect_curves ( nodes1 , nodes2 ) : r nodes1 = _curve_helpers . full_reduce ( nodes1 ) nodes2 = _curve_helpers . full_reduce ( nodes2 ) _ , num_nodes1 = nodes1 . shape _ , num_nodes2 = nodes2 . shape swapped = False if num_nodes1 > num_nodes2 : nodes1 , nodes2 = nodes2 , nodes1 swapped = True coeffs = normalize_...
r Intersect two parametric B |eacute| zier curves .
54,174
def poly_to_power_basis ( bezier_coeffs ) : num_coeffs , = bezier_coeffs . shape if num_coeffs == 1 : return bezier_coeffs elif num_coeffs == 2 : coeff0 , coeff1 = bezier_coeffs return np . asfortranarray ( [ coeff0 , coeff1 - coeff0 ] ) elif num_coeffs == 3 : coeff0 , coeff1 , coeff2 = bezier_coeffs return np . asfort...
Convert a B |eacute| zier curve to polynomial in power basis .
54,175
def locate_point ( nodes , x_val , y_val ) : r zero1 = _curve_helpers . full_reduce ( nodes [ [ 0 ] , : ] ) - x_val zero2 = _curve_helpers . full_reduce ( nodes [ [ 1 ] , : ] ) - y_val if zero1 . shape [ 1 ] > zero2 . shape [ 1 ] : zero1 , zero2 = zero2 , zero1 if zero1 . shape [ 1 ] == 1 : zero1 , zero2 = zero2 , zero...
r Find the parameter corresponding to a point on a curve .
54,176
def _vector_close ( vec1 , vec2 , eps = _EPS ) : r size1 = np . linalg . norm ( vec1 , ord = 2 ) size2 = np . linalg . norm ( vec2 , ord = 2 ) if size1 == 0 : return size2 <= eps elif size2 == 0 : return size1 <= eps else : upper_bound = eps * min ( size1 , size2 ) return np . linalg . norm ( vec1 - vec2 , ord = 2 ) <=...
r Checks that two vectors are equal to some threshold .
54,177
def _bbox ( nodes ) : left , bottom = np . min ( nodes , axis = 1 ) right , top = np . max ( nodes , axis = 1 ) return left , right , bottom , top
Get the bounding box for set of points .
54,178
def _contains_nd ( nodes , point ) : r min_vals = np . min ( nodes , axis = 1 ) if not np . all ( min_vals <= point ) : return False max_vals = np . max ( nodes , axis = 1 ) if not np . all ( point <= max_vals ) : return False return True
r Predicate indicating if a point is within a bounding box .
54,179
def matrix_product ( mat1 , mat2 ) : return np . dot ( mat2 . T , mat1 . T ) . T
Compute the product of two Fortran contiguous matrices .
54,180
def cross_product_compare ( start , candidate1 , candidate2 ) : delta1 = candidate1 - start delta2 = candidate2 - start return cross_product ( delta1 , delta2 )
Compare two relative changes by their cross - product .
54,181
def in_sorted ( values , value ) : index = bisect . bisect_left ( values , value ) if index >= len ( values ) : return False return values [ index ] == value
Checks if a value is in a sorted list .
54,182
def _simple_convex_hull ( points ) : r if points . size == 0 : return points unique_points = np . unique ( points , axis = 1 ) _ , num_points = unique_points . shape if num_points < 2 : return unique_points points = np . empty ( ( 2 , num_points ) , order = "F" ) for index , xy_val in enumerate ( sorted ( tuple ( colum...
r Compute the convex hull for a set of points .
54,183
def is_separating ( direction , polygon1 , polygon2 ) : norm_squared = direction [ 0 ] * direction [ 0 ] + direction [ 1 ] * direction [ 1 ] params = [ ] vertex = np . empty ( ( 2 , ) , order = "F" ) for polygon in ( polygon1 , polygon2 ) : _ , polygon_size = polygon . shape min_param = np . inf max_param = - np . inf ...
Checks if a given direction is a separating line for two polygons .
54,184
def solve2x2 ( lhs , rhs ) : if np . abs ( lhs [ 1 , 0 ] ) > np . abs ( lhs [ 0 , 0 ] ) : ratio = lhs [ 0 , 0 ] / lhs [ 1 , 0 ] denominator = lhs [ 0 , 1 ] - ratio * lhs [ 1 , 1 ] if denominator == 0.0 : return True , None , None y_val = ( rhs [ 0 ] - ratio * rhs [ 1 ] ) / denominator x_val = ( rhs [ 1 ] - lhs [ 1 , 1 ...
Solve a square 2 x 2 system via LU factorization .
54,185
def add_plot_boundary ( ax , padding = 0.125 ) : nodes = np . asfortranarray ( np . vstack ( [ line . get_xydata ( ) for line in ax . lines ] ) . T ) left , right , bottom , top = _helpers . bbox ( nodes ) center_x = 0.5 * ( right + left ) delta_x = right - left center_y = 0.5 * ( top + bottom ) delta_y = top - bottom ...
Add a buffer of empty space around a plot boundary .
54,186
def add_patch ( ax , color , pts_per_edge , * edges ) : from matplotlib import patches from matplotlib import path as _path_mod s_vals = np . linspace ( 0.0 , 1.0 , pts_per_edge ) all_points = [ ] for edge in edges : points = edge . evaluate_multi ( s_vals ) all_points . append ( points [ : , 1 : ] ) first_edge = all_p...
Add a polygonal surface patch to a plot .
54,187
def visit_literal_block ( self , node ) : language = node . attributes . get ( "language" , "" ) test_type = node . attributes . get ( "testnodetype" , "" ) if test_type != "doctest" : if language . lower ( ) in ( "" , "python" ) : msg = _LITERAL_ERR_TEMPLATE . format ( node . rawsource , language , test_type ) raise e...
Visit a literal_block node .
54,188
def _bbox_intersect ( nodes1 , nodes2 ) : r left1 , right1 , bottom1 , top1 = _helpers . bbox ( nodes1 ) left2 , right2 , bottom2 , top2 = _helpers . bbox ( nodes2 ) if right2 < left1 or right1 < left2 or top2 < bottom1 or top1 < bottom2 : return BoxIntersectionType . DISJOINT if ( right2 == left1 or right1 == left2 or...
r Bounding box intersection predicate .
54,189
def linearization_error ( nodes ) : r _ , num_nodes = nodes . shape degree = num_nodes - 1 if degree == 1 : return 0.0 second_deriv = nodes [ : , : - 2 ] - 2.0 * nodes [ : , 1 : - 1 ] + nodes [ : , 2 : ] worst_case = np . max ( np . abs ( second_deriv ) , axis = 1 ) multiplier = 0.125 * degree * ( degree - 1 ) return m...
r Compute the maximum error of a linear approximation .
54,190
def segment_intersection ( start0 , end0 , start1 , end1 ) : r delta0 = end0 - start0 delta1 = end1 - start1 cross_d0_d1 = _helpers . cross_product ( delta0 , delta1 ) if cross_d0_d1 == 0.0 : return None , None , False else : start_delta = start1 - start0 s = _helpers . cross_product ( start_delta , delta1 ) / cross_d0...
r Determine the intersection of two line segments .
54,191
def parallel_lines_parameters ( start0 , end0 , start1 , end1 ) : r delta0 = end0 - start0 line0_const = _helpers . cross_product ( start0 , delta0 ) start1_against = _helpers . cross_product ( start1 , delta0 ) if line0_const != start1_against : return True , None norm0_sq = np . vdot ( delta0 , delta0 ) s_val0 = np ....
r Checks if two parallel lines ever meet .
54,192
def line_line_collide ( line1 , line2 ) : s , t , success = segment_intersection ( line1 [ : , 0 ] , line1 [ : , 1 ] , line2 [ : , 0 ] , line2 [ : , 1 ] ) if success : return _helpers . in_interval ( s , 0.0 , 1.0 ) and _helpers . in_interval ( t , 0.0 , 1.0 ) else : disjoint , _ = parallel_lines_parameters ( line1 [ :...
Determine if two line segments meet .
54,193
def convex_hull_collide ( nodes1 , nodes2 ) : polygon1 = _helpers . simple_convex_hull ( nodes1 ) _ , polygon_size1 = polygon1 . shape polygon2 = _helpers . simple_convex_hull ( nodes2 ) _ , polygon_size2 = polygon2 . shape if polygon_size1 == 2 and polygon_size2 == 2 : return line_line_collide ( polygon1 , polygon2 ) ...
Determine if the convex hulls of two curves collide .
54,194
def from_linearized ( first , second , intersections ) : s , t , success = segment_intersection ( first . start_node , first . end_node , second . start_node , second . end_node ) bad_parameters = False if success : if not ( _helpers . in_interval ( s , 0.0 , 1.0 ) and _helpers . in_interval ( t , 0.0 , 1.0 ) ) : bad_p...
Determine curve - curve intersection from pair of linearizations .
54,195
def add_intersection ( s , t , intersections ) : r if not intersections : intersections . append ( ( s , t ) ) return if s < _intersection_helpers . ZERO_THRESHOLD : candidate_s = 1.0 - s else : candidate_s = s if t < _intersection_helpers . ZERO_THRESHOLD : candidate_t = 1.0 - t else : candidate_t = t norm_candidate =...
r Adds an intersection to list of intersections .
54,196
def endpoint_check ( first , node_first , s , second , node_second , t , intersections ) : r if _helpers . vector_close ( node_first , node_second ) : orig_s = ( 1 - s ) * first . start + s * first . end orig_t = ( 1 - t ) * second . start + t * second . end add_intersection ( orig_s , orig_t , intersections )
r Check if curve endpoints are identical .
54,197
def tangent_bbox_intersection ( first , second , intersections ) : r node_first1 = first . nodes [ : , 0 ] node_first2 = first . nodes [ : , - 1 ] node_second1 = second . nodes [ : , 0 ] node_second2 = second . nodes [ : , - 1 ] endpoint_check ( first , node_first1 , 0.0 , second , node_second1 , 0.0 , intersections ) ...
r Check if two curves with tangent bounding boxes intersect .
54,198
def bbox_line_intersect ( nodes , line_start , line_end ) : r left , right , bottom , top = _helpers . bbox ( nodes ) if _helpers . in_interval ( line_start [ 0 ] , left , right ) and _helpers . in_interval ( line_start [ 1 ] , bottom , top ) : return BoxIntersectionType . INTERSECTION if _helpers . in_interval ( line_...
r Determine intersection of a bounding box and a line .
54,199
def intersect_one_round ( candidates , intersections ) : next_candidates = [ ] for first , second in candidates : both_linearized = False if first . __class__ is Linearization : if second . __class__ is Linearization : both_linearized = True bbox_int = bbox_intersect ( first . curve . nodes , second . curve . nodes ) e...
Perform one step of the intersection process .