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:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return name<EOL>
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 node.args + node.kwonlyargs)<EOL>if node.vararg:<EOL><INDENT>targets.add(node.vararg.id)<EOL><DEDENT>if node.kwarg:<EOL><INDENT>targets.add(node.kwarg.id)<EOL><DEDENT>return targets<EOL><DEDENT>else:<EOL><INDENT>return set()<EOL><DEDENT>
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 return `i`, etc. Args: node: An AST node Returns: A set of variable names (strings) of all the variables created or mutated.
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 given node is not a statement.
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: ValueError: If the given node is not a statement.
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: ValueError: If the given node is not a statement.
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>elif node:<EOL><INDENT>self.to_insert[-<NUM_LIT:1>].extend(node)<EOL><DEDENT>self.visit_statements(self.to_append.pop())<EOL><DEDENT>else:<EOL><INDENT>self.to_insert[-<NUM_LIT:1>].append(node)<EOL><DEDENT><DEDENT>return self.to_insert[-<NUM_LIT:1>]<EOL>
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: nodes: A list of statements. Returns: A list of transformed statements.
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.Module([node])<EOL>anno.clearanno(node)<EOL>return node, fad.required<EOL>
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 argument indices with respect to which we take the derivative. preserve_result: A boolean indicating whether the original non-differentiated function value should be returned check_dims: A boolean indicating whether the provided derivatives should have the same shape as their corresponding arguments. Returns: mod: A `Module` node containing the naive primal and adjoint of the function which can be fed to the `split` and `joint` functions. required: A list of tuples of functions and argument indices. These functions were called by the function but did not have an adjoint.
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=template.Replace.TANGENT,<EOL>namer=self.namer,<EOL>temp=self.tmp_node,<EOL>tangent=tangent_node,<EOL>target=self.target,<EOL>value=self.value)<EOL>self.reset_tmp_node()<EOL><DEDENT>else:<EOL><INDENT>def template_(z, f):<EOL><INDENT>tmp = f<EOL>d[z] = tmp[<NUM_LIT:0>]<EOL>z = tmp[<NUM_LIT:1>]<EOL><DEDENT>new_node = template.replace(<EOL>template_,<EOL>replace_grad=template.Replace.TANGENT,<EOL>namer=self.namer,<EOL>z=self.target,<EOL>f=tangent_node[<NUM_LIT:0>])<EOL><DEDENT>self.target = None<EOL>for i in range(len(new_node)):<EOL><INDENT>new_node[i] = comments.add_comment(new_node[i], '<STR_LIT>'<EOL>'<STR_LIT:%s>' % quoting.unquote(node))<EOL><DEDENT>return new_node<EOL>
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_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
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 implemented derivatives. A function should be checkable for membership using the `fn in implemented` syntax. Returns: module_fns: A set of functions, builtins or ufuncs in `modules`.
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 trying to resolve won't be resolved, since they are not in the local namespace of the outer function. The function definition itself is also annotated, so that it can be matched to calls to it in other functions. Args: func: The function whose calls are being resolved. Returns: node: An AST where each `Call` node has a `func` annotation with the function handle that the call resolves to. Raises: AttributeError: When a function is used on the RHS of an assignment cannot be resolved (because it was passed as an argument or was defined in the body of the function).
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 derivatives of code generated in split-motion. Returns: node: The node passed in, but with pushes and pops annotated in AST nodes.
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 all the nodes, this attribute contanis a set of definitions in the form of `(variable_name, node)` pairs which are unused in this AST.
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 containing statement will be commented. text: A comment string. location: Where the comment should appear. Valid values are 'above', 'below' and 'right' Returns: The node with the comment stored as an annotation.
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 = comment<EOL><DEDENT><DEDENT>return node<EOL>
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: An AST Returns: An AST where comments are not repeated in sequence.
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 = '<STR_LIT>' % uuid<EOL>if six.PY3:<EOL><INDENT>spec = util.spec_from_file_location(module_name, tmpname)<EOL>m = util.module_from_spec(spec)<EOL>spec.loader.exec_module(m)<EOL><DEDENT>else:<EOL><INDENT>m = imp.load_source(module_name, tmpname)<EOL><DEDENT>if globals_:<EOL><INDENT>m.__dict__.update(globals_)<EOL><DEDENT>return m<EOL>
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 in the compiled module. They will be monkey patched after importing the module. Returns: A module object containing the compiled source code.
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>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>elif isinstance(node, gast.FunctionDef):<EOL><INDENT>name = node.name<EOL><DEDENT>else:<EOL><INDENT>raise TypeError<EOL><DEDENT>module = compile_file(node, globals_)<EOL>return getattr(module, name)<EOL>
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. If a module contains multiple functions, a handle to the first one will be returned. globals_: See `compile_file` Returns: A handle to the compiled function. Raises: TypeError: If the input is not a string or AST. ValueError: If no function can be found.
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 lines of generated source code changed after the latest pass. Args: node: The AST to optimize. Returns: The optimized AST.
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>'))<EOL><DEDENT><DEDENT><DEDENT>transformers.Remove(to_remove).visit(node)<EOL>anno.clearanno(node)<EOL>return node<EOL>
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 statements; if a pop statement is removed, it will also try to remove the accompanying push statement. Note that this *requires dead code elimination to be performed on the primal and adjoint simultaneously*. Args: node: The AST to optimize. Returns: The optimized AST.
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_[<NUM_LIT:1>] for def_ in anno.getanno(succ, '<STR_LIT>')<EOL>if def_[<NUM_LIT:0>] == rhs_name]<EOL>if (len(rhs_defs) == <NUM_LIT:1> and isinstance(rhs_defs[<NUM_LIT:0>], gast.Assign) and<EOL>n_reads[rhs_defs[<NUM_LIT:0>]] == <NUM_LIT:1> and<EOL>isinstance(rhs_defs[<NUM_LIT:0>].value, gast.Name) and<EOL>isinstance(rhs_defs[<NUM_LIT:0>].targets[<NUM_LIT:0>], gast.Name)):<EOL><INDENT>to_remove.append(rhs_defs[<NUM_LIT:0>])<EOL>succ.value = rhs_defs[<NUM_LIT:0>].value<EOL><DEDENT><DEDENT><DEDENT>transformers.Remove(to_remove).visit(node)<EOL>anno.clearanno(node)<EOL>return node<EOL>
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 optimized AST.
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 optimized AST.
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.vararg = None<EOL><DEDENT>if set(replacements.keys()) != placeholders:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>elif isinstance(template, gast.AST):<EOL><INDENT>tree = template<EOL><DEDENT>else:<EOL><INDENT>tree = quoting.quote(template, return_expr=True)<EOL><DEDENT>for k, v in replacements.items():<EOL><INDENT>if isinstance(v, six.string_types):<EOL><INDENT>replacements[k] = quoting.quote(v)<EOL><DEDENT><DEDENT>ReplaceTransformer(replacements).visit(tree)<EOL>if replace_grad is not Replace.NONE:<EOL><INDENT>rgt = ReplaceGradTransformer(<EOL>replace_grad=replace_grad,<EOL>namer=namer,<EOL>tangent=replace_grad is Replace.TANGENT)<EOL>rgt.visit(tree)<EOL><DEDENT>if is_function:<EOL><INDENT>return tree.body<EOL><DEDENT>else:<EOL><INDENT>return tree<EOL><DEDENT>
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, and any variable it references is a placeholder. replace_grad: If Replace.NONE, statements of the form `d[x]` are ignored. For the other possible values, see `ReplaceGradTransformer`. namer: See `ReplaceGradTransformer`. **replacements: A mapping from placeholder names to (lists of) AST nodes that these placeholders will be replaced by. If a string is passed, `quote` will be called on it to turn it into a node. Returns: body: An AST node or list of AST nodes with the replacements made. If the template was a function, a list will be returned. If the template was a node, the same node will be returned. If the template was a string, an AST node will be returned (a `Module` node in the case of a multi-line string, an `Expr` node otherwise). Raises: ValueError: If a function is used as a template and an incorrect set of replacements was passed.
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 binary function that takes a first argument of type t, and a second argument that t needs to be unbroadcast to.
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 distributed evenly into the original shape.
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 the shape of the original array.
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 shape of the original array.
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 broadcast to match the shape of the original array.
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 `t`.
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 the same signature as e.g. `unreduce_array`
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 unary function that takes an argument of type t and returns a zero object of the same size as the argument. For example, the gradient initializer for Numpy objects is zeros_like.
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><INDENT>return obj.instantiate()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if allow_lazy_initializer:<EOL><INDENT>return ZeroGradient(obj)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>assert not isinstance(obj, ZeroGradient)<EOL><DEDENT>return initializer(obj)<EOL>
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, shape, etc. but with all numeric values set to zero. If the type is unknown, a zero is returned.
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 type of the left operand supported by the adder. right_type: A Python type object. The data type of the right operand supported by the adder. add_grad_function: A binary function that takes two arguments, left and right, of the types left_type and right_type respectively, and returns their sum. For example, the gradient adder for Numpy objects is np.add. Raises: ValueError: If the given type pair was already registered.
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. arg_types: List of Python type objects. The gradient adder will be registered for all pairs of these types. exclude: Optional list of type tuples to exclude. ignore_existing: Boolean. Whether to silently skip argument pairs that were already registered.
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 supported by the adder. right_type: A Python type object. The data type of the right operand supported by the adder. shape_checker_function: A binary function that takes two arguments, left and right, of the types left_type and right_type respectively, and returns a boolean indicating whether or not they match. Raises: ValueError: If the given type pair was already registered.
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_checker. arg_types: List of Python type objects. The shape checker will be registered for all pairs of these types. exclude: Optional list of type tuples to exclude. ignore_existing: Boolean. Whether to silently skip argument pairs that were already registered.
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><DEDENT>match = True<EOL>for (ak, av), (bk, bv) in zip(a.items(), b.items()):<EOL><INDENT>match = match and all([ak == bk and shapes_match(av, bv)])<EOL><DEDENT>return match<EOL><DEDENT>else:<EOL><INDENT>shape_checker = shape_checkers[(type(a), type(b))]<EOL>return shape_checker(a, b)<EOL><DEDENT>
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 indicating whether the shapes of `a` and `b` match.
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 also passed into the corresponding pop. Allows optimization passes to track pairs of pushes and pops.
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 pairs of pushes and pops. Returns: The last value.
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 that is also passed into the corresponding pop. Allows optimization passes to track pairs of pushes and pops. Raises: ValueError: If a non-stack value for `substack` is passed.
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 automatic differentiation, and shouldn't actually ever be called. If the user wants to use a function containing this context manager without taking the derivative, the `tangent` decorator should be used to remove it from the code. Args: var: The variable of which we want the gradient. Returns: The gradient of this value. Raises: ValueError: If this context manager isn't removed using the `tangent` decorator and the code is actually run.
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(numpy.arange(numpy.ndim(x2) - <NUM_LIT:2>)))))<EOL>dy_x2 = numpy.sum(dy, axis=tuple(-numpy.arange(numpy.ndim(x2) - <NUM_LIT:2>) - <NUM_LIT:2>))<EOL>return numpy.reshape(numpy.dot(dy_x2, x2_t), numpy.shape(x1))<EOL>
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 involved.
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)<EOL>return sig.replace(<EOL>parameters=(first,) + tuple(sig.parameters.values())[<NUM_LIT:1>:])<EOL><DEDENT>else:<EOL><INDENT>return sig<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return sig.replace(parameters=tuple(sig.parameters.values())[<NUM_LIT:1>:])<EOL><DEDENT><DEDENT>try:<EOL><INDENT>sig = obj.__signature__<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>if sig is not None:<EOL><INDENT>return sig<EOL><DEDENT><DEDENT>try:<EOL><INDENT>wrapped = obj.__wrapped__<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return signature(wrapped)<EOL><DEDENT>if isinstance(obj, types.FunctionType):<EOL><INDENT>return Signature.from_function(obj)<EOL><DEDENT>if isinstance(obj, functools.partial):<EOL><INDENT>sig = signature(obj.func)<EOL>new_params = OrderedDict(sig.parameters.items())<EOL>partial_args = obj.args or ()<EOL>partial_keywords = obj.keywords or {}<EOL>try:<EOL><INDENT>ba = sig.bind_partial(*partial_args, **partial_keywords)<EOL><DEDENT>except TypeError as ex:<EOL><INDENT>msg = '<STR_LIT>'.format(obj)<EOL>raise ValueError(msg)<EOL><DEDENT>for arg_name, arg_value in ba.arguments.items():<EOL><INDENT>param = new_params[arg_name]<EOL>if arg_name in partial_keywords:<EOL><INDENT>new_params[arg_name] = param.replace(default=arg_value,<EOL>_partial_kwarg=True)<EOL><DEDENT>elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and<EOL>not param._partial_kwarg):<EOL><INDENT>new_params.pop(arg_name)<EOL><DEDENT><DEDENT>return sig.replace(parameters=new_params.values())<EOL><DEDENT>sig = None<EOL>if isinstance(obj, type):<EOL><INDENT>call = _get_user_defined_method(type(obj), '<STR_LIT>')<EOL>if call is not None:<EOL><INDENT>sig = signature(call)<EOL><DEDENT>else:<EOL><INDENT>new = _get_user_defined_method(obj, '<STR_LIT>')<EOL>if new is not None:<EOL><INDENT>sig = signature(new)<EOL><DEDENT>else:<EOL><INDENT>init = _get_user_defined_method(obj, '<STR_LIT>')<EOL>if init is not None:<EOL><INDENT>sig = signature(init)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif not isinstance(obj, _NonUserDefinedCallables):<EOL><INDENT>call = _get_user_defined_method(type(obj), '<STR_LIT>', '<STR_LIT>')<EOL>if call is not None:<EOL><INDENT>sig = signature(call)<EOL><DEDENT><DEDENT>if sig is not None:<EOL><INDENT>return sig.replace(parameters=tuple(sig.parameters.values())[<NUM_LIT:1>:])<EOL><DEDENT>if isinstance(obj, types.BuiltinFunctionType):<EOL><INDENT>msg = '<STR_LIT>'.format(obj)<EOL>raise ValueError(msg)<EOL><DEDENT>raise ValueError(<EOL>'<STR_LIT>'.format(obj))<EOL>
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_kwarg = self._partial_kwarg<EOL><DEDENT>return type(self)(name, kind, default=default, annotation=annotation,<EOL>_partial_kwarg=_partial_kwarg)<EOL>
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 = msg.format(top_kind, param.kind)<EOL>raise ValueError(msg)<EOL><DEDENT>else:<EOL><INDENT>top_kind = kind<EOL><DEDENT>name = param.name<EOL>if name is None:<EOL><INDENT>name = str(idx)<EOL>param = param.replace(name=name)<EOL><DEDENT>if name in params:<EOL><INDENT>msg = '<STR_LIT>'.format(name)<EOL>raise ValueError(msg)<EOL><DEDENT>params[name] = param<EOL><DEDENT><DEDENT>else:<EOL><INDENT>params = OrderedDict(((param.name, param)<EOL>for param in parameters))<EOL><DEDENT><DEDENT>self._parameters = params<EOL>self._return_annotation = return_annotation<EOL>
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 = getattr(func_code, '<STR_LIT>', <NUM_LIT:0>)<EOL>keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]<EOL>annotations = getattr(func, '<STR_LIT>', {})<EOL>defaults = func.__defaults__<EOL>kwdefaults = getattr(func, '<STR_LIT>', None)<EOL>if defaults:<EOL><INDENT>pos_default_count = len(defaults)<EOL><DEDENT>else:<EOL><INDENT>pos_default_count = <NUM_LIT:0><EOL><DEDENT>parameters = []<EOL>non_default_count = pos_count - pos_default_count<EOL>for name in positional[:non_default_count]:<EOL><INDENT>annotation = annotations.get(name, _empty)<EOL>parameters.append(Parameter(name, annotation=annotation,<EOL>kind=_POSITIONAL_OR_KEYWORD))<EOL><DEDENT>for offset, name in enumerate(positional[non_default_count:]):<EOL><INDENT>annotation = annotations.get(name, _empty)<EOL>parameters.append(Parameter(name, annotation=annotation,<EOL>kind=_POSITIONAL_OR_KEYWORD,<EOL>default=defaults[offset]))<EOL><DEDENT>if func_code.co_flags & <NUM_LIT>:<EOL><INDENT>name = arg_names[pos_count + keyword_only_count]<EOL>annotation = annotations.get(name, _empty)<EOL>parameters.append(Parameter(name, annotation=annotation,<EOL>kind=_VAR_POSITIONAL))<EOL><DEDENT>for name in keyword_only:<EOL><INDENT>default = _empty<EOL>if kwdefaults is not None:<EOL><INDENT>default = kwdefaults.get(name, _empty)<EOL><DEDENT>annotation = annotations.get(name, _empty)<EOL>parameters.append(Parameter(name, annotation=annotation,<EOL>kind=_KEYWORD_ONLY,<EOL>default=default))<EOL><DEDENT>if func_code.co_flags & <NUM_LIT>:<EOL><INDENT>index = pos_count + keyword_only_count<EOL>if func_code.co_flags & <NUM_LIT>:<EOL><INDENT>index += <NUM_LIT:1><EOL><DEDENT>name = arg_names[index]<EOL>annotation = annotations.get(name, _empty)<EOL>parameters.append(Parameter(name, annotation=annotation,<EOL>kind=_VAR_KEYWORD))<EOL><DEDENT>return cls(parameters,<EOL>return_annotation=annotations.get('<STR_LIT>', _empty),<EOL>__validate_parameters__=False)<EOL>
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><DEDENT><DEDENT><DEDENT>while True:<EOL><INDENT>try:<EOL><INDENT>arg_val = next(arg_vals)<EOL><DEDENT>except StopIteration:<EOL><INDENT>try:<EOL><INDENT>param = next(parameters)<EOL><DEDENT>except StopIteration:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>if param.kind == _VAR_POSITIONAL:<EOL><INDENT>break<EOL><DEDENT>elif param.name in kwargs:<EOL><INDENT>if param.kind == _POSITIONAL_ONLY:<EOL><INDENT>msg = '<STR_LIT>''<STR_LIT>'<EOL>msg = msg.format(arg=param.name)<EOL>raise TypeError(msg)<EOL><DEDENT>parameters_ex = (param,)<EOL>break<EOL><DEDENT>elif (param.kind == _VAR_KEYWORD or<EOL>param.default is not _empty):<EOL><INDENT>parameters_ex = (param,)<EOL>break<EOL><DEDENT>else:<EOL><INDENT>if partial:<EOL><INDENT>parameters_ex = (param,)<EOL>break<EOL><DEDENT>else:<EOL><INDENT>msg = '<STR_LIT>'<EOL>msg = msg.format(arg=param.name)<EOL>raise TypeError(msg)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>param = next(parameters)<EOL><DEDENT>except StopIteration:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if param.kind == _VAR_POSITIONAL:<EOL><INDENT>values = [arg_val]<EOL>values.extend(arg_vals)<EOL>arguments[param.name] = tuple(values)<EOL>break<EOL><DEDENT>if param.name in kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>'.format(arg=param.name))<EOL><DEDENT>arguments[param.name] = arg_val<EOL><DEDENT><DEDENT><DEDENT>kwargs_param = None<EOL>for param in itertools.chain(parameters_ex, parameters):<EOL><INDENT>if param.kind == _POSITIONAL_ONLY:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>'.<EOL>format(arg=param.name))<EOL><DEDENT>if param.kind == _VAR_KEYWORD:<EOL><INDENT>kwargs_param = param<EOL>continue<EOL><DEDENT>param_name = param.name<EOL>try:<EOL><INDENT>arg_val = kwargs.pop(param_name)<EOL><DEDENT>except KeyError:<EOL><INDENT>if (not partial and param.kind != _VAR_POSITIONAL and<EOL>param.default is _empty):<EOL><INDENT>raise TypeError('<STR_LIT>'.<EOL>format(arg=param_name))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>arguments[param_name] = arg_val<EOL><DEDENT><DEDENT>if kwargs:<EOL><INDENT>if kwargs_param is not None:<EOL><INDENT>arguments[kwargs_param.name] = kwargs<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT>return self._bound_arguments_cls(self, arguments)<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><DEDENT>if level != "<STR_LIT>":<EOL><INDENT>version += "<STR_LIT>".format(level_dict[level], serial)<EOL><DEDENT>return version<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>if exp < <NUM_LIT:0>:<EOL><INDENT>return "<STR_LIT>" + "<STR_LIT:0>" * (-exp - <NUM_LIT:1>) + mant<EOL><DEDENT>if not floating_mant:<EOL><INDENT>return mant + "<STR_LIT:0>" * exp + ("<STR_LIT>" if isinstance(number, float) else "<STR_LIT>")<EOL><DEDENT>lfpart = len(mant) - <NUM_LIT:1><EOL>if lfpart < exp:<EOL><INDENT>return (mant + "<STR_LIT:0>" * (exp - lfpart)).rstrip("<STR_LIT:.>")<EOL><DEDENT>return mant<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 ("<STR_LIT:0>", <NUM_LIT:0>)<EOL><DEDENT>sign, digits, exp = Decimal(str(number) if convert else number).as_tuple()<EOL>mant = (<EOL>"<STR_LIT>".format(<EOL>sign="<STR_LIT:->" if sign else "<STR_LIT>",<EOL>itg=digits[<NUM_LIT:0>],<EOL>frac="<STR_LIT>".join(str(item) for item in digits[<NUM_LIT:1>:]),<EOL>)<EOL>.rstrip("<STR_LIT:0>")<EOL>.rstrip("<STR_LIT:.>")<EOL>)<EOL>exp += len(digits) - <NUM_LIT:1><EOL>return (mant, exp)<EOL>
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 item is the exponent (*integer*) of the number when expressed in scientific notation :raises: RuntimeError (Argument \`number\` is not valid)
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 element in vector[<NUM_LIT:2>:]:<EOL><INDENT>current_gcd = pgcd(current_gcd, element)<EOL><DEDENT>return current_gcd<EOL>
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 the `fractions <https://docs.python.org/3/library/fractions.html>`_ data type with the numerator and denominator arguments when computing the GCD of floating point numbers. :param vector: Vector of numbers :type vector: list of numbers or Numpy vector of numbers
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 = float(value)<EOL>offset = float(offset)<EOL>if not <NUM_LIT:0> <= offset <= <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not smin <= value <= smax:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>return offset + ((<NUM_LIT:1.0> - offset) * (value - smin) / (smax - smin))<EOL>
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 range [**offset**, 1.0] :type offset: number :rtype: number :raises: * RuntimeError (Argument \`offset\` is not valid) * RuntimeError (Argument \`series\` is not valid) * RuntimeError (Argument \`value\` is not valid) * ValueError (Argument \`offset\` has to be in the [0.0, 1.0] range) * ValueError (Argument \`value\` has to be within the bounds of the argument \`series\`) For example:: >>> import pmisc >>> pmisc.normalize(15, [10, 20]) 0.5 >>> pmisc.normalize(15, [10, 20], 0.5) 0.75
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:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if not b_type:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if a_type != b_type:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if a_type == <NUM_LIT:1>:<EOL><INDENT>arga, argb = float(arga), float(argb)<EOL>num_min, num_max = min(arga, argb), max(arga, argb)<EOL>return (<EOL><NUM_LIT:0><EOL>if _isclose(arga, argb)<EOL>else (<EOL>sys.float_info.max<EOL>if _isclose(num_min, <NUM_LIT:0.0>)<EOL>else round((num_max / num_min) - <NUM_LIT:1>, prec)<EOL>)<EOL>)<EOL><DEDENT>ret = copy.copy(arga)<EOL>for num, (x, y) in enumerate(zip(arga, argb)):<EOL><INDENT>if not _isreal(x):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if not _isreal(y):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>x, y = float(x), float(y)<EOL>ret[num] = (<EOL><NUM_LIT:0><EOL>if _isclose(x, y)<EOL>else (<EOL>sys.float_info.max<EOL>if _isclose(x, <NUM_LIT:0.0>) or _isclose(y, <NUM_LIT:0>)<EOL>else (round((max(x, y) / min(x, y)) - <NUM_LIT:1>, prec))<EOL>)<EOL>)<EOL><DEDENT>return ret<EOL>
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 the arguments is zero the value returned is the maximum floating-point number supported by the Python interpreter. :param arga: First number, list of numbers or Numpy vector :type arga: float, integer, list of floats or integers, or Numpy vector of floats or integers :param argb: Second number, list of numbers or or Numpy vector :type argb: float, integer, list of floats or integers, or Numpy vector of floats or integers :param prec: Maximum length of the fractional part of the result :type prec: integer :rtype: Float, list of floats or Numpy vector, depending on the arguments type :raises: * RuntimeError (Argument \`arga\` is not valid) * RuntimeError (Argument \`argb\` is not valid) * RuntimeError (Argument \`prec\` is not valid) * TypeError (Arguments are not of the same type)
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 (not fraction_args):<EOL><INDENT>numa, numb = (<EOL>Fraction(_no_exp(numa)).limit_denominator(),<EOL>Fraction(_no_exp(numb)).limit_denominator(),<EOL>)<EOL><DEDENT>while numb:<EOL><INDENT>numa, numb = (<EOL>numb,<EOL>(numa % numb if int_args else (numa % numb).limit_denominator()),<EOL>)<EOL><DEDENT>return int(numa) if int_args else (numa if fraction_args else float(numa))<EOL>
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(5/3.0, 2/3.0))[:6] '0.3333' >>> pmisc.pgcd( ... fractions.Fraction(str(5/3.0)), ... fractions.Fraction(str(2/3.0)) ... ) Fraction(1, 3) >>> pmisc.pgcd( ... fractions.Fraction(5, 3), ... fractions.Fraction(2, 3) ... ) Fraction(1, 3)
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 character | +------+-------+-----------------+ | 7 | \\a | Bell / alarm | +------+-------+-----------------+ | 8 | \\b | Backspace | +------+-------+-----------------+ | 9 | \\t | Horizontal tab | +------+-------+-----------------+ | 10 | \\n | Line feed | +------+-------+-----------------+ | 11 | \\v | Vertical tab | +------+-------+-----------------+ | 12 | \\f | Form feed | +------+-------+-----------------+ | 13 | \\r | Carriage return | +------+-------+-----------------+ For example: >>> import pmisc, struct, sys >>> def py23struct(num): ... if sys.hexversion < 0x03000000: ... return struct.pack('h', num) ... else: ... return struct.pack('h', num).decode('ascii') >>> nums = range(1, 15) >>> pmisc.binary_string_to_octal_string( ... ''.join([py23struct(num) for num in nums]) ... ).replace('o', '') #doctest: +ELLIPSIS '\\1\\0\\2\\0\\3\\0\\4\\0\\5\\0\\6\\0\\a\\0\\b\\0\\t\\0\\...
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>)<EOL>years, remainder = divmod(tot_seconds, <NUM_LIT> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT>)<EOL>months, remainder = divmod(remainder, <NUM_LIT:30> * <NUM_LIT> * <NUM_LIT> * <NUM_LIT>)<EOL>days, remainder = divmod(remainder, <NUM_LIT> * <NUM_LIT> * <NUM_LIT>)<EOL>hours, remainder = divmod(remainder, <NUM_LIT> * <NUM_LIT>)<EOL>minutes, seconds = divmod(remainder, <NUM_LIT>)<EOL>token_iter = zip(<EOL>[years, months, days, hours, minutes, seconds],<EOL>["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>)<EOL>ret_list = [<EOL>"<STR_LIT>".format(<EOL>token=num, token_name=desc, plural="<STR_LIT:s>" if num > <NUM_LIT:1> else "<STR_LIT>"<EOL>)<EOL>for num, desc in token_iter<EOL>if num > <NUM_LIT:0><EOL>]<EOL>if not ret_list:<EOL><INDENT>return "<STR_LIT:None>"<EOL><DEDENT>if len(ret_list) == <NUM_LIT:1>:<EOL><INDENT>return ret_list[<NUM_LIT:0>]<EOL><DEDENT>if len(ret_list) == <NUM_LIT:2>:<EOL><INDENT>return ret_list[<NUM_LIT:0>] + "<STR_LIT>" + ret_list[<NUM_LIT:1>]<EOL><DEDENT>return ("<STR_LIT:U+002CU+0020>".join(ret_list[<NUM_LIT:0>:-<NUM_LIT:1>])) + "<STR_LIT>" + ret_list[-<NUM_LIT:1>]<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 returned is [YY year[s], [MM month[s], [DD day[s], [HH hour[s], [MM minute[s] [and SS second[s\]\]\]\]\]\]. Any part (year[s], month[s], etc.) is omitted if the value of that part is null/zero :param start_time: Starting time point :type start_time: `datetime <https://docs.python.org/3/library/ datetime.html#datetime-objects>`_ :param stop_time: Ending time point :type stop_time: `datetime` :rtype: string :raises: RuntimeError (Invalid time delta specification) For example: >>> import datetime, pmisc >>> start_time = datetime.datetime(2014, 1, 1, 1, 10, 1) >>> stop_time = datetime.datetime(2015, 1, 3, 1, 10, 3) >>> pmisc.elapsed_time_string(start_time, stop_time) '1 year, 2 days and 2 seconds'
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):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if not isinstance(color, str):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>if not isinstance(indent, int):<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>color = color.lower()<EOL>if color not in esc_dict:<EOL><INDENT>raise ValueError("<STR_LIT>".format(color=color))<EOL><DEDENT>if esc_dict[color] != -<NUM_LIT:1>:<EOL><INDENT>return "<STR_LIT>".format(<EOL>color_code=esc_dict[color], indent="<STR_LIT:U+0020>" * indent, text=text<EOL>)<EOL><DEDENT>return "<STR_LIT>".format(indent="<STR_LIT:U+0020>" * indent, text=text)<EOL>
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:`'white'` or :code:`'none'` (case insensitive) :type color: string :param indent: Number of spaces to prefix the output with :type indent: integer :rtype: string :raises: * RuntimeError (Argument \`color\` is not valid) * RuntimeError (Argument \`indent\` is not valid) * RuntimeError (Argument \`text\` is not valid) * ValueError (Unknown color *[color]*)
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!"' >>> pmisc.quote_str('He said "hello!"') '\'He said "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("<STR_LIT>".format(obj[<NUM_LIT:4>]))<EOL>ret.append("<STR_LIT>".format(obj[<NUM_LIT:5>]))<EOL>if extended:<EOL><INDENT>ret.append("<STR_LIT>".format(hex(id(obj[<NUM_LIT:0>].f_back))))<EOL>ret.append("<STR_LIT>".format(obj[<NUM_LIT:0>].f_builtins))<EOL>ret.append("<STR_LIT>".format(obj[<NUM_LIT:0>].f_code))<EOL>ret.append("<STR_LIT>".format(obj[<NUM_LIT:0>].f_globals))<EOL>ret.append("<STR_LIT>".format(obj[<NUM_LIT:0>].f_lasti))<EOL>ret.append("<STR_LIT>".format(obj[<NUM_LIT:0>].f_lineno))<EOL>ret.append("<STR_LIT>".format(obj[<NUM_LIT:0>].f_locals))<EOL>if hasattr(obj[<NUM_LIT:0>], "<STR_LIT>"): <EOL><INDENT>ret.append("<STR_LIT>".format(obj[<NUM_LIT:0>].f_restricted))<EOL><DEDENT>ret.append("<STR_LIT>".format(obj[<NUM_LIT:0>].f_trace))<EOL><DEDENT>return "<STR_LIT:\n>".join(ret)<EOL>
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 are printed (True) or not (False) :type extended: boolean :rtype: string
f4107:m5