code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if token_type not in http.VALID_TOKEN_TYPES:
return False
allowed_chars = ascii_letters + digits + '_' + '-' + '=' + '/' + '+'
# True if token only contains allowed_chars
return all(characters in allowed_chars for characters in token) | def _authorization_headers_valid(self, token_type, token) | Verify authorization headers for a request.
Parameters
token_type (str)
Type of token to access resources.
token (str)
Server Token or OAuth 2.0 Access Token.
Returns
(bool)
True iff token_type and token are valid. | 7.431097 | 7.926591 | 0.93749 |
if hasattr(input, 'unit'): # check units
if expected_units is None:
raise ValueError('Expecting dimensionless input')
elif input.unit != expected_units:
raise ValueError('Expecting input units of ' + str(expected_units))
else:
dimensionless = input... | def check_units_and_type(input, expected_units, num=None, is_scalar=False) | Check whether variable has expected units and type.
If input does not have units and expected units is not None, then the
output will be assigned those units. If input has units that conflict
with expected units a ValueError will be raised.
Parameters
----------
input : array_like or float
... | 3.859211 | 3.846972 | 1.003181 |
if type(input) != np.ndarray:
if type(input) == list:
output = np.array(input)
else:
raise TypeError('Expecting input type as ndarray or list.')
else:
output = input
if output.ndim != 1:
raise ValueError('Input array must have 1 dimension.')
... | def check_array_or_list(input) | Return 1D ndarray, if input can be converted and elements are
non-negative. | 2.79818 | 2.744517 | 1.019553 |
filename = os.path.abspath('') + '/../files/Suite_No_1_for_Cello_M1_Prelude.mxl'
s = music21.converter.parse(filename)
c = s.getElementById('Violoncello')
m = c.flat.notes
note_obj_seq = [x for x in m if type(x) is music21.note.Note]
bo = vmo.build_oracle(note_obj_seq,'f')
bo.name =... | def main() | This example shows how to parse a music mxl file (music21 and musescore/finale required)
and create a simple oracle representation. The output is a reshuffled midi stream shown
in either musescore or finale based on your installation of music21.
OPTIONAL ARGS:
seq_len: an integer for the leng... | 4.244499 | 3.542842 | 1.198049 |
if 400 <= response.status_code <= 499:
message = response.json()['error_description'] \
if 'error_description' in response.json() \
else response.json()['error_detail']
raise ClientError(response, message)
elif 500 <= response.status_code <= 599:
raise Serve... | def error_handler(response, **kwargs) | Error Handler to surface 4XX and 5XX errors.
Attached as a callback hook on the Request object.
Parameters
response (requests.Response)
The HTTP response from an API request.
**kwargs
Arbitrary keyword arguments.
Raises
ClientError (ApiError)
Raise... | 2.212152 | 2.294543 | 0.964093 |
'''
Return a sorted list of names defined by thing that are not also names in
a standard object, except include __doc__.
'''
standard_names = set( dir( object() ) )
things_names = set( dir( thing ) )
if not all :
things_names -= standard_names
things_names |= set( ['__doc__']... | def object_attributes( thing, all=False ) | Return a sorted list of names defined by thing that are not also names in
a standard object, except include __doc__. | 7.081766 | 2.582091 | 2.742647 |
'''
Print the attribute names in thing vertically
'''
if heading : print( '==', heading, '==', file=file )
print( '\n'.join( object_attributes( thing ) ), file=file ) | def print_object_attributes( thing, heading=None, file=None ) | Print the attribute names in thing vertically | 7.182042 | 4.011117 | 1.790534 |
'''
Print the attributes of thing which have non-empty values,
as a vertical list of "name : value". When all=True, print
all attributes even those with empty values.
'''
if heading :
if isinstance( heading, int ) :
# request for default heading
heading = '== {} a... | def print_attr_values( thing, all=False, heading=None, file=None ) | Print the attributes of thing which have non-empty values,
as a vertical list of "name : value". When all=True, print
all attributes even those with empty values. | 4.401908 | 2.912259 | 1.51151 |
'''
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 _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. | 5.221496 | 3.421889 | 1.52591 |
'''
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, only "real" file objects have ... | 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, only "real" file objects have a mode attri... | 9.100351 | 2.9254 | 3.110806 |
# 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
... | 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 its... | 3.170397 | 2.628079 | 1.206355 |
'''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 kpca.fit_transform(W... | 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 | 6.176005 | 3.233961 | 1.909734 |
'''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(normed=normed)
return _null_space(L, num_dims,... | 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 | 6.883397 | 2.501544 | 2.751659 |
'''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.shape
if n >= d: # optimized order: F(X'LX... | def locality_preserving_projections(self, coordinates, num_dims=None) | Locality Preserving Projections (LPP, linearized Laplacian Eigenmaps). | 4.763975 | 4.173766 | 1.141409 |
'''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_dims, overw... | def locally_linear_embedding(self, num_dims=None) | Locally Linear Embedding (LLE).
Note: may need to call barycenter_edge_weights() before this! | 5.844579 | 3.764845 | 1.552409 |
'''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.flat[::M.shape[0] + 1] += 1
# ... | def neighborhood_preserving_embedding(self, X, num_dims=None, reweight=True) | Neighborhood Preserving Embedding (NPE, linearized LLE). | 5.242519 | 4.569025 | 1.147404 |
'''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 = self.laplacian(normed=True)
kernel = X... | 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. | 4.169915 | 2.214935 | 1.882636 |
'''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_circle(self) | Position vertices evenly around a circle. | 3.688619 | 2.891264 | 1.275781 |
'''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 nodes. If None the distance is set to
1/sqrt(n) where n is the number of nodes... | 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 nodes. If None the distance is set to
1/sqrt(n) where n is the number of nodes. Incr... | 4.727704 | 2.934978 | 1.610814 |
def runner(walk, dispatcher, node):
handler(dispatcher, node)
return
yield # pragma: no cover
return runner | def optimize_structure_handler(rule, handler) | Produce an "optimized" version of handler for the dispatcher to
limit reference lookups. | 23.736753 | 18.406065 | 1.289616 |
def runner(walk, dispatcher, node):
yield LayoutChunk(rule, handler, node)
return runner | def optimize_layout_handler(rule, handler) | Produce an "optimized" version of handler for the dispatcher to
limit reference lookups. | 36.147804 | 29.459854 | 1.227019 |
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 charac... | def t_QUOTED_STRING(t) | r'"([^"\\]|\\["\\])*" | 7.765066 | 7.315661 | 1.061431 |
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 t_NUMBER(t) | r'[0-9]+[KkMmGg]? | 2.586562 | 2.321321 | 1.114263 |
extra = given - required
if extra:
raise extraException(extra)
missing = required - given
if missing:
raise missingException(missing) | 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 must be given.
@param extraException: An exception to raise if ... | 2.655404 | 3.437799 | 0.772414 |
table = table.table
_missingExtraCheck(
set(table.keys()), set(states.iterconstants()),
ExtraTransitionState, MissingTransitionState)
_missingExtraCheck(
set(i for s in table.values() for i in s), set(inputs.iterconstants()),
ExtraTransitionInput, MissingTransitionInpu... | 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.Names} subclass.
@param outputs: Definitions of all output symbols the resulting machine is
allowed t... | 3.513049 | 3.527083 | 0.996021 |
for richInput in richInputs:
for state in fsm:
for input in fsm[state]:
if richInput.symbol() == input:
# This rich input will be supplied to represent this input
# symbol in this state. Check to see if it satisfies the
... | 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{IRichInput} providers
@param fsm: The L... | 6.030015 | 5.121285 | 1.177442 |
return implementer(IRichInput)(type(
symbol.name.title(), (FancyStrMixin, object), {
"symbol": _symbol(symbol),
})) | 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: A... | 36.491367 | 27.521957 | 1.3259 |
table = {}
for existingState, existingOutputs in self.table.items():
table[existingState] = {}
for (existingInput, existingTransition) in existingOutputs.items():
table[existingState][existingInput] = existingTransition
return TransitionTable(tabl... | def _copy(self) | Create a new L{TransitionTable} just like this one using a copy of the
underlying transition table.
@rtype: L{TransitionTable} | 5.161363 | 4.459975 | 1.157263 |
return self.addTransitions(state, {input: (output, nextState)}) | 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 output produced by the new transi... | 6.4315 | 9.942801 | 0.64685 |
table = self._copy()
state = table.table.setdefault(state, {})
for (input, (output, nextState)) in transitions.items():
state[input] = Transition(output, nextState)
return table | 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 item from this... | 4.852554 | 3.678747 | 1.319078 |
table = self._copy()
table.table[state] = {}
return table | 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}. | 11.800299 | 9.329622 | 1.264821 |
layout_handlers = {
OpenBlock: layout_handler_openbrace,
CloseBlock: layout_handler_closebrace,
EndStatement: layout_handler_semicolon,
Space: layout_handler_space_minimum,
OptionalSpace: layout_handler_space_minimum,
RequiredSpace: layout_handler_space_imply,
... | 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. | 5.008149 | 4.521051 | 1.10774 |
def indentation_rule():
inst = Indentator(indent_str)
return {'layout_handlers': {
OpenBlock: layout_handler_openbrace,
CloseBlock: layout_handler_closebrace,
EndStatement: layout_handler_semicolon,
Space: layout_handler_space_imply,
... | 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. | 4.340186 | 4.345684 | 0.998735 |
"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 .' % ... | def dist_docs() | create a documentation bundle | 6.73174 | 6.048748 | 1.112915 |
"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!")
... | def release() | check release before upload to PyPI | 7.695815 | 7.319331 | 1.051437 |
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))
if PyroleTable.get(lookup, 0):
result[atom.handle] = atom
return result | 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 | 8.433599 | 7.548875 | 1.117199 |
cycleLength = len(cycle)
# *******************************************************
# check for kekular five membered rings
if cycleLength == 5:
# check atom types
for atom in cycle.atoms:
if not AROMATIC_PYROLE_ATOMS.has_key(atom.symbol):
return NEVER
... | 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 a... | 4.219396 | 4.074531 | 1.035554 |
bonds = cycle.bonds
atoms = cycle.atoms
initialBondStates = []
initialAtomStates = []
_usedPyroles = {}
for bond in bonds:
# store the initial states but assume the
# bond is aromatic
initialBondStates.append((bond, bond.symbol,
bon... | 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 | 5.193141 | 4.912578 | 1.057111 |
for atom in molecule.atoms:
# if the atom has an explicit hcount, we can't set the
# hcount
if atom.has_explicit_hcount:
atom.hcount = atom.explicit_hcount
continue
if atom.valences:
for valence in atom.valences:
... | 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 | 4.538776 | 4.305674 | 1.054138 |
usedPyroles = {}
cyclesToCheck = []
# determine which cycles came in marked as aromatic
# and which need to be checked form the kekular form
#
# if a cycle came in as aromatic, convert it
# before going on.
for cycle in molecule.cycles:
for atom in cycle.atoms:
... | def aromatize(molecule, usedPyroles=None):
pyroleLike = getPyroleLikeAtoms(molecule)
if usedPyroles is 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 | 6.286994 | 6.198298 | 1.01431 |
noise_lists = {}
self.noise_interpolants = {}
if isinstance(self.sensitivity_curves, str):
self.sensitivity_curves = [self.sensitivity_curves]
if isinstance(self.noise_type_in, list):
if len(self.noise_type_in) != len(self.sensitivity_curves):
... | 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... | 2.710057 | 2.609273 | 1.038625 |
len_oracle = oracle.n_states - 1
mat = np.zeros((len_oracle, len_oracle))
if method == 'com':
if not oracle.code:
print("Codes not generated. Generating codes with encode().")
oracle.encode()
ind = 0 # index
for l, p in oracle.code: # l for length, p f... | 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... | 2.312075 | 2.120938 | 1.090119 |
mat, hist, n = _create_trn_mat_symbolic(oracle, method)
return mat, hist, n | def create_transition(oracle, method='trn') | Create a transition matrix based on oracle links | 13.246758 | 11.411424 | 1.160833 |
if verbose:
print("original context: ", context)
if ab is None:
ab = oracle.get_alphabet()
_b, _s, context = _test_context(oracle, context)
_lrs = [oracle.lrs[k] for k in oracle.rsfx[_s]]
context_state = []
while not context_state:
for _i, _l in enumerate(_lrs):
... | 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 not
:return: a probability distribut... | 3.70924 | 3.671651 | 1.010238 |
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
for i, t in enumerate(test_seq):
p, c = predict(oracle, context, ab,... | def log_loss(oracle, test_seq, ab=[], m_order=None, verbose=False) | Evaluate the average log-loss of a sequence given an oracle | 2.773533 | 2.76868 | 1.001753 |
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]]
for k in trn_data:
... | def _rsfx_count(oracle, s, count, hist, ab) | Accumulate counts for context | 2.46125 | 2.518565 | 0.977243 |
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 in _ind:
s = i
while oracle.sfx[s] != 0:
s = oracle.sfx[s]
init_in... | 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 | 3.554036 | 3.491235 | 1.017988 |
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[k]][_d], dvec[_d]
else:
a = np.subtract(query, oracle.f_array... | def _query_init(k, oracle, query, method='all') | A helper function for query-matching function initialization. | 4.671985 | 4.552128 | 1.02633 |
a = np.subtract(query, [oracle.f_array[t] for t in trn_list])
return (a * a).sum(axis=1) | def _dist_obs_oracle(oracle, query, trn_list) | A helper function calculating distances between a feature and frames in oracle. | 7.068791 | 5.496457 | 1.286063 |
_trn = trn(oracle, P[i - 1][k])
t = list(itertools.chain.from_iterable([oracle.latent[oracle.data[j]] for j in _trn]))
_trn_unseen = [_t for _t in _trn if _t not in state_cache]
state_cache.extend(_trn_unseen)
if _trn_unseen:
t_unseen = list(itertools.chain.from_iterable([oracle.laten... | 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 paths initiated,
N the frame number of observations
ora... | 3.21559 | 3.066666 | 1.048562 |
# 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") as fnull:
with captured_output():
check_output(cmd, stderr=fnull, **kwargs)
retur... | 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. | 6.194329 | 5.940549 | 1.04272 |
# 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 + message + Style.RESET_ALL) | def cprint(message, status=None) | color printing based on status:
None -> BRIGHT
'ok' -> GREEN
'err' -> RED
'warn' -> YELLOW | 7.026405 | 6.053815 | 1.160657 |
# TODO something more clever.
if not os.path.isfile(env.envctoxfile):
return []
with open(env.envctoxfile) as f:
return f.read().split() | def prev_deps(env) | Naively gets the dependancies from the last time ctox was run. | 8.165108 | 4.978736 | 1.639996 |
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 make_dist(toxinidir, toxdir, package) | zip up the package into the toxdir. | 3.916017 | 3.87327 | 1.011036 |
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 = cmd
command[0] = abbr_cmd
print('(%s)$ %s' % (env.name, ' '.join(['"%s"' % c if " " i... | def print_pretty_command(env, command) | This is a hack for prettier printing.
Rather than "{envpython} foo.py" we print "python foo.py". | 4.541945 | 4.388433 | 1.034981 |
bs = self.model.branchScale
for node in self._tree.find_clades():
if node != self._tree.root:
node.branch_length = self.t[self.name_to_nodeindex[node]] * bs
return self._tree | 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. | 8.144918 | 7.408365 | 1.099422 |
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:
... | def paramsarraybounds(self) | Bounds for parameters in `paramsarray`. | 3.105339 | 3.153782 | 0.98464 |
# Return copy of `_paramsarray` because setter checks if changed
if self._paramsarray is not None:
return self._paramsarray.copy()
nparams = len(self._index_to_param)
self._paramsarray = scipy.ndarray(shape=(nparams,), dtype='float')
for (i, param) in self._i... | 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. | 3.101009 | 3.069753 | 1.010182 |
nparams = len(self._index_to_param)
assert (isinstance(value, scipy.ndarray) and value.ndim == 1), (
"paramsarray must be 1-dim ndarray")
assert len(value) == nparams, ("Assigning paramsarray to ndarray "
"of the wrong length.")
if (self._paramsar... | def paramsarray(self, value) | Set new `paramsarray` and update via `updateParams`. | 2.948968 | 2.850448 | 1.034563 |
assert isinstance(value, bool)
if value and self.dparamscurrent:
raise RuntimeError("Can't set both dparamscurrent and dtcurrent True")
if value != self.dtcurrent:
self._dtcurrent = value
self._updateInternals() | def dtcurrent(self, value) | Set value of `dtcurrent`, update derivatives if needed. | 7.078331 | 6.169772 | 1.14726 |
assert (isinstance(value, scipy.ndarray) and (value.dtype ==
'float') and (value.shape == self.t.shape))
if (self._t != value).any():
self._t = value.copy()
self._updateInternals() | def t(self, value) | Set new branch lengths, update likelihood and derivatives. | 5.560643 | 5.182809 | 1.072901 |
assert self.dparamscurrent, "dloglikarray requires paramscurrent == True"
nparams = len(self._index_to_param)
dloglikarray = scipy.ndarray(shape=(nparams,), dtype='float')
for (i, param) in self._index_to_param.items():
if isinstance(param, str):
dlog... | def dloglikarray(self) | Derivative of `loglik` with respect to `paramsarray`. | 3.196018 | 3.079896 | 1.037703 |
for (param, value) in newvalues.items():
if param not in self.model.freeparams:
raise RuntimeError("Can't handle param: {0}".format(
param))
if newvalues:
self.model.updateParams(newvalues)
self._updateInternals()
... | def updateParams(self, newvalues) | Update model parameters and re-compute likelihoods.
This method is the **only** acceptable way to update model
parameters. The likelihood is re-computed as needed
by this method.
Args:
`newvalues` (dict)
A dictionary keyed by param name and with value as new... | 5.816371 | 5.29447 | 1.098575 |
rootnode = self.nnodes - 1
if self._distributionmodel:
catweights = self.model.catweights
else:
catweights = scipy.ones(1, dtype='float')
# When there are multiple categories, it is acceptable
# for some (but not all) of them to have underflow at
... | def _updateInternals(self) | Update internal attributes related to likelihood.
Should be called any time branch lengths or model parameters
are changed. | 3.781851 | 3.762452 | 1.005156 |
if self._distributionmodel:
return self.model.M(k, t, tips, gaps)
else:
return self.model.M(t, tips, gaps) | def _M(self, k, t, tips=None, gaps=None) | Returns matrix exponential `M`. | 4.193237 | 4.123956 | 1.0168 |
if self._distributionmodel:
return self.model.dM(k, t, param, M, tips, gaps)
else:
return self.model.dM(t, param, M, tips, gaps) | def _dM(self, k, t, param, M, tips=None, gaps=None) | Returns derivative of matrix exponential. | 3.215611 | 3.122764 | 1.029732 |
if self._distributionmodel:
return self.model.stationarystate(k)
else:
return self.model.stationarystate | def _stationarystate(self, k) | Returns the stationarystate . | 5.047242 | 4.594091 | 1.098638 |
if self._distributionmodel:
return self.model.dstationarystate(k, param)
else:
return self.model.dstationarystate(param) | def _dstationarystate(self, k, param) | Returns the dstationarystate . | 4.437779 | 4.039569 | 1.098577 |
if self._distributionmodel:
return [param for param in self.model.freeparams +
[self.model.distributedparam] if param not in
self.model.distributionparams]
else:
return self.model.freeparams | def _paramlist_PartialLikelihoods(self) | List of parameters looped over in `_computePartialLikelihoods`. | 6.421849 | 6.414564 | 1.001136 |
if self._distributionmodel and (param ==
self.model.distributedparam):
indices = [()]
else:
paramvalue = getattr(self.model, param)
if isinstance(paramvalue, float):
indices = [()]
elif (isinstance(paramvalue, scipy... | def _sub_index_param(self, param) | Returns list of sub-indexes for `param`.
Used in computing partial likelihoods; loop over these indices. | 4.54906 | 4.399347 | 1.034031 |
try:
return super(JSHost, self).send_request(*args, **kwargs)
except RequestsConnectionError as e:
if (
self.manager and
self.has_connected and
self.logfile and
'unsafe' not in kwargs
):
... | def send_request(self, *args, **kwargs) | Intercept connection errors which suggest that a managed host has
crashed and raise an exception indicating the location of the log | 4.963687 | 4.376349 | 1.134207 |
def _updateB(oldB, B, W, degrees, damping, inds, backinds): # pragma: no cover
'''belief update function.'''
for j,d in enumerate(degrees):
kk = inds[j]
bk = backinds[j]
if d == 0:
B[kk,bk] = -np.inf
continue
belief = W[kk,bk] + W[j]
oldBj = oldB[j]
if d == oldBj.s... | belief update function. | null | null | null | |
def _func_copy(f, newcode) :
'''
Return a copy of function f with a different __code__
Because I can't find proper documentation on the
correct signature of the types.FunctionType() constructor,
I pass the minimum arguments then set the important
dunder-values by direct assignment.
... | Return a copy of function f with a different __code__
Because I can't find proper documentation on the
correct signature of the types.FunctionType() constructor,
I pass the minimum arguments then set the important
dunder-values by direct assignment.
Note you cannot assign __closure__, it is a... | null | null | null | |
def bind_all(mc, builtin_only=False, stoplist=[], verbose=False):
import types
try:
d = vars(mc)
except TypeError:
return
for k, v in d.items():
if isinstance( v, types.FunctionType ) :
if verbose :
print( 'make_constants(', v.__name__,... | Recursively apply constant binding to functions in a module or class.
Use as the last line of the module (after everything is defined, but
before test code). In modules that need modifiable globals, set
builtin_only to True. | null | null | null | |
def make_constants(builtin_only=False, stoplist=[], verbose=False):
if type(builtin_only) == type(make_constants):
raise ValueError("The make_constants decorator must have arguments.")
return lambda f: _make_constants(f, builtin_only, stoplist, verbose) | Return a decorator for optimizing global references.
Verify that the first argument is a function. | null | null | null | |
'''Get The playback state: 'playing', 'paused', or 'stopped'.
If PLAYING or PAUSED, show information on current track.
Calls PlaybackController.get_state(), and if state is PLAYING or PAUSED, get
PlaybackController.get_current_track() and
PlaybackController.get_time_position()'''
server =... | def state() | Get The playback state: 'playing', 'paused', or 'stopped'.
If PLAYING or PAUSED, show information on current track.
Calls PlaybackController.get_state(), and if state is PLAYING or PAUSED, get
PlaybackController.get_current_track() and
PlaybackController.get_time_position() | 4.816769 | 2.860968 | 1.683615 |
'''Pause playback.
Calls PlaybackController.pause()'''
server = getServer()
server.core.playback.pause()
pos = server.core.playback.get_time_position()
print('Paused at {}'.format(formatTimeposition(pos))) | def pause() | Pause playback.
Calls PlaybackController.pause() | 8.416559 | 6.913816 | 1.217354 |
'''Get tracklist
Calls TracklistController.get_tl_tracks()
'''
_c = 0
server = getServer()
_current = server.core.tracklist.index()
for t in server.core.tracklist.get_tl_tracks():
logging.debug('Got tl trak: %r', t)
currently = ' -- CURRENT' if t['tlid'] == _current else ''
... | def tracklist() | Get tracklist
Calls TracklistController.get_tl_tracks() | 6.338813 | 5.206286 | 1.217531 |
'''Get album or track from backend uri and play all tracks found.
uri is a string which represents some directory belonging to a backend.
Calls LibraryController.browse(uri) to get an album and LibraryController.lookup(uri)
to get track'''
if argv is None:
argv = sys.argv[1:]
parser =... | def play_backend_uri(argv=None) | Get album or track from backend uri and play all tracks found.
uri is a string which represents some directory belonging to a backend.
Calls LibraryController.browse(uri) to get an album and LibraryController.lookup(uri)
to get track | 4.716668 | 3.262092 | 1.445903 |
'''Returns `default` is there is no subsequent item'''
try:
result = self.pointer.next()
# immediately push it back onto the front of the iterable
self.pointer = itertools.chain([result], self.pointer)
return result
except StopIteration:
... | def peek(self, default=None) | Returns `default` is there is no subsequent item | 9.760873 | 7.525982 | 1.296957 |
try:
equiv_class = atom.number + \
1000*(atom.charge+10) + \
100000*(atom.hcount) + \
1000000*(atom.weight)
except TypeError:
raise ValueError, \
"Can't compute number from atom.number %s atom.charge %s atom... | def compute_equiv_class(atom) | (atom)->Computes a unique integer for an atom | 3.13798 | 3.135001 | 1.00095 |
if not self._token:
self._token = self.fetch_token()
logger.payment(self)
return self._token | def token(self) | Token given by Transbank for payment initialization url.
Will raise PaymentError when an error ocurred. | 7.948765 | 7.284288 | 1.091221 |
if not self._transaction_id:
self._transaction_id = random.randint(0, 10000000000 - 1)
return self._transaction_id | def transaction_id(self) | Transaction ID for Transbank, a secure random int between 0 and 999999999. | 2.790823 | 2.398 | 1.163813 |
if any(self.m1 < 0.0):
raise ValueError("Mass 1 is negative.")
if any(self.m2 < 0.0):
raise ValueError("Mass 2 is negative.")
if any(self.chi_1 < -1.0) or any(self.chi_1 > 1.0):
raise ValueError("Chi 1 is outside [-1.0, 1.0].")
if any(self.c... | def _sanity_check(self) | Check if parameters are okay.
Sanity check makes sure each parameter is within an allowable range.
Raises:
ValueError: Problem with a specific parameter. | 2.005541 | 1.994143 | 1.005716 |
del local_dict['self']
self.remove_axis = False
max_length = 0
for key in local_dict:
try:
length = len(local_dict[key])
if length > max_length:
max_length = length
except TypeError:
pas... | def _broadcast_and_set_attrs(self, local_dict) | Cast all inputs to correct dimensions.
This method fixes inputs who have different lengths. Namely one input as
an array and others that are scalara or of len-1.
Raises:
Value Error: Multiple length arrays of len>1 | 2.797058 | 2.676183 | 1.045167 |
c_obj = ctypes.CDLL(self.exec_call)
# prepare ctypes arrays
freq_amp_cast = ctypes.c_double*self.num_points*self.length
freqs = freq_amp_cast()
hc = freq_amp_cast()
fmrg_fpeak_cast = ctypes.c_double*self.length
fmrg = fmrg_fpeak_cast()
fpeak = ... | def _create_waveforms(self) | Create frequency domain waveforms.
Method to create waveforms for PhenomDWaveforms class.
It adds waveform information in the form of attributes. | 2.385311 | 2.375455 | 1.004149 |
if any(self.m1 < 0.0):
raise ValueError("Mass 1 is negative.")
if any(self.m2 < 0.0):
raise ValueError("Mass 2 is negative.")
if any(self.z <= 0.0):
raise ValueError("Redshift is zero or negative.")
if any(self.dist <= 0.0):
rais... | def _sanity_check(self) | Check if parameters are okay.
Sanity check makes sure each parameter is within an allowable range.
Raises:
ValueError: Problem with a specific parameter. | 2.767953 | 2.704129 | 1.023602 |
self.m1 = self.m1*M_sun*ct.G/ct.c**2
self.m2 = self.m2*M_sun*ct.G/ct.c**2
initial_cond_type_conversion = {
'time': ct.c*ct.Julian_year,
'frequency': 1./ct.c,
'separation': ct.parsec,
}
self.initial_point = self.initial_point*initial_c... | def _convert_units(self) | Convert units to geometrized units.
Change to G=c=1 (geometrized) units for ease in calculations. | 4.152654 | 4.01686 | 1.033806 |
if ef is None:
ef = np.ones_like(self.e0)*0.0000001
beta = 64.0/5.0*self.m1*self.m2*(self.m1+self.m2)
e_vals = np.asarray([np.linspace(ef[i], self.e0[i], self.num_points)
for i in range(len(self.e0))])
integrand = self._find_integrand(e_... | def _t_of_e(self, a0=None, t_start=None, f0=None, ef=None, t_obs=5.0) | Rearranged versions of Peters equations
This function calculates the semi-major axis and eccentricity over time. | 3.96496 | 3.963619 | 1.000338 |
return (self.m1*self.m2)**(3./5.)/(self.m1+self.m2)**(1./5.) | def _chirp_mass(self) | Chirp mass calculation | 3.833218 | 3.551988 | 1.079175 |
return (self.n**4./32.
* ((jv(self.n-2., self.n*self.e_vals)
- 2. * self.e_vals*jv(self.n-1., self.n*self.e_vals)
+ 2./self.n * jv(self.n, self.n*self.e_vals)
+ 2.*self.e_vals*jv(self.n+1., self.n*self.e_vals)
-... | def _g_func(self) | Eq. 20 in Peters and Mathews 1963. | 2.384321 | 2.303819 | 1.034943 |
Mc = self._chirp_mass()
return (np.pi**(2./3.)*Mc**(5./3.)/(3.*(1.+self.z)**(1./3.)
* (self.freqs_orb/(1.+self.z))**(1./3.))*(2./self.n)**(2./3.)
* self._g_func()/self._f_func()) | def _dEndfr(self) | Eq. 4 from Orazio and Samsing (2018)
Takes f in rest frame. | 8.451419 | 7.798541 | 1.083718 |
self.hc = 1./(np.pi*self.dist)*np.sqrt(2.*self._dEndfr())
return | def _hcn_func(self) | Eq. 56 from Barack and Cutler 2004 | 21.412888 | 16.98126 | 1.260972 |
# find eccentricity and semi major axis over time until e=0.
e_vals, a_vals, t_vals = self._t_of_e(a0=self.a0, f0=self.f0,
t_start=self.t_start, ef=None,
t_obs=self.t_obs)
f_mrg = 0.02/(self.m1... | def _create_waveforms(self) | Create the eccentric waveforms | 3.934897 | 3.868779 | 1.01709 |
codons = pyvolve.genetics.Genetics().codons
codon_dict = pyvolve.genetics.Genetics().codon_dict
pyrims = pyvolve.genetics.Genetics().pyrims
purines = pyvolve.genetics.Genetics().purines
if divselection:
(divomega, divsites) = divselection
else:
divsites = []
assert all... | def pyvolvePartitions(model, divselection=None) | Get list of `pyvolve` partitions for `model`.
Args:
`model` (`phydmslib.models.Models` object)
The model used for the simulations. Currently only
certain `Models` are supported (e.g., `YNGKP`,
`ExpCM`)
`divselection` (`None` or 2-tuple `(divomega, divsites)`)
... | 3.92224 | 3.553881 | 1.10365 |
if randomSeed == False:
pass
else:
random.seed(randomSeed)
#Transform the branch lengths by dividing by the model `branchScale`
tree = Bio.Phylo.read(treeFile, 'newick')
for node in tree.get_terminals() + tree.get_nonterminals():
if (node.branch_length == None) and (nod... | def simulateAlignment(model, treeFile, alignmentPrefix, randomSeed=False) | Simulate an alignment given a model and tree (units = subs/site).
Simulations done using `pyvolve`.
Args:
`model` (`phydmslib.models.Models` object)
The model used for the simulations. Only
models that can be passed to `pyvolve.Partitions`
are supported.
`tr... | 3.816782 | 3.604018 | 1.059035 |
if oracle_type == 'f':
return FO(**kwargs)
elif oracle_type == 'a':
return MO(**kwargs)
else:
return MO(**kwargs) | def _create_oracle(oracle_type, **kwargs) | A routine for creating a factor oracle. | 4.847469 | 4.715704 | 1.027942 |
if not self.seg:
j = 0
else:
j = self.seg[-1][1]
last_len = self.seg[-1][0]
if last_len + j > self.n_states:
return
i = j
while j < self.n_states - 1:
while not (not (i < self.n_states - 1) or not (sel... | def segment(self) | An non-overlap version Compror | 2.571837 | 2.521857 | 1.019819 |
code, _ = self.encode()
N = self.n_states
BL = np.zeros(N - 1) # BL is the block length of compror codewords
h0 = np.log2(np.cumsum(
[1.0 if sfx == 0 else 0.0 for sfx in self.sfx[1:]])
)
h1 = np.array([np.log2(i + 1) if m == 0 else np.log2(i + 1) +... | def _ir_cum2(self, alpha=1.0) | h1 = np.array([h if m == 0 else h+np.log2(m)
for h,m in zip(h0,self.lrs[1:])])
h1 = np.array([h if m == 0 else h+np.log2(m)
for h,m in zip(h0,self.max_lrs[1:])])
h1 = np.array([h if m == 0 else h+np.log2(m)
for h,m in zip(h0,self.av... | 4.926284 | 4.313406 | 1.142087 |
_next = 0
for _s in context:
_data = [self.data[j] for j in self.trn[_next]]
if _s in _data:
_next = self.trn[_next][_data.index(_s)]
else:
return 0, _next
return 1, _next | def accept(self, context) | Check if the context could be accepted by the oracle
Args:
context: s sequence same type as the oracle data
Returns:
bAccepted: whether the sequence is accepted or not
_next: the state where the sequence is accepted | 5.486325 | 4.407499 | 1.244771 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.