我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.asfortranarray()。
def mask_to_mscoco(alpha, annotations, img_id, mode='rle'): if mode == 'rle': in_ = np.reshape(np.asfortranarray(alpha), (alpha.shape[0], alpha.shape[1], 1)) in_ = np.asfortranarray(in_) rle = mask.encode(in_) segmentation = rle[0] else: raise ValueError('Unknown mask mode "{}"'.format(mode)) for idx, c in enumerate(np.unique(alpha)): area = mask.area(rle).tolist() if isinstance(area, list): area = area[0] bbox = mask.toBbox(rle).tolist() if isinstance(bbox[0], list): bbox = bbox[0] annotation = { 'area': area, 'bbox': bbox, 'category_id': c, 'id': len(annotations)+idx, 'image_id': img_id, 'iscrowd': 0, 'segmentation': segmentation} annotations.append(annotation) return annotations
def initialize(self, corpus): """ Initialize the random projection matrix. """ if self.id2word is None: logger.info("no word id mapping provided; initializing from corpus, assuming identity") self.id2word = utils.dict_from_corpus(corpus) self.num_terms = len(self.id2word) else: self.num_terms = 1 + max([-1] + self.id2word.keys()) shape = self.num_topics, self.num_terms logger.info("constructing %s random matrix" % str(shape)) # Now construct the projection matrix itself. # Here i use a particular form, derived in "Achlioptas: Database-friendly random projection", # and his (1) scenario of Theorem 1.1 in particular (all entries are +1/-1). randmat = 1 - 2 * numpy.random.binomial(1, 0.5, shape) # convert from 0/1 to +1/-1 self.projection = numpy.asfortranarray(randmat, dtype=numpy.float32) # convert from int32 to floats, for faster multiplications
def set_attribute(self, attribute, value): if isinstance(value, np.ndarray): getattr(self.veros_new, attribute)[...] = value else: setattr(self.veros_new, attribute, value) for module in self.legacy_modules: module_handle = getattr(self.veros_legacy, module) if hasattr(module_handle, attribute): try: v = np.asfortranarray(value.copy2numpy()) except AttributeError: v = np.asfortranarray(value) setattr(module_handle, attribute, v) assert np.all(value == getattr(module_handle, attribute)), attribute return raise AttributeError("Legacy pyOM has no attribute {}".format(attribute))
def _create_ann(whole_m, lbl, sc, img_id, ann_id, crw=None, ar=None): H, W = whole_m.shape if crw is None: crw = False whole_m = np.asfortranarray(whole_m.astype(np.uint8)) rle = mask_tools.encode(whole_m) # Surprisingly, ground truth ar can be different from area(rle) if ar is None: ar = mask_tools.area(rle) ann = { 'image_id': img_id, 'category_id': lbl, 'segmentation': rle, 'area': ar, 'id': ann_id, 'iscrowd': crw} if sc is not None: ann.update({'score': sc}) return ann
def deposit(self, positions, fields = None, method = None, kernel_name = 'cubic'): # Here we perform our particle deposition. if fields is None: fields = [] cls = getattr(particle_deposit, "deposit_%s" % method, None) if cls is None: raise YTParticleDepositionNotImplemented(method) nz = self.nz nvals = (nz, nz, nz, self.ires.size) # We allocate number of zones, not number of octs op = cls(nvals, kernel_name) op.initialize() mylog.debug("Depositing %s (%s^3) particles into %s Root Mesh", positions.shape[0], positions.shape[0]**0.3333333, nvals[-1]) pos = np.array(positions, dtype="float64") f64 = [np.array(f, dtype="float64") for f in fields] self.oct_handler.deposit(op, self.base_selector, pos, f64) vals = op.finalize() if vals is None: return return np.asfortranarray(vals)
def _init_kd_tree(self): """ Builds the kd tree of grid center points. """ # Grid cell centers. mylog.info("Multigrid: Building kD-Tree.") xp = self.ds["x"] yp = self.ds["y"] zp = self.ds["z"] fKD.pos = np.asfortranarray(np.empty((3,xp.size), dtype='float64')) # Normalize the grid points only within the kdtree. fKD.pos[0, :] = xp[:] / self.period[0] fKD.pos[1, :] = yp[:] / self.period[1] fKD.pos[2, :] = zp[:] / self.period[2] fKD.nn = 1 fKD.sort = False fKD.rearrange = True create_tree(0)
def _find_nearest_cell(self, points): """ Finds the closest grid cell for each point in a vectorized manner. """ if self.nlevels == 0: pos = (points - self.ds.left_edge) / self.width n = (self.sizes[2] * pos[:,2]).astype('int32') n += self.sizes[2] * (self.sizes[1] * pos[:,1]).astype('int32') n += self.sizes[2] * self.sizes[1] * (self.sizes[0] * pos[:,0]).astype('int32') else: # Normalize the points to a 1-period for use only within the kdtree. points[:, 0] = points[:, 0] / self.period[0] points[:, 1] = points[:, 1] / self.period[1] points[:, 2] = points[:, 2] / self.period[2] fKD.qv_many = points.T fKD.nn_tags = np.asfortranarray(np.empty((1, points.shape[0]), dtype='int64')) fKD.find_many_nn_nearest_neighbors() # The -1 is for fortran counting. n = fKD.nn_tags[0,:] - 1 return n
def newton_refine2(s_vals, curve1, curve2): """Image for :func:`.newton_refine` docstring.""" if NO_IMAGES: return ax = curve1.plot(256) ax.lines[-1].zorder = 1 curve2.plot(256, ax=ax) ax.lines[-1].zorder = 1 points = curve1.evaluate_multi(np.asfortranarray(s_vals)) colors = seaborn.dark_palette('blue', 5) ax.scatter(points[:, 0], points[:, 1], c=colors, s=20, alpha=0.75, zorder=2) ax.axis('scaled') ax.set_xlim(0.0, 1.0) ax.set_ylim(0.0, 1.0) save_image(ax.figure, 'newton_refine2.png')
def newton_refine3(s_vals, curve1, curve2): """Image for :func:`.newton_refine` docstring.""" if NO_IMAGES: return ax = curve1.plot(256) ax.lines[-1].zorder = 1 curve2.plot(256, ax=ax) ax.lines[-1].zorder = 1 points = curve1.evaluate_multi(np.asfortranarray(s_vals)) colors = seaborn.dark_palette('blue', 6) ax.scatter(points[:, 0], points[:, 1], c=colors, s=20, alpha=0.75, zorder=2) ax.axis('scaled') ax.set_xlim(0.0, 1.0) ax.set_ylim(0.0, 0.5625) save_image(ax.figure, 'newton_refine3.png')
def newton_refine_curve(curve, point, s, new_s): """Image for :func:`._curve_helpers.newton_refine` docstring.""" if NO_IMAGES: return ax = curve.plot(256) ax.plot(point[:, 0], point[:, 1], marker='H') wrong_points = curve.evaluate_multi(np.asfortranarray([s, new_s])) ax.plot(wrong_points[[0], 0], wrong_points[[0], 1], color='black', linestyle='None', marker='o') ax.plot(wrong_points[[1], 0], wrong_points[[1], 1], color='black', linestyle='None', marker='o', markeredgewidth=1, markerfacecolor='None') # Set the axis bounds / scaling. ax.axis('scaled') ax.set_xlim(-0.125, 3.125) ax.set_ylim(-0.125, 1.375) save_image(ax.figure, 'newton_refine_curve.png')
def newton_refine_curve_cusp(curve, s_vals): """Image for :func:`._curve_helpers.newton_refine` docstring.""" if NO_IMAGES: return ax = curve.plot(256) ax.lines[-1].zorder = 1 points = curve.evaluate_multi(np.asfortranarray(s_vals)) colors = seaborn.dark_palette('blue', 6) ax.scatter(points[:, 0], points[:, 1], c=colors, s=20, alpha=0.75, zorder=2) # Set the axis bounds / scaling. ax.axis('scaled') ax.set_xlim(-0.125, 6.125) ax.set_ylim(-3.125, 3.125) save_image(ax.figure, 'newton_refine_curve_cusp.png')
def unit_triangle(): """Image for :class:`.surface.Surface` docstring.""" if NO_IMAGES: return nodes = np.asfortranarray([ [0.0, 0.0], [1.0, 0.0], [0.0, 1.0], ]) surface = bezier.Surface(nodes, degree=1) ax = surface.plot(256) ax.axis('scaled') _plot_helpers.add_plot_boundary(ax) save_image(ax.figure, 'unit_triangle.png')
def from_json(cls, id_, info): """Convert JSON curve info into ``CurveInfo``. This involves parsing the dictionary and converting some stringified values (rationals and IEEE-754) to Python ``float``-s. Args: id_ (str): The ID of the curve. info (dict): The JSON data of the curve. Returns: CurveInfo: The curve info parsed from the JSON. """ control_points = info.pop('control_points') control_points = np.asfortranarray(_convert_float(control_points)) implicitized = info.pop('implicitized', None) # Optional fields. note = info.pop('note', None) _ensure_empty(info) return cls(id_, control_points, implicitized=implicitized, note=note)
def from_json(cls, id_, info): """Convert JSON surface info into ``SurfaceInfo``. This involves parsing the dictionary and converting some stringified values (rationals and IEEE-754) to Python ``float``-s. Args: id_ (str): The ID of the surface. info (dict): The JSON data of the surface. Returns: SurfaceInfo: The surface info parsed from the JSON. """ control_points = info.pop('control_points') control_points = np.asfortranarray(_convert_float(control_points)) # Optional fields. note = info.pop('note', None) _ensure_empty(info) return cls(id_, control_points, note=note) # pylint: disable=too-few-public-methods
def test_degree_elevated_linear(self): nodes = np.asfortranarray([ [0.0, 0.0], [0.5, 1.0], [1.0, 2.0], ]) error_val = self._call_function_under_test(nodes) self.assertEqual(error_val, 0.0) nodes = np.asfortranarray([ [0.0, 0.0], [0.25, 0.5], [0.5, 1.0], [0.75, 1.5], [1.0, 2.0], ]) error_val = self._call_function_under_test(nodes) self.assertEqual(error_val, 0.0)
def test_quadratic(self): from bezier import _curve_helpers nodes = np.asfortranarray([ [0.0, 0.0], [1.0, 1.0], [5.0, 6.0], ]) # NOTE: This is hand picked so that # d Nodes = [1, 1], [4, 5] # d^2 Nodes = [3, 4] # so that sqrt(3^2 + 4^2) = 5.0 error_val = self._call_function_under_test(nodes) expected = 0.125 * 2 * 1 * 5.0 self.assertEqual(error_val, expected) # For a degree two curve, the 2nd derivative is constant # so by subdividing, our error should drop by a factor # of (1/2)^2 = 4. left_nodes, right_nodes = _curve_helpers.subdivide_nodes(nodes) error_left = self._call_function_under_test(left_nodes) error_right = self._call_function_under_test(right_nodes) self.assertEqual(error_left, 0.25 * expected) self.assertEqual(error_right, 0.25 * expected)
def test_degree_weights_on_the_fly(self): nodes = np.asfortranarray([ [0.0, 0.0], [1.0, 1.0], [7.0, 3.0], [11.0, 8.0], [15.0, 1.0], [16.0, -3.0], ]) # NOTE: This is hand picked so that # d Nodes = [1, 1], [6, 2], [4, 5], [4, -7], [1, -4] # d^2 Nodes = [5, 1], [-2, 3], [0, -12], [-3, 3] # so that sqrt(5^2 + 12^2) = 13.0 error_val = self._call_function_under_test(nodes) expected = 0.125 * 5 * 4 * 13.0 self.assertEqual(error_val, expected)
def test_success(self): nodes1 = np.asfortranarray([ [0.0, 0.0], [0.5, 1.0], [1.0, 1.0], ]) curve1 = subdivided_curve(nodes1) # NOTE: This curve isn't close to linear, but that's OK. lin1 = make_linearization(curve1) nodes2 = np.asfortranarray([ [0.0, 1.0], [0.5, 1.0], [1.0, 0.0], ]) curve2 = subdivided_curve(nodes2) # NOTE: This curve isn't close to linear, but that's OK. lin2 = make_linearization(curve2) intersections = [] self.assertIsNone( self._call_function_under_test(lin1, lin2, intersections)) self.assertEqual(intersections, [(0.5, 0.5)])
def test_failure(self): # The bounding boxes intersect but the lines do not. nodes1 = np.asfortranarray([ [0.0, 0.0], [1.0, 1.0], ]) curve1 = subdivided_curve(nodes1) lin1 = make_linearization(curve1, 0.0) nodes2 = np.asfortranarray([ [1.75, -0.75], [0.75, 0.25], ]) curve2 = subdivided_curve(nodes2) lin2 = make_linearization(curve2, 0.0) intersections = [] self.assertIsNone( self._call_function_under_test(lin1, lin2, intersections)) self.assertEqual(len(intersections), 0)
def test_parallel_intersection(self): nodes1 = np.asfortranarray([ [0.0, 0.0], [1.0, 1.0], ]) curve1 = subdivided_curve(nodes1) lin1 = make_linearization(curve1, 0.0) nodes2 = np.asfortranarray([ [0.0, 1.0], [1.0, 2.0], ]) curve2 = subdivided_curve(nodes2) lin2 = make_linearization(curve2, 0.0) intersections = [] return_value = self._call_function_under_test( lin1, lin2, intersections) self.assertIsNone(return_value) self.assertEqual(intersections, [])
def test_same_line_intersection(self): nodes1 = np.asfortranarray([ [0.0, 0.0], [1.0, 1.0], ]) curve1 = subdivided_curve(nodes1) lin1 = make_linearization(curve1, 0.0) nodes2 = np.asfortranarray([ [0.5, 0.5], [3.0, 3.0], ]) curve2 = subdivided_curve(nodes2) lin2 = make_linearization(curve2, 0.0) intersections = [] with self.assertRaises(NotImplementedError): self._call_function_under_test(lin1, lin2, intersections) self.assertEqual(intersections, [])
def test_parallel_non_degree_one_disjoint(self): nodes1 = np.asfortranarray([ [0.0, 0.0], [1.0, 1.0], ]) curve1 = subdivided_curve(nodes1) lin1 = make_linearization(curve1, 0.0) nodes2 = np.asfortranarray([ [2.0, 2.0], [2.5009765625, 2.5009765625], [3.0, 3.0], ]) curve2 = subdivided_curve(nodes2) lin2 = make_linearization(curve2, np.nan) intersections = [] return_value = self._call_function_under_test( lin1, lin2, intersections) self.assertIsNone(return_value) self.assertEqual(intersections, [])
def test_parallel_non_degree_not_disjoint(self): nodes1 = np.asfortranarray([ [0.0, 0.0], [1.0, 1.0], ]) curve1 = subdivided_curve(nodes1) lin1 = make_linearization(curve1, 0.0) nodes2 = np.asfortranarray([ [0.5, 0.75], [1.0009765625, 1.2509765625], [1.5, 1.75], ]) curve2 = subdivided_curve(nodes2) lin2 = make_linearization(curve2, np.nan) intersections = [] with self.assertRaises(NotImplementedError): self._call_function_under_test(lin1, lin2, intersections) self.assertEqual(intersections, [])
def test_same(self): nodes_first = np.asfortranarray([ [0.0, 0.0], [1.0, 1.0], ]) first = subdivided_curve(nodes_first) nodes_second = np.asfortranarray([ [1.0, 1.0], [2.0, 1.0], ]) second = subdivided_curve(nodes_second) s_val = 1.0 node_first = np.asfortranarray(first.nodes[[1], :]) t_val = 0.0 node_second = np.asfortranarray(second.nodes[[0], :]) intersections = [] self._call_function_under_test( first, node_first, s_val, second, node_second, t_val, intersections) self.assertEqual(intersections, [(s_val, t_val)])
def test_one_endpoint(self): nodes1 = np.asfortranarray([ [0.0, 0.0], [1.0, 2.0], [2.0, 0.0], ]) curve1 = subdivided_curve(nodes1) nodes2 = np.asfortranarray([ [2.0, 0.0], [3.0, 2.0], [4.0, 0.0], ]) curve2 = subdivided_curve(nodes2) intersections = [] self.assertIsNone( self._call_function_under_test(curve1, curve2, intersections)) self.assertEqual(intersections, [(1.0, 0.0)])
def test_two_endpoints(self): nodes1 = np.asfortranarray([ [0.0, 0.0], [-1.0, 0.5], [0.0, 1.0], ]) curve1 = subdivided_curve(nodes1) nodes2 = np.asfortranarray([ [0.0, 0.0], [1.0, 0.5], [0.0, 1.0], ]) curve2 = subdivided_curve(nodes2) intersections = [] self.assertIsNone( self._call_function_under_test(curve1, curve2, intersections)) expected = [ (0.0, 0.0), (1.0, 1.0), ] self.assertEqual(intersections, expected)
def test_no_endpoints(self): # Lines have tangent bounding boxes but don't intersect. nodes1 = np.asfortranarray([ [0.0, 0.0], [2.0, 1.0], ]) curve1 = subdivided_curve(nodes1) nodes2 = np.asfortranarray([ [0.5, 1.0], [2.5, 2.0], ]) curve2 = subdivided_curve(nodes2) intersections = [] self.assertIsNone( self._call_function_under_test(curve1, curve2, intersections)) self.assertEqual(intersections, [])
def test_tangent_bboxes(self): nodes1 = np.asfortranarray([ [0.0, 0.0], [0.5, 1.0], [1.0, 0.0], ]) curve1 = subdivided_curve(nodes1) nodes2 = np.asfortranarray([ [1.0, 0.0], [1.5, 0.5], [2.0, -0.25], ]) curve2 = subdivided_curve(nodes2) intersections = [] next_candidates = self._call_function_under_test( [(curve1, curve2)], intersections) self.assertEqual(next_candidates, []) self.assertEqual(intersections, [(1.0, 0.0)])
def test_quadratics_intersect_once(self): # NOTE: ``nodes1`` is a specialization of [0, 0], [1/2, 1], [1, 1] # onto the interval [1/4, 1] and ``nodes`` is a specialization # of [0, 1], [1/2, 1], [1, 0] onto the interval [0, 3/4]. # We expect them to intersect at s = 1/3, t = 2/3, which is # the point [1/2, 3/4]. nodes1 = np.asfortranarray([ [0.25, 0.4375], [0.625, 1.0], [1.0, 1.0], ]) nodes2 = np.asfortranarray([ [0.0, 1.0], [0.375, 1.0], [0.75, 0.4375], ]) s_val = 1.0 / 3.0 t_val = 2.0 / 3.0 intersections = self._call_function_under_test(nodes1, nodes2) # Due to round-off, the answer may be wrong by a tiny wiggle. self.assertEqual(intersections.shape, (1, 2)) self.assertAlmostEqual( intersections[0, 0], s_val, delta=SPACING(s_val)) self.assertEqual(intersections[0, 1], t_val)
def test_parallel_failure(self): from bezier import _geometric_intersection nodes1 = np.asfortranarray([ [0.0, 0.0], [0.375, 0.75], [0.75, 0.375], ]) nodes2 = np.asfortranarray([ [0.25, 0.625], [0.625, 0.25], [1.0, 1.0], ]) with self.assertRaises(NotImplementedError) as exc_info: self._call_function_under_test(nodes1, nodes2) exc_args = exc_info.exception.args self.assertEqual( exc_args, (_geometric_intersection._SEGMENTS_PARALLEL,))
def test_non_convergence(self): from bezier import _geometric_intersection multiplier = 16384.0 nodes1 = multiplier * np.asfortranarray([ [0.0, 0.0], [4.5, 9.0], [9.0, 0.0], ]) nodes2 = multiplier * np.asfortranarray([ [0.0, 8.0], [6.0, 0.0], ]) with self.assertRaises(ValueError) as exc_info: self._call_function_under_test(nodes1, nodes2) exc_args = exc_info.exception.args expected = _geometric_intersection._NO_CONVERGE_TEMPLATE.format( _geometric_intersection._MAX_INTERSECT_SUBDIVISIONS) self.assertEqual(exc_args, (expected,))
def test_duplicates(self): # After three subdivisions, there are 8 pairs of curve segments # which have bounding boxes that touch at corners (these corners are # also intersections). This test makes sure the duplicates are # de-duplicated. nodes1 = np.asfortranarray([ [0.0, 0.0], [0.5, 1.0], [1.0, 0.0], ]) nodes2 = np.asfortranarray([ [0.0, 0.75], [0.5, -0.25], [1.0, 0.75], ]) intersections = self._call_function_under_test(nodes1, nodes2) expected = np.asfortranarray([ [0.25, 0.25], [0.75, 0.75], ]) self.assertEqual(intersections, expected)
def test_workspace_resize(self): nodes1 = np.asfortranarray([ [-3.0, 0.0], [5.0, 0.0], ]) nodes2 = np.asfortranarray([ [-7.0, -9.0], [9.0, 13.0], [-7.0, -13.0], [9.0, 9.0], ]) # NOTE: These curves intersect 3 times, so a workspace of # 2 is not large enough. self.reset_workspace(2) intersections = self._call_function_under_test(nodes1, nodes2) expected = np.asfortranarray([ [0.5, 0.5], [0.375, 0.25], [0.625, 0.75], ]) self.assertEqual(intersections, expected) # Make sure the workspace was resized. self.assertEqual(self.workspace_size(), 3)
def test_workspace_too_small(self): from bezier import _curve_intersection_speedup nodes1 = np.asfortranarray([ [-3.0, 0.0], [5.0, 0.0], ]) nodes2 = np.asfortranarray([ [-7.0, -9.0], [9.0, 13.0], [-7.0, -13.0], [9.0, 9.0], ]) # NOTE: These curves intersect 3 times, so a workspace of # 2 is not large enough. self.reset_workspace(2) with self.assertRaises(ValueError) as exc_info: self._call_function_under_test( nodes1, nodes2, allow_resize=False) exc_args = exc_info.exception.args expected = _curve_intersection_speedup.TOO_SMALL_TEMPLATE.format(3, 2) self.assertEqual(exc_args, (expected,)) # Make sure the workspace was **not** resized. self.assertEqual(self.workspace_size(), 2)
def test___dict___property(self): nodes = np.asfortranarray([ [0.0, 1.0], [0.0, 2.0], ]) curve = subdivided_curve(nodes) error = 0.0 linearization = self._make_one(curve, error) props_dict = linearization.__dict__ # NOTE: We cannot use dictionary equality check because of # the comparison of NumPy arrays. self.assertEqual(len(props_dict), 4) self.assertIs(props_dict['curve'], curve) self.assertEqual(props_dict['error'], error) self.assertEqual(props_dict['start_node'], nodes[[0], :]) self.assertEqual(props_dict['end_node'], nodes[[1], :]) # Check that modifying ``props_dict`` won't modify ``linearization``. props_dict['error'] = 0.5 self.assertNotEqual(linearization.error, props_dict['error'])
def test_length_property_not_cached(self): nodes = np.asfortranarray([ [0.0, 0.0], [1.0, 2.0], ]) curve = self._make_one(nodes, 1) self.assertIsNone(curve._length) patch = unittest.mock.patch( 'bezier._curve_helpers.compute_length', return_value=unittest.mock.sentinel.length) with patch as mocked: self.assertEqual(curve.length, unittest.mock.sentinel.length) self.assertEqual(mocked.call_count, 1) call = mocked.mock_calls[0] _, positional, keyword = call self.assertEqual(keyword, {}) self.assertEqual(len(positional), 1) self.assertEqual(positional[0], nodes)
def test_evaluate_multi(self): s_vals = np.asfortranarray([0.0, 0.25, 0.5, 1.0, 1.25]) nodes = np.asfortranarray([ [0.0, 0.0], [0.375, 0.375], [1.0, 1.0], ]) curve = self._make_one(nodes, 2) expected = np.asfortranarray([ [0.0, 0.0], [0.203125, 0.203125], [0.4375, 0.4375], [1.0, 1.0], [1.328125, 1.328125], ]) result = curve.evaluate_multi(s_vals) self.assertEqual(expected, result)
def test_plot_defaults(self, new_axis_mock): ax = unittest.mock.Mock(spec=['plot']) new_axis_mock.return_value = ax nodes = np.asfortranarray([ [0.0, 1.0], [1.0, 3.0], ]) curve = self._make_one(nodes, 1, _copy=False) num_pts = 2 # This value is crucial for the plot call. result = curve.plot(num_pts) self.assertIs(result, ax) # Verify mocks. new_axis_mock.assert_called_once_with() # Check the call to ax.plot(). We can't assert_any_call() # since == breaks on NumPy arrays. self.assertEqual(ax.plot.call_count, 1) call = ax.plot.mock_calls[0] utils.check_plot_call(self, call, nodes, color=None, alpha=None)
def test_plot_explicit(self, new_axis_mock): nodes = np.asfortranarray([ [0.0, 0.0], [1.0, 1.0], ]) curve = self._make_one(nodes, 1, _copy=False) num_pts = 2 # This value is crucial for the plot call. ax = unittest.mock.Mock(spec=['plot']) color = (0.75, 1.0, 1.0) alpha = 0.625 result = curve.plot(num_pts, color=color, alpha=alpha, ax=ax) self.assertIs(result, ax) # Verify mocks. new_axis_mock.assert_not_called() # Check the call to ax.plot(). We can't assert_any_call() # since == breaks on NumPy arrays. self.assertEqual(ax.plot.call_count, 1) call = ax.plot.mock_calls[0] utils.check_plot_call(self, call, nodes, color=color, alpha=alpha)
def test_intersect_algebraic(self): from bezier import _intersection_helpers nodes1 = np.asfortranarray([ [0.0, 0.0], [1.0, 1.0], ]) curve1 = self._make_one(nodes1, 1) nodes2 = np.asfortranarray([ [0.0, 1.0], [1.0, 0.0], ]) curve2 = self._make_one(nodes2, 1) strategy = _intersection_helpers.IntersectionStrategy.ALGEBRAIC intersections = curve1.intersect(curve2, strategy=strategy) expected = np.asfortranarray([ [0.5, 0.5], ]) self.assertEqual(intersections, expected)
def _intersect_helper(self, **kwargs): # NOTE: ``nodes1`` is a specialization of [0, 0], [1/2, 1], [1, 1] # onto the interval [1/4, 1] and ``nodes`` is a specialization # of [0, 1], [1/2, 1], [1, 0] onto the interval [0, 3/4]. # We expect them to intersect at s = 1/3, t = 2/3. nodes_left = np.asfortranarray([ [0.25, 0.4375], [0.625, 1.0], [1.0, 1.0], ]) left = self._make_one(nodes_left, 2) nodes_right = np.asfortranarray([ [0.0, 1.0], [0.375, 1.0], [0.75, 0.4375], ]) right = self._make_one(nodes_right, 2) result = left.intersect(right, **kwargs) expected = np.asfortranarray([[1.0, 2.0]]) / 3.0 self.assertTrue( np.allclose(result, expected, atol=0.0, rtol=0.5**52))
def test_elevate(self): nodes = np.asfortranarray([ [0.0, 0.5], [1.0, 1.0], [3.0, 2.0], [3.5, 4.0], ]) curve = self._make_one(nodes, 3) self.assertEqual(curve.degree, 3) elevated = curve.elevate() self.assertEqual(elevated.degree, 4) self.assertEqual(elevated.start, curve.start) self.assertEqual(elevated.end, curve.end) s_vals = np.linspace(0.0, 1.0, 64 + 1) orig_vals = curve.evaluate_multi(s_vals) new_vals = elevated.evaluate_multi(s_vals) self.assertEqual(orig_vals, new_vals)
def test_reduce_(self): nodes = np.asfortranarray([ [0.0, 0.0], [1.0, 3.0], [2.0, 3.0], [3.0, 0.0], ]) curve = self._make_one(nodes, 3) self.assertEqual(curve.degree, 3) reduced = curve.reduce_() expected = np.asfortranarray([ [0.0, 0.0], [1.5, 4.5], [3.0, 0.0], ]) self.assertEqual(reduced.nodes, expected) self.assertEqual(reduced.start, curve.start) self.assertEqual(reduced.end, curve.end) s_vals = np.linspace(0.0, 1.0, 64 + 1) orig_vals = curve.evaluate_multi(s_vals) new_vals = reduced.evaluate_multi(s_vals) self.assertEqual(orig_vals, new_vals)
def test_quartic(self): expected_l = np.asfortranarray([ [1.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0, 0.0], [1.0, 2.0, 1.0, 0.0, 0.0], [1.0, 3.0, 3.0, 1.0, 0.0], [1.0, 4.0, 6.0, 4.0, 1.0], ]) expected_r = np.asfortranarray([ [1.0, 4.0, 6.0, 4.0, 1.0], [0.0, 1.0, 3.0, 3.0, 1.0], [0.0, 0.0, 1.0, 2.0, 1.0], [0.0, 0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0, 1.0], ]) row_scaling = np.asfortranarray([[1.0], [2.0], [4.0], [8.0], [16.0]]) expected_l /= row_scaling expected_r /= row_scaling[::-1, :] self._helper(4, expected_l, expected_r)
def test_cubic(self): nodes = np.asfortranarray([ [0.0, 1.0], [4.0, 6.0], [7.0, 3.0], [6.0, 5.0], ]) expected_l = np.asfortranarray([ [0.0, 1.0], [2.0, 3.5], [3.75, 4.0], [4.875, 4.125], ]) expected_r = np.asfortranarray([ [4.875, 4.125], [6.0, 4.25], [6.5, 4.0], [6.0, 5.0], ]) self._helper(nodes, expected_l, expected_r)
def test_non_unity(self): nodes = np.asfortranarray([ [0.0, 0.0, 0.0], [0.5, 3.0, 1.0], [1.5, 4.0, 1.0], [2.0, 8.0, 1.0], ]) lambda1 = np.asfortranarray([0.25, 0.5, 0.75]) lambda2 = np.asfortranarray([0.25, 0.125, -0.75]) result = self._call_function_under_test(nodes, lambda1, lambda2) expected = np.asfortranarray([ [0.125, 0.453125, 0.109375], [0.0859375, 0.390625, 0.119140625], [0.421875, -2.109375, -0.421875], ]) self.assertEqual(result, expected)
def test_linear(self): num_vals = 129 s_vals = np.linspace(0.0, 1.0, num_vals) # B(s) = [s + 1, 1 - 2 s, 3 s - 7] nodes = np.asfortranarray([ [1.0, 1.0, -7.0], [2.0, -1.0, -4.0], ]) result = self._call_function_under_test(nodes, s_vals) expected = np.empty((num_vals, 3), order='F') expected[:, 0] = 1.0 + s_vals expected[:, 1] = 1.0 - 2.0 * s_vals expected[:, 2] = -7.0 + 3.0 * s_vals self.assertEqual(result, expected)