INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Converts Celestial J2000 (deg) to Calactic (deg) coordinates | def celToGal(ra, dec):
"""
Converts Celestial J2000 (deg) to Calactic (deg) coordinates
"""
dec = np.radians(dec)
sin_dec = np.sin(dec)
cos_dec = np.cos(dec)
ra = np.radians(ra)
ra_gp = np.radians(192.85948)
de_gp = np.radians(27.12825)
sin_ra_gp = np.sin(ra - ra_gp)
co... |
https://github.com/astropy/astropy/issues/3093 | def estimate_angle(angle, origin, new_frame, offset=1e-7):
"""
https://github.com/astropy/astropy/issues/3093
"""
from astropy.coordinates import SkyCoord
import astropy.units as u
angle_deg = angle*np.pi/180
newlat = offset * np.cos(angle_deg) + origin.data.lat.degree
newlon = (offset *... |
ADW: This should really be replaced by astropy | def dec2hms(dec):
"""
ADW: This should really be replaced by astropy
"""
DEGREE = 360.
HOUR = 24.
MINUTE = 60.
SECOND = 3600.
dec = float(dec)
fhour = dec*(HOUR/DEGREE)
hour = int(fhour)
fminute = (fhour - hour)*MINUTE
minute = int(fminute)
second = (fminut... |
ADW: This should really be replaced by astropy | def dec2dms(dec):
"""
ADW: This should really be replaced by astropy
"""
DEGREE = 360.
HOUR = 24.
MINUTE = 60.
SECOND = 3600.
dec = float(dec)
sign = np.copysign(1.0,dec)
fdeg = np.abs(dec)
deg = int(fdeg)
fminute = (fdeg - deg)*MINUTE
minute = int(fminute)
... |
Convert longitude from hours,minutes,seconds in string or 3-array
format to decimal degrees.
ADW: This really should be replaced by astropy | def hms2dec(hms):
"""
Convert longitude from hours,minutes,seconds in string or 3-array
format to decimal degrees.
ADW: This really should be replaced by astropy
"""
DEGREE = 360.
HOUR = 24.
MINUTE = 60.
SECOND = 3600.
if isstring(hms):
hour,minute,second = np.array(re.... |
Convert latitude from degrees,minutes,seconds in string or 3-array
format to decimal degrees. | def dms2dec(dms):
"""
Convert latitude from degrees,minutes,seconds in string or 3-array
format to decimal degrees.
"""
DEGREE = 360.
HOUR = 24.
MINUTE = 60.
SECOND = 3600.
# Be careful here, degree needs to be a float so that negative zero
# can have its signbit set:
# http:... |
Adapted from Eric Tollerud.
Finds matches in one catalog to another.
Parameters
lon1 : array-like
Longitude of the first catalog (degrees)
lat1 : array-like
Latitude of the first catalog (shape of array must match `lon1`)
lon2 : array-like
Longitude of the second catalog
... | def match(lon1, lat1, lon2, lat2, tol=None, nnearest=1):
"""
Adapted from Eric Tollerud.
Finds matches in one catalog to another.
Parameters
lon1 : array-like
Longitude of the first catalog (degrees)
lat1 : array-like
Latitude of the first catalog (shape of array must match `lo... |
May be overidden to provide custom functionality.
Constructs an argparse.ArgumentParser used to parse configuration options from the command line.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object contai... | def getArgumentParser(self, configManager, config):
"""
May be overidden to provide custom functionality.
Constructs an argparse.ArgumentParser used to parse configuration options from the command line.
Inputs: configManager - Our parent ConfigManager instance which is constructing the ... |
Parses commandline arguments, given a series of configuration options.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration options populated thus far.
Outputs: A dictionary of new... | def parse(self, configManager, config):
"""
Parses commandline arguments, given a series of configuration options.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration optio... |
Given a `text` string, get candidates and context for feature
extraction and classification | def candidates(text):
"""
Given a `text` string, get candidates and context for feature
extraction and classification
"""
for Pmatch in finditer(TARGET, text):
# the punctuation mark itself
P = Pmatch.group(1)
# is it a boundary?
B ... |
Given left context `L`, punctuation mark `P`, and right context
R`, extract features. Probability distributions for any
quantile-based features will not be modified. | def extract_one(self, L, P, R):
"""
Given left context `L`, punctuation mark `P`, and right context
R`, extract features. Probability distributions for any
quantile-based features will not be modified.
"""
yield "*bias*"
# L feature(s)
if match(QUOTE, L):
... |
Given a string `text`, use it to train the segmentation classifier for `epochs` iterations. | def fit(self, text, epochs=EPOCHS):
""" Given a string `text`, use it to train the segmentation classifier for `epochs` iterations.
"""
logger.debug("Extracting features and classifications.")
Phi = []
Y = []
for (L, P, R, gold, _) in Detector.candidates(text):
... |
Given an left context `L`, punctuation mark `P`, and right context
`R`, return True iff this observation is hypothesized to be a
sentence boundary. | def predict(self, L, P, R):
"""
Given an left context `L`, punctuation mark `P`, and right context
`R`, return True iff this observation is hypothesized to be a
sentence boundary.
"""
phi = self.extract_one(L, P, R)
return self.classifier.predict(phi) |
Given a string of `text`, return a generator yielding each
hypothesized sentence string | def segments(self, text):
"""
Given a string of `text`, return a generator yielding each
hypothesized sentence string
"""
start = 0
for (L, P, R, B, end) in Detector.candidates(text):
# if there's already a newline there, we have nothing to do
if B... |
Given a string of `text`, compute confusion matrix for the
classification task. | def evaluate(self, text):
"""
Given a string of `text`, compute confusion matrix for the
classification task.
"""
cx = BinaryConfusion()
for (L, P, R, gold, _) in Detector.candidates(text):
guess = self.predict(L, P, R)
cx.update(gold, guess)
... |
DEPRECATED: 2018-05-04
Mangle must be set up on your system.
The index argument is a temporary file naming convention to avoid file conflicts.
Coordinates must be given in the native coordinate system of the Mangle file. | def readMangleFile(infile, lon, lat, index = None):
"""
DEPRECATED: 2018-05-04
Mangle must be set up on your system.
The index argument is a temporary file naming convention to avoid file conflicts.
Coordinates must be given in the native coordinate system of the Mangle file.
"""
msg = "'mas... |
Scale the completeness depth of a mask such that mag_new = mag + mag_scale.
Input is a full HEALPix map.
Optionally write out the scaled mask as an sparse HEALPix map. | def scale(mask, mag_scale, outfile=None):
"""
Scale the completeness depth of a mask such that mag_new = mag + mag_scale.
Input is a full HEALPix map.
Optionally write out the scaled mask as an sparse HEALPix map.
"""
msg = "'mask.scale': ADW 2018-05-05"
DeprecationWarning(msg)
mask_new ... |
Assemble a set of unique magnitude tuples for the ROI | def mask_roi_unique(self):
"""
Assemble a set of unique magnitude tuples for the ROI
"""
# There is no good inherent way in numpy to do this...
# http://stackoverflow.com/q/16970982/
# Also possible and simple:
#return np.unique(zip(self.mask_1.mask_roi_sparse,se... |
Get the index of the unique magnitude tuple for each pixel in the ROI. | def mask_roi_digi(self):
"""
Get the index of the unique magnitude tuple for each pixel in the ROI.
"""
# http://stackoverflow.com/q/24205045/#24206440
A = np.vstack([self.mask_1.mask_roi_sparse,self.mask_2.mask_roi_sparse]).T
B = self.mask_roi_unique
AA = np.asc... |
Calculate an approximate pixel coverage fraction from the two masks.
We have no way to know a priori how much the coverage of the
two masks overlap in a give pixel. For example, masks that each
have frac = 0.5 could have a combined frac = [0.0 to 0.5].
The limits will be:
ma... | def _fracRoiSparse(self):
"""
Calculate an approximate pixel coverage fraction from the two masks.
We have no way to know a priori how much the coverage of the
two masks overlap in a give pixel. For example, masks that each
have frac = 0.5 could have a combined frac = [0.0 to 0.... |
Compute solid angle within the mask annulus (deg^2) as a
function of mag_1 and mag_2 | def _solidAngleMMD(self):
"""
Compute solid angle within the mask annulus (deg^2) as a
function of mag_1 and mag_2
"""
# Take upper corner of the magnitude bin
mag_2,mag_1 = np.meshgrid(self.roi.bins_mag[1:],self.roi.bins_mag[1:])
# Havent tested since adding fra... |
Remove regions of magnitude-magnitude space where the unmasked solid angle is
statistically insufficient to estimate the background.
INPUTS:
solid_angle[1]: minimum solid angle (deg^2) | def _pruneMMD(self, minimum_solid_angle):
"""
Remove regions of magnitude-magnitude space where the unmasked solid angle is
statistically insufficient to estimate the background.
INPUTS:
solid_angle[1]: minimum solid angle (deg^2)
"""
logger.info('Pruning ma... |
Compute solid angle within the mask annulus (deg^2) as a
function of color and magnitude. | def _solidAngleCMD(self):
"""
Compute solid angle within the mask annulus (deg^2) as a
function of color and magnitude.
"""
self.solid_angle_cmd = np.zeros([len(self.roi.centers_mag),
len(self.roi.centers_color)])
for index_ma... |
Remove regions of color-magnitude space where the unmasked solid angle is
statistically insufficient to estimate the background.
ADW: Why are we clipping at the bin center instead of edge?
INPUTS:
solid_angle[1]: minimum solid angle (deg^2) | def _pruneCMD(self, minimum_solid_angle):
"""
Remove regions of color-magnitude space where the unmasked solid angle is
statistically insufficient to estimate the background.
ADW: Why are we clipping at the bin center instead of edge?
INPUTS:
solid_angle[1]: minimum... |
Return the completeness as a function of magnitude.
ADW: Eventually want a completeness mask to set overall efficiency. | def completeness(self, delta, method='step'):
"""
Return the completeness as a function of magnitude.
ADW: Eventually want a completeness mask to set overall efficiency.
"""
delta = np.asarray(delta)
if method == 'step':
func = lambda delta: (delta > 0).astyp... |
Realistic photometric errors estimated from catalog objects and mask.
Extend below the magnitude threshold with a flat extrapolation. | def _photometricErrors(self, catalog=None, n_per_bin=100):
"""
Realistic photometric errors estimated from catalog objects and mask.
Extend below the magnitude threshold with a flat extrapolation.
"""
if catalog is None:
# Simple proxy for photometric errors
... |
Solid angle within the mask as a function of color and magnitude. | def plotSolidAngleCMD(self):
"""
Solid angle within the mask as a function of color and magnitude.
"""
msg = "'%s.plotSolidAngleCMD': ADW 2018-05-05"%self.__class__.__name__
DeprecationWarning(msg)
import ugali.utils.plotting
ugali.utils.plotting.twoDimen... |
Solid angle within the mask as a function of color and magnitude. | def plotSolidAngleMMD(self):
"""
Solid angle within the mask as a function of color and magnitude.
"""
msg = "'%s.plotSolidAngleMMD': ADW 2018-05-05"%self.__class__.__name__
DeprecationWarning(msg)
import ugali.utils.plotting
ugali.utils.plotting.twoDime... |
Generate an empirical background model in magnitude-magnitude space.
INPUTS:
catalog: Catalog object
OUTPUTS:
background | def backgroundMMD(self, catalog, method='cloud-in-cells', weights=None):
"""
Generate an empirical background model in magnitude-magnitude space.
INPUTS:
catalog: Catalog object
OUTPUTS:
background
"""
# Select objects in annulus
... |
Generate an empirical background model in color-magnitude space.
INPUTS:
catalog: Catalog object
OUTPUTS:
background | def backgroundCMD(self, catalog, mode='cloud-in-cells', weights=None):
"""
Generate an empirical background model in color-magnitude space.
INPUTS:
catalog: Catalog object
OUTPUTS:
background
"""
# Select objects in annulus
cut_an... |
Retain only the catalog objects which fall within the observable (i.e., unmasked) space.
Parameters:
catalog: a Catalog object
Returns:
sel : boolean selection array where True means the object would be observable (i.e., unmasked).
ADW: Careful, this function is fragile! The... | def restrictCatalogToObservableSpaceMMD(self, catalog):
"""
Retain only the catalog objects which fall within the observable (i.e., unmasked) space.
Parameters:
catalog: a Catalog object
Returns:
sel : boolean selection array where True means the object would be obser... |
Retain only the catalog objects which fall within the
observable (i.e., unmasked) space. NOTE: This returns a
*selection* (i.e., objects are retained if the value of the
output array is True).
Parameters:
catalog: a Catalog object
Returns:
sel : boolean selec... | def restrictCatalogToObservableSpaceCMD(self, catalog):
"""
Retain only the catalog objects which fall within the
observable (i.e., unmasked) space. NOTE: This returns a
*selection* (i.e., objects are retained if the value of the
output array is True).
Parameters:
... |
Return the completeness as a function of magnitude.
ADW: Eventually want a completeness mask to set overall efficiency. | def completeness(self, mags, method='step'):
"""
Return the completeness as a function of magnitude.
ADW: Eventually want a completeness mask to set overall efficiency.
"""
if method == 'step':
func = lambda x: (x < self.mask_roi_unique[:,np.newaxis]).astype(float)
... |
Plot the magnitude depth. | def plot(self):
"""
Plot the magnitude depth.
"""
msg = "'%s.plot': ADW 2018-05-05"%self.__class__.__name__
DeprecationWarning(msg)
import ugali.utils.plotting
mask = hp.UNSEEN * np.ones(hp.nside2npix(self.nside))
mask[self.roi.pixels] = self.mask_roi_sp... |
Build the Expected parameters from a dict | def build_expected(dynamizer, expected):
""" Build the Expected parameters from a dict """
ret = {}
for k, v in six.iteritems(expected):
if is_null(v):
ret[k] = {
'Exists': False,
}
else:
ret[k] = {
'Exists': True,
... |
Build ExpresionAttributeValues from a value or kwargs | def build_expression_values(dynamizer, expr_values, kwargs):
""" Build ExpresionAttributeValues from a value or kwargs """
if expr_values:
values = expr_values
return dynamizer.encode_keys(values)
elif kwargs:
values = dict(((':' + k, v) for k, v in six.iteritems(kwargs)))
re... |
Connect to an AWS region.
This method has been deprecated in favor of :meth:`~.connect`
Parameters
----------
region : str
Name of an AWS region
session : :class:`~botocore.session.Session`, optional
The Session object to use for the connection
a... | def connect_to_region(cls, region, session=None, access_key=None,
secret_key=None, **kwargs):
"""
Connect to an AWS region.
This method has been deprecated in favor of :meth:`~.connect`
Parameters
----------
region : str
Name of an ... |
Connect to a specific host.
This method has been deprecated in favor of :meth:`~.connect`
Parameters
----------
host : str, optional
Address of the host (default 'localhost')
port : int, optional
Connect to the host on this port (default 8000)
is... | def connect_to_host(cls, host='localhost', port=8000, is_secure=False,
session=None, access_key=None, secret_key=None,
**kwargs):
"""
Connect to a specific host.
This method has been deprecated in favor of :meth:`~.connect`
Parameters
... |
Connect to an AWS region.
Parameters
----------
region : str
Name of an AWS region
session : :class:`~botocore.session.Session`, optional
The Session object to use for the connection
access_key : str, optional
If session is None, set this acce... | def connect(cls, region, session=None, access_key=None, secret_key=None,
host=None, port=80, is_secure=True, **kwargs):
"""
Connect to an AWS region.
Parameters
----------
region : str
Name of an AWS region
session : :class:`~botocore.session.... |
Make a request to DynamoDB using the raw botocore API
Parameters
----------
command : str
The name of the Dynamo command to execute
**kwargs : dict
The parameters to pass up in the request
Raises
------
exc : :class:`~.DynamoDBError`
... | def call(self, command, **kwargs):
"""
Make a request to DynamoDB using the raw botocore API
Parameters
----------
command : str
The name of the Dynamo command to execute
**kwargs : dict
The parameters to pass up in the request
Raises
... |
Subscribe a callback to an event
Parameters
----------
event : str
Available events are 'precall', 'postcall', and 'capacity'.
precall is called with: (connection, command, query_kwargs)
postcall is called with: (connection, command, query_kwargs, response)
... | def subscribe(self, event, hook):
"""
Subscribe a callback to an event
Parameters
----------
event : str
Available events are 'precall', 'postcall', and 'capacity'.
precall is called with: (connection, command, query_kwargs)
postcall is called... |
Unsubscribe a hook from an event | def unsubscribe(self, event, hook):
""" Unsubscribe a hook from an event """
if hook in self._hooks[event]:
self._hooks[event].remove(hook) |
Add a RateLimit to the connection | def add_rate_limit(self, limiter):
""" Add a RateLimit to the connection """
if limiter not in self.rate_limiters:
self.subscribe('capacity', limiter.on_capacity)
self.rate_limiters.append(limiter) |
Remove a RateLimit from the connection | def remove_rate_limit(self, limiter):
""" Remove a RateLimit from the connection """
if limiter in self.rate_limiters:
self.unsubscribe('capacity', limiter.on_capacity)
self.rate_limiters.remove(limiter) |
Get the value for ReturnConsumedCapacity from provided value | def _default_capacity(self, value):
""" Get the value for ReturnConsumedCapacity from provided value """
if value is not None:
return value
if self.default_return_capacity or self.rate_limiters:
return INDEXES
return NONE |
Do a scan or query and aggregate the results into a Count | def _count(self, method, limit, keywords):
""" Do a scan or query and aggregate the results into a Count """
# The limit will be mutated, so copy it and leave the original intact
limit = limit.copy()
has_more = True
count = None
while has_more:
limit.set_reque... |
Get the details about a table
Parameters
----------
tablename : str
Name of the table
Returns
-------
table : :class:`~dynamo3.fields.Table` | def describe_table(self, tablename):
"""
Get the details about a table
Parameters
----------
tablename : str
Name of the table
Returns
-------
table : :class:`~dynamo3.fields.Table`
"""
try:
response = self.call(
... |
Create a table
Parameters
----------
tablename : str
Name of the table
hash_key : :class:`~dynamo3.fields.DynamoKey`
The key to use as the Hash key
range_key : :class:`~dynamo3.fields.DynamoKey`, optional
The key to use as the Range key
... | def create_table(self, tablename, hash_key, range_key=None, indexes=None,
global_indexes=None, throughput=None, wait=False):
"""
Create a table
Parameters
----------
tablename : str
Name of the table
hash_key : :class:`~dynamo3.fields.Dyn... |
Delete a table
Parameters
----------
tablename : str
Name of the table to delete
Returns
-------
response : bool
True if the table was deleted, False if no table exists | def delete_table(self, tablename, wait=False):
"""
Delete a table
Parameters
----------
tablename : str
Name of the table to delete
Returns
-------
response : bool
True if the table was deleted, False if no table exists
"... |
Store an item, overwriting existing data
This uses the older version of the DynamoDB API.
See also: :meth:`~.put_item2`.
Parameters
----------
tablename : str
Name of the table to write
item : dict
Item data
expected : dict, optional
... | def put_item(self, tablename, item, expected=None, returns=NONE,
return_capacity=None, expect_or=False, **kwargs):
"""
Store an item, overwriting existing data
This uses the older version of the DynamoDB API.
See also: :meth:`~.put_item2`.
Parameters
--... |
Fetch a single item from a table
This uses the older version of the DynamoDB API.
See also: :meth:`~.get_item2`.
Parameters
----------
tablename : str
Name of the table to fetch from
key : dict
Primary key dict specifying the hash key and, if app... | def get_item(self, tablename, key, attributes=None, consistent=False,
return_capacity=None):
"""
Fetch a single item from a table
This uses the older version of the DynamoDB API.
See also: :meth:`~.get_item2`.
Parameters
----------
tablename : s... |
Fetch a single item from a table
Parameters
----------
tablename : str
Name of the table to fetch from
key : dict
Primary key dict specifying the hash key and, if applicable, the
range key of the item.
attributes : str or list, optional
... | def get_item2(self, tablename, key, attributes=None, alias=None,
consistent=False, return_capacity=None):
"""
Fetch a single item from a table
Parameters
----------
tablename : str
Name of the table to fetch from
key : dict
Prima... |
Delete an item
This uses the older version of the DynamoDB API.
See also: :meth:`~.delete_item2`.
Parameters
----------
tablename : str
Name of the table to delete from
key : dict
Primary key dict specifying the hash key and, if applicable, the
... | def delete_item(self, tablename, key, expected=None, returns=NONE,
return_capacity=None, expect_or=False, **kwargs):
"""
Delete an item
This uses the older version of the DynamoDB API.
See also: :meth:`~.delete_item2`.
Parameters
----------
t... |
Delete an item from a table
For many parameters you will want to reference the DynamoDB API:
http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DeleteItem.html
Parameters
----------
tablename : str
Name of the table to update
key : dict
... | def delete_item2(self, tablename, key, expr_values=None, alias=None,
condition=None, returns=NONE, return_capacity=None,
return_item_collection_metrics=NONE, **kwargs):
"""
Delete an item from a table
For many parameters you will want to reference the D... |
Perform a batch write on a table
Parameters
----------
tablename : str
Name of the table to write to
return_capacity : {NONE, INDEXES, TOTAL}, optional
INDEXES will return the consumed capacity for indexes, TOTAL will
return the consumed capacity for ... | def batch_write(self, tablename, return_capacity=None,
return_item_collection_metrics=NONE):
"""
Perform a batch write on a table
Parameters
----------
tablename : str
Name of the table to write to
return_capacity : {NONE, INDEXES, TOTAL},... |
Perform a batch get of many items in a table
Parameters
----------
tablename : str
Name of the table to fetch from
keys : list or iterable
List or iterable of primary key dicts that specify the hash key and
the optional range key of each item to fetch... | def batch_get(self, tablename, keys, attributes=None, alias=None,
consistent=False, return_capacity=None):
"""
Perform a batch get of many items in a table
Parameters
----------
tablename : str
Name of the table to fetch from
keys : list or ... |
Update a single item in a table
This uses the older version of the DynamoDB API.
See also: :meth:`~.update_item2`.
Parameters
----------
tablename : str
Name of the table to update
key : dict
Primary key dict specifying the hash key and, if appli... | def update_item(self, tablename, key, updates, returns=NONE,
return_capacity=None, expect_or=False, **kwargs):
"""
Update a single item in a table
This uses the older version of the DynamoDB API.
See also: :meth:`~.update_item2`.
Parameters
---------... |
Perform a full-table scan
This uses the older version of the DynamoDB API.
See also: :meth:`~.scan2`.
Parameters
----------
tablename : str
Name of the table to scan
attributes : list
If present, only fetch these attributes from the item
... | def scan(self, tablename, attributes=None, count=False, limit=None,
return_capacity=None, filter_or=False, exclusive_start_key=None,
**kwargs):
"""
Perform a full-table scan
This uses the older version of the DynamoDB API.
See also: :meth:`~.scan2`.
Pa... |
Perform a full-table scan
For many parameters you will want to reference the DynamoDB API:
http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html
Parameters
----------
tablename : str
Name of the table to scan
expr_values : dict, optiona... | def scan2(self, tablename, expr_values=None, alias=None, attributes=None,
consistent=False, select=None, index=None, limit=None,
return_capacity=None, filter=False, segment=None,
total_segments=None, exclusive_start_key=None, **kwargs):
"""
Perform a full-table ... |
Perform an index query on a table
This uses the older version of the DynamoDB API.
See also: :meth:`~.query2`.
Parameters
----------
tablename : str
Name of the table to query
attributes : list
If present, only fetch these attributes from the ite... | def query(self, tablename, attributes=None, consistent=False, count=False,
index=None, limit=None, desc=False, return_capacity=None,
filter=None, filter_or=False, exclusive_start_key=None, **kwargs):
"""
Perform an index query on a table
This uses the older version o... |
Update the throughput of a table and/or global indexes
Parameters
----------
tablename : str
Name of the table to update
throughput : :class:`~dynamo3.fields.Throughput`, optional
The new throughput of the table
global_indexes : dict, optional
... | def update_table(self, tablename, throughput=None, global_indexes=None,
index_updates=None):
"""
Update the throughput of a table and/or global indexes
Parameters
----------
tablename : str
Name of the table to update
throughput : :class:... |
Break catalog into chunks by healpix pixel.
Parameters:
-----------
infiles : List of input files
config : Configuration file
force : Overwrite existing files (depricated)
Returns:
--------
None | def pixelizeCatalog(infiles, config, force=False):
"""
Break catalog into chunks by healpix pixel.
Parameters:
-----------
infiles : List of input files
config : Configuration file
force : Overwrite existing files (depricated)
Returns:
--------
None
"""
nside... |
Get weblogo data for a sequence alignment.
Returns a list of tuples: (posn, letter_counts, entropy, weight) | def read_logodata(handle):
"""Get weblogo data for a sequence alignment.
Returns a list of tuples: (posn, letter_counts, entropy, weight)
"""
seqs = weblogolib.read_seq_data(handle,
alphabet=unambiguous_protein_alphabet)
ldata = weblogolib.LogoData.from_seqs(seqs... |
Get weblogo data for an alignment object.
Returns a list of tuples: (posn, letter_counts, entropy, weight) | def aln2logodata(aln):
"""Get weblogo data for an alignment object.
Returns a list of tuples: (posn, letter_counts, entropy, weight)
"""
handle = StringIO(aln.format('fasta'))
logodata = read_logodata(handle)
handle.close()
return logodata |
Convert letter counts to frequencies, sorted increasing. | def letter_scales(counts):
"""Convert letter counts to frequencies, sorted increasing."""
try:
scale = 1.0 / sum(counts.values())
except ZeroDivisionError:
# This logo is all gaps, nothing can be done
return []
freqs = [(aa, cnt*scale) for aa, cnt in counts.iteritems() if cnt]
... |
Check if value exists into object.
:param doc: the document base
:param pointer: the path to search in
:param expected: the expected value
:param raise_onerror: should raise on error?
:return: boolean | def check(doc, pointer, expected, raise_onerror=False):
"""Check if value exists into object.
:param doc: the document base
:param pointer: the path to search in
:param expected: the expected value
:param raise_onerror: should raise on error?
:return: boolean
"""
return Target(doc).chec... |
Add element to sequence, member to mapping.
:param doc: the document base
:param pointer: the path to add in it
:param value: the new value
:return: the new object | def add(doc, pointer, value):
"""Add element to sequence, member to mapping.
:param doc: the document base
:param pointer: the path to add in it
:param value: the new value
:return: the new object
"""
return Target(doc).add(pointer, value).document |
Replace element from sequence, member from mapping.
:param doc: the document base
:param pointer: the path to search in
:param value: the new value
:return: the new object
.. note::
This operation is functionally identical to a "remove" operation for
a value, followed immediately ... | def replace(doc, pointer, value):
"""Replace element from sequence, member from mapping.
:param doc: the document base
:param pointer: the path to search in
:param value: the new value
:return: the new object
.. note::
This operation is functionally identical to a "remove" operation f... |
Move element from sequence, member from mapping.
:param doc: the document base
:param dest: the destination
:type dest: Pointer
:param src: the source
:type src: Pointer
:return: the new object
.. note::
it delete then it add to the new location
soo the dest must refer to ... | def move(doc, dest, src):
"""Move element from sequence, member from mapping.
:param doc: the document base
:param dest: the destination
:type dest: Pointer
:param src: the source
:type src: Pointer
:return: the new object
.. note::
it delete then it add to the new location
... |
Copy element from sequence, member from mapping.
:param doc: the document base
:param dest: the destination
:type dest: Pointer
:param src: the source
:type src: Pointer
:return: the new object | def copy(doc, dest, src):
"""Copy element from sequence, member from mapping.
:param doc: the document base
:param dest: the destination
:type dest: Pointer
:param src: the source
:type src: Pointer
:return: the new object
"""
return Target(doc).copy(dest, src).document |
Delete member from network
It is method for DELETE /network/{id}/member/{address} | def deleteMember(self, address, id, headers=None, query_params=None, content_type="application/json"):
"""
Delete member from network
It is method for DELETE /network/{id}/member/{address}
"""
uri = self.client.base_url + "/network/"+id+"/member/"+address
return self.clie... |
Get network member settings
It is method for GET /network/{id}/member/{address} | def getMember(self, address, id, headers=None, query_params=None, content_type="application/json"):
"""
Get network member settings
It is method for GET /network/{id}/member/{address}
"""
uri = self.client.base_url + "/network/"+id+"/member/"+address
return self.client.ge... |
Update member settings
It is method for POST /network/{id}/member/{address} | def updateMember(self, data, address, id, headers=None, query_params=None, content_type="application/json"):
"""
Update member settings
It is method for POST /network/{id}/member/{address}
"""
uri = self.client.base_url + "/network/"+id+"/member/"+address
return self.clie... |
Get a list of network members
It is method for GET /network/{id}/member | def listMembers(self, id, headers=None, query_params=None, content_type="application/json"):
"""
Get a list of network members
It is method for GET /network/{id}/member
"""
uri = self.client.base_url + "/network/"+id+"/member"
return self.client.get(uri, None, headers, qu... |
Delete network
It is method for DELETE /network/{id} | def deleteNetwork(self, id, headers=None, query_params=None, content_type="application/json"):
"""
Delete network
It is method for DELETE /network/{id}
"""
uri = self.client.base_url + "/network/"+id
return self.client.delete(uri, None, headers, query_params, content_type... |
Update network configuration
It is method for POST /network/{id} | def updateNetwork(self, data, id, headers=None, query_params=None, content_type="application/json"):
"""
Update network configuration
It is method for POST /network/{id}
"""
uri = self.client.base_url + "/network/"+id
return self.client.post(uri, data, headers, query_para... |
Create a new network
It is method for POST /network | def createNetwork(self, data, headers=None, query_params=None, content_type="application/json"):
"""
Create a new network
It is method for POST /network
"""
uri = self.client.base_url + "/network"
return self.client.post(uri, data, headers, query_params, content_type) |
r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads` | def set_options(self, **kw):
r"""Set Parser options.
.. seealso::
``kw`` argument have the same meaning as in :func:`lazyxml.loads`
"""
for k, v in kw.iteritems():
if k in self.__options:
self.__options[k] = v |
r"""Convert xml content to python object.
:param content: xml content
:rtype: dict
.. versionadded:: 1.2 | def xml2object(self, content):
r"""Convert xml content to python object.
:param content: xml content
:rtype: dict
.. versionadded:: 1.2
"""
content = self.xml_filter(content)
element = ET.fromstring(content)
tree = self.parse(element) if self.__options['... |
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str | def xml_filter(self, content):
r"""Filter and preprocess xml content
:param content: xml content
:rtype: str
"""
content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()
if not self.__options['encoding']:
encoding = sel... |
r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None | def guess_xml_encoding(self, content):
r"""Guess encoding from xml header declaration.
:param content: xml content
:rtype: str or None
"""
matchobj = self.__regex['xml_encoding'].match(content)
return matchobj and matchobj.group(1).lower() |
r"""Parse xml element.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict | def parse(self, element):
r"""Parse xml element.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
values = {}
for child in element:
node = self.get_node(child)
subs = self.parse(child)
value = subs o... |
r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1 | def parse_full(self, element):
r"""Parse xml element include the node attributes.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
.. versionadded:: 1.2.1
"""
values = collections.defaultdict(dict)
for child in element:
... |
r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict | def get_node(self, element):
r"""Get node info.
Parse element and get the element tag info. Include tag name, value, attribute, namespace.
:param element: an :class:`~xml.etree.ElementTree.Element` instance
:rtype: dict
"""
ns, tag = self.split_namespace(element.tag)
... |
r"""Split tag namespace.
:param tag: tag name
:return: a pair of (namespace, tag)
:rtype: tuple | def split_namespace(self, tag):
r"""Split tag namespace.
:param tag: tag name
:return: a pair of (namespace, tag)
:rtype: tuple
"""
matchobj = self.__regex['xml_ns'].search(tag)
return matchobj.groups() if matchobj else ('', tag) |
Creates instances of the probes inputed;
Args:
probes: probes is a nested dictionary with
(key, sub_dict ) = (name of the probe, {'probe_name': value_probe, 'instrument_name': value_inst}),
where value_probe is a valid name of a probe in intrument with name value_inst
for... | def instantiate_probes(probes, instruments):
"""
Creates instances of the probes inputed;
Args:
probes: probes is a nested dictionary with
(key, sub_dict ) = (name of the probe, {'probe_name': value_probe, 'instrument_name': value_inst}),
where value_probe is a valid name... |
Derive address using ``RIPEMD160(SHA256(x))`` | def derivesha256address(self):
""" Derive address using ``RIPEMD160(SHA256(x))`` """
pkbin = unhexlify(repr(self._pubkey))
addressbin = ripemd160(hexlify(hashlib.sha256(pkbin).digest()))
return Base58(hexlify(addressbin).decode('ascii')) |
Derive address using ``RIPEMD160(SHA512(x))`` | def derivesha512address(self):
""" Derive address using ``RIPEMD160(SHA512(x))`` """
pkbin = unhexlify(repr(self._pubkey))
addressbin = ripemd160(hexlify(hashlib.sha512(pkbin).digest()))
return Base58(hexlify(addressbin).decode('ascii')) |
Derive compressed public key | def compressed(self):
""" Derive compressed public key """
order = ecdsa.SECP256k1.generator.order()
p = ecdsa.VerifyingKey.from_string(
compat_bytes(self), curve=ecdsa.SECP256k1).pubkey.point
x_str = ecdsa.util.number_to_string(p.x(), order)
# y_str = ecdsa.util.numb... |
Derive uncompressed key | def unCompressed(self):
""" Derive uncompressed key """
public_key = repr(self._pk)
prefix = public_key[0:2]
if prefix == "04":
return public_key
assert prefix == "02" or prefix == "03"
x = int(public_key[2:], 16)
y = self._derive_y_from_x(x, (prefix =... |
Derive uncompressed public key | def compressedpubkey(self):
""" Derive uncompressed public key """
secret = unhexlify(repr(self._wif))
order = ecdsa.SigningKey.from_string(
secret, curve=ecdsa.SECP256k1).curve.generator.order()
p = ecdsa.SigningKey.from_string(
secret, curve=ecdsa.SECP256k1).ver... |
Derive private key from the brain key and the current sequence
number | def get_private(self):
""" Derive private key from the brain key and the current sequence
number
"""
a = compat_bytes(self.account + self.role + self.password, 'utf8')
s = hashlib.sha256(a).digest()
return PrivateKey(hexlify(s).decode('ascii')) |
:type activeBridge: bool
:type address: str
:type authorized: bool
:type clock: int
:type identity: str
:type ipAssignments: list[str]
:type memberRevision: int
:type nwid: str
:rtype: NetworkMemberConfig | def create(activeBridge=None, address=None, authorized=None, clock=None, identity=None, ipAssignments=None, memberRevision=None, nwid=None):
"""
:type activeBridge: bool
:type address: str
:type authorized: bool
:type clock: int
:type identity: str
:type ipAssignm... |
Get flow direction induced cell length dict.
Args:
flow_model: Currently, "TauDEM", "ArcGIS", and "Whitebox" are supported. | def get_cell_length(flow_model):
"""Get flow direction induced cell length dict.
Args:
flow_model: Currently, "TauDEM", "ArcGIS", and "Whitebox" are supported.
"""
assert flow_model.lower() in FlowModelConst.d8_lens
return FlowModelConst.d8_lens.get(flow_model.lower()... |
find downslope coordinate for D8 direction. | def downstream_index(dir_value, i, j, alg='taudem'):
"""find downslope coordinate for D8 direction."""
assert alg.lower() in FlowModelConst.d8_deltas
delta = FlowModelConst.d8_deltas.get(alg.lower())
drow, dcol = delta[int(dir_value)]
return i + drow, j + dcol |
Get flow direction induced cell shift dict.
Args:
flow_model: Currently, "TauDEM", "ArcGIS", and "Whitebox" are supported. | def get_cell_shift(flow_model):
"""Get flow direction induced cell shift dict.
Args:
flow_model: Currently, "TauDEM", "ArcGIS", and "Whitebox" are supported.
"""
assert flow_model.lower() in FlowModelConst.d8_deltas
return FlowModelConst.d8_deltas.get(flow_model.lower... |
convert D8 flow direction code from one algorithm to another.
Args:
in_file: input raster file path
out_file: output raster file path
in_alg: available algorithms are in FlowModelConst.d8_dirs. "taudem" is the default
out_alg: same as in_alg. "arcgis" is the defau... | def convert_code(in_file, out_file, in_alg='taudem', out_alg='arcgis', datatype=None):
"""
convert D8 flow direction code from one algorithm to another.
Args:
in_file: input raster file path
out_file: output raster file path
in_alg: available algorithms are in... |
search_seqs - method for annotating a BioPython sequence without alignment
:param seqrec: The reference sequence
:type seqrec: SeqRecord
:param locus: The gene locus associated with the sequence.
:type locus: str
:param in_seq: The input sequence
:type in_seq: SeqRecord
... | def search_seqs(self, seqrec, in_seq, locus, run=0, partial_ann=None):
"""
search_seqs - method for annotating a BioPython sequence without alignment
:param seqrec: The reference sequence
:type seqrec: SeqRecord
:param locus: The gene locus associated with the sequence.
... |
Converts parseResult from to ConfGroup type. | def convert_group(tokens):
"""Converts parseResult from to ConfGroup type."""
tok = tokens.asList()
dic = dict(tok)
if not (len(dic) == len(tok)):
raise ParseFatalException("Names in group must be unique: %s" % tokens)
return ConfGroup(dic) |
checks if name has been changed and ignores the name change if the changed_item is an existing script
Args:
changed_item: | def name_changed(self, changed_item):
"""
checks if name has been changed and ignores the name change if the changed_item is an existing script
Args:
changed_item:
"""
name = str(changed_item.text())
# if the item has been moved we ignore this because the ite... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.