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={'token': server.get('token', '')})
for session in json.loads(response.text):
if session['kernel']['id'] == kernel_id:
relative_path = session['notebook']['path']
return pjoin(server['notebook_dir'], relative_path)
raise Exception('Noteboook not found.')
|
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
mod.__dict__['get_ipython'] = get_ipython
sys.modules[fullname] = mod
# extra work to ensure that magics that would affect the user_ns
# actually affect the notebook module's ns
save_user_ns = shell.user_ns
shell.user_ns = mod.__dict__
try:
for cell in notebook.cells:
if cell.cell_type == 'code':
try:
# only run valid python code
ast.parse(cell.source)
except SyntaxError:
continue
try:
# pylint: disable=exec-used
exec(cell.source, mod.__dict__)
except NameError:
print(cell.source)
raise
finally:
shell.user_ns = save_user_ns
return mod
|
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(
'No `App` instance was returned. '
'In the function decorated with @command, '
'return the `App` instance so it can be built.'
)
if not isinstance(app, App):
raise TypeError(
f'Returned value {app} is of type {type(app)}, '
'it needs to be a bowtie.App instance.'
)
@click.group(options_metavar='[--help]')
def cmd():
@cmd.command(add_help_option=False)
def build():
app._build()
@cmd.command(add_help_option=False)
@click.option('--host', '-h', default='0.0.0.0', type=str)
@click.option('--port', '-p', default=9991, type=int)
def run(host, port):
app._build()
app._serve(host, port)
@cmd.command(add_help_option=True)
@click.option('--host', '-h', default='0.0.0.0', type=str)
@click.option('--port', '-p', default=9991, type=int)
def serve(host, port):
app._serve(host, port)
@cmd.command(context_settings=dict(ignore_unknown_options=True),
add_help_option=False)
@click.argument('extra', nargs=-1, type=click.UNPROCESSED)
def dev(extra):
line = (_WEBPACK, '--config', 'webpack.dev.js') + extra
call(line, cwd=app._build_dir)
@cmd.command(context_settings=dict(ignore_unknown_options=True),
add_help_option=False)
@click.argument('extra', nargs=-1, type=click.UNPROCESSED)
def prod(extra):
line = (_WEBPACK, '--config', 'webpack.prod.js', '--progress') + extra
call(line, cwd=app._build_dir)
locale = inspect.stack()[1][0].f_locals
module = locale.get("__name__")
if module == "__main__":
try:
arg = sys.argv[1:]
except IndexError:
arg = ('--help',)
# pylint: disable=too-many-function-args
sys.exit(cmd(arg))
return cmd
|
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)
# Extract a list of the modules that all of the discovered tests are in
modules = set([x.module for x in proto_test_list])
# Get the list of user-specified targets that are NOT modules
non_module_targets = []
for target in targets:
if not list(filter(None, [target in x for x in modules])):
non_module_targets.append(target)
# Main loop -- iterating through all loaded test methods
parallel_targets = []
for test in proto_test_list:
found = False
for target in non_module_targets:
# target is a dotted name of either a test case or test method
# here test.dotted name is always a dotted name of a method
if (target in test.dotted_name):
if target not in parallel_targets:
# Explicitly specified targets get their own entry to
# run parallel to everything else
parallel_targets.append(target)
found = True
break
if found:
continue
# This test does not appear to be part of a specified target, so
# its entire module must have been discovered, so just add the
# whole module to the list if we haven't already.
if test.module not in parallel_targets:
parallel_targets.append(test.module)
return parallel_targets
|
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_dir) + '.' + dotted_module
parent_dir = os.path.dirname(parent_dir)
debug("Dotted module: {} -> {}".format(
parent_dir, dotted_module), 2)
return (dotted_module, parent_dir)
|
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 /a/b/c/d.py where b is the package, ('b.c.d', '/a')
would be returned.
| 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 priority
for cfg_file in ("setup.cfg", ".green"):
cwd_filepath = os.path.join(os.getcwd(), cfg_file)
if os.path.isfile(cwd_filepath):
filepaths.append(cwd_filepath)
# High priority
if filepath and os.path.isfile(filepath):
filepaths.append(filepath)
if filepaths:
global files_loaded
files_loaded = filepaths
# Python 3 has parser.read_file(iterator) while Python2 has
# parser.readfp(obj_with_readline)
read_func = getattr(parser, 'read_file', getattr(parser, 'readfp'))
for filepath in filepaths:
# Users are expected to put a [green] section
# only if they use setup.cfg
if filepath.endswith('setup.cfg'):
with open(filepath) as f:
read_func(f)
else:
read_func(ConfigFile(filepath))
return parser
|
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,
self._wrap_exception,
self._finalizer,
self._finalargs)
)
self._pool.append(w)
w.name = w.name.replace('Process', 'PoolWorker')
w.daemon = True
w.start()
util.debug('added worker')
|
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" issue 18040)
installHandler()
registerResult(result)
with warnings.catch_warnings():
if args.warnings: # pragma: no cover
# if args.warnings is set, use it to filter all the warnings
warnings.simplefilter(args.warnings)
# if the filter is 'default' or 'always', special-case the
# warnings from the deprecated unittest methods to show them
# no more than once per module, because they can be fairly
# noisy. The -Wd and -Wa flags can be used to bypass this
# only when args.warnings is None.
if args.warnings in ['default', 'always']:
warnings.filterwarnings('module',
category=DeprecationWarning,
message='Please use assert\w+ instead.')
result.startTestRun()
pool = LoggingDaemonlessPool(processes=args.processes or None,
initializer=InitializerOrFinalizer(args.initializer),
finalizer=InitializerOrFinalizer(args.finalizer))
manager = multiprocessing.Manager()
targets = [(target, manager.Queue())
for target in toParallelTargets(suite, args.targets)]
if targets:
for index, (target, queue) in enumerate(targets):
if args.run_coverage:
coverage_number = index + 1
else:
coverage_number = None
debug("Sending {} to runner {}".format(target, poolRunner))
pool.apply_async(
poolRunner,
(target, queue, coverage_number, args.omit_patterns, args.cov_config_file))
pool.close()
for target, queue in targets:
abort = False
while True:
msg = queue.get()
# Sentinel value, we're done
if not msg:
break
else:
# Result guaranteed after this message, we're
# currently waiting on this test, so print out
# the white 'processing...' version of the output
result.startTest(msg)
proto_test_result = queue.get()
result.addProtoTestResult(proto_test_result)
if result.shouldStop:
abort = True
break
if abort:
break
pool.close()
pool.join()
result.stopTestRun()
removeResult(result)
return result
|
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_resid_reg(Q, D, G, A, eps,
dx, ds, dz, dy, rx, rs, rz, ry)
resx, ress, resz, resy = res
res = resx
for k in range(niter):
ddx, dds, ddz, ddy = factor_solve_kkt_reg(Q_tilde, D_tilde, G, A, -resx, -ress, -resz,
-resy if resy is not None else None,
eps)
dx, ds, dz, dy = [v + dv if v is not None else None
for v, dv in zip((dx, ds, dz, dy), (ddx, dds, ddz, ddy))]
res = kkt_resid_reg(Q, D, G, A, eps,
dx, ds, dz, dy, rx, rs, rz, ry)
resx, ress, resz, resy = res
# res = torch.cat(resx)
res = resx
return dx, ds, dz, dy
|
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.unsqueeze(1).bmm(G.transpose(1, 2)).squeeze(1) + rs / d - rz
w = -(h.btrisolve(*S_LU))
g1 = -rx - w[:, neq:].unsqueeze(1).bmm(G).squeeze(1)
if neq > 0:
g1 -= w[:, :neq].unsqueeze(1).bmm(A).squeeze(1)
g2 = -rs - w[:, neq:]
dx = g1.btrisolve(*Q_LU)
ds = g2 / d
dz = w[:, neq:]
dy = w[:, :neq] if neq > 0 else None
return dx, ds, dz, dy
|
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
# that can be completed once D^{-1} is known.
# See the 'Block LU factorization' part of our website
# for more details.
G_invQ_GT = torch.bmm(G, G.transpose(1, 2).btrisolve(*Q_LU))
R = G_invQ_GT.clone()
S_LU_pivots = torch.IntTensor(range(1, 1 + neq + nineq)).unsqueeze(0) \
.repeat(nBatch, 1).type_as(Q).int()
if neq > 0:
invQ_AT = A.transpose(1, 2).btrisolve(*Q_LU)
A_invQ_AT = torch.bmm(A, invQ_AT)
G_invQ_AT = torch.bmm(G, invQ_AT)
LU_A_invQ_AT = btrifact_hack(A_invQ_AT)
P_A_invQ_AT, L_A_invQ_AT, U_A_invQ_AT = torch.btriunpack(*LU_A_invQ_AT)
P_A_invQ_AT = P_A_invQ_AT.type_as(A_invQ_AT)
S_LU_11 = LU_A_invQ_AT[0]
U_A_invQ_AT_inv = (P_A_invQ_AT.bmm(L_A_invQ_AT)
).btrisolve(*LU_A_invQ_AT)
S_LU_21 = G_invQ_AT.bmm(U_A_invQ_AT_inv)
T = G_invQ_AT.transpose(1, 2).btrisolve(*LU_A_invQ_AT)
S_LU_12 = U_A_invQ_AT.bmm(T)
S_LU_22 = torch.zeros(nBatch, nineq, nineq).type_as(Q)
S_LU_data = torch.cat((torch.cat((S_LU_11, S_LU_12), 2),
torch.cat((S_LU_21, S_LU_22), 2)),
1)
S_LU_pivots[:, :neq] = LU_A_invQ_AT[1]
R -= G_invQ_AT.bmm(T)
else:
S_LU_data = torch.zeros(nBatch, nineq, nineq).type_as(Q)
S_LU = [S_LU_data, S_LU_pivots]
return Q_LU, S_LU, R
|
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).repeat(
nBatch, 1, 1).type_as(R).byte()
T = R.clone()
T[factor_kkt_eye] += (1. / d).squeeze().view(-1)
T_LU = btrifact_hack(T)
global shown_btrifact_warning
if shown_btrifact_warning or not T.is_cuda:
# TODO: Don't use pivoting in most cases because
# torch.btriunpack is inefficient here:
oldPivotsPacked = S_LU[1][:, -nineq:] - neq
oldPivots, _, _ = torch.btriunpack(
T_LU[0], oldPivotsPacked, unpack_data=False)
newPivotsPacked = T_LU[1]
newPivots, _, _ = torch.btriunpack(
T_LU[0], newPivotsPacked, unpack_data=False)
# Re-pivot the S_LU_21 block.
if neq > 0:
S_LU_21 = S_LU[0][:, -nineq:, :neq]
S_LU[0][:, -nineq:,
:neq] = newPivots.transpose(1, 2).bmm(oldPivots.bmm(S_LU_21))
# Add the new S_LU_22 block pivots.
S_LU[1][:, -nineq:] = newPivotsPacked + neq
# Add the new S_LU_22 block.
S_LU[0][:, -nineq:, -nineq:] = T_LU[0]
|
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, 1), U_S).view(-1)
g1 = -rx - torch.mv(G.t(), w[neq:])
if neq > 0:
g1 -= torch.mv(A.t(), w[:neq])
g2 = -rs - w[neq:]
dx = torch.potrs(g1.view(-1, 1), U_Q).view(-1)
ds = g2 / d
dz = w[neq:]
dy = w[:neq] if neq > 0 else None
# if np.all(np.array([x.norm() for x in [rx, rs, rz, ry]]) != 0):
if dbg:
import IPython
import sys
IPython.embed()
sys.exit(-1)
# if rs.norm() > 0: import IPython, sys; IPython.embed(); sys.exit(-1)
return dx, ds, dz, dy
|
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(G.t(), U_Q))
R = G_invQ_GT
if neq > 0:
invQ_AT = torch.potrs(A.t(), U_Q)
A_invQ_AT = torch.mm(A, invQ_AT)
G_invQ_AT = torch.mm(G, invQ_AT)
# TODO: torch.potrf sometimes says the matrix is not PSD but
# numpy does? I filed an issue at
# https://github.com/pytorch/pytorch/issues/199
try:
U11 = torch.potrf(A_invQ_AT)
except:
U11 = torch.Tensor(np.linalg.cholesky(
A_invQ_AT.cpu().numpy())).type_as(A_invQ_AT)
# TODO: torch.trtrs is currently not implemented on the GPU
# and we are using gesv as a workaround.
U12 = torch.gesv(G_invQ_AT.t(), U11.t())[0]
U_S[:neq, :neq] = U11
U_S[:neq, neq:] = U12
R -= torch.mm(U12.t(), U12)
return U_Q, U_S, R
|
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_seconds = kwargs.pop('timeout', seconds)
if new_seconds:
old = signal.signal(signal.SIGALRM, handler)
signal.setitimer(signal.ITIMER_REAL, new_seconds)
try:
return function(*args, **kwargs)
finally:
if new_seconds:
signal.setitimer(signal.ITIMER_REAL, 0)
signal.signal(signal.SIGALRM, old)
return new_function
else:
@wraps(function)
def new_function(*args, **kwargs):
timeout_wrapper = _Timeout(function, timeout_exception, exception_message, seconds)
return timeout_wrapper(*args, **kwargs)
return new_function
return decorate
|
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_signals: flag indicating whether signals should be used for timing function out or the multiprocessing
When using multiprocessing, timeout granularity is limited to 10ths of a second.
:type use_signals: bool
:raises: TimeoutError if time limit is reached
It is illegal to pass anything other than a function as the first
parameter. The function is wrapped and returned to the caller.
| 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 _Timeout to be raised by the value property.
| 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:
complexthing = complex(thing)
bbs.append((complexthing.real, complexthing.real,
complexthing.imag, complexthing.imag))
except ValueError:
raise TypeError(
"paths_n_stuff can only contains Path, CubicBezier, "
"QuadraticBezier, Line, and complex objects.")
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 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=viewbox, text=text, text_path=text_path, font_size=font_size,
attributes=attributes, svg_attributes=svg_attributes,
svgwrite_debug=svgwrite_debug, paths2Drawing=paths2Drawing)
|
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_path=None, font_size=None,
attributes=None, svg_attributes=None, svgwrite_debug=False, paths2Drawing=False)
|
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 idx, r in enumerate(roots) if idx not in duplicates]
|
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 assuming all roots are real.
condition - a boolean-valued function. Only roots satisfying this will be
returned. If realroots==True, these conditions should assume the roots
are real.
OUTPUT:
A list containing the roots of the polynomial.
NOTE: This uses np.isclose and np.roots
| 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 a method of CubicBezier,
QuadraticBezier and Line objects.
| 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 numpy) the coefficients will
be output in reverse standard order.
Note: This function is redundant thanks to the .poly() method included
with all bezier segment classes.
| 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) for seg in curve])
elif is_bezier_segment(curve):
return bpoints2bezier([transform(bpt) for bpt in curve.bpoints()])
elif isinstance(curve, Arc):
new_start = transform(curve.start)
new_end = transform(curve.end)
new_rotation = curve.rotation + degs
return Arc(new_start, radius=curve.radius, rotation=new_rotation,
large_arc=curve.large_arc, sweep=curve.sweep, end=new_end)
else:
raise TypeError("Input `curve` should be a Path, Line, "
"QuadraticBezier, CubicBezier, or Arc object.")
|
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 Arc(new_start, radius=curve.radius, rotation=curve.rotation,
large_arc=curve.large_arc, sweep=curve.sweep, end=new_end)
else:
raise TypeError("Input `curve` should be a Path, Line, "
"QuadraticBezier, CubicBezier, or Arc object.")
|
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 poly2bez(p)
if isinstance(curve, Path):
return Path(*[scale(seg, sx, sy, origin) for seg in curve])
elif is_bezier_segment(curve):
return scale_bezier(curve)
elif isinstance(curve, Arc):
if sy is None or sy == sx:
return Arc(start=sx*(curve.start - origin) + origin,
radius=sx*curve.radius,
rotation=curve.rotation,
large_arc=curve.large_arc,
sweep=curve.sweep,
end=sx*(curve.end - origin) + origin)
else:
raise Exception("\nFor `Arc` objects, only scale transforms "
"with sx==sy are implemented.\n")
else:
raise TypeError("Input `curve` should be a Path, Line, "
"QuadraticBezier, CubicBezier, or Arc object.")
|
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) - origin) * sx) + origin
| 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])
elif is_bezier_segment(curve):
return bpoints2bezier([to_complex(tf.dot(to_point(p)))
for p in curve.bpoints()])
elif isinstance(curve, Arc):
new_start = to_complex(tf.dot(to_point(curve.start)))
new_end = to_complex(tf.dot(to_point(curve.end)))
new_radius = to_complex(tf.dot(to_vector(curve.radius)))
return Arc(new_start, radius=new_radius, rotation=curve.rotation,
large_arc=curve.large_arc, sweep=curve.sweep, end=new_end)
else:
raise TypeError("Input `curve` should be a Path, Line, "
"QuadraticBezier, CubicBezier, or Arc object.")
|
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 limit.
# Note: limit{{dseg / abs(dseg)} = sqrt(limit{dseg**2 / abs(dseg)**2})
dseg_poly = seg.poly().deriv()
dseg_abs_squared_poly = (real(dseg_poly) ** 2 +
imag(dseg_poly) ** 2)
try:
unit_tangent = csqrt(rational_limit(dseg_poly**2,
dseg_abs_squared_poly, t))
except ValueError:
bef = seg.poly().deriv()(t - 1e-4)
aft = seg.poly().deriv()(t + 1e-4)
mes = ("Unit tangent appears to not be well-defined at "
"t = {}, \n".format(t) +
"seg.poly().deriv()(t - 1e-4) = {}\n".format(bef) +
"seg.poly().deriv()(t + 1e-4) = {}".format(aft))
raise ValueError(mes)
return unit_tangent
|
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 vector is zero at t, use polytools to find limit
p = self.poly()
dp = p.deriv()
ddp = dp.deriv()
dx, dy = real(dp), imag(dp)
ddx, ddy = real(ddp), imag(ddp)
f2 = (dx*ddy - dy*ddx)**2
g2 = (dx*dx + dy*dy)**3
lim2 = rational_limit(f2, g2, t)
if lim2 < 0: # impossible, must be numerical error
return 0
kappa = sqrt(lim2)
finally:
np.seterr(**old_np_seterr)
return kappa
|
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]
if return_all_global_extrema:
raise NotImplementedError
else:
seg_global_min = min(extrema, key=itemgetter(0))
seg_global_max = max(extrema, key=itemgetter(0))
return seg_global_min, seg_global_max
|
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 global extrema.
| 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 length of each segment:
depth += 1
return (segment_length(curve, start, mid, start_point, mid_point,
error, min_depth, depth) +
segment_length(curve, mid, end, mid_point, end_point,
error, min_depth, depth))
# This is accurate enough.
return length2
|
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):
seg_lengths = [seg.length(error=error, min_depth=min_depth)
for seg in curve]
lsum = 0
# Find which segment the point we search for is located on
for k, len_k in enumerate(seg_lengths):
if lsum <= s <= lsum + len_k:
t = inv_arclength(curve[k], s - lsum, s_tol=s_tol,
maxits=maxits, error=error,
min_depth=min_depth)
return curve.t2T(k, t)
lsum += len_k
return 1
elif isinstance(curve, Line):
return s / curve.length(error=error, min_depth=min_depth)
elif (isinstance(curve, QuadraticBezier) or
isinstance(curve, CubicBezier) or
isinstance(curve, Arc)):
t_upper = 1
t_lower = 0
iteration = 0
while iteration < maxits:
iteration += 1
t = (t_lower + t_upper)/2
s_t = curve.length(t1=t, error=error, min_depth=min_depth)
if abs(s_t - s) < s_tol:
return t
elif s_t < s: # t too small
t_lower = t
else: # s < s_t, t too big
t_upper = t
if t_upper == t_lower:
warn("t is as close as a float can be to the correct value, "
"but |s(t) - s| = {} > s_tol".format(abs(s_t-s)))
return t
raise Exception("Maximum iterations reached with s(t) - s = {}."
"".format(s_t - s))
else:
raise TypeError("First argument must be a Line, QuadraticBezier, "
"CubicBezier, Arc, or Path object.")
|
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,
if curve is a Path object, then seg is a segment in curve.
error - used to compute lengths of cubics and arcs
min_depth - used to compute lengths of cubics and arcs
Note: This function is not designed to be efficient, but if it's slower
than you need, make sure you have scipy installed.
| 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
# trimmed_seg.point(t1) ~= pt))and trim off the t1 < t <= 1 part
t1_adj = trimmed_seg.radialrange(pt1)[0][1]
cropped_seg = crop_bezier(trimmed_seg, 0, t1_adj)
return cropped_seg
|
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_parameterization=True.
| 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 = (self.start.real, self.end.real)
b = (self.start.imag, self.end.imag)
c = (other_seg.start.real, other_seg.end.real)
d = (other_seg.start.imag, other_seg.end.imag)
denom = ((a[1] - a[0])*(d[0] - d[1]) -
(b[1] - b[0])*(c[0] - c[1]))
if np.isclose(denom, 0):
return []
t1 = (c[0]*(b[0] - d[1]) -
c[1]*(b[0] - d[0]) -
a[0]*(d[0] - d[1]))/denom
t2 = -(a[1]*(b[0] - d[0]) -
a[0]*(b[1] - d[0]) -
c[0]*(b[0] - b[1]))/denom
if 0 <= t1 <= 1 and 0 <= t2 <= 1:
return [(t1, t2)]
return []
elif isinstance(other_seg, QuadraticBezier):
t2t1s = bezier_by_line_intersections(other_seg, self)
return [(t1, t2) for t2, t1 in t2t1s]
elif isinstance(other_seg, CubicBezier):
t2t1s = bezier_by_line_intersections(other_seg, self)
return [(t1, t2) for t2, t1 in t2t1s]
elif isinstance(other_seg, Arc):
t2t1s = other_seg.intersect(self)
return [(t1, t2) for t2, t1 in t2t1s]
elif isinstance(other_seg, Path):
raise TypeError(
"other_seg must be a path segment, not a Path object, use "
"Path.intersect().")
else:
raise TypeError("other_seg must be a path segment.")
|
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
# Finding the point "by hand" here is much faster than calling
# radialrange(), see the discussion on PR #40:
# https://github.com/mathandy/svgpathtools/pull/40#issuecomment-358134261
p = self.poly()
# p(t) = (p_1 * t) + p_0 = point
# t = (point - p_0) / p_1
t = (point - p[0]) / p[1]
if np.isclose(t.imag, 0) and (t.real >= 0.0) and (t.real <= 1.0):
return t.real
return None
|
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 self.control == self.start
|
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_with() method instead.]
| 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 self.control1 == self.start
|
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_with() method instead.]
| 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*(
-self.start + 3*(self.control1 - self.control2) + self.end
)))
|
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.quad is quick
if _quad_available:
s = quad(lambda tau: abs(self.derivative(tau)), t0, t1,
epsabs=error, limit=1000)[0]
else:
s = segment_length(self, t0, t1, self.point(t0), self.point(t1),
error, min_depth, 0)
if t0 == 0 and t1 == 1:
self._length_info['length'] = s
self._length_info['bpoints'] = self.bpoints()
self._length_info['error'] = error
self._length_info['min_depth'] = min_depth
return self._length_info['length']
else:
return s
|
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:
return 6*(p[3] - 3*(p[2] - p[1]) - p[0])
elif n > 3:
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.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, self.start)
return new_cub
|
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.length())
return bezier_intersections(self, other_seg,
longer_length=longer_length,
tol=tol, tol_deC=tol)
elif isinstance(other_seg, Arc):
t2t1s = other_seg.intersect(self)
return [(t1, t2) for t2, t1 in t2t1s]
elif isinstance(other_seg, Path):
raise TypeError(
"other_seg must be a path segment, not a Path object, use "
"Path.intersect().")
else:
raise TypeError("other_seg must be a path segment.")
|
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),
error, min_depth, 0)
|
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*(
rx*sin(phi)*cos(angle) + ry*cos(phi)*sin(angle))
elif n % 4 == 1:
return k*(-rx*cos(phi)*sin(angle) - ry*sin(phi)*cos(angle) + 1j*(
-rx*sin(phi)*sin(angle) + ry*cos(phi)*cos(angle)))
elif n % 4 == 2:
return k*(-rx*cos(phi)*cos(angle) + ry*sin(phi)*sin(angle) + 1j*(
-rx*sin(phi)*cos(angle) - ry*cos(phi)*sin(angle)))
elif n % 4 == 3:
return k*(rx*cos(phi)*sin(angle) + ry*sin(phi)*cos(angle) + 1j*(
rx*sin(phi)*sin(angle) - ry*cos(phi)*cos(angle)))
else:
raise ValueError("n should be a positive integer.")
|
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 degs < domain_lower_limit:
degs += 360
return degs
if self.delta > 0:
degs = _deg(psi, domain_lower_limit=self.theta)
else:
degs = _deg(psi, domain_lower_limit=self.theta)
return (degs - self.theta)/self.delta
|
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: ~~~~~~~~~~
# rx*sin(phi)*sin(a(t)) = ry*cos(phi)*cos(a(t))
# (rx/ry)*tan(phi)*tan(a(t)) = 1
# a(t) = arctan((ry/rx)*cot(phi))
# atanres = arctan((ry/rx)*cot(phi)) === atan_y
# ~~~~~~~~
# (2*pi/360)*(self.theta + self.delta*t) = atanres + pi*k
# Therfore, for both x' and y', we have...
# t = ((atan_{x/y} + pi*k)*(360/(2*pi)) - self.theta)/self.delta
# for all k s.t. 0 < t < 1
from math import atan, tan
if cos(self.phi) == 0:
atan_x = pi/2
atan_y = 0
elif sin(self.phi) == 0:
atan_x = 0
atan_y = pi/2
else:
rx, ry = self.radius.real, self.radius.imag
atan_x = atan(-(ry/rx)*tan(self.phi))
atan_y = atan((ry/rx)/tan(self.phi))
def angle_inv(ang, k): # inverse of angle from Arc.derivative()
return ((ang + pi*k)*(360/(2*pi)) - self.theta)/self.delta
xtrema = [self.start.real, self.end.real]
ytrema = [self.start.imag, self.end.imag]
for k in range(-4, 5):
tx = angle_inv(atan_x, k)
ty = angle_inv(atan_y, k)
if 0 <= tx <= 1:
xtrema.append(self.point(tx).real)
if 0 <= ty <= 1:
ytrema.append(self.point(ty).imag)
xmin = max(xtrema)
return min(xtrema), max(xtrema), min(ytrema), max(ytrema)
|
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_radius=self.autoscale_radius)
|
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)]))
return subpaths
|
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_WARNING_ON=False.")
if warning_on:
warn(mes)
return self._closed and self._is_closable()
|
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
parts = []
previous_segment = None
end = self[-1].end
for segment in segments:
seg_start = segment.start
# If the start of this segment does not coincide with the end of
# the last segment or if this segment is actually the close point
# of a closed path, then we should start a new subpath here.
if current_pos != seg_start or \
(self_closed and seg_start == end and use_closed_attrib):
parts.append('M {},{}'.format(seg_start.real, seg_start.imag))
if isinstance(segment, Line):
args = segment.end.real, segment.end.imag
parts.append('L {},{}'.format(*args))
elif isinstance(segment, CubicBezier):
if useSandT and segment.is_smooth_from(previous_segment,
warning_on=False):
args = (segment.control2.real, segment.control2.imag,
segment.end.real, segment.end.imag)
parts.append('S {},{} {},{}'.format(*args))
else:
args = (segment.control1.real, segment.control1.imag,
segment.control2.real, segment.control2.imag,
segment.end.real, segment.end.imag)
parts.append('C {},{} {},{} {},{}'.format(*args))
elif isinstance(segment, QuadraticBezier):
if useSandT and segment.is_smooth_from(previous_segment,
warning_on=False):
args = segment.end.real, segment.end.imag
parts.append('T {},{}'.format(*args))
else:
args = (segment.control.real, segment.control.imag,
segment.end.real, segment.end.imag)
parts.append('Q {},{} {},{}'.format(*args))
elif isinstance(segment, Arc):
args = (segment.radius.real, segment.radius.imag,
segment.rotation,int(segment.large_arc),
int(segment.sweep),segment.end.real, segment.end.imag)
parts.append('A {},{} {} {:d},{:d} {},{}'.format(*args))
current_pos = segment.end
previous_segment = segment
if self_closed:
parts.append('Z')
return ' '.join(parts)
|
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):
T1 = T0 + seg_length # the T-value the current segment ends on
if T1 >= T:
# This is the segment!
t = (T - T0)/seg_length
return seg_idx, t
T0 = T1
assert 0 <= T <= 1
raise BugException
|
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)
raise
segment_start = sum(self._lengths[:seg_idx])
segment_end = segment_start + self._lengths[seg_idx]
T = (segment_end - segment_start)*t + segment_start
return T
|
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 Note: seg can be a segment in the Path object or its
corresponding index.
| 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):
return float('inf')
elif np.isclose(t, 1) and (seg_idx != len(self) - 1 or
self.end == self.start):
next_seg_in_path = self._segments[
(seg_idx + 1) % len(self._segments)]
if not next_seg_in_path.joins_smoothly_with(seg):
return float('inf')
dz = self.derivative(T)
ddz = self.derivative(T, n=2)
dx, dy = dz.real, dz.imag
ddx, ddy = ddz.real, ddz.imag
return abs(dx*ddy - dy*ddx)/(dx*dx + dy*dy)**1.5
|
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) - integral(0)
return area_enclosed
def seg2lines(seg):
num_lines = int(ceil(seg.length() / chord_length))
pts = [seg.point(t) for t in np.linspace(0, 1, num_lines+1)]
return [Line(pts[i], pts[i+1]) for i in range(num_lines)]
assert self.isclosed()
bezier_path_approximation = []
for seg in self:
if isinstance(seg, Arc):
bezier_path_approximation += seg2lines(seg)
else:
bezier_path_approximation.append(seg)
return area_without_arcs(Path(*bezier_path_approximation))
|
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
sure this `chord_length` is set to a reasonable value (e.g. by
checking curvature).
Notes
-----
* Negative area results from clockwise (as opposed to
counter-clockwise) parameterization of the input Path.
To Contributors
---------------
This is one of many parts of `svgpathtools` that could be
improved by a noble soul implementing a piecewise-linear
approximation scheme for paths (one with controls to guarantee a
desired accuracy).
| 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 intersection_list:
return intersection_list[0]
for t1, t2 in seg1.intersect(seg2, tol=tol):
T1 = path1.t2T(seg1, t1)
T2 = path2.t2T(seg2, t2)
intersection_list.append(((T1, seg1, t1), (T2, seg2, t2)))
if justonemode and intersection_list:
return intersection_list[0]
# Note: If the intersection takes place at a joint (point one seg ends
# and next begins in path) then intersection_list may contain a
# redundant intersection. This code block checks for and removes said
# redundancies.
if intersection_list:
pts = [seg1.point(_t1)
for _T1, _seg1, _t1 in list(zip(*intersection_list))[0]]
indices2remove = []
for ind1 in range(len(pts)):
for ind2 in range(ind1 + 1, len(pts)):
if abs(pts[ind1] - pts[ind2]) < tol:
# then there's a redundancy. Remove it.
indices2remove.append(ind2)
intersection_list = [inter for ind, inter in
enumerate(intersection_list) if
ind not in indices2remove]
return intersection_list
|
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).
Note: If the two path objects coincide for more than a finite set of
points, this code will fail.
| 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
else:
seg1_idx, t_seg1 = self.T2t(T1)
seg1 = self[seg1_idx]
if np.isclose(t_seg1, 0):
i1 = (self.index(seg1) - 1) % len(self)
seg1 = self[i1]
t_seg1 = 1
else:
i1 = self.index(seg1)
if T0 == 0:
seg0 = self[0]
t_seg0 = 0
i0 = 0
else:
seg0_idx, t_seg0 = self.T2t(T0)
seg0 = self[seg0_idx]
if np.isclose(t_seg0, 1):
i0 = (self.index(seg0) + 1) % len(self)
seg0 = self[i0]
t_seg0 = 0
else:
i0 = self.index(seg0)
if T0 < T1 and i0 == i1:
new_path = Path(seg0.cropped(t_seg0, t_seg1))
else:
new_path = Path(seg0.cropped(t_seg0, 1))
# T1<T0 must cross discontinuity case
if T1 < T0:
if not self.isclosed():
raise ValueError("This path is not closed, thus T0 must "
"be less than T1.")
else:
for i in range(i0 + 1, len(self)):
new_path.append(self[i])
for i in range(0, i1):
new_path.append(self[i])
# T0<T1 straight-forward case
else:
for i in range(i0 + 1, i1):
new_path.append(self[i])
if t_seg1 != 0:
new_path.append(seg1.cropped(0, t_seg1))
return new_path
|
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)
if seg_global_min[0] < global_min[0]:
global_min = seg_global_min + (seg_idx,)
if seg_global_max[0] > global_max[0]:
global_max = seg_global_max + (seg_idx,)
return global_min, global_max
|
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.