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_second != start_node . index_second : raise ValueError ( _WRONG_CURVE ) return start_node . index_second + 3 , start_node . t , end_node . t elif start_node . interior_curve == CLASSIFICATION_T . COINCIDENT : if end_node . index_first == start_node . index_first : return start_node . index_first , start_node . s , end_node . s elif end_node . index_second == start_node . index_second : return start_node . index_second + 3 , start_node . t , end_node . t else : raise ValueError ( _WRONG_CURVE ) else : raise ValueError ( 'Segment start must be classified as "FIRST", "TANGENT_FIRST", ' '"SECOND", "TANGENT_SECOND" or "COINCIDENT".' ) | 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 , degree1 , nodes2 [ 0 , 0 ] , nodes2 [ 1 , 0 ] ) if located is not None : return None , False return [ ] , None | 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 elif point_type == CLASSIFICATION_T . TANGENT_FIRST : return None , True elif point_type == CLASSIFICATION_T . TANGENT_SECOND : return None , False elif point_type == CLASSIFICATION_T . COINCIDENT_UNUSED : return [ ] , None else : raise ValueError ( "Point type not for tangency" , point_type ) | 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 ( next_node , intersections , unused ) if curr_node is start : break next_node = get_next ( curr_node , intersections , unused ) edge_ends . append ( ( curr_node , next_node ) ) if len ( edge_ends ) > max_edges : raise RuntimeError ( "Unexpected number of edges" , len ( edge_ends ) ) edge_info = tuple ( ends_to_curve ( start_node , end_node ) for start_node , end_node in edge_ends ) result . append ( edge_info ) if len ( result ) == 1 : if result [ 0 ] in FIRST_SURFACE_INFO : return None , True elif result [ 0 ] in SECOND_SURFACE_INFO : return None , False return result , None | 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 . asfortranarray ( [ lambda2 ] ) for k in six . moves . xrange ( degree - 1 , - 1 , - 1 ) : binom_val = ( binom_val * ( k + 1 ) ) / ( degree - k ) index -= 1 new_index = index - degree + k col_nodes = nodes [ : , new_index : index + 1 ] col_nodes = np . asfortranarray ( col_nodes ) col_result = _curve_helpers . evaluate_multi_barycentric ( col_nodes , lambda1 , lambda2 ) result *= lambda3 result += binom_val * col_result index = new_index return result | 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 . moves . xrange ( degree + 1 ) : nodes1 [ : , i ] = nodes [ : , i ] nodes2 [ : , i ] = nodes [ : , curr2 ] nodes3 [ : , i ] = nodes [ : , curr3 ] curr2 += degree - i curr3 -= i + 2 return nodes1 , nodes2 , nodes3 | 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 scale_factor = 70.0 else : raise _helpers . UnsupportedDegree ( num_nodes - 1 , supported = ( 1 , 2 , 3 , 4 ) ) result = 0.0 for multiplier , index1 , index2 in shoelace : result += multiplier * ( nodes [ 0 , index1 ] * nodes [ 1 , index2 ] - nodes [ 1 , index1 ] * nodes [ 0 , index2 ] ) return result / scale_factor | 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 , 25.0 , 30.0 ] , [ 20.0 , 20.0 , 15.0 ] ] ) ) , bezier . Curve . from_nodes ( np . asfortranarray ( [ [ 30.0 , 32.0 ] , [ 15.0 , 20.0 ] ] ) ) , ) edges2 = ( bezier . Curve . from_nodes ( np . asfortranarray ( [ [ 8.0 , 10.0 ] , [ 20.0 , 15.0 ] ] ) ) , bezier . Curve . from_nodes ( np . asfortranarray ( [ [ 10.0 , 15.0 , 20.0 ] , [ 15.0 , 20.0 , 20.0 ] ] ) ) , bezier . Curve . from_nodes ( np . asfortranarray ( [ [ 20.0 , 15.0 , 10.0 ] , [ 20.0 , 20.0 , 25.0 ] ] ) ) , bezier . Curve . from_nodes ( np . asfortranarray ( [ [ 10.0 , 8.0 ] , [ 25.0 , 20.0 ] ] ) ) , ) return edges1 , edges2 | 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_helpers . subdivide_nodes ( candidate_nodes , degree ) half_width = 0.5 * width next_candidates . extend ( ( ( centroid_x - half_width , centroid_y - half_width , half_width , nodes_a , ) , ( centroid_x , centroid_y , - half_width , nodes_b ) , ( centroid_x + width , centroid_y - half_width , half_width , nodes_c ) , ( centroid_x - half_width , centroid_y + width , half_width , nodes_d ) , ) ) | 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_candidates if not candidates : return None s_approx , t_approx = mean_centroid ( candidates ) s , t = newton_refine ( nodes , degree , x_val , y_val , s_approx , t_approx ) actual = _surface_helpers . evaluate_barycentric ( nodes , degree , 1.0 - s - t , s , t ) expected = np . asfortranarray ( [ x_val , y_val ] ) if not _helpers . vector_close ( actual . ravel ( order = "F" ) , expected , eps = LOCATE_EPS ) : s , t = newton_refine ( nodes , degree , x_val , y_val , s , t ) return s , t | 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 . s , intersection2 . t ] , atol = 0.0 , rtol = wiggle , ) | 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 ) : if same_intersection ( dupe , uniq ) : matches . append ( index ) if len ( matches ) != 1 : raise ValueError ( "Duplicate not among uniques" , dupe ) matched = matches [ 0 ] counter [ matched ] += 1 for index , count in six . iteritems ( counter ) : uniq = uniques [ index ] if count == 1 : if ( uniq . s , uniq . t ) . count ( 0.0 ) != 1 : raise ValueError ( "Count == 1 should be a single corner" , uniq ) elif count == 3 : if ( uniq . s , uniq . t ) != ( 0.0 , 0.0 ) : raise ValueError ( "Count == 3 should be a double corner" , uniq ) else : raise ValueError ( "Unexpected duplicate count" , count ) | 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 , edge_info [ index ] ) index2 , _ , _ = edge_info [ index + 1 ] if index1 == index2 : raise ValueError ( SEGMENTS_SAME_EDGE , edge_info [ index ] , edge_info [ index + 1 ] ) | 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 == 0.0 and other . t == 0.0 : found = other break if found is not None : intersections . remove ( found ) duplicates . append ( found ) intersections . append ( intersection ) | 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 ( intersection ) return True if intersection . t == 0.0 and other . t == 0.0 : duplicates . append ( intersection ) return True return False | 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_vals , coincident ) for s , t in st_vals . T : add_intersection ( index1 , s , index2 , t , interior_curve , edge_nodes1 , edge_nodes2 , duplicates , intersections , ) all_types = set ( ) to_keep = [ ] unused = [ ] for intersection in intersections : all_types . add ( intersection . interior_curve ) if should_use ( intersection ) : to_keep . append ( intersection ) else : unused . append ( intersection ) return to_keep , duplicates , unused , all_types | 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 : pass | 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 . append ( edge ) return curved_polygon . CurvedPolygon ( * edges , metadata = edge_info , _verify = False ) | 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 . _degree , _copy = False ) return edge1 , edge2 , edge3 | 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 must be positive" , lambda1 , lambda2 , lambda3 ) | 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_edge , * self . _get_edges ( ) ) if with_nodes : ax . plot ( self . _nodes [ 0 , : ] , self . _nodes [ 1 , : ] , color = "black" , marker = "o" , linestyle = "None" , ) return ax | 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 ( nodes_d , self . _degree , _copy = False ) , ) | 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 == 2 : bernstein = _surface_helpers . quadratic_jacobian_polynomial ( self . _nodes ) poly_sign = _surface_helpers . polynomial_sign ( bernstein , 2 ) elif self . _degree == 3 : bernstein = _surface_helpers . cubic_jacobian_polynomial ( self . _nodes ) poly_sign = _surface_helpers . polynomial_sign ( bernstein , 4 ) else : raise _helpers . UnsupportedDegree ( self . _degree , supported = ( 1 , 2 , 3 ) ) return poly_sign == 1 | 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 ( self . _dimension , self . _dimension , point , point_dimensions ) raise ValueError ( msg ) return _surface_intersection . locate_point ( self . _nodes , self . _degree , point [ 0 , 0 ] , point [ 1 , 0 ] ) | 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 only implemented in 2D" ) if strategy == _STRATEGY . GEOMETRIC : do_intersect = _surface_intersection . geometric_intersect elif strategy == _STRATEGY . ALGEBRAIC : do_intersect = _surface_intersection . algebraic_intersect else : raise ValueError ( "Unexpected strategy." , strategy ) edge_infos , contained , all_edge_nodes = do_intersect ( self . _nodes , self . _degree , other . _nodes , other . _degree , _verify ) if edge_infos is None : if contained : return [ self ] else : return [ other ] else : return [ _make_intersection ( edge_info , all_edge_nodes ) for edge_info in edge_infos ] | 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 . moves . xrange ( self . _degree + 1 - k ) : i = self . _degree - j - k new_nodes [ : , parent_i1 ] += ( i + 1 ) * self . _nodes [ : , index ] new_nodes [ : , parent_i2 ] += ( j + 1 ) * self . _nodes [ : , index ] new_nodes [ : , parent_i3 ] += ( k + 1 ) * self . _nodes [ : , index ] parent_i1 += 1 parent_i2 += 1 parent_i3 += 1 index += 1 parent_i1 += 1 parent_i2 += 1 denominator = self . _degree + 1.0 new_nodes /= denominator return Surface ( new_nodes , self . _degree + 1 , _copy = False ) | 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 [ : , : 1 ] = _curve_helpers . evaluate_hodograph ( s , nodes1 ) jac_mat [ : , 1 : ] = - _curve_helpers . evaluate_hodograph ( t , nodes2 ) singular , delta_s , delta_t = _helpers . solve2x2 ( jac_mat , func_val [ : , 0 ] ) if singular : raise ValueError ( "Jacobian is singular." ) else : return s + delta_s , t + delta_t | 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 singular , delta_s , delta_t = _helpers . solve2x2 ( jacobian , func_val [ : , 0 ] ) if singular : break norm_update_prev = norm_update norm_update = np . linalg . norm ( [ delta_s , delta_t ] , ord = 2 ) if index > 0 and norm_update > 0.25 * norm_update_prev : linear_updates += 1 if index >= 4 and 3 * linear_updates >= 2 * index : break norm_soln = np . linalg . norm ( [ current_s , current_t ] , ord = 2 ) current_s -= delta_s current_t -= delta_t if norm_update < NEWTON_ERROR_RATIO * norm_soln : return True , current_s , current_t return False , current_s , current_t | 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 . strip ( ) . split ( "\n" ) library_lines = [ line [ len ( FORTRAN_LIBRARY_PREFIX ) : ] for line in search_lines if line . startswith ( FORTRAN_LIBRARY_PREFIX ) ] if len ( library_lines ) != 1 : msg = GFORTRAN_MISSING_LIBS . format ( cmd_output ) print ( msg , file = sys . stderr ) return library_dirs library_line = library_lines [ 0 ] accepted = set ( library_dirs ) for part in library_line . split ( os . pathsep ) : full_path = os . path . abspath ( part . strip ( ) ) if os . path . isdir ( full_path ) : accepted . add ( full_path ) else : msg = GFORTRAN_BAD_PATH . format ( full_path ) print ( msg , file = sys . stderr ) return sorted ( accepted ) | 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 ( WHEEL_ENV ) is None : to_add += ( GFORTRAN_NATIVE_FLAG , ) to_remove = GFORTRAN_DEBUG_FLAGS for flag in to_add : if flag not in compiler_flags : compiler_flags . append ( flag ) return [ flag for flag in compiler_flags if not ( flag in to_remove or flag in remove_flags ) ] | 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_flags ( f90_compiler . compiler_f90 ) | 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 . ccompiler . replace_method ( distutils . ccompiler . CCompiler , "spawn" , journaled_spawn ) | 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" , prev , curr , ) | 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_min = curr_dist elif curr_dist > d_max : d_max = curr_dist return coeff_a , coeff_b , coeff_c , d_min , d_max | 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_min ) : return s , s_max elif _helpers . in_interval ( s , s_max , 1.0 ) : return s_min , s return s_min , s_max | 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 ] = index / denominator polynomial [ 1 , index ] = ( coeff_a * nodes2 [ 0 , index ] + coeff_b * nodes2 [ 1 , index ] + coeff_c ) start_bottom = np . asfortranarray ( [ 0.0 , d_min ] ) end_bottom = np . asfortranarray ( [ 1.0 , d_min ] ) start_top = np . asfortranarray ( [ 0.0 , d_max ] ) end_top = np . asfortranarray ( [ 1.0 , d_max ] ) s_min = DEFAULT_S_MIN s_max = DEFAULT_S_MAX for start_index in six . moves . xrange ( num_nodes2 - 1 ) : for end_index in six . moves . xrange ( start_index + 1 , num_nodes2 ) : s_min , s_max = _update_parameters ( s_min , s_max , start_bottom , end_bottom , polynomial [ : , start_index ] , polynomial [ : , end_index ] , ) s_min , s_max = _update_parameters ( s_min , s_max , start_top , end_top , polynomial [ : , start_index ] , polynomial [ : , end_index ] , ) return _check_parameter_range ( s_min , s_max ) | 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_obj : file_obj . write ( processed ) | 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 ( rtd_version = rtd_version ) bernstein_basis = BERNSTEIN_BASIS_PLAIN . format ( img_prefix = img_prefix ) bezier_defn = BEZIER_DEFN_PLAIN . format ( img_prefix = img_prefix ) sum_to_unity = SUM_TO_UNITY_PLAIN . format ( img_prefix = img_prefix ) template_kwargs = { "code_block1" : PLAIN_CODE_BLOCK , "code_block2" : PLAIN_CODE_BLOCK , "code_block3" : PLAIN_CODE_BLOCK , "testcleanup" : "" , "toctree" : "" , "bernstein_basis" : bernstein_basis , "bezier_defn" : bezier_defn , "sum_to_unity" : sum_to_unity , "img_prefix" : img_prefix , "extra_links" : extra_links , "docs" : "|docs| " , "docs_img" : docs_img , "pypi" : "\n\n|pypi| " , "pypi_img" : PYPI_IMG , "versions" : "|versions|\n\n" , "versions_img" : VERSIONS_IMG , "rtd_version" : rtd_version , "revision" : revision , "circleci_badge" : CIRCLECI_BADGE , "circleci_path" : "" , "travis_badge" : TRAVIS_BADGE , "travis_path" : "" , "appveyor_badge" : APPVEYOR_BADGE , "appveyor_path" : "" , "coveralls_badge" : COVERALLS_BADGE , "coveralls_path" : COVERALLS_PATH , "zenodo" : "|zenodo|" , "zenodo_img" : ZENODO_IMG , "joss" : " |JOSS|" , "joss_img" : JOSS_IMG , } template_kwargs . update ( ** extra_kwargs ) readme_contents = template . format ( ** template_kwargs ) readme_contents = INLINE_MATH_EXPR . sub ( inline_math , readme_contents ) sphinx_modules = [ ] to_replace = functools . partial ( mod_replace , sphinx_modules = sphinx_modules ) readme_contents = MOD_EXPR . sub ( to_replace , readme_contents ) if sphinx_modules != [ "bezier.curve" , "bezier.surface" ] : raise ValueError ( "Unexpected sphinx_modules" , sphinx_modules ) sphinx_docs = [ ] to_replace = functools . partial ( doc_replace , sphinx_docs = sphinx_docs ) readme_contents = DOC_EXPR . sub ( to_replace , readme_contents ) if sphinx_docs != [ "python/reference/bezier" , "development" ] : raise ValueError ( "Unexpected sphinx_docs" , sphinx_docs ) return readme_contents | 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 ( "README contents are as expected." ) | 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_build}" , appveyor_badge = APPVEYOR_BADGE_RELEASE , appveyor_path = "/build/{appveyor_build}" , coveralls_badge = COVERALLS_BADGE_RELEASE , coveralls_path = "builds/{coveralls_build}" , ) with open ( RELEASE_README_FILE , "r" ) as file_obj : contents = file_obj . read ( ) if contents != expected : err_msg = "\n" + get_diff ( contents , expected , "README.rst.release.actual" , "README.rst.release.expected" , ) raise ValueError ( err_msg ) else : print ( "README.rst.release.template contents are as expected." ) | 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 , "testcleanup" : TEST_CLEANUP , "toctree" : TOCTREE , "bernstein_basis" : BERNSTEIN_BASIS_SPHINX , "bezier_defn" : BEZIER_DEFN_SPHINX , "sum_to_unity" : SUM_TO_UNITY_SPHINX , "img_prefix" : "" , "extra_links" : "" , "docs" : "" , "docs_img" : "" , "pypi" : "\n\n|pypi| " , "pypi_img" : PYPI_IMG , "versions" : "|versions|\n\n" , "versions_img" : VERSIONS_IMG , "rtd_version" : RTD_VERSION , "revision" : REVISION , "circleci_badge" : CIRCLECI_BADGE , "circleci_path" : "" , "travis_badge" : TRAVIS_BADGE , "travis_path" : "" , "appveyor_badge" : APPVEYOR_BADGE , "appveyor_path" : "" , "coveralls_badge" : COVERALLS_BADGE , "coveralls_path" : COVERALLS_PATH , "zenodo" : "|zenodo|" , "zenodo_img" : ZENODO_IMG , "joss" : " |JOSS|" , "joss_img" : JOSS_IMG , } template_kwargs . update ( ** extra_kwargs ) expected = template . format ( ** template_kwargs ) if side_effect is not None : expected = side_effect ( expected ) with open ( index_file , "r" ) as file_obj : contents = file_obj . read ( ) if contents != expected : err_msg = "\n" + get_diff ( contents , expected , index_file + ".actual" , index_file + ".expected" , ) raise ValueError ( err_msg ) else : rel_name = os . path . relpath ( index_file , _ROOT_DIR ) msg = "{} contents are as expected." . format ( rel_name ) print ( msg ) | 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 = result . replace ( "{{appveyor_build}}" , "{appveyor_build}" ) result = result . replace ( "{{coveralls_build}}" , "{coveralls_build}" ) return result | 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" + get_diff ( contents , expected , "DEVELOPMENT.rst.actual" , "DEVELOPMENT.rst.expected" , ) raise ValueError ( err_msg ) else : print ( "DEVELOPMENT.rst contents are as expected." ) | 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 , expected , "docs/python/binary-extension.rst.actual" , "docs/python/binary-extension.rst.expected" , ) raise ValueError ( err_msg ) else : print ( "docs/python/binary-extension.rst contents are as expected." ) | 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_a , val_b , val_c = nodes [ 0 , : ] - x_val val_b *= 2 val_d , val_e , val_f = nodes [ 1 , : ] - y_val val_e *= 2 sub1 = val_b * val_f - val_c * val_e sub2 = val_a * val_f - val_c * val_d sub_det_a = - val_e * sub1 + val_f * sub2 sub_det_d = val_b * sub1 - val_c * sub2 return val_a * sub_det_a + val_d * sub_det_d elif num_nodes == 4 : return _evaluate3 ( nodes , x_val , y_val ) else : raise _helpers . UnsupportedDegree ( num_nodes - 1 , supported = ( 1 , 2 , 3 ) ) | 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 , degree , 0 sigma_coeffs = coeffs [ : effective_degree ] / coeffs [ effective_degree ] binom_numerator = effective_degree binom_denominator = degree - effective_degree + 1 for exponent in six . moves . xrange ( effective_degree - 1 , - 1 , - 1 ) : sigma_coeffs [ exponent ] *= binom_numerator sigma_coeffs [ exponent ] /= binom_denominator binom_numerator *= exponent binom_denominator *= degree - exponent + 1 return sigma_coeffs , degree , effective_degree | 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 : : effective_degree + 1 ] = 1.0 companion [ 0 , : ] = - sigma_coeffs [ : : - 1 ] return companion , degree , effective_degree | 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 ) else : s_vals = np . empty ( ( 0 , ) , order = "F" ) if effective_degree != degree : delta = degree - effective_degree s_vals = np . hstack ( [ s_vals , [ 1 ] * delta ] ) return s_vals | 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." ) return rcond | 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 ) lu_mat , one_norm = lu_companion ( - sigma_coeffs [ : : - 1 ] , sigma_val ) rcond = _reciprocal_condition_number ( lu_mat , one_norm ) return rcond < effective_degree * _SINGULAR_EPS | 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 ( num_companion , order = "F" ) evaluated = coeffs [ - 1 ] * id_mat for index in six . moves . xrange ( num_coeffs - 2 , - 1 , - 1 ) : coeff = coeffs [ index ] evaluated = ( _helpers . matrix_product ( evaluated , companion ) + coeff * id_mat ) if num_companion == 1 : if np . abs ( evaluated [ 0 , 0 ] ) > _NON_SIMPLE_THRESHOLD : rank = 1 else : rank = 0 else : rank = np . linalg . matrix_rank ( evaluated ) if rank < num_companion : raise NotImplementedError ( _NON_SIMPLE_ERR , coeffs ) | 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 ) : return final_s . append ( s_val ) final_t . append ( t_val ) | 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_polynomial ( to_power_basis ( nodes1 , nodes2 ) ) if np . all ( coeffs == 0.0 ) : raise NotImplementedError ( _COINCIDENT_ERR ) _check_non_simple ( coeffs ) t_vals = roots_in_unit_interval ( coeffs ) final_s = [ ] final_t = [ ] for t_val in t_vals : ( x_val , ) , ( y_val , ) = _curve_helpers . evaluate_multi ( nodes2 , np . asfortranarray ( [ t_val ] ) ) s_val = locate_point ( nodes1 , x_val , y_val ) if s_val is not None : _resolve_and_add ( nodes1 , s_val , final_s , nodes2 , t_val , final_t ) result = np . zeros ( ( 2 , len ( final_s ) ) , order = "F" ) if swapped : final_s , final_t = final_t , final_s result [ 0 , : ] = final_s result [ 1 , : ] = final_t return result | 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 . asfortranarray ( [ coeff0 , 2.0 * ( coeff1 - coeff0 ) , coeff2 - 2.0 * coeff1 + coeff0 ] ) elif num_coeffs == 4 : coeff0 , coeff1 , coeff2 , coeff3 = bezier_coeffs return np . asfortranarray ( [ coeff0 , 3.0 * ( coeff1 - coeff0 ) , 3.0 * ( coeff2 - 2.0 * coeff1 + coeff0 ) , coeff3 - 3.0 * coeff2 + 3.0 * coeff1 - coeff0 , ] ) else : raise _helpers . UnsupportedDegree ( num_coeffs - 1 , supported = ( 0 , 1 , 2 , 3 ) ) | 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 , zero1 power_basis1 = poly_to_power_basis ( zero1 [ 0 , : ] ) all_roots = roots_in_unit_interval ( power_basis1 ) if all_roots . size == 0 : return None power_basis2 = normalize_polynomial ( poly_to_power_basis ( zero2 [ 0 , : ] ) ) near_zero = np . abs ( polynomial . polyval ( all_roots , power_basis2 ) ) index = np . argmin ( near_zero ) if near_zero [ index ] < _ZERO_THRESHOLD : return all_roots [ index ] return None | 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 ) <= upper_bound | 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 ( column ) for column in unique_points . T ) ) : points [ : , index ] = xy_val if num_points < 3 : return points lower = [ 0 , 1 ] for index in six . moves . xrange ( 2 , num_points ) : point2 = points [ : , index ] while len ( lower ) >= 2 : point0 = points [ : , lower [ - 2 ] ] point1 = points [ : , lower [ - 1 ] ] if cross_product_compare ( point0 , point1 , point2 ) > 0 : break else : lower . pop ( ) lower . append ( index ) upper = [ num_points - 1 ] for index in six . moves . xrange ( num_points - 2 , - 1 , - 1 ) : if index > 0 and in_sorted ( lower , index ) : continue point2 = points [ : , index ] while len ( upper ) >= 2 : point0 = points [ : , upper [ - 2 ] ] point1 = points [ : , upper [ - 1 ] ] if cross_product_compare ( point0 , point1 , point2 ) > 0 : break else : upper . pop ( ) upper . append ( index ) size_polygon = len ( lower ) + len ( upper ) - 2 polygon = np . empty ( ( 2 , size_polygon ) , order = "F" ) for index , column in enumerate ( lower [ : - 1 ] ) : polygon [ : , index ] = points [ : , column ] index_start = len ( lower ) - 1 for index , column in enumerate ( upper [ : - 1 ] ) : polygon [ : , index + index_start ] = points [ : , column ] return polygon | 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 for index in six . moves . xrange ( polygon_size ) : vertex [ : ] = polygon [ : , index ] param = cross_product ( direction , vertex ) / norm_squared min_param = min ( min_param , param ) max_param = max ( max_param , param ) params . append ( ( min_param , max_param ) ) return params [ 0 ] [ 0 ] > params [ 1 ] [ 1 ] or params [ 0 ] [ 1 ] < params [ 1 ] [ 0 ] | 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 ] * y_val ) / lhs [ 1 , 0 ] return False , x_val , y_val else : if lhs [ 0 , 0 ] == 0.0 : return True , None , None ratio = lhs [ 1 , 0 ] / lhs [ 0 , 0 ] denominator = lhs [ 1 , 1 ] - ratio * lhs [ 0 , 1 ] if denominator == 0.0 : return True , None , None y_val = ( rhs [ 1 ] - ratio * rhs [ 0 ] ) / denominator x_val = ( rhs [ 0 ] - lhs [ 0 , 1 ] * y_val ) / lhs [ 0 , 0 ] return False , x_val , y_val | 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 multiplier = ( 1.0 + padding ) * 0.5 ax . set_xlim ( center_x - multiplier * delta_x , center_x + multiplier * delta_x ) ax . set_ylim ( center_y - multiplier * delta_y , center_y + multiplier * delta_y ) | 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_points [ 0 ] all_points . append ( first_edge [ : , [ 0 ] ] ) polygon = np . asfortranarray ( np . hstack ( all_points ) ) line , = ax . plot ( polygon [ 0 , : ] , polygon [ 1 , : ] , color = color ) color = line . get_color ( ) path = _path_mod . Path ( polygon . T ) patch = patches . PathPatch ( path , facecolor = color , alpha = 0.625 ) ax . add_patch ( patch ) | 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 errors . ExtensionError ( msg ) return html . HTMLTranslator . visit_literal_block ( self , node ) | 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 top2 == bottom1 or top1 == bottom2 ) : return BoxIntersectionType . TANGENT else : return BoxIntersectionType . INTERSECTION | 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 multiplier * np . linalg . norm ( worst_case , ord = 2 ) | 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_d1 t = _helpers . cross_product ( start_delta , delta0 ) / cross_d0_d1 return s , t , True | 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 . vdot ( start1 - start0 , delta0 ) / norm0_sq s_val1 = np . vdot ( end1 - start0 , delta0 ) / norm0_sq if s_val0 <= s_val1 : if 1.0 < s_val0 : return True , None elif s_val0 < 0.0 : start_s = 0.0 start_t = - s_val0 / ( s_val1 - s_val0 ) else : start_s = s_val0 start_t = 0.0 if s_val1 < 0.0 : return True , None elif 1.0 < s_val1 : end_s = 1.0 end_t = ( 1.0 - s_val0 ) / ( s_val1 - s_val0 ) else : end_s = s_val1 end_t = 1.0 else : if s_val0 < 0.0 : return True , None elif 1.0 < s_val0 : start_s = 1.0 start_t = ( s_val0 - 1.0 ) / ( s_val0 - s_val1 ) else : start_s = s_val0 start_t = 0.0 if 1.0 < s_val1 : return True , None elif s_val1 < 0.0 : end_s = 0.0 end_t = s_val0 / ( s_val0 - s_val1 ) else : end_s = s_val1 end_t = 1.0 parameters = np . asfortranarray ( [ [ start_s , end_s ] , [ start_t , end_t ] ] ) return False , parameters | 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 [ : , 0 ] , line1 [ : , 1 ] , line2 [ : , 0 ] , line2 [ : , 1 ] ) return not disjoint | 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 ) else : return _helpers . polygon_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_parameters = True else : if first . error == 0.0 and second . error == 0.0 : raise ValueError ( _UNHANDLED_LINES ) bad_parameters = True s = 0.5 t = 0.5 if bad_parameters : if not convex_hull_collide ( first . curve . nodes , second . curve . nodes ) : return orig_s = ( 1 - s ) * first . curve . start + s * first . curve . end orig_t = ( 1 - t ) * second . curve . start + t * second . curve . end refined_s , refined_t = _intersection_helpers . full_newton ( orig_s , first . curve . original_nodes , orig_t , second . curve . original_nodes ) refined_s , success = _helpers . wiggle_interval ( refined_s ) if not success : return refined_t , success = _helpers . wiggle_interval ( refined_t ) if not success : return add_intersection ( refined_s , refined_t , intersections ) | 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 = np . linalg . norm ( [ candidate_s , candidate_t ] , ord = 2 ) for existing_s , existing_t in intersections : delta_s = s - existing_s delta_t = t - existing_t norm_update = np . linalg . norm ( [ delta_s , delta_t ] , ord = 2 ) if ( norm_update < _intersection_helpers . NEWTON_ERROR_RATIO * norm_candidate ) : return intersections . append ( ( s , t ) ) | 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 ) endpoint_check ( first , node_first1 , 0.0 , second , node_second2 , 1.0 , intersections ) endpoint_check ( first , node_first2 , 1.0 , second , node_second1 , 0.0 , intersections ) endpoint_check ( first , node_first2 , 1.0 , second , node_second2 , 1.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_end [ 0 ] , left , right ) and _helpers . in_interval ( line_end [ 1 ] , bottom , top ) : return BoxIntersectionType . INTERSECTION s_bottom , t_bottom , success = segment_intersection ( np . asfortranarray ( [ left , bottom ] ) , np . asfortranarray ( [ right , bottom ] ) , line_start , line_end , ) if ( success and _helpers . in_interval ( s_bottom , 0.0 , 1.0 ) and _helpers . in_interval ( t_bottom , 0.0 , 1.0 ) ) : return BoxIntersectionType . INTERSECTION s_right , t_right , success = segment_intersection ( np . asfortranarray ( [ right , bottom ] ) , np . asfortranarray ( [ right , top ] ) , line_start , line_end , ) if ( success and _helpers . in_interval ( s_right , 0.0 , 1.0 ) and _helpers . in_interval ( t_right , 0.0 , 1.0 ) ) : return BoxIntersectionType . INTERSECTION s_top , t_top , success = segment_intersection ( np . asfortranarray ( [ right , top ] ) , np . asfortranarray ( [ left , top ] ) , line_start , line_end , ) if ( success and _helpers . in_interval ( s_top , 0.0 , 1.0 ) and _helpers . in_interval ( t_top , 0.0 , 1.0 ) ) : return BoxIntersectionType . INTERSECTION return BoxIntersectionType . DISJOINT | 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 ) else : bbox_int = bbox_line_intersect ( second . nodes , first . start_node , first . end_node ) else : if second . __class__ is Linearization : bbox_int = bbox_line_intersect ( first . nodes , second . start_node , second . end_node ) else : bbox_int = bbox_intersect ( first . nodes , second . nodes ) if bbox_int == BoxIntersectionType . DISJOINT : continue elif bbox_int == BoxIntersectionType . TANGENT and not both_linearized : tangent_bbox_intersection ( first , second , intersections ) continue if both_linearized : from_linearized ( first , second , intersections ) continue lin1 = six . moves . map ( Linearization . from_shape , first . subdivide ( ) ) lin2 = six . moves . map ( Linearization . from_shape , second . subdivide ( ) ) next_candidates . extend ( itertools . product ( lin1 , lin2 ) ) return next_candidates | Perform one step of the intersection process . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.