INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Create an MCMC instance | def createMCMC(config,srcfile,section='source',samples=None):
""" Create an MCMC instance """
source = ugali.analysis.source.Source()
source.load(srcfile,section=section)
loglike = ugali.analysis.loglike.createLoglike(config,source)
mcmc = MCMC(config,loglike)
if samples is not None:
m... |
Logarithm of the likelihood | def lnlike(self, theta):
""" Logarithm of the likelihood """
params,loglike = self.params,self.loglike
kwargs = dict(list(zip(params,theta)))
try:
lnlike = loglike.value(**kwargs)
except ValueError as AssertionError:
lnlike = -np.inf
return lnlike |
Logarithm of the prior | def lnprior(self,theta):
""" Logarithm of the prior """
params,priors = self.params,self.priors
kwargs = dict(list(zip(params,theta)))
err = np.seterr(invalid='raise')
try:
lnprior = np.sum(np.log([priors[k](v) for k,v in list(kwargs.items())]))
except (Floati... |
Logarithm of the probability | def lnprob(self,theta):
""" Logarithm of the probability """
global niter
params,priors,loglike = self.params,self.priors,self.loglike
# Avoid extra likelihood calls with bad priors
_lnprior = self.lnprior(theta)
if np.isfinite(_lnprior):
_lnlike = self.lnlike... |
Top level interface to write the membership from a config and source model. | def write_membership(filename,config,srcfile,section=None):
"""
Top level interface to write the membership from a config and source model.
"""
source = Source()
source.load(srcfile,section=section)
loglike = createLoglike(config,source)
loglike.write_membership(filename) |
Create a catalog object | def createCatalog(config,roi=None,lon=None,lat=None):
"""
Create a catalog object
"""
import ugali.observation.catalog
if roi is None: roi = createROI(config,lon,lat)
catalog = ugali.observation.catalog.Catalog(config,roi=roi)
return catalog |
Simulate a catalog object. | def simulateCatalog(config,roi=None,lon=None,lat=None):
"""
Simulate a catalog object.
"""
import ugali.simulation.simulator
if roi is None: roi = createROI(config,lon,lat)
sim = ugali.simulation.simulator.Simulator(config,roi)
return sim.catalog() |
Calculated observable fraction within each pixel of the target region. | def calc_observable_fraction(self,distance_modulus):
"""
Calculated observable fraction within each pixel of the target region.
"""
# This is the observable fraction after magnitude cuts in each
# pixel of the ROI.
observable_fraction = self.isochrone.observableFraction(... |
Compute signal color probability (u_color) for each catalog object on the fly. | def calc_signal_color1(self, distance_modulus, mass_steps=10000):
"""
Compute signal color probability (u_color) for each catalog object on the fly.
"""
mag_1, mag_2 = self.catalog.mag_1,self.catalog.mag_2
mag_err_1, mag_err_2 = self.catalog.mag_err_1,self.catalog.mag_err_2
... |
Compute signal color probability (u_color) for each catalog object on the fly. | def calc_signal_color2(self, distance_modulus, mass_steps=1000):
"""
Compute signal color probability (u_color) for each catalog object on the fly.
"""
logger.info('Calculating signal color from MMD')
mag_1, mag_2 = self.catalog.mag_1,self.catalog.mag_2
lon, lat = self.c... |
Calculate the surface intensity for each pixel in the interior
region of the ROI. Pixels are adaptively subsampled around the
kernel centroid out to a radius of 'factor * max_pixrad'.
Parameters:
-----------
factor : the radius of the oversample region in units of max_pixrad
... | def calc_surface_intensity(self, factor=10):
"""Calculate the surface intensity for each pixel in the interior
region of the ROI. Pixels are adaptively subsampled around the
kernel centroid out to a radius of 'factor * max_pixrad'.
Parameters:
-----------
factor : the ra... |
Calculate the spatial signal probability for each catalog object.
Parameters:
-----------
None
Returns:
--------
u_spatial : array of spatial probabilities per object | def calc_signal_spatial(self):
"""
Calculate the spatial signal probability for each catalog object.
Parameters:
-----------
None
Returns:
--------
u_spatial : array of spatial probabilities per object
"""
# Calculate the surface intensit... |
Maximize the log-likelihood as a function of richness.
ADW 2018-06-04: Does it make sense to set the richness to the mle?
Parameters:
-----------
atol : absolute tolerence for conversion
maxiter : maximum number of iterations
Returns:
--------
loglike, ... | def fit_richness(self, atol=1.e-3, maxiter=50):
"""
Maximize the log-likelihood as a function of richness.
ADW 2018-06-04: Does it make sense to set the richness to the mle?
Parameters:
-----------
atol : absolute tolerence for conversion
maxiter : maximum numbe... |
Write a catalog file of the likelihood region including
membership properties.
Parameters:
-----------
filename : output filename
Returns:
--------
None | def write_membership(self,filename):
"""
Write a catalog file of the likelihood region including
membership properties.
Parameters:
-----------
filename : output filename
Returns:
--------
None
"""
# Column names
n... |
Resolve a JSON Pointer object reference to the object itself.
:param ref: Reference string (`#/foo/bar`, for instance)
:return: The object, if found
:raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference | def resolve_reference(self, ref):
"""
Resolve a JSON Pointer object reference to the object itself.
:param ref: Reference string (`#/foo/bar`, for instance)
:return: The object, if found
:raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the referenc... |
Construct a Path object from a path string.
The Path string must be declared in the API.
:type path: str
:rtype: lepo.path.Path | def get_path(self, path):
"""
Construct a Path object from a path string.
The Path string must be declared in the API.
:type path: str
:rtype: lepo.path.Path
"""
mapping = self.get_path_mapping(path)
return self.path_class(api=self, path=path, mapping=ma... |
Construct an APIDefinition by parsing the given `filename`.
If PyYAML is installed, YAML files are supported.
JSON files are always supported.
:param filename: The filename to read.
:rtype: APIDefinition | def from_file(cls, filename):
"""
Construct an APIDefinition by parsing the given `filename`.
If PyYAML is installed, YAML files are supported.
JSON files are always supported.
:param filename: The filename to read.
:rtype: APIDefinition
"""
with open(fi... |
Call `resolve` on the `object`'s `$ref` value if it has one.
:param object: An object.
:param resolve: A resolving function.
:return: An object, or some other object! :sparkles: | def maybe_resolve(object, resolve):
"""
Call `resolve` on the `object`'s `$ref` value if it has one.
:param object: An object.
:param resolve: A resolving function.
:return: An object, or some other object! :sparkles:
"""
if isinstance(object, dict) and object.get('$ref'):
return re... |
Parse configuration options out of a YAML configuration file.
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 configur... | def parse(self, configManager, config):
"""
Parse configuration options out of a YAML configuration file.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration options popula... |
Log and return a server error message. | def _server_error_message(url, message):
"""Log and return a server error message."""
msg = _error_message.format(url=url, message=message)
log.error(msg)
return msg |
Make a request with the provided data.
@param url The url to make the request to.
@param method The HTTP request method (defaulting to "GET").
@param query A dict of the query key and values.
@param body The optional body as a string or as a JSON decoded dict.
@param auth The optional username and ... | def make_request(
url, method='GET', query=None, body=None, auth=None, timeout=10,
client=None, macaroons=None):
"""Make a request with the provided data.
@param url The url to make the request to.
@param method The HTTP request method (defaulting to "GET").
@param query A dict of the q... |
Get the plans for a given charm.
@param the Reference to a charm.
@return a tuple of plans or an empty tuple if no plans.
@raise ServerError | def get_plans(self, reference):
"""Get the plans for a given charm.
@param the Reference to a charm.
@return a tuple of plans or an empty tuple if no plans.
@raise ServerError
"""
response = make_request(
'{}charm?charm-url={}'.format(self.url,
... |
Get the list of wallets.
@return an dict containing a list of wallets, a total, and available
credit.
@raise ServerError | def list_wallets(self):
"""Get the list of wallets.
@return an dict containing a list of wallets, a total, and available
credit.
@raise ServerError
"""
response = make_request(
'{}wallet'.format(self.url),
timeout=self.timeout,
cli... |
Get a single wallet.
@param the name of the wallet.
@return the wallet's total.
@raise ServerError | def get_wallet(self, wallet_name):
"""Get a single wallet.
@param the name of the wallet.
@return the wallet's total.
@raise ServerError
"""
response = make_request(
'{}wallet/{}'.format(self.url, wallet_name),
timeout=self.timeout,
cl... |
Update a wallet with a new limit.
@param the name of the wallet.
@param the new value of the limit.
@return a success string from the plans server.
@raise ServerError via make_request. | def update_wallet(self, wallet_name, limit):
"""Update a wallet with a new limit.
@param the name of the wallet.
@param the new value of the limit.
@return a success string from the plans server.
@raise ServerError via make_request.
"""
request = {
'u... |
Delete a wallet.
@param the name of the wallet.
@return a success string from the plans server.
@raise ServerError via make_request. | def delete_wallet(self, wallet_name):
"""Delete a wallet.
@param the name of the wallet.
@return a success string from the plans server.
@raise ServerError via make_request.
"""
return make_request(
'{}wallet/{}'.format(self.url, wallet_name),
met... |
Create a new budget for a model and wallet.
@param the name of the wallet.
@param the model UUID.
@param the new value of the limit.
@return a success string from the plans server.
@raise ServerError via make_request. | def create_budget(self, wallet_name, model_uuid, limit):
"""Create a new budget for a model and wallet.
@param the name of the wallet.
@param the model UUID.
@param the new value of the limit.
@return a success string from the plans server.
@raise ServerError via make_re... |
Delete a budget.
@param the name of the wallet.
@param the model UUID.
@return a success string from the plans server.
@raise ServerError via make_request. | def delete_budget(self, model_uuid):
"""Delete a budget.
@param the name of the wallet.
@param the model UUID.
@return a success string from the plans server.
@raise ServerError via make_request.
"""
return make_request(
'{}model/{}/budget'.format(sel... |
Randomly sample Dataframe rows. Typically for testset/training set cross-valication
random_split(pd.DataFrame()) | def random_split(df, first_portion=.1):
"""Randomly sample Dataframe rows. Typically for testset/training set cross-valication
random_split(pd.DataFrame())
"""
mask = np.random.binomial(1, first_portion, size=len(df)).astype(bool)
return df[mask].copy(), df[~mask].copy() |
Safely divide by zero and inf and nan and produce floating point result
Numerical results are equivalent to `from __future__ import division`
Args:
a (float or int): numerator
b (float or int): denominator
inf (float or object): value to return in place of division by zero errors
none (f... | def safe_div(a, b, inf=INF):
"""Safely divide by zero and inf and nan and produce floating point result
Numerical results are equivalent to `from __future__ import division`
Args:
a (float or int): numerator
b (float or int): denominator
inf (float or object): value to return in place of d... |
Calculate Chi from True Positive (tp), True Negative (tn), False Positive/Negative counts.
Assumes that the random variable being measured is continuous rather than discrete.
Reference:
https://en.wikipedia.org/wiki/Matthews_correlation_coefficient
>>> round(tptnfpfn_chi(1000, 2000, 30, 40))
2765.... | def tptnfpfn_chi(*args, **kwargs):
"""Calculate Chi from True Positive (tp), True Negative (tn), False Positive/Negative counts.
Assumes that the random variable being measured is continuous rather than discrete.
Reference:
https://en.wikipedia.org/wiki/Matthews_correlation_coefficient
>>> round(t... |
Convert kwargs for tp, tn, fp, fn to ordered tuple of args
If a single tuple/list is passed as the first arg, it is assumed to be the desired tuple of args
>>> args_tptnfpfn(1, 2, 3, 4)
(1, 2, 3, 4)
>>> args_tptnfpfn((1, 2, 3, 4))
(1, 2, 3, 4)
>>> args_tptnfpfn([1, 2, 3, 4])
(1, 2, 3, 4)
... | def args_tptnfpfn(*args, **kwargs):
"""Convert kwargs for tp, tn, fp, fn to ordered tuple of args
If a single tuple/list is passed as the first arg, it is assumed to be the desired tuple of args
>>> args_tptnfpfn(1, 2, 3, 4)
(1, 2, 3, 4)
>>> args_tptnfpfn((1, 2, 3, 4))
(1, 2, 3, 4)
>>> args_... |
Count the True Pos, True Neg, False Pos, False Neg samples within a confusions matrx (potentiall larger than 2x2)
>>> matrix = [[5, 3, 0], [2, 3, 1], [0, 2, 11]]
>>> columns=['Cat', 'Dog', 'Rabbit']
>>> x = np.array([[tc, pc] for (tc, row) in enumerate(matrix) for (pc, n) in enumerate(row) for i in range(n)... | def dataframe_tptnfpfn(df, pos_label=True, labels=None):
"""Count the True Pos, True Neg, False Pos, False Neg samples within a confusions matrx (potentiall larger than 2x2)
>>> matrix = [[5, 3, 0], [2, 3, 1], [0, 2, 11]]
>>> columns=['Cat', 'Dog', 'Rabbit']
>>> x = np.array([[tc, pc] for (tc, row) in e... |
Binary classification confusion | def confusion(df, labels=['neg', 'pos']):
""" Binary classification confusion """
c = pd.DataFrame(np.zeros((2, 2)), dtype=int)
a, b = df.columns[:2] # labels[df.columns[:2]]
c.columns = sorted(set(df[a]))[:2]
c.columns.name = a
c.index = list(c.columns)
c.index.name = b
c1, c2 = c.colu... |
Try to guess a positive classification label from a negative label
Basis for an NLP function to find the "opposite" of a string
yes->no, true->false, etc)
>>> [infer_pos_label(x) for x in ('1', '-1', '0', '2', 1, 0, 'F', 'False', False, True)]
['0', '1', '1', '3', 0, 1, 'T', 'True', True, False] | def infer_pos_label(neg_label=None):
"""Try to guess a positive classification label from a negative label
Basis for an NLP function to find the "opposite" of a string
yes->no, true->false, etc)
>>> [infer_pos_label(x) for x in ('1', '-1', '0', '2', 1, 0, 'F', 'False', False, True)]
['0', '1', '1', ... |
Compose pair of lists of dicts (nodes, edges) for the graph described by a DataFrame | def graph_from_cov_df(df, threshold=.5, gain=2., n=None, class_dict=CLASSES):
"""Compose pair of lists of dicts (nodes, edges) for the graph described by a DataFrame"""
n = n or len(df)
nodes = [{'group': class_dict.get(name, 0), "name": name} for name in df.index.values][:n]
edges = []
for i, (row_... |
Produce a json string describing the graph (list of edges) from a square auto-correlation/covariance matrix
{ "nodes": [{"group": 1, "name": "the"},
{"group": 1, "name": "and"},
{"group": 1, "name": "our"},
{"group": 2, "name": "that"},...
"links": [{"sour... | def json_from_cov_df(df, threshold=.5, gain=2., n=None, indent=1):
"""Produce a json string describing the graph (list of edges) from a square auto-correlation/covariance matrix
{ "nodes": [{"group": 1, "name": "the"},
{"group": 1, "name": "and"},
{"group": 1, "name": "our"},
... |
r"""Compute the specifity that a particular threshold on the scores can acheive
specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive)
>>> scores = np.arange(0, 1, 0.1)
>>> spec_from_thresh(0.5, labels=(scores > .5).astype(int), scores=scores)
1.0
>>> spec_from_thresh(0.5, labels... | def spec_from_thresh(thresh, labels, scores, *args, **kwargs):
r"""Compute the specifity that a particular threshold on the scores can acheive
specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive)
>>> scores = np.arange(0, 1, 0.1)
>>> spec_from_thresh(0.5, labels=(scores > .5).astyp... |
r"""Find the sensitivity that corresponds to the indicated specificity (ROC function)
sensitivity = Num_True_Positive / (Num_True_Postive + Num_False_Negative)
specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive) | def sens_from_spec(spec, labels, scores, *args, **kwargs):
r"""Find the sensitivity that corresponds to the indicated specificity (ROC function)
sensitivity = Num_True_Positive / (Num_True_Postive + Num_False_Negative)
specificity = Num_True_Negative / (Num_True_Negative + Num_False_Positive)
"""
th... |
Enables minimization (root-finding) for non-zero targets
Returns regularized absolute error between target and output of `fun`.
Configurable state with function attributes.
>>> cost_fun.fun = spec_from_thresh # "forward" function we want to evaluate in cost_fun to compute error
>>> cost_fun.target = 1.... | def cost_fun(x, *args, **kwargs):
"""Enables minimization (root-finding) for non-zero targets
Returns regularized absolute error between target and output of `fun`.
Configurable state with function attributes.
>>> cost_fun.fun = spec_from_thresh # "forward" function we want to evaluate in cost_fun to c... |
Plot the cost function topology (contours for each of several targets) | def plot_cost(scores=np.random.rand(100), thresh=0.5, noise=0):
"""Plot the cost function topology (contours for each of several targets)"""
c = pd.DataFrame(index=np.arange(0, 1, 0.01))
if isinstance(thresh, (int, float)):
thresh = [thresh]
elif not isinstance(thresh, (pd.Series, np.ndarray, li... |
r"""Find the threshold level that accomplishes the desired specificity
Call indicated function repeatedly to find answer to the inverse function evaluation
Arguments:
fun (function): function to be calculate an inverse for
y (float): desired output of fun
x0 (float): initial guess at input to ... | def fun_inverse(fun=None, y=0, x0=None, args=(), disp=False, method='Nelder-Mead', **kwargs):
r"""Find the threshold level that accomplishes the desired specificity
Call indicated function repeatedly to find answer to the inverse function evaluation
Arguments:
fun (function): function to be calculate ... |
r"""Find the threshold level that accomplishes the desired specificity | def thresh_from_spec(spec, labels, scores, **kwargs):
r"""Find the threshold level that accomplishes the desired specificity"""
cost_fun.verbose = kwargs.pop('verbose', cost_fun.verbose)
cost_fun.target = spec
return minimize(cost_fun,
x0=[.5],
args=(labels, score... |
Probability Distribution function from values
Arguments:
probability (bool): whether the values should be min/max scaled to lie on the range [0, 1]
Like `hist` but smoother, more accurate/useful
Double-Normalization:
The x values are min/max normalized to lie in the range 0-1 inclusive
The... | def dyno_hist(x, window=None, probability=True, edge_weight=1.):
""" Probability Distribution function from values
Arguments:
probability (bool): whether the values should be min/max scaled to lie on the range [0, 1]
Like `hist` but smoother, more accurate/useful
Double-Normalization:
The x ... |
Calculations that only depend on aggregate counts in Confusion Matrix go here | def refresh_meta(self):
"""Calculations that only depend on aggregate counts in Confusion Matrix go here"""
# these calcs are duplicated in __init__()
setattr(self, '_num_classes', len(self.index))
setattr(self, '_colnums', np.arange(0, self._num_classes))
try:
setat... |
Num_True_Positive / Num_Samples | def get_accuracy(self, scalar=None):
"""Num_True_Positive / Num_Samples"""
# to get a Series instead of a dict:
# (np.diag(c).astype(float) / c.T.sum())
# == pd.Series(self.sensitivity)
if ((not self._scalar_stats and not scalar and self._num_classes > 2) or
(... |
Creates a confusion matrix from a DataFrame that already contains confusion counts (but not meta stats)
>>> df = pd.DataFrame(np.matrix([[0,1,2,0,1,2,1,2,2,1],[0,1,2,1,2,0,0,1,2,0]]).T, columns=['True', 'Pred'])
>>> c = Confusion(df)
>>> c2 = pd.DataFrame(c)
>>> hasattr(c2, '_binary_sens... | def from_existing(cls, confusion, *args, **kwargs):
"""Creates a confusion matrix from a DataFrame that already contains confusion counts (but not meta stats)
>>> df = pd.DataFrame(np.matrix([[0,1,2,0,1,2,1,2,2,1],[0,1,2,1,2,0,0,1,2,0]]).T, columns=['True', 'Pred'])
>>> c = Confusion(df)
... |
True Positive Rate = TP / P = Num_True_Positive / (Num_True_Postive + Num_False_Negative) | def get_sensitivity(self, scalar=None):
"""True Positive Rate = TP / P = Num_True_Positive / (Num_True_Postive + Num_False_Negative)"""
# to get a Series instead of a dict:
# (np.diag(c).astype(float) / c.T.sum())
# == pd.Series(self.sensitivity)
if ((not self._scalar_stats a... |
True_Negative / (True_Negative + False_Positive) | def get_specificity(self, scalar=None):
"""True_Negative / (True_Negative + False_Positive)"""
if ((not self._scalar_stats and not scalar and self._num_classes > 2) or
((scalar is False or self._scalar_stats is False) and self._num_classes > 1)):
spec = PrettyDict()
... |
Phi (φ) Coefficient -- lack of confusion
Arguments:
scalar (bool or None): Whether to return a scalar Phi coefficient
(assume binary classification) rather than a multiclass vector
Measure of the lack of confusion in a single value
References:
[MCC on wikipedia](htt... | def get_phi(self, scalar=None):
"""Phi (φ) Coefficient -- lack of confusion
Arguments:
scalar (bool or None): Whether to return a scalar Phi coefficient
(assume binary classification) rather than a multiclass vector
Measure of the lack of confusion in a single value
R... |
sqrt(Chi_Squared) statistic (see `mcc`, `phi`, or google 'Matthews Correlation Coefficient | def get_chi(self, scalar=None):
"""sqrt(Chi_Squared) statistic (see `mcc`, `phi`, or google 'Matthews Correlation Coefficient'"""
phi = self.get_phi(scalar=scalar)
return mcc_chi(phi, self._num_samples) |
Normalized false positive rate (0 <= fp <= 1) | def get_false_negative(self, scalar=True):
"""Normalized false positive rate (0 <= fp <= 1)"""
ans = pd.Series(PrettyDict([(k, safe_div(np.sum(self.loc[k]) - self[k][k],
np.sum(self.sum() - self.loc[k]))) for k in self.columns]))
if (not self._sca... |
Check valid parameter range and download isochrones from:
http://stev.oapd.inaf.it/cgi-bin/cmd | def download(self,age,metallicity,outdir=None,force=False):
"""
Check valid parameter range and download isochrones from:
http://stev.oapd.inaf.it/cgi-bin/cmd
"""
if outdir is None: outdir = './'
basename = self.isochrone.params2filename(age,metallicity)
outfile =... |
Merge two dicts of addable values | def add_dicts(d1, d2):
""" Merge two dicts of addable values """
if d1 is None:
return d2
if d2 is None:
return d1
keys = set(d1)
keys.update(set(d2))
ret = {}
for key in keys:
v1 = d1.get(key)
v2 = d2.get(key)
if v1 is None:
ret[key] = v2
... |
Update the consumed capacity metrics | def _update_capacity(self, data):
""" Update the consumed capacity metrics """
if 'ConsumedCapacity' in data:
# This is all for backwards compatibility
consumed = data['ConsumedCapacity']
if not isinstance(consumed, list):
consumed = [consumed]
... |
Fetch more results from Dynamo | def fetch(self):
""" Fetch more results from Dynamo """
self.limit.set_request_args(self.kwargs)
data = self.connection.call(*self.args, **self.kwargs)
self.limit.post_fetch(data)
self.last_evaluated_key = data.get('LastEvaluatedKey')
if self.last_evaluated_key is None:
... |
Construct the kwargs to pass to batch_get_item | def build_kwargs(self):
""" Construct the kwargs to pass to batch_get_item """
keys, self.keys = self.keys[:MAX_GET_BATCH], self.keys[MAX_GET_BATCH:]
query = {'ConsistentRead': self.consistent}
if self.attributes is not None:
query['ProjectionExpression'] = self.attributes
... |
Fetch a set of items from their keys | def fetch(self):
""" Fetch a set of items from their keys """
kwargs = self.build_kwargs()
data = self.connection.call('batch_get_item', **kwargs)
if 'UnprocessedKeys' in data:
for items in six.itervalues(data['UnprocessedKeys']):
self.keys.extend(items['Keys'... |
Return a copy of the limit | def copy(self):
""" Return a copy of the limit """
return Limit(self.scan_limit, self.item_limit, self.min_scan_limit,
self.strict, self.filter) |
Set the Limit parameter into the request args | def set_request_args(self, args):
""" Set the Limit parameter into the request args """
if self.scan_limit is not None:
args['Limit'] = self.scan_limit
elif self.item_limit is not None:
args['Limit'] = max(self.item_limit, self.min_scan_limit)
else:
ar... |
Return True if the limit has been reached | def complete(self):
""" Return True if the limit has been reached """
if self.scan_limit is not None and self.scan_limit == 0:
return True
if self.item_limit is not None and self.item_limit == 0:
return True
return False |
Apply the filter and item_limit, and return True to accept | def accept(self, item):
""" Apply the filter and item_limit, and return True to accept """
accept = self.filter(item)
if accept and self.item_limit is not None:
if self.item_limit > 0:
self.item_limit -= 1
elif self.strict:
return False
... |
Generate a random walk and return True if the walker has returned to
the origin after taking `n` steps. | def returned(n):
"""Generate a random walk and return True if the walker has returned to
the origin after taking `n` steps.
"""
## `takei` yield lazily so we can short-circuit and avoid computing the rest of the walk
for pos in randwalk() >> drop(1) >> takei(xrange(n-1)):
if pos == Origin:
return True
return... |
Generate a random walk and return its length upto the moment
that the walker first returns to the origin.
It is mathematically provable that the walker will eventually return,
meaning that the function call will halt, although it may take
a *very* long time and your computer may run out of memory!
Thus, try this ... | def first_return():
"""Generate a random walk and return its length upto the moment
that the walker first returns to the origin.
It is mathematically provable that the walker will eventually return,
meaning that the function call will halt, although it may take
a *very* long time and your computer may run out of ... |
An arithmetic sequence generator. Works with any type with + defined.
>>> seq(1, 0.25) >> item[:10]
[1, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25] | def seq(start=0, step=1):
"""An arithmetic sequence generator. Works with any type with + defined.
>>> seq(1, 0.25) >> item[:10]
[1, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25]
"""
def seq(a, d):
while 1:
yield a
a += d
return seq(start, step) |
Curried version of the built-in reduce.
>>> reduce(lambda x,y: x+y)( [1, 2, 3, 4, 5] )
15 | def reduce(function, initval=None):
"""
Curried version of the built-in reduce.
>>> reduce(lambda x,y: x+y)( [1, 2, 3, 4, 5] )
15
"""
if initval is None:
return lambda s: __builtin__.reduce(function, s)
else:
return lambda s: __builtin__.reduce(function, s, initval) |
Connect inpipe and outpipe. If outpipe is not a Stream instance,
it should be an function callable on an iterable. | def pipe(inpipe, outpipe):
"""Connect inpipe and outpipe. If outpipe is not a Stream instance,
it should be an function callable on an iterable.
"""
if hasattr(outpipe, '__pipe__'):
return outpipe.__pipe__(inpipe)
elif hasattr(outpipe, '__call__'):
return outpipe(inpipe)
else:
raise BrokenPipe('No... |
Similar to __pipe__, except that outpipe must be a Stream, in
which case self.iterator will be modified in-place by calling
outpipe.__call__ on it. | def extend(self, outpipe):
"""Similar to __pipe__, except that outpipe must be a Stream, in
which case self.iterator will be modified in-place by calling
outpipe.__call__ on it.
"""
self.iterator = outpipe.__call__(self.iterator)
return self |
Return job ids assigned to the submitted items. | def submit(self, *items):
"""Return job ids assigned to the submitted items."""
with self.lock:
if self.closed:
raise BrokenPipe('Job submission has been closed.')
id = self.jobcount
self._status += ['SUBMITTED'] * len(items)
self.jobcount += len(items)
for item in items:
self.waitqueue.put((... |
Try to cancel jobs with associated ids.
Return the actual number of jobs cancelled. | def cancel(self, *ids):
"""Try to cancel jobs with associated ids.
Return the actual number of jobs cancelled.
"""
ncancelled = 0
with self.lock:
for id in ids:
try:
if self._status[id] == 'SUBMITTED':
self._status[id] = 'CANCELLED'
ncancelled += 1
except IndexError:
pass
... |
Return the statuses of jobs with associated ids at the
time of call: either 'SUBMITED', 'CANCELLED', 'RUNNING',
'COMPLETED' or 'FAILED'. | def status(self, *ids):
"""Return the statuses of jobs with associated ids at the
time of call: either 'SUBMITED', 'CANCELLED', 'RUNNING',
'COMPLETED' or 'FAILED'.
"""
with self.lock:
if len(ids) > 1:
return [self._status[i] for i in ids]
else:
return self._status[ids[0]] |
Signal that the executor will no longer accept job submission.
Worker threads/processes are now allowed to terminate after all
jobs have been are completed. Without a call to close(), they will
stay around forever waiting for more jobs to come. | def close(self):
"""Signal that the executor will no longer accept job submission.
Worker threads/processes are now allowed to terminate after all
jobs have been are completed. Without a call to close(), they will
stay around forever waiting for more jobs to come.
"""
with self.lock:
if self.closed:
... |
Note that the Executor must be close()'d elsewhere,
or join() will never return. | def join(self):
"""Note that the Executor must be close()'d elsewhere,
or join() will never return.
"""
self.inputfeeder_thread.join()
self.pool.join()
self.resulttracker_thread.join()
self.failuretracker_thread.join() |
Shut down the Executor. Suspend all waiting jobs.
Running workers will terminate after finishing their current job items.
The call will block until all workers are terminated. | def shutdown(self):
"""Shut down the Executor. Suspend all waiting jobs.
Running workers will terminate after finishing their current job items.
The call will block until all workers are terminated.
"""
with self.lock:
self.pool.inqueue.put(StopIteration) # Stop the pool workers
self.waitqueue.put... |
monica helps you order food from the timeline | def main():
'''monica helps you order food from the timeline'''
arguments = docopt(__doc__, version=__version__)
if arguments['configure'] and flag:
configure()
if arguments['cuisine']:
if arguments['list']:
cuisine('list')
else:
cuisine(arguments['<cuisine-id>'])
elif arguments['surp... |
Create a list of requirements from the output of the pip freeze command
saved in a text file. | def _get_requirements(fname):
"""
Create a list of requirements from the output of the pip freeze command
saved in a text file.
"""
packages = _read(fname).split('\n')
packages = (p.strip() for p in packages)
packages = (p for p in packages if p and not p.startswith('#'))
return list(pac... |
Adds links all placeholders plugins except django-terms plugins | def TermsProcessor(instance, placeholder, rendered_content, original_context):
"""
Adds links all placeholders plugins except django-terms plugins
"""
if 'terms' in original_context:
return rendered_content
return mark_safe(replace_terms(rendered_content)) |
Call to isochrone install command:
http://stackoverflow.com/a/24353921/4075339 | def install_isochrones(self):
"""
Call to isochrone install command:
http://stackoverflow.com/a/24353921/4075339
"""
cmd_obj = self.distribution.get_command_obj('isochrones')
cmd_obj.force = self.force
if self.ugali_dir: cmd_obj.ugali_dir = self.ugali_dir
... |
Call to catalog install command:
http://stackoverflow.com/a/24353921/4075339 | def install_catalogs(self):
"""
Call to catalog install command:
http://stackoverflow.com/a/24353921/4075339
"""
cmd_obj = self.distribution.get_command_obj('catalogs')
cmd_obj.force = self.force
if self.ugali_dir: cmd_obj.ugali_dir = self.ugali_dir
self.r... |
Google return a JSON document describing the error. We should parse this
and extract the error reason. See
https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors | def parse_reason(response, content):
"""
Google return a JSON document describing the error. We should parse this
and extract the error reason. See
https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors
"""
def first_error(data):
errors = data['error']['errors']
... |
Valid time steps for this service as a list of datetime objects. | def time_stops(self):
""" Valid time steps for this service as a list of datetime objects. """
if not self.supports_time:
return []
if self.service.calendar == 'standard':
units = self.service.time_interval_units
interval = self.service.time_interval
... |
Parse target coordinates in various ways... | def _parse_coords(self,opts):
""" Parse target coordinates in various ways...
"""
# The coordinates are mutually exclusive, so
# shouldn't have to worry about over-writing them.
if 'coords' in vars(opts): return
radius = vars(opts).get('radius',0)
gal = None
... |
Load a text file with target coordinates. Returns
an array of target locations in Galactic coordinates.
File description:
[NAME] [LON] [LAT] [RADIUS] [COORD]
The values of LON and LAT will depend on COORD:
COORD = [GAL | CEL | HPX ],
LON = [GLON | RA | NSIDE... | def parse_targets(filename):
"""
Load a text file with target coordinates. Returns
an array of target locations in Galactic coordinates.
File description:
[NAME] [LON] [LAT] [RADIUS] [COORD]
The values of LON and LAT will depend on COORD:
COORD = [GAL | ... |
special_fields: "a dict of data specific to collector type
that should be added to the data returned by the parser.
This will also be and operated on by idMapping, mappings and
plugins"
This method loops through the data provided to the instance.
For each item it wil... | def get_data(self, special_fields=None):
"""
special_fields: "a dict of data specific to collector type
that should be added to the data returned by the parser.
This will also be and operated on by idMapping, mappings and
plugins"
This method loops through th... |
Compute the mean fracdet within circular aperture (radius specified in decimal degrees)
lon, lat, and radius are taken to be arrays of the same length | def meanFracdet(map_fracdet, lon_population, lat_population, radius_population):
"""
Compute the mean fracdet within circular aperture (radius specified in decimal degrees)
lon, lat, and radius are taken to be arrays of the same length
"""
nside_fracdet = healpy.npix2nside(len(map_fracdet))
map... |
Simulate a single satellite. This is currently only valid for band_1 = g and band_2 = r.
r_physical is azimuthally averaged half-light radius, kpc | def catsimSatellite(config, lon_centroid, lat_centroid, distance, stellar_mass, r_physical,
m_maglim_1, m_maglim_2, m_ebv,
plot=False, title='test'):
"""
Simulate a single satellite. This is currently only valid for band_1 = g and band_2 = r.
r_physical is azimuthall... |
n = Number of satellites to simulation
n_chunk = Number of satellites in a file chunk | def catsimPopulation(tag, mc_source_id_start=1, n=5000, n_chunk=100, config='simulate_population.yaml'):
"""
n = Number of satellites to simulation
n_chunk = Number of satellites in a file chunk
"""
assert mc_source_id_start >= 1, "Starting mc_source_id must be >= 1"
assert n % n_chunk == 0, "... |
Property to return the default value.
If the default value is callable and call_default is True, return
the result of default(). Else return default.
Returns:
object: the default value. | def default_value(self):
"""
Property to return the default value.
If the default value is callable and call_default is True, return
the result of default(). Else return default.
Returns:
object: the default value.
"""
if callable(self.default) and s... |
Property to return the variable defined in ``django.conf.settings``.
Returns:
object: the variable defined in ``django.conf.settings``.
Raises:
AttributeError: if the variable is missing.
KeyError: if the item is missing from nested setting. | def raw_value(self):
"""
Property to return the variable defined in ``django.conf.settings``.
Returns:
object: the variable defined in ``django.conf.settings``.
Raises:
AttributeError: if the variable is missing.
KeyError: if the item is missing from... |
Return the transformed raw or default value.
If the variable is missing from the project settings, and the setting
is required, re-raise an AttributeError. If it is not required,
return the (optionally transformed) default value.
Returns:
object: the transformed raw value. | def get_value(self):
"""
Return the transformed raw or default value.
If the variable is missing from the project settings, and the setting
is required, re-raise an AttributeError. If it is not required,
return the (optionally transformed) default value.
Returns:
... |
Run the validators on the setting value. | def run_validators(self, value):
"""Run the validators on the setting value."""
errors = []
for validator in self.validators:
try:
validator(value)
except ValidationError as error:
errors.extend(error.messages)
if errors:
... |
Run the setting checker against the setting raw value.
Raises:
AttributeError: if the setting is missing and required.
ValueError: if the raw value is invalid. | def check(self):
"""
Run the setting checker against the setting raw value.
Raises:
AttributeError: if the setting is missing and required.
ValueError: if the raw value is invalid.
"""
try:
value = self.raw_value
except (AttributeError... |
Transform a path into an actual Python object.
The path can be arbitrary long. You can pass the path to a package,
a module, a class, a function or a global variable, as deep as you
want, as long as the deepest module is importable through
``importlib.import_module`` and each object is ... | def transform(self, path):
"""
Transform a path into an actual Python object.
The path can be arbitrary long. You can pass the path to a package,
a module, a class, a function or a global variable, as deep as you
want, as long as the deepest module is importable through
... |
Return dictionary with values of subsettings.
Returns:
dict: values of subsettings. | def get_value(self):
"""
Return dictionary with values of subsettings.
Returns:
dict: values of subsettings.
"""
try:
self.raw_value
except (AttributeError, KeyError) as err:
self._reraise_if_required(err)
default_value = s... |
Run the setting checker against the setting raw value.
Raises:
AttributeError: if the setting is missing and required.
ValueError: (or other Exception) if the raw value is invalid. | def check(self):
"""
Run the setting checker against the setting raw value.
Raises:
AttributeError: if the setting is missing and required.
ValueError: (or other Exception) if the raw value is invalid.
"""
super(NestedSetting, self).check()
errors... |
Sum an array of magnitudes in flux space.
Parameters:
-----------
mags : array of magnitudes
weights : array of weights for each magnitude (i.e. from a pdf)
Returns:
--------
sum_mag : the summed magnitude of all the stars | def sum_mags(mags, weights=None):
"""
Sum an array of magnitudes in flux space.
Parameters:
-----------
mags : array of magnitudes
weights : array of weights for each magnitude (i.e. from a pdf)
Returns:
--------
sum_mag : the summed magnitude of all the stars
"""
fl... |
Calculate the absolute magnitude from a set of bands | def absolute_magnitude(distance_modulus,g,r,prob=None):
""" Calculate the absolute magnitude from a set of bands """
V = g - 0.487*(g - r) - 0.0249
flux = np.sum(10**(-(V-distance_modulus)/2.5))
Mv = -2.5*np.log10(flux)
return Mv |
Sample the isochrone in steps of mass interpolating between
the originally defined isochrone points.
Parameters:
-----------
mode :
mass_steps :
mass_min : Minimum mass [Msun]
full_data_range :
Returns:
--------
mass_init : Init... | def sample(self, mode='data', mass_steps=1000, mass_min=0.1, full_data_range=False):
"""Sample the isochrone in steps of mass interpolating between
the originally defined isochrone points.
Parameters:
-----------
mode :
mass_steps :
mass_min : Minimum mass [Msu... |
Compute the stellar mass (Msun; average per star). PDF comes
from IMF, but weight by actual stellar mass.
Parameters:
-----------
mass_min : Minimum mass to integrate the IMF
steps : Number of steps to sample the isochrone
Returns:
--------
mass :... | def stellar_mass(self, mass_min=0.1, steps=10000):
"""
Compute the stellar mass (Msun; average per star). PDF comes
from IMF, but weight by actual stellar mass.
Parameters:
-----------
mass_min : Minimum mass to integrate the IMF
steps : Number of steps to sam... |
Compute the stellar luminosity (Lsun; average per star). PDF
comes from IMF. The range of integration only covers the
input isochrone data (no extrapolation used), but this seems
like a sub-percent effect if the isochrone goes to 0.15 Msun
for the old and metal-poor stellar populations ... | def stellar_luminosity(self, steps=10000):
"""
Compute the stellar luminosity (Lsun; average per star). PDF
comes from IMF. The range of integration only covers the
input isochrone data (no extrapolation used), but this seems
like a sub-percent effect if the isochrone goes to 0.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.