code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
kernel_id = re.search( # type: ignore 'kernel-(.*).json', ipykernel.connect.get_connection_file() ).group(1) servers = list_running_servers() for server in servers: response = requests.get(urljoin(server['url'], 'api/sessions'), params={'toke...
def get_notebook_name() -> str
Return the full path of the jupyter notebook. References ---------- https://github.com/jupyter/notebook/issues/1000#issuecomment-359875246
3.260202
2.926751
1.113932
shell = InteractiveShell.instance() path = fullname # load the notebook object with open(path, 'r', encoding='utf-8') as f: notebook = read(f, 4) # create the module and add it to sys.modules mod = types.ModuleType(fullname) mod.__file__ = path # mod.__loader__ = self ...
def load_notebook(fullname: str)
Import a notebook as a module.
2.884031
2.747874
1.04955
event = f'message.{status}' if flask.has_request_context(): emit(event, dict(data=pack(content))) else: sio = flask.current_app.extensions['socketio'] sio.emit(event, dict(data=pack(content))) eventlet.sleep()
def _message(status, content)
Send message interface. Parameters ---------- status : str The type of message content : str
4.4984
5.470826
0.822252
return [dict(title=str(c), dataIndex=str(c), key=str(c)) for c in columns]
def _make_columns(columns: List[Union[int, str]]) -> List[Dict]
Transform list of columns into AntTable format.
4.539893
3.591716
1.26399
jsdata = [] for idx, row in data.iterrows(): row.index = row.index.astype(str) rdict = row.to_dict() rdict.update(dict(key=str(idx))) jsdata.append(rdict) return jsdata, Table._make_columns(data.columns)
def _make_data(data) -> Tuple[List[Dict], List[Dict]]
Transform table data into JSON.
4.181808
3.604654
1.160114
# pylint: disable=protected-access,unused-variable nargs = numargs(func) if nargs > 0: raise WrongNumberOfArguments( f'Decorated function "{func.__name__}" should have no arguments, it has {nargs}.' ) app = func() if app is None: raise TypeError( ...
def command(func)
Command line interface decorator. Decorate a function for building a Bowtie application and turn it into a command line interface.
2.536038
2.534627
1.000557
targets = filter(lambda x: x != '.', targets) # First, convert the suite to a proto test list - proto tests nicely # parse things like the fully dotted name of the test and the # finest-grained module it belongs to, which simplifies our job. proto_test_list = toProtoTestList(suite) # Extrac...
def toParallelTargets(suite, targets)
Produce a list of targets which should be tested in parallel. For the most part this will be a list of test modules. The exception is when a dotted name representing something more granular than a module was input (like an individal test case or test method)
5.14784
5.036218
1.022164
return (os.path.isdir(file_path) and os.path.isfile(os.path.join(file_path, '__init__.py')))
def isPackage(file_path)
Determine whether or not a given path is a (sub)package or not.
1.988337
2.019253
0.984689
if not os.path.isfile(file_path): raise ValueError("'{}' is not a file.".format(file_path)) parent_dir = os.path.dirname(os.path.abspath(file_path)) dotted_module = os.path.basename(file_path).replace('.py', '') while isPackage(parent_dir): dotted_module = os.path.basename(parent_di...
def findDottedModuleAndParentDir(file_path)
I return a tuple (dotted_module, parent_dir) where dotted_module is the full dotted name of the module with respect to the package it is in, and parent_dir is the absolute path to the parent directory of the package. If the python file is not part of a package, I return (None, None). For for filepath ...
1.99718
2.12547
0.939641
default_filepath = os.path.join(home, ".green") if os.path.isfile(default_filepath): filepaths.append(default_filepath) # Low priority env_filepath = os.getenv("GREEN_CONFIG") if env_filepath and os.path.isfile(env_filepath): filepaths.append(env_filepath) # Medium ...
def getConfig(filepath=None): # pragma: no cover parser = configparser.ConfigParser() filepaths = [] # Lowest priority goes first in the list home = os.getenv("HOME") if home
Get the Green config file settings. All available config files are read. If settings are in multiple configs, the last value encountered wins. Values specified on the command-line take precedence over all config file settings. Returns: A ConfigParser object.
2.906389
2.876828
1.010275
err = ''.join(traceback.format_exception(*err)) else: err = '' sys.__stdout__.write("({}) {} {}".format(os.getpid(), msg, err)+'\n') sys.__stdout__.flush()
def ddebug(msg, err=None): # pragma: no cover import os if err
err can be an instance of sys.exc_info() -- which is the latest traceback info
5.161487
4.097863
1.259556
for i in range(self._processes - len(self._pool)): w = self.Process(target=worker, args=(self._inqueue, self._outqueue, self._initializer, self._initargs, self._maxtasksperchild, ...
def _repopulate_pool(self)
Bring the number of pool processes up to the specified number, for use after reaping workers which have exited.
3.842238
3.376584
1.137907
if level <= debug_level: logging.debug(' ' * (level - 1) * 2 + str(message))
def debug(message, level=1)
So we can tune how much debug output we get when we turn it on.
4.202891
4.306973
0.975834
actual_spaces = (indent * self.indent_spaces) - len(outcome_char) return (outcome_char + ' ' * actual_spaces + line)
def formatLine(self, line, indent=0, outcome_char='')
Takes a single line, optionally adds an indent and/or outcome character to the beginning of the line.
5.82238
5.028763
1.157815
if not issubclass(GreenStream, type(stream)): stream = GreenStream(stream, disable_windows=args.disable_windows, disable_unidecode=args.disable_unidecode) result = GreenTestResult(args, stream) # Note: Catching SIGINT isn't supported by Python on windows (python # "WONTFIX"...
def run(suite, stream, args, testing=False)
Run the given test case or test suite with the specified arguments. Any args.stream passed in will be wrapped in a GreenStream
5.782552
5.751722
1.00536
nineq, nz, neq, nBatch = get_sizes(G, A) eps = 1e-7 Q_tilde = Q + eps * torch.eye(nz).type_as(Q).repeat(nBatch, 1, 1) D_tilde = D + eps * torch.eye(nineq).type_as(Q).repeat(nBatch, 1, 1) dx, ds, dz, dy = factor_solve_kkt_reg( Q_tilde, D_tilde, G, A, rx, rs, rz, ry, eps) res = kkt_...
def solve_kkt_ir(Q, D, G, A, rx, rs, rz, ry, niter=1)
Inefficient iterative refinement.
2.512223
2.491721
1.008228
nineq, nz, neq, nBatch = get_sizes(G, A) invQ_rx = rx.btrisolve(*Q_LU) if neq > 0: h = torch.cat((invQ_rx.unsqueeze(1).bmm(A.transpose(1, 2)).squeeze(1) - ry, invQ_rx.unsqueeze(1).bmm(G.transpose(1, 2)).squeeze(1) + rs / d - rz), 1) else: h = invQ_rx.unsqueez...
def solve_kkt(Q_LU, d, G, A, S_LU, rx, rs, rz, ry)
Solve KKT equations for the affine step
3.2918
3.243233
1.014975
nineq, nz, neq, nBatch = get_sizes(G, A) try: Q_LU = btrifact_hack(Q) except: raise RuntimeError() # S = [ A Q^{-1} A^T A Q^{-1} G^T ] # [ G Q^{-1} A^T G Q^{-1} G^T + D^{-1} ] # # We compute a partial LU decomposition of the S matrix # th...
def pre_factor_kkt(Q, G, A)
Perform all one-time factorizations and cache relevant matrix products
2.962658
2.969993
0.99753
nBatch, nineq = d.size() neq = S_LU[1].size(1) - nineq # TODO: There's probably a better way to add a batched diagonal. global factor_kkt_eye if factor_kkt_eye is None or factor_kkt_eye.size() != d.size(): # print('Updating batchedEye size.') factor_kkt_eye = torch.eye(nineq).re...
def factor_kkt(S_LU, R, d)
Factor the U22 block that we can only do after we know D.
4.54381
4.420864
1.02781
nineq, nz, neq, _ = get_sizes(G, A) invQ_rx = torch.potrs(rx.view(-1, 1), U_Q).view(-1) if neq > 0: h = torch.cat([torch.mv(A, invQ_rx) - ry, torch.mv(G, invQ_rx) + rs / d - rz], 0) else: h = torch.mv(G, invQ_rx) + rs / d - rz w = -torch.potrs(h.view(-1,...
def solve_kkt(U_Q, d, G, A, U_S, rx, rs, rz, ry, dbg=False)
Solve KKT equations for the affine step
3.218962
3.189029
1.009386
nineq, nz, neq, _ = get_sizes(G, A) # S = [ A Q^{-1} A^T A Q^{-1} G^T ] # [ G Q^{-1} A^T G Q^{-1} G^T + D^{-1} ] U_Q = torch.potrf(Q) # partial cholesky of S matrix U_S = torch.zeros(neq + nineq, neq + nineq).type_as(Q) G_invQ_GT = torch.mm(G, torch.potrs(...
def pre_factor_kkt(Q, G, A)
Perform all one-time factorizations and cache relevant matrix products
3.709364
3.71829
0.997599
nineq = R.size(0) U_S[-nineq:, -nineq:] = torch.potrf(R + torch.diag(1 / d.cpu()).type_as(d))
def factor_kkt(U_S, R, d)
Factor the U22 block that we can only do after we know D.
7.498366
7.296558
1.027658
def decorate(function): if not seconds: return function if use_signals: def handler(signum, frame): _raise_exception(timeout_exception, exception_message) @wraps(function) def new_function(*args, **kwargs): new_s...
def timeout(seconds=None, use_signals=True, timeout_exception=TimeoutError, exception_message=None)
Add a timeout parameter to a function and return it. :param seconds: optional time limit in seconds or fractions of a second. If None is passed, no timeout is applied. This adds some flexibility to the usage: you can disable timing out depending on the settings. :type seconds: float :param use_sign...
1.910564
2.043271
0.935051
try: queue.put((True, function(*args, **kwargs))) except: queue.put((False, sys.exc_info()[1]))
def _target(queue, function, *args, **kwargs)
Run a function with arguments and return output via a queue. This is a helper function for the Process created in _Timeout. It runs the function with positional arguments and keyword arguments and then returns the function's output by way of a queue. If an exception gets raised, it is returned to _Time...
2.371452
2.874043
0.825128
if self.__process.is_alive(): self.__process.terminate() _raise_exception(self.__timeout_exception, self.__exception_message)
def cancel(self)
Terminate any possible execution of the embedded function.
7.931096
6.677467
1.18774
if self.__timeout < time.time(): self.cancel() return self.__queue.full() and not self.__queue.empty()
def ready(self)
Read-only property indicating status of "value" property.
7.772804
8.221615
0.945411
if self.ready is True: flag, load = self.__queue.get() if flag: return load raise load
def value(self)
Read-only property containing data returned from function.
16.731735
13.611957
1.229194
bbs = [] for thing in paths_n_stuff: if is_path_segment(thing) or isinstance(thing, Path): bbs.append(thing.bbox()) elif isinstance(thing, complex): bbs.append((thing.real, thing.real, thing.imag, thing.imag)) else: try: complexthi...
def big_bounding_box(paths_n_stuff)
Finds a BB containing a collection of paths, Bezier path segments, and points (given as complex numbers).
2.30513
2.171829
1.061377
disvg(paths, colors=colors, filename=filename, stroke_widths=stroke_widths, nodes=nodes, node_colors=node_colors, node_radii=node_radii, openinbrowser=openinbrowser, timestamp=timestamp, margin_size=margin_size, mindim=mindim, dimensions=dimensions, viewbox=vie...
def wsvg(paths=None, colors=None, filename=os_path.join(getcwd(), 'disvg_output.svg'), stroke_widths=None, nodes=None, node_colors=None, node_radii=None, openinbrowser=False, timestamp=False, margin_size=0.1, mindim=600, dimensions=None, viewbox=None, text=None, text_pa...
Convenience function; identical to disvg() except that openinbrowser=False by default. See disvg() docstring for more info.
1.262309
1.283589
0.983421
roots = np.roots(p) if realroots: roots = [r.real for r in roots if isclose(r.imag, 0)] roots = [r for r in roots if condition(r)] duplicates = [] for idx, (r1, r2) in enumerate(combinations(roots, 2)): if isclose(r1, r2): duplicates.append(idx) return [r for id...
def polyroots(p, realroots=False, condition=lambda r: True)
Returns the roots of a polynomial with coefficients given in p. p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] INPUT: p - Rank-1 array-like object of polynomial coefficients. realroots - a boolean. If true, only real roots will be returned and the condition function can be written ass...
2.293101
2.643953
0.8673
assert isinstance(f, np.poly1d) and isinstance(g, np.poly1d) assert g != np.poly1d([0]) if g(t0) != 0: return f(t0)/g(t0) elif f(t0) == 0: return rational_limit(f.deriv(), g.deriv(), t0) else: raise ValueError("Limit does not exist.")
def rational_limit(f, g, t0)
Computes the limit of the rational function (f/g)(t) as t approaches t0.
2.657671
2.737225
0.970936
b = Line(xmin + 1j*ymin, xmax + 1j*ymin) t = Line(xmin + 1j*ymax, xmax + 1j*ymax) r = Line(xmax + 1j*ymin, xmax + 1j*ymax) l = Line(xmin + 1j*ymin, xmin + 1j*ymax) return Path(b, r, t.reversed(), l.reversed())
def bbox2path(xmin, xmax, ymin, ymax)
Converts a bounding box 4-tuple to a Path object.
2.36759
2.306506
1.026483
return Path(*[Line(points[i], points[i+1]) for i in range(len(points) - 1)])
def polyline(*points)
Converts a list of points to a Path composed of lines connecting those points (i.e. a linear spline or polyline). See also `polygon()`.
3.551376
3.295019
1.077801
return Path(*[Line(points[i], points[(i + 1) % len(points)]) for i in range(len(points))])
def polygon(*points)
Converts a list of points to a Path composed of lines connecting those points, then closes the path by connecting the last point to the first. See also `polyline()`.
3.143064
2.782976
1.129389
order = len(bpoints) - 1 if order == 3: return CubicBezier(*bpoints) elif order == 2: return QuadraticBezier(*bpoints) elif order == 1: return Line(*bpoints) else: assert len(bpoints) in {2, 3, 4}
def bpoints2bezier(bpoints)
Converts a list of length 2, 3, or 4 to a CubicBezier, QuadraticBezier, or Line object, respectively. See also: poly2bez.
2.297036
2.19537
1.046309
bpoints = polynomial2bezier(poly) if return_bpoints: return bpoints else: return bpoints2bezier(bpoints)
def poly2bez(poly, return_bpoints=False)
Converts a cubic or lower order Polynomial object (or a sequence of coefficients) to a CubicBezier, QuadraticBezier, or Line object as appropriate. If return_bpoints=True then this will instead only return the control points of the corresponding Bezier curve. Note: The inverse operation is available as...
3.21234
3.889879
0.82582
if is_bezier_segment(bez): bez = bez.bpoints() return bezier2polynomial(bez, numpy_ordering=numpy_ordering, return_poly1d=return_poly1d)
def bez2poly(bez, numpy_ordering=True, return_poly1d=False)
Converts a Bezier object or tuple of Bezier control points to a tuple of coefficients of the expanded polynomial. return_poly1d : returns a numpy.poly1d object. This makes computations of derivatives/anti-derivatives and many other operations quite quick. numpy_ordering : By default (to accommodate num...
3.723709
3.692133
1.008552
def transform(z): return exp(1j*radians(degs))*(z - origin) + origin if origin is None: if isinstance(curve, Arc): origin = curve.center else: origin = curve.point(0.5) if isinstance(curve, Path): return Path(*[rotate(seg, degs, origin=origin) f...
def rotate(curve, degs, origin=None)
Returns curve rotated by `degs` degrees (CCW) around the point `origin` (a complex number). By default origin is either `curve.point(0.5)`, or in the case that curve is an Arc object, `origin` defaults to `curve.center`.
3.044178
2.772934
1.097819
if isinstance(curve, Path): return Path(*[translate(seg, z0) for seg in curve]) elif is_bezier_segment(curve): return bpoints2bezier([bpt + z0 for bpt in curve.bpoints()]) elif isinstance(curve, Arc): new_start = curve.start + z0 new_end = curve.end + z0 return A...
def translate(curve, z0)
Shifts the curve by the complex quantity z such that translate(curve, z0).point(t) = curve.point(t) + z0
2.945862
2.868009
1.027145
if sy is None: isy = 1j*sx else: isy = 1j*sy def _scale(z): if sy is None: return sx*z return sx*z.real + isy*z.imag def scale_bezier(bez): p = [_scale(c) for c in bez2poly(bez)] p[-1] += origin - _scale(origin) return...
def scale(curve, sx, sy=None, origin=0j)
Scales `curve`, about `origin`, by diagonal matrix `[[sx,0],[0,sy]]`. Notes: ------ * If `sy` is not specified, it is assumed to be equal to `sx` and a scalar transformation of `curve` about `origin` will be returned. I.e. scale(curve, sx, origin).point(t) == ((curve.point(t) ...
3.270763
3.373415
0.96957
def to_point(p): return np.array([[p.real], [p.imag], [1.0]]) def to_vector(z): return np.array([[z.real], [z.imag], [0.0]]) def to_complex(v): return v.item(0) + 1j * v.item(1) if isinstance(curve, Path): return Path(*[transform(segment, tf) for segment in curve]...
def transform(curve, tf)
Transforms the curve by the homogeneous transformation matrix tf
2.516097
2.512986
1.001238
assert 0 <= t <= 1 dseg = seg.derivative(t) # Note: dseg might be numpy value, use np.seterr(invalid='raise') try: unit_tangent = dseg/abs(dseg) except (ZeroDivisionError, FloatingPointError): # This may be a removable singularity, if so we just need to compute # the li...
def bezier_unit_tangent(seg, t)
Returns the unit tangent of the segment at t. Notes ----- If you receive a RuntimeWarning, try the following: >>> import numpy >>> old_numpy_error_settings = numpy.seterr(invalid='raise') This can be undone with: >>> numpy.seterr(**old_numpy_error_settings)
4.514592
4.734145
0.953624
dz = self.derivative(t) ddz = self.derivative(t, n=2) dx, dy = dz.real, dz.imag ddx, ddy = ddz.real, ddz.imag old_np_seterr = np.seterr(invalid='raise') try: kappa = abs(dx*ddy - dy*ddx)/sqrt(dx*dx + dy*dy)**3 except (ZeroDivisionError, FloatingPointError): # tangent ve...
def segment_curvature(self, t, use_inf=False)
returns the curvature of the segment at t. Notes ----- If you receive a RuntimeWarning, run command >>> old = np.seterr(invalid='raise') This can be undone with >>> np.seterr(**old)
3.538768
3.345453
1.057784
def _radius(tau): return abs(seg.point(tau) - origin) shifted_seg_poly = seg.poly() - origin r_squared = real(shifted_seg_poly) ** 2 + \ imag(shifted_seg_poly) ** 2 extremizers = [0, 1] + polyroots01(r_squared.deriv()) extrema = [(_radius(t), t) for t in extremizers] ...
def bezier_radialrange(seg, origin, return_all_global_extrema=False)
returns the tuples (d_min, t_min) and (d_max, t_max) which minimize and maximize, respectively, the distance d = |self.point(t)-origin|. return_all_global_extrema: Multiple such t_min or t_max values can exist. By default, this will only return one. Set return_all_global_extrema=True to return all such...
3.882716
3.740372
1.038056
assert path.isclosed() intersections = Path(Line(pt, opt)).intersect(path) if len(intersections) % 2: return True else: return False
def path_encloses_pt(pt, opt, path)
returns true if pt is a point enclosed by path (which must be a Path object satisfying path.isclosed==True). opt is a point you know is NOT enclosed by path.
6.050798
5.068597
1.193782
mid = (start + end)/2 mid_point = curve.point(mid) length = abs(end_point - start_point) first_half = abs(mid_point - start_point) second_half = abs(end_point - mid_point) length2 = first_half + second_half if (length2 - length > error) or (depth < min_depth): # Calculate the l...
def segment_length(curve, start, end, start_point, end_point, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH, depth=0)
Recursively approximates the length by straight lines
2.591853
2.543261
1.019106
curve_length = curve.length(error=error, min_depth=min_depth) assert curve_length > 0 if not 0 <= s <= curve_length: raise ValueError("s is not in interval [0, curve.length()].") if s == 0: return 0 if s == curve_length: return 1 if isinstance(curve, Path): ...
def inv_arclength(curve, s, s_tol=ILENGTH_S_TOL, maxits=ILENGTH_MAXITS, error=ILENGTH_ERROR, min_depth=ILENGTH_MIN_DEPTH)
INPUT: curve should be a CubicBezier, Line, of Path of CubicBezier and/or Line objects. OUTPUT: Returns a float, t, such that the arc length of curve from 0 to t is approximately s. s_tol - exit when |s(t) - s| < s_tol where s(t) = seg.length(0, t, error, min_depth) and seg is either curve or, ...
2.625599
2.57426
1.019943
assert t0 < t1 if t0 == 0: cropped_seg = seg.split(t1)[0] elif t1 == 1: cropped_seg = seg.split(t0)[1] else: pt1 = seg.point(t1) # trim off the 0 <= t < t0 part trimmed_seg = crop_bezier(seg, t0, 1) # find the adjusted t1 (i.e. the t1 such that ...
def crop_bezier(seg, t0, t1)
returns a cropped copy of this segment which starts at self.point(t0) and ends at self.point(t1).
4.093462
3.867905
1.058315
if wrt_parameterization: return self.start == previous.end and np.isclose( self.derivative(0), previous.derivative(1)) else: return self.start == previous.end and np.isclose( self.unit_tangent(0), previous.unit_tangent(1))
def joins_smoothly_with(self, previous, wrt_parameterization=False)
Checks if this segment joins smoothly with previous segment. By default, this only checks that this segment starts moving (at t=0) in the same direction (and from the same positive) as previous stopped moving (at t=1). To check if the tangent magnitudes also match, set wrt_parameteriza...
2.936291
2.240697
1.310437
distance = self.end - self.start return self.start + distance*t
def point(self, t)
returns the coordinates of the Bezier curve evaluated at t.
7.792747
6.886596
1.131582
return abs(self.end - self.start)*(t1-t0)
def length(self, t0=0, t1=1, error=None, min_depth=None)
returns the length of the line segment between t0 and t1.
8.326482
6.006574
1.386228
return inv_arclength(self, s, s_tol=s_tol, maxits=maxits, error=error, min_depth=min_depth)
def ilength(self, s, s_tol=ILENGTH_S_TOL, maxits=ILENGTH_MAXITS, error=ILENGTH_ERROR, min_depth=ILENGTH_MIN_DEPTH)
Returns a float, t, such that self.length(0, t) is approximately s. See the inv_arclength() docstring for more details.
2.96678
1.922493
1.543194
assert self.end != self.start if n == 1: return self.end - self.start elif n > 1: return 0 else: raise ValueError("n should be a positive integer.")
def derivative(self, t=None, n=1)
returns the nth derivative of the segment at t.
3.726334
3.483768
1.069628
assert self.end != self.start dseg = self.end - self.start return dseg/abs(dseg)
def unit_tangent(self, t=None)
returns the unit tangent of the segment at t.
7.868661
6.28594
1.251787
if isinstance(other_seg, Line): assert other_seg.end != other_seg.start and self.end != self.start assert self != other_seg # Solve the system [p1-p0, q1-q0]*[t1, t2]^T = q0 - p0 # where self == Line(p0, p1) and other_seg == Line(q0, q1) a = (...
def intersect(self, other_seg, tol=None)
Finds the intersections of two segments. returns a list of tuples (t1, t2) such that self.point(t1) == other_seg.point(t2). Note: This will fail if the two segments coincide for more than a finite collection of points. tol is not used.
2.10761
2.031216
1.03761
xmin = min(self.start.real, self.end.real) xmax = max(self.start.real, self.end.real) ymin = min(self.start.imag, self.end.imag) ymax = max(self.start.imag, self.end.imag) return xmin, xmax, ymin, ymax
def bbox(self)
returns the bounding box for the segment in the form (xmin, xmax, ymin, ymax).
1.820305
1.676629
1.085693
# Single-precision floats have only 7 significant figures of # resolution, so test that we're within 6 sig figs. if np.isclose(point, self.start, rtol=0, atol=1e-6): return 0.0 elif np.isclose(point, self.end, rtol=0, atol=1e-6): return 1.0 # Fi...
def point_to_t(self, point)
If the point lies on the Line, returns its `t` parameter. If the point does not lie on the Line, returns None.
4.284103
4.051685
1.057363
return Line(self.point(t0), self.point(t1))
def cropped(self, t0, t1)
returns a cropped copy of this segment which starts at self.point(t0) and ends at self.point(t1).
6.004348
4.132162
1.453077
pt = self.point(t) return Line(self.start, pt), Line(pt, self.end)
def split(self, t)
returns two segments, whose union is this segment and which join at self.point(t).
5.497168
3.749544
1.46609
return bezier_radialrange(self, origin, return_all_global_extrema=return_all_global_extrema)
def radialrange(self, origin, return_all_global_extrema=False)
returns the tuples (d_min, t_min) and (d_max, t_max) which minimize and maximize, respectively, the distance d = |self.point(t)-origin|.
3.882297
3.991108
0.972737
return scale(self, sx=sx, sy=sy, origin=origin)
def scaled(self, sx, sy=None, origin=0j)
Scale transform. See `scale` function for further explanation.
5.154077
3.192759
1.614302
if warning_on: warn(_is_smooth_from_warning) if isinstance(previous, QuadraticBezier): return (self.start == previous.end and (self.control - self.start) == ( previous.end - previous.control)) else: return s...
def is_smooth_from(self, previous, warning_on=True)
[Warning: The name of this method is somewhat misleading (yet kept for compatibility with scripts created using svg.path 2.0). This method is meant only for d string creation and should not be used to check for kinks. To check a segment for differentiability, use the joins_smoothly_wit...
4.356516
3.673711
1.185862
return (1 - t)**2*self.start + 2*(1 - t)*t*self.control + t**2*self.end
def point(self, t)
returns the coordinates of the Bezier curve evaluated at t.
3.158515
2.601938
1.213909
p = self.bpoints() coeffs = (p[0] - 2*p[1] + p[2], 2*(p[1] - p[0]), p[0]) if return_coeffs: return coeffs else: return np.poly1d(coeffs)
def poly(self, return_coeffs=False)
returns the quadratic as a Polynomial object.
2.944818
2.808818
1.048419
p = self.bpoints() if n == 1: return 2*((p[1] - p[0])*(1 - t) + (p[2] - p[1])*t) elif n == 2: return 2*(p[2] - 2*p[1] + p[0]) elif n > 2: return 0 else: raise ValueError("n should be a positive integer.")
def derivative(self, t, n=1)
returns the nth derivative of the segment at t. Note: Bezier curves can have points where their derivative vanishes. If you are interested in the tangent direction, use the unit_tangent() method instead.
2.765072
2.535073
1.090727
new_quad = QuadraticBezier(self.end, self.control, self.start) if self._length_info['length']: new_quad._length_info = self._length_info new_quad._length_info['bpoints'] = ( self.end, self.control, self.start) return new_quad
def reversed(self)
returns a copy of the QuadraticBezier object with its orientation reversed.
4.30211
3.571423
1.204593
bpoints1, bpoints2 = split_bezier(self.bpoints(), t) return QuadraticBezier(*bpoints1), QuadraticBezier(*bpoints2)
def split(self, t)
returns two segments, whose union is this segment and which join at self.point(t).
5.445813
4.776465
1.140135
if warning_on: warn(_is_smooth_from_warning) if isinstance(previous, CubicBezier): return (self.start == previous.end and (self.control1 - self.start) == ( previous.end - previous.control2)) else: return sel...
def is_smooth_from(self, previous, warning_on=True)
[Warning: The name of this method is somewhat misleading (yet kept for compatibility with scripts created using svg.path 2.0). This method is meant only for d string creation and should not be used to check for kinks. To check a segment for differentiability, use the joins_smoothly_wit...
4.177956
3.64568
1.146002
# algebraically equivalent to # P0*(1-t)**3 + 3*P1*t*(1-t)**2 + 3*P2*(1-t)*t**2 + P3*t**3 # for (P0, P1, P2, P3) = self.bpoints() return self.start + t*( 3*(self.control1 - self.start) + t*( 3*(self.start + self.control2) - 6*self.control1 + t*( ...
def point(self, t)
Evaluate the cubic Bezier curve at t using Horner's rule.
3.4592
2.944725
1.174711
if t0 == 0 and t1 == 1: if self._length_info['bpoints'] == self.bpoints() \ and self._length_info['error'] >= error \ and self._length_info['min_depth'] >= min_depth: return self._length_info['length'] # using scipy.integrate....
def length(self, t0=0, t1=1, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH)
Calculate the length of the path up to a certain position
2.482484
2.519341
0.98537
return self.start, self.control1, self.control2, self.end
def bpoints(self)
returns the Bezier control points of the segment.
7.949986
3.49295
2.276009
p = self.bpoints() if n == 1: return 3*(p[1] - p[0])*(1 - t)**2 + 6*(p[2] - p[1])*(1 - t)*t + 3*( p[3] - p[2])*t**2 elif n == 2: return 6*( (1 - t)*(p[2] - 2*p[1] + p[0]) + t*(p[3] - 2*p[2] + p[1])) elif n == 3: ...
def derivative(self, t, n=1)
returns the nth derivative of the segment at t. Note: Bezier curves can have points where their derivative vanishes. If you are interested in the tangent direction, use the unit_tangent() method instead.
2.220928
2.098512
1.058335
new_cub = CubicBezier(self.end, self.control2, self.control1, self.start) if self._length_info['length']: new_cub._length_info = self._length_info new_cub._length_info['bpoints'] = ( self.end, self.control2, self.control1, se...
def reversed(self)
returns a copy of the CubicBezier object with its orientation reversed.
4.056022
3.284256
1.234989
if isinstance(other_seg, Line): return bezier_by_line_intersections(self, other_seg) elif (isinstance(other_seg, QuadraticBezier) or isinstance(other_seg, CubicBezier)): assert self != other_seg longer_length = max(self.length(), other_seg.lengt...
def intersect(self, other_seg, tol=1e-12)
Finds the intersections of two segments. returns a list of tuples (t1, t2) such that self.point(t1) == other_seg.point(t2). Note: This will fail if the two segments coincide for more than a finite collection of points.
3.356851
3.097383
1.08377
bpoints1, bpoints2 = split_bezier(self.bpoints(), t) return CubicBezier(*bpoints1), CubicBezier(*bpoints2)
def split(self, t)
returns two segments, whose union is this segment and which join at self.point(t).
5.527829
4.864524
1.136355
x = real(zeta) y = imag(zeta) z = x*self.radius.real + y*self.radius.imag return self.rot_matrix*z + self.center
def iu1transform(self, zeta)
This is an affine transformation, the inverse of self.u1transform().
5.154815
4.575392
1.126639
assert 0 <= t0 <= 1 and 0 <= t1 <= 1 if _quad_available: return quad(lambda tau: abs(self.derivative(tau)), t0, t1, epsabs=error, limit=1000)[0] else: return segment_length(self, t0, t1, self.point(t0), self.point(t1), ...
def length(self, t0=0, t1=1, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH)
The length of an elliptical large_arc segment requires numerical integration, and in that case it's simpler to just do a geometric approximation, as for cubic bezier curves.
4.027458
3.90178
1.03221
angle = radians(self.theta + t*self.delta) phi = radians(self.rotation) rx = self.radius.real ry = self.radius.imag k = (self.delta*2*pi/360)**n # ((d/dt)angle)**n if n % 4 == 0 and n > 0: return rx*cos(phi)*cos(angle) - ry*sin(phi)*sin(angle) + 1j*...
def derivative(self, t, n=1)
returns the nth derivative of the segment at t.
2.013442
1.973687
1.020143
dseg = self.derivative(t) return dseg/abs(dseg)
def unit_tangent(self, t)
returns the unit tangent vector of the segment at t (centered at the origin and expressed as a complex number).
9.418225
5.324557
1.768828
return Arc(self.end, self.radius, self.rotation, self.large_arc, not self.sweep, self.start)
def reversed(self)
returns a copy of the Arc object with its orientation reversed.
6.354658
4.448014
1.428651
def _deg(rads, domain_lower_limit): # Convert rads to degrees in [0, 360) domain degs = degrees(rads % (2*pi)) # Convert to [domain_lower_limit, domain_lower_limit + 360) domain k = domain_lower_limit // 360 degs += k * 360 if deg...
def phase2t(self, psi)
Given phase -pi < psi <= pi, returns the t value such that exp(1j*psi) = self.u1transform(self.point(t)).
3.351231
3.2176
1.041531
# a(t) = radians(self.theta + self.delta*t) # = (2*pi/360)*(self.theta + self.delta*t) # x'=0: ~~~~~~~~~ # -rx*cos(phi)*sin(a(t)) = ry*sin(phi)*cos(a(t)) # -(rx/ry)*cot(phi)*tan(a(t)) = 1 # a(t) = arctan(-(ry/rx)tan(phi)) + pi*k === atan_x # y'=0: ~~...
def bbox(self)
returns a bounding box for the segment in the form (xmin, xmax, ymin, ymax).
3.231119
3.15939
1.022703
if abs(self.delta*(t1 - t0)) <= 180: new_large_arc = 0 else: new_large_arc = 1 return Arc(self.point(t0), radius=self.radius, rotation=self.rotation, large_arc=new_large_arc, sweep=self.sweep, end=self.point(t1), autoscale_ra...
def cropped(self, t0, t1)
returns a cropped copy of this segment which starts at self.point(t0) and ends at self.point(t1).
3.563088
3.264268
1.091543
newpath = [seg.reversed() for seg in self] newpath.reverse() return Path(*newpath)
def reversed(self)
returns a copy of the Path object with its orientation reversed.
6.117809
4.362813
1.402263
return all(self[i].end == self[i+1].start for i in range(len(self) - 1))
def iscontinuous(self)
Checks if a path is continuous with respect to its parameterization.
4.486453
4.209183
1.065872
subpaths = [] subpath_start = 0 for i in range(len(self) - 1): if self[i].end != self[(i+1) % len(self)].start: subpaths.append(Path(*self[subpath_start: i+1])) subpath_start = i+1 subpaths.append(Path(*self[subpath_start: len(self)]))...
def continuous_subpaths(self)
Breaks self into its continuous components, returning a list of continuous subpaths. I.e. (all(subpath.iscontinuous() for subpath in self.continuous_subpaths()) and self == concatpaths(self.continuous_subpaths())) )
2.232546
2.073667
1.076618
assert len(self) != 0 assert self.iscontinuous() return self.start == self.end
def isclosed(self)
This function determines if a connected path is closed.
8.540316
8.233519
1.037262
mes = ("This attribute is deprecated, consider using isclosed() " "method instead.\n\nThis attribute is kept for compatibility " "with scripts created using svg.path (v2.0). You can prevent " "this warning in the future by setting " "CLOSED_WA...
def closed(self, warning_on=CLOSED_WARNING_ON)
The closed attribute is deprecated, please use the isclosed() method instead. See _closed_warning for more information.
9.413644
7.809728
1.205374
if use_closed_attrib: self_closed = self.closed(warning_on=False) if self_closed: segments = self[:-1] else: segments = self[:] else: self_closed = False segments = self[:] current_pos = None ...
def d(self, useSandT=False, use_closed_attrib=False)
Returns a path d-string for the path object. For an explanation of useSandT and use_closed_attrib, see the compatibility notes in the README.
2.044586
2.001348
1.021605
if T == 1: return len(self)-1, 1 if T == 0: return 0, 0 self._calc_lengths() # Find which segment self.point(T) falls on: T0 = 0 # the T-value the current segment starts on for seg_idx, seg_length in enumerate(self._lengths): ...
def T2t(self, T)
returns the segment index, `seg_idx`, and segment parameter, `t`, corresponding to the path parameter `T`. In other words, this is the inverse of the `Path.t2T()` method.
4.517387
4.058393
1.113097
self._calc_lengths() # Accept an index or a segment for seg if isinstance(seg, int): seg_idx = seg else: try: seg_idx = self.index(seg) except ValueError: assert is_path_segment(seg) or isinstance(seg, int) ...
def t2T(self, seg, t)
returns the path parameter T which corresponds to the segment parameter t. In other words, for any Path object, path, and any segment in path, seg, T(t) = path.t2T(seg, t) is the unique reparameterization such that path.point(T(t)) == seg.point(t) for all 0 <= t <= 1. Input Not...
4.047261
3.541396
1.142843
seg_idx, t = self.T2t(T) seg = self._segments[seg_idx] return seg.derivative(t, n=n)/seg.length()**n
def derivative(self, T, n=1)
returns the tangent vector of the Path at T (centered at the origin and expressed as a complex number). Note: Bezier curves can have points where their derivative vanishes. If you are interested in the tangent direction, use unit_tangent() method instead.
6.684678
5.763305
1.159869
seg_idx, t = self.T2t(T) return self._segments[seg_idx].unit_tangent(t)
def unit_tangent(self, T)
returns the unit tangent vector of the Path at T (centered at the origin and expressed as a complex number). If the tangent vector's magnitude is zero, this method will find the limit of self.derivative(tau)/abs(self.derivative(tau)) as tau approaches T.
6.97909
6.746915
1.034412
seg_idx, t = self.T2t(T) seg = self[seg_idx] if np.isclose(t, 0) and (seg_idx != 0 or self.end==self.start): previous_seg_in_path = self._segments[ (seg_idx - 1) % len(self._segments)] if not seg.joins_smoothly_with(previous_seg_in_path): ...
def curvature(self, T)
returns the curvature of this Path object at T and outputs float('inf') if not differentiable at T.
2.636595
2.500969
1.05423
def area_without_arcs(path): area_enclosed = 0 for seg in path: x = real(seg.poly()) dy = imag(seg.poly()).deriv() integrand = x*dy integral = integrand.integ() area_enclosed += integral(1) - integr...
def area(self, chord_length=1e-4)
Find area enclosed by path. Approximates any Arc segments in the Path with lines approximately `chord_length` long, and returns the area enclosed by the approximated Path. Default chord length is 0.01. If Arc segments are included in path, to ensure accurate results, make ...
3.723205
3.365097
1.106418
path1 = self if isinstance(other_curve, Path): path2 = other_curve else: path2 = Path(other_curve) assert path1 != path2 intersection_list = [] for seg1 in path1: for seg2 in path2: if justonemode and intersecti...
def intersect(self, other_curve, justonemode=False, tol=1e-12)
returns list of pairs of pairs ((T1, seg1, t1), (T2, seg2, t2)) giving the intersection points. If justonemode==True, then returns just the first intersection found. tol is used to check for redundant intersections (see comment above the code block where tol is used). Not...
3.199713
2.846908
1.123926
bbs = [seg.bbox() for seg in self._segments] xmins, xmaxs, ymins, ymaxs = list(zip(*bbs)) xmin = min(xmins) xmax = max(xmaxs) ymin = min(ymins) ymax = max(ymaxs) return xmin, xmax, ymin, ymax
def bbox(self)
returns a bounding box for the input Path object in the form (xmin, xmax, ymin, ymax).
2.167362
1.941472
1.11635
assert 0 <= T0 <= 1 and 0 <= T1<= 1 assert T0 != T1 assert not (T0 == 1 and T1 == 0) if T0 == 1 and 0 < T1 < 1 and self.isclosed(): return self.cropped(0, T1) if T1 == 1: seg1 = self[-1] t_seg1 = 1 i1 = len(self) - 1 ...
def cropped(self, T0, T1)
returns a cropped copy of the path.
2.090693
2.018829
1.035597
if return_all_global_extrema: raise NotImplementedError else: global_min = (np.inf, None, None) global_max = (0, None, None) for seg_idx, seg in enumerate(self): seg_global_min, seg_global_max = seg.radialrange(origin) ...
def radialrange(self, origin, return_all_global_extrema=False)
returns the tuples (d_min, t_min, idx_min), (d_max, t_max, idx_max) which minimize and maximize, respectively, the distance d = |self[idx].point(t)-origin|.
1.826067
1.670842
1.092902
t1 = 1-t return [n_choose_k(n, k) * t1**(n-k) * t**k for k in range(n+1)]
def bernstein(n, t)
returns a list of the Bernstein basis polynomials b_{i, n} evaluated at t, for i =0...n
3.713827
3.978735
0.933419