signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def valid(self, name): | name = re.sub('<STR_LIT>', '<STR_LIT>', name)<EOL>if re.match('<STR_LIT>', name):<EOL><INDENT>name = '<STR_LIT:_>' + name<EOL><DEDENT>return name<EOL> | Ensure a variable name is valid.
Note: Assumes variable names are ASCII, which isn't necessarily true in
Python 3.
Args:
name: A proposed variable name.
Returns:
A valid version of the name. | f4080:c1:m2 |
def trim(self, name): | if len(name) > self.MAX_LENGTH and self.target:<EOL><INDENT>name = self.TEMP_VAR.format(self._name(self.target))<EOL><DEDENT>if len(name) > self.MAX_LENGTH:<EOL><INDENT>while True:<EOL><INDENT>name = '<STR_LIT>'.format(random.randint(<NUM_LIT:0>, <NUM_LIT:16> ** <NUM_LIT:4> - <NUM_LIT:1>))<EOL>if name not in self.names... | When the name is too long, use the LHS or a random string instead. | f4080:c1:m3 |
def unique(self, name): | <EOL>name = self.valid(name)<EOL>name = self.trim(name)<EOL>unique_name = name<EOL>i = <NUM_LIT:2><EOL>while unique_name in self.names:<EOL><INDENT>unique_name = name + str(i)<EOL>i += <NUM_LIT:1><EOL><DEDENT>self.names.add(unique_name)<EOL>return unique_name<EOL> | Make a variable name unique by appending a number if needed. | f4080:c1:m4 |
def __getattr__(self, attr): | if attr.startswith('<STR_LIT:_>') and hasattr(self, attr[<NUM_LIT:1>:]):<EOL><INDENT>return getattr(self, attr[<NUM_LIT:1>:]).__wrapped__.__get__(self, Namer)<EOL><DEDENT>raise AttributeError<EOL> | Access unwrapped versions of methods.
Methods are wrapped with `uniqify` to return a unique version of a
name. Internally the class however might want to use the original
version of these methods. This method makes those accessible by using a
leading underscore. | f4080:c1:m6 |
def get_name(node): | if isinstance(node, gast.Name):<EOL><INDENT>return node.id<EOL><DEDENT>elif isinstance(node, (gast.Subscript, gast.Attribute)):<EOL><INDENT>return get_name(node.value)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError<EOL><DEDENT> | Get the name of a variable.
Args:
node: A `Name`, `Subscript` or `Attribute` node.
Returns:
The name of the variable e.g. `'x'` for `x`, `x.i` and `x[i]`. | f4082:m0 |
def get_updated(node): | if isinstance(node, gast.Assign):<EOL><INDENT>return set.union(*(_get_target(target)<EOL>for target in node.targets))<EOL><DEDENT>elif isinstance(node, (gast.For, gast.AugAssign)):<EOL><INDENT>return _get_target(node.target)<EOL><DEDENT>elif isinstance(node, gast.arguments):<EOL><INDENT>targets = set(arg.id for arg in ... | Return the variable names created or mutated by this statement.
This function considers assign statements, augmented assign statements, and
the targets of for loops, as well as function arguments.
For example, `x[0] = 2` will return `x`, `x, y = 3, 4` will return `x` and
`y`, `for i in range(x)` will ... | f4082:m2 |
def copy_node(node): | if not isinstance(node, gast.AST):<EOL><INDENT>return [copy_node(n) for n in node]<EOL><DEDENT>new_node = copy.deepcopy(node)<EOL>setattr(new_node, anno.ANNOTATION_FIELD,<EOL>getattr(node, anno.ANNOTATION_FIELD, {}).copy())<EOL>return new_node<EOL> | Copy a node but keep its annotations intact. | f4082:m3 |
def is_insert_grad_of_statement(node): | tangent_calls = [anno.getanno(item.context_expr, '<STR_LIT>', None)<EOL>is utils.insert_grad_of for item in node.items]<EOL>if all(tangent_calls):<EOL><INDENT>return True<EOL><DEDENT>elif any(tangent_calls):<EOL><INDENT>raise ValueError<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT> | Check whether a context manager calls `insert_grad_of`.
Args:
node: The context manager node.
Returns:
Whether or not this node contains `insert_grad_of` calls.
Raises:
ValueError: If the `insert_grad_of` calls are mixed with other calls. | f4082:m5 |
def prepend(self, node): | if not isinstance(node, grammar.STATEMENTS):<EOL><INDENT>raise ValueError<EOL><DEDENT>self.to_prepend[-<NUM_LIT:1>].appendleft(node)<EOL> | Prepend a statement to the current statement.
Note that multiple calls to prepend will result in the last statement to be
prepended to end up at the top.
Args:
node: The statement to prepend.
Raises:
ValueError: If the given node is not a statement. | f4083:c0:m1 |
def append(self, node): | if not isinstance(node, grammar.STATEMENTS):<EOL><INDENT>raise ValueError<EOL><DEDENT>self.to_append[-<NUM_LIT:1>].append(node)<EOL> | Append a statement to the current statement.
Note that multiple calls to append will result in the last statement to be
appended to end up at the bottom.
Args:
node: The statement to append.
Raises:
ValueError: If the given node is not a statement. | f4083:c0:m2 |
def remove(self, node): | self.to_remove.add(node)<EOL> | Remove the given node. | f4083:c0:m3 |
def insert_top(self, node): | if not isinstance(node, grammar.STATEMENTS):<EOL><INDENT>raise ValueError<EOL><DEDENT>self.to_insert_top.append(node)<EOL> | Insert statements at the top of the function body.
Note that multiple calls to `insert_top` will result in the statements
being prepended in that order; this is different behavior from `prepend`.
Args:
node: The statement to prepend.
Raises:
ValueError: If the give... | f4083:c0:m4 |
def prepend_block(self, node, reverse=False): | if not isinstance(node, grammar.STATEMENTS):<EOL><INDENT>raise ValueError<EOL><DEDENT>if reverse:<EOL><INDENT>self.to_prepend_block[-<NUM_LIT:1>].appendleft(node)<EOL><DEDENT>else:<EOL><INDENT>self.to_prepend_block[-<NUM_LIT:1>].append(node)<EOL><DEDENT> | Prepend a statement to the current block.
Args:
node: The statement to prepend.
reverse: When called multiple times, this flag determines whether the
statement should be prepended or appended to the already inserted
statements.
Raises:
ValueErr... | f4083:c0:m5 |
def append_block(self, node, reverse=False): | if not isinstance(node, grammar.STATEMENTS):<EOL><INDENT>raise ValueError<EOL><DEDENT>if reverse:<EOL><INDENT>self.to_append_block[-<NUM_LIT:1>].appendleft(node)<EOL><DEDENT>else:<EOL><INDENT>self.to_append_block[-<NUM_LIT:1>].append(node)<EOL><DEDENT> | Append a statement to the current block.
Args:
node: The statement to prepend.
reverse: When called multiple times, this flag determines whether the
statement should be prepended or appended to the already inserted
statements.
Raises:
ValueErro... | f4083:c0:m6 |
def visit_statements(self, nodes): | for node in nodes:<EOL><INDENT>if isinstance(node, gast.AST):<EOL><INDENT>self.to_prepend.append(deque())<EOL>self.to_append.append(deque())<EOL>node = self.visit(node)<EOL>self.visit_statements(self.to_prepend.pop())<EOL>if isinstance(node, gast.AST):<EOL><INDENT>self.to_insert[-<NUM_LIT:1>].append(node)<EOL><DEDENT>e... | Visit a series of nodes in a node body.
This function is factored out so that it can be called recursively on
statements that are appended or prepended. This allows e.g. a nested
expression to prepend a statement, and that statement can prepend a
statement again, etc.
Args:
... | f4083:c0:m7 |
def forward_ad(node, wrt, preserve_result=False, check_dims=True): | if not isinstance(node, gast.FunctionDef):<EOL><INDENT>raise TypeError<EOL><DEDENT>cfg_obj = cfg.CFG.build_cfg(node)<EOL>cfg.Active(range(len(node.args.args))).visit(cfg_obj.entry)<EOL>fad = ForwardAD(wrt, preserve_result, check_dims)<EOL>node = fad.visit(node)<EOL>node = annotate.find_stacks(node)<EOL>node = gast.Modu... | Perform forward-mode AD on an AST.
This function analyses the AST to determine which variables are active and
proceeds by taking the naive derivative. Before returning the primal and
adjoint it annotates push and pop statements as such.
Args:
node: A `FunctionDef` AST node.
wrt: A tuple of... | f4085:m0 |
def visit_Assign(self, node): | <EOL>self.target = node.targets[<NUM_LIT:0>]<EOL>self.value = node.value<EOL>tangent_node = self.visit(self.value)<EOL>if tangent_node == self.value:<EOL><INDENT>self.target = None<EOL>return node<EOL><DEDENT>if self.value:<EOL><INDENT>new_node = template.replace(<EOL>tangents.tangents[gast.Assign],<EOL>replace_grad=te... | Visit assignment statement.
Notes
-----
This method sets the `self.target` attribute to the first assignment
target for callees to use. | f4085:c0:m6 |
def visit_Num(self, node): | if not self.target:<EOL><INDENT>return node<EOL><DEDENT>template_ = tangents.tangents[node.__class__]<EOL>tangent_node = template.replace(<EOL>template_,<EOL>replace_grad=template.Replace.TANGENT,<EOL>namer=self.namer,<EOL>x=node,<EOL>z=self.target)<EOL>return tangent_node<EOL> | Tangent of e.g.
x = 0 | f4085:c0:m11 |
def visit_Name(self, node): | if not self.target:<EOL><INDENT>return node<EOL><DEDENT>if node.id in ['<STR_LIT:None>','<STR_LIT:True>','<STR_LIT:False>']:<EOL><INDENT>template_ = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>template_ = tangents.tangents[node.__class__]<EOL><DEDENT>tangent_node = template.replace(<EOL>template=template_,<EOL>replace_gr... | Tangent of e.g.
x = y | f4085:c0:m12 |
def visit_NameConstant(self, node): | constant_val = {<EOL>True: '<STR_LIT:True>',<EOL>False: '<STR_LIT:False>',<EOL>None: '<STR_LIT:None>',<EOL>}[node.value]<EOL>new_node = gast.Name(id=constant_val,ctx=gast.Load(),annotation=None)<EOL>return self.visit_Name(new_node)<EOL> | Tangent of e.g.
x = None
Lines of this type are sometimes auto-generated by reverse-mode,
and thus handling them is important for higher-order autodiff
We will shunt NameConstant tangents off to visit_Name, to prevent
code duplication. | f4085:c0:m13 |
def visit_Attribute(self, node): | if not self.target:<EOL><INDENT>return node<EOL><DEDENT>template_ = tangents.tangents[node.__class__]<EOL>tangent_node = template.replace(<EOL>template=template_,<EOL>replace_grad=template.Replace.TANGENT,<EOL>namer=self.namer,<EOL>x=node,<EOL>z=self.target)<EOL>return tangent_node<EOL> | Tangent of e.g.
x = y.z | f4085:c0:m14 |
def visit_Subscript(self, node): | if not self.target:<EOL><INDENT>return node<EOL><DEDENT>template_ = tangents.tangents[node.__class__]<EOL>tangent_node = template.replace(<EOL>template=template_,<EOL>replace_grad=template.Replace.TANGENT,<EOL>namer=self.namer,<EOL>x=node,<EOL>z=self.target)<EOL>return tangent_node<EOL> | Tangent of e.g.
x = y[i] | f4085:c0:m15 |
def get_module_functions(modules): | module_fns = set()<EOL>for module in modules:<EOL><INDENT>for key in dir(module):<EOL><INDENT>attr = getattr(module, key)<EOL>if isinstance(<EOL>attr, (types.BuiltinFunctionType, types.FunctionType, numpy.ufunc)):<EOL><INDENT>module_fns.add(attr)<EOL><DEDENT><DEDENT><DEDENT>return module_fns<EOL> | Finds functions that do not have implemented derivatives.
Args:
modules: A list of Python modules. Functions contained in these modules
will be checked for membership in 'implemented', and if not found,
will be added to an 'unimplemented' set
implemented: A Python object containing ... | f4086:m0 |
@adjoint(numpy.linalg.det)<EOL>def adet(z, x): | adjugate = numpy.linalg.det(x) * numpy.linalg.pinv(x)<EOL>d[x] = d[z] * numpy.transpose(adjugate)<EOL> | d|A|/dA = adj(A).T
See Jacobi's formula: https://en.wikipedia.org/wiki/Jacobi%27s_formula | f4086:m40 |
def resolve_calls(func): | node = quoting.parse_function(func)<EOL>ResolveCalls(func).visit(node)<EOL>return node<EOL> | Parse a function into an AST with function calls resolved.
Since the calls are resolved using the global and local namespace of the
function it means that procedural parameters (i.e. functions passed as
arguments) won't be resolved.
Similarly, functions defined inside of the function that we are tryin... | f4089:m0 |
def find_stacks(node, strict=False): | <EOL>fso = FindStackOps()<EOL>fso.visit(node)<EOL>AnnotateStacks(fso.push_pop_pairs, strict).visit(node)<EOL>return node<EOL> | Find pushes and pops to the stack and annotate them as such.
Args:
node: An AST node that might contain stack pushes and pops.
strict: A boolean indicating whether to stringently test whether each
push and pop are matched. This is not always possible when taking
higher-order derivat... | f4089:m2 |
def unused(node): | cfg.forward(node, cfg.ReachingDefinitions())<EOL>unused_obj = Unused()<EOL>unused_obj.visit(node)<EOL>return unused_obj.unused<EOL> | Find unused definitions that can be remove.
This runs reaching definitions analysis followed by a walk over the AST to
find all variable definitions that are not used later on.
Args:
node: The AST of e.g. a function body to find unused variable definitions.
Returns:
unused: After visiting... | f4089:m3 |
@property<EOL><INDENT>def unused(self):<DEDENT> | unused = self.definitions - self.used<EOL>used_nodes = set([u[<NUM_LIT:1>] for u in self.used])<EOL>unused = set([u for u in unused if u[<NUM_LIT:1>] not in used_nodes])<EOL>return unused<EOL> | Calculate which AST nodes are unused.
Note that we have to take special care in the case of
x,y = f(z) where x is used later, but y is not. | f4089:c3:m1 |
def add_comment(node, text, location='<STR_LIT>'): | anno.setanno(node, '<STR_LIT>', dict(location=location, text=text), safe=False)<EOL>return node<EOL> | Add a comment to the given node.
If the `SourceWithCommentGenerator` class is used these comments will be
output as part of the source code.
Note that a node can only contain one comment. Subsequent calls to
`add_comment` will ovverride the existing comments.
Args:
node: The AST node whose ... | f4090:m0 |
def remove_repeated_comments(node): | last_comment = {'<STR_LIT:text>': None}<EOL>for _node in gast.walk(node):<EOL><INDENT>if anno.hasanno(_node, '<STR_LIT>'):<EOL><INDENT>comment = anno.getanno(_node, '<STR_LIT>')<EOL>if comment['<STR_LIT:text>'] == last_comment['<STR_LIT:text>']:<EOL><INDENT>anno.delanno(_node, '<STR_LIT>')<EOL><DEDENT>last_comment = co... | Remove comments that repeat themselves.
Multiple statements might be annotated with the same comment. This way if one
of the statements is deleted during optimization passes, the comment won't be
lost. This pass removes sequences of identical comments, leaving only the
first one.
Args:
node:... | f4090:m1 |
def tangent(f): | node = annotate.resolve_calls(f)<EOL>RemoveWith().visit(node)<EOL>wrapped = functools.wraps(f)(compile_.compile_function(node))<EOL>wrapped.tangent = f<EOL>return wrapped<EOL> | A decorator which removes the `with insert_grad_of` statement.
This allows the function to be called as usual.
Args:
f: A function
Returns:
A function with any `with insert_grad_of` context managers removed. | f4091:m0 |
def validate(node, source): | <EOL>lf = LanguageFence(source, strict=False)<EOL>lf.visit(node)<EOL>return node<EOL> | Call this function to validate an AST. | f4092:m0 |
def __init__(self, source, strict=True): | self._visited_top_module = False<EOL>if not source:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self._source = source<EOL>self._strict = strict<EOL>self._current_lineno = None <EOL>self._current_offset = None <EOL>super(LanguageFence, self).__init__()<EOL> | Creates a LanguageFence.
Args:
source: String, the source code of the AST that will be verified.
strict: Boolean, set to False to allow unsafe constructs.
Raises:
ValueError: if source code has not been supplied. | f4092:c0:m0 |
def compile_file(source, globals_=None): | if isinstance(source, gast.AST):<EOL><INDENT>source = quoting.to_source(source)<EOL><DEDENT>tempdir = tempfile.mkdtemp()<EOL>uuid = str(uuid4().hex[:<NUM_LIT:4>])<EOL>tmpname = os.path.join(tempdir, '<STR_LIT>' % uuid)<EOL>with open(tmpname, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(source)<EOL><DEDENT>module_name = '<S... | Compile by saving to file and importing that.
Compiling the AST/source code this way ensures that the source code is
readable by e.g. `pdb` or `inspect`.
Args:
source: The code to compile, either as a string or as an AST.
globals_: A dictionary of variables that should be available as globals ... | f4093:m0 |
def compile_function(node, globals_=None): | if not isinstance(node, gast.AST):<EOL><INDENT>if not isinstance(node, six.string_types):<EOL><INDENT>raise TypeError<EOL><DEDENT>node = gast.parse(node)<EOL><DEDENT>if isinstance(node, gast.Module):<EOL><INDENT>for succ in node.body:<EOL><INDENT>if isinstance(succ, gast.FunctionDef):<EOL><INDENT>name = succ.name<EOL>b... | Convert an AST or string into a function with inspectable source.
This function uses `compile_file` internally, but instead of returning the
entire module it will return the function only.
Args:
node: A `FunctionDef` node or a `Module` node which contains at least one
`FunctionDef` node. I... | f4093:m1 |
def trace_grad(fn, args): | from tensorflow.python.eager.backprop import make_vjp<EOL>result, vjp = make_vjp(fn)(*args)<EOL>return result, vjp<EOL> | Trace a function, and return a VJP and the function's output. | f4094:m0 |
def trace(fn): | fn.should_trace = True<EOL>return fn<EOL> | Decorator that marks a function to be traced. | f4094:m1 |
@fixed_point<EOL>def optimize(node): | node = dead_code_elimination(node)<EOL>node = constant_folding(node)<EOL>node = assignment_propagation(node)<EOL>return node<EOL> | Perform a series of optimization passes.
This function performs a series of optimizations (dead code elimination,
constant folding, variable folding) on the given AST.
It optimizes the code repeatedly until reaching a fixed point. The fixed
point is determine roughly by checking whether the number of l... | f4095:m1 |
@fixed_point<EOL>def dead_code_elimination(node): | to_remove = set(def_[<NUM_LIT:1>] for def_ in annotate.unused(node)<EOL>if not isinstance(def_[<NUM_LIT:1>], (gast.arguments, gast.For)))<EOL>for n in list(to_remove):<EOL><INDENT>for succ in gast.walk(n):<EOL><INDENT>if anno.getanno(succ, '<STR_LIT>', False):<EOL><INDENT>to_remove.add(anno.getanno(succ, '<STR_LIT>'))<... | Perform a simple form of dead code elimination on a Python AST.
This method performs reaching definitions analysis on all function
definitions. It then looks for the definition of variables that are not used
elsewhere and removes those definitions.
This function takes into consideration push and pop s... | f4095:m2 |
def read_counts(node): | cfg.forward(node, cfg.ReachingDefinitions())<EOL>rc = ReadCounts()<EOL>rc.visit(node)<EOL>return rc.n_read<EOL> | Check how many times a variable definition was used.
Args:
node: An AST to analyze.
Returns:
A dictionary from assignment nodes to the number of times the assigned to
variable was used. | f4095:m3 |
@fixed_point<EOL>def assignment_propagation(node): | n_reads = read_counts(node)<EOL>to_remove = []<EOL>for succ in gast.walk(node):<EOL><INDENT>if (isinstance(succ, gast.Assign) and isinstance(succ.value, gast.Name) and<EOL>len(succ.targets) == <NUM_LIT:1> and isinstance(succ.targets[<NUM_LIT:0>], gast.Name)):<EOL><INDENT>rhs_name = succ.value.id<EOL>rhs_defs = [def_[<N... | Perform assignment propagation.
Assignment propagation is not a compiler optimization as much as a
readability optimization. If a variable name is used only once, it gets
renamed when possible e.g. `y = x; z = y` will become `z = x`.
Args:
node: The AST to optimize.
Returns:
The optim... | f4095:m4 |
@fixed_point<EOL>def constant_folding(node): | f = ConstantFolding()<EOL>return f.visit(node)<EOL> | Perform constant folding.
This function also uses arithmetic identities (like multiplying with one or
adding zero) to simplify statements. However, it doesn't inline constants in
expressions, so the simplifications don't propagate.
Args:
node: The AST to optimize.
Returns:
The optimiz... | f4095:m5 |
def replace(template, replace_grad=Replace.PARTIAL,<EOL>namer=None, **replacements): | <EOL>is_function = isinstance(template, types.FunctionType)<EOL>if is_function:<EOL><INDENT>tree = quoting.parse_function(template).body[<NUM_LIT:0>]<EOL>placeholders = set(arg.id for arg in tree.args.args)<EOL>tree.args.args = []<EOL>if tree.args.vararg:<EOL><INDENT>placeholders.add(tree.args.vararg)<EOL>tree.args.var... | Replace placeholders in a Python template (quote).
Args:
template: A function, AST node or string to be used as a template. Note
that if a function is passed, any placeholder is expected to also be a
function argument. If a string is passed, it must represent valid
Python code, ... | f4096:m0 |
def forward(node, analysis): | if not isinstance(analysis, Forward):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>for succ in gast.walk(node):<EOL><INDENT>if isinstance(succ, gast.FunctionDef):<EOL><INDENT>cfg_obj = CFG.build_cfg(succ)<EOL>analysis.visit(cfg_obj.entry)<EOL><DEDENT><DEDENT>return node<EOL> | Perform a given analysis on all functions within an AST. | f4097:m0 |
@staticmethod<EOL><INDENT>def backlink(node):<DEDENT> | seen = set()<EOL>to_see = [node]<EOL>while to_see:<EOL><INDENT>node = to_see.pop()<EOL>seen.add(node)<EOL>for succ in node.next:<EOL><INDENT>succ.prev.add(node)<EOL>if succ not in seen:<EOL><INDENT>to_see.append(succ)<EOL><DEDENT><DEDENT><DEDENT> | Given a CFG with outgoing links, create incoming links. | f4097:c1:m1 |
def set_head(self, node): | for head in self.head:<EOL><INDENT>head.next.add(node)<EOL><DEDENT>self.head[:] = []<EOL>self.head.append(node)<EOL> | Link this node to the current leaves. | f4097:c1:m2 |
@classmethod<EOL><INDENT>def build_cfg(cls, node):<DEDENT> | if not isinstance(node, gast.FunctionDef):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>cfg = cls()<EOL>cfg.entry = Node(node.args)<EOL>cfg.head = [cfg.entry]<EOL>cfg.visit_statements(node.body)<EOL>cfg.exit = Node(None)<EOL>cfg.set_head(cfg.exit)<EOL>cfg.backlink(cfg.entry)<EOL>return cfg<EOL> | Build a CFG for a function.
Args:
node: A function definition the body of which to analyze.
Returns:
A CFG object.
Raises:
TypeError: If the input is not a function definition. | f4097:c1:m3 |
def array_size(x, axis): | axis_shape = x.shape if axis is None else tuple(x.shape[a] for a in axis)<EOL>return max(numpy.prod(axis_shape), <NUM_LIT:1>)<EOL> | Calculate the size of `x` along `axis` dimensions only. | f4098:m0 |
def register_unbroadcast(t, unbroadcaster_function): | assert t not in unbroadcasters<EOL>unbroadcasters[t] = unbroadcaster_function<EOL> | Register a new unbroadcaster.
Unbroadcasters are used to undo broadcasting, e.g. np.eye(3) + 3
will broadcast 3 to np.shape(np.eye(3)). In the backward pass, we have to
undo this.
Args:
t: A Python type object. The data type supported by the
unbroadcaster.
unbroadcaster_function: A... | f4098:m1 |
def unbroadcast(array, like): | unbroadcaster = unbroadcasters[type(array)]<EOL>return unbroadcaster(array, like)<EOL> | Reverse the broadcasting operation.
Args:
array: An array.
like: An array that could have been broadcasted to the shape of array.
Returns:
Tensor with certain dimensions summed to match the shape of `like`. | f4098:m2 |
def create_unbroadcast_axis(shape, broadcast_shape): | return tuple(<EOL>-(<NUM_LIT:1> + i)<EOL>for i in range(len(broadcast_shape))<EOL>if i >= len(shape) or broadcast_shape[-(<NUM_LIT:1> + i)] > shape[-(<NUM_LIT:1> + i)])<EOL> | Creates the reduction axis for unbroadcasting.
Args:
shape: A list. The shape after the broadcast operation.
broadcast_shape: A list. The original shape the array being unbroadcast
had.
Returns:
A list. The axes along which the array needs to be reduced. These axes will
be distr... | f4098:m3 |
def unbroadcast_numpy_to(array, shape): | axis = create_unbroadcast_axis(shape, numpy.shape(array))<EOL>return numpy.reshape(numpy.sum(array, axis=axis), shape)<EOL> | Reverse the broadcasting operation.
Args:
array: An array.
shape: A shape that could have been broadcasted to the shape of array.
Returns:
Array with dimensions summed to match `shape`. | f4098:m4 |
def unreduce(array, shape, axis, keepdims): | unreducer = unreducers[type(array)]<EOL>return unreducer(array, shape, axis, keepdims)<EOL> | Reverse summing over a dimension.
Args:
array: The array that was reduced.
shape: The original shape of the array before reduction.
axis: The axis or axes that were summed.
keepdims: Whether these axes were kept as singleton axes.
Returns:
An array with axes broadcast to match th... | f4098:m5 |
def unreduce_like(array, original_array, axis, keepdims): | atype = type(array)<EOL>unreducer = unreducers[atype]<EOL>shape = shape_functions[atype]<EOL>return unreducer(array, shape(original_array), axis, keepdims)<EOL> | Reverse summing over a dimension.
Args:
array: The array that was reduced.
original_array: An array whose shape to unreduce to.
axis: The axis or axes that were summed.
keepdims: Whether these axes were kept as singleton axes.
Returns:
An array with axes broadcast to match the sh... | f4098:m6 |
def unreduce_array(array, shape, axis, keepdims): | <EOL>if axis is not None and (not keepdims or keepdims is numpy._NoValue): <EOL><INDENT>if isinstance(axis, int):<EOL><INDENT>axis = axis,<EOL><DEDENT>for ax in sorted(axis):<EOL><INDENT>array = numpy.expand_dims(array, ax)<EOL><DEDENT><DEDENT>return numpy.broadcast_to(array, shape)<EOL> | Reverse summing over a dimension, NumPy implementation.
Args:
array: The array that was reduced.
shape: The original shape of the array before reduction.
axis: The axis or axes that were summed.
keepdims: Whether these axes were kept as singleton axes.
Returns:
An array with axes... | f4098:m7 |
def register_shape_function(t, shape_function): | assert t not in shape_functions<EOL>shape_functions[t] = shape_function<EOL> | Register a new shape function.
Shape functions extract the shape of an array-like object.
Args:
t: A Python type object. The data type supported by the
unreducer.
shape_function: A unary function that returns a list or tuple with zero
or more integers representing the dimensions of... | f4098:m8 |
def register_unreduce(t, unreducer_function): | assert t not in unreducers<EOL>unreducers[t] = unreducer_function<EOL> | Register a new unreducer.
Unreducers are used to undo reduction, e.g. np.sum(np.eye(3))
will reduce a (3,3) array to a scalar. In the backward pass, we have to
undo this.
Args:
t: A Python type object. The data type supported by the
unreducer.
unreducer_function: A function with th... | f4098:m9 |
def astype(array, y): | if isinstance(y, autograd.core.Node):<EOL><INDENT>return array.astype(numpy.array(y.value).dtype)<EOL><DEDENT>return array.astype(numpy.array(y).dtype)<EOL> | A functional form of the `astype` method.
Args:
array: The array or number to cast.
y: An array or number, as the input, whose type should be that of array.
Returns:
An array or number with the same dtype as `y`. | f4098:m10 |
def balanced_eq(x, z, y): | return (x == z) / (<NUM_LIT:1.0> + (x == y))<EOL> | Gradient of the max operator with tie breaking.
Args:
x: The left value
z: The maximum of x and y
y: The right value
Returns:
The gradient of the left value i.e. 1 if it is the maximum, 0.5 if they are
equal and 0 if it was not the maximum. | f4098:m11 |
def init_common_object(obj): | if obj is numpy._globals._NoValue: <EOL><INDENT>return obj<EOL><DEDENT>raise ValueError('<STR_LIT>' % obj)<EOL> | Initialize gradients for the types of common objects we support. | f4098:m12 |
def init_zero_int(_): | global init_zero_int_warnings_left<EOL>if init_zero_int_warnings_left:<EOL><INDENT>print(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>init_zero_int_warnings_left -= <NUM_LIT:1><EOL><DEDENT>return <NUM_LIT:0><EOL> | Initialize gradient for an integral type. This prints a warning. | f4098:m13 |
def init_zero_bool(_): | global init_zero_bool_warnings_left<EOL>if init_zero_bool_warnings_left:<EOL><INDENT>print(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>init_zero_bool_warnings_left -= <NUM_LIT:1><EOL><DEDENT>return False<EOL> | Initialize gradient for an bool type. This prints a warning. | f4098:m14 |
def register_init_grad(t, init_grad_function): | assert t not in grad_initializers<EOL>grad_initializers[t] = (init_grad_function, True)<EOL> | Register a new gradient initializer.
Gradient initializers are used to initialize new adjoint and tangent
variables.
TODO: Link to the document explaining the overall terminology and mechanics.
Args:
t: A Python type object. The data type supported by the initializer.
init_grad_function: A... | f4098:m15 |
def init_grad(obj, allow_lazy_initializer=False): | if obj is None:<EOL><INDENT>return <NUM_LIT:0.0><EOL><DEDENT>initializer, supports_lazy_initializer = grad_initializers[type(obj)]<EOL>if supports_lazy_initializer:<EOL><INDENT>if isinstance(obj, ZeroGradient):<EOL><INDENT>if allow_lazy_initializer:<EOL><INDENT>return ZeroGradient(obj.like)<EOL><DEDENT>else:<EOL><INDEN... | Initialize the gradient for an object.
Args:
obj: The object to initialize the gradient for, can be either a number,
array, tuple, list, or dictionary.
allow_lazy_initializer: Whether to allow using the ZeroGradient wrapper,
for efficiency.
Returns:
An object of the same type... | f4098:m16 |
def register_add_grad(left_type, right_type, add_grad_function): | key = (left_type, right_type)<EOL>if key in grad_adders:<EOL><INDENT>raise ValueError('<STR_LIT>' % (key, grad_adders[key]))<EOL><DEDENT>grad_adders[key] = add_grad_function<EOL> | Register a new gradient adder supporting the given types.
Gradient adders are used to add (in the sense of arithmetic addition)
intermediate adjoint and tangent variables.
TODO: Link to the document explaining the overall terminology and mechanics.
Args:
left_type: A Python type object. The data... | f4098:m21 |
def register_all_add_grad(<EOL>add_grad_function, arg_types, exclude=(), ignore_existing=False): | for t1 in arg_types:<EOL><INDENT>for t2 in arg_types:<EOL><INDENT>if (t1, t2) in exclude:<EOL><INDENT>continue<EOL><DEDENT>if ignore_existing and (t1, t2) in grad_adders:<EOL><INDENT>continue<EOL><DEDENT>register_add_grad(t1, t2, add_grad_function)<EOL><DEDENT><DEDENT> | Register a gradient adder for all combinations of given types.
This is a convenience shorthand for calling register_add_grad when registering
gradient adders for multiple types that can be interchanged for the purpose
of addition.
Args:
add_grad_function: A gradient adder, see register_add_grad.... | f4098:m22 |
def add_grad(left, right): | <EOL>assert left is not None and right is not None<EOL>left_type = type(left)<EOL>right_type = type(right)<EOL>if left_type is ZeroGradient:<EOL><INDENT>return right<EOL><DEDENT>if right_type is ZeroGradient:<EOL><INDENT>return left<EOL><DEDENT>return grad_adders[(left_type, right_type)](left, right)<EOL> | Recursively add the gradient of two objects.
Args:
left: The left value to add. Can be either an array, a number, list or
dictionary.
right: The right value. Must be of the same type (recursively) as the left.
Returns:
The sum of the two gradients, which will of the same type. | f4098:m23 |
def register_shape_checker(left_type, right_type, shape_checker_function): | key = (left_type, right_type)<EOL>if key in shape_checkers:<EOL><INDENT>raise ValueError('<STR_LIT>' % (key,<EOL>shape_checkers[key]))<EOL><DEDENT>shape_checkers[key] = shape_checker_function<EOL> | Register a new shape checking function supporting given types.
Shape checkers are primarily used to make sure that the seed derivatives
passed into generated autodiff functions match their corresponding
primal values.
Args:
left_type: A Python type object. The data type of the left operand
... | f4098:m25 |
def register_all_shape_checker(shape_checker_function,<EOL>arg_types,<EOL>exclude=(),<EOL>ignore_existing=False): | for t1 in arg_types:<EOL><INDENT>for t2 in arg_types:<EOL><INDENT>if (t1, t2) in exclude:<EOL><INDENT>continue<EOL><DEDENT>if ignore_existing and (t1, t2) in shape_checkers:<EOL><INDENT>continue<EOL><DEDENT>register_shape_checker(t1, t2, shape_checker_function)<EOL><DEDENT><DEDENT> | Register a gradient adder for all combinations of given types.
This is a convenience shorthand for calling register_add_grad when registering
gradient adders for multiple types that can be interchanged for the purpose
of addition.
Args:
shape_checker_function: A shape checker, see register_shape... | f4098:m26 |
def shapes_match(a, b): | if isinstance(a, (tuple, list)) and isinstance(b, (tuple, list)):<EOL><INDENT>if len(a) != len(b):<EOL><INDENT>return False<EOL><DEDENT>return all([shapes_match(ia, ib) for ia, ib in zip(a, b)])<EOL><DEDENT>elif isinstance(a, dict) and isinstance(b, dict):<EOL><INDENT>if len(a) != len(b):<EOL><INDENT>return False<EOL><... | Recursively check if shapes of object `a` and `b` match.
Will walk lists, tuples and dicts.
Args:
a: object of type (numpy.ndarray,tf.Tensor,list,tuple,dict)
to check for matching shapes against `b`.
b: object to check for matching shape against `a`.
Returns:
A boolean indicat... | f4098:m27 |
def push(stack, x, op_id): | if isinstance(x, numpy.ndarray):<EOL><INDENT>x = x.copy()<EOL><DEDENT>elif isinstance(x, list):<EOL><INDENT>x = x[:]<EOL><DEDENT>if __debug__:<EOL><INDENT>stack.append((x, op_id))<EOL><DEDENT>else:<EOL><INDENT>stack.append(x)<EOL><DEDENT> | Push a value onto the stack (i.e. record it on the tape).
Args:
stack: The stack object, which must support appending values.
x: The value to append. If it is a mutable object like an array or list, it
will be copied before being added onto the stack.
op_id: A unique variable that is al... | f4098:m28 |
def pop(stack, op_id): | if __debug__:<EOL><INDENT>pushed_value, pushed_op_id = stack.pop()<EOL>assert pushed_op_id == op_id, '<STR_LIT>' % (op_id, pushed_op_id)<EOL><DEDENT>else:<EOL><INDENT>pushed_value = stack.pop()<EOL><DEDENT>return pushed_value<EOL> | Pop a value from the stack (i.e. read it from the tape).
Args:
stack: The stack to pop from.
op_id: A unique variable that is also passed into the matching push.
Allows optimization passes to track pairs of pushes and pops.
Returns:
The last value. | f4098:m29 |
def pop_stack(stack, op_id): | if __debug__:<EOL><INDENT>pushed_stack, pushed_op_id = stack.pop()<EOL>assert pushed_op_id == op_id, '<STR_LIT>' % (op_id, pushed_op_id)<EOL><DEDENT>else:<EOL><INDENT>pushed_stack = stack.pop()<EOL><DEDENT>return pushed_stack<EOL> | Proxy of pop, where we know we're popping a stack off of a stack.
We know that we don't need to differentiate through this.
See pop() for more.
Args:
stack: The stack to pop from.
op_id: A unique variable that is also passed into the matching push.
Allows optimization passes to track... | f4098:m30 |
def push_stack(stack, substack, op_id): | if substack is not None and not isinstance(substack, Stack):<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>' %<EOL>type(substack))<EOL><DEDENT>if __debug__:<EOL><INDENT>stack.append((substack, op_id))<EOL><DEDENT>else:<EOL><INDENT>stack.append(substack)<EOL><DEDENT> | Proxy of push, where we know we're pushing a stack onto a stack.
Used when differentiating call trees,where sub-functions get their own stack.
See push() for more.
Args:
stack: The stack object, which must support appending values.
substack: The stack to append.
op_id: A unique variable ... | f4098:m31 |
def insert_grad_of(var): | raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL> | The context manager that allows insertion of arbitrary adjoint code.
This function can be used as a context manager e.g. `with insert_grad_of(x) as dx`
to write code that will be inserted in the adjoint while having access to the
gradients of certain variables.
This function is handled by reverse mode... | f4098:m32 |
def grad_dot(dy, x1, x2): | if len(numpy.shape(x1)) == <NUM_LIT:1>:<EOL><INDENT>dy = numpy.atleast_2d(dy)<EOL><DEDENT>elif len(numpy.shape(x2)) == <NUM_LIT:1>:<EOL><INDENT>dy = numpy.transpose(numpy.atleast_2d(dy))<EOL>x2 = numpy.transpose(numpy.atleast_2d(x2))<EOL><DEDENT>x2_t = numpy.transpose(numpy.atleast_2d(<EOL>numpy.sum(x2, axis=tuple(nump... | Gradient of NumPy dot product w.r.t. to the left hand side.
Args:
dy: The gradient with respect to the output.
x1: The left hand side of the `numpy.dot` function.
x2: The right hand side
Returns:
The gradient with respect to `x1` i.e. `x2.dot(dy.T)` with all the
broadcasting invo... | f4098:m33 |
def signature(obj): | if not callable(obj):<EOL><INDENT>raise TypeError('<STR_LIT>'.format(obj))<EOL><DEDENT>if isinstance(obj, types.MethodType):<EOL><INDENT>sig = signature(obj.__func__)<EOL>if obj.__self__ is None:<EOL><INDENT>if sig.parameters:<EOL><INDENT>first = sig.parameters.values()[<NUM_LIT:0>].replace(<EOL>kind=_POSITIONAL_ONLY)<... | Get a signature object for the passed callable. | f4101:m2 |
def replace(self, name=_void, kind=_void, annotation=_void,<EOL>default=_void, _partial_kwarg=_void): | if name is _void:<EOL><INDENT>name = self._name<EOL><DEDENT>if kind is _void:<EOL><INDENT>kind = self._kind<EOL><DEDENT>if annotation is _void:<EOL><INDENT>annotation = self._annotation<EOL><DEDENT>if default is _void:<EOL><INDENT>default = self._default<EOL><DEDENT>if _partial_kwarg is _void:<EOL><INDENT>_partial_kwar... | Creates a customized copy of the Parameter. | f4101:c3:m5 |
def __init__(self, parameters=None, return_annotation=_empty,<EOL>__validate_parameters__=True): | if parameters is None:<EOL><INDENT>params = OrderedDict()<EOL><DEDENT>else:<EOL><INDENT>if __validate_parameters__:<EOL><INDENT>params = OrderedDict()<EOL>top_kind = _POSITIONAL_ONLY<EOL>for idx, param in enumerate(parameters):<EOL><INDENT>kind = param.kind<EOL>if kind < top_kind:<EOL><INDENT>msg = '<STR_LIT>'<EOL>msg ... | Constructs Signature from the given list of Parameter
objects and 'return_annotation'. All arguments are optional. | f4101:c5:m0 |
@classmethod<EOL><INDENT>def from_function(cls, func):<DEDENT> | if not isinstance(func, types.FunctionType):<EOL><INDENT>raise TypeError('<STR_LIT>'.format(func))<EOL><DEDENT>Parameter = cls._parameter_cls<EOL>func_code = func.__code__<EOL>pos_count = func_code.co_argcount<EOL>arg_names = func_code.co_varnames<EOL>positional = tuple(arg_names[:pos_count])<EOL>keyword_only_count = g... | Constructs Signature for the given python function | f4101:c5:m1 |
def replace(self, parameters=_void, return_annotation=_void): | if parameters is _void:<EOL><INDENT>parameters = self.parameters.values()<EOL><DEDENT>if return_annotation is _void:<EOL><INDENT>return_annotation = self._return_annotation<EOL><DEDENT>return type(self)(parameters,<EOL>return_annotation=return_annotation)<EOL> | Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy. | f4101:c5:m4 |
def _bind(self, args, kwargs, partial=False): | arguments = OrderedDict()<EOL>parameters = iter(self.parameters.values())<EOL>parameters_ex = ()<EOL>arg_vals = iter(args)<EOL>if partial:<EOL><INDENT>for param_name, param in self.parameters.items():<EOL><INDENT>if (param._partial_kwarg and param_name not in kwargs):<EOL><INDENT>kwargs[param_name] = param.default<EOL>... | Private method. Don't use directly. | f4101:c5:m8 |
def bind(self, *args, **kwargs): | return self._bind(args, kwargs)<EOL> | Get a BoundArguments object, that maps the passed `args`
and `kwargs` to the function's signature. Raises `TypeError`
if the passed arguments can not be bound. | f4101:c5:m9 |
def bind_partial(self, *args, **kwargs): | return self._bind(args, kwargs, partial=True)<EOL> | Get a BoundArguments object, that partially maps the
passed `args` and `kwargs` to the function's signature.
Raises `TypeError` if the passed arguments can not be bound. | f4101:c5:m10 |
def _make_version(major, minor, micro, level, serial): | level_dict = {"<STR_LIT>": "<STR_LIT:a>", "<STR_LIT>": "<STR_LIT:b>", "<STR_LIT>": "<STR_LIT>", "<STR_LIT>": "<STR_LIT>"}<EOL>if level not in level_dict:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>version = "<STR_LIT>".format(major, minor)<EOL>if micro:<EOL><INDENT>version += "<STR_LIT>".format(micro)<EOL>... | Generate version string from tuple (almost entirely from coveragepy). | f4104:m0 |
def flatten_list(lobj): | ret = []<EOL>for item in lobj:<EOL><INDENT>if isinstance(item, list):<EOL><INDENT>for sub_item in flatten_list(item):<EOL><INDENT>ret.append(sub_item)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ret.append(item)<EOL><DEDENT><DEDENT>return ret<EOL> | Recursively flattens a list.
:param lobj: List to flatten
:type lobj: list
:rtype: list
For example:
>>> import pmisc
>>> pmisc.flatten_list([1, [2, 3, [4, 5, 6]], 7])
[1, 2, 3, 4, 5, 6, 7] | f4105:m0 |
def _isclose(obja, objb, rtol=<NUM_LIT>, atol=<NUM_LIT>): | return abs(obja - objb) <= (atol + rtol * abs(objb))<EOL> | Return floating point equality. | f4106:m0 |
def _isreal(obj): | <EOL>if (obj is None) or isinstance(obj, bool):<EOL><INDENT>return False<EOL><DEDENT>try:<EOL><INDENT>cond = (int(obj) == obj) or (float(obj) == obj)<EOL><DEDENT>except:<EOL><INDENT>return False<EOL><DEDENT>return cond<EOL> | Determine if an object is a real number.
Both Python standard data types and Numpy data types are supported.
:param obj: Object
:type obj: any
:rtype: boolean | f4106:m1 |
def _no_exp(number): | if isinstance(number, bool) or (not isinstance(number, (int, float))):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>mant, exp = _to_scientific_tuple(number)<EOL>if not exp:<EOL><INDENT>return str(number)<EOL><DEDENT>floating_mant = "<STR_LIT:.>" in mant<EOL>mant = mant.replace("<STR_LIT:.>", "<STR_LIT>")<EOL... | r"""
Convert a number to a string without using scientific notation.
:param number: Number to convert
:type number: integer or float
:rtype: string
:raises: RuntimeError (Argument \`number\` is not valid) | f4106:m2 |
def _to_scientific_tuple(number): | <EOL>if isinstance(number, bool) or (not isinstance(number, (int, float, str))):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>convert = not isinstance(number, str)<EOL>if (convert and (not number)) or (<EOL>(not convert) and (not number.strip("<STR_LIT:0>").strip("<STR_LIT:.>"))<EOL>):<EOL><INDENT>return ("<... | r"""
Return mantissa and exponent of a number expressed in scientific notation.
Full precision is maintained if the number is represented as a string.
:param number: Number
:type number: integer, float or string
:rtype: Tuple whose first item is the mantissa (*string*) and the second
... | f4106:m3 |
def gcd(vector): | <EOL>if not len(vector):<EOL><INDENT>return None<EOL><DEDENT>if len(vector) == <NUM_LIT:1>:<EOL><INDENT>return vector[<NUM_LIT:0>]<EOL><DEDENT>if len(vector) == <NUM_LIT:2>:<EOL><INDENT>return pgcd(vector[<NUM_LIT:0>], vector[<NUM_LIT:1>])<EOL><DEDENT>current_gcd = pgcd(vector[<NUM_LIT:0>], vector[<NUM_LIT:1>])<EOL>for... | Calculate the greatest common divisor (GCD) of a sequence of numbers.
The sequence can be a list of numbers or a Numpy vector of numbers. The
computations are carried out with a precision of 1E-12 if the objects are
not `fractions <https://docs.python.org/3/library/fractions.html>`_. When
possible it is best to use th... | f4106:m4 |
def normalize(value, series, offset=<NUM_LIT:0>): | if not _isreal(value):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if not _isreal(offset):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>smin = float(min(series))<EOL>smax = float(max(series))<EOL><DEDENT>except:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>value = floa... | r"""
Scale a value to the range defined by a series.
:param value: Value to normalize
:type value: number
:param series: List of numbers that defines the normalization range
:type series: list
:param offset: Normalization offset, i.e. the returned value will be in
the ran... | f4106:m5 |
def per(arga, argb, prec=<NUM_LIT:10>): | <EOL>if not isinstance(prec, int):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>a_type = <NUM_LIT:1> * _isreal(arga) + <NUM_LIT:2> * (isiterable(arga) and not isinstance(arga, str))<EOL>b_type = <NUM_LIT:1> * _isreal(argb) + <NUM_LIT:2> * (isiterable(argb) and not isinstance(argb, str))<EOL>if not a_type:<EO... | r"""
Calculate percentage difference between numbers.
If only two numbers are given, the percentage difference between them is
computed. If two sequences of numbers are given (either two lists of
numbers or Numpy vectors), the element-wise percentage difference is
computed. If any of the numbers in... | f4106:m6 |
def pgcd(numa, numb): | <EOL>int_args = (int(numa) == numa) and (int(numb) == numb)<EOL>fraction_args = isinstance(numa, Fraction) and isinstance(numb, Fraction)<EOL>if int_args:<EOL><INDENT>numa, numb = int(numa), int(numb)<EOL><DEDENT>elif not fraction_args:<EOL><INDENT>numa, numb = float(numa), float(numb)<EOL><DEDENT>if (not int_args) and... | Calculate the greatest common divisor (GCD) of two numbers.
:param numa: First number
:type numa: number
:param numb: Second number
:type numb: number
:rtype: number
For example:
>>> import pmisc, fractions
>>> pmisc.pgcd(10, 15)
5
>>> str(pmisc.pgcd(0.05, 0.02))
'0.01'
>>> str(pmisc.pgcd... | f4106:m7 |
def binary_string_to_octal_string(text): | <EOL>return "<STR_LIT>".join([_OCTAL_ALPHABET[ord(char)] for char in text])<EOL> | r"""
Return binary-packed octal string aliasing typical codes to their escape sequences.
:param text: Text to convert
:type text: string
:rtype: string
+------+-------+-----------------+
| Code | Alias | Description |
+======+=======+=================+
| 0 | \\0 | Null cha... | f4107:m0 |
def char_to_decimal(text): | return "<STR_LIT:U+0020>".join([str(ord(char)) for char in text])<EOL> | Convert a string to its decimal ASCII representation with spaces between characters.
:param text: Text to convert
:type text: string
:rtype: string
For example:
>>> import pmisc
>>> pmisc.char_to_decimal('Hello world!')
'72 101 108 108 111 32 119 111 114 108 100 33' | f4107:m1 |
def elapsed_time_string(start_time, stop_time): | if start_time > stop_time:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>delta_time = stop_time - start_time<EOL>tot_seconds = int(<EOL>(<EOL>delta_time.microseconds<EOL>+ (delta_time.seconds + delta_time.days * <NUM_LIT> * <NUM_LIT>) * <NUM_LIT:10> ** <NUM_LIT:6><EOL>)<EOL>/ <NUM_LIT:10> ** <NUM_LIT:6><EOL>)... | r"""
Return a formatted string with the elapsed time between two time points.
The string includes years (365 days), months (30 days), days (24 hours),
hours (60 minutes), minutes (60 seconds) and seconds. If both arguments
are equal, the string returned is :code:`'None'`; otherwise, the string
retu... | f4107:m2 |
def pcolor(text, color, indent=<NUM_LIT:0>): | esc_dict = {<EOL>"<STR_LIT>": <NUM_LIT:30>,<EOL>"<STR_LIT>": <NUM_LIT>,<EOL>"<STR_LIT>": <NUM_LIT:32>,<EOL>"<STR_LIT>": <NUM_LIT>,<EOL>"<STR_LIT>": <NUM_LIT>,<EOL>"<STR_LIT>": <NUM_LIT>,<EOL>"<STR_LIT>": <NUM_LIT>,<EOL>"<STR_LIT>": <NUM_LIT>,<EOL>"<STR_LIT:none>": -<NUM_LIT:1>,<EOL>}<EOL>if not isinstance(text, str):<E... | r"""
Return a string that once printed is colorized.
:param text: Text to colorize
:type text: string
:param color: Color to use, one of :code:`'black'`, :code:`'red'`,
:code:`'green'`, :code:`'yellow'`, :code:`'blue'`,
:code:`'magenta'`, :code:`'cyan'`, :code:`... | f4107:m3 |
def quote_str(obj): | if not isinstance(obj, str):<EOL><INDENT>return obj<EOL><DEDENT>return "<STR_LIT>".format(obj=obj) if '<STR_LIT:">' in obj else '<STR_LIT>'.format(obj=obj)<EOL> | r"""
Add extra quotes to a string.
If the argument is not a string it is returned unmodified.
:param obj: Object
:type obj: any
:rtype: Same as argument
For example:
>>> import pmisc
>>> pmisc.quote_str(5)
5
>>> pmisc.quote_str('Hello!')
'"Hello!"'
... | f4107:m4 |
def strframe(obj, extended=False): | <EOL>fname = normalize_windows_fname(obj[<NUM_LIT:1>])<EOL>ret = list()<EOL>ret.append(pcolor("<STR_LIT>".format(hex(id(obj[<NUM_LIT:0>]))), "<STR_LIT>"))<EOL>ret.append("<STR_LIT>".format(fname))<EOL>ret.append("<STR_LIT>".format(obj[<NUM_LIT:2>]))<EOL>ret.append("<STR_LIT>".format(obj[<NUM_LIT:3>]))<EOL>ret.append("<... | Return a string with a frame record pretty-formatted.
The record is typically an item in a list generated by `inspect.stack()
<https://docs.python.org/3/library/inspect.html#inspect.stack>`_).
:param obj: Frame record
:type obj: tuple
:param extended: Flag that indicates whether contents of the frame object
... | f4107:m5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.