INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns geometry shifted to center of mass. | def ctr_geom(geom, masses):
""" Returns geometry shifted to center of mass.
Helper function to automate / encapsulate translation of a geometry to its
center of mass.
Parameters
----------
geom
length-3N |npfloat_| --
Original coordinates of the atoms
masses
length... |
Generate the 3x3 moment - of - inertia tensor. | def inertia_tensor(geom, masses):
"""Generate the 3x3 moment-of-inertia tensor.
Compute the 3x3 moment-of-inertia tensor for the
provided geometry and atomic masses. Always recenters the
geometry to the center of mass as the first step.
Reference for inertia tensor: [Kro92]_, Eq. (2.26)
.. t... |
Principal axes and moments of inertia for the indicated geometry. | def principals(geom, masses, on_tol=_DEF.ORTHONORM_TOL):
"""Principal axes and moments of inertia for the indicated geometry.
Calculated by :func:`scipy.linalg.eigh`, since the moment of inertia tensor
is symmetric (real-Hermitian) by construction. More convenient to
compute both the axes and moments ... |
Rotational constants for a given molecular system. | def rot_consts(geom, masses, units=_EURC.INV_INERTIA, on_tol=_DEF.ORTHONORM_TOL):
"""Rotational constants for a given molecular system.
Calculates the rotational constants for the provided system with numerical
value given in the units provided in `units`. The orthnormality tolerance
`on_tol` is requi... |
First non - zero Atomic Displacement Non - Orthogonal to Vec | def _fadn_orth(vec, geom):
"""First non-zero Atomic Displacement Non-Orthogonal to Vec
Utility function to identify the first atomic displacement in a geometry
that is (a) not the zero vector; and (b) not normal to the reference vector.
Parameters
----------
vec
length-3 |npfloat_| --
... |
First non - zero Atomic Displacement that is Non - Parallel with Vec | def _fadn_par(vec, geom):
"""First non-zero Atomic Displacement that is Non-Parallel with Vec
Utility function to identify the first atomic displacement in a geometry
that is both (a) not the zero vector and (b) non-(anti-)parallel with a
reference vector.
Parameters
----------
vec
... |
variant: varcode. Variant | def reference_contexts_for_variant(
variant,
context_size,
transcript_id_whitelist=None):
"""
variant : varcode.Variant
context_size : int
Max of nucleotides to include to the left and right of the variant
in the context sequence.
transcript_id_whitelist : set, ... |
Extract a set of reference contexts for each variant in the collection. | def reference_contexts_for_variants(
variants,
context_size,
transcript_id_whitelist=None):
"""
Extract a set of reference contexts for each variant in the collection.
Parameters
----------
variants : varcode.VariantCollection
context_size : int
Max of nucleotid... |
Given a collection of variants find all reference sequence contexts around each variant. | def variants_to_reference_contexts_dataframe(
variants,
context_size,
transcript_id_whitelist=None):
"""
Given a collection of variants, find all reference sequence contexts
around each variant.
Parameters
----------
variants : varcode.VariantCollection
context_size... |
Two - dimensional oriented Gaussian pattern ( i. e. 2D version of a bell curve like a normal distribution but not necessarily summing to 1. 0 ). | def gaussian(x, y, xsigma, ysigma):
"""
Two-dimensional oriented Gaussian pattern (i.e., 2D version of a
bell curve, like a normal distribution but not necessarily summing
to 1.0).
"""
if xsigma==0.0 or ysigma==0.0:
return x*0.0
with float_error_ignore():
x_w = np.divide(x,x... |
Two - dimensional oriented Log Gaussian pattern ( i. e. 2D version of a bell curve with an independent movable peak ). Much like a normal distribution but not necessarily placing the peak above the center and not necessarily summing to 1. 0 ). | def log_gaussian(x, y, x_sigma, y_sigma, mu):
"""
Two-dimensional oriented Log Gaussian pattern (i.e., 2D version of a
bell curve with an independent, movable peak). Much like a normal
distribution, but not necessarily placing the peak above the center,
and not necessarily summing to 1.0).
"""
... |
Two - dimensional oriented exponential decay pattern. | def exponential(x, y, xscale, yscale):
"""
Two-dimensional oriented exponential decay pattern.
"""
if xscale==0.0 or yscale==0.0:
return x*0.0
with float_error_ignore():
x_w = np.divide(x,xscale)
y_h = np.divide(y,yscale)
return np.exp(-np.sqrt(x_w*x_w+y_h*y_h)) |
Gabor pattern ( sine grating multiplied by a circular Gaussian ). | def gabor(x, y, xsigma, ysigma, frequency, phase):
"""
Gabor pattern (sine grating multiplied by a circular Gaussian).
"""
if xsigma==0.0 or ysigma==0.0:
return x*0.0
with float_error_ignore():
x_w = np.divide(x,xsigma)
y_h = np.divide(y,ysigma)
p = np.exp(-0.5*x_w*x... |
Infinite - length line with a solid central region then Gaussian fall - off at the edges. | def line(y, thickness, gaussian_width):
"""
Infinite-length line with a solid central region, then Gaussian fall-off at the edges.
"""
distance_from_line = abs(y)
gaussian_y_coord = distance_from_line - thickness/2.0
sigmasq = gaussian_width*gaussian_width
if sigmasq==0.0:
falloff =... |
Circular disk with Gaussian fall - off after the solid central region. | def disk(x, y, height, gaussian_width):
"""
Circular disk with Gaussian fall-off after the solid central region.
"""
disk_radius = height/2.0
distance_from_origin = np.sqrt(x**2+y**2)
distance_outside_disk = distance_from_origin - disk_radius
sigmasq = gaussian_width*gaussian_width
if ... |
Circular ring ( annulus ) with Gaussian fall - off after the solid ring - shaped region. | def ring(x, y, height, thickness, gaussian_width):
"""
Circular ring (annulus) with Gaussian fall-off after the solid ring-shaped region.
"""
radius = height/2.0
half_thickness = thickness/2.0
distance_from_origin = np.sqrt(x**2+y**2)
distance_outside_outer_disk = distance_from_origin - rad... |
Rectangle with a solid central region then Gaussian fall - off at the edges. | def smooth_rectangle(x, y, rec_w, rec_h, gaussian_width_x, gaussian_width_y):
"""
Rectangle with a solid central region, then Gaussian fall-off at the edges.
"""
gaussian_x_coord = abs(x)-rec_w/2.0
gaussian_y_coord = abs(y)-rec_h/2.0
box_x=np.less(gaussian_x_coord,0.0)
box_y=np.less(gaussi... |
Radial arc with Gaussian fall - off after the solid ring - shaped region with the given thickness with shape specified by the ( start end ) radian_range. | def arc_by_radian(x, y, height, radian_range, thickness, gaussian_width):
"""
Radial arc with Gaussian fall-off after the solid ring-shaped
region with the given thickness, with shape specified by the
(start,end) radian_range.
"""
# Create a circular ring (copied from the ring function)
rad... |
Arc with Gaussian fall - off after the solid ring - shaped region and specified by point of tangency ( x and y ) and arc width and height. | def arc_by_center(x, y, arc_box, constant_length, thickness, gaussian_width):
"""
Arc with Gaussian fall-off after the solid ring-shaped region and specified
by point of tangency (x and y) and arc width and height.
This function calculates the start and end radian from the given width and
height, a... |
Skip PG versions below specific version i. e. ( 9 5 ). | def skipPGVersionBefore(*ver):
"""Skip PG versions below specific version i.e. (9, 5)."""
ver = ver + (0,) * (3 - len(ver))
def skip_before_postgres_(func):
@wraps(func)
def skip_before_postgres__(obj, *args, **kwargs):
if hasattr(obj.conn, 'server_version'):
s... |
Pack an arbitrary set of iterables and non - iterables into tuples. | def pack_tups(*args):
"""Pack an arbitrary set of iterables and non-iterables into tuples.
Function packs a set of inputs with arbitrary iterability into tuples.
Iterability is tested with :func:`iterable`. Non-iterable inputs
are repeated in each output tuple. Iterable inputs are expanded
uniforml... |
Performs a safe typecast. | def safe_cast(invar, totype):
"""Performs a "safe" typecast.
Ensures that `invar` properly casts to `totype`. Checks after
casting that the result is actually of type `totype`. Any exceptions raised
by the typecast itself are unhandled.
Parameters
----------
invar
(arbitrary) -- Va... |
Generate an hour - minutes - seconds timestamp from an interval in seconds. | def make_timestamp(el_time):
""" Generate an hour-minutes-seconds timestamp from an interval in seconds.
Assumes numeric input of a time interval in seconds. Converts this
interval to a string of the format "#h #m #s", indicating the number of
hours, minutes, and seconds in the interval. Intervals gr... |
Check for consistency of two geometries and atom symbol lists | def check_geom(c1, a1, c2, a2, tol=_DEF.XYZ_COORD_MATCH_TOL):
""" Check for consistency of two geometries and atom symbol lists
Cartesian coordinates are considered consistent with the input
coords if each component matches to within `tol`. If coords or
atoms vectors are passed that are of mismatched ... |
Perform substitution of content into tagged string. | def template_subst(template, subs, delims=('<', '>')):
""" Perform substitution of content into tagged string.
For substitutions into template input files for external computational
packages, no checks for valid syntax are performed.
Each key in `subs` corresponds to a delimited
substitution tag t... |
Assert a value is an |nparray| of NumPy floats. | def assert_npfloatarray(obj, varname, desc, exc, tc, errsrc):
""" Assert a value is an |nparray| of NumPy floats.
Pass |None| to `varname` if `obj` itself is to be checked.
Otherwise, `varname` is the string name of the attribute of `obj` to
check. In either case, `desc` is a string description of the... |
Advance the base iterator publish to constituent iterators. | def advance(self):
"""Advance the base iterator, publish to constituent iterators."""
elem = next(self._iterable)
for deque in self._deques:
deque.append(elem) |
Returns true if the distance between the ( x y ) locations of two generators g0 and g1 is greater than a minimum separation. | def __distance_valid(self, g0, g1, p):
"""
Returns true if the distance between the (x,y) locations of
two generators g0 and g1 is greater than a minimum separation.
Can be extended easily to support other criteria.
"""
dist = np.sqrt((g1.x - g0.x) ** 2 +
... |
Advance the parameters for each generator for this presentation. | def _advance_pattern_generators(self,p):
"""
Advance the parameters for each generator for this
presentation.
Picks a position for each generator that is accepted by
__distance_valid for all combinations. Returns a new list of
the generators, with some potentially omitt... |
Explicitly generate new values for these parameters only when appropriate. | def _advance_params(self):
"""
Explicitly generate new values for these parameters only
when appropriate.
"""
for p in ['x','y','direction']:
self.force_new_dynamic_value(p)
self.last_time = self.time_fn() |
Selects and returns one of the patterns in the list. | def function(self,p):
"""Selects and returns one of the patterns in the list."""
pg = p.generator
motion_orientation=p.orientation+pi/2.0
new_x = p.x+p.size*pg.x
new_y = p.y+p.size*pg.y
image_array = pg(xdensity=p.xdensity,ydensity=p.ydensity,bounds=p.bounds,
... |
Check for consistency of Hessian geometry with input coords/ atoms. | def check_geom(self, coords, atoms, tol=_DEF.HESS_COORD_MATCH_TOL):
""" Check for consistency of Hessian geometry with input coords/atoms.
The cartesian coordinates associated with a Hessian object
are considered consistent with the input `coords` and `atoms`
if each component matches t... |
Initialize OrcaHess Hessian object from. hess file | def _load(self, **kwargs):
""" Initialize OrcaHess Hessian object from .hess file
Searches indicated file for data blocks within the .hess file. The
geometry, Hessian block, frequencies, and normal modes must be present
and will be retrieved; other blocks will be imported if present, o... |
Register a settings class with the switcher. Can be passed the settings class to register or be used as a decorator. | def register(self, settings_class=NoSwitcher, *simple_checks,
**conditions):
"""
Register a settings class with the switcher. Can be passed the settings
class to register or be used as a decorator.
:param settings_class: The class to register with the provided
... |
Get the next line without consuming it. | def _peek_buffer(self, i=0):
"""Get the next line without consuming it."""
while len(self._buffer) <= i:
self._buffer.append(next(self._source))
return self._buffer[i] |
Make a readline - like function which peeks into the source. | def _make_readline_peeker(self):
"""Make a readline-like function which peeks into the source."""
counter = itertools.count(0)
def readline():
try:
return self._peek_buffer(next(counter))
except StopIteration:
return ''
return readl... |
Consume the buffer up to the given token ( from _peek_python_tokens ). | def _consume_python_token(self, token):
"""Consume the buffer up to the given token (from _peek_python_tokens).
Returns a single string that was consumed.
"""
ret = []
line, col = token[3]
if line > 1:
ret = self._buffer[:line-1]
self._buffer[:li... |
Add a node to the graph and the stack. | def _add_node(self, node, depth):
"""Add a node to the graph, and the stack."""
self._topmost_node.add_child(node, bool(depth[1]))
self._stack.append((depth, node)) |
Internal function for making XYZ object from explicit geom data. | def _load_data(self, atom_syms, coords, bohrs=True):
""" Internal function for making XYZ object from explicit geom data.
Parameters
----------
atom_syms
Squeezes to array of N |str| --
Element symbols for the XYZ. Must be valid elements as defined in
... |
Initialize OpanXYZ geometry object from OpenBabel file | def _load_file(self, XYZ_path, bohrs=False):
""" Initialize OpanXYZ geometry object from OpenBabel file
Import of an arbitrary number of multiple geometries from an OpenBabel
file. All geometries must have the same number and type of atoms,
and the ordering of atom types must be retaine... |
Iterator over a subset of geometries. | def geom_iter(self, g_nums):
"""Iterator over a subset of geometries.
The indices of the geometries to be returned are indicated by an
iterable of |int|\\ s passed as `g_nums`.
As with :meth:`geom_single`, each geometry is returned as a
length-3N |npfloat_| with each atom's x/y... |
Distance between two atoms. | def dist_single(self, g_num, at_1, at_2):
""" Distance between two atoms.
Parameters
----------
g_num
|int| -- Index of the desired geometry
at_1
|int| -- Index of the first atom
at_2
|int| -- Index of the second atom
Return... |
Iterator over selected interatomic distances. | def dist_iter(self, g_nums, ats_1, ats_2, invalid_error=False):
""" Iterator over selected interatomic distances.
Distances are in Bohrs as with :meth:`dist_single`.
See `above <toc-generators_>`_ for more information on
calling options.
Parameters
----------
g... |
Spanning angle among three atoms. | def angle_single(self, g_num, at_1, at_2, at_3):
""" Spanning angle among three atoms.
The indices `at_1` and `at_3` can be the same (yielding a
trivial zero angle), but `at_2` must be different from
both `at_1` and `at_3`.
Parameters
----------
g_num
... |
Iterator over selected atomic angles. | def angle_iter(self, g_nums, ats_1, ats_2, ats_3, invalid_error=False):
""" Iterator over selected atomic angles.
Angles are in degrees as with :meth:`angle_single`.
See `above <toc-generators_>`_ for more information on
calling options.
Parameters
----------
g... |
Dihedral/ out - of - plane angle among four atoms. | def dihed_single(self, g_num, at_1, at_2, at_3, at_4):
""" Dihedral/out-of-plane angle among four atoms.
Returns the out-of-plane angle among four atoms from geometry
`g_num`, in degrees. The reference plane
is spanned by `at_1`, `at_2` and `at_3`. The out-of-plane angle is
def... |
Iterator over selected dihedral angles. | def dihed_iter(self, g_nums, ats_1, ats_2, ats_3, ats_4, \
invalid_error=False):
""" Iterator over selected dihedral angles.
Angles are in degrees as with :meth:`dihed_single`.
See `above <toc-generators_>`_ for more information on
ca... |
Displacement vector between two atoms. | def displ_single(self, g_num, at_1, at_2):
""" Displacement vector between two atoms.
Returns the displacement vector pointing from `at_1`
toward `at_2` from geometry `g_num`.
If `at_1` == `at_2` a strict zero vector is returned.
Displacement vector is returned in units of Bohr... |
Iterator over indicated displacement vectors. | def displ_iter(self, g_nums, ats_1, ats_2, invalid_error=False):
""" Iterator over indicated displacement vectors.
Displacements are in Bohrs as with :meth:`displ_single`.
See `above <toc-generators_>`_ for more information on
calling options.
Parameters
----------
... |
Helper function to insert full ranges for |None| for X_iter methods. | def _none_subst(self, *args):
""" Helper function to insert full ranges for |None| for X_iter methods.
Custom method, specifically tailored, taking in the arguments from
an X_iter method and performing the replacement of |None| after
error-checking the arguments for a max of one |None| ... |
Wrapper for exception/ |None| output handling of X_iter methods. | def _iter_return(tup, fxn, invalid_error):
""" Wrapper for exception/|None| output handling of X_iter methods.
Attempts to pass `tup` as arguments to `fxn`. If the call is
successful, returns the value produced. If
:exc:`~exceptions.IndexError` or
:exc:`~exceptions.ValueError`
... |
Return a URL that is most likely to route to local_host from outside. | def guess_external_url(local_host, port):
"""Return a URL that is most likely to route to `local_host` from outside.
The point is that we may be running on a remote host from the user's
point of view, so they can't access `local_host` from a Web browser just
by typing ``http://localhost:12345/``.
"... |
Make sure columns are of the same length or else DataFrame construction will fail. | def _check_column_lengths(self):
"""
Make sure columns are of the same length or else DataFrame construction
will fail.
"""
column_lengths_dict = {
name: len(xs)
for (name, xs)
in self.columns_dict.items()
}
unique_column_length... |
Initialize with data from files. | def new_from_files(self, basepath, basename, repo, \
bohrs=False, \
software=_E_SW.ORCA, \
repo_clobber=False, **kwargs):
""" Initialize with data from files.
"""
# Imports
import os
from os import path as osp
... |
Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings numbers tuples lists dicts booleans and None. | def literal_eval(node_or_string):
"""
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
"""
_safe_names = {
... |
Metaclass that wraps exception type in RemoteException | def remote_exception(exc, tb):
""" Metaclass that wraps exception type in RemoteException """
if type(exc) in exceptions:
typ = exceptions[type(exc)]
return typ(exc, tb)
else:
try:
typ = type(exc.__class__.__name__,
(RemoteException, type(exc)),
... |
Given a collection of LocusRead objects returns a list of AlleleRead objects ( which are split into prefix/ allele/ suffix nucleotide strings ). | def allele_reads_from_locus_reads(locus_reads, n_ref):
"""
Given a collection of LocusRead objects, returns a
list of AlleleRead objects
(which are split into prefix/allele/suffix nucleotide strings).
Parameters
----------
locus_reads : sequence of LocusRead records
n_ref : int
... |
Find reads in the given SAM/ BAM file which overlap the given variant and return them as a list of AlleleRead objects. | def reads_overlapping_variant(
samfile,
variant,
chromosome=None,
use_duplicate_reads=USE_DUPLICATE_READS,
use_secondary_alignments=USE_SECONDARY_ALIGNMENTS,
min_mapping_quality=MIN_READ_MAPPING_QUALITY):
"""
Find reads in the given SAM/BAM file which overlap the ... |
Generates sequence of tuples each containing a variant paired with a list of AlleleRead objects. | def reads_overlapping_variants(variants, samfile, **kwargs):
"""
Generates sequence of tuples, each containing a variant paired with
a list of AlleleRead objects.
Parameters
----------
variants : varcode.VariantCollection
samfile : pysam.AlignmentFile
use_duplicate_reads : bool
... |
Returns dictionary mapping each allele s nucleotide sequence to a list of supporting AlleleRead objects. | def group_reads_by_allele(allele_reads):
"""
Returns dictionary mapping each allele's nucleotide sequence to a list of
supporting AlleleRead objects.
"""
allele_to_reads_dict = defaultdict(list)
for allele_read in allele_reads:
allele_to_reads_dict[allele_read.allele].append(allele_read)... |
Parameters ---------- variants_and_allele_reads: sequence List or generator of pairs whose first element is a Variant and whose second element is a sequence of AlleleRead objects. | def reads_to_dataframe(variants_and_allele_reads):
"""
Parameters
----------
variants_and_allele_reads : sequence
List or generator of pairs whose first element is a Variant and
whose second element is a sequence of AlleleRead objects.
"""
df_builder = DataFrameBuilder(
A... |
Given a single LocusRead object return either an AlleleRead or None | def from_locus_read(cls, locus_read, n_ref):
"""
Given a single LocusRead object, return either an AlleleRead or None
Parameters
----------
locus_read : LocusRead
Read which overlaps a variant locus but doesn't necessarily contain the
alternate nucleotide... |
Count the number of times { A C T G } occur at each position to the left and right of the variant. | def nucleotide_counts(variant_reads):
"""
Count the number of times {A, C, T, G} occur at each position to the
left and right of the variant.
Parameters
----------
variant_reads : list of AlleleRead objects
Expected to all contain the same variant allele.
Returns a tuple with the f... |
Find the most common nucleotide at each offset to the left and right of a variant. | def most_common_nucleotides(partitioned_read_sequences):
"""
Find the most common nucleotide at each offset to the left and
right of a variant.
Parameters
----------
partitioned_read_sequences : list of tuples
Each tuple has three elements:
- sequence before mutant nucleotid... |
Calculate the displacement vector between two n - D points. | def point_displ(pt1, pt2):
""" Calculate the displacement vector between two n-D points.
pt1 - pt2
.. todo:: Complete point_disp docstring
"""
#Imports
import numpy as np
# Make iterable
if not np.iterable(pt1):
pt1 = np.float64(np.array([pt1]))
else:
pt1 = np.fl... |
Calculate the Euclidean distance between two n - D points. | def point_dist(pt1, pt2):
""" Calculate the Euclidean distance between two n-D points.
|pt1 - pt2|
.. todo:: Complete point_dist docstring
"""
# Imports
from scipy import linalg as spla
dist = spla.norm(point_displ(pt1, pt2))
return dist |
Rotate a 3 - D point around a 3 - D axis through the origin. | def point_rotate(pt, ax, theta):
""" Rotate a 3-D point around a 3-D axis through the origin.
Handedness is a counter-clockwise rotation when viewing the rotation
axis as pointing at the observer. Thus, in a right-handed x-y-z frame,
a 90deg rotation of (1,0,0) around the z-axis (0,0,1) yields a point... |
Reflect a 3 - D point through a plane intersecting the origin. | def point_reflect(pt, nv):
""" Reflect a 3-D point through a plane intersecting the origin.
nv defines the normal vector to the plane (needs not be normalized)
.. todo:: Complete point_reflect docstring
Raises
------
ValueError : If pt or nv are not reducible to 3-D vectors
ValueError : I... |
Reflection symmetry operation. | def geom_reflect(g, nv):
""" Reflection symmetry operation.
nv is normal vector to reflection plane
g is assumed already translated to center of mass @ origin
.. todo:: Complete geom_reflect docstring
"""
# Imports
import numpy as np
# Force g to n-vector
g = make_nd_vec(g, nd=N... |
Rotation symmetry operation. | def geom_rotate(g, ax, theta):
""" Rotation symmetry operation.
ax is rotation axis
g is assumed already translated to center of mass @ origin
Sense of rotation is the same as point_rotate
.. todo:: Complete geom_rotate docstring
"""
# Imports
import numpy as np
# Force g to n-... |
Perform general point symmetry operation on a geometry. | def symm_op(g, ax, theta, do_refl):
""" Perform general point symmetry operation on a geometry.
.. todo:: Complete symm_op docstring
"""
# Imports
import numpy as np
# Depend on lower functions' geometry vector coercion. Just
# do the rotation and, if indicated, the reflection.
gx =... |
[ Revised match factor calculation ] | def geom_symm_match(g, atwts, ax, theta, do_refl):
""" [Revised match factor calculation]
.. todo:: Complete geom_symm_match docstring
"""
# Imports
import numpy as np
from scipy import linalg as spla
# Convert g and atwts to n-D vectors
g = make_nd_vec(g, nd=None, t=np.float64, norm... |
Identify highest - order symmetry for a geometry on a given axis. | def geom_find_rotsymm(g, atwts, ax, improp, \
nmax=_DEF.SYMM_MATCH_NMAX, \
tol=_DEF.SYMM_MATCH_TOL):
""" Identify highest-order symmetry for a geometry on a given axis.
Regular and improper axes possible.
.. todo:: Complete geom_find_rotsymm docstring
"""
# Imports
import num... |
[ Get max proper order and reflection for an axis ] | def geom_check_axis(g, atwts, ax,
nmax=_DEF.SYMM_MATCH_NMAX,
tol=_DEF.SYMM_MATCH_TOL):
""" [Get max proper order and reflection for an axis]
.. todo:: Complete geom_parse_axis docstring
"""
# Imports
import numpy as np
# Store the max found rotation order of the geometry.
... |
[ Find all ( ? ) proper rotation axes ( n > 1 ) and reflection planes. ] | def geom_find_group(g, atwts, pr_ax, mom, tt, \
nmax=_DEF.SYMM_MATCH_NMAX, \
tol=_DEF.SYMM_MATCH_TOL, \
dig=_DEF.SYMM_ATWT_ROUND_DIGITS,
avmax=_DEF.SYMM_AVG_MAX):
""" [Find all(?) proper rotation axes (n > 1) and reflection planes.]
.. todo:: Complete geom_find_axes docstring IN... |
Extract a subset of a geometry matching a desired atom. | def g_subset(g, atwts, atwt,
digits=_DEF.SYMM_ATWT_ROUND_DIGITS):
""" Extract a subset of a geometry matching a desired atom.
.. todo:: Complete g_subset docstring
"""
# Imports
import numpy as np
# Ensure g and atwts are n-D vectors
g = make_nd_vec(g, nd=None, t=np.float64, ... |
Coerce input to np. array () and validate dimensionality. | def make_nd_vec(v, nd=None, t=None, norm=False):
""" Coerce input to np.array() and validate dimensionality.
Ensure dimensionality 'n' if passed.
Cast to type 't' if passed
Normalize output if norm=True
.. todo:: Complete make_nd_vec docstring
"""
# Imports
import numpy as np
fro... |
Generate block - diagonal reflection matrix about nv. | def mtx_refl(nv, reps=1):
""" Generate block-diagonal reflection matrix about nv.
reps must be >=1 and indicates the number of times the reflection
matrix should be repeated along the block diagonal. Typically this
will be the number of atoms in a geometry.
.. todo:: Complete mtx_refl docstring
... |
Generate block - diagonal rotation matrix about ax. | def mtx_rot(ax, theta, reps=1):
""" Generate block-diagonal rotation matrix about ax.
[copy handedness from somewhere]
.. todo:: Complete mtx_rot docstring
"""
# Imports
import numpy as np
from scipy import linalg as spla
from ..const import PRM
# Ensure |ax| is large enough for... |
First - Fit | def ff(items, targets):
"""First-Fit
This is perhaps the simplest packing heuristic;
it simply packs items in the next available bin.
Complexity O(n^2)
"""
bins = [(target, []) for target in targets]
skip = []
for item in items:
for target, content in bins:
if item... |
First - Fit Decreasing | def ffd(items, targets, **kwargs):
"""First-Fit Decreasing
This is perhaps the simplest packing heuristic;
it simply packs items in the next available bin.
This algorithm differs only from Next-Fit Decreasing
in having a 'sort'; that is, the items are pre-sorted
(largest to smallest).
Com... |
Max - Rest | def mr(items, targets, **kwargs):
"""Max-Rest
Complexity O(n^2)
"""
bins = [(target, []) for target in targets]
skip = []
for item in items:
capacities = [target - sum(content) for target, content in bins]
weighted = weight(capacities, **kwargs)
(target, content), capa... |
Best - Fit | def bf(items, targets, **kwargs):
"""Best-Fit
Complexity O(n^2)
"""
bins = [(target, []) for target in targets]
skip = []
for item in items:
containers = []
capacities = []
for target, content in bins:
capacity = target - sum(content)
if item <= ... |
Best - Fit Decreasing | def bfd(items, targets, **kwargs):
"""Best-Fit Decreasing
Complexity O(n^2)
"""
sizes = zip(items, weight(items, **kwargs))
sizes = sorted(sizes, key=operator.itemgetter(1), reverse=True)
items = map(operator.itemgetter(0), sizes)
return bf(items, targets, **kwargs) |
A VariantSequence and ReferenceContext may contain a different number of nucleotides before the variant locus. Furthermore the VariantSequence is always expressed in terms of the positive strand against which it aligned but reference transcripts may have sequences from the negative strand of the genome. Take the revers... | def trim_sequences(variant_sequence, reference_context):
"""
A VariantSequence and ReferenceContext may contain a different number of
nucleotides before the variant locus. Furthermore, the VariantSequence is
always expressed in terms of the positive strand against which it aligned,
but reference tra... |
Computes the number of mismatching nucleotides between two cDNA sequences before a variant locus. | def count_mismatches_before_variant(reference_prefix, cdna_prefix):
"""
Computes the number of mismatching nucleotides between two cDNA sequences before a variant
locus.
Parameters
----------
reference_prefix : str
cDNA sequence of a reference transcript before a variant locus
cdna... |
Computes the number of mismatching nucleotides between two cDNA sequences after a variant locus. | def count_mismatches_after_variant(reference_suffix, cdna_suffix):
"""
Computes the number of mismatching nucleotides between two cDNA sequences after a variant locus.
Parameters
----------
reference_suffix : str
cDNA sequence of a reference transcript after a variant locus
cdna_suffix... |
Once we ve aligned the variant sequence to the ReferenceContext we need to transfer reading frame from the reference transcripts to the variant sequences. | def compute_offset_to_first_complete_codon(
offset_to_first_complete_reference_codon,
n_trimmed_from_reference_sequence):
"""
Once we've aligned the variant sequence to the ReferenceContext, we need
to transfer reading frame from the reference transcripts to the variant
sequences.
P... |
Iteratively trim low - coverage subsequences of a variant sequence until it either matches the given reference context or there are too few nucleotides left in the variant sequence. | def match_variant_sequence_to_reference_context(
variant_sequence,
reference_context,
min_transcript_prefix_length,
max_transcript_mismatches,
include_mismatches_after_variant=False,
max_trimming_attempts=2):
"""
Iteratively trim low-coverage subsequences of a var... |
Combines a VariantSequence with the reading frame implied by a ReferenceContext reverse complementing if necessary and finding the offset to the first complete codon in the cDNA sequence. Parameters ---------- variant_sequence: VariantSequence | def from_variant_sequence_and_reference_context(
cls, variant_sequence, reference_context):
"""
Combines a VariantSequence with the reading frame implied by a
ReferenceContext, reverse complementing if necessary and finding the
offset to the first complete codon in the cDNA s... |
Given a cDNA sequence which is aligned to a reading frame returns the translated protein sequence and a boolean flag indicating whether the translated sequence ended on a stop codon ( or just ran out of codons ). | def translate_cdna(
cdna_sequence,
first_codon_is_start=False,
mitochondrial=False):
"""
Given a cDNA sequence which is aligned to a reading frame, returns
the translated protein sequence and a boolean flag indicating whether
the translated sequence ended on a stop codon (or just... |
If codon table is missing stop codons then add them. | def _check_codons(self):
"""
If codon table is missing stop codons, then add them.
"""
for stop_codon in self.stop_codons:
if stop_codon in self.codon_table:
if self.codon_table[stop_codon] != "*":
raise ValueError(
... |
Given a cDNA sequence which is aligned to a reading frame returns the translated protein sequence and a boolean flag indicating whether the translated sequence ended on a stop codon ( or just ran out of codons ). | def translate(self, cdna_sequence, first_codon_is_start=False):
"""
Given a cDNA sequence which is aligned to a reading frame, returns
the translated protein sequence and a boolean flag indicating whether
the translated sequence ended on a stop codon (or just ran out of codons).
... |
Make copy of this GeneticCode object with optional replacement values for all fields. | def copy(
self,
name,
start_codons=None,
stop_codons=None,
codon_table=None,
codon_table_changes=None):
"""
Make copy of this GeneticCode object with optional replacement
values for all fields.
"""
new_start_... |
Initialize: class: OrcaEngrad object from. engrad file | def _load(self, **kwargs):
""" Initialize :class:`OrcaEngrad` object from .engrad file
Searches indicated file for energy, geometry, gradient, and number
of atoms and stores in the corresponding instance variables.
Parameters
----------
path
|str| -- Comple... |
Start listening to changes | def start(self):
"""
Start listening to changes
"""
self.running = True
self.thread = threading.Thread(target=self._main_loop)
self.thread.start() |
Subscribe to given fields. | def subscribe(self, field_names):
"""
Subscribe to given fields.
Special fields cannot be subscribed to and will be checked on every iteration. These include:
* loco name
* coordinates
* fuel level
* gradient
* current heading
* is in tunnel
... |
Channels () adds a shared interface for single channel and multichannel structures. It will always return an ordered dict: its first element is the single channel of the pattern ( if single - channel ) or the channel average ( if multichannel ) ; the successive elements are the individual channels arrays ( key: 0 1.. N... | def channels(self, use_cached=False, **params_to_override):
"""
Channels() adds a shared interface for single channel and
multichannel structures. It will always return an ordered
dict: its first element is the single channel of the pattern
(if single-channel) or the channel ave... |
Produce pattern coordinate matrices from the bounds and density ( or rows and cols ) and transforms them according to x y and orientation. | def _setup_xy(self,bounds,xdensity,ydensity,x,y,orientation):
"""
Produce pattern coordinate matrices from the bounds and
density (or rows and cols), and transforms them according to
x, y, and orientation.
"""
self.debug("bounds=%s, xdensity=%s, ydensity=%s, x=%s, y=%s, o... |
Create pattern matrices from x and y vectors and rotate them to the specified orientation. | def _create_and_rotate_coordinate_arrays(self, x, y, orientation):
"""
Create pattern matrices from x and y vectors, and rotate them
to the specified orientation.
"""
# Using this two-liner requires that x increase from left to
# right and y decrease from left to right; I... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.