code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
assert_corofunction(coro=coro) assert_iter(iterable=iterable) # By default do not collect yielded values from coroutines results = None if collect: # Store ordered results results = [None] * len(iterable) # Create concurrent executor pool = ConcurrentExecutor(limit=li...
def each(coro, iterable, limit=0, loop=None, collect=False, timeout=None, return_exceptions=False, *args, **kw)
Concurrently iterates values yielded from an iterable, passing them to an asynchronous coroutine. You can optionally collect yielded values passing collect=True param, which would be equivalent to `paco.map()``. Mapped values will be returned as an ordered list. Items order is preserved based on o...
4.356294
5.17546
0.841721
# support to be called as @log or as @log(name='') if func is None: return functools.partial(log, name=name, timing=timing, timestamp=timestamp) @functools.wraps(func) def decorated(*args, **kwargs): assert len(args) > 0 and hasattr(args[0], 'log'),...
def log(func=None, name=None, timing=True, timestamp=False)
Decorator to show a description of the running function By default, it outputs the first line of the docstring. If the docstring is empty, it displays the name of the function. Alternatively, if a ``name`` is specified, it will display that only. It can be called as ``@log`` or as ``@log(name='abc...
2.481161
2.723773
0.910928
@asyncio.coroutine def coro(): if delay: yield from asyncio.sleep(delay) return value return coro
def constant(value, delay=None)
Returns a coroutine function that when called, always returns the provided value. This function has an alias: `paco.identity`. Arguments: value (mixed): value to constantly return when coroutine is called. delay (int/float): optional return value delay in seconds. Returns: cor...
4.394229
5.483666
0.801331
drop = False @asyncio.coroutine def assert_fn(element): nonlocal drop if element and not drop: return False if not element and not drop: drop = True return True if drop else element @asyncio.coroutine def filter_fn(element): r...
def dropwhile(coro, iterable, loop=None)
Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce any output until the predicate first becomes false, so it may have a lengthy start-up time. This function is pretty much equivalent to Python ...
4.164225
6.86101
0.606941
try: ref_id, __, __ = ctx.env['ir.model.data'].xmlid_lookup(xmlid) except ValueError: pass # does not exist, we'll create a new one else: return ctx.env['ir.model.data'].browse(ref_id) if '.' in xmlid: module, name = xmlid.split('.') else: module = '' ...
def add_xmlid(ctx, record, xmlid, noupdate=False)
Add a XMLID on an existing record
2.546124
2.613231
0.97432
if isinstance(model, basestring): model = ctx.env[model] record = ctx.env.ref(xmlid, raise_if_not_found=False) if record: record.update(values) else: record = model.create(values) add_xmlid(ctx, record, xmlid) return record
def create_or_update(ctx, model, xmlid, values)
Create or update a record matching xmlid with values
2.483038
2.360329
1.051988
if isinstance(item, basestring): return ctx.env.ref(item) return item
def safe_record(ctx, item)
Make sure we get a record instance even if we pass an xmlid.
7.207747
3.954801
1.822531
current_company = ctx.env.user.company_id ctx.env.user.company_id = safe_record(ctx, company) yield ctx ctx.env.user.company_id = current_company
def switch_company(ctx, company)
Context manager to switch current company. Accepts both company record and xmlid.
4.950728
4.372004
1.132371
assert_corofunction(coro=coro) @asyncio.coroutine def wrapper(*_args, **_kw): # Explicitely ignore wrapper arguments return (yield from coro(*args, **kw)) return wrapper
def apply(coro, *args, **kw)
Creates a continuation coroutine function with some arguments already applied. Useful as a shorthand when combined with other control flow functions. Any arguments passed to the returned function are added to the arguments originally passed to apply. This is similar to `paco.partial()`. This ...
6.609609
13.997436
0.472201
loop = loop or asyncio.get_event_loop() return loop.run_until_complete(coro)
def run(coro, loop=None)
Convenient shortcut alias to ``loop.run_until_complete``. Arguments: coro (coroutine): coroutine object to schedule. loop (asyncio.BaseEventLoop): optional event loop to use. Defaults to: ``asyncio.get_event_loop()``. Returns: mixed: returned value by coroutine. Usage:...
2.165262
4.48938
0.482307
if node is None: node = self.ast try: first = iter(node) except TypeError: first = None if first: for kid in node: self.postorder(kid) try: name = 'n_' + self.typestring(node) if h...
def postorder(self, node=None)
Walk the tree in roughly 'postorder' (a bit of a lie explained below). For each node with typestring name *name* if the node has a method called n_*name*, call that before walking children. If there is no method define, call a self.default(node) instead. Subclasses of GenericAST...
3.288426
2.679153
1.227412
' expr ::= expr ADD_OP term ' op = 'add' if args[1].attr == '+' else 'subtract' return AST(op, [args[0], args[2]])
def p_expr_add_term(self, args)
expr ::= expr ADD_OP term
7.782492
5.725553
1.359256
' term ::= term MULT_OP factor ' op = 'multiply' if args[1].attr == '*' else 'divide' return AST(op, [args[0], args[2]])
def p_term_mult_factor(self, args)
term ::= term MULT_OP factor
8.639663
6.160552
1.402417
# Support iterable as first argument for better interoperability if len(coros_or_futures) == 1 and isiter(coros_or_futures[0]): coros_or_futures = coros_or_futures[0] # If no coroutines to schedule, return empty list # Mimics asyncio behaviour. if len(coros_or_futures) == 0: ra...
def wait(*coros_or_futures, limit=0, timeout=None, loop=None, return_exceptions=False, return_when='ALL_COMPLETED')
Wait for the Futures and coroutine objects given by the sequence futures to complete, with optional concurrency limit. Coroutines will be wrapped in Tasks. ``timeout`` can be used to control the maximum number of seconds to wait before returning. timeout can be an int or float. If timeout is not sp...
4.085247
4.557693
0.896341
self._attributes[attrib.key()] = attrib req = attrib.ledgerRequest() if req: self.pendRequest(req, attrib.key()) return len(self._pending)
def addAttribute(self, attrib: Attribute)
Used to create a new attribute on Sovrin :param attrib: attribute to add :return: number of pending txns
10.218151
7.312565
1.397342
self._nodes[node.id] = node req = node.ledgerRequest() if req: self.pendRequest(req, node.id) return len(self._pending)
def addNode(self, node: Node)
Used to add a new node on Sovrin :param node: Node :return: number of pending txns
9.295663
6.455621
1.439933
key = upgrade.key self._upgrades[key] = upgrade req = upgrade.ledgerRequest() if req: self.pendRequest(req, key) return len(self._pending)
def doPoolUpgrade(self, upgrade: Upgrade)
Used to send a new code upgrade :param upgrade: upgrade data :return: number of pending txns
9.584585
8.251248
1.161592
preparedReq = self._prepared.get((result[IDENTIFIER], reqId)) if not preparedReq: raise RuntimeError('no matching prepared value for {},{}'. format(result[IDENTIFIER], reqId)) typ = result.get(TXN_TYPE) if typ and typ in self.replyHandl...
def handleIncomingReply(self, observer_name, reqId, frm, result, numReplies)
Called by an external entity, like a Client, to notify of incoming replies :return:
7.363848
7.651556
0.962399
self._attributes[attrib.key()] = attrib req = attrib.getRequest(sender) if req: return self.prepReq(req, key=attrib.key())
def requestAttribute(self, attrib: Attribute, sender)
Used to get a raw attribute from Sovrin :param attrib: attribute to add :return: number of pending txns
8.405985
7.748954
1.08479
operation = { TARGET_NYM: nym, TXN_TYPE: GET_SCHEMA, DATA: {NAME : name, VERSION: version} } req = Request(sender, operation=operation) return self.prepReq(req)
def requestSchema(self, nym, name, version, sender)
Used to get a schema from Sovrin :param nym: nym that schema is attached to :param name: name of schema :param version: version of schema :return: req object
5.471467
6.942295
0.788135
operation = { TXN_TYPE: GET_CLAIM_DEF, ORIGIN: sender, REF : seqNo, SIGNATURE_TYPE : signature } req = Request(sender, operation=operation) return self.prepReq(req)
def requestClaimDef(self, seqNo, signature, sender)
Used to get a claim def from Sovrin :param seqNo: reference number of schema :param signature: CL is only supported option currently :return: req object
6.626809
7.736636
0.856549
r'(?:[^*-+,\d\'"\t \n:][^\'"\t \n:,]*)|(?:^)|(?:\'\'\'.+\'\'\')' maybe_funcname = True if s == 'if': self.add_token('IF', s) return if s[0] in frozenset(('"', "'")): # Pick out text inside of triple-quoted string if ( (s.startswith("'''") a...
def t_file_or_func(self, s)
r'(?:[^*-+,\d\'"\t \n:][^\'"\t \n:,]*)|(?:^""".+""")|(?:\'\'\'.+\'\'\')
5.334224
3.793641
1.406096
return (yield from gather(*coros_or_futures, loop=loop, limit=1, timeout=timeout, return_exceptions=return_exceptions))
def series(*coros_or_futures, timeout=None, loop=None, return_exceptions=False)
Run the given coroutine functions in series, each one running once the previous execution has completed. If any coroutines raises an exception, no more coroutines are executed. Otherwise, the coroutines returned values will be returned as `list`. ``timeout`` can be used to control the maximum numb...
3.665311
9.653315
0.379695
assert_corofunction(coro=coro) # Iterate and attach coroutine for defer scheduling times = max(int(times), 1) iterable = range(1, times + 1, step) # Run iterable times return (yield from map(coro, iterable, limit=limit, loop=loop))
def repeat(coro, times=1, step=1, limit=1, loop=None)
Executes the coroutine function ``x`` number of times, and accumulates results in order as you would use with ``map``. Execution concurrency is configurable using ``limit`` param. This function is a coroutine. Arguments: coro (coroutinefunction): coroutine function to schedule. times...
9.622971
14.95928
0.643278
return times(coro, limit=1, return_value=return_value, raise_exception=raise_exception)
def once(coro, raise_exception=False, return_value=None)
Wrap a given coroutine function that is restricted to one execution. Repeated calls to the coroutine function will return the value of the first invocation. This function can be used as decorator. arguments: coro (coroutinefunction): coroutine function to wrap. raise_exception (bool):...
4.617881
11.144543
0.414363
assert_corofunction(coro=coro) @asyncio.coroutine def wrapper(*args, **kw): # Wait until we're done yield from asyncio.sleep(delay) return (yield from coro(*args, **kw)) return wrapper
def defer(coro, delay=1)
Returns a coroutine function wrapper that will defer the given coroutine execution for a certain amount of seconds in a non-blocking way. This function can be used as decorator. Arguments: coro (coroutinefunction): coroutine function to defer. delay (int/float): number of seconds to defer ...
4.431809
6.601115
0.671373
try: result = yield from coro except Exception as err: if return_exceptions: result = err else: raise err return result
def safe_run(coro, return_exceptions=False)
Executes a given coroutine and optionally catches exceptions, returning them as value. This function is intended to be used internally.
2.620489
2.693043
0.973059
result = yield from safe_run(coro, return_exceptions=return_exceptions) if preserve_order: results[index] = result else: results.append(result)
def collect(coro, index, results, preserve_order=False, return_exceptions=False)
Collect is used internally to execute coroutines and collect the returned value. This function is intended to be used internally.
3.183517
4.012632
0.793374
if self.running: raise RuntimeError('paco: executor is still running') self.pool.clear() self.observer.clear() self.semaphore = asyncio.Semaphore(self.limit, loop=self.loop)
def reset(self)
Resets the executer scheduler internal state. Raises: RuntimeError: is the executor is still running.
8.458581
6.464161
1.308535
# Create coroutine object if a function is provided if asyncio.iscoroutinefunction(coro): coro = coro(*args, **kw) # Verify coroutine if not asyncio.iscoroutine(coro): raise TypeError('paco: coro must be a coroutine object') # Store coroutine wi...
def add(self, coro, *args, **kw)
Adds a new coroutine function with optional variadic argumetns. Arguments: coro (coroutine function): coroutine to execute. *args (mixed): optional variadic arguments Raises: TypeError: if the coro object is not a valid coroutine Returns: future...
4.944863
5.406592
0.914599
# Only allow 1 concurrent execution if self.running: raise RuntimeError('paco: executor is already running') # Overwrite ignore empty behaviour, if explicitly defined ignore_empty = (self.ignore_empty if ignore_empty is None else ignore_empty...
def run(self, timeout=None, return_when=None, return_exceptions=None, ignore_empty=None)
Executes the registered coroutines in the executor queue. Arguments: timeout (int/float): max execution timeout. No limit by default. return_exceptions (bool): in case of coroutine exception. return_when (str): sets when coroutine should be resolved. See `asy...
3.866819
3.578841
1.080467
index = np.where(self.intervals == interval) if index[0][0] + 1 < len(self.intervals): return self.intervals[index[0][0] + 1] else: raise IndexError("Ran out of intervals!")
def next_interval(self, interval)
Given a value of an interval, this function returns the next interval value
2.826914
2.645027
1.068765
thresh_range = 25 # in cents if interval < self.intervals[0] - thresh_range or interval > self.intervals[-1] + thresh_range: raise IndexError("The interval given is beyond " + str(thresh_range) + " cents over the range of intervals defined.") i...
def nearest_interval(self, interval)
This function returns the nearest interval to any given interval.
5.072795
4.623038
1.097286
from scipy.optimize import minimize_scalar wrapper = BranchLengthOptimiser(node1, node2, (min_brlen + max_brlen) / 2.) n = minimize_scalar(lambda x: -wrapper(x)[0], method='brent', bracket=(min_brlen, max_brlen))['x'] if verbose: logger.info(wrapper) if n < min_brlen: n = min_br...
def brent_optimise(node1, node2, min_brlen=0.001, max_brlen=10, verbose=False)
Optimise ML distance between two partials. min and max set brackets
4.203876
4.431161
0.948708
# Check if not isinstance(subs_model, phylo_utils.models.Model): raise ValueError("Can't handle this model: {}".format(model)) if alpha is None: alpha = 1.0 ncat = 1 # Set up markov model tm = TransitionMatrix(subs_model) gamma_rates = discrete_gamma(alpha, ncat)...
def pairdists(alignment, subs_model, alpha=None, ncat=4, tolerance=1e-6, verbose=False)
Load an alignment, calculate all pairwise distances and variances model parameter must be a Substitution model type from phylo_utils
4.213477
4.063628
1.036876
if file_format == 'phylip': file_format = 'phylip-relaxed' AlignIO.write(self._msa, filename, file_format)
def write_alignment(self, filename, file_format, interleaved=None)
Write the alignment to file using Bio.AlignIO
3.536375
3.356484
1.053595
return pairdists(self, model, alpha, ncat, tolerance)
def compute_distances(self, model, alpha=None, ncat=4, tolerance=1e-6)
Compute pairwise distances between all sequences according to a given substitution model, `model`, of type phylo_utils.models.Model (e.g. phylo_utils.models.WAG(freqs), phylo_utils.models.GTR(rates, freqs)) The number of gamma categories is controlled by `ncat`. Setting ncat=1 disable ga...
12.596115
11.977674
1.051633
sim = SequenceSimulator(transition_matrix, tree, ncat, alpha) return list(sim.simulate(nsites).items())
def simulate(self, nsites, transition_matrix, tree, ncat=1, alpha=1)
Return sequences simulated under the transition matrix's model
5.59402
4.863371
1.150235
new_sites = sorted(sample_wr(self.get_sites())) seqs = list(zip(self.get_names(), (''.join(seq) for seq in zip(*new_sites)))) return self.__class__(seqs)
def bootstrap(self)
Return a new Alignment that is a bootstrap replicate of self
9.469711
7.472357
1.267299
self.tree._tree.seed_node.states = self.ancestral_states(n) categories = np.random.randint(self.ncat, size=n).astype(np.intc) for node in self.tree.preorder(skip_seed=True): node.states = self.evolve_states(node.parent_node.states, categories, node.pmats) if nod...
def simulate(self, n)
Evolve multiple sites during one tree traversal
6.677332
6.117321
1.091545
anc = np.empty(n, dtype=np.intc) _weighted_choices(self.state_indices, self.freqs, anc) return anc
def ancestral_states(self, n)
Generate ancestral sequence states from the equilibrium frequencies
8.466296
7.868501
1.075973
child_states = np.empty(parent_states.shape, dtype=np.intc) _evolve_states(self.state_indices, parent_states, categories, probs, child_states) return child_states
def evolve_states(self, parent_states, categories, probs)
Evolve states from parent to child. States are sampled from gamma categories passed in the array 'categories'. The branch length information is encoded in the probability matrix, 'probs', generated in __init__.
3.182057
3.506192
0.907554
return {k: ''.join(self.states[v]) for (k, v) in self.sequences.items()}
def sequences_to_string(self)
Convert state indices to a string of characters
6.315647
4.74504
1.331
crc = sum(bytearray(binascii.unhexlify(hexstr))) crc &= 0xff crc ^= 0xff return crc
def crc_srec(hexstr)
Calculate the CRC for given Motorola S-Record hexstring.
4.766581
4.130068
1.154117
crc = sum(bytearray(binascii.unhexlify(hexstr))) crc &= 0xff crc = ((~crc + 1) & 0xff) return crc
def crc_ihex(hexstr)
Calculate the CRC for given Intel HEX hexstring.
3.950607
3.685122
1.072042
if type_ in '0159': line = '{:02X}{:04X}'.format(size + 2 + 1, address) elif type_ in '268': line = '{:02X}{:06X}'.format(size + 3 + 1, address) elif type_ in '37': line = '{:02X}{:08X}'.format(size + 4 + 1, address) else: raise Error( "expected record t...
def pack_srec(type_, address, size, data)
Create a Motorola S-Record record of given data.
3.335681
3.235907
1.030833
# Minimum STSSCC, where T is type, SS is size and CC is crc. if len(record) < 6: raise Error("record '{}' too short".format(record)) if record[0] != 'S': raise Error( "record '{}' not starting with an 'S'".format(record)) size = int(record[2:4], 16) type_ = record...
def unpack_srec(record)
Unpack given Motorola S-Record record into variables.
3.376647
3.301668
1.022709
line = '{:02X}{:04X}{:02X}'.format(size, address, type_) if data: line += binascii.hexlify(data).decode('ascii').upper() return ':{}{:02X}'.format(line, crc_ihex(line))
def pack_ihex(type_, address, size, data)
Create a Intel HEX record of given data.
3.989164
3.65073
1.092703
# Minimum :SSAAAATTCC, where SS is size, AAAA is address, TT is # type and CC is crc. if len(record) < 11: raise Error("record '{}' too short".format(record)) if record[0] != ':': raise Error("record '{}' not starting with a ':'".format(record)) size = int(record[1:3], 16) ...
def unpack_ihex(record)
Unpack given Intel HEX record into variables.
2.762817
2.693233
1.025837
if (size % alignment) != 0: raise Error( 'size {} is not a multiple of alignment {}'.format( size, alignment)) address = self.address data = self.data # First chunk may be shorter than `size` due to alignment...
def chunks(self, size=32, alignment=1)
Return chunks of the data aligned as given by `alignment`. `size` must be a multiple of `alignment`. Each chunk is returned as a named two-tuple of its address and data.
2.719823
2.560642
1.062165
if minimum_address == self.maximum_address: self.maximum_address = maximum_address self.data += data elif maximum_address == self.minimum_address: self.minimum_address = minimum_address self.data = data + self.data elif (overwrite ...
def add_data(self, minimum_address, maximum_address, data, overwrite)
Add given data to this segment. The added data must be adjacent to the current segment data, otherwise an exception is thrown.
2.289246
2.229012
1.027023
if ((minimum_address >= self.maximum_address) and (maximum_address <= self.minimum_address)): raise Error('cannot remove data that is not part of the segment') if minimum_address < self.minimum_address: minimum_address = self.minimum_address if max...
def remove_data(self, minimum_address, maximum_address)
Remove given data range from this segment. Returns the second segment if the removed data splits this segment in two.
2.177845
2.09087
1.041598
if self._list: if segment.minimum_address == self._current_segment.maximum_address: # Fast insertion for adjacent segments. self._current_segment.add_data(segment.minimum_address, segment.maximum_address, ...
def add(self, segment, overwrite=False)
Add segments by ascending address.
2.423495
2.36181
1.026118
if (size % alignment) != 0: raise Error( 'size {} is not a multiple of alignment {}'.format( size, alignment)) for segment in self: for chunk in segment.chunks(size, alignment): yield chunk
def chunks(self, size=32, alignment=1)
Iterate over all segments and return chunks of the data aligned as given by `alignment`. `size` must be a multiple of `alignment`. Each chunk is returned as a named two-tuple of its address and data.
3.796636
3.642572
1.042295
minimum_address = self._segments.minimum_address if minimum_address is not None: minimum_address //= self.word_size_bytes return minimum_address
def minimum_address(self)
The minimum address of the data, or ``None`` if the file is empty.
6.9431
5.249458
1.322632
maximum_address = self._segments.maximum_address if maximum_address is not None: maximum_address //= self.word_size_bytes return maximum_address
def maximum_address(self)
The maximum address of the data, or ``None`` if the file is empty.
6.724765
5.134224
1.309792
if self._header_encoding is None: return self._header else: return self._header.decode(self._header_encoding)
def header(self)
The binary file header, or ``None`` if missing. See :class:`BinFile's<.BinFile>` `header_encoding` argument for encoding options.
4.736759
2.806184
1.687972
if is_srec(data): self.add_srec(data, overwrite) elif is_ihex(data): self.add_ihex(data, overwrite) elif is_ti_txt(data): self.add_ti_txt(data, overwrite) else: raise UnsupportedFileFormatError()
def add(self, data, overwrite=False)
Add given data string by guessing its format. The format must be Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to ``True`` to allow already added data to be overwritten.
3.30816
2.204879
1.500382
for record in StringIO(records): type_, address, size, data = unpack_srec(record.strip()) if type_ == '0': self._header = data elif type_ in '123': address *= self.word_size_bytes self._segments.add(_Segment(address, ...
def add_srec(self, records, overwrite=False)
Add given Motorola S-Records string. Set `overwrite` to ``True`` to allow already added data to be overwritten.
5.722971
5.687747
1.006193
extended_segment_address = 0 extended_linear_address = 0 for record in StringIO(records): type_, address, size, data = unpack_ihex(record.strip()) if type_ == IHEX_DATA: address = (address + extended_segment_address ...
def add_ihex(self, records, overwrite=False)
Add given Intel HEX records string. Set `overwrite` to ``True`` to allow already added data to be overwritten.
2.978078
2.885563
1.032062
address = None eof_found = False for line in StringIO(lines): # Abort if data is found after end of file. if eof_found: raise Error("bad file terminator") line = line.strip() if len(line) < 1: raise Erro...
def add_ti_txt(self, lines, overwrite=False)
Add given TI-TXT string `lines`. Set `overwrite` to ``True`` to allow already added data to be overwritten.
3.600513
3.576155
1.006811
address *= self.word_size_bytes self._segments.add(_Segment(address, address + len(data), bytearray(data), self.word_size_bytes), overwrite)
def add_binary(self, data, address=0, overwrite=False)
Add given data at given address. Set `overwrite` to ``True`` to allow already added data to be overwritten.
7.849534
7.908025
0.992604
with open(filename, 'r') as fin: self.add(fin.read(), overwrite)
def add_file(self, filename, overwrite=False)
Open given file and add its data by guessing its format. The format must be Motorola S-Records, Intel HEX or TI-TXT. Set `overwrite` to ``True`` to allow already added data to be overwritten.
5.097096
4.361952
1.168536
with open(filename, 'r') as fin: self.add_srec(fin.read(), overwrite)
def add_srec_file(self, filename, overwrite=False)
Open given Motorola S-Records file and add its records. Set `overwrite` to ``True`` to allow already added data to be overwritten.
3.866007
4.030815
0.959113
with open(filename, 'r') as fin: self.add_ihex(fin.read(), overwrite)
def add_ihex_file(self, filename, overwrite=False)
Open given Intel HEX file and add its records. Set `overwrite` to ``True`` to allow already added data to be overwritten.
3.907865
4.029337
0.969853
with open(filename, 'r') as fin: self.add_ti_txt(fin.read(), overwrite)
def add_ti_txt_file(self, filename, overwrite=False)
Open given TI-TXT file and add its contents. Set `overwrite` to ``True`` to allow already added data to be overwritten.
3.714243
3.458357
1.073991
with open(filename, 'rb') as fin: self.add_binary(fin.read(), address, overwrite)
def add_binary_file(self, filename, address=0, overwrite=False)
Open given binary file and add its contents. Set `overwrite` to ``True`` to allow already added data to be overwritten.
3.589727
3.425102
1.048064
header = [] if self._header is not None: record = pack_srec('0', 0, len(self._header), self._header) header.append(record) type_ = str((address_length_bits // 8) - 1) if type_ not in '123': raise Error("expected data record type 1..3, but ...
def as_srec(self, number_of_data_bytes=32, address_length_bits=32)
Format the binary file as Motorola S-Records records and return them as a string. `number_of_data_bytes` is the number of data bytes in each record. `address_length_bits` is the number of address bits in each record. >>> print(binfile.as_srec()) S32500000100214...
2.635052
2.712366
0.971496
lines = [] for segment in self._segments: lines.append('@{:04X}'.format(segment.address)) for _, data in segment.chunks(TI_TXT_BYTES_PER_LINE): lines.append(' '.join('{:02X}'.format(byte) for byte in data)) lines.append('q') return '\...
def as_ti_txt(self)
Format the binary file as a TI-TXT file and return it as a string. >>> print(binfile.as_ti_txt()) @0100 21 46 01 36 01 21 47 01 36 00 7E FE 09 D2 19 01 21 46 01 7E 17 C2 00 01 FF 5F 16 00 21 48 01 19 19 4E 79 23 46 23 96 57 78 23 9E DA 3F 01 B2 CA 3F 01 56 70 2B 5E 71 2B...
4.509809
3.835457
1.175821
if len(self._segments) == 0: return b'' if minimum_address is None: current_maximum_address = self.minimum_address else: current_maximum_address = minimum_address if maximum_address is None: maximum_address = self.maximum_addres...
def as_binary(self, minimum_address=None, maximum_address=None, padding=None)
Return a byte string of all data within given address range. `minimum_address` is the absolute minimum address of the resulting binary data. `maximum_address` is the absolute maximum address of the resulting binary data (non-inclusive). `padding` is the word value of the paddi...
1.939213
1.937956
1.000648
binary_data = self.as_binary(minimum_address, padding=padding) words = [] for offset in range(0, len(binary_data), self.word_size_bytes): word = 0 for byte in binary_data[offset:offset + self.word_size_bytes]: ...
def as_array(self, minimum_address=None, padding=None, separator=', ')
Format the binary file as a string values separated by given separator `separator`. This function can be used to generate array initialization code for C and other languages. `minimum_address` is the start address of the resulting binary data. `padding` is the value of the padd...
2.599132
2.882059
0.901832
# Empty file? if len(self) == 0: return '\n' non_dot_characters = set(string.printable) non_dot_characters -= set(string.whitespace) non_dot_characters |= set(' ') def align16(address): return address - (address % 16) def paddi...
def as_hexdump(self)
Format the binary file as a hexdump and return it as a string. >>> print(binfile.as_hexdump()) 00000100 21 46 01 36 01 21 47 01 36 00 7e fe 09 d2 19 01 |!F.6.!G.6.~.....| 00000110 21 46 01 7e 17 c2 00 01 ff 5f 16 00 21 48 01 19 |!F.~....._..!H..| 00000120 19 4e 79 23 46 23 96 57 ...
2.578632
2.525588
1.021003
previous_segment_maximum_address = None fill_segments = [] for address, data in self._segments: maximum_address = address + len(data) if previous_segment_maximum_address is not None: fill_size = address - previous_segment_maximum_address ...
def fill(self, value=b'\xff')
Fill all empty space between segments with given value `value`.
2.858057
2.655313
1.076354
if maximum_address < minimum_address: raise Error('bad address range') minimum_address *= self.word_size_bytes maximum_address *= self.word_size_bytes self._segments.remove(minimum_address, maximum_address)
def exclude(self, minimum_address, maximum_address)
Exclude given range and keep the rest. `minimum_address` is the first word address to exclude (including). `maximum_address` is the last word address to exclude (excluding).
4.048999
4.112216
0.984627
minimum_address *= self.word_size_bytes maximum_address *= self.word_size_bytes maximum_address_address = self._segments.maximum_address self._segments.remove(0, minimum_address) self._segments.remove(maximum_address, maximum_address_address)
def crop(self, minimum_address, maximum_address)
Keep given range and discard the rest. `minimum_address` is the first word address to keep (including). `maximum_address` is the last word address to keep (excluding).
4.219721
4.551868
0.927031
info = '' if self._header is not None: if self._header_encoding is None: header = '' for b in bytearray(self.header): if chr(b) in string.printable: header += chr(b) else: ...
def info(self)
Return a string of human readable information about the binary file. .. code-block:: python >>> print(binfile.info()) Data ranges: 0x00000100 - 0x00000140 (64 bytes)
3.169724
3.057701
1.036636
d = {} for n in tree.preorder_internal_node_iter(): d[n] = namedtuple('NodeDist', ['dist_from_root', 'edges_from_root']) if n.parent_node: d[n].dist_from_root = d[n.parent_node].dist_from_root + n.edge_length d[n].edges_from_root = d[n.par...
def _precompute(self, tree)
Collect metric info in a single preorder traversal.
2.323173
2.177198
1.067047
little_m = [] big_m = [] leaf_nodes = sorted(tree.leaf_nodes(), key=lambda x: x.taxon.label) # inner nodes, sorted order for leaf_a, leaf_b in combinations(leaf_nodes, 2): mrca = tree.mrca(taxa=[leaf_a.taxon, leaf_b.taxon]) little_m.append(precom...
def _get_vectors(self, tree, precomputed_info)
Populate the vectors m and M.
3.201011
3.074671
1.041091
if self.tree ^ other.tree: if len(self.tree & other.tree) < min_overlap: return 0 # raise AttributeError('Can\'t calculate tree distances when tree overlap is less than two leaves') else: t1, t2 = self._equalise_leaf_sets(other, Fa...
def get_distance(self, other, lbda=0.5, min_overlap=4)
Return the Euclidean distance between vectors v of two trees. Must have the same leaf set (too lazy to check).
4.262757
3.799037
1.122062
delete = False combination = list() z = list(zip(sequence1, sequence2)) for (a, b) in z: if a == b: combination.append(a) else: if a == '-' or b == '-': combination.append('-') else: if delete_ambiguous: ...
def ambiguate(sequence1, sequence2, delete_ambiguous=False)
delete_ambiguous: Marks sequences for deletion by replacing all chars with 'X'. These seqs are deleted later with remove_empty
2.529378
2.784389
0.908414
for header, sequence in rec.mapping.items(): if all(char == 'X' for char in sequence): rec.headers.remove(header) rec.sequences.remove(sequence) rec.update() return rec
def remove_empty(rec)
Deletes sequences that were marked for deletion by convert_to_IUPAC
5.041538
4.31966
1.167114
text = unidecode(six.text_type(text)) text = text.replace('@', 'a') return text
def transliterate(text)
Utility to properly transliterate text.
4.893957
5.22166
0.937242
for value in values: if isinstance(value, six.string_types): value = transliterate(value) value = normality.slugify(value) yield value
def slugify(mapping, bind, values)
Transform all values into URL-capable slugs.
4.32135
4.164466
1.037672
for v in values: if isinstance(v, six.string_types): v = transliterate(v) yield v
def latinize(mapping, bind, values)
Transliterate a given string into the latin alphabet.
4.183659
4.159481
1.005813
return [' '.join([six.text_type(v) for v in values if v is not None])]
def join(mapping, bind, values)
Merge all the strings. Put space between them.
5.615071
4.420656
1.27019
def func(mapping, bind, values): for v in values: if isinstance(v, six.string_types): v = getattr(v, name)() yield v return func
def str_func(name)
Apply functions like upper(), lower() and strip().
6.478703
5.390771
1.201814
for v in values: if v is None: continue if not isinstance(v, six.string_types): v = six.text_type(v) yield sha1(v.encode('utf-8')).hexdigest()
def hash(mapping, bind, values)
Generate a sha1 for each of the given values.
2.624625
2.217299
1.183703
categories = {'C': ' '} for value in values: if isinstance(value, six.string_types): value = normality.normalize(value, lowercase=False, collapse=True, decompose=False, replace_categories=categories) ...
def clean(mapping, bind, values)
Perform several types of string cleaning for titles etc..
9.896834
8.469759
1.168491
nodes_to_check = list((np.where(mask[0, :])[0])[1:]) seen = [True] + [False] * (len(mask) - 1) while nodes_to_check and not all(seen): node = nodes_to_check.pop() reachable = np.where(mask[node, :])[0] for i in reachable: if not seen[i]: nodes_to_che...
def isconnected(mask)
Checks that all nodes are reachable from the first node - i.e. that the graph is fully connected.
2.675997
2.373641
1.127381
mask = (mask if mask is not None else np.ones(matrix.shape, dtype=bool)) assert isconnected(mask) scale = (scale if scale is not None else np.ones(matrix.shape)) ix = np.where(np.logical_not(mask)) scaled_matrix = -matrix ** 2 / scale # inputs where distance = 0 and scale = 0 result in Na...
def affinity( matrix, mask=None, scale=None, )
Mask is a 2d boolean matrix. Scale is a 2d local scale matrix, as output by kscale(). It's the outer product of the kdists column vector produced by kdists.
3.654344
3.654859
0.999859
m = matrix.copy() if square_input: m **= 2 (rows, cols) = m.shape cm = np.mean(m, axis=0) # column means rm = np.mean(m, axis=1).reshape((rows, 1)) # row means gm = np.mean(cm) # grand mean m -= rm + cm - gm m /= -2 return m
def double_centre(matrix, square_input=True)
Double-centres the input matrix: From each element: Subtract the row mean Subtract the column mean Add the grand mean Divide by -2 Method from: Torgerson, W S (1952). Multidimensional scaling: I. Theory and method. Alternatively M = -0.5 * (I - 1/n)D[^2](I - 1/n)
3.552025
3.041877
1.167708
topleft = np.zeros(matrix.shape) topright = 2*double_centre(matrix) bottomleft = -np.eye(matrix.shape[0]) bottomright = -4*double_centre(matrix, square_input=False) Z = np.vstack([np.hstack([topleft,topright]), np.hstack([bottomleft,bottomright])]) return max(np.real(np.l...
def _estimate_additive_constant(matrix)
CMDS Additive Constant: correction for non-Euclidean distances. Procedure taken from R function cmdscale. The additive constant is given by the largest eigenvalue (real part) of this 2x2 block matrix - /-------+-------\ | | | | 0 | 2*dbc | NB: dbc function(m: matrix): | ...
3.952017
3.151541
1.253995
try: np.linalg.cholesky(matrix) return True except np.linalg.LinAlgError: return False
def check_pd(matrix)
A symmetric matrix (M) is PD if it has a Cholesky decomposition, i.e. M = R.T dot R, where R is upper triangular with positive diagonal entries
2.410335
2.679747
0.899464
hermitian = (matrix + matrix.T.conjugate()) / 2 eigenvalues = np.linalg.eigh(hermitian)[0] return (eigenvalues > -tolerance).all()
def check_psd(matrix, tolerance=1e-6)
A square matrix is PSD if all eigenvalues of its Hermitian part are non- negative. The Hermitian part is given by (self + M*)/2, where M* is the complex conjugate transpose of M
3.857147
3.492496
1.10441
lengths = np.apply_along_axis(np.linalg.norm, 1, matrix) if not (lengths > 0).all(): # raise ValueError('Cannot normalise 0 length vector to length 1') # print(matrix) lengths[lengths == 0] = 1 return matrix / lengths[:, np.newaxis]
def normalise_rows(matrix)
Scales all rows to length 1. Fails when row is 0-length, so it leaves these unchanged
3.612139
3.254545
1.109875
ix = ix or kindex(matrix, k) return matrix[ix][np.newaxis].T
def kdists(matrix, k=7, ix=None)
Returns the k-th nearest distances, row-wise, as a column vector
8.334348
8.968815
0.929259
ix = (np.arange(len(matrix)), matrix.argsort(axis=0)[k]) return ix
def kindex(matrix, k)
Returns indices to select the kth nearest neighbour
6.329975
5.390085
1.174374
dists = (kdists(matrix, k=k) if dists is None else dists) mask = (matrix <= dists) if logic == 'or' or logic == '|': return mask | mask.T elif logic == 'and' or logic == '&': return mask & mask.T return mask
def kmask(matrix, k=7, dists=None, logic='or')
Creates a boolean mask to include points within k nearest neighbours, and exclude the rest. Logic can be OR or AND. OR gives the k-nearest-neighbour mask, AND gives the mutual k-nearest-neighbour mask.
3.022859
3.702112
0.816523
dists = (kdists(matrix, k=k) if dists is None else dists) scale = dists.dot(dists.T) return scale
def kscale(matrix, k=7, dists=None)
Returns the local scale based on the k-th nearest neighbour
4.163404
3.802168
1.095008
diagonal = affinity_matrix.sum(axis=1) - affinity_matrix.diagonal() zeros = diagonal <= 1e-10 diagonal[zeros] = 1 if (diagonal <= 1e-10).any(): # arbitrarily small value raise ZeroDivisionError if shi_malik_type: inv_d = np.diag(1 / diagonal) return inv_d.dot(affinity_...
def laplace(affinity_matrix, shi_malik_type=False)
Converts affinity matrix into normalised graph Laplacian, for spectral clustering. (At least) two forms exist: L = (D^-0.5).A.(D^-0.5) - default L = (D^-1).A - `Shi-Malik` type, from Shi Malik paper
3.483968
3.674068
0.948259