INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
find xml
:param url: contents url
:param features: markup provider
:param headers: http header
:return: BeautifulSoup object | def find_xml(cls, url, features):
"""
find xml
:param url: contents url
:param features: markup provider
:param headers: http header
:return: BeautifulSoup object
"""
req = cls._get_content(url)
if req.status_code in range(200, 300):
re... |
find xml(list)
:param url: contents url
:param markup: markup provider
:param tag: find tag
:param pattern: xml file pattern
:return: BeautifulSoup object list | def find_xml_all(cls, url, markup, tag, pattern):
"""
find xml(list)
:param url: contents url
:param markup: markup provider
:param tag: find tag
:param pattern: xml file pattern
:return: BeautifulSoup object list
"""
body = cls.find_xml(url, marku... |
Get attribute for Beautifulsoup object
:param soup: Beautifulsoup object
:param key: attribute key
:param unknown: attribute key not exists value(default:None)
:return: attribute value | def get_attribute(cls, soup, key, unknown=None):
"""
Get attribute for Beautifulsoup object
:param soup: Beautifulsoup object
:param key: attribute key
:param unknown: attribute key not exists value(default:None)
:return: attribute value
"""
if key in soup... |
Get attribute for Beautifulsoup object
:param soup: Beautifulsoup object
:param key: attribute key
:param data_type: Data type(int, float, etc...)
:param unknown: attribute key not exists value(default:None)
:return: (data_type)attribute value | def get_attribute_stats(cls, soup, key, data_type=str, unknown=None):
"""
Get attribute for Beautifulsoup object
:param soup: Beautifulsoup object
:param key: attribute key
:param data_type: Data type(int, float, etc...)
:param unknown: attribute key not exists value(defa... |
Calculates the edit distance between two tokens. | def token_distance(t1, t2, initial_match_penalization):
"""Calculates the edit distance between two tokens."""
if isinstance(t1, NameInitial) or isinstance(t2, NameInitial):
if t1.token == t2.token:
return 0
if t1 == t2:
return initial_match_penalization
return 1.... |
Simple tokenizer function to be used with the normalizers. | def simple_tokenize(name):
"""Simple tokenizer function to be used with the normalizers."""
last_names, first_names = name.split(',')
last_names = _RE_NAME_TOKEN_SEPARATOR.split(last_names)
first_names = _RE_NAME_TOKEN_SEPARATOR.split(first_names)
first_names = [NameToken(n) if len(n) > 1 else Name... |
Determines rotatable bonds in a ligand molecule
Takes:
* mol * - mol file in rdkit environment
Output:
* bonds * - tuples of atom ids | def get_rotatable_bonds(self,mol):
"""Determines rotatable bonds in a ligand molecule
Takes:
* mol * - mol file in rdkit environment
Output:
* bonds * - tuples of atom ids
"""
RotatableBondSmarts = Chem.MolFromSmarts('[!$(*#*)&!D1]-&!@[!$(*#*)&!D1]')
bonds = mol.GetSubstructMatches(RotatableBondSmarts... |
Calculates descriptors such as logP, charges and MR and saves that in a dictionary. | def calculate_descriptors(self,mol):
"""Calculates descriptors such as logP, charges and MR and saves that in a dictionary."""
#make dictionary
self.ligand_atoms = {index:{"name":x.name} for index,x in enumerate(self.topology_data.universe.ligand_noH.atoms)}
#Calculate logP and MR
contribs = self.calculate_l... |
Calculates formal charge for each atom.
Takes:
* mol * - mol file in rdkit environment
Output:
* formal_charges * - list of charges | def calculate_formal_charge(self,mol):
"""Calculates formal charge for each atom.
Takes:
* mol * - mol file in rdkit environment
Output:
* formal_charges * - list of charges
"""
formal_charges = []
for atom in mol.GetAtoms():
formal_charges.append(atom.GetFormalCharge())
return formal_charges |
return geohash for given point with self.precision
:param point: GeoPoint instance
:return: string | def get_point_hash(self, point):
"""
return geohash for given point with self.precision
:param point: GeoPoint instance
:return: string
"""
return geohash.encode(point.latitude, point.longitude, self.precision) |
add point to index, point must be a GeoPoint instance
:param point:
:return: | def add_point(self, point):
"""
add point to index, point must be a GeoPoint instance
:param point:
:return:
"""
assert isinstance(point, GeoPoint), \
'point should be GeoPoint instance'
point_hash = self.get_point_hash(point)
points = self.dat... |
return approx list of point from circle with given center and radius
it uses geohash and return with some error (see GEO_HASH_ERRORS)
:param center_point: center of search circle
:param radius: radius of search circle
:return: list of GeoPoints from given area | def get_nearest_points_dirty(self, center_point, radius, unit='km'):
"""
return approx list of point from circle with given center and radius
it uses geohash and return with some error (see GEO_HASH_ERRORS)
:param center_point: center of search circle
:param radius: radius of sea... |
return list of geo points from circle with given center and radius
:param center_point: GeoPoint with center of search circle
:param radius: radius of search circle
:return: generator with tuple with GeoPoints and distance | def get_nearest_points(self, center_point, radius, unit='km'):
"""
return list of geo points from circle with given center and radius
:param center_point: GeoPoint with center of search circle
:param radius: radius of search circle
:return: generator with tuple with GeoPoints and... |
Return a specific variant.
Args:
case_id (str): Path to vcf file
variant_id (str): A variant id
Returns:
variant (Variant): The variant object for the given id | def variant(self, case_id, variant_id):
"""Return a specific variant.
Args:
case_id (str): Path to vcf file
variant_id (str): A variant id
Returns:
variant (Variant): The variant object for the given id
"""
case_obj = self... |
Return all variants in the VCF.
This function will apply the given filter and return the 'count' first
variants. If skip the first 'skip' variants will not be regarded.
Args:
case_id (str): Path to a vcf file (for this adapter)
skip (int): Skip first variant... | def variants(self, case_id, skip=0, count=1000, filters=None):
"""Return all variants in the VCF.
This function will apply the given filter and return the 'count' first
variants. If skip the first 'skip' variants will not be regarded.
Args:
case_id (str): Path to a ... |
Check if variants follows the filters
This function will try to make filters faster for the vcf adapter
Args:
vcf_file_path(str): Path to vcf
filters (dict): A dictionary with filters
Yields:
varian_line (str): A vcf variant line | def _get_filtered_variants(self, vcf_file_path, filters={}):
"""Check if variants follows the filters
This function will try to make filters faster for the vcf adapter
Args:
vcf_file_path(str): Path to vcf
filters (dict): A dictionary with filters
... |
Return a Variant object
Format variant make a variant that includes enough information for
the variant view.
If add_all_info then all transcripts will be parsed
Args:
variant (cython2.Variant): A variant object
index (int): The index of the variant
c... | def _format_variants(self, variant, index, case_obj, add_all_info=False):
"""Return a Variant object
Format variant make a variant that includes enough information for
the variant view.
If add_all_info then all transcripts will be parsed
Args:
variant (cython2.Varia... |
Core FNV hash algorithm used in FNV0 and FNV1. | def fnv(data, hval_init, fnv_prime, fnv_size):
"""
Core FNV hash algorithm used in FNV0 and FNV1.
"""
assert isinstance(data, bytes)
hval = hval_init
for byte in data:
hval = (hval * fnv_prime) % fnv_size
hval = hval ^ _get_byte(byte)
return hval |
Send session_prepare signal in session "before_commit".
The signal contains another event argument, which records whole info
of what's changed in this session, so the signal receiver can receive
and record the event. | def session_prepare(self, session, _):
"""Send session_prepare signal in session "before_commit".
The signal contains another event argument, which records whole info
of what's changed in this session, so the signal receiver can receive
and record the event.
"""
if not h... |
Send session_commit signal in sqlalchemy ``before_commit``.
This marks the success of session so the session may enter commit
state. | def session_commit(self, session):
"""Send session_commit signal in sqlalchemy ``before_commit``.
This marks the success of session so the session may enter commit
state.
"""
# this may happen when there's nothing to commit
if not hasattr(session, 'meepo_unique_id'):
... |
Send session_rollback signal in sqlalchemy ``after_rollback``.
This marks the failure of session so the session may enter commit
phase. | def session_rollback(self, session):
"""Send session_rollback signal in sqlalchemy ``after_rollback``.
This marks the failure of session so the session may enter commit
phase.
"""
# this may happen when there's nothing to rollback
if not hasattr(session, 'meepo_unique_id... |
Returns polar mesh for matplotlib.pyplot.pcolormesh() in polar coordinates.
polar coordinates of data points -> polar mesh for colormesh
polar coordinates is assumed to be equidistanced in a sense that
the r_values and theta_values are assumed to be equally-spaced. | def augment_polar_mesh_for_colormesh(r_values, theta_values):
"""
Returns polar mesh for matplotlib.pyplot.pcolormesh() in polar coordinates.
polar coordinates of data points -> polar mesh for colormesh
polar coordinates is assumed to be equidistanced in a sense that
the r_values and theta_values a... |
Returns polar mesh for matplotlib.pyplot.pcolormesh() in Cartesian coordinates
polar coordinates of data points -> polar mesh for colormesh
polar coordinates is assumed to be equidistanced in a sense that
the r_values and theta_values are assumed to be equally-spaced. | def construct_polar_mesh_for_colormesh(r_values, theta_values):
"""
Returns polar mesh for matplotlib.pyplot.pcolormesh() in Cartesian coordinates
polar coordinates of data points -> polar mesh for colormesh
polar coordinates is assumed to be equidistanced in a sense that
the r_values and theta_val... |
Construct the corresponding 1D mesh from 1D array for pcolormesh() in ```matplotlib``` | def construct_mesh_for_1d_array(x_values):
"""Construct the corresponding 1D mesh from 1D array for pcolormesh() in ```matplotlib```"""
if not isinstance(x_values, np.ndarray):
try: x_values = np.array(x_values)
except: raise TypeError("Can not convert to numpy.ndarray: {0}".format(x_values))
... |
Set matplotlib.rcParams['font.size'] value so that
all texts on a plot would look nice in terms of fontsize.
[NOTE] The formula for the font size is:
fontsize = sqrt(fig_area) * 'scale'
where fig_area = fig_height * fig_width (in inch) | def set_global_fontsize_from_fig(fig, scale=1.5):
"""
Set matplotlib.rcParams['font.size'] value so that
all texts on a plot would look nice in terms of fontsize.
[NOTE] The formula for the font size is:
fontsize = sqrt(fig_area) * 'scale'
where fig_area = fig_height * fig_width (in inch)
... |
Process 'fig' and 'ax' arguments.
'fig' is of type: 'matplotlib.figure.Figure' (or its child object)
'ax' is of type: 'matplotlib.axes._base._AxesBase' (or its child object)
'fig' and 'ax' should be simultaneously None or of respective proper type. | def process_fig_and_ax_argument(fig, ax, default_figsize=None):
"""Process 'fig' and 'ax' arguments.
'fig' is of type: 'matplotlib.figure.Figure' (or its child object)
'ax' is of type: 'matplotlib.axes._base._AxesBase' (or its child object)
'fig' and 'ax' should be simultaneously None or of respective... |
Return N-dimensional square's limits
## Arguments
# 'coords': list of coordinates of poins to be plotted
# 'margin': margin to be added from boundaries of the square.
- 'margin' can be negative if one wants to reduce the square size.
## Example
if 'coords' was given as [x,y,z],
then the r... | def get_square_axes_limits(coords, margin=0.05):
"""Return N-dimensional square's limits
## Arguments
# 'coords': list of coordinates of poins to be plotted
# 'margin': margin to be added from boundaries of the square.
- 'margin' can be negative if one wants to reduce the square size.
## Examp... |
Sets the current track position in microseconds.
:param str track_id: The currently playing track's identifier.
:param int position: Track position in microseconds.
This must be between 0 and <track_length>.
If the Position argument is less than 0, do nothing.
... | def SetPosition(self, track_id, position):
"""Sets the current track position in microseconds.
:param str track_id: The currently playing track's identifier.
:param int position: Track position in microseconds.
This must be between 0 and <track_length>.
If ... |
Not standard hashing algorithm!
Install NumPy for better hashing service.
>>> from Redy.Tools._py_hash import hash_from_stream
>>> s = iter((1, 2, 3))
>>> assert hash_from_stream(3, map(hash, s)) == hash((1, 2, 3)) | def hash_from_stream(n, hash_stream):
"""
Not standard hashing algorithm!
Install NumPy for better hashing service.
>>> from Redy.Tools._py_hash import hash_from_stream
>>> s = iter((1, 2, 3))
>>> assert hash_from_stream(3, map(hash, s)) == hash((1, 2, 3))
"""
_to_int64 = to_int64
x... |
Add the genes for a variant
Get the hgnc symbols from all transcripts and add them
to the variant
Args:
variant (dict): A variant dictionary
Returns:
genes (list): A list of Genes | def _get_genes(self, variant):
"""Add the genes for a variant
Get the hgnc symbols from all transcripts and add them
to the variant
Args:
variant (dict): A variant dictionary
Returns:
genes (list): A list of Genes
"""
ensembl_ids = []
... |
Add the neccesary sv coordinates for a variant
Args:
variant (puzzle.models.variant) | def _add_sv_coordinates(self, variant):
"""Add the neccesary sv coordinates for a variant
Args:
variant (puzzle.models.variant)
"""
variant.stop_chrom = variant.CHROM
variant.start = int(variant.POS)
# If we have a translocation:
if '... |
Do any preprocessing of the lists. | def process_lists(self):
"""Do any preprocessing of the lists."""
for l1_idx, obj1 in enumerate(self.l1):
for l2_idx, obj2 in enumerate(self.l2):
if self.equal(obj1, obj2):
self.matches.add((l1_idx, l2_idx)) |
Get elements equal to the idx'th in src from the other list.
e.g. get_matches(self, 'l1', 0) will return all elements from self.l2
matching with self.l1[0] | def get_matches(self, src, src_idx):
"""Get elements equal to the idx'th in src from the other list.
e.g. get_matches(self, 'l1', 0) will return all elements from self.l2
matching with self.l1[0]
"""
if src not in ('l1', 'l2'):
raise ValueError('Must have one of "l1"... |
Loads the topology file (e.g. GRO,PDB,INPCRD) as a MDAnalysis Universe,
checks if it can be loaded. Needs to be run before the equivalent function
topol.load_trajectory() and provides the snapshot that is going to be used
for final residue placement - i.e. the residue coordinates for placement
... | def load_topology(self,topology):
"""
Loads the topology file (e.g. GRO,PDB,INPCRD) as a MDAnalysis Universe,
checks if it can be loaded. Needs to be run before the equivalent function
topol.load_trajectory() and provides the snapshot that is going to be used
for final residue pl... |
Loads the trajectory files e.g. XTC, DCD, TRJ together with the topology
file as a MDAnalysis Universe. This will only be run if a trajectory has
been submitted for analysis.
Takes:
* topology * - a topology file e.g. GRO, PDB, INPCRD, CARD, DMS
* trajectory *... | def load_trajectory(self,trajectory):
"""
Loads the trajectory files e.g. XTC, DCD, TRJ together with the topology
file as a MDAnalysis Universe. This will only be run if a trajectory has
been submitted for analysis.
Takes:
* topology * - a topology file e.g. ... |
Loads a MOL file of the ligand (submitted by user) into RDKit environment.
Takes:
* mol_file * - user submitted MOL file of the ligand
Output:
* self.mol_mda * - the ligand as MDAnalysis Universe,
* self.mol * - the ligand in RDKit environment as M... | def load_mol(self, mol_file):
"""Loads a MOL file of the ligand (submitted by user) into RDKit environment.
Takes:
* mol_file * - user submitted MOL file of the ligand
Output:
* self.mol_mda * - the ligand as MDAnalysis Universe,
* self.mol... |
Get an atom selection for the selected from both topology and trajectory. Rename the ligand LIG
to help with ligand names that are not standard, e.g. contain numbers.
Takes:
* ligand_name * - MDAnalysis atom selection for the ligand selected by user
Output:
... | def rename_ligand(self,ligand_name,mol_file):
"""
Get an atom selection for the selected from both topology and trajectory. Rename the ligand LIG
to help with ligand names that are not standard, e.g. contain numbers.
Takes:
* ligand_name * - MDAnalysis atom selection ... |
The residue numbers of the protein can be reformated in case of misallignment with the convention.
Takes:
* offset * - a number that represents by how many residues the numbering has to be shifted. | def renumber_system(self, offset):
"""
The residue numbers of the protein can be reformated in case of misallignment with the convention.
Takes:
* offset * - a number that represents by how many residues the numbering has to be shifted.
"""
self.universe.pro... |
This function defines the residues for plotting in case only a topology file has been submitted.
In this case the residence time analysis in not necessary and it is enough just to find all
residues within a cutoff distance.
Takes:
* cutoff * - cutoff distance in angstroms tha... | def define_residues_for_plotting_topology(self,cutoff):
"""
This function defines the residues for plotting in case only a topology file has been submitted.
In this case the residence time analysis in not necessary and it is enough just to find all
residues within a cutoff distance.
... |
This function defines the ligand atoms that are closest to the residues that will be plotted
in the final graph. | def find_the_closest_atoms(self,topology):
"""
This function defines the ligand atoms that are closest to the residues that will be plotted
in the final graph.
"""
# The measurements are made to ligand molecule without hydrogen atoms (ligand_noH) because the
# hydrogen a... |
This function loads all relevant data - except trajectories since those are dealt with one at a time.
Therefore, this process only needs to be done once, and every time a trajectory needs to be loaded, it
can be loaded seperataly and the Data object can be shared across LINTools processes. | def load_data(self, topology, mol_file, ligand_name, offset=0):
"""
This function loads all relevant data - except trajectories since those are dealt with one at a time.
Therefore, this process only needs to be done once, and every time a trajectory needs to be loaded, it
can be loaded s... |
In case user wants to analyse only a single topology file, this process will determine the residues
that should be plotted and find the ligand atoms closest to these residues. | def analyse_topology(self,topology, cutoff=3.5):
"""
In case user wants to analyse only a single topology file, this process will determine the residues
that should be plotted and find the ligand atoms closest to these residues.
"""
self.define_residues_for_plotting_topology(cut... |
Convert the start/end datetimes specified by the user, specifically:
- truncate any minutes/seconds
- for a missing end time, use start + 24 hours
- for a missing start time, use end - 24 hours
- for missing start and end, use the last 24 hours | def parse_time_range(start_dt, end_dt):
"""
Convert the start/end datetimes specified by the user, specifically:
- truncate any minutes/seconds
- for a missing end time, use start + 24 hours
- for a missing start time, use end - 24 hours
- for missing start and end, use the last 24 hours
"""... |
Calculate the 2D integral of the 1D surface brightness profile
(i.e, the flux) between rmin and rmax (elliptical radii).
Parameters:
-----------
rmin : minimum integration radius (deg)
rmax : maximum integration radius (deg)
Returns:
--------
integral ... | def integrate(self, rmin=0, rmax=np.inf):
"""
Calculate the 2D integral of the 1D surface brightness profile
(i.e, the flux) between rmin and rmax (elliptical radii).
Parameters:
-----------
rmin : minimum integration radius (deg)
rmax : maximum integration rad... |
Sample the radial distribution (deg) from the 2D stellar density.
Output is elliptical radius in true projected coordinates. | def sample_radius(self, n):
"""
Sample the radial distribution (deg) from the 2D stellar density.
Output is elliptical radius in true projected coordinates.
"""
edge = self.edge if self.edge<20*self.extension else 20*self.extension
radius = np.linspace(0, edge, 1.e5)
... |
Sample 2D distribution of points in lon, lat | def sample_lonlat(self, n):
"""
Sample 2D distribution of points in lon, lat
"""
# From http://en.wikipedia.org/wiki/Ellipse#General_parametric_form
# However, Martin et al. (2009) use PA theta "from North to East"
# Definition of phi (position angle) is offset by pi/4
... |
groupby which sorts the input, discards the key and returns the output
as a sequence of lists. | def group(iterable, key):
"""
groupby which sorts the input, discards the key and returns the output
as a sequence of lists.
"""
for _, grouped in groupby(sorted(iterable, key=key), key=key):
yield list(grouped) |
Straightforward sum of the given keyname. | def aggregate_count(keyname):
"""
Straightforward sum of the given keyname.
"""
def inner(docs):
return sum(doc[keyname] for doc in docs)
return keyname, inner |
Compute an aggregate rate for `rate_key` weighted according to
`count_rate`. | def aggregate_rate(rate_key, count_key):
"""
Compute an aggregate rate for `rate_key` weighted according to
`count_rate`.
"""
def inner(docs):
total = sum(doc[count_key] for doc in docs)
weighted_total = sum(doc[rate_key] * doc[count_key] for doc in docs)
total_rate = weighte... |
Given `docs` and `aggregations` return a single document with the
aggregations applied. | def make_aggregate(docs, aggregations):
"""
Given `docs` and `aggregations` return a single document with the
aggregations applied.
"""
new_doc = dict(docs[0])
for keyname, aggregation_function in aggregations:
new_doc[keyname] = aggregation_function(docs)
return new_doc |
Sanitize the JSON string using the Bleach HTML tag remover | def json(value):
'''
Sanitize the JSON string using the Bleach HTML tag remover
'''
uncleaned = jsonlib.dumps(value)
clean = bleach.clean(uncleaned)
return mark_safe(clean) |
Finds a subset of nondominated individuals in a given list
:param population: a list of individuals
:return: a set of indices corresponding to nondominated individuals | def find_pareto_front(population):
"""Finds a subset of nondominated individuals in a given list
:param population: a list of individuals
:return: a set of indices corresponding to nondominated individuals
"""
pareto_front = set(range(len(population)))
for i in range(len(population)):
... |
r"""[a-zA-Z_][a-zA-Z_0-9]* | def t_ID(self, t):
r"""[a-zA-Z_][a-zA-Z_0-9]*"""
# If the value is a reserved name, give it the appropriate type (not ID)
if t.value in self.reserved:
t.type = self.reserved[t.value]
# If it's a function, give it the FUNC type
elif t.value in self.functions:
... |
conditional : conditional AND condition
| conditional OR condition
condition : condition LTE expression
| condition GTE expression
| condition LT expression
| condition GT expression
| condition EQ expression
... | def p_binary_operators(self, p):
"""
conditional : conditional AND condition
| conditional OR condition
condition : condition LTE expression
| condition GTE expression
| condition LT expression
| condition GT expre... |
term : SUB factor
| ADD factor | def p_factor_unary_operators(self, p):
"""
term : SUB factor
| ADD factor
"""
p[0] = p[2]
if p[1] == '-':
p[0] = Instruction('-x', context={'x': p[0]}) |
factor : ID | def p_factor_id(self, p):
"""
factor : ID
"""
def resolve_id(key, context):
try:
return context[key]
except KeyError:
raise NameError("name '{}' is not defined".format(key))
p[0] = Instruction('resolve_id(key, context)', c... |
fn : FUNC LPAREN arguments RPAREN | def p_fn(self, p):
"""
fn : FUNC LPAREN arguments RPAREN
"""
fn = getattr(self, 'fn_{0}'.format(p[1]))
p[0] = Instruction('fn(*[x.execute() if isinstance(x, Instruction) else x for x in args])', context={
'fn': fn,
'args': p[3],
'Instruction':... |
factor : factor LBRACK conditional RBRACK | def p_factor_item(self, p):
"""
factor : factor LBRACK conditional RBRACK
"""
def resolve_item(obj, index):
if is_ndarray(obj) or isinstance(obj, (list, tuple)):
if not isinstance(index, int):
raise TypeError("Not a valid array index: '{}'... |
Casts Python lists and tuples to a numpy array or raises an AssertionError. | def _to_ndarray(self, a):
"""Casts Python lists and tuples to a numpy array or raises an AssertionError."""
if isinstance(a, (list, tuple)):
a = numpy.array(a)
if not is_ndarray(a):
raise TypeError("Expected an ndarray but got object of type '{}' instead".format(type(a)... |
Return the absolute value of a number.
:param value: The number.
:return: The absolute value of the number. | def fn_abs(self, value):
"""
Return the absolute value of a number.
:param value: The number.
:return: The absolute value of the number.
"""
if is_ndarray(value):
return numpy.absolute(value)
else:
return abs(value) |
Return an array mask.
:param value: The array.
:return: The array mask. | def fn_get_mask(self, value):
"""
Return an array mask.
:param value: The array.
:return: The array mask.
"""
value = self._to_ndarray(value)
if numpy.ma.is_masked(value):
return value.mask
else:
return numpy.zeros(value.shape).a... |
Return the minimum of an array, ignoring any NaNs.
:param a: The array.
:return: The minimum value of the array. | def fn_min(self, a, axis=None):
"""
Return the minimum of an array, ignoring any NaNs.
:param a: The array.
:return: The minimum value of the array.
"""
return numpy.nanmin(self._to_ndarray(a), axis=axis) |
Return the maximum of an array, ignoring any NaNs.
:param a: The array.
:return: The maximum value of the array | def fn_max(self, a, axis=None):
"""
Return the maximum of an array, ignoring any NaNs.
:param a: The array.
:return: The maximum value of the array
"""
return numpy.nanmax(self._to_ndarray(a), axis=axis) |
Compute the median of an array, ignoring NaNs.
:param a: The array.
:return: The median value of the array. | def fn_median(self, a, axis=None):
"""
Compute the median of an array, ignoring NaNs.
:param a: The array.
:return: The median value of the array.
"""
return numpy.nanmedian(self._to_ndarray(a), axis=axis) |
Compute the arithmetic mean of an array, ignoring NaNs.
:param a: The array.
:return: The arithmetic mean of the array. | def fn_mean(self, a, axis=None):
"""
Compute the arithmetic mean of an array, ignoring NaNs.
:param a: The array.
:return: The arithmetic mean of the array.
"""
return numpy.nanmean(self._to_ndarray(a), axis=axis) |
Compute the standard deviation of an array, ignoring NaNs.
:param a: The array.
:return: The standard deviation of the array. | def fn_std(self, a, axis=None):
"""
Compute the standard deviation of an array, ignoring NaNs.
:param a: The array.
:return: The standard deviation of the array.
"""
return numpy.nanstd(self._to_ndarray(a), axis=axis) |
Compute the variance of an array, ignoring NaNs.
:param a: The array.
:return: The variance of the array. | def fn_var(self, a, axis=None):
"""
Compute the variance of an array, ignoring NaNs.
:param a: The array.
:return: The variance of the array.
"""
return numpy.nanvar(self._to_ndarray(a), axis=axis) |
Return the floor of a number. For negative numbers, floor returns a lower value. E.g., `floor(-2.5) == -3`
:param value: The number.
:return: The floor of the number. | def fn_floor(self, value):
"""
Return the floor of a number. For negative numbers, floor returns a lower value. E.g., `floor(-2.5) == -3`
:param value: The number.
:return: The floor of the number.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... |
Return the ceiling of a number.
:param value: The number.
:return: The ceiling of the number. | def fn_ceil(self, value):
"""
Return the ceiling of a number.
:param value: The number.
:return: The ceiling of the number.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
return numpy.ceil(self._to_ndarray(value))
else:
ret... |
Return the value cast to an int.
:param value: The number.
:return: The number as an int. | def fn_int(self, value):
"""
Return the value cast to an int.
:param value: The number.
:return: The number as an int.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
return self._to_ndarray(value).astype('int')
else:
return... |
Return the value cast to an 8-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8 | def fn_int8(self, value):
"""
Return the value cast to an 8-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... |
Return the value cast to an 16-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8 | def fn_int16(self, value):
"""
Return the value cast to an 16-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... |
Return the value cast to an 32-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8 | def fn_int32(self, value):
"""
Return the value cast to an 32-bit signed integer (numpy array) or a Python int (single value)
:param value: The number or array
:return: The number or array as int/int8
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
... |
Return the value cast to a float.
:param value: The number.
:return: The number as a float. | def fn_float(self, value):
"""
Return the value cast to a float.
:param value: The number.
:return: The number as a float.
"""
if is_ndarray(value) or isinstance(value, (list, tuple)):
return self._to_ndarray(value).astype('float')
else:
... |
Coerce a datetime or string into datetime.datetime object
Arguments:
dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date
to be coerced into a `datetime.date` object
Returns:
datetime.time: Time of day portion of a `datetime` string or object
>>> make_date(''... | def make_datetime(dt, date_parser=parse_date):
"""Coerce a datetime or string into datetime.datetime object
Arguments:
dt (str or datetime.datetime or atetime.time or numpy.Timestamp): time or date
to be coerced into a `datetime.date` object
Returns:
datetime.time: Time of day portion ... |
Quantize a datetime to integer years, months, days, hours, minutes, seconds or microseconds
Also works with a `datetime.timetuple` or `time.struct_time` or a 1to9-tuple of ints or floats.
Also works with a sequenece of struct_times, tuples, or datetimes
>>> quantize_datetime(datetime.datetime(1970,1,2,3,4... | def quantize_datetime(dt, resolution=None):
"""Quantize a datetime to integer years, months, days, hours, minutes, seconds or microseconds
Also works with a `datetime.timetuple` or `time.struct_time` or a 1to9-tuple of ints or floats.
Also works with a sequenece of struct_times, tuples, or datetimes
>... |
Like datetime.ordinal, but rather than integer allows fractional days (so float not ordinal at all)
Similar to the Microsoft Excel numerical representation of a datetime object
>>> ordinal_float(datetime.datetime(1970, 1, 1))
719163.0
>>> ordinal_float(datetime.datetime(1, 2, 3, 4, 5, 6, 7)) # doctes... | def ordinal_float(dt):
"""Like datetime.ordinal, but rather than integer allows fractional days (so float not ordinal at all)
Similar to the Microsoft Excel numerical representation of a datetime object
>>> ordinal_float(datetime.datetime(1970, 1, 1))
719163.0
>>> ordinal_float(datetime.datetime(1... |
Inverse of `ordinal_float()`, converts a float number of days back to a `datetime` object
>>> dt = datetime.datetime(1970, 1, 1)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
True
>>> dt = datetime.datetime(1, 2, 3, 4, 5, 6, 7)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
... | def datetime_from_ordinal_float(days):
"""Inverse of `ordinal_float()`, converts a float number of days back to a `datetime` object
>>> dt = datetime.datetime(1970, 1, 1)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
True
>>> dt = datetime.datetime(1, 2, 3, 4, 5, 6, 7)
>>> datetime_f... |
Generate a date-time tag suitable for appending to a file name.
>>> timetag_str(resolution=3) == '-'.join('{0:02d}'.format(i) for i in
... tuple(datetime.datetime.now().timetuple()[:3]))
True
>>> timetag_str(datetime.datetime(2004,12,8,1,2,3,400000))
'2004-12-08-01-02-03'
>>> timeta... | def timetag_str(dt=None, sep='-', filler='0', resolution=6):
"""Generate a date-time tag suitable for appending to a file name.
>>> timetag_str(resolution=3) == '-'.join('{0:02d}'.format(i) for i in
... tuple(datetime.datetime.now().timetuple()[:3]))
True
>>> timetag_str(datetime.dateti... |
Add timezone information to a datetime object, only if it is naive.
>>> make_tz_aware(datetime.datetime(2001, 9, 8, 7, 6))
datetime.datetime(2001, 9, 8, 7, 6, tzinfo=<UTC>)
>>> make_tz_aware(['2010-01-01'], 'PST')
[datetime.datetime(2010, 1, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 S... | def make_tz_aware(dt, tz='UTC', is_dst=None):
"""Add timezone information to a datetime object, only if it is naive.
>>> make_tz_aware(datetime.datetime(2001, 9, 8, 7, 6))
datetime.datetime(2001, 9, 8, 7, 6, tzinfo=<UTC>)
>>> make_tz_aware(['2010-01-01'], 'PST')
[datetime.datetime(2010, 1, 1, 0, 0,... |
Limit a datetime to a valid range for datetime, datetime64, and Timestamp objects
>>> from datetime import timedelta
>>> clip_datetime(MAX_DATETIME + timedelta(100)) == pd.Timestamp(MAX_DATETIME, tz='utc') == MAX_TIMESTAMP
True
>>> MAX_TIMESTAMP
Timestamp('2262-04-11 23:47:16.854775+0000', tz='UTC') | def clip_datetime(dt, tz=DEFAULT_TZ, is_dst=None):
"""Limit a datetime to a valid range for datetime, datetime64, and Timestamp objects
>>> from datetime import timedelta
>>> clip_datetime(MAX_DATETIME + timedelta(100)) == pd.Timestamp(MAX_DATETIME, tz='utc') == MAX_TIMESTAMP
True
>>> MAX_TIMESTAMP
... |
decorator to translate the addressType field.
translate the value of the addressType field of the API response into a
translated type. | def translate_addresstype(f):
"""decorator to translate the addressType field.
translate the value of the addressType field of the API response into a
translated type.
"""
@wraps(f)
def wr(r, pc):
at = r["addressType"]
try:
r.update({"addressType": POSTCODE_API_TYPED... |
decorator to translate the purposes field.
translate the values of the purposes field of the API response into
translated values. | def translate_purposes(f):
"""decorator to translate the purposes field.
translate the values of the purposes field of the API response into
translated values.
"""
@wraps(f)
def wr(r, pc):
tmp = []
for P in r["purposes"]:
try:
tmp.append(POSTCODE_API_... |
Calculate Jenks natural breaks.
Adapted from http://danieljlewis.org/files/2010/06/Jenks.pdf
Credit: Daniel Lewis
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform. | def jenks(data, num_breaks):
"""
Calculate Jenks natural breaks.
Adapted from http://danieljlewis.org/files/2010/06/Jenks.pdf
Credit: Daniel Lewis
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform.
"""
data = numpy.ma.compressed(data)
if... |
Calculate quantile breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform. | def quantile(data, num_breaks):
"""
Calculate quantile breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform.
"""
def scipy_mquantiles(a, prob=list([.25,.5,.75]), alphap=.4, betap=.4, axis=None, limit=()):
""" function copied from scipy 0... |
Calculate equal interval breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform. | def equal(data, num_breaks):
"""
Calculate equal interval breaks.
Arguments:
data -- Array of values to classify.
num_breaks -- Number of breaks to perform.
"""
step = (numpy.amax(data) - numpy.amin(data)) / num_breaks
return numpy.linspace(numpy.amin(data) + step, numpy.amax(data), nu... |
Inputs:
catalog_dir = string corresponding to directory containing the stellar catalog infiles
mc_source_id = integer corresponding the target MC_SOURCE_ID value
Outputs:
catalog_infile = string corresponding to filename of stellar catalog containing mc_source_id | def getCatalogFile(catalog_dir, mc_source_id):
"""
Inputs:
catalog_dir = string corresponding to directory containing the stellar catalog infiles
mc_source_id = integer corresponding the target MC_SOURCE_ID value
Outputs:
catalog_infile = string corresponding to filename of stellar c... |
Read a generic input file into a recarray.
Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat]
Parameters:
filename : input file name
kwargs : keyword arguments for the reader
Returns:
recarray : data array | def read(filename,**kwargs):
""" Read a generic input file into a recarray.
Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat]
Parameters:
filename : input file name
kwargs : keyword arguments for the reader
Returns:
recarray : data array
"""
base,ext = os.path.splitext(fi... |
Write a recarray to a specific format.
Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat]
Parameters:
filename : output file name
data : the recarray data
kwargs : keyword arguments for the writer
Returns:
ret : writer return (usually None) | def write(filename,data,**kwargs):
""" Write a recarray to a specific format.
Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat]
Parameters:
filename : output file name
data : the recarray data
kwargs : keyword arguments for the writer
Returns:
ret : writer return (us... |
Add a column to a FITS file.
ADW: Could this be replaced by a ftool? | def add_column(filename,column,formula,force=False):
""" Add a column to a FITS file.
ADW: Could this be replaced by a ftool?
"""
columns = parse_formula(formula)
logger.info("Running file: %s"%filename)
logger.debug(" Reading columns: %s"%columns)
data = fitsio.read(filename,columns=colum... |
Load a set of FITS files with kwargs. | def load_files(filenames,multiproc=False,**kwargs):
""" Load a set of FITS files with kwargs. """
filenames = np.atleast_1d(filenames)
logger.debug("Loading %s files..."%len(filenames))
kwargs = [dict(filename=f,**kwargs) for f in filenames]
if multiproc:
from multiprocessing import Pool
... |
Write a catalog file of the likelihood region including
membership properties.
Parameters:
-----------
loglike : input loglikelihood object
filename : output filename
Returns:
--------
None | def write_membership(loglike,filename):
"""
Write a catalog file of the likelihood region including
membership properties.
Parameters:
-----------
loglike : input loglikelihood object
filename : output filename
Returns:
--------
None
"""
ra,dec = gal2cel(loglike.ca... |
Take the value from a two-dimensional histogram from the bin corresponding to (x, y).
Parameters:
-----------
histogram : The values in the histogram (n,m) (ADW: is this ordering right?)
x : the x-value to take from the hist
y : the y-value to take from the hist
bins_x : the xbin edges, includi... | def take2D(histogram, x, y, bins_x, bins_y):
"""
Take the value from a two-dimensional histogram from the bin corresponding to (x, y).
Parameters:
-----------
histogram : The values in the histogram (n,m) (ADW: is this ordering right?)
x : the x-value to take from the hist
y : the y-value t... |
Use cloud-in-cells binning algorithm. Only valid for equal-spaced linear bins.
http://ta.twi.tudelft.nl/dv/users/Lemmens/MThesis.TTH/chapter4.html#tth_sEc2
http://www.gnu.org/software/archimedes/manual/html/node29.html
INPUTS:
x: array of x-values
y: array or y-values
bins: [bins_x,... | def cloudInCells(x, y, bins, weights=None):
"""
Use cloud-in-cells binning algorithm. Only valid for equal-spaced linear bins.
http://ta.twi.tudelft.nl/dv/users/Lemmens/MThesis.TTH/chapter4.html#tth_sEc2
http://www.gnu.org/software/archimedes/manual/html/node29.html
INPUTS:
x: array of x-va... |
Performs a gaussian kernel density estimate over a regular grid using a
convolution of the gaussian kernel with a 2D histogram of the data.
This function is typically several orders of magnitude faster than
scipy.stats.kde.gaussian_kde for large (>1e7) numbers of points and
produces an essentially id... | def fast_kde(x, y, gridsize=(200,200), extents=None, nocorrelation=False, weights=None):
"""
Performs a gaussian kernel density estimate over a regular grid using a
convolution of the gaussian kernel with a 2D histogram of the data.
This function is typically several orders of magnitude faster than
... |
Bins data using np.histogram and calculates the
reverse indices for the entries like IDL.
Parameters:
data : data to pass to np.histogram
bins : bins to pass to np.histogram
Returns:
hist : bin content output by np.histogram
edges : edges output from np.histogram
rev : reverse i... | def reverseHistogram(data,bins=None):
"""
Bins data using np.histogram and calculates the
reverse indices for the entries like IDL.
Parameters:
data : data to pass to np.histogram
bins : bins to pass to np.histogram
Returns:
hist : bin content output by np.histogram
... |
Input (lon, lat) in degrees instead of (theta, phi) in radians | def angToPix(nside, lon, lat, nest=False):
"""
Input (lon, lat) in degrees instead of (theta, phi) in radians
"""
theta = np.radians(90. - lat)
phi = np.radians(lon)
return hp.ang2pix(nside, theta, phi, nest=nest) |
Wrapper around healpy.query_disc to deal with old healpy implementation.
nside : int
The nside of the Healpix map.
vec : float, sequence of 3 elements
The coordinates of unit vector defining the disk center.
radius : float
The radius (in degrees) of the disc
inclusive : bool, optional
... | def query_disc(nside, vec, radius, inclusive=False, fact=4, nest=False):
"""
Wrapper around healpy.query_disc to deal with old healpy implementation.
nside : int
The nside of the Healpix map.
vec : float, sequence of 3 elements
The coordinates of unit vector defining the disk center.
rad... |
Wrap `query_disc` to use lon, lat, and radius in degrees. | def angToDisc(nside, lon, lat, radius, inclusive=False, fact=4, nest=False):
"""
Wrap `query_disc` to use lon, lat, and radius in degrees.
"""
vec = angToVec(lon,lat)
return query_disc(nside,vec,radius,inclusive,fact,nest) |
Angular separation (deg) between two sky coordinates.
Borrowed from astropy (www.astropy.org)
Notes
-----
The angular separation is calculated using the Vincenty formula [1],
which is slighly more complex and computationally expensive than
some alternatives, but is stable at at all distances, in... | def angsep(lon1, lat1, lon2, lat2):
"""
Angular separation (deg) between two sky coordinates.
Borrowed from astropy (www.astropy.org)
Notes
-----
The angular separation is calculated using the Vincenty formula [1],
which is slighly more complex and computationally expensive than
some alt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.