INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Return a sine grating pattern (two-dimensional sine wave). | def function(self,p):
"""Return a sine grating pattern (two-dimensional sine wave)."""
return 0.5 + 0.5*np.sin(p.frequency*2*pi*self.pattern_y + p.phase) |
Calculate line width necessary to cover at least one pixel on all axes. | def _pixelsize(self, p):
"""Calculate line width necessary to cover at least one pixel on all axes."""
xpixelsize = 1./float(p.xdensity)
ypixelsize = 1./float(p.ydensity)
return max([xpixelsize,ypixelsize]) |
Count the number of pixels rendered on this line. | def _count_pixels_on_line(self, y, p):
"""Count the number of pixels rendered on this line."""
h = line(y, self._effective_thickness(p), 0.0)
return h.sum() |
For the specified y and one offset by half a pixel, return the
one that results in the fewest pixels turned on, so that when
the thickness has been enforced to be at least one pixel, no
extra pixels are needlessly included (which would cause
double-width lines). | def _minimal_y(self, p):
"""
For the specified y and one offset by half a pixel, return the
one that results in the fewest pixels turned on, so that when
the thickness has been enforced to be at least one pixel, no
extra pixels are needlessly included (which would cause
d... |
Return a square-wave grating (alternating black and white bars). | def function(self,p):
"""
Return a square-wave grating (alternating black and white bars).
"""
return np.around(
0.5 +
0.5*np.sin(pi*(p.duty_cycle-0.5)) +
0.5*np.sin(p.frequency*2*pi*self.pattern_y + p.phase)) |
Selects and returns one of the patterns in the list. | def function(self,p):
"""Selects and returns one of the patterns in the list."""
int_index=int(len(p.generators)*wrap(0,1.0,p.index))
pg=p.generators[int_index]
image_array = pg(xdensity=p.xdensity,ydensity=p.ydensity,bounds=p.bounds,
x=p.x+p.size*(pg.x*np.cos(p... |
Return the current generator (as specified by self.index). | def get_current_generator(self):
"""Return the current generator (as specified by self.index)."""
int_index=int(len(self.generators)*wrap(0,1.0,self.inspect_value('index')))
return self.generators[int_index] |
Get channel data from the current generator. use_cached is
not supported at the moment, though it must be forced to be
True in the current_generator in order to avoid generating the
same data twice (the first time by self() and the second with
current_generator.channels() ). | def channels(self, use_cached=False, **params_to_override):
"""
Get channel data from the current generator. use_cached is
not supported at the moment, though it must be forced to be
True in the current_generator in order to avoid generating the
same data twice (the first time b... |
Get the number of channels in the input generators. | def num_channels(self):
"""
Get the number of channels in the input generators.
"""
if(self.inspect_value('index') is None):
if(len(self.generators)>0):
return self.generators[0].num_channels()
return 0
return self.get_current_generator().... |
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, p):
"""
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, orientation=%s",p.bounds, p.xdensity, p... |
Create pattern matrices from x and y vectors, and rotate
them to the specified orientation. | def _create_and_rotate_coordinate_arrays(self, x, y, p):
"""
Create pattern matrices from x and y vectors, and rotate
them to the specified orientation.
"""
if p.aspect_ratio == 0 or p.size == 0:
x = x * 0.0
y = y * 0.0
else:
x = (x*10... |
Overload if special behaviour is required when a series ends. | def extract_specific_interval(self, interval_start, interval_end):
"""
Overload if special behaviour is required when a series ends.
"""
interval_start = int(interval_start)
interval_end = int(interval_end)
if interval_start >= interval_end:
raise ValueError... |
Frequency spacing to use, i.e. how to map the available
frequency range to the discrete sheet rows.
NOTE: We're calculating the spacing of a range between the
highest and lowest frequencies, the actual segmentation and
averaging of the frequencies to fit this spacing occurs in
_... | def _set_frequency_spacing(self, min_freq, max_freq):
"""
Frequency spacing to use, i.e. how to map the available
frequency range to the discrete sheet rows.
NOTE: We're calculating the spacing of a range between the
highest and lowest frequencies, the actual segmentation and
... |
Perform a real Discrete Fourier Transform (DFT; implemented
using a Fast Fourier Transform algorithm, FFT) of the current
sample from the signal multiplied by the smoothing window.
See numpy.rfft for information about the Fourier transform. | def _get_row_amplitudes(self):
"""
Perform a real Discrete Fourier Transform (DFT; implemented
using a Fast Fourier Transform algorithm, FFT) of the current
sample from the signal multiplied by the smoothing window.
See numpy.rfft for information about the Fourier transform.
... |
This function creates a graph of vertices and edges from segments returned by SLIC.
:param array grid: A grid of segments as returned by the slic function defined in skimage library
:return: A graph as [vertices, edges] | def create_graph(grid):
"""
This function creates a graph of vertices and edges from segments returned by SLIC.
:param array grid: A grid of segments as returned by the slic function defined in skimage library
:return: A graph as [vertices, edges]
"""
try:
import numpy as np
except I... |
Get index/doc_type given a record.
It tries to extract from `record['$schema']` the index and doc_type.
If it fails, return the default values.
:param record: The record object.
:returns: Tuple (index, doc_type). | def default_record_to_index(record):
"""Get index/doc_type given a record.
It tries to extract from `record['$schema']` the index and doc_type.
If it fails, return the default values.
:param record: The record object.
:returns: Tuple (index, doc_type).
"""
index_names = current_search.mapp... |
Python to postgres encoding map. | def get_postgres_encoding(python_encoding: str) -> str:
"""Python to postgres encoding map."""
encoding = normalize_encoding(python_encoding.lower())
encoding_ = aliases.aliases[encoding.replace('_', '', 1)].upper()
pg_encoding = PG_ENCODING_MAP[encoding_.replace('_', '')]
return pg_encoding |
Try loading each binding in turn
Please note: the entire Qt module is replaced with this code:
sys.modules["Qt"] = binding()
This means no functions or variables can be called after
this has executed. | def _init():
"""Try loading each binding in turn
Please note: the entire Qt module is replaced with this code:
sys.modules["Qt"] = binding()
This means no functions or variables can be called after
this has executed.
"""
preferred = os.getenv("QT_PREFERRED_BINDING")
verbose = os.... |
Report the energies from the last SCF present in the output.
Returns a |dict| providing the various energy values from the
last SCF cycle performed in the output. Keys are those of
:attr:`~opan.output.OrcaOutput.p_en`.
Any energy value not relevant to the parsed
output is assign... | def en_last(self):
""" Report the energies from the last SCF present in the output.
Returns a |dict| providing the various energy values from the
last SCF cycle performed in the output. Keys are those of
:attr:`~opan.output.OrcaOutput.p_en`.
Any energy value not relevant to the ... |
Create a database connection. | def connect(host=None, database=None, user=None, password=None, **kwargs):
"""Create a database connection."""
host = host or os.environ['PGHOST']
database = database or os.environ['PGDATABASE']
user = user or os.environ['PGUSER']
password = password or os.environ['PGPASSWORD']
return psycopg2... |
Executes |orca| on a dynamically constructed input file.
.. warning:: Function is still under active development! Execution with
`wait_to_complete` == |True| should be robust, however.
**Execution**
Generates an |orca| input file dynamically from information passed into the
various arguments,... | def execute_orca(inp_tp, work_dir, exec_cmd, subs=None, subs_delims=("<",">"),
sim_name="orcarun",
inp_ext=_DEF.FILE_EXTS[_E_SW.ORCA][_E_FT.INPUTFILE],
out_ext=_DEF.FILE_EXTS[_E_SW.ORCA][_E_FT.OUTPUT],
wait_to_complete=True,
bohrs=False):
"""Executes |orca... |
Set up module.
Open a UDP socket, and listen in a thread. | def _setup():
""" Set up module.
Open a UDP socket, and listen in a thread.
"""
_SOCKET.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
_SOCKET.bind(('', PORT))
udp = threading.Thread(target=_listen, daemon=True)
udp.start() |
Discover devices on the local network.
:param timeout: Optional timeout in seconds.
:returns: Set of discovered host addresses. | def discover(timeout=DISCOVERY_TIMEOUT):
""" Discover devices on the local network.
:param timeout: Optional timeout in seconds.
:returns: Set of discovered host addresses.
"""
hosts = {}
payload = MAGIC + DISCOVERY
for _ in range(RETRIES):
_SOCKET.sendto(bytearray(payload), ('255.2... |
Discovers MAC address of device.
Discovery is done by sending a UDP broadcast.
All configured devices reply. The response contains
the MAC address in both needed formats.
Discovery of multiple switches must be done synchronously.
:returns: Tuple of MAC address and reversed MAC... | def _discover_mac(self):
""" Discovers MAC address of device.
Discovery is done by sending a UDP broadcast.
All configured devices reply. The response contains
the MAC address in both needed formats.
Discovery of multiple switches must be done synchronously.
:returns: ... |
Subscribe to the device.
A subscription serves two purposes:
- Returns state (on/off).
- Enables state changes on the device
for a short period of time. | def _subscribe(self):
""" Subscribe to the device.
A subscription serves two purposes:
- Returns state (on/off).
- Enables state changes on the device
for a short period of time.
"""
cmd = MAGIC + SUBSCRIBE + self._mac \
+ PADDING_1 + self._mac_reve... |
Control device state.
Possible states are ON or OFF.
:param state: Switch to this state. | def _control(self, state):
""" Control device state.
Possible states are ON or OFF.
:param state: Switch to this state.
"""
# Renew subscription if necessary
if not self._subscription_is_recent():
self._subscribe()
cmd = MAGIC + CONTROL + self._mac... |
Handle a discovery response.
:param data: Payload.
:param addr: Address tuple.
:returns: MAC and reversed MAC. | def _discovery_resp(self, data):
""" Handle a discovery response.
:param data: Payload.
:param addr: Address tuple.
:returns: MAC and reversed MAC.
"""
if _is_discovery_response(data):
_LOGGER.debug("Discovered MAC of %s: %s", self.host,
... |
Handle a subscribe response.
:param data: Payload.
:returns: State (ON/OFF) | def _subscribe_resp(self, data):
""" Handle a subscribe response.
:param data: Payload.
:returns: State (ON/OFF)
"""
if _is_subscribe_response(data):
status = bytes([data[23]])
_LOGGER.debug("Successfully subscribed to %s, state: %s",
... |
Handle a control response.
:param data: Payload.
:param state: Requested state.
:returns: Acknowledged state. | def _control_resp(self, data, state):
""" Handle a control response.
:param data: Payload.
:param state: Requested state.
:returns: Acknowledged state.
"""
if _is_control_response(data):
ack_state = bytes([data[22]])
if state == ack_state:
... |
Complete a UDP transaction.
UDP is stateless and not guaranteed, so we have to
take some mitigation steps:
- Send payload multiple times.
- Wait for awhile to receive response.
:param payload: Payload to send.
:param handler: Response handler.
:param args: Argum... | def _udp_transact(self, payload, handler, *args,
broadcast=False, timeout=TIMEOUT):
""" Complete a UDP transaction.
UDP is stateless and not guaranteed, so we have to
take some mitigation steps:
- Send payload multiple times.
- Wait for awhile to receive re... |
Load OpenCorpora corpus.
The ``source`` can be any of the following:
- a file name/path
- a file object
- a file-like object
- a URL using the HTTP or FTP protocol | def load(source):
"""
Load OpenCorpora corpus.
The ``source`` can be any of the following:
- a file name/path
- a file object
- a file-like object
- a URL using the HTTP or FTP protocol
"""
parser = get_xml_parser()
return etree.parse(source, parser=parser).getroot() |
Parameters
----------
cdna_sequence : skbio.DNA or str
cDNA sequence found in RNAseq data
cdna_first_codon_offset : int
Offset into cDNA sequence to first complete codon, lets us skip
past UTR region and incomplete codons.
cdna_variant_start_offset : int
Interbase start... | def find_mutant_amino_acid_interval(
cdna_sequence,
cdna_first_codon_offset,
cdna_variant_start_offset,
cdna_variant_end_offset,
n_ref,
n_amino_acids):
"""
Parameters
----------
cdna_sequence : skbio.DNA or str
cDNA sequence found in RNAseq data
... |
Given all detected VariantSequence objects for a particular variant
and all the ReferenceContext objects for that locus, translate
multiple protein sequences, up to the number specified by the argument
max_protein_sequences_per_variant.
Parameters
----------
variant_sequences : list of VariantS... | def translation_generator(
variant_sequences,
reference_contexts,
min_transcript_prefix_length,
max_transcript_mismatches,
include_mismatches_after_variant,
protein_sequence_length=None):
"""
Given all detected VariantSequence objects for a particular variant
... |
Given a variant and its associated alt reads, construct variant sequences
and translate them into Translation objects.
Returns 0 or more Translation objects.
Parameters
----------
variant : varcode.Variant
variant_reads : sequence or generator
AlleleRead objects supporting the variant... | def translate_variant_reads(
variant,
variant_reads,
protein_sequence_length,
transcript_id_whitelist=None,
min_alt_rna_reads=MIN_ALT_RNA_READS,
min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE,
min_transcript_prefix_length=MIN_TRANSCRIPT_PREFIX_LENGTH,... |
Translates each coding variant in a collection to one or more protein
fragment sequences (if the variant is not filtered and its spanning RNA
sequences can be given a reading frame).
Parameters
----------
variants_with_reads : sequence or generator
Each item of this sequence should be a pai... | def translate_variants(
variants_with_supporting_reads,
transcript_id_whitelist=None,
protein_sequence_length=PROTEIN_SEQUENCE_LENGTH,
min_alt_rna_reads=MIN_ALT_RNA_READS,
min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE,
min_transcript_prefix_length=MIN_TRANSC... |
Given a generator of (Variant, [Translation]) pairs,
returns a DataFrame of translated protein fragments with columns
for each field of a Translation object (and chr/pos/ref/alt per variant). | def translations_generator_to_dataframe(translations_generator):
"""
Given a generator of (Variant, [Translation]) pairs,
returns a DataFrame of translated protein fragments with columns
for each field of a Translation object (and chr/pos/ref/alt per variant).
"""
return dataframe_from_generator... |
Project Translation object or any other derived class into just a
TranslationKey, which has fewer fields and can be used as a
dictionary key. | def as_translation_key(self):
"""
Project Translation object or any other derived class into just a
TranslationKey, which has fewer fields and can be used as a
dictionary key.
"""
return TranslationKey(**{
name: getattr(self, name)
for name in Tran... |
Attempt to translate a single VariantSequence using the reading frame
from a single ReferenceContext.
Parameters
----------
variant_sequence : VariantSequence
reference_context : ReferenceContext
min_transcript_prefix_length : int
Minimum number of nucleoti... | def from_variant_sequence_and_reference_context(
cls,
variant_sequence,
reference_context,
min_transcript_prefix_length,
max_transcript_mismatches,
include_mismatches_after_variant,
protein_sequence_length=None):
"""
Att... |
Create a new component.
:param name: Name of the component
:param status: Status of the component; 1-4
:param description: (optional) Description of the component
:param link: (optional) A hyperlink to the component
:param order: (optional) Order of the component
:param ... | def postComponents(self, name, status, **kwargs):
'''Create a new component.
:param name: Name of the component
:param status: Status of the component; 1-4
:param description: (optional) Description of the component
:param link: (optional) A hyperlink to the component
:p... |
Create a new incident.
:param name: Name of the incident
:param message: A message (supporting Markdown) to explain more.
:param status: Status of the incident.
:param visible: Whether the incident is publicly visible.
:param component_id: (optional) Component to update.
... | def postIncidents(self, name, message, status, visible, **kwargs):
'''Create a new incident.
:param name: Name of the incident
:param message: A message (supporting Markdown) to explain more.
:param status: Status of the incident.
:param visible: Whether the incident is publicly... |
Create a new metric.
:param name: Name of metric
:param suffix: Measurments in
:param description: Description of what the metric is measuring
:param default_value: The default value to use when a point is added
:param display_chart: (optional) Whether to display the chart on th... | def postMetrics(self, name, suffix, description, default_value, **kwargs):
'''Create a new metric.
:param name: Name of metric
:param suffix: Measurments in
:param description: Description of what the metric is measuring
:param default_value: The default value to use when a poin... |
Add a metric point to a given metric.
:param id: Metric ID
:param value: Value to plot on the metric graph
:param timestamp: Unix timestamp of the point was measured
:return: :class:`Response <Response>` object
:rtype: requests.Response | def postMetricsPointsByID(self, id, value, **kwargs):
'''Add a metric point to a given metric.
:param id: Metric ID
:param value: Value to plot on the metric graph
:param timestamp: Unix timestamp of the point was measured
:return: :class:`Response <Response>` object
:rt... |
Calculate the center of mass of the indicated geometry.
Take a geometry and atom masses and compute the location of
the center of mass.
Parameters
----------
geom
length-3N |npfloat_| --
Coordinates of the atoms
masses
length-N OR length-3N |npfloat_| --
Atomic... | def ctr_mass(geom, masses):
"""Calculate the center of mass of the indicated geometry.
Take a geometry and atom masses and compute the location of
the center of mass.
Parameters
----------
geom
length-3N |npfloat_| --
Coordinates of the atoms
masses
length-N OR len... |
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-N OR length-3N |npfloat_| --
... | 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.
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)
.. todo:: Replace cite eventually with link t... | 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.
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 at the same time since the eigenvectors
must be processed to... | 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.
Calculates the rotational constants for the provided system with numerical
value given in the units provided in `units`. The orthnormality tolerance
`on_tol` is required in order to be passed through to the
:func:`principals` function.
If the sys... | 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
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_| --
Reference vector. Does not... | 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
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
length-3 |npfloat_| --
R... | 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
context_size : int
Max of nucleotides to include to the left and right of the variant
in the context sequence.
transcript_id_whitelist : set, optional
If given, then only consider transcripts whose IDs are in this set.
Returns list of ReferenceContext obj... | 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.
Parameters
----------
variants : varcode.VariantCollection
context_size : int
Max of nucleotides to include to the left and right of the variant
in the context sequence.
transcript_id_whitelist : set, optional... | 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.
Parameters
----------
variants : varcode.VariantCollection
context_size : int
Max of nucleotides to include to the left and right of the variant
in the context sequence.
transcript_id_whi... | 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.
This function calculates the start and end radian from the given width and
height, and then calls arc_by_radian function to draw the curve. | 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.
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
uniformly across the output 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.
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) -- Value to be typecast.
totype
... | 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.
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 greater than 24h
are unproblematic.... | 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
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 lengths, a
|False| value is returned.
Both coords vectors mus... | 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.
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 to be replaced in `template` by the entire text of the
value... | 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.
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
object to be checked, for use in raising of exceptions.
Rais... | 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.
Can be extended easily to support other criteria. | 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.
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 omitted due to failure
to meet the constraints. | 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.
The cartesian coordinates associated with a Hessian object
are considered consistent with the input `coords` and `atoms`
if each component matches to within `tol` and all atoms
are identical. If
`coords` or `ato... | 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
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, or
ignored if absent (stored as ... | 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.
:param settings_class: The class to register with the provided
conditions.
:param *simple_checks: A list of conditions for using the settings
clas... | 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] |
Consume the buffer up to the given token (from _peek_python_tokens).
Returns a single string that was consumed. | 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... |
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... |
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.
Parameters
----------
atom_syms
Squeezes to array of N |str| --
Element symbols for the XYZ. Must be valid elements as defined in
the keys of :data:`const.atom_num <opan.const.atom_num>`.
... | 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
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 retained throughout.
Parameters
----------
... | 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.
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/z coordinates
grouped together:... | 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.
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
Returns
-------
dist
|npfloat_| ... | 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.
Distances are in Bohrs as with :meth:`dist_single`.
See `above <toc-generators_>`_ for more information on
calling options.
Parameters
----------
g_nums
|int| or length-R iterable |int| or |None| --
... | 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.
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
|int| --
Index of the desired geometry
... | 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.
Angles are in degrees as with :meth:`angle_single`.
See `above <toc-generators_>`_ for more information on
calling options.
Parameters
----------
g_nums
|int| or iterable |int| or |None| --
Index of the desi... | 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.
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
defined such that a positive angle represents a counter-clockwise
... | 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.
Angles are in degrees as with :meth:`dihed_single`.
See `above <toc-generators_>`_ for more information on
calling options.
Parameters
----------
g_nums
|int| or iterable |int| or |None| --
Indices of the... | 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.
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 Bohrs.
Parameters
----------
g_num... | 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.
Displacements are in Bohrs as with :meth:`displ_single`.
See `above <toc-generators_>`_ for more information on
calling options.
Parameters
----------
g_nums
|int| or length-R iterable |int| or |None| --
... | 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.
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| value, and ensuring
that if a |Non... | 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.
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`
is raised, indicating an invalid index value, r... | 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.
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/``. | 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).
Parameters
----------
locus_reads : sequence of LocusRead records
n_ref : int
Number of reference nucleotides affected by variant.
Generate... | 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
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.