INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Return the weight corresponding to single power. | def _compute_value(power, wg):
"""Return the weight corresponding to single power."""
if power not in wg:
p1, p2 = power
# y power
if p1 == 0:
yy = wg[(0, -1)]
wg[power] = numpy.power(yy, p2 / 2).sum() / len(yy)
# x power
else:
xx = wg[... |
Add acquisition source.
:type submission_number: integer
:type email: integer
:type source: string
:param method: method of acquisition for the suggested document
:type method: string
:param orcid: orcid of the user that is creating the record
:type orcid: st... | def add_acquisition_source(
self,
method,
submission_number=None,
internal_uid=None,
email=None,
orcid=None,
source=None,
datetime=None,
):
"""Add acquisition source.
:type submission_number: integer
:type email: integer
... |
Return the weight corresponding to given powers. | def _compute_weight(powers, wg):
"""Return the weight corresponding to given powers."""
# split
pow1 = (powers[0], 0)
pow2 = (0, powers[1])
cal1 = _compute_value(pow1, wg)
cal2 = _compute_value(pow2, wg)
return cal1 * cal2 |
Fit a bidimensional polynomial to an image.
:param data: a bidimensional array
:param integer order: order of the polynomial
:param bool output_fit: return the fitted image
:returns: a tuple with an array with the coefficients of the polynomial terms
>>> import numpy
>>> xx, yy = numpy.mgrid[-... | def imsurfit(data, order, output_fit=False):
"""Fit a bidimensional polynomial to an image.
:param data: a bidimensional array
:param integer order: order of the polynomial
:param bool output_fit: return the fitted image
:returns: a tuple with an array with the coefficients of the polynomial terms
... |
Fetch data from Yahoo! Return a dict if successfull or None. | def _yql_query(yql):
"""Fetch data from Yahoo! Return a dict if successfull or None."""
url = _YAHOO_BASE_URL.format(urlencode({'q': yql}))
# send request
_LOGGER.debug("Send request to url: %s", url)
try:
request = urlopen(url)
rawData = request.read()
# parse jason
... |
Ask Yahoo! who is the woeid from GPS position. | def get_woeid(lat, lon):
"""Ask Yahoo! who is the woeid from GPS position."""
yql = _YQL_WOEID.format(lat, lon)
# send request
tmpData = _yql_query(yql)
if tmpData is None:
_LOGGER.error("No woid is received!")
return None
# found woid?
return tmpData.get("place", {}).get(... |
Fetch weather data from Yahoo! True if success. | def updateWeather(self):
"""Fetch weather data from Yahoo! True if success."""
yql = _YQL_WEATHER.format(self._woeid, self._unit)
# send request
tmpData = _yql_query(yql)
# data exists
if tmpData is not None and "channel" in tmpData:
self._data = tmpData["ch... |
Compatibility function, return mode=metal, when
available, mode=hill, when not (ASE <= 3.13) | def get_chemical_formula(atoms, mode='metal'):
"""
Compatibility function, return mode=metal, when
available, mode=hill, when not (ASE <= 3.13)
"""
try:
return atoms.get_chemical_formula(mode=mode)
except ValueError:
return atoms.get_chemical_formula(mode='hill') |
Potential energy for a list of atoms objects | def get_energies(atoms_list):
""" Potential energy for a list of atoms objects"""
if len(atoms_list) == 1:
return atoms_list[0].get_potential_energy()
elif len(atoms_list) > 1:
energies = []
for atoms in atoms_list:
energies.append(atoms.get_potential_energy())
re... |
Check if entry is allready in ASE db | def check_in_ase(atoms, ase_db, energy=None):
"""Check if entry is allready in ASE db"""
db_ase = ase.db.connect(ase_db)
if energy is None:
energy = atoms.get_potential_energy()
formula = get_chemical_formula(atoms)
rows = db_ase.select(energy=energy)
n = 0
ids = []
for row in r... |
Connect to ASE db | def write_ase(atoms, db_file, stdout=sys.stdout, user=None, data=None, **key_value_pairs):
"""Connect to ASE db"""
db_ase = ase.db.connect(db_file)
_normalize_key_value_pairs_inplace(key_value_pairs)
id = db_ase.write(atoms, data=data, **key_value_pairs)
stdout.write(' writing atoms to ASE db row i... |
Connect to ASE db | def update_ase(db_file, identity, stdout, **key_value_pairs):
"""Connect to ASE db"""
db_ase = ase.db.connect(db_file)
_normalize_key_value_pairs_inplace(key_value_pairs)
count = db_ase.update(identity, **key_value_pairs)
stdout.write(' Updating {0} key value pairs in ASE db row id = {1}\n'
... |
Define a new task. | def task(name, deps = None, fn = None):
"""Define a new task."""
if callable(deps):
fn = deps
deps = None
if not deps and not fn:
logger.log(logger.red("The task '%s' is empty" % name))
else:
tasks[name] = [fn, deps] |
Start a task. | def start(name, called = None):
"""Start a task."""
if name not in tasks:
logger.log(logger.red("Task '%s' not in your pylpfile" % name))
else:
task = tasks[name]
runner = TaskRunner(name, task[0], task[1], called)
running.append(runner)
return runner |
Find or create single document. Return (doc, created_now). | def get_or_create(cls, spec, defaults=None):
'''Find or create single document. Return (doc, created_now).'''
docs = list(cls.find(spec).limit(2))
assert len(docs) < 2, 'multiple docs returned'
if docs:
return docs[0], False
else:
kwargs = defaults or {}
... |
Return a model of the sum of N Gaussians and a constant background. | def sum_of_gaussian_factory(N):
"""Return a model of the sum of N Gaussians and a constant background."""
name = "SumNGauss%d" % N
attr = {}
# parameters
for i in range(N):
key = "amplitude_%d" % i
attr[key] = Parameter(key)
key = "center_%d" % i
attr[key] = Paramet... |
Apply global (integer) offsets to image.
Parameters
----------
image2d : numpy array
Input image
offx : int
Offset in the X direction (must be integer).
offy : int
Offset in the Y direction (must be integer).
Returns
-------
image2d_shifted : numpy array
... | def apply_integer_offsets(image2d, offx, offy):
"""Apply global (integer) offsets to image.
Parameters
----------
image2d : numpy array
Input image
offx : int
Offset in the X direction (must be integer).
offy : int
Offset in the Y direction (must be integer).
Return... |
Find cosmetic defects in a detector using two flat field images.
Two arrays representing flat fields of different exposure times are
required. Cosmetic defects are selected as points that deviate
significantly of the expected normal distribution of pixels in
the ratio between `flat2` and `flat1`. The m... | def ccdmask(flat1, flat2=None, mask=None, lowercut=6.0, uppercut=6.0,
siglev=1.0, mode='region', nmed=(7, 7), nsig=(15, 15)):
"""Find cosmetic defects in a detector using two flat field images.
Two arrays representing flat fields of different exposure times are
required. Cosmetic defects are se... |
Find cosmetic defects in a detector using two flat field images.
Two arrays representing flat fields of different exposure times are
required. Cosmetic defects are selected as points that deviate
significantly of the expected normal distribution of pixels in
the ratio between `flat2` and `flat1`.
... | def cosmetics(flat1, flat2 = None, mask=None, lowercut=6.0, uppercut=6.0, siglev=2.0):
"""Find cosmetic defects in a detector using two flat field images.
Two arrays representing flat fields of different exposure times are
required. Cosmetic defects are selected as points that deviate
significantly of ... |
Simple debouncing decorator for apigpio callbacks.
Example:
`@Debouncer()
def my_cb(gpio, level, tick)
print('gpio cb: {} {} {}'.format(gpio, level, tick))
`
The threshold can be given to the decorator as an argument (in millisec).
This decorator can be used both on function and obj... | def Debounce(threshold=100):
"""
Simple debouncing decorator for apigpio callbacks.
Example:
`@Debouncer()
def my_cb(gpio, level, tick)
print('gpio cb: {} {} {}'.format(gpio, level, tick))
`
The threshold can be given to the decorator as an argument (in millisec).
This decor... |
Wrapper around JWTIdentityPolicy.verify_refresh which verify
if the request to refresh the token is valid.
If valid it returns the userid which can be used to create to
create an updated identity with ``remember_identity``.
Otherwise it raises an exception based on InvalidTokenError.
:param request... | def verify_refresh_request(request):
"""
Wrapper around JWTIdentityPolicy.verify_refresh which verify
if the request to refresh the token is valid.
If valid it returns the userid which can be used to create to
create an updated identity with ``remember_identity``.
Otherwise it raises an exceptio... |
Compute a baseline trend of a signal | def detrend(arr, x=None, deg=5, tol=1e-3, maxloop=10):
"""Compute a baseline trend of a signal"""
xx = numpy.arange(len(arr)) if x is None else x
base = arr.copy()
trend = base
pol = numpy.ones((deg + 1,))
for _ in range(maxloop):
pol_new = numpy.polyfit(xx, base, deg)
pol_norm ... |
Peak-ground velocity [m/sec]. | def pgv(self, centimeters=False):
"""Peak-ground velocity [m/sec]."""
if self._pgv is None:
# Compute transfer function -- only over non-zero frequencies
mask = ~np.isclose(self.angular_freqs, 0)
tf = np.zeros_like(mask, dtype=np.complex)
tf[mask] = 1 / (s... |
Compute the pseudo-acceleration spectral response of an oscillator
with a specific frequency and damping.
Parameters
----------
osc_freq : float
Frequency of the oscillator (Hz).
osc_damping : float
Fractional damping of the oscillator (dec). For example,... | def calc_osc_accels(self, osc_freqs, osc_damping=0.05, tf=None):
"""Compute the pseudo-acceleration spectral response of an oscillator
with a specific frequency and damping.
Parameters
----------
osc_freq : float
Frequency of the oscillator (Hz).
osc_damping ... |
Compute the Fourier Amplitude Spectrum of the time series. | def _calc_fourier_spectrum(self, fa_length=None):
"""Compute the Fourier Amplitude Spectrum of the time series."""
if fa_length is None:
# Use the next power of 2 for the length
n = 1
while n < self.accels.size:
n <<= 1
else:
n = f... |
Compute the transfer function for a single-degree-of-freedom
oscillator.
The transfer function computes the pseudo-spectral acceleration.
Parameters
----------
osc_freq : float
natural frequency of the oscillator [Hz]
damping : float, optional
da... | def _calc_sdof_tf(self, osc_freq, damping=0.05):
"""Compute the transfer function for a single-degree-of-freedom
oscillator.
The transfer function computes the pseudo-spectral acceleration.
Parameters
----------
osc_freq : float
natural frequency of the osci... |
Read an AT2 formatted time series.
Parameters
----------
filename: str
Filename to open. | def load_at2_file(cls, filename):
"""Read an AT2 formatted time series.
Parameters
----------
filename: str
Filename to open.
"""
with open(filename) as fp:
next(fp)
description = next(fp).strip()
next(fp)
part... |
Read an SMC formatted time series.
Format of the time series is provided by:
https://escweb.wr.usgs.gov/nsmp-data/smcfmt.html
Parameters
----------
filename: str
Filename to open. | def load_smc_file(cls, filename):
"""Read an SMC formatted time series.
Format of the time series is provided by:
https://escweb.wr.usgs.gov/nsmp-data/smcfmt.html
Parameters
----------
filename: str
Filename to open.
"""
from .tools impo... |
Return surface reconstruction as well as primary and
secondary adsorption site labels | def get_info(self):
"""Return surface reconstruction as well as primary and
secondary adsorption site labels"""
reconstructed = self.is_reconstructed()
site, site_type = self.get_site()
return reconstructed, site, site_type |
Check if adsorbate dissociates | def check_dissociated(self, cutoff=1.2):
"""Check if adsorbate dissociates"""
dissociated = False
if not len(self.B) > self.nslab + 1: # only one adsorbate
return dissociated
adsatoms = [atom for atom in self.B[self.nslab:]]
ads0, ads1 = set(atom.symbol for atom in ... |
Compare initial and final slab configuration
to determine if slab reconstructs during relaxation
xy_cutoff: Allowed xy-movement is determined from
the covalent radii as:
xy_cutoff * np.mean(cradii)
z_cutoff: Allowed z-movement is determined as
... | def is_reconstructed(self, xy_cutoff=0.3, z_cutoff=0.4):
"""Compare initial and final slab configuration
to determine if slab reconstructs during relaxation
xy_cutoff: Allowed xy-movement is determined from
the covalent radii as:
xy_cutoff * np.mean(cradi... |
Get dictionary with high symmetry sites close to adsorbate
position.
Top sites: Optained from the atomic positions of
the top layer of the slab.
Bridge sites: The average position of atomic pairs
Hollow sites: Optained as the Voronoi vertices
4-fold sites: As... | def get_site_dict(self, ads_pos):
"""Get dictionary with high symmetry sites close to adsorbate
position.
Top sites: Optained from the atomic positions of
the top layer of the slab.
Bridge sites: The average position of atomic pairs
Hollow sites: Optained as ... |
Return element closest to the adsorbate in the subsurface layer | def get_under_bridge(self):
"""Return element closest to the adsorbate in the subsurface layer"""
C0 = self.B[-1:] * (3, 3, 1)
ads_pos = C0.positions[4]
C = self.get_subsurface_layer() * (3, 3, 1)
dis = self.B.cell[0][0] * 2
ret = None
for ele in C:
... |
Return HCP if an atom is present below the adsorbate in the
subsurface layer and FCC if not | def get_under_hollow(self):
""" Return HCP if an atom is present below the adsorbate in the
subsurface layer and FCC if not"""
C0 = self.B[-1:] * (3, 3, 1)
ads_pos = C0.positions[4]
C = self.get_subsurface_layer() * (3, 3, 1)
ret = 'FCC'
if np.any([np.linalg.no... |
Return primaty (top, bridge, hollow, 4fold) and
secondary (chemical elements in close environment) site designation | def get_site(self, plot_voronoi_sites=False):
"""Return primaty (top, bridge, hollow, 4fold) and
secondary (chemical elements in close environment) site designation"""
if self.dissociated:
return 'dissociated', ''
if self.is_desorbed():
return 'desorbed', ''
... |
Compute image distortion transformation.
This function computes the following 2D transformation:
x_orig = sum[i=0:order]( sum[j=0:j]( a_ij * x_rect**(i - j) * y_rect**j ))
y_orig = sum[i=0:order]( sum[j=0:j]( b_ij * x_rect**(i - j) * y_rect**j ))
Parameters
----------
x_orig : numpy array
... | def compute_distortion(x_orig, y_orig, x_rect, y_rect, order, debugplot):
"""Compute image distortion transformation.
This function computes the following 2D transformation:
x_orig = sum[i=0:order]( sum[j=0:j]( a_ij * x_rect**(i - j) * y_rect**j ))
y_orig = sum[i=0:order]( sum[j=0:j]( b_ij * x_rect**(i... |
Evaluate the 2D polynomial transformation.
u = sum[i=0:order]( sum[j=0:j]( a_ij * x**(i - j) * y**j ))
v = sum[i=0:order]( sum[j=0:j]( b_ij * x**(i - j) * y**j ))
Parameters
----------
order : int
Order of the polynomial transformation.
aij : numpy array
Polynomial coefficents ... | def fmap(order, aij, bij, x, y):
"""Evaluate the 2D polynomial transformation.
u = sum[i=0:order]( sum[j=0:j]( a_ij * x**(i - j) * y**j ))
v = sum[i=0:order]( sum[j=0:j]( b_ij * x**(i - j) * y**j ))
Parameters
----------
order : int
Order of the polynomial transformation.
aij : num... |
Expected number of coefficients in a 2D transformation of a given order.
Parameters
----------
order : int
Order of the 2D polynomial transformation.
Returns
-------
ncoef : int
Expected number of coefficients. | def ncoef_fmap(order):
"""Expected number of coefficients in a 2D transformation of a given order.
Parameters
----------
order : int
Order of the 2D polynomial transformation.
Returns
-------
ncoef : int
Expected number of coefficients.
"""
ncoef = 0
for i in ... |
Compute order corresponding to a given number of coefficients.
Parameters
----------
ncoef : int
Number of coefficients.
Returns
-------
order : int
Order corresponding to the provided number of coefficients. | def order_fmap(ncoef):
"""Compute order corresponding to a given number of coefficients.
Parameters
----------
ncoef : int
Number of coefficients.
Returns
-------
order : int
Order corresponding to the provided number of coefficients.
"""
loop = True
order = 1... |
Rectify image applying the provided 2D transformation.
The rectified image correspond to the transformation given by:
u = sum[i=0:order]( sum[j=0:j]( a_ij * x**(i - j) * y**j ))
v = sum[i=0:order]( sum[j=0:j]( b_ij * x**(i - j) * y**j ))
Parameters
----------
image2d : 2d numpy array
... | def rectify2d(image2d, aij, bij, resampling,
naxis1out=None, naxis2out=None,
ioffx=None, ioffy=None,
debugplot=0):
"""Rectify image applying the provided 2D transformation.
The rectified image correspond to the transformation given by:
u = sum[i=0:order]( sum[j... |
Args:
obj (object): The object whose property values are used to build the URL.
Returns:
str: The URL to which to go if the form was processed successfully. | def get_success_url(self, obj=None):
"""
Args:
obj (object): The object whose property values are used to build the URL.
Returns:
str: The URL to which to go if the form was processed successfully.
"""
if self.success_endpoint is None:
raise A... |
Returns the name of the template.
If the template_name property is not set, the value will be generated automatically based on the class name.
Example:
>>> class MyEntityAction(BaseView): pass
>>> view = MyEntityAction()
>>> view.get_template_name()
"my_... | def get_template_name(self):
"""
Returns the name of the template.
If the template_name property is not set, the value will be generated automatically based on the class name.
Example:
>>> class MyEntityAction(BaseView): pass
>>> view = MyEntityAction()
... |
Conversion from geodetic to geocentric coordinates by using the WGS84 spheroid.
:param theta: colatitude (float, rad)
:param alt: altitude (float, km)
:return gccolat: geocentric colatitude (float, rad)
d: gccolat minus theta (float, rad)
r: geocentric radius (float, km) | def geodetic2geocentric(theta, alt):
"""
Conversion from geodetic to geocentric coordinates by using the WGS84 spheroid.
:param theta: colatitude (float, rad)
:param alt: altitude (float, km)
:return gccolat: geocentric colatitude (float, rad)
d: gccolat minus theta (float, rad)
... |
This is a synthesis routine for the 12th generation IGRF as agreed
in December 2014 by IAGA Working Group V-MOD. It is valid 1900.0 to
2020.0 inclusive. Values for dates from 1945.0 to 2010.0 inclusive are
definitive, otherwise they are non-definitive.
INPUT
isv = 0 if main-field values are req... | def igrf12syn(isv, date, itype, alt, lat, elong):
"""
This is a synthesis routine for the 12th generation IGRF as agreed
in December 2014 by IAGA Working Group V-MOD. It is valid 1900.0 to
2020.0 inclusive. Values for dates from 1945.0 to 2010.0 inclusive are
definitive, otherwise they are non-d... |
Append a new file in the stream. | def append_file(self, file):
"""Append a new file in the stream."""
self.files.append(file)
if self.transformer:
future = asyncio.ensure_future(self.transformer.transform(file))
future.add_done_callback(self.handle_transform) |
Call 'flush' function if all files have been transformed. | def flush_if_ended(self):
"""Call 'flush' function if all files have been transformed."""
if self.ended and self.next and len(self.files) == self.transformed:
future = asyncio.ensure_future(self.transformer.flush())
future.add_done_callback(lambda x: self.next.end_of_stream()) |
Handle a 'transform' callback. | def handle_transform(self, task):
"""Handle a 'transform' callback."""
self.transformed += 1
file = task.result()
if file:
self.next.append_file(file)
self.flush_if_ended() |
Pipe this stream to another. | def pipe(self, transformer):
"""Pipe this stream to another."""
if self.next:
return
stream = Stream()
self.next = stream
stream.prev = self
self.transformer = transformer
transformer.stream = self
transformer.piped()
for file in self.files:
future = asyncio.ensure_future(self.transformer.tra... |
Pipe several transformers end to end. | def pipes(stream, *transformers):
"""Pipe several transformers end to end."""
for transformer in transformers:
stream = stream.pipe(transformer)
return stream |
Convert input values to type values. | def convert(self, val):
"""Convert input values to type values."""
pre = super(Parameter, self).convert(val)
if self.custom_validator is not None:
post = self.custom_validator(pre)
else:
post = pre
return post |
Validate values according to the requirement | def validate(self, val):
"""Validate values according to the requirement"""
if self.validation:
self.type.validate(val)
if self.custom_validator is not None:
self.custom_validator(val)
return True |
Decorator for the View classes. | def route(obj, rule, *args, **kwargs):
"""Decorator for the View classes."""
def decorator(cls):
endpoint = kwargs.get('endpoint', camel_to_snake(cls.__name__))
kwargs['view_func'] = cls.as_view(endpoint)
obj.add_url_rule(rule, *args, **kwargs)
return cls
return decorator |
Fit to a target crustal amplification or site term.
The fitting process adjusts the velocity, site attenuation, and layer
thickness (if enabled) to fit a target values. The frequency range is
specified by the input motion.
Parameters
----------
target_type: str
... | def fit(self,
target_type,
target,
adjust_thickness=False,
adjust_site_atten=False,
adjust_source_vel=False):
"""
Fit to a target crustal amplification or site term.
The fitting process adjusts the velocity, site attenuation, and layer... |
Compute the wave numbers and amplitudes (up- and down-going).
Parameters
----------
angular_freqs: :class:`numpy.ndarray`
Angular frequency at which the waves are computed.
profile: :class:`~.base.site.Profile`
Site profile. | def _calc_waves(self, angular_freqs, profile):
"""Compute the wave numbers and amplitudes (up- and down-going).
Parameters
----------
angular_freqs: :class:`numpy.ndarray`
Angular frequency at which the waves are computed.
profile: :class:`~.base.site.Profile`
... |
Compute the wave field at specific location.
Parameters
----------
l : site.Location
:class:`site.Location` of the input
Returns
-------
`np.ndarray`
Amplitude and phase of waves | def wave_at_location(self, l):
"""Compute the wave field at specific location.
Parameters
----------
l : site.Location
:class:`site.Location` of the input
Returns
-------
`np.ndarray`
Amplitude and phase of waves
"""
cterm... |
Compute the acceleration transfer function.
Parameters
----------
lin : :class:`~site.Location`
Location of input
lout : :class:`~site.Location`
Location of output. Note that this would typically be midheight
of the layer. | def calc_accel_tf(self, lin, lout):
"""Compute the acceleration transfer function.
Parameters
----------
lin : :class:`~site.Location`
Location of input
lout : :class:`~site.Location`
Location of output. Note that this would typically be midheight
... |
Compute the stress transfer function.
Parameters
----------
lin : :class:`~site.Location`
Location of input
lout : :class:`~site.Location`
Location of output. Note that this would typically be midheight
of the layer. | def calc_stress_tf(self, lin, lout, damped):
"""Compute the stress transfer function.
Parameters
----------
lin : :class:`~site.Location`
Location of input
lout : :class:`~site.Location`
Location of output. Note that this would typically be midheight
... |
Compute the strain transfer function from `lout` to
`location_in`.
The strain transfer function from the acceleration at layer `n`
(outcrop) to the mid-height of layer `m` (within) is defined as
Parameters
----------
lin : :class:`~site.Location`
Location of... | def calc_strain_tf(self, lin, lout):
"""Compute the strain transfer function from `lout` to
`location_in`.
The strain transfer function from the acceleration at layer `n`
(outcrop) to the mid-height of layer `m` (within) is defined as
Parameters
----------
lin :... |
Compute an estimate of the strains. | def _estimate_strains(self):
"""Compute an estimate of the strains."""
# Estimate the strain based on the PGV and shear-wave velocity
for l in self._profile:
l.reset()
l.strain = self._motion.pgv / l.initial_shear_vel |
Compute the strain used for iterations of material properties. | def _calc_strain(self, loc_input, loc_layer, motion, *args):
"""Compute the strain used for iterations of material properties."""
strain_max = self._calc_strain_max(loc_input, loc_layer, motion, *args)
return self.strain_ratio * strain_max |
Compute the effective strain at the center of a layer. | def _calc_strain_max(self, loc_input, loc_layer, motion, *args):
"""Compute the effective strain at the center of a layer."""
return motion.calc_peak(
self.calc_strain_tf(loc_input, loc_layer)) |
Estimate the strains by running an EQL site response.
This step was recommended in Section 8.3.1 of Zalachoris (2014). | def _estimate_strains(self):
"""Estimate the strains by running an EQL site response.
This step was recommended in Section 8.3.1 of Zalachoris (2014).
"""
eql = EquivalentLinearCalculator()
eql(self._motion, self._profile, self._loc_input) |
Decorator to measure the time used by the recipe | def timeit(method):
"""Decorator to measure the time used by the recipe"""
import datetime
@functools.wraps(method)
def timed_method(self, rinput):
time_start = datetime.datetime.utcnow()
result = method(self, rinput)
time_end = datetime.datetime.utcnow()
result.time_i... |
Save intermediate FITS objects. | def save_intermediate_img(self, img, name):
"""Save intermediate FITS objects."""
if self.intermediate_results:
img.writeto(name, overwrite=True) |
Save intermediate array object as FITS. | def save_intermediate_array(self, array, name):
"""Save intermediate array object as FITS."""
if self.intermediate_results:
fits.writeto(name, array, overwrite=True) |
Set metadata in FITS headers. | def set_base_headers(self, hdr):
"""Set metadata in FITS headers."""
hdr['NUMXVER'] = (__version__, 'Numina package version')
hdr['NUMRNAM'] = (self.__class__.__name__, 'Numina recipe name')
hdr['NUMRVER'] = (self.__version__, 'Numina recipe version')
return hdr |
Build a RecipeInput object. | def build_recipe_input(self, ob, dal):
"""Build a RecipeInput object."""
result = {}
# We have to decide if the ob input
# is a plain description (ObservingBlock)
# or if it contains the nested results (Obsres)
#
# it has to contain the tags corresponding to the ... |
Returns a dictionary with subsets of FileInfo instances from a TXT file.
Each subset of files must be preceded by a line:
@ <number> <label>
where <number> indicates the number of files in that subset,
and <label> is a label for that subset. Any additional text
beyond <label> in the same line is ig... | def subsets_of_fileinfo_from_txt(filename):
"""Returns a dictionary with subsets of FileInfo instances from a TXT file.
Each subset of files must be preceded by a line:
@ <number> <label>
where <number> indicates the number of files in that subset,
and <label> is a label for that subset. Any additi... |
Compute the slice representation of intersection of two arrays.
Given the shapes of two arrays and a reference point ref, compute the
intersection of the two arrays.
It returns a tuple of slices, that can be passed to the two \
images as indexes
:param shape: the shape of the reference array
:... | def subarray_match(shape, ref, sshape, sref=None):
"""Compute the slice representation of intersection of two arrays.
Given the shapes of two arrays and a reference point ref, compute the
intersection of the two arrays.
It returns a tuple of slices, that can be passed to the two \
images as indexes... |
Scale an array to a new shape. | def rebin_scale(a, scale=1):
"""Scale an array to a new shape."""
newshape = tuple((side * scale) for side in a.shape)
return rebin(a, newshape) |
Rebin an array to a new shape. | def rebin(a, newshape):
"""Rebin an array to a new shape."""
slices = [slice(0, old, float(old)/new)
for old, new in zip(a.shape, newshape)]
coordinates = numpy.mgrid[slices]
# choose the biggest smaller integer index
indices = coordinates.astype('i')
return a[tuple(indices)] |
Interpolate 2D array data in rows | def fixpix(data, mask, kind='linear'):
"""Interpolate 2D array data in rows"""
if data.shape != mask.shape:
raise ValueError
if not numpy.any(mask):
return data
x = numpy.arange(0, data.shape[0])
for row, mrow in zip(data, mask):
if numpy.any(mrow): # Interpolate if there'... |
Substitute pixels in mask by a bilinear least square fitting. | def fixpix2(data, mask, iterations=3, out=None):
"""Substitute pixels in mask by a bilinear least square fitting.
"""
out = out if out is not None else data.copy()
# A binary mask, regions are ones
binry = mask != 0
# Label regions in the binary mask
lblarr, labl = ndimage.label(binry)
... |
Return x if it is an array or create an array and fill it with x. | def numberarray(x, shape):
"""Return x if it is an array or create an array and fill it with x."""
try:
iter(x)
except TypeError:
return numpy.ones(shape) * x
else:
return x |
Returns the token model instance associated with the given request token key.
If no user is retrieved AnonymousToken is returned. | def get_token(request):
"""
Returns the token model instance associated with the given request token key.
If no user is retrieved AnonymousToken is returned.
"""
if (not request.META.get(header_name_to_django(auth_token_settings.HEADER_NAME)) and
config.CHAMBER_MULTIDOMAINS_OVERTAKER_AUT... |
Lazy set user and token | def process_request(self, request):
"""
Lazy set user and token
"""
request.token = get_token(request)
request.user = SimpleLazyObject(lambda: get_user(request))
request._dont_enforce_csrf_checks = dont_enforce_csrf_checks(request) |
Auxiliary function to call ximplotxy from a jupyter notebook. | def ximplotxy_jupyter(x, y, fmt=None, **args):
"""Auxiliary function to call ximplotxy from a jupyter notebook.
"""
using_jupyter = True
if fmt is None:
return ximplotxy(x, y, using_jupyter=using_jupyter, **args)
else:
return ximplotxy(x, y, fmt, using_jupyter=using_jupyter, **args) |
Parameters
----------
x : 1d numpy array, float
Array containing the X coordinate.
y : 1d numpy array, float
Array containing the Y coordinate.
fmt : str, optional
Format string for quickly setting basic line properties.
plottype : string
Plot type. It can be 'loglog'... | def ximplotxy(x, y, fmt=None, plottype=None,
xlim=None, ylim=None,
xlabel=None, ylabel=None, title=None,
show=True, geometry=(0, 0, 640, 480), tight_layout=True,
debugplot=0, using_jupyter=False,
**kwargs):
"""
Parameters
----------
... |
Decorator helper that overrides django atomic decorator and automatically adds create revision. | def atomic(func):
"""
Decorator helper that overrides django atomic decorator and automatically adds create revision.
"""
try:
from reversion.revisions import create_revision
return transaction.atomic(create_revision()(func))
except ImportError:
return transaction.atomic(fun... |
Register a handler or a function to be called after successful code pass.
If transaction signals are not active the handler/function is called immediately.
:param handler: handler or function that will be called.
:param using: name of the database | def on_success(handler, using=None):
"""
Register a handler or a function to be called after successful code pass.
If transaction signals are not active the handler/function is called immediately.
:param handler: handler or function that will be called.
:param using: name of the database
"""
... |
Atomic decorator with transaction signals. | def atomic_with_signals(func):
"""
Atomic decorator with transaction signals.
"""
try:
from reversion.revisions import create_revision
return transaction.atomic(create_revision()(transaction_signals(func)))
except ImportError:
return transaction.atomic(transaction_signals(fu... |
Parse the XML file using the processor starting from the root of the document.
:param root_processor: Root processor of the XML document.
:param xml_file_path: Path to XML file to parse.
:param encoding: Encoding of the file.
:return: Parsed value. | def parse_from_file(
root_processor, # type: RootProcessor
xml_file_path, # type: Text
encoding='utf-8' # type: Text
):
# type: (...) -> Any
"""
Parse the XML file using the processor starting from the root of the document.
:param root_processor: Root processor of the XML doc... |
Parse the XML string using the processor starting from the root of the document.
:param xml_string: XML string to parse.
See also :func:`declxml.parse_from_file` | def parse_from_string(
root_processor, # type: RootProcessor
xml_string # type: Text
):
# type: (...) -> Any
"""
Parse the XML string using the processor starting from the root of the document.
:param xml_string: XML string to parse.
See also :func:`declxml.parse_from_file`
"... |
Serialize the value to an XML file using the root processor.
:param root_processor: Root processor of the XML document.
:param value: Value to serialize.
:param xml_file_path: Path to the XML file to which the serialized value will be written.
:param encoding: Encoding of the file.
:param indent: I... | def serialize_to_file(
root_processor, # type: RootProcessor
value, # type: Any
xml_file_path, # type: Text
encoding='utf-8', # type: Text
indent=None # type: Optional[Text]
):
# type: (...) -> None
"""
Serialize the value to an XML file using the root processor.... |
Serialize the value to an XML string using the root processor.
:return: The serialized XML string.
See also :func:`declxml.serialize_to_file` | def serialize_to_string(
root_processor, # type: RootProcessor
value, # type: Any
indent=None # type: Optional[Text]
):
# type: (...) -> Text
"""
Serialize the value to an XML string using the root processor.
:return: The serialized XML string.
See also :func:`declxml.se... |
Create an array processor that can be used to parse and serialize array data.
XML arrays may be nested within an array element, or they may be embedded
within their parent. A nested array would look like:
.. sourcecode:: xml
<root-element>
<some-element>ABC</some-element>
... | def array(
item_processor, # type: Processor
alias=None, # type: Optional[Text]
nested=None, # type: Optional[Text]
omit_empty=False, # type: bool
hooks=None # type: Optional[Hooks]
):
# type: (...) -> RootProcessor
"""
Create an array processor that can be used ... |
Create a processor for boolean values.
:param element_name: Name of the XML element containing the value. Can also be specified
using supported XPath syntax.
:param attribute: If specified, then the value is searched for under the
attribute within the element specified by element_name. If not s... | def boolean(
element_name, # type: Text
attribute=None, # type: Optional[Text]
required=True, # type: bool
alias=None, # type: Optional[Text]
default=False, # type: Optional[bool]
omit_empty=False, # type: bool
hooks=None # type: Optional[Hooks]
):
# ty... |
Create a processor for dictionary values.
:param element_name: Name of the XML element containing the dictionary value. Can also be
specified using supported XPath syntax.
:param children: List of declxml processor objects for processing the children
contained within the dictionary.
:param ... | def dictionary(
element_name, # type: Text
children, # type: List[Processor]
required=True, # type: bool
alias=None, # type: Optional[Text]
hooks=None # type: Optional[Hooks]
):
# type: (...) -> RootProcessor
"""
Create a processor for dictionary values.
:pa... |
Create a processor for floating point values.
See also :func:`declxml.boolean` | def floating_point(
element_name, # type: Text
attribute=None, # type: Optional[Text]
required=True, # type: bool
alias=None, # type: Optional[Text]
default=0.0, # type: Optional[float]
omit_empty=False, # type: bool
hooks=None # type: Optional[Hooks]
):
... |
Create a processor for integer values.
See also :func:`declxml.boolean` | def integer(
element_name, # type: Text
attribute=None, # type: Optional[Text]
required=True, # type: bool
alias=None, # type: Optional[Text]
default=0, # type: Optional[int]
omit_empty=False, # type: bool
hooks=None # type: Optional[Hooks]
):
# type: (... |
Create a processor for namedtuple values.
:param tuple_type: The namedtuple type.
See also :func:`declxml.dictionary` | def named_tuple(
element_name, # type: Text
tuple_type, # type: Type[Tuple]
child_processors, # type: List[Processor]
required=True, # type: bool
alias=None, # type: Optional[Text]
hooks=None # type: Optional[Hooks]
):
# type: (...) -> RootProcessor
"""
... |
Create a processor for string values.
:param strip_whitespace: Indicates whether leading and trailing whitespace should be stripped
from parsed string values.
See also :func:`declxml.boolean` | def string(
element_name, # type: Text
attribute=None, # type: Optional[Text]
required=True, # type: bool
alias=None, # type: Optional[Text]
default='', # type: Optional[Text]
omit_empty=False, # type: bool
strip_whitespace=True, # type: bool
hooks=... |
Create a processor for user objects.
:param cls: Class object with a no-argument constructor or other callable no-argument object.
See also :func:`declxml.dictionary` | def user_object(
element_name, # type: Text
cls, # type: Type[Any]
child_processors, # type: List[Processor]
required=True, # type: bool
alias=None, # type: Optional[Text]
hooks=None # type: Optional[Hooks]
):
# type: (...) -> RootProcessor
"""
Create a ... |
Append the list of element names as a path to the provided start element.
:return: The final element along the path. | def _element_append_path(
start_element, # type: ET.Element
element_names # type: Iterable[Text]
):
# type: (...) -> ET.Element
"""
Append the list of element names as a path to the provided start element.
:return: The final element along the path.
"""
end_element = start_elem... |
Find the element specified by the given path starting from the root element of the document.
The first component of the element path is expected to be the name of the root element. Return
None if the element is not found. | def _element_find_from_root(
root, # type: ET.Element
element_path # type: Text
):
# type: (...) -> Optional[ET.Element]
"""
Find the element specified by the given path starting from the root element of the document.
The first component of the element path is expected to be the name ... |
Ensure all elements specified in the given path relative to the provided parent element exist.
Create new elements along the path only when needed, and return the final element specified
by the path. | def _element_get_or_add_from_parent(
parent, # type: ET.Element
element_path # type: Text
):
# type: (...) -> ET.Element
"""
Ensure all elements specified in the given path relative to the provided parent element exist.
Create new elements along the path only when needed, and return t... |
Create an entirely new element path.
Return a tuple where the first item is the first element in the path, and the second item is
the final element in the path. | def _element_path_create_new(element_path):
# type: (Text) -> Tuple[ET.Element, ET.Element]
"""
Create an entirely new element path.
Return a tuple where the first item is the first element in the path, and the second item is
the final element in the path.
"""
element_names = element_path.s... |
Apply the after parse hook. | def _hooks_apply_after_parse(
hooks, # type: Optional[Hooks]
state, # type: _ProcessorState
value # type: Any
):
# type: (...) -> Any
"""Apply the after parse hook."""
if hooks and hooks.after_parse:
return hooks.after_parse(ProcessorStateView(state), value)
return va... |
Apply the before serialize hook. | def _hooks_apply_before_serialize(
hooks, # type: Optional[Hooks]
state, # type: _ProcessorState
value # type: Any
):
# type: (...) -> Any
"""Apply the before serialize hook."""
if hooks and hooks.before_serialize:
return hooks.before_serialize(ProcessorStateView(state), v... |
Return an _AggregateConverter for named tuples of the given type. | def _named_tuple_converter(tuple_type):
# type: (Type[Tuple]) -> _AggregateConverter
"""Return an _AggregateConverter for named tuples of the given type."""
def _from_dict(dict_value):
if dict_value:
return tuple_type(**dict_value)
# Cannot construct a namedtuple value from an e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.