code
stringlengths
1
18.2k
def _get_a_code_object_from( thing ) : ''' Given a thing that might be a property, a class method, a function or a code object, reduce it to code object. If we cannot, return the thing itself. ''' # If we were passed a Method wrapper, get its function if isinstance( thing, types.MethodType ) : thing = thing.__func__ # ...
def printcodelist(thing, to=sys.stdout, heading=None): ''' Write the lines of the codelist string list to the given file, or to the default output. A little Python 3 problem: if the to-file is in binary mode, we need to encode the strings, else a TypeError will be raised. Obvious answer, test for 'b' in to.mode? Nope, ...
# If we were passed a list, assume that it is a CodeList or # a manually-assembled list of code tuples. if not isinstance( thing, list ) : # Passed something else. Reduce it to a CodeList. if isinstance( thing, Code ): thing = thing.code else : # Convert various sources to a code object. thing = _get_a_code_object_from...
heading = heading.encode( 'UTF-8' ) # send it on its way if heading : to.write( '===' + heading + '===\n' ) to.write( whole_thang )
def _findlinestarts(code_object): """ Find the offsets in a byte code which are the start of source lines. Generate pairs (offset, lineno) as described in Python/compile.c. This is a modified version of dis.findlinestarts. This version allows multiple "line starts" with the same line number. (The dis version conditions...
increment on the previous line's number to the next line's number. Thus co_firstlineno+co_lnotab[1] is the first effective line's number, and co_lnotab[0] is the number of bytes it generated. Note that an effective line number generates code by definition, hence the even byte cannot be zero; and as line numbers are mon...
line numbers? It is not unheard of to find blocks of comments larger than 255 lines (like this one?). Then compile.c generates pairs of (0, 255) until it has accounted for the line number difference and a final pair of (offset,lineincr%256). Uh, but...? Yes, what now, annoying reader? Well, does the following code hand...
(0,255) entries correctly. """ # grab the even bytes as integer byte_increments: byte_increments = [c for c in code_object.co_lnotab[0::2]] # grab the odd bytes as integer line_increments: line_increments = [c for c in code_object.co_lnotab[1::2]] lineno = code_object.co_firstlineno addr = 0 for byte_incr, line_incr in...
def from_code(cls, code_object): """ Disassemble a Python code object and make a Code object from the bits. This is the expected way to make a Code instance. But you are welcome to call Code() directly if you wish. """ # It's an annoyance to keep having to add ".__code__" to a function # name, so let's automate that wh...
findlabels(co_code)) # Make a dict{ source_line : offset } for the source lines in the code. linestarts = dict(cls._findlinestarts(code_object)) cellfree = code_object.co_cellvars + code_object.co_freevars # Create a CodeList object to represent the bytecode string. code = CodeList() # receives (op,arg) tuples n = len(...
(SetLineno, line#) ahead of it. if i in linestarts: code.append((SetLineno, linestarts[i])) i += 1 # step index to the argument if any if op not in hasargx : # No argument, push the minimal tuple, done. code.append((op, None)) else: # op takes an argument. Look for MAKE_FUNCTION or MAKE_CLOSURE. if op in hascode : # sp...
isinstance( code[-2][1], types.CodeType ) : code[-2] = ( Opcode(LOAD_CONST), Code.from_code( code[-2][1] ) ) else : raise ValueError( 'Invalid opcode sequence for MAKE_FUNCTION/MAKE_CLOSURE' ) # now continue and handle the argument of MAKE_F/C normally. # Assemble the argument value from two bytes plus an extended # ar...
itself in the opcode tuple. If that constant is a code # object, the test above (if op in hascode) will later # convert it into a Code object. code.append((op, code_object.co_consts[arg])) elif op in hasname: # When the argument is a name, put the name string itself # in the opcode tuple. code.append((op, code_object.c...
in the tuple. code.append((op, code_object.co_varnames[arg])) elif op in hascompare: # When the argument is a relation (like ">=") put that # string in the tuple instead. code.append((op, cmp_op[arg])) elif op in hasfree: code.append((op, cellfree[arg])) else: # whatever, just put the arg in the tuple code.append((op, ...
(not present if kwonlyargs > 0) # names of other local variables # Hence the count of argument names is # co_argcount + co_kwonlyargcount + varargs + varkwargs nargs = code_object.co_argcount + code_object.co_kwonlyargcount + varargs + varkwargs args = code_object.co_varnames[ : nargs ] # Preserve a docstring if any. I...
def _compute_stacksize(self): ''' Given this object's code list, compute its maximal stack usage. This is done by scanning the code, and computing for each opcode the stack state at the opcode. ''' # get local access to code, save some attribute lookups later code = self.code # A mapping from labels to their positions ...
are pushed. If nothing happened, the # block is popped by a POP_BLOCK opcode and 1 object is pushed by a # (LOAD_CONST, None) operation. # # In Python 3, the targets of SETUP_WITH have similar behavior, # complicated by the fact that they also have an __exit__ method # stacked and what it returns determines what they p...
pushed, but # this will be corrected in the actual stack recording. sf_targets = set( label_pos[arg] for op, arg in code if op == SETUP_FINALLY or op == SETUP_WITH ) # What we compute - for each opcode, its stack state, as an n-tuple. # n is the number of blocks pushed. For each block, we record the number # of objects...
if isinstance(op, Label): # We should check if we already reached a node only if it is # a label. if pos in sf_targets: # Adjust a SETUP_FINALLY from 1 to 3 stack entries. curstack = curstack[:-1] + (curstack[-1] + 2,) if stacks[pos] is None: stacks[pos] = curstack else: if stacks[pos] != curstack: raise ValueError("In...
possibility for a jump yield label_pos[arg], curstack elif op in (POP_JUMP_IF_FALSE, POP_JUMP_IF_TRUE): # Two possibilities for a jump yield label_pos[arg], newstack(-1) yield pos+1, newstack(-1) elif op in (JUMP_IF_TRUE_OR_POP, JUMP_IF_FALSE_OR_POP): # Two possibilities for a jump yield label_pos[arg], curstack yield ...
nor does it create or pop a block. #yield label_pos[arg], curstack #yield label_pos[arg], curstack[:-1] pass elif op == SETUP_LOOP: # We continue with a new block. # On break, we jump to the label and return to current stack # state. yield label_pos[arg], curstack yield pos+1, curstack + (0,) elif op == SETUP_EXCEPT: #...
1 object. Extra 2 will be added to the actual # recording. yield label_pos[arg], newstack(1) yield pos+1, curstack + ( int(op == SETUP_WITH) ,) elif op == POP_BLOCK: # Just pop the block yield pos+1, curstack[:-1] elif op == END_FINALLY : # Since stack recording of SETUP_FINALLY targets is of 3 pushed # objects (as whe...
the calculation: open_positions holds positions which are # yet to be explored. In each step we take one open position, and # explore it by appending the positions to which it can go, to # open_positions. On the way, we update maxsize. # # open_positions is a list of tuples: (pos, stack state) # # Sneaky Python coding ...
# all yielded values to the list. Hence the statement # # open_positions.extend(get_next_stacks(pos,curstack)) # # appends 0, 1 or 2 tuples (pos, stack_state) to open_positions. maxsize = 0 open_positions = [(0, (0,))] while open_positions: pos, curstack = open_positions.pop() maxsize = max(maxsize, sum(curstack)) open...
def isomap(self, num_dims=None, directed=None): '''Isomap embedding. num_dims : dimension of embedded coordinates, defaults to input dimension directed : used for .shortest_path() calculation ''' W = -0.5 * self.shortest_path(directed=directed) ** 2 kpca = KernelPCA(n_components=num_dims, kernel='precomputed') return k...
def laplacian_eigenmaps(self, num_dims=None, normed=True, val_thresh=1e-8): '''Laplacian Eigenmaps embedding. num_dims : dimension of embedded coordinates, defaults to input dimension normed : used for .laplacian() calculation val_thresh : threshold for omitting vectors with near-zero eigenvalues ''' L = self.laplacian...
def locality_preserving_projections(self, coordinates, num_dims=None): '''Locality Preserving Projections (LPP, linearized Laplacian Eigenmaps).''' X = np.atleast_2d(coordinates) # n x d L = self.laplacian(normed=True) # n x n u,s,_ = np.linalg.svd(X.T.dot(X)) Fplus = np.linalg.pinv(u * np.sqrt(s)) # d x d n, d = X.sha...
def locally_linear_embedding(self, num_dims=None): '''Locally Linear Embedding (LLE). Note: may need to call barycenter_edge_weights() before this! ''' W = self.matrix() # compute M = (I-W)'(I-W) M = W.T.dot(W) - W.T - W if issparse(M): M = M.toarray() M.flat[::M.shape[0] + 1] += 1 return _null_space(M, num_vecs=num_di...
def neighborhood_preserving_embedding(self, X, num_dims=None, reweight=True): '''Neighborhood Preserving Embedding (NPE, linearized LLE).''' if reweight: W = self.barycenter_edge_weights(X).matrix() else: W = self.matrix() # compute M = (I-W)'(I-W) as in LLE M = W.T.dot(W) - W.T - W if issparse(M): M = M.toarray() M.fl...
def laplacian_pca(self, coordinates, num_dims=None, beta=0.5): '''Graph-Laplacian PCA (CVPR 2013). coordinates : (n,d) array-like, assumed to be mean-centered. beta : float in [0,1], scales how much PCA/LapEig contributes. Returns an approximation of input coordinates, ala PCA.''' X = np.atleast_2d(coordinates) L = sel...
def layout_circle(self): '''Position vertices evenly around a circle.''' n = self.num_vertices() t = np.linspace(0, 2*np.pi, n+1)[:n] return np.column_stack((np.cos(t), np.sin(t)))
def layout_spring(self, num_dims=2, spring_constant=None, iterations=50, initial_temp=0.1, initial_layout=None): '''Position vertices using the Fruchterman-Reingold (spring) algorithm. num_dims : int (default=2) Number of dimensions to embed vertices in. spring_constant : float (default=None) Optimal distance between n...
# default to sqrt(area_of_viewport / num_vertices) spring_constant = X.shape[0] ** -0.5 S = self.matrix('csr', 'csc', 'coo', copy=True) S.data[:] = 1. / S.data # Convert to similarity ii,jj = S.nonzero() # cache nonzero indices # simple cooling scheme, linearly steps down cooling_scheme = np.linspace(initial_temp, 0, i...
def optimize_structure_handler(rule, handler): """ Produce an "optimized" version of handler for the dispatcher to limit reference lookups. """ def runner(walk, dispatcher, node): handler(dispatcher, node) return yield # pragma: no cover return runner
def optimize_layout_handler(rule, handler): """ Produce an "optimized" version of handler for the dispatcher to limit reference lookups. """ def runner(walk, dispatcher, node): yield LayoutChunk(rule, handler, node) return runner
def walk(dispatcher, node, definition=None): """ The default, standalone walk function following the standard argument ordering for the unparsing walkers. Arguments: dispatcher a Dispatcher instance, defined earlier in this module. This instance will dispatch out the correct callable for the various object types encoun...
""" # The inner walk function - this is actually exposed to the token # rule objects so they can also make use of it to process the node # with the dispatcher. nodes = [] sourcepath_stack = [NotImplemented] def _walk(dispatcher, node, definition=None, token=None): if not isinstance(node, Node): for fragment in dispatch...
else None after_text = chunk.text if chunk else None # the text that was yielded by the previous layout handler prev_text = None # While Layout rules in a typical definition are typically # interspersed with Tokens, certain assumptions with how the # Layouts are specified within there will fail when Tokens fail # to ge...
stack that will be cleared whenever a # normalized layout rule chunk is generated. lrcs_stack = [] # first pass: generate both the normalized/finalized lrcs. for lrc in layout_rule_chunks: lrcs_stack.append(lrc) # check every single chunk from left to right... for idx in range(len(lrcs_stack)): rule = tuple(lrc.rule fo...
second pass: now the processing can be done. for lr_chunk in lrcs_stack: gen = lr_chunk.handler( dispatcher, lr_chunk.node, before_text, after_text, prev_text) if not gen: continue for chunk_from_layout in gen: yield chunk_from_layout prev_text = chunk_from_layout.text # The top level walker implementation def walk(): ...
def t_QUOTED_STRING(t): r'"([^"\\]|\\["\\])*"' # TODO: Add support for: # - An undefined escape sequence (such as "\a" in a context where "a" # has no special meaning) is interpreted as if there were no backslash # (in this case, "\a" is just "a"), though that may be changed by # extensions. # - Non-printing characters...
def t_NUMBER(t): r'[0-9]+[KkMmGg]?' exponents = { 'G' : 30, 'g' : 30, 'M' : 20, 'm' : 20, 'K' : 10, 'k' : 10, } if t.value[-1] in exponents: t.value = math.ldexp(int(t.value[:-1]), exponents[t.value[-1]]) else: t.value = int(t.value) return t
def _missingExtraCheck(given, required, extraException, missingException): """ If the L{sets<set>} C{required} and C{given} do not contain the same elements raise an exception describing how they are different. @param given: The L{set} of elements that was actually given. @param required: The L{set} of elements that mu...
def constructFiniteStateMachine(inputs, outputs, states, table, initial, richInputs, inputContext, world, logger=LOGGER): """ Construct a new finite state machine from a definition of its states. @param inputs: Definitions of all input symbols the resulting machine will need to handle, as a L{twisted.python.constants.N...
which correspond to each of the input symbols from C{inputs}. @type richInputs: L{list} of L{IRichInput} I{providers} @param inputContext: A L{dict} mapping output symbols to L{Interface} subclasses describing the requirements of the inputs which lead to them. @param world: An object responsible for turning FSM outputs...
except MissingTransitionNextState as e: if e.args != ({initial},): raise if initial not in states.iterconstants(): raise InvalidInitialState(initial) extraInputContext = set(inputContext) - set(outputs.iterconstants()) if extraInputContext: raise ExtraInputContext(extraInputContext) _checkConsistency(richInputs, table,...
def _checkConsistency(richInputs, fsm, inputContext): """ Verify that the outputs that can be generated by fsm have their requirements satisfied by the given rich inputs. @param richInputs: A L{list} of all of the types which will serve as rich inputs to an L{IFiniteStateMachine}. @type richInputs: L{list} of L{IRichIn...
input: # This rich input will be supplied to represent this input # symbol in this state. Check to see if it satisfies the # output requirements. outputs = fsm[state][input].output for output in outputs: try: required = inputContext[output] except KeyError: continue # Consider supporting non-interface based checking in...
def trivialInput(symbol): """ Create a new L{IRichInput} implementation for the given input symbol. This creates a new type object and is intended to be used at module scope to define rich input types. Generally, only one use per symbol should be required. For example:: Apple = trivialInput(Fruit.apple) @param symbol: ...
def _copy(self): """ Create a new L{TransitionTable} just like this one using a copy of the underlying transition table. @rtype: L{TransitionTable} """ table = {} for existingState, existingOutputs in self.table.items(): table[existingState] = {} for (existingInput, existingTransition) in existingOutputs.items(): table...
def addTransition(self, state, input, output, nextState): """ Create a new L{TransitionTable} with all the same transitions as this L{TransitionTable} plus a new transition. @param state: The state for which the new transition is defined. @param input: The input that triggers the new transition. @param output: The outp...
def addTransitions(self, state, transitions): """ Create a new L{TransitionTable} with all the same transitions as this L{TransitionTable} plus a number of new transitions. @param state: The state for which the new transitions are defined. @param transitions: A L{dict} mapping inputs to output, nextState pairs. Each it...
def addTerminalState(self, state): """ Create a new L{TransitionTable} with all of the same transitions as this L{TransitionTable} plus a new state with no transitions. @param state: The new state to include in the new table. @return: The newly created L{TransitionTable}. """ table = self._copy() table.table[state] = {...
def minify(drop_semi=True): """ Rules for minifying output. Arguments: drop_semi Drop semicolons whenever possible. Note that if Dedent and OptionalNewline has a handler defined, it will stop final break statements from being resolved due to reliance on normalized resolution. """ layout_handlers = { OpenBlock: layout_h...
won't neuter all optional # semicolons. (EndStatement, Dedent): rule_handler_noop, ((OptionalSpace, EndStatement), CloseBlock): layout_handler_closebrace, }) def minify_rule(): return { 'layout_handlers': layout_handlers, 'deferrable_handlers': { Literal: deferrable_handler_literal_continuation, }, } return minify_rule
def indent(indent_str=None): """ A complete, standalone indent ruleset. Arguments: indent_str The string used for indentation. Defaults to None, which will defer the value used to the one provided by the Dispatcher. """ def indentation_rule(): inst = Indentator(indent_str) return {'layout_handlers': { OpenBlock: layout...
def dist_docs(): "create a documentation bundle" dist_dir = path("dist") docs_package = path("%s/%s-%s-docs.zip" % (dist_dir.abspath(), options.setup.name, options.setup.version)) dist_dir.exists() or dist_dir.makedirs() docs_package.exists() and docs_package.remove() sh(r'cd build/apidocs && zip -qr9 %s .' % (docs_pac...
def release(): "check release before upload to PyPI" sh("paver bdist_wheel") wheels = path("dist").files("*.whl") if not wheels: error("\n*** ERROR: No release wheel was built!") sys.exit(1) if any(".dev" in i for i in wheels): error("\n*** ERROR: You're still using a 'dev' version!") sys.exit(1) # Check that source di...
(project["name"], version)).rmtree() print("~" * 78) print('') print("Created", " ".join([str(i) for i in path("dist").listdir()])) print("Use 'paver sdist bdist_wheel' to build the release and") print(" 'twine upload dist/*.{zip,whl}' to upload to PyPI") print("Use 'paver dist_docs' to prepare an API documentation upl...
def getPyroleLikeAtoms(cycle): """cycle->return a dictionary of pyrole nitrogen-like atoms in a cycle or a molecule The dictionary is keyed on the atom.handle""" result = {} # the outgoing bonds might need to be single or aromatic for atom in cycle.atoms: lookup = (atom.symbol, atom.charge, atom.hcount, len(atom.bonds)...
def canBeAromatic(cycle, pyroleLike): """(cycle)-> returns AROMATIC if a ring is conjugatable and passes the simple tests for aromaticity returns MAYBE if the ring in its present form can be aromatic but is not currently NEVER if the ring can never be aromatic""" cycleLength = len(cycle) # *****************************...
a kekular structure for index, bond in zip(range(len(bonds)), bonds): if bond.bondtype not in AROMATIC_5_RING[index]: return MAYBE return AROMATIC # ***************************************************** # check for kekular six membered rings # kekular rings must have atoms in the AROMATIC_ATOMS # groups and must belong...
bond.bondtype not in [2,4]: return MAYBE elif last == 2 and bond.bondtype not in [1, 4]: return MAYBE last = switch[last] if bondtype != last: bond.bondorder = last return AROMATIC else: # we can never be aromatic return NEVER
def convert(cycle, pyroleLike, usedPyroles): """cycle, pyroleLike, aromatic=0-> aromatize the cycle pyroleLike is a lookup of the pyrole like atoms in the cycle. return 1 if the cycle was aromatized 2 if the cycle could not be aromatized""" bonds = cycle.bonds atoms = cycle.atoms initialBondStates = [] initialAtomState...
the atom to # fill the valences for valence in atom.valences: neededHydrogens = int(valence - nonhydrogens) if neededHydrogens >= 0: break else: # we can't change the aromaticity and have correct # valence. # # there is one special case of a five membered # ring and a pyrole nitrogen like atom we need # to look for. if...
in initialAtomStates: atom.aromatic = aromatic else: # we used some pyroles, we'll have to send these to # the valence checker later usedPyroles.update(_usedPyroles) return aromatized
def addHydrogens(molecule, usedPyroles=None): """(molecule) -> add implicit hydrogens to a molecule. If the atom has specified valences and the atom must be charged then a Valence Error is raised""" for atom in molecule.atoms: # if the atom has an explicit hcount, we can't set the # hcount if atom.has_explicit_hcount: ...
def aromatize(molecule, usedPyroles=None): """(molecule, usedPyroles=None)->aromatize a molecular graph usedPyroles is a dictionary that holds the pyrole like atoms that are used in the conversion process. The following valence checker may need this information""" pyroleLike = getPyroleLikeAtoms(molecule) if usedPyrole...
PinkyError("Bad initial aromaticity") # keep checking rings until something happens while 1: # assume nothing happened needToCheckAgain = 0 _cyclesToCheck = [] for cycle in cyclesToCheck: canAromatic = canBeAromatic(cycle, pyroleLike) if canAromatic == NEVER: # the ring can NEVER EVER be aromatic, so remove it for good...
def _prep_noise_interpolants(self): """Construct interpolated sensitivity curves This will construct the interpolated sensitivity curves using scipy.interpolate.interp1d. It will add wd noise if that is requested. Raises: ValueError: ``len(noise_type_in) != len(sensitivity_curves)`` ValueError: Issue with sensitivity c...
sc.split('.')[0].split('/')[-1] else: key = sc elif isinstance(sc, list): # TODO: add to docs if inputing special noise curve, make sure its char_strain f, h_n = sc key = str(num) else: raise ValueError('Sensitivity curves must either be string' + 'or list containing f_n and asd_n.') noise_lists[key] = [f, h_n] # add w...
def create_selfsim(oracle, method='rsfx'): """ Create self similarity matrix from attributes of a vmo object :param oracle: a encoded vmo object :param method: "comp":use the compression codes "sfx" - use suffix links "rsfx" - use reverse suffix links "lrs" - use LRS values "seg" - use patterns found :return: the creat...
ind + inc)] = 1 ind = ind + l elif method == 'sfx': for i, s in enumerate(oracle.sfx[1:]): if s != 0: mat[i][s - 1] = 1 mat[s - 1][i] = 1 elif method == 'rsfx': for cluster in oracle.latent: p = itertools.product(cluster, repeat=2) for _p in p: mat[_p[0] - 1][_p[1] - 1] = 1 elif method == 'lrs': for i, l in enumerate(o...
length, p for position if l == 0: inc = 1 else: inc = l mat[range(ind, ind + inc), range(p - 1, p - 1 + inc)] = 1 mat[range(p - 1, p - 1 + inc), range(ind, ind + inc)] = 1 ind = ind + l return mat
def create_transition(oracle, method='trn'): """Create a transition matrix based on oracle links""" mat, hist, n = _create_trn_mat_symbolic(oracle, method) return mat, hist, n
def predict(oracle, context, ab=None, verbose=False): """Single symbolic prediction given a context, an oracle and an alphabet. :param oracle: a learned vmo object from a symbolic sequence. :param context: the context precedes the predicted symbol :param ab: alphabet :param verbose: to show if the context if pruned or ...
d_count = len(ab) hist = [1.0] * len(ab) # initialize all histograms with 1s. trn_data = [oracle.data[n] for n in oracle.trn[_s]] for k in trn_data: hist[ab[k]] += 1.0 d_count += 1.0 for i in context_state: d_count, hist = _rsfx_count(oracle, i, d_count, hist, ab) return [hist[idx] / d_count for idx in range(len(hist))...
def log_loss(oracle, test_seq, ab=[], m_order=None, verbose=False): """ Evaluate the average log-loss of a sequence given an oracle """ if not ab: ab = oracle.get_alphabet() if verbose: print(' ') logP = 0.0 context = [] increment = np.floor((len(test_seq) - 1) / 100) bar_count = -1 maxContextLength = 0 avgContext = 0 ...
+ "% " + str(i) + "/" + str(len(test_seq) - 1) + " Current max length: " + str( maxContextLength)) sys.stdout.flush() return logP / len(test_seq), avgContext
def _rsfx_count(oracle, s, count, hist, ab): """ Accumulate counts for context """ trn_data = [oracle.data[n] for n in oracle.trn[s]] for k in trn_data: hist[ab[k]] += 1.0 count += 1.0 rsfx_candidate = oracle.rsfx[s][:] while rsfx_candidate: s = rsfx_candidate.pop(0) trn_data = [oracle.data[n] for n in oracle.trn[s]] f...
def tracking(oracle, obs, trn_type=1, reverse_init=False, method='else', decay=1.0): """ Off-line tracking function using sub-optimal query-matching algorithm""" N = len(obs) if reverse_init: r_oracle = create_reverse_oracle(oracle) _ind = [r_oracle.n_states - rsfx for rsfx in r_oracle.rsfx[0][:]] init_ind = [] for i i...
iterate over the rest of query state_cache = [] dist_cache = distance_cache map_k_inner = partial(map_k_outer, i=i, P=P, trn=trn, state_cache=state_cache, dist_cache=dist_cache) P[i], _c = zip(*map(map_k_inner, range(K))) C = decay * C + np.array(_c) T[i] = P[i][argmin(C)] return T
def _query_init(k, oracle, query, method='all'): """A helper function for query-matching function initialization.""" if method == 'all': a = np.subtract(query, [oracle.f_array[t] for t in oracle.latent[oracle.data[k]]]) dvec = (a * a).sum(axis=1) # Could skip the sqrt _d = dvec.argmin() return oracle.latent[oracle.data...
def _dist_obs_oracle(oracle, query, trn_list): """A helper function calculating distances between a feature and frames in oracle.""" a = np.subtract(query, [oracle.f_array[t] for t in trn_list]) return (a * a).sum(axis=1)
def _query_k(k, i, P, oracle, query, trn, state_cache, dist_cache, smooth=False, D=None, weight=0.5): """A helper function for query-matching function`s iteration over observations. Args: k - index of the candidate path i - index of the frames of the observations P - the path matrix of size K x N, K the number for path...
smooth - whether to enforce a preference on continuation or not D - Self-similarity matrix, required if smooth is set to True weight - the weight between continuation or jumps (1.0 for certain continuation) """ _trn = trn(oracle, P[i - 1][k]) t = list(itertools.chain.from_iterable([oracle.latent[oracle.data[j]] for j i...
def safe_shell_out(cmd, verbose=False, **kwargs): """run cmd and return True if it went ok, False if something went wrong. Suppress all output. """ # TODO rename this suppressed_shell_out ? # TODO this should probably return 1 if there's an error (i.e. vice-versa). # print("cmd %s" % cmd) try: with open(os.devnull, "w"...
def cprint(message, status=None): """color printing based on status: None -> BRIGHT 'ok' -> GREEN 'err' -> RED 'warn' -> YELLOW """ # TODO use less obscure dict, probably "error", "warn", "success" as keys status = {'warn': Fore.YELLOW, 'err': Fore.RED, 'ok': Fore.GREEN, None: Style.BRIGHT}[status] print(status + messa...
def prev_deps(env): """Naively gets the dependancies from the last time ctox was run.""" # TODO something more clever. if not os.path.isfile(env.envctoxfile): return [] with open(env.envctoxfile) as f: return f.read().split()
def make_dist(toxinidir, toxdir, package): """zip up the package into the toxdir.""" dist = os.path.join(toxdir, "dist") # Suppress warnings. success = safe_shell_out(["python", "setup.py", "sdist", "--quiet", "--formats=zip", "--dist-dir", dist], cwd=toxinidir) if success: return os.path.join(dist, package + ".zip")
def print_pretty_command(env, command): """This is a hack for prettier printing. Rather than "{envpython} foo.py" we print "python foo.py". """ cmd = abbr_cmd = command[0] if cmd.startswith(env.envbindir): abbr_cmd = os.path.relpath(cmd, env.envbindir) if abbr_cmd == ".": # TODO are there more edge cases? abbr_cmd = cm...
def maximizeLikelihood(self, optimize_brlen=False, approx_grad=False, logliktol=1.0e-2, nparamsretry=1, printfunc=None): """Maximize the log likelihood. Maximizes log likelihood with respect to model parameters and potentially branch lengths depending on `optimize_brlen`. If optimizing the branch lengths, iterates betw...
the first time. `printfunc` (`None` or a function) If not `None`, then we print using `printfunc` the detailed results of the optimization at each step. For instance, `printfunc` might be `sys.stderr.write` or `logger.info`. Returns: A string giving a summary of the maximization. """ # Some useful notes on optimization...
paramsdfunc = False tdfunc = False self.dtcurrent = False self.dparamscurrent = False def _printResult(opttype, result, i, old, new): """Print summary of optimization result.""" if printfunc is not None: printfunc('Step {0}, optimized {1}.\n' 'Likelihood went from {2} to {3}.\n' 'Max magnitude in Jacobian is {4}.\n' 'F...
iterations, {4} function ' 'evals)'.format(i, oldloglik, self.loglik, result.nit, result.nfev)) summary.append(msg) if result.success and (not (oldloglik - self.loglik > logliktol)): paramsconverged = True jacmax = scipy.absolute(result.jac).max() if (jacmax > 1000) and not (firstbrlenpass and optimize_brlen): warnings...
scipy.array([self.paramsarraybounds[j][1] for j in range(len(self.paramsarray))]) randarray = scipy.random.uniform(minarray, maxarray) newarray = (minarray * maxarray * randarray * origparamsarray)**(1 / 4.) # geometric mean assert newarray.shape == self.paramsarray.shape assert (newarray > minarray).all() assert (newa...
during t " "optimization: {0} to {1}".format( oldloglik, self.loglik)) elif self.loglik - oldloglik >= logliktol: oldloglik = self.loglik else: converged = True else: converged = True else: converged = True return '\n'.join(summary)
def tree(self): """Tree with branch lengths in codon substitutions per site. The tree is a `Bio.Phylo.BaseTree.Tree` object. This is the current tree after whatever optimizations have been performed so far. """ bs = self.model.branchScale for node in self._tree.find_clades(): if node != self._tree.root: node.branch_len...
def paramsarraybounds(self): """Bounds for parameters in `paramsarray`.""" bounds = [] for (i, param) in self._index_to_param.items(): if isinstance(param, str): bounds.append(self.model.PARAMLIMITS[param]) elif isinstance(param, tuple): bounds.append(self.model.PARAMLIMITS[param[0]]) else: raise ValueError("Invalid pa...
def paramsarray(self): """All free model parameters as 1-dimensional `numpy.ndarray`. You are allowed to update model parameters by direct assignment of this property.""" # Return copy of `_paramsarray` because setter checks if changed if self._paramsarray is not None: return self._paramsarray.copy() nparams = len(self...