repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
castelao/oceansdb | oceansdb/woa.py | woa_track_from_file | def woa_track_from_file(d, lat, lon, filename, varnames=None):
""" Temporary solution: WOA for surface track
"""
d = np.asanyarray(d)
lat = np.asanyarray(lat)
lon = np.asanyarray(lon)
lon[lon < 0] += 360
doy = np.array([int(dd.strftime('%j')) for dd in d])
nc = netCDF4.Dataset(expanduser(filename), 'r')
if varnames is None:
varnames = {}
for v in nc.variables.keys():
if nc.variables[v].dimensions == \
(u'time', u'depth', u'lat', u'lon'):
varnames[v] = v
output = {}
for v in varnames:
output[v] = []
for d_n, lat_n, lon_n in zip(doy, lat, lon):
# Get the nearest point. In the future interpolate.
n_d = (np.abs(d_n - nc.variables['time'][:])).argmin()
n_x = (np.abs(lon_n - nc.variables['lon'][:])).argmin()
n_y = (np.abs(lat_n - nc.variables['lat'][:])).argmin()
for v in varnames:
output[v].append(nc.variables[varnames[v]][n_d, 0, n_y, n_x])
for v in varnames:
output[v] = ma.fix_invalid(output[v])
return output | python | def woa_track_from_file(d, lat, lon, filename, varnames=None):
""" Temporary solution: WOA for surface track
"""
d = np.asanyarray(d)
lat = np.asanyarray(lat)
lon = np.asanyarray(lon)
lon[lon < 0] += 360
doy = np.array([int(dd.strftime('%j')) for dd in d])
nc = netCDF4.Dataset(expanduser(filename), 'r')
if varnames is None:
varnames = {}
for v in nc.variables.keys():
if nc.variables[v].dimensions == \
(u'time', u'depth', u'lat', u'lon'):
varnames[v] = v
output = {}
for v in varnames:
output[v] = []
for d_n, lat_n, lon_n in zip(doy, lat, lon):
# Get the nearest point. In the future interpolate.
n_d = (np.abs(d_n - nc.variables['time'][:])).argmin()
n_x = (np.abs(lon_n - nc.variables['lon'][:])).argmin()
n_y = (np.abs(lat_n - nc.variables['lat'][:])).argmin()
for v in varnames:
output[v].append(nc.variables[varnames[v]][n_d, 0, n_y, n_x])
for v in varnames:
output[v] = ma.fix_invalid(output[v])
return output | [
"def",
"woa_track_from_file",
"(",
"d",
",",
"lat",
",",
"lon",
",",
"filename",
",",
"varnames",
"=",
"None",
")",
":",
"d",
"=",
"np",
".",
"asanyarray",
"(",
"d",
")",
"lat",
"=",
"np",
".",
"asanyarray",
"(",
"lat",
")",
"lon",
"=",
"np",
"."... | Temporary solution: WOA for surface track | [
"Temporary",
"solution",
":",
"WOA",
"for",
"surface",
"track"
] | train | https://github.com/castelao/oceansdb/blob/a154c5b845845a602800f9bc53d1702d4cb0f9c5/oceansdb/woa.py#L100-L136 |
castelao/oceansdb | oceansdb/woa.py | WOA_var_nc.crop | def crop(self, doy, depth, lat, lon, var):
""" Crop a subset of the dataset for each var
Given doy, depth, lat and lon, it returns the smallest subset
that still contains the requested coordinates inside it.
It handels special cases like a region around greenwich and
the international date line.
Accepts 0 to 360 and -180 to 180 longitude reference.
It extends time and longitude coordinates, so simplify the use
of series. For example, a ship track can be requested with
a longitude sequence like [352, 358, 364, 369, 380], and
the equivalent for day of year above 365.
"""
dims, idx = cropIndices(self.dims, lat, lon, depth, doy)
subset = {}
for v in var:
subset[v] = ma.asanyarray([
self.ncs[tnn][v][0, idx['zn'], idx['yn'], idx['xn']] \
for tnn in idx['tn']])
return subset, dims | python | def crop(self, doy, depth, lat, lon, var):
""" Crop a subset of the dataset for each var
Given doy, depth, lat and lon, it returns the smallest subset
that still contains the requested coordinates inside it.
It handels special cases like a region around greenwich and
the international date line.
Accepts 0 to 360 and -180 to 180 longitude reference.
It extends time and longitude coordinates, so simplify the use
of series. For example, a ship track can be requested with
a longitude sequence like [352, 358, 364, 369, 380], and
the equivalent for day of year above 365.
"""
dims, idx = cropIndices(self.dims, lat, lon, depth, doy)
subset = {}
for v in var:
subset[v] = ma.asanyarray([
self.ncs[tnn][v][0, idx['zn'], idx['yn'], idx['xn']] \
for tnn in idx['tn']])
return subset, dims | [
"def",
"crop",
"(",
"self",
",",
"doy",
",",
"depth",
",",
"lat",
",",
"lon",
",",
"var",
")",
":",
"dims",
",",
"idx",
"=",
"cropIndices",
"(",
"self",
".",
"dims",
",",
"lat",
",",
"lon",
",",
"depth",
",",
"doy",
")",
"subset",
"=",
"{",
"... | Crop a subset of the dataset for each var
Given doy, depth, lat and lon, it returns the smallest subset
that still contains the requested coordinates inside it.
It handels special cases like a region around greenwich and
the international date line.
Accepts 0 to 360 and -180 to 180 longitude reference.
It extends time and longitude coordinates, so simplify the use
of series. For example, a ship track can be requested with
a longitude sequence like [352, 358, 364, 369, 380], and
the equivalent for day of year above 365. | [
"Crop",
"a",
"subset",
"of",
"the",
"dataset",
"for",
"each",
"var"
] | train | https://github.com/castelao/oceansdb/blob/a154c5b845845a602800f9bc53d1702d4cb0f9c5/oceansdb/woa.py#L189-L211 |
castelao/oceansdb | oceansdb/woa.py | WOA_var_nc.interpolate | def interpolate(self, doy, depth, lat, lon, var):
""" Interpolate each var on the coordinates requested
"""
subset, dims = self.crop(doy, depth, lat, lon, var)
# Subset contains everything requested. No need to interpolate.
if np.all([d in dims['time'] for d in doy]) & \
np.all([z in dims['depth'] for z in depth]) & \
np.all([y in dims['lat'] for y in lat]) & \
np.all([x in dims['lon'] for x in lon]):
dn = np.nonzero([d in doy for d in dims['time']])[0]
zn = np.nonzero([z in depth for z in dims['depth']])[0]
yn = np.nonzero([y in lat for y in dims['lat']])[0]
xn = np.nonzero([x in lon for x in dims['lon']])[0]
output = {}
for v in subset:
# output[v] = subset[v][dn, zn, yn, xn]
# Seriously that this is the way to do it?!!??
output[v] = subset[v][:, :, :, xn][:, :, yn][:, zn][dn]
return output
output = {}
for v in var:
output[v] = ma.masked_all(
(doy.size, depth.size, lat.size, lon.size),
dtype=subset[v].dtype)
# These interpolators don't understand Masked Arrays, but do NaN
if subset[v].dtype in ['int32']:
subset[v] = subset[v].astype('f')
subset[v][ma.getmaskarray(subset[v])] = np.nan
subset[v] = subset[v].data
# First linear interpolate on time.
if not (doy == dims['time']).all():
for v in subset.keys():
f = interp1d(dims['time'], subset[v], axis=0)
subset[v] = f(doy)
dims['time'] = np.atleast_1d(doy)
if not (np.all(lat == dims['lat']) and np.all(lon == dims['lon'])):
# Lat x Lon target coordinates are the same for all time and depth.
points_out = []
for latn in lat:
for lonn in lon:
points_out.append([latn, lonn])
points_out = np.array(points_out)
# Interpolate on X/Y plane
for v in subset:
tmp = np.nan * np.ones(
(doy.size, dims['depth'].size, lat.size, lon.size),
dtype=subset[v].dtype)
for nt in range(doy.size):
for nz in range(dims['depth'].size):
data = subset[v][nt, nz]
# The valid data
idx = np.nonzero(~np.isnan(data))
if idx[0].size > 0:
points = np.array([
dims['lat'][idx[0]], dims['lon'][idx[1]]]).T
values = data[idx]
# Interpolate along the dimensions that have more than
# one position, otherwise it means that the output
# is exactly on that coordinate.
#ind = np.array([np.unique(points[:, i]).size > 1
# for i in range(points.shape[1])])
#assert ind.any()
try:
values_out = griddata(
#np.atleast_1d(np.squeeze(points[:, ind])),
np.atleast_1d(np.squeeze(points)),
values,
#np.atleast_1d(np.squeeze(points_out[:, ind])))
np.atleast_1d(np.squeeze(points_out)))
except:
values_out = []
for p in points_out:
try:
values_out.append(griddata(
np.atleast_1d(np.squeeze(points)),
values,
np.atleast_1d(np.squeeze(
p))))
except:
values_out.append(np.nan)
values_out = np.array(values_out)
# Remap the interpolated value back into a 4D array
idx = np.isfinite(values_out)
for [y, x], out in zip(
points_out[idx], values_out[idx]):
tmp[nt, nz, y==lat, x==lon] = out
subset[v] = tmp
# Interpolate on z
same_depth = (np.shape(depth) == dims['depth'].shape) and \
np.allclose(depth, dims['depth'])
if not same_depth:
for v in list(subset.keys()):
try:
f = interp1d(dims['depth'], subset[v], axis=1, bounds_error=False)
# interp1d does not handle Masked Arrays
subset[v] = f(np.array(depth))
except:
print("Fail to interpolate '%s' in depth" % v)
del(subset[v])
for v in subset:
if output[v].dtype in ['int32']:
subset[v] = np.round(subset[v])
output[v][:] = ma.fix_invalid(subset[v][:])
return output | python | def interpolate(self, doy, depth, lat, lon, var):
""" Interpolate each var on the coordinates requested
"""
subset, dims = self.crop(doy, depth, lat, lon, var)
# Subset contains everything requested. No need to interpolate.
if np.all([d in dims['time'] for d in doy]) & \
np.all([z in dims['depth'] for z in depth]) & \
np.all([y in dims['lat'] for y in lat]) & \
np.all([x in dims['lon'] for x in lon]):
dn = np.nonzero([d in doy for d in dims['time']])[0]
zn = np.nonzero([z in depth for z in dims['depth']])[0]
yn = np.nonzero([y in lat for y in dims['lat']])[0]
xn = np.nonzero([x in lon for x in dims['lon']])[0]
output = {}
for v in subset:
# output[v] = subset[v][dn, zn, yn, xn]
# Seriously that this is the way to do it?!!??
output[v] = subset[v][:, :, :, xn][:, :, yn][:, zn][dn]
return output
output = {}
for v in var:
output[v] = ma.masked_all(
(doy.size, depth.size, lat.size, lon.size),
dtype=subset[v].dtype)
# These interpolators don't understand Masked Arrays, but do NaN
if subset[v].dtype in ['int32']:
subset[v] = subset[v].astype('f')
subset[v][ma.getmaskarray(subset[v])] = np.nan
subset[v] = subset[v].data
# First linear interpolate on time.
if not (doy == dims['time']).all():
for v in subset.keys():
f = interp1d(dims['time'], subset[v], axis=0)
subset[v] = f(doy)
dims['time'] = np.atleast_1d(doy)
if not (np.all(lat == dims['lat']) and np.all(lon == dims['lon'])):
# Lat x Lon target coordinates are the same for all time and depth.
points_out = []
for latn in lat:
for lonn in lon:
points_out.append([latn, lonn])
points_out = np.array(points_out)
# Interpolate on X/Y plane
for v in subset:
tmp = np.nan * np.ones(
(doy.size, dims['depth'].size, lat.size, lon.size),
dtype=subset[v].dtype)
for nt in range(doy.size):
for nz in range(dims['depth'].size):
data = subset[v][nt, nz]
# The valid data
idx = np.nonzero(~np.isnan(data))
if idx[0].size > 0:
points = np.array([
dims['lat'][idx[0]], dims['lon'][idx[1]]]).T
values = data[idx]
# Interpolate along the dimensions that have more than
# one position, otherwise it means that the output
# is exactly on that coordinate.
#ind = np.array([np.unique(points[:, i]).size > 1
# for i in range(points.shape[1])])
#assert ind.any()
try:
values_out = griddata(
#np.atleast_1d(np.squeeze(points[:, ind])),
np.atleast_1d(np.squeeze(points)),
values,
#np.atleast_1d(np.squeeze(points_out[:, ind])))
np.atleast_1d(np.squeeze(points_out)))
except:
values_out = []
for p in points_out:
try:
values_out.append(griddata(
np.atleast_1d(np.squeeze(points)),
values,
np.atleast_1d(np.squeeze(
p))))
except:
values_out.append(np.nan)
values_out = np.array(values_out)
# Remap the interpolated value back into a 4D array
idx = np.isfinite(values_out)
for [y, x], out in zip(
points_out[idx], values_out[idx]):
tmp[nt, nz, y==lat, x==lon] = out
subset[v] = tmp
# Interpolate on z
same_depth = (np.shape(depth) == dims['depth'].shape) and \
np.allclose(depth, dims['depth'])
if not same_depth:
for v in list(subset.keys()):
try:
f = interp1d(dims['depth'], subset[v], axis=1, bounds_error=False)
# interp1d does not handle Masked Arrays
subset[v] = f(np.array(depth))
except:
print("Fail to interpolate '%s' in depth" % v)
del(subset[v])
for v in subset:
if output[v].dtype in ['int32']:
subset[v] = np.round(subset[v])
output[v][:] = ma.fix_invalid(subset[v][:])
return output | [
"def",
"interpolate",
"(",
"self",
",",
"doy",
",",
"depth",
",",
"lat",
",",
"lon",
",",
"var",
")",
":",
"subset",
",",
"dims",
"=",
"self",
".",
"crop",
"(",
"doy",
",",
"depth",
",",
"lat",
",",
"lon",
",",
"var",
")",
"# Subset contains everyt... | Interpolate each var on the coordinates requested | [
"Interpolate",
"each",
"var",
"on",
"the",
"coordinates",
"requested"
] | train | https://github.com/castelao/oceansdb/blob/a154c5b845845a602800f9bc53d1702d4cb0f9c5/oceansdb/woa.py#L232-L347 |
zagaran/mongolia | mongolia/database_collection.py | DatabaseCollection.count | def count(cls, path=None, objtype=None, query=None, **kwargs):
"""
Like __init__, but simply returns the number of objects that match the
query rather than returning the objects
NOTE: The path and objtype parameters to this function are to allow
use of the DatabaseCollection class directly. However, this class is
intended for subclassing and children of it should override either the
OBJTYPE or PATH attribute rather than passing them as parameters here.
@param path: the path of the database to query, in the form
"database.colletion"; pass None to use the value of the
PATH property of the object or, if that is none, the
PATH property of OBJTYPE
@param objtype: the object type to use for these DatabaseObjects;
pass None to use the OBJTYPE property of the class
@param query: a dictionary specifying key-value pairs that the result
must match. If query is None, use kwargs in it's place
@param **kwargs: used as query parameters if query is None
@raise Exception: if path, PATH, and OBJTYPE.PATH are all None;
the database path must be defined in at least one of these
"""
if not objtype:
objtype = cls.OBJTYPE
if not path:
path = cls.PATH
if not query:
query = kwargs
return objtype.db(path).find(query).count() | python | def count(cls, path=None, objtype=None, query=None, **kwargs):
"""
Like __init__, but simply returns the number of objects that match the
query rather than returning the objects
NOTE: The path and objtype parameters to this function are to allow
use of the DatabaseCollection class directly. However, this class is
intended for subclassing and children of it should override either the
OBJTYPE or PATH attribute rather than passing them as parameters here.
@param path: the path of the database to query, in the form
"database.colletion"; pass None to use the value of the
PATH property of the object or, if that is none, the
PATH property of OBJTYPE
@param objtype: the object type to use for these DatabaseObjects;
pass None to use the OBJTYPE property of the class
@param query: a dictionary specifying key-value pairs that the result
must match. If query is None, use kwargs in it's place
@param **kwargs: used as query parameters if query is None
@raise Exception: if path, PATH, and OBJTYPE.PATH are all None;
the database path must be defined in at least one of these
"""
if not objtype:
objtype = cls.OBJTYPE
if not path:
path = cls.PATH
if not query:
query = kwargs
return objtype.db(path).find(query).count() | [
"def",
"count",
"(",
"cls",
",",
"path",
"=",
"None",
",",
"objtype",
"=",
"None",
",",
"query",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"objtype",
":",
"objtype",
"=",
"cls",
".",
"OBJTYPE",
"if",
"not",
"path",
":",
"path",... | Like __init__, but simply returns the number of objects that match the
query rather than returning the objects
NOTE: The path and objtype parameters to this function are to allow
use of the DatabaseCollection class directly. However, this class is
intended for subclassing and children of it should override either the
OBJTYPE or PATH attribute rather than passing them as parameters here.
@param path: the path of the database to query, in the form
"database.colletion"; pass None to use the value of the
PATH property of the object or, if that is none, the
PATH property of OBJTYPE
@param objtype: the object type to use for these DatabaseObjects;
pass None to use the OBJTYPE property of the class
@param query: a dictionary specifying key-value pairs that the result
must match. If query is None, use kwargs in it's place
@param **kwargs: used as query parameters if query is None
@raise Exception: if path, PATH, and OBJTYPE.PATH are all None;
the database path must be defined in at least one of these | [
"Like",
"__init__",
"but",
"simply",
"returns",
"the",
"number",
"of",
"objects",
"that",
"match",
"the",
"query",
"rather",
"than",
"returning",
"the",
"objects",
"NOTE",
":",
"The",
"path",
"and",
"objtype",
"parameters",
"to",
"this",
"function",
"are",
"... | train | https://github.com/zagaran/mongolia/blob/82c499345f0a8610c7289545e19f5f633e8a81c0/mongolia/database_collection.py#L164-L193 |
zagaran/mongolia | mongolia/database_collection.py | DatabaseCollection.iterator | def iterator(cls, path=None, objtype=None, query=None, page_size=1000, **kwargs):
""""
Linear time, constant memory, iterator for a mongo collection.
@param path: the path of the database to query, in the form
"database.colletion"; pass None to use the value of the
PATH property of the object or, if that is none, the
PATH property of OBJTYPE
@param objtype: the object type to use for these DatabaseObjects;
pass None to use the OBJTYPE property of the class
@param query: a dictionary specifying key-value pairs that the result
must match. If query is None, use kwargs in it's place
@param page_size: the number of items to fetch per page of iteration
@param **kwargs: used as query parameters if query is None
"""
if not objtype:
objtype = cls.OBJTYPE
if not path:
path = cls.PATH
db = objtype.db(path)
if not query:
query = kwargs
results = list(db.find(query).sort(ID_KEY, ASCENDING).limit(page_size))
while results:
page = [objtype(path=path, _new_object=result) for result in results]
for obj in page:
yield obj
query[ID_KEY] = {GT: results[-1][ID_KEY]}
results = list(db.find(query).sort(ID_KEY, ASCENDING).limit(page_size)) | python | def iterator(cls, path=None, objtype=None, query=None, page_size=1000, **kwargs):
""""
Linear time, constant memory, iterator for a mongo collection.
@param path: the path of the database to query, in the form
"database.colletion"; pass None to use the value of the
PATH property of the object or, if that is none, the
PATH property of OBJTYPE
@param objtype: the object type to use for these DatabaseObjects;
pass None to use the OBJTYPE property of the class
@param query: a dictionary specifying key-value pairs that the result
must match. If query is None, use kwargs in it's place
@param page_size: the number of items to fetch per page of iteration
@param **kwargs: used as query parameters if query is None
"""
if not objtype:
objtype = cls.OBJTYPE
if not path:
path = cls.PATH
db = objtype.db(path)
if not query:
query = kwargs
results = list(db.find(query).sort(ID_KEY, ASCENDING).limit(page_size))
while results:
page = [objtype(path=path, _new_object=result) for result in results]
for obj in page:
yield obj
query[ID_KEY] = {GT: results[-1][ID_KEY]}
results = list(db.find(query).sort(ID_KEY, ASCENDING).limit(page_size)) | [
"def",
"iterator",
"(",
"cls",
",",
"path",
"=",
"None",
",",
"objtype",
"=",
"None",
",",
"query",
"=",
"None",
",",
"page_size",
"=",
"1000",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"objtype",
":",
"objtype",
"=",
"cls",
".",
"OBJTYPE",
... | Linear time, constant memory, iterator for a mongo collection.
@param path: the path of the database to query, in the form
"database.colletion"; pass None to use the value of the
PATH property of the object or, if that is none, the
PATH property of OBJTYPE
@param objtype: the object type to use for these DatabaseObjects;
pass None to use the OBJTYPE property of the class
@param query: a dictionary specifying key-value pairs that the result
must match. If query is None, use kwargs in it's place
@param page_size: the number of items to fetch per page of iteration
@param **kwargs: used as query parameters if query is None | [
"Linear",
"time",
"constant",
"memory",
"iterator",
"for",
"a",
"mongo",
"collection",
"."
] | train | https://github.com/zagaran/mongolia/blob/82c499345f0a8610c7289545e19f5f633e8a81c0/mongolia/database_collection.py#L211-L239 |
zagaran/mongolia | mongolia/database_collection.py | DatabaseCollection.insert | def insert(self, data, **kwargs):
"""
Calls the create method of OBJTYPE
NOTE: this function is only properly usable on children classes that
have overridden either OBJTYPE or PATH.
@param data: the data of the new object to be created
@param **kwargs: forwarded to create
@raise DatabaseConflictError: if there is already an object with that
ID_KEY and overwrite == False
@raise MalformedObjectError: if a REQUIRED key of defaults is missing,
or if the ID_KEY of the object is None and random_id is False
"""
obj = self.OBJTYPE.create(data, path=self.PATH, **kwargs)
self.append(obj)
return obj | python | def insert(self, data, **kwargs):
"""
Calls the create method of OBJTYPE
NOTE: this function is only properly usable on children classes that
have overridden either OBJTYPE or PATH.
@param data: the data of the new object to be created
@param **kwargs: forwarded to create
@raise DatabaseConflictError: if there is already an object with that
ID_KEY and overwrite == False
@raise MalformedObjectError: if a REQUIRED key of defaults is missing,
or if the ID_KEY of the object is None and random_id is False
"""
obj = self.OBJTYPE.create(data, path=self.PATH, **kwargs)
self.append(obj)
return obj | [
"def",
"insert",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"self",
".",
"OBJTYPE",
".",
"create",
"(",
"data",
",",
"path",
"=",
"self",
".",
"PATH",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"append",
"(",
"obj"... | Calls the create method of OBJTYPE
NOTE: this function is only properly usable on children classes that
have overridden either OBJTYPE or PATH.
@param data: the data of the new object to be created
@param **kwargs: forwarded to create
@raise DatabaseConflictError: if there is already an object with that
ID_KEY and overwrite == False
@raise MalformedObjectError: if a REQUIRED key of defaults is missing,
or if the ID_KEY of the object is None and random_id is False | [
"Calls",
"the",
"create",
"method",
"of",
"OBJTYPE",
"NOTE",
":",
"this",
"function",
"is",
"only",
"properly",
"usable",
"on",
"children",
"classes",
"that",
"have",
"overridden",
"either",
"OBJTYPE",
"or",
"PATH",
"."
] | train | https://github.com/zagaran/mongolia/blob/82c499345f0a8610c7289545e19f5f633e8a81c0/mongolia/database_collection.py#L252-L269 |
zagaran/mongolia | mongolia/database_collection.py | DatabaseCollection._move | def _move(self, new_path):
"""
Moves the collection to a different database path
NOTE: this function is intended for command prompt use only.
WARNING: if execution is interrupted halfway through, the collection will
be split into multiple pieces. Furthermore, there is a possible
duplication of the database object being processed at the time of
interruption.
@param new_path: the new place for the collection to live, in the format
"database.collection"
"""
for elt in self:
DatabaseObject.create(elt, path=new_path)
for elt in self:
elt._collection.remove({ID_KEY: elt[ID_KEY]}) | python | def _move(self, new_path):
"""
Moves the collection to a different database path
NOTE: this function is intended for command prompt use only.
WARNING: if execution is interrupted halfway through, the collection will
be split into multiple pieces. Furthermore, there is a possible
duplication of the database object being processed at the time of
interruption.
@param new_path: the new place for the collection to live, in the format
"database.collection"
"""
for elt in self:
DatabaseObject.create(elt, path=new_path)
for elt in self:
elt._collection.remove({ID_KEY: elt[ID_KEY]}) | [
"def",
"_move",
"(",
"self",
",",
"new_path",
")",
":",
"for",
"elt",
"in",
"self",
":",
"DatabaseObject",
".",
"create",
"(",
"elt",
",",
"path",
"=",
"new_path",
")",
"for",
"elt",
"in",
"self",
":",
"elt",
".",
"_collection",
".",
"remove",
"(",
... | Moves the collection to a different database path
NOTE: this function is intended for command prompt use only.
WARNING: if execution is interrupted halfway through, the collection will
be split into multiple pieces. Furthermore, there is a possible
duplication of the database object being processed at the time of
interruption.
@param new_path: the new place for the collection to live, in the format
"database.collection" | [
"Moves",
"the",
"collection",
"to",
"a",
"different",
"database",
"path",
"NOTE",
":",
"this",
"function",
"is",
"intended",
"for",
"command",
"prompt",
"use",
"only",
".",
"WARNING",
":",
"if",
"execution",
"is",
"interrupted",
"halfway",
"through",
"the",
... | train | https://github.com/zagaran/mongolia/blob/82c499345f0a8610c7289545e19f5f633e8a81c0/mongolia/database_collection.py#L281-L298 |
biocore/burrito-fillings | bfillings/align.py | pair_hmm_align_unaligned_seqs | def pair_hmm_align_unaligned_seqs(seqs, moltype=DNA_cogent, params={}):
"""
Checks parameters for pairwise alignment, returns alignment.
Code from Greg Caporaso.
"""
seqs = LoadSeqs(data=seqs, moltype=moltype, aligned=False)
try:
s1, s2 = seqs.values()
except ValueError:
raise ValueError(
"Pairwise aligning of seqs requires exactly two seqs.")
try:
gap_open = params['gap_open']
except KeyError:
gap_open = 5
try:
gap_extend = params['gap_extend']
except KeyError:
gap_extend = 2
try:
score_matrix = params['score_matrix']
except KeyError:
score_matrix = make_dna_scoring_dict(
match=1, transition=-1, transversion=-1)
return local_pairwise(s1, s2, score_matrix, gap_open, gap_extend) | python | def pair_hmm_align_unaligned_seqs(seqs, moltype=DNA_cogent, params={}):
"""
Checks parameters for pairwise alignment, returns alignment.
Code from Greg Caporaso.
"""
seqs = LoadSeqs(data=seqs, moltype=moltype, aligned=False)
try:
s1, s2 = seqs.values()
except ValueError:
raise ValueError(
"Pairwise aligning of seqs requires exactly two seqs.")
try:
gap_open = params['gap_open']
except KeyError:
gap_open = 5
try:
gap_extend = params['gap_extend']
except KeyError:
gap_extend = 2
try:
score_matrix = params['score_matrix']
except KeyError:
score_matrix = make_dna_scoring_dict(
match=1, transition=-1, transversion=-1)
return local_pairwise(s1, s2, score_matrix, gap_open, gap_extend) | [
"def",
"pair_hmm_align_unaligned_seqs",
"(",
"seqs",
",",
"moltype",
"=",
"DNA_cogent",
",",
"params",
"=",
"{",
"}",
")",
":",
"seqs",
"=",
"LoadSeqs",
"(",
"data",
"=",
"seqs",
",",
"moltype",
"=",
"moltype",
",",
"aligned",
"=",
"False",
")",
"try",
... | Checks parameters for pairwise alignment, returns alignment.
Code from Greg Caporaso. | [
"Checks",
"parameters",
"for",
"pairwise",
"alignment",
"returns",
"alignment",
"."
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/align.py#L12-L40 |
michaelpb/omnic | omnic/builtin/services/viewer/views.py | viewers_js | async def viewers_js(request):
'''
Viewers determines the viewers installed based on settings, then uses the
conversion infrastructure to convert all these JS files into a single JS
bundle, that is then served. As with media, it will simply serve a cached
version if necessary.
'''
# Generates single bundle as such:
# BytesResource -> ViewerNodePackageBuilder -> nodepackage -> ... -> min.js
response = singletons.server.response
# Create a viewers resource, which is simply a JSON encoded description of
# the viewers necessary for this viewers bundle.
viewers_resource = singletons.viewers.get_resource()
url_string = viewers_resource.url_string
target_ts = TypeString('min.js') # get a minified JS bundle
target_resource = TypedResource(url_string, target_ts)
if target_resource.cache_exists():
return await response.file(target_resource.cache_path, headers={
'Content-Type': 'application/javascript',
})
# Otherwise, does not exist, save this descriptor to cache and kick off
# conversion process
if not viewers_resource.cache_exists():
viewers_resource.save()
# Queue up a single function that will in turn queue up conversion process
await singletons.workers.async_enqueue_sync(
enqueue_conversion_path,
url_string,
str(target_ts),
singletons.workers.enqueue_convert
)
return response.text(NOT_LOADED_JS, headers={
'Content-Type': 'application/javascript',
}) | python | async def viewers_js(request):
'''
Viewers determines the viewers installed based on settings, then uses the
conversion infrastructure to convert all these JS files into a single JS
bundle, that is then served. As with media, it will simply serve a cached
version if necessary.
'''
# Generates single bundle as such:
# BytesResource -> ViewerNodePackageBuilder -> nodepackage -> ... -> min.js
response = singletons.server.response
# Create a viewers resource, which is simply a JSON encoded description of
# the viewers necessary for this viewers bundle.
viewers_resource = singletons.viewers.get_resource()
url_string = viewers_resource.url_string
target_ts = TypeString('min.js') # get a minified JS bundle
target_resource = TypedResource(url_string, target_ts)
if target_resource.cache_exists():
return await response.file(target_resource.cache_path, headers={
'Content-Type': 'application/javascript',
})
# Otherwise, does not exist, save this descriptor to cache and kick off
# conversion process
if not viewers_resource.cache_exists():
viewers_resource.save()
# Queue up a single function that will in turn queue up conversion process
await singletons.workers.async_enqueue_sync(
enqueue_conversion_path,
url_string,
str(target_ts),
singletons.workers.enqueue_convert
)
return response.text(NOT_LOADED_JS, headers={
'Content-Type': 'application/javascript',
}) | [
"async",
"def",
"viewers_js",
"(",
"request",
")",
":",
"# Generates single bundle as such:",
"# BytesResource -> ViewerNodePackageBuilder -> nodepackage -> ... -> min.js",
"response",
"=",
"singletons",
".",
"server",
".",
"response",
"# Create a viewers resource, which is simply a ... | Viewers determines the viewers installed based on settings, then uses the
conversion infrastructure to convert all these JS files into a single JS
bundle, that is then served. As with media, it will simply serve a cached
version if necessary. | [
"Viewers",
"determines",
"the",
"viewers",
"installed",
"based",
"on",
"settings",
"then",
"uses",
"the",
"conversion",
"infrastructure",
"to",
"convert",
"all",
"these",
"JS",
"files",
"into",
"a",
"single",
"JS",
"bundle",
"that",
"is",
"then",
"served",
"."... | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/builtin/services/viewer/views.py#L18-L57 |
biocore/burrito-fillings | bfillings/fasttree.py | build_tree_from_alignment | def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None):
"""Returns a tree from alignment
Will check MolType of aln object
"""
if params is None:
params = {}
if moltype == DNA or moltype == RNA:
params['-nt'] = True
elif moltype == PROTEIN:
params['-nt'] = False
else:
raise ValueError, \
"FastTree does not support moltype: %s" % moltype.label
if best_tree:
params['-slow'] = True
#Create mapping between abbreviated IDs and full IDs
int_map, int_keys = aln.getIntMap()
#Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map,MolType=moltype)
app = FastTree(params=params)
result = app(int_map.toFasta())
tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
#remap tip names
for tip in tree.tips():
tip.Name = int_keys[tip.Name]
return tree | python | def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None):
"""Returns a tree from alignment
Will check MolType of aln object
"""
if params is None:
params = {}
if moltype == DNA or moltype == RNA:
params['-nt'] = True
elif moltype == PROTEIN:
params['-nt'] = False
else:
raise ValueError, \
"FastTree does not support moltype: %s" % moltype.label
if best_tree:
params['-slow'] = True
#Create mapping between abbreviated IDs and full IDs
int_map, int_keys = aln.getIntMap()
#Create SequenceCollection from int_map.
int_map = SequenceCollection(int_map,MolType=moltype)
app = FastTree(params=params)
result = app(int_map.toFasta())
tree = DndParser(result['Tree'].read(), constructor=PhyloNode)
#remap tip names
for tip in tree.tips():
tip.Name = int_keys[tip.Name]
return tree | [
"def",
"build_tree_from_alignment",
"(",
"aln",
",",
"moltype",
"=",
"DNA",
",",
"best_tree",
"=",
"False",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"if",
"moltype",
"==",
"DNA",
"or",
"moltype",... | Returns a tree from alignment
Will check MolType of aln object | [
"Returns",
"a",
"tree",
"from",
"alignment"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/fasttree.py#L130-L162 |
kejbaly2/metrique | metrique/cubes/csvdata/rows.py | Rows.get_objects | def get_objects(self, uri, _oid=None, _start=None, _end=None,
load_kwargs=None, **kwargs):
'''
Load and transform csv data into a list of dictionaries.
Each row in the csv will result in one dictionary in the list.
:param uri: uri (file://, http(s)://) of csv file to load
:param _oid:
column or func to apply to map _oid in all resulting objects
:param _start:
column or func to apply to map _start in all resulting objects
:param _end:
column or func to apply to map _end in all resulting objects
:param kwargs: kwargs to pass to pandas.read_csv method
_start and _oid arguments can be a column name or a function
which accepts a single argument -- the row being extracted.
If either is a column name (string) then that column will be applied
as _oid for each object generated.
If either is a function, the function will be applied per each row
and the result of the function will be assigned to the _start
or _oid, respectively.
'''
load_kwargs = load_kwargs or {}
objects = load(path=uri, filetype='csv', **load_kwargs)
k = itertools.count(1)
now = utcnow()
__oid = lambda o: k.next()
_oid = _oid or __oid
_start = _start or now
_end = _end or None
def is_callable(v):
_v = type(v)
_ = True if _v is type or hasattr(v, '__call__') else False
return _
for obj in objects:
obj['_oid'] = _oid(obj) if is_callable(_oid) else _oid
obj['_start'] = _start(obj) if is_callable(_start) else _start
obj['_end'] = _end(obj) if is_callable(_end) else _end
self.container.add(obj)
return super(Rows, self).get_objects(**kwargs) | python | def get_objects(self, uri, _oid=None, _start=None, _end=None,
load_kwargs=None, **kwargs):
'''
Load and transform csv data into a list of dictionaries.
Each row in the csv will result in one dictionary in the list.
:param uri: uri (file://, http(s)://) of csv file to load
:param _oid:
column or func to apply to map _oid in all resulting objects
:param _start:
column or func to apply to map _start in all resulting objects
:param _end:
column or func to apply to map _end in all resulting objects
:param kwargs: kwargs to pass to pandas.read_csv method
_start and _oid arguments can be a column name or a function
which accepts a single argument -- the row being extracted.
If either is a column name (string) then that column will be applied
as _oid for each object generated.
If either is a function, the function will be applied per each row
and the result of the function will be assigned to the _start
or _oid, respectively.
'''
load_kwargs = load_kwargs or {}
objects = load(path=uri, filetype='csv', **load_kwargs)
k = itertools.count(1)
now = utcnow()
__oid = lambda o: k.next()
_oid = _oid or __oid
_start = _start or now
_end = _end or None
def is_callable(v):
_v = type(v)
_ = True if _v is type or hasattr(v, '__call__') else False
return _
for obj in objects:
obj['_oid'] = _oid(obj) if is_callable(_oid) else _oid
obj['_start'] = _start(obj) if is_callable(_start) else _start
obj['_end'] = _end(obj) if is_callable(_end) else _end
self.container.add(obj)
return super(Rows, self).get_objects(**kwargs) | [
"def",
"get_objects",
"(",
"self",
",",
"uri",
",",
"_oid",
"=",
"None",
",",
"_start",
"=",
"None",
",",
"_end",
"=",
"None",
",",
"load_kwargs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"load_kwargs",
"=",
"load_kwargs",
"or",
"{",
"}",
"o... | Load and transform csv data into a list of dictionaries.
Each row in the csv will result in one dictionary in the list.
:param uri: uri (file://, http(s)://) of csv file to load
:param _oid:
column or func to apply to map _oid in all resulting objects
:param _start:
column or func to apply to map _start in all resulting objects
:param _end:
column or func to apply to map _end in all resulting objects
:param kwargs: kwargs to pass to pandas.read_csv method
_start and _oid arguments can be a column name or a function
which accepts a single argument -- the row being extracted.
If either is a column name (string) then that column will be applied
as _oid for each object generated.
If either is a function, the function will be applied per each row
and the result of the function will be assigned to the _start
or _oid, respectively. | [
"Load",
"and",
"transform",
"csv",
"data",
"into",
"a",
"list",
"of",
"dictionaries",
"."
] | train | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/cubes/csvdata/rows.py#L38-L86 |
mickybart/python-atlasapi | atlasapi/specs.py | DatabaseUsersPermissionsSpecs.getSpecs | def getSpecs(self):
"""Get specs
Returns:
dict: Representation of the object
"""
content = {
"databaseName" : self.databaseName,
"roles" : self.roles,
"username" : self.username,
"password" : self.password
}
return content | python | def getSpecs(self):
"""Get specs
Returns:
dict: Representation of the object
"""
content = {
"databaseName" : self.databaseName,
"roles" : self.roles,
"username" : self.username,
"password" : self.password
}
return content | [
"def",
"getSpecs",
"(",
"self",
")",
":",
"content",
"=",
"{",
"\"databaseName\"",
":",
"self",
".",
"databaseName",
",",
"\"roles\"",
":",
"self",
".",
"roles",
",",
"\"username\"",
":",
"self",
".",
"username",
",",
"\"password\"",
":",
"self",
".",
"p... | Get specs
Returns:
dict: Representation of the object | [
"Get",
"specs",
"Returns",
":",
"dict",
":",
"Representation",
"of",
"the",
"object"
] | train | https://github.com/mickybart/python-atlasapi/blob/2962c37740998694cb55f82b375b81cc604b953e/atlasapi/specs.py#L55-L68 |
mickybart/python-atlasapi | atlasapi/specs.py | DatabaseUsersPermissionsSpecs.add_roles | def add_roles(self, databaseName, roleNames, collectionName=None):
"""Add multiple roles
Args:
databaseName (str): Database Name
roleNames (list of RoleSpecs): roles
Keyword Args:
collectionName (str): Collection
Raises:
ErrRoleException: role not compatible with the databaseName and/or collectionName
"""
for roleName in roleNames:
self.add_role(databaseName, roleName, collectionName) | python | def add_roles(self, databaseName, roleNames, collectionName=None):
"""Add multiple roles
Args:
databaseName (str): Database Name
roleNames (list of RoleSpecs): roles
Keyword Args:
collectionName (str): Collection
Raises:
ErrRoleException: role not compatible with the databaseName and/or collectionName
"""
for roleName in roleNames:
self.add_role(databaseName, roleName, collectionName) | [
"def",
"add_roles",
"(",
"self",
",",
"databaseName",
",",
"roleNames",
",",
"collectionName",
"=",
"None",
")",
":",
"for",
"roleName",
"in",
"roleNames",
":",
"self",
".",
"add_role",
"(",
"databaseName",
",",
"roleName",
",",
"collectionName",
")"
] | Add multiple roles
Args:
databaseName (str): Database Name
roleNames (list of RoleSpecs): roles
Keyword Args:
collectionName (str): Collection
Raises:
ErrRoleException: role not compatible with the databaseName and/or collectionName | [
"Add",
"multiple",
"roles",
"Args",
":",
"databaseName",
"(",
"str",
")",
":",
"Database",
"Name",
"roleNames",
"(",
"list",
"of",
"RoleSpecs",
")",
":",
"roles",
"Keyword",
"Args",
":",
"collectionName",
"(",
"str",
")",
":",
"Collection",
"Raises",
":",
... | train | https://github.com/mickybart/python-atlasapi/blob/2962c37740998694cb55f82b375b81cc604b953e/atlasapi/specs.py#L70-L84 |
mickybart/python-atlasapi | atlasapi/specs.py | DatabaseUsersPermissionsSpecs.add_role | def add_role(self, databaseName, roleName, collectionName=None):
"""Add one role
Args:
databaseName (str): Database Name
roleName (RoleSpecs): role
Keyword Args:
collectionName (str): Collection
Raises:
ErrRole: role not compatible with the databaseName and/or collectionName
"""
role = {"databaseName" : databaseName,
"roleName" : roleName}
if collectionName:
role["collectionName"] = collectionName
# Check atlas constraints
if collectionName and roleName not in [RoleSpecs.read, RoleSpecs.readWrite]:
raise ErrRole("Permissions [%s] not available for a collection" % roleName)
elif not collectionName and roleName not in [RoleSpecs.read, RoleSpecs.readWrite, RoleSpecs.dbAdmin] and databaseName != "admin":
raise ErrRole("Permissions [%s] is only available for admin database" % roleName)
if role not in self.roles:
self.roles.append(role) | python | def add_role(self, databaseName, roleName, collectionName=None):
"""Add one role
Args:
databaseName (str): Database Name
roleName (RoleSpecs): role
Keyword Args:
collectionName (str): Collection
Raises:
ErrRole: role not compatible with the databaseName and/or collectionName
"""
role = {"databaseName" : databaseName,
"roleName" : roleName}
if collectionName:
role["collectionName"] = collectionName
# Check atlas constraints
if collectionName and roleName not in [RoleSpecs.read, RoleSpecs.readWrite]:
raise ErrRole("Permissions [%s] not available for a collection" % roleName)
elif not collectionName and roleName not in [RoleSpecs.read, RoleSpecs.readWrite, RoleSpecs.dbAdmin] and databaseName != "admin":
raise ErrRole("Permissions [%s] is only available for admin database" % roleName)
if role not in self.roles:
self.roles.append(role) | [
"def",
"add_role",
"(",
"self",
",",
"databaseName",
",",
"roleName",
",",
"collectionName",
"=",
"None",
")",
":",
"role",
"=",
"{",
"\"databaseName\"",
":",
"databaseName",
",",
"\"roleName\"",
":",
"roleName",
"}",
"if",
"collectionName",
":",
"role",
"["... | Add one role
Args:
databaseName (str): Database Name
roleName (RoleSpecs): role
Keyword Args:
collectionName (str): Collection
Raises:
ErrRole: role not compatible with the databaseName and/or collectionName | [
"Add",
"one",
"role",
"Args",
":",
"databaseName",
"(",
"str",
")",
":",
"Database",
"Name",
"roleName",
"(",
"RoleSpecs",
")",
":",
"role",
"Keyword",
"Args",
":",
"collectionName",
"(",
"str",
")",
":",
"Collection",
"Raises",
":",
"ErrRole",
":",
"rol... | train | https://github.com/mickybart/python-atlasapi/blob/2962c37740998694cb55f82b375b81cc604b953e/atlasapi/specs.py#L86-L112 |
mickybart/python-atlasapi | atlasapi/specs.py | DatabaseUsersPermissionsSpecs.remove_roles | def remove_roles(self, databaseName, roleNames, collectionName=None):
"""Remove multiple roles
Args:
databaseName (str): Database Name
roleNames (list of RoleSpecs): roles
Keyword Args:
collectionName (str): Collection
"""
for roleName in roleNames:
self.remove_role(databaseName, roleName, collectionName) | python | def remove_roles(self, databaseName, roleNames, collectionName=None):
"""Remove multiple roles
Args:
databaseName (str): Database Name
roleNames (list of RoleSpecs): roles
Keyword Args:
collectionName (str): Collection
"""
for roleName in roleNames:
self.remove_role(databaseName, roleName, collectionName) | [
"def",
"remove_roles",
"(",
"self",
",",
"databaseName",
",",
"roleNames",
",",
"collectionName",
"=",
"None",
")",
":",
"for",
"roleName",
"in",
"roleNames",
":",
"self",
".",
"remove_role",
"(",
"databaseName",
",",
"roleName",
",",
"collectionName",
")"
] | Remove multiple roles
Args:
databaseName (str): Database Name
roleNames (list of RoleSpecs): roles
Keyword Args:
collectionName (str): Collection | [
"Remove",
"multiple",
"roles",
"Args",
":",
"databaseName",
"(",
"str",
")",
":",
"Database",
"Name",
"roleNames",
"(",
"list",
"of",
"RoleSpecs",
")",
":",
"roles",
"Keyword",
"Args",
":",
"collectionName",
"(",
"str",
")",
":",
"Collection"
] | train | https://github.com/mickybart/python-atlasapi/blob/2962c37740998694cb55f82b375b81cc604b953e/atlasapi/specs.py#L114-L125 |
mickybart/python-atlasapi | atlasapi/specs.py | DatabaseUsersPermissionsSpecs.remove_role | def remove_role(self, databaseName, roleName, collectionName=None):
"""Remove one role
Args:
databaseName (str): Database Name
roleName (RoleSpecs): role
Keyword Args:
collectionName (str): Collection
"""
role = {"databaseName" : databaseName,
"roleName" : roleName}
if collectionName:
role["collectionName"] = collectionName
if role in self.roles:
self.roles.remove(role) | python | def remove_role(self, databaseName, roleName, collectionName=None):
"""Remove one role
Args:
databaseName (str): Database Name
roleName (RoleSpecs): role
Keyword Args:
collectionName (str): Collection
"""
role = {"databaseName" : databaseName,
"roleName" : roleName}
if collectionName:
role["collectionName"] = collectionName
if role in self.roles:
self.roles.remove(role) | [
"def",
"remove_role",
"(",
"self",
",",
"databaseName",
",",
"roleName",
",",
"collectionName",
"=",
"None",
")",
":",
"role",
"=",
"{",
"\"databaseName\"",
":",
"databaseName",
",",
"\"roleName\"",
":",
"roleName",
"}",
"if",
"collectionName",
":",
"role",
... | Remove one role
Args:
databaseName (str): Database Name
roleName (RoleSpecs): role
Keyword Args:
collectionName (str): Collection | [
"Remove",
"one",
"role",
"Args",
":",
"databaseName",
"(",
"str",
")",
":",
"Database",
"Name",
"roleName",
"(",
"RoleSpecs",
")",
":",
"role",
"Keyword",
"Args",
":",
"collectionName",
"(",
"str",
")",
":",
"Collection"
] | train | https://github.com/mickybart/python-atlasapi/blob/2962c37740998694cb55f82b375b81cc604b953e/atlasapi/specs.py#L127-L144 |
mickybart/python-atlasapi | atlasapi/specs.py | DatabaseUsersUpdatePermissionsSpecs.getSpecs | def getSpecs(self):
"""Get specs
Returns:
dict: Representation of the object
"""
content = {}
if len(self.roles) != 0:
content["roles"] = self.roles
if self.password:
content["password"] = self.password
return content | python | def getSpecs(self):
"""Get specs
Returns:
dict: Representation of the object
"""
content = {}
if len(self.roles) != 0:
content["roles"] = self.roles
if self.password:
content["password"] = self.password
return content | [
"def",
"getSpecs",
"(",
"self",
")",
":",
"content",
"=",
"{",
"}",
"if",
"len",
"(",
"self",
".",
"roles",
")",
"!=",
"0",
":",
"content",
"[",
"\"roles\"",
"]",
"=",
"self",
".",
"roles",
"if",
"self",
".",
"password",
":",
"content",
"[",
"\"p... | Get specs
Returns:
dict: Representation of the object | [
"Get",
"specs",
"Returns",
":",
"dict",
":",
"Representation",
"of",
"the",
"object"
] | train | https://github.com/mickybart/python-atlasapi/blob/2962c37740998694cb55f82b375b81cc604b953e/atlasapi/specs.py#L160-L175 |
biocore/burrito-fillings | bfillings/sumaclust_v1.py | sumaclust_denovo_cluster | def sumaclust_denovo_cluster(seq_path=None,
result_path=None,
shortest_len=True,
similarity=0.97,
threads=1,
exact=False,
HALT_EXEC=False
):
""" Function : launch SumaClust de novo OTU picker
Parameters: seq_path, filepath to reads;
result_path, filepath to output OTU map;
shortest_len, boolean;
similarity, the similarity threshold (between (0,1]);
threads, number of threads to use;
exact, boolean to perform exact matching
Return : clusters, list of lists
"""
# Sequence path is mandatory
if (seq_path is None
or not exists(seq_path)):
raise ValueError("Error: FASTA query sequence filepath is "
"mandatory input.")
# Output directory is mandatory
if (result_path is None
or not isdir(dirname(realpath(result_path)))):
raise ValueError("Error: output directory is mandatory input.")
# Instantiate the object
sumaclust = Sumaclust(HALT_EXEC=HALT_EXEC)
# Set the OTU-map filepath
sumaclust.Parameters['-O'].on(result_path)
# Set the similarity threshold
if similarity is not None:
sumaclust.Parameters['-t'].on(similarity)
# Set the option to perform exact clustering (default: False)
if exact:
sumaclust.Parameters['-e'].on()
# Turn off option for reference sequence length to be the shortest
if not shortest_len:
sumaclust.Parameters['-l'].off()
# Set the number of threads
if threads > 0:
sumaclust.Parameters['-p'].on(threads)
else:
raise ValueError("Number of threads must be positive.")
# Launch SumaClust,
# set the data string to include the read filepath
# (to be passed as final arguments in the sumaclust command)
app_result = sumaclust(seq_path)
# Put clusters into a list of lists
f_otumap = app_result['OtuMap']
clusters = [line.strip().split('\t')[1:] for line in f_otumap]
# Return clusters
return clusters | python | def sumaclust_denovo_cluster(seq_path=None,
result_path=None,
shortest_len=True,
similarity=0.97,
threads=1,
exact=False,
HALT_EXEC=False
):
""" Function : launch SumaClust de novo OTU picker
Parameters: seq_path, filepath to reads;
result_path, filepath to output OTU map;
shortest_len, boolean;
similarity, the similarity threshold (between (0,1]);
threads, number of threads to use;
exact, boolean to perform exact matching
Return : clusters, list of lists
"""
# Sequence path is mandatory
if (seq_path is None
or not exists(seq_path)):
raise ValueError("Error: FASTA query sequence filepath is "
"mandatory input.")
# Output directory is mandatory
if (result_path is None
or not isdir(dirname(realpath(result_path)))):
raise ValueError("Error: output directory is mandatory input.")
# Instantiate the object
sumaclust = Sumaclust(HALT_EXEC=HALT_EXEC)
# Set the OTU-map filepath
sumaclust.Parameters['-O'].on(result_path)
# Set the similarity threshold
if similarity is not None:
sumaclust.Parameters['-t'].on(similarity)
# Set the option to perform exact clustering (default: False)
if exact:
sumaclust.Parameters['-e'].on()
# Turn off option for reference sequence length to be the shortest
if not shortest_len:
sumaclust.Parameters['-l'].off()
# Set the number of threads
if threads > 0:
sumaclust.Parameters['-p'].on(threads)
else:
raise ValueError("Number of threads must be positive.")
# Launch SumaClust,
# set the data string to include the read filepath
# (to be passed as final arguments in the sumaclust command)
app_result = sumaclust(seq_path)
# Put clusters into a list of lists
f_otumap = app_result['OtuMap']
clusters = [line.strip().split('\t')[1:] for line in f_otumap]
# Return clusters
return clusters | [
"def",
"sumaclust_denovo_cluster",
"(",
"seq_path",
"=",
"None",
",",
"result_path",
"=",
"None",
",",
"shortest_len",
"=",
"True",
",",
"similarity",
"=",
"0.97",
",",
"threads",
"=",
"1",
",",
"exact",
"=",
"False",
",",
"HALT_EXEC",
"=",
"False",
")",
... | Function : launch SumaClust de novo OTU picker
Parameters: seq_path, filepath to reads;
result_path, filepath to output OTU map;
shortest_len, boolean;
similarity, the similarity threshold (between (0,1]);
threads, number of threads to use;
exact, boolean to perform exact matching
Return : clusters, list of lists | [
"Function",
":",
"launch",
"SumaClust",
"de",
"novo",
"OTU",
"picker"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/sumaclust_v1.py#L108-L173 |
biocore/burrito-fillings | bfillings/sumaclust_v1.py | Sumaclust._get_result_paths | def _get_result_paths(self, data):
""" Set the result paths
"""
result = {}
# OTU map (mandatory output)
result['OtuMap'] = ResultPath(Path=self.Parameters['-O'].Value,
IsWritten=True)
# SumaClust will not produce any output file if the
# input file was empty, so we create an empty
# output file
if not isfile(result['OtuMap'].Path):
otumap_f = open(result['OtuMap'].Path, 'w')
otumap_f.close()
return result | python | def _get_result_paths(self, data):
""" Set the result paths
"""
result = {}
# OTU map (mandatory output)
result['OtuMap'] = ResultPath(Path=self.Parameters['-O'].Value,
IsWritten=True)
# SumaClust will not produce any output file if the
# input file was empty, so we create an empty
# output file
if not isfile(result['OtuMap'].Path):
otumap_f = open(result['OtuMap'].Path, 'w')
otumap_f.close()
return result | [
"def",
"_get_result_paths",
"(",
"self",
",",
"data",
")",
":",
"result",
"=",
"{",
"}",
"# OTU map (mandatory output)",
"result",
"[",
"'OtuMap'",
"]",
"=",
"ResultPath",
"(",
"Path",
"=",
"self",
".",
"Parameters",
"[",
"'-O'",
"]",
".",
"Value",
",",
... | Set the result paths | [
"Set",
"the",
"result",
"paths"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/sumaclust_v1.py#L71-L88 |
biocore/burrito-fillings | bfillings/vsearch.py | vsearch_dereplicate_exact_seqs | def vsearch_dereplicate_exact_seqs(
fasta_filepath,
output_filepath,
output_uc=False,
working_dir=None,
strand="both",
maxuniquesize=None,
minuniquesize=None,
sizein=False,
sizeout=True,
log_name="derep.log",
HALT_EXEC=False):
""" Generates clusters and fasta file of
dereplicated subsequences
Parameters
----------
fasta_filepath : string
input filepath of fasta file to be dereplicated
output_filepath : string
write the dereplicated sequences to output_filepath
working_dir : string, optional
directory path for storing intermediate output
output_uc : boolean, optional
uutput dereplication results in a file using a
uclust-like format
strand : string, optional
when searching for strictly identical sequences,
check the 'strand' only (default: both) or
check the plus strand only
maxuniquesize : integer, optional
discard sequences with an abundance value greater
than maxuniquesize
minuniquesize : integer, optional
discard sequences with an abundance value smaller
than integer
sizein : boolean, optional
take into account the abundance annotations present in
the input fasta file, (search for the pattern
"[>;]size=integer[;]" in sequence headers)
sizeout : boolean, optional
add abundance annotations to the output fasta file
(add the pattern ";size=integer;" to sequence headers)
log_name : string, optional
specifies log filename
HALT_EXEC : boolean, optional
used for debugging app controller
Return
------
output_filepath : string
filepath to dereplicated fasta file
uc_filepath : string
filepath to dereplication results in uclust-like format
log_filepath : string
filepath to log file
"""
# write all vsearch output files to same directory
# as output_filepath if working_dir is not specified
if not working_dir:
working_dir = dirname(abspath(output_filepath))
app = Vsearch(WorkingDir=working_dir, HALT_EXEC=HALT_EXEC)
log_filepath = join(working_dir, log_name)
uc_filepath = None
if output_uc:
root_name = splitext(abspath(output_filepath))[0]
uc_filepath = join(working_dir, '%s.uc' % root_name)
app.Parameters['--uc'].on(uc_filepath)
if maxuniquesize:
app.Parameters['--maxuniquesize'].on(maxuniquesize)
if minuniquesize:
app.Parameters['--minuniquesize'].on(minuniquesize)
if sizein:
app.Parameters['--sizein'].on()
if sizeout:
app.Parameters['--sizeout'].on()
if (strand == "both" or strand == "plus"):
app.Parameters['--strand'].on(strand)
else:
raise ValueError("Option --strand accepts only 'both'"
"or 'plus' values")
app.Parameters['--derep_fulllength'].on(fasta_filepath)
app.Parameters['--output'].on(output_filepath)
app.Parameters['--log'].on(log_filepath)
app_result = app()
return output_filepath, uc_filepath, log_filepath | python | def vsearch_dereplicate_exact_seqs(
fasta_filepath,
output_filepath,
output_uc=False,
working_dir=None,
strand="both",
maxuniquesize=None,
minuniquesize=None,
sizein=False,
sizeout=True,
log_name="derep.log",
HALT_EXEC=False):
""" Generates clusters and fasta file of
dereplicated subsequences
Parameters
----------
fasta_filepath : string
input filepath of fasta file to be dereplicated
output_filepath : string
write the dereplicated sequences to output_filepath
working_dir : string, optional
directory path for storing intermediate output
output_uc : boolean, optional
uutput dereplication results in a file using a
uclust-like format
strand : string, optional
when searching for strictly identical sequences,
check the 'strand' only (default: both) or
check the plus strand only
maxuniquesize : integer, optional
discard sequences with an abundance value greater
than maxuniquesize
minuniquesize : integer, optional
discard sequences with an abundance value smaller
than integer
sizein : boolean, optional
take into account the abundance annotations present in
the input fasta file, (search for the pattern
"[>;]size=integer[;]" in sequence headers)
sizeout : boolean, optional
add abundance annotations to the output fasta file
(add the pattern ";size=integer;" to sequence headers)
log_name : string, optional
specifies log filename
HALT_EXEC : boolean, optional
used for debugging app controller
Return
------
output_filepath : string
filepath to dereplicated fasta file
uc_filepath : string
filepath to dereplication results in uclust-like format
log_filepath : string
filepath to log file
"""
# write all vsearch output files to same directory
# as output_filepath if working_dir is not specified
if not working_dir:
working_dir = dirname(abspath(output_filepath))
app = Vsearch(WorkingDir=working_dir, HALT_EXEC=HALT_EXEC)
log_filepath = join(working_dir, log_name)
uc_filepath = None
if output_uc:
root_name = splitext(abspath(output_filepath))[0]
uc_filepath = join(working_dir, '%s.uc' % root_name)
app.Parameters['--uc'].on(uc_filepath)
if maxuniquesize:
app.Parameters['--maxuniquesize'].on(maxuniquesize)
if minuniquesize:
app.Parameters['--minuniquesize'].on(minuniquesize)
if sizein:
app.Parameters['--sizein'].on()
if sizeout:
app.Parameters['--sizeout'].on()
if (strand == "both" or strand == "plus"):
app.Parameters['--strand'].on(strand)
else:
raise ValueError("Option --strand accepts only 'both'"
"or 'plus' values")
app.Parameters['--derep_fulllength'].on(fasta_filepath)
app.Parameters['--output'].on(output_filepath)
app.Parameters['--log'].on(log_filepath)
app_result = app()
return output_filepath, uc_filepath, log_filepath | [
"def",
"vsearch_dereplicate_exact_seqs",
"(",
"fasta_filepath",
",",
"output_filepath",
",",
"output_uc",
"=",
"False",
",",
"working_dir",
"=",
"None",
",",
"strand",
"=",
"\"both\"",
",",
"maxuniquesize",
"=",
"None",
",",
"minuniquesize",
"=",
"None",
",",
"s... | Generates clusters and fasta file of
dereplicated subsequences
Parameters
----------
fasta_filepath : string
input filepath of fasta file to be dereplicated
output_filepath : string
write the dereplicated sequences to output_filepath
working_dir : string, optional
directory path for storing intermediate output
output_uc : boolean, optional
uutput dereplication results in a file using a
uclust-like format
strand : string, optional
when searching for strictly identical sequences,
check the 'strand' only (default: both) or
check the plus strand only
maxuniquesize : integer, optional
discard sequences with an abundance value greater
than maxuniquesize
minuniquesize : integer, optional
discard sequences with an abundance value smaller
than integer
sizein : boolean, optional
take into account the abundance annotations present in
the input fasta file, (search for the pattern
"[>;]size=integer[;]" in sequence headers)
sizeout : boolean, optional
add abundance annotations to the output fasta file
(add the pattern ";size=integer;" to sequence headers)
log_name : string, optional
specifies log filename
HALT_EXEC : boolean, optional
used for debugging app controller
Return
------
output_filepath : string
filepath to dereplicated fasta file
uc_filepath : string
filepath to dereplication results in uclust-like format
log_filepath : string
filepath to log file | [
"Generates",
"clusters",
"and",
"fasta",
"file",
"of",
"dereplicated",
"subsequences"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/vsearch.py#L225-L318 |
biocore/burrito-fillings | bfillings/vsearch.py | vsearch_sort_by_abundance | def vsearch_sort_by_abundance(
fasta_filepath,
output_filepath,
working_dir=None,
minsize=None,
maxsize=None,
log_name="abundance_sort.log",
HALT_EXEC=False):
""" Fasta entries are sorted by decreasing abundance
(Fasta entries are assumed to be dereplicated with
the pattern "[>;]size=integer[;]" present in the
read label, ex. use function vsearch_dereplicate_exact_seqs
prior to calling this function)
Parameters
----------
fasta_filepath : string
input fasta file (dereplicated fasta)
output_filepath : string
output filepath for the sorted sequences in fasta format
working_dir : string, optional
working directory to store intermediate files
minsize : integer, optional
discard sequences with an abundance value smaller than
minsize
maxsize : integer, optional
discard sequences with an abundance value greater than
maxsize
log_name : string, optional
log filename
HALT_EXEC : boolean, optional
used for debugging app controller
Return
------
output_filepath : string
filepath to sorted fasta file
log_filepath : string
filepath to log file
"""
# set working dir to same directory as the output
# file (if not provided)
if not working_dir:
working_dir = dirname(output_filepath)
app = Vsearch(WorkingDir=working_dir, HALT_EXEC=HALT_EXEC)
log_filepath = join(working_dir, log_name)
if minsize:
app.Parameters['--minsize'].on(minsize)
if maxsize:
app.Parameters['--maxsize'].on(maxsize)
app.Parameters['--sortbysize'].on(fasta_filepath)
app.Parameters['--output'].on(output_filepath)
app.Parameters['--log'].on(log_filepath)
app_result = app()
return output_filepath, log_filepath | python | def vsearch_sort_by_abundance(
fasta_filepath,
output_filepath,
working_dir=None,
minsize=None,
maxsize=None,
log_name="abundance_sort.log",
HALT_EXEC=False):
""" Fasta entries are sorted by decreasing abundance
(Fasta entries are assumed to be dereplicated with
the pattern "[>;]size=integer[;]" present in the
read label, ex. use function vsearch_dereplicate_exact_seqs
prior to calling this function)
Parameters
----------
fasta_filepath : string
input fasta file (dereplicated fasta)
output_filepath : string
output filepath for the sorted sequences in fasta format
working_dir : string, optional
working directory to store intermediate files
minsize : integer, optional
discard sequences with an abundance value smaller than
minsize
maxsize : integer, optional
discard sequences with an abundance value greater than
maxsize
log_name : string, optional
log filename
HALT_EXEC : boolean, optional
used for debugging app controller
Return
------
output_filepath : string
filepath to sorted fasta file
log_filepath : string
filepath to log file
"""
# set working dir to same directory as the output
# file (if not provided)
if not working_dir:
working_dir = dirname(output_filepath)
app = Vsearch(WorkingDir=working_dir, HALT_EXEC=HALT_EXEC)
log_filepath = join(working_dir, log_name)
if minsize:
app.Parameters['--minsize'].on(minsize)
if maxsize:
app.Parameters['--maxsize'].on(maxsize)
app.Parameters['--sortbysize'].on(fasta_filepath)
app.Parameters['--output'].on(output_filepath)
app.Parameters['--log'].on(log_filepath)
app_result = app()
return output_filepath, log_filepath | [
"def",
"vsearch_sort_by_abundance",
"(",
"fasta_filepath",
",",
"output_filepath",
",",
"working_dir",
"=",
"None",
",",
"minsize",
"=",
"None",
",",
"maxsize",
"=",
"None",
",",
"log_name",
"=",
"\"abundance_sort.log\"",
",",
"HALT_EXEC",
"=",
"False",
")",
":"... | Fasta entries are sorted by decreasing abundance
(Fasta entries are assumed to be dereplicated with
the pattern "[>;]size=integer[;]" present in the
read label, ex. use function vsearch_dereplicate_exact_seqs
prior to calling this function)
Parameters
----------
fasta_filepath : string
input fasta file (dereplicated fasta)
output_filepath : string
output filepath for the sorted sequences in fasta format
working_dir : string, optional
working directory to store intermediate files
minsize : integer, optional
discard sequences with an abundance value smaller than
minsize
maxsize : integer, optional
discard sequences with an abundance value greater than
maxsize
log_name : string, optional
log filename
HALT_EXEC : boolean, optional
used for debugging app controller
Return
------
output_filepath : string
filepath to sorted fasta file
log_filepath : string
filepath to log file | [
"Fasta",
"entries",
"are",
"sorted",
"by",
"decreasing",
"abundance",
"(",
"Fasta",
"entries",
"are",
"assumed",
"to",
"be",
"dereplicated",
"with",
"the",
"pattern",
"[",
">",
";",
"]",
"size",
"=",
"integer",
"[",
";",
"]",
"present",
"in",
"the",
"rea... | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/vsearch.py#L321-L385 |
biocore/burrito-fillings | bfillings/vsearch.py | vsearch_chimera_filter_de_novo | def vsearch_chimera_filter_de_novo(
fasta_filepath,
working_dir,
output_chimeras=True,
output_nonchimeras=True,
output_alns=False,
output_tabular=False,
log_name="vsearch_uchime_de_novo_chimera_filtering.log",
HALT_EXEC=False):
""" Detect chimeras present in the fasta-formatted filename,
without external references (i.e. de novo). Automatically
sort the sequences in filename by decreasing abundance
beforehand. Output chimeras and non-chimeras to FASTA files
and/or 3-way global alignments and/or tabular output.
Parameters
----------
fasta_filepath : string
input fasta file (dereplicated fasta with pattern
[>;]size=integer[;] in the fasta header)
working_dir : string
directory path for all output files
output_chimeras : boolean, optional
output chimeric sequences to file, in fasta format
output_nonchimeras : boolean, optional
output nonchimeric sequences to file, in fasta format
output_alns : boolean, optional
output 3-way global alignments (parentA, parentB, chimera)
in human readable format to file
output_tabular : boolean, optional
output results using the uchime tab-separated format of
18 fields (see Vsearch user manual)
HALT_EXEC : boolean, optional
used for debugging app controller
Return
------
output_chimera_filepath : string
filepath to chimeric fasta sequences
output_non_chimera_filepath : string
filepath to nonchimeric fasta sequences
output_alns_filepath : string
filepath to chimeric sequences alignment
file
output_tabular_filepath : string
filepath to chimeric sequences tabular
output file
log_filepath : string
filepath to log file
"""
app = Vsearch(WorkingDir=working_dir, HALT_EXEC=HALT_EXEC)
if not (output_chimeras or
output_nonchimeras or
output_alns or
output_tabular):
raise ValueError("At least one output format (output_chimeras,"
"output_nonchimeras, output_alns, output_tabular)"
"must be selected")
output_chimera_filepath = None
output_non_chimera_filepath = None
output_alns_filepath = None
output_tabular_filepath = None
# set output filepaths
if output_chimeras:
output_chimera_filepath = join(working_dir, 'uchime_chimeras.fasta')
app.Parameters['--chimeras'].on(output_chimera_filepath)
if output_nonchimeras:
output_non_chimera_filepath = join(working_dir,
'uchime_non_chimeras.fasta')
app.Parameters['--nonchimeras'].on(output_non_chimera_filepath)
if output_alns:
output_alns_filepath = join(working_dir, 'uchime_alignments.txt')
app.Parameters['--uchimealns'].on(output_alns_filepath)
if output_tabular:
output_tabular_filepath = join(working_dir, 'uchime_tabular.txt')
app.Parameters['--uchimeout'].on(output_tabular_filepath)
log_filepath = join(working_dir, log_name)
app.Parameters['--uchime_denovo'].on(fasta_filepath)
app.Parameters['--log'].on(log_filepath)
app_result = app()
return output_chimera_filepath, output_non_chimera_filepath,\
output_alns_filepath, output_tabular_filepath, log_filepath | python | def vsearch_chimera_filter_de_novo(
fasta_filepath,
working_dir,
output_chimeras=True,
output_nonchimeras=True,
output_alns=False,
output_tabular=False,
log_name="vsearch_uchime_de_novo_chimera_filtering.log",
HALT_EXEC=False):
""" Detect chimeras present in the fasta-formatted filename,
without external references (i.e. de novo). Automatically
sort the sequences in filename by decreasing abundance
beforehand. Output chimeras and non-chimeras to FASTA files
and/or 3-way global alignments and/or tabular output.
Parameters
----------
fasta_filepath : string
input fasta file (dereplicated fasta with pattern
[>;]size=integer[;] in the fasta header)
working_dir : string
directory path for all output files
output_chimeras : boolean, optional
output chimeric sequences to file, in fasta format
output_nonchimeras : boolean, optional
output nonchimeric sequences to file, in fasta format
output_alns : boolean, optional
output 3-way global alignments (parentA, parentB, chimera)
in human readable format to file
output_tabular : boolean, optional
output results using the uchime tab-separated format of
18 fields (see Vsearch user manual)
HALT_EXEC : boolean, optional
used for debugging app controller
Return
------
output_chimera_filepath : string
filepath to chimeric fasta sequences
output_non_chimera_filepath : string
filepath to nonchimeric fasta sequences
output_alns_filepath : string
filepath to chimeric sequences alignment
file
output_tabular_filepath : string
filepath to chimeric sequences tabular
output file
log_filepath : string
filepath to log file
"""
app = Vsearch(WorkingDir=working_dir, HALT_EXEC=HALT_EXEC)
if not (output_chimeras or
output_nonchimeras or
output_alns or
output_tabular):
raise ValueError("At least one output format (output_chimeras,"
"output_nonchimeras, output_alns, output_tabular)"
"must be selected")
output_chimera_filepath = None
output_non_chimera_filepath = None
output_alns_filepath = None
output_tabular_filepath = None
# set output filepaths
if output_chimeras:
output_chimera_filepath = join(working_dir, 'uchime_chimeras.fasta')
app.Parameters['--chimeras'].on(output_chimera_filepath)
if output_nonchimeras:
output_non_chimera_filepath = join(working_dir,
'uchime_non_chimeras.fasta')
app.Parameters['--nonchimeras'].on(output_non_chimera_filepath)
if output_alns:
output_alns_filepath = join(working_dir, 'uchime_alignments.txt')
app.Parameters['--uchimealns'].on(output_alns_filepath)
if output_tabular:
output_tabular_filepath = join(working_dir, 'uchime_tabular.txt')
app.Parameters['--uchimeout'].on(output_tabular_filepath)
log_filepath = join(working_dir, log_name)
app.Parameters['--uchime_denovo'].on(fasta_filepath)
app.Parameters['--log'].on(log_filepath)
app_result = app()
return output_chimera_filepath, output_non_chimera_filepath,\
output_alns_filepath, output_tabular_filepath, log_filepath | [
"def",
"vsearch_chimera_filter_de_novo",
"(",
"fasta_filepath",
",",
"working_dir",
",",
"output_chimeras",
"=",
"True",
",",
"output_nonchimeras",
"=",
"True",
",",
"output_alns",
"=",
"False",
",",
"output_tabular",
"=",
"False",
",",
"log_name",
"=",
"\"vsearch_u... | Detect chimeras present in the fasta-formatted filename,
without external references (i.e. de novo). Automatically
sort the sequences in filename by decreasing abundance
beforehand. Output chimeras and non-chimeras to FASTA files
and/or 3-way global alignments and/or tabular output.
Parameters
----------
fasta_filepath : string
input fasta file (dereplicated fasta with pattern
[>;]size=integer[;] in the fasta header)
working_dir : string
directory path for all output files
output_chimeras : boolean, optional
output chimeric sequences to file, in fasta format
output_nonchimeras : boolean, optional
output nonchimeric sequences to file, in fasta format
output_alns : boolean, optional
output 3-way global alignments (parentA, parentB, chimera)
in human readable format to file
output_tabular : boolean, optional
output results using the uchime tab-separated format of
18 fields (see Vsearch user manual)
HALT_EXEC : boolean, optional
used for debugging app controller
Return
------
output_chimera_filepath : string
filepath to chimeric fasta sequences
output_non_chimera_filepath : string
filepath to nonchimeric fasta sequences
output_alns_filepath : string
filepath to chimeric sequences alignment
file
output_tabular_filepath : string
filepath to chimeric sequences tabular
output file
log_filepath : string
filepath to log file | [
"Detect",
"chimeras",
"present",
"in",
"the",
"fasta",
"-",
"formatted",
"filename",
"without",
"external",
"references",
"(",
"i",
".",
"e",
".",
"de",
"novo",
")",
".",
"Automatically",
"sort",
"the",
"sequences",
"in",
"filename",
"by",
"decreasing",
"abu... | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/vsearch.py#L388-L478 |
biocore/burrito-fillings | bfillings/vsearch.py | Vsearch._get_result_paths | def _get_result_paths(self, data):
""" Set the result paths """
result = {}
result['Output'] = ResultPath(
Path=self.Parameters['--output'].Value,
IsWritten=self.Parameters['--output'].isOn())
result['ClusterFile'] = ResultPath(
Path=self.Parameters['--uc'].Value,
IsWritten=self.Parameters['--uc'].isOn())
# uchime 3-way global alignments
result['Output_aln'] = ResultPath(
Path=self.Parameters['--uchimealns'].Value,
IsWritten=self.Parameters['--uchimealns'].isOn())
# uchime tab-separated format
result['Output_tabular'] = ResultPath(
Path=self.Parameters['--uchimeout'].Value,
IsWritten=self.Parameters['--uchimeout'].isOn())
# chimeras fasta file output
result['Output_chimeras'] = ResultPath(
Path=self.Parameters['--chimeras'].Value,
IsWritten=self.Parameters['--chimeras'].isOn())
# nonchimeras fasta file output
result['Output_nonchimeras'] = ResultPath(
Path=self.Parameters['--nonchimeras'].Value,
IsWritten=self.Parameters['--nonchimeras'].isOn())
# log file
result['LogFile'] = ResultPath(
Path=self.Parameters['--log'].Value,
IsWritten=self.Parameters['--log'].isOn())
return result | python | def _get_result_paths(self, data):
""" Set the result paths """
result = {}
result['Output'] = ResultPath(
Path=self.Parameters['--output'].Value,
IsWritten=self.Parameters['--output'].isOn())
result['ClusterFile'] = ResultPath(
Path=self.Parameters['--uc'].Value,
IsWritten=self.Parameters['--uc'].isOn())
# uchime 3-way global alignments
result['Output_aln'] = ResultPath(
Path=self.Parameters['--uchimealns'].Value,
IsWritten=self.Parameters['--uchimealns'].isOn())
# uchime tab-separated format
result['Output_tabular'] = ResultPath(
Path=self.Parameters['--uchimeout'].Value,
IsWritten=self.Parameters['--uchimeout'].isOn())
# chimeras fasta file output
result['Output_chimeras'] = ResultPath(
Path=self.Parameters['--chimeras'].Value,
IsWritten=self.Parameters['--chimeras'].isOn())
# nonchimeras fasta file output
result['Output_nonchimeras'] = ResultPath(
Path=self.Parameters['--nonchimeras'].Value,
IsWritten=self.Parameters['--nonchimeras'].isOn())
# log file
result['LogFile'] = ResultPath(
Path=self.Parameters['--log'].Value,
IsWritten=self.Parameters['--log'].isOn())
return result | [
"def",
"_get_result_paths",
"(",
"self",
",",
"data",
")",
":",
"result",
"=",
"{",
"}",
"result",
"[",
"'Output'",
"]",
"=",
"ResultPath",
"(",
"Path",
"=",
"self",
".",
"Parameters",
"[",
"'--output'",
"]",
".",
"Value",
",",
"IsWritten",
"=",
"self"... | Set the result paths | [
"Set",
"the",
"result",
"paths"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/vsearch.py#L175-L213 |
castelao/oceansdb | oceansdb/cars.py | extract | def extract(filename, doy, latitude, longitude, depth):
"""
For now only the nearest value
For now only for one position, not an array of positions
longitude 0-360
"""
assert np.size(doy) == 1
assert np.size(latitude) == 1
assert np.size(longitude) == 1
assert np.size(depth) == 1
assert (longitude >= 0) & (longitude <= 360)
assert depth >= 0
nc = netCDF4.Dataset(filename)
t = 2 * np.pi * doy/366
Z = np.absolute(nc['depth'][:] - depth).argmin()
I = np.absolute(nc['lat'][:] - latitude).argmin()
J = np.absolute(nc['lon'][:] - longitude).argmin()
# Naive solution
value = nc['mean'][:, I, J]
value[:64] += nc['an_cos'][Z, I, J] * np.cos(t) + \
nc['an_sin'][:, I, J] * np.sin(t)
value[:55] += nc['sa_cos'][Z, I, J] * np.cos(2*t) + \
nc['sa_sin'][:, I, J] * np.sin(2*t)
value = value[Z]
std = nc['std_dev'][Z, I, J]
return value, std | python | def extract(filename, doy, latitude, longitude, depth):
"""
For now only the nearest value
For now only for one position, not an array of positions
longitude 0-360
"""
assert np.size(doy) == 1
assert np.size(latitude) == 1
assert np.size(longitude) == 1
assert np.size(depth) == 1
assert (longitude >= 0) & (longitude <= 360)
assert depth >= 0
nc = netCDF4.Dataset(filename)
t = 2 * np.pi * doy/366
Z = np.absolute(nc['depth'][:] - depth).argmin()
I = np.absolute(nc['lat'][:] - latitude).argmin()
J = np.absolute(nc['lon'][:] - longitude).argmin()
# Naive solution
value = nc['mean'][:, I, J]
value[:64] += nc['an_cos'][Z, I, J] * np.cos(t) + \
nc['an_sin'][:, I, J] * np.sin(t)
value[:55] += nc['sa_cos'][Z, I, J] * np.cos(2*t) + \
nc['sa_sin'][:, I, J] * np.sin(2*t)
value = value[Z]
std = nc['std_dev'][Z, I, J]
return value, std | [
"def",
"extract",
"(",
"filename",
",",
"doy",
",",
"latitude",
",",
"longitude",
",",
"depth",
")",
":",
"assert",
"np",
".",
"size",
"(",
"doy",
")",
"==",
"1",
"assert",
"np",
".",
"size",
"(",
"latitude",
")",
"==",
"1",
"assert",
"np",
".",
... | For now only the nearest value
For now only for one position, not an array of positions
longitude 0-360 | [
"For",
"now",
"only",
"the",
"nearest",
"value",
"For",
"now",
"only",
"for",
"one",
"position",
"not",
"an",
"array",
"of",
"positions",
"longitude",
"0",
"-",
"360"
] | train | https://github.com/castelao/oceansdb/blob/a154c5b845845a602800f9bc53d1702d4cb0f9c5/oceansdb/cars.py#L31-L63 |
castelao/oceansdb | oceansdb/cars.py | cars_profile | def cars_profile(filename, doy, latitude, longitude, depth):
"""
For now only the nearest value
For now only for one position, not an array of positions
longitude 0-360
"""
assert np.size(doy) == 1
assert np.size(latitude) == 1
assert np.size(longitude) == 1
#assert np.size(depth) == 1
assert (longitude >= 0) & (longitude <= 360)
assert depth >= 0
nc = netCDF4.Dataset(filename)
t = 2 * np.pi * doy/366
# Improve this. Optimize to get only necessary Z
Z = slice(0, nc['depth'].size)
I = np.absolute(nc['lat'][:] - latitude).argmin()
J = np.absolute(nc['lon'][:] - longitude).argmin()
# Not efficient, but it works
assert (nc['depth'][:64] == nc['depth_ann'][:]).all()
assert (nc['depth'][:55] == nc['depth_semiann'][:]).all()
value = nc['mean'][:, I, J]
value[:64] += nc['an_cos'][Z, I, J] * np.cos(t) + \
nc['an_sin'][:, I, J] * np.sin(t)
value[:55] += nc['sa_cos'][Z, I, J] * np.cos(2*t) + \
nc['sa_sin'][:, I, J] * np.sin(2*t)
value = value
output = {'depth': np.asanyarray(depth)}
from scipy.interpolate import griddata
output['value'] = griddata(nc['depth'][Z], value[Z], depth)
for v in ['std_dev']:
output[v] = griddata(nc['depth'][Z], nc[v][Z, I, J], depth)
return output | python | def cars_profile(filename, doy, latitude, longitude, depth):
"""
For now only the nearest value
For now only for one position, not an array of positions
longitude 0-360
"""
assert np.size(doy) == 1
assert np.size(latitude) == 1
assert np.size(longitude) == 1
#assert np.size(depth) == 1
assert (longitude >= 0) & (longitude <= 360)
assert depth >= 0
nc = netCDF4.Dataset(filename)
t = 2 * np.pi * doy/366
# Improve this. Optimize to get only necessary Z
Z = slice(0, nc['depth'].size)
I = np.absolute(nc['lat'][:] - latitude).argmin()
J = np.absolute(nc['lon'][:] - longitude).argmin()
# Not efficient, but it works
assert (nc['depth'][:64] == nc['depth_ann'][:]).all()
assert (nc['depth'][:55] == nc['depth_semiann'][:]).all()
value = nc['mean'][:, I, J]
value[:64] += nc['an_cos'][Z, I, J] * np.cos(t) + \
nc['an_sin'][:, I, J] * np.sin(t)
value[:55] += nc['sa_cos'][Z, I, J] * np.cos(2*t) + \
nc['sa_sin'][:, I, J] * np.sin(2*t)
value = value
output = {'depth': np.asanyarray(depth)}
from scipy.interpolate import griddata
output['value'] = griddata(nc['depth'][Z], value[Z], depth)
for v in ['std_dev']:
output[v] = griddata(nc['depth'][Z], nc[v][Z, I, J], depth)
return output | [
"def",
"cars_profile",
"(",
"filename",
",",
"doy",
",",
"latitude",
",",
"longitude",
",",
"depth",
")",
":",
"assert",
"np",
".",
"size",
"(",
"doy",
")",
"==",
"1",
"assert",
"np",
".",
"size",
"(",
"latitude",
")",
"==",
"1",
"assert",
"np",
".... | For now only the nearest value
For now only for one position, not an array of positions
longitude 0-360 | [
"For",
"now",
"only",
"the",
"nearest",
"value",
"For",
"now",
"only",
"for",
"one",
"position",
"not",
"an",
"array",
"of",
"positions",
"longitude",
"0",
"-",
"360"
] | train | https://github.com/castelao/oceansdb/blob/a154c5b845845a602800f9bc53d1702d4cb0f9c5/oceansdb/cars.py#L66-L106 |
castelao/oceansdb | oceansdb/cars.py | CARS_var_nc.crop | def crop(self, doy, depth, lat, lon, var):
""" Crop a subset of the dataset for each var
Given doy, depth, lat and lon, it returns the smallest subset
that still contains the requested coordinates inside it.
It handels special cases like a region around greenwich and
the international date line.
Accepts 0 to 360 and -180 to 180 longitude reference.
It extends time and longitude coordinates, so simplify the use
of series. For example, a ship track can be requested with
a longitude sequence like [352, 358, 364, 369, 380], and
the equivalent for day of year above 365.
"""
dims, idx = cropIndices(self.dims, lat, lon, depth)
dims['time'] = np.atleast_1d(doy)
idx['tn'] = np.arange(dims['time'].size)
# Temporary solution. Create an object for CARS dataset
xn = idx['xn']
yn = idx['yn']
zn = idx['zn']
tn = idx['tn']
subset = {}
for v in var:
if v == 'mn':
mn = []
for d in doy:
t = 2 * np.pi * d/366
# Naive solution
# FIXME: This is not an efficient solution.
value = self.ncs[0]['mean'][:, yn, xn]
value[:64] += self.ncs[0]['an_cos'][:, yn, xn] * np.cos(t) + \
self.ncs[0]['an_sin'][:, yn, xn] * np.sin(t)
value[:55] += self.ncs[0]['sa_cos'][:, yn, xn] * np.cos(2*t) + \
self.ncs[0]['sa_sin'][:, yn, xn] * np.sin(2*t)
mn.append(value[zn])
subset['mn'] = ma.asanyarray(mn)
else:
subset[v] = ma.asanyarray(
doy.size * [self[v][zn, yn, xn]])
return subset, dims | python | def crop(self, doy, depth, lat, lon, var):
""" Crop a subset of the dataset for each var
Given doy, depth, lat and lon, it returns the smallest subset
that still contains the requested coordinates inside it.
It handels special cases like a region around greenwich and
the international date line.
Accepts 0 to 360 and -180 to 180 longitude reference.
It extends time and longitude coordinates, so simplify the use
of series. For example, a ship track can be requested with
a longitude sequence like [352, 358, 364, 369, 380], and
the equivalent for day of year above 365.
"""
dims, idx = cropIndices(self.dims, lat, lon, depth)
dims['time'] = np.atleast_1d(doy)
idx['tn'] = np.arange(dims['time'].size)
# Temporary solution. Create an object for CARS dataset
xn = idx['xn']
yn = idx['yn']
zn = idx['zn']
tn = idx['tn']
subset = {}
for v in var:
if v == 'mn':
mn = []
for d in doy:
t = 2 * np.pi * d/366
# Naive solution
# FIXME: This is not an efficient solution.
value = self.ncs[0]['mean'][:, yn, xn]
value[:64] += self.ncs[0]['an_cos'][:, yn, xn] * np.cos(t) + \
self.ncs[0]['an_sin'][:, yn, xn] * np.sin(t)
value[:55] += self.ncs[0]['sa_cos'][:, yn, xn] * np.cos(2*t) + \
self.ncs[0]['sa_sin'][:, yn, xn] * np.sin(2*t)
mn.append(value[zn])
subset['mn'] = ma.asanyarray(mn)
else:
subset[v] = ma.asanyarray(
doy.size * [self[v][zn, yn, xn]])
return subset, dims | [
"def",
"crop",
"(",
"self",
",",
"doy",
",",
"depth",
",",
"lat",
",",
"lon",
",",
"var",
")",
":",
"dims",
",",
"idx",
"=",
"cropIndices",
"(",
"self",
".",
"dims",
",",
"lat",
",",
"lon",
",",
"depth",
")",
"dims",
"[",
"'time'",
"]",
"=",
... | Crop a subset of the dataset for each var
Given doy, depth, lat and lon, it returns the smallest subset
that still contains the requested coordinates inside it.
It handels special cases like a region around greenwich and
the international date line.
Accepts 0 to 360 and -180 to 180 longitude reference.
It extends time and longitude coordinates, so simplify the use
of series. For example, a ship track can be requested with
a longitude sequence like [352, 358, 364, 369, 380], and
the equivalent for day of year above 365. | [
"Crop",
"a",
"subset",
"of",
"the",
"dataset",
"for",
"each",
"var"
] | train | https://github.com/castelao/oceansdb/blob/a154c5b845845a602800f9bc53d1702d4cb0f9c5/oceansdb/cars.py#L208-L254 |
castelao/oceansdb | oceansdb/cars.py | CARS_var_nc.interpolate | def interpolate(self, doy, depth, lat, lon, var):
""" Interpolate each var on the coordinates requested
"""
subset, dims = self.crop(doy, depth, lat, lon, var)
if np.all([d in dims['time'] for d in doy]) & \
np.all([z in dims['depth'] for z in depth]) & \
np.all([y in dims['lat'] for y in lat]) & \
np.all([x in dims['lon'] for x in lon]):
dn = np.nonzero([d in doy for d in dims['time']])[0]
zn = np.nonzero([z in depth for z in dims['depth']])[0]
yn = np.nonzero([y in lat for y in dims['lat']])[0]
xn = np.nonzero([x in lon for x in dims['lon']])[0]
output = {}
for v in subset:
# output[v] = subset[v][dn, zn, yn, xn]
# Seriously that this is the way to do it?!!??
output[v] = subset[v][:, :, :, xn][:, :, yn][:, zn][dn]
return output
# The output coordinates shall be created only once.
points_out = []
for doyn in doy:
for depthn in depth:
for latn in lat:
for lonn in lon:
points_out.append([doyn, depthn, latn, lonn])
points_out = np.array(points_out)
output = {}
for v in var:
output[v] = ma.masked_all(
(doy.size, depth.size, lat.size, lon.size),
dtype=subset[v].dtype)
# The valid data
idx = np.nonzero(~ma.getmaskarray(subset[v]))
if idx[0].size > 0:
points = np.array([
dims['time'][idx[0]], dims['depth'][idx[1]],
dims['lat'][idx[2]], dims['lon'][idx[3]]]).T
values = subset[v][idx]
# Interpolate along the dimensions that have more than one
# position, otherwise it means that the output is exactly
# on that coordinate.
ind = np.array(
[np.unique(points[:, i]).size > 1 for i in
range(points.shape[1])])
assert ind.any()
# These interpolators understand NaN, but not masks.
values[ma.getmaskarray(values)] = np.nan
values_out = griddata(
np.atleast_1d(np.squeeze(points[:, ind])),
values,
np.atleast_1d(np.squeeze(points_out[:, ind]))
)
# Remap the interpolated value back into a 4D array
idx = np.isfinite(values_out)
for [t, z, y, x], out in zip(points_out[idx], values_out[idx]):
output[v][t==doy, z==depth, y==lat, x==lon] = out
output[v] = ma.fix_invalid(output[v])
return output | python | def interpolate(self, doy, depth, lat, lon, var):
""" Interpolate each var on the coordinates requested
"""
subset, dims = self.crop(doy, depth, lat, lon, var)
if np.all([d in dims['time'] for d in doy]) & \
np.all([z in dims['depth'] for z in depth]) & \
np.all([y in dims['lat'] for y in lat]) & \
np.all([x in dims['lon'] for x in lon]):
dn = np.nonzero([d in doy for d in dims['time']])[0]
zn = np.nonzero([z in depth for z in dims['depth']])[0]
yn = np.nonzero([y in lat for y in dims['lat']])[0]
xn = np.nonzero([x in lon for x in dims['lon']])[0]
output = {}
for v in subset:
# output[v] = subset[v][dn, zn, yn, xn]
# Seriously that this is the way to do it?!!??
output[v] = subset[v][:, :, :, xn][:, :, yn][:, zn][dn]
return output
# The output coordinates shall be created only once.
points_out = []
for doyn in doy:
for depthn in depth:
for latn in lat:
for lonn in lon:
points_out.append([doyn, depthn, latn, lonn])
points_out = np.array(points_out)
output = {}
for v in var:
output[v] = ma.masked_all(
(doy.size, depth.size, lat.size, lon.size),
dtype=subset[v].dtype)
# The valid data
idx = np.nonzero(~ma.getmaskarray(subset[v]))
if idx[0].size > 0:
points = np.array([
dims['time'][idx[0]], dims['depth'][idx[1]],
dims['lat'][idx[2]], dims['lon'][idx[3]]]).T
values = subset[v][idx]
# Interpolate along the dimensions that have more than one
# position, otherwise it means that the output is exactly
# on that coordinate.
ind = np.array(
[np.unique(points[:, i]).size > 1 for i in
range(points.shape[1])])
assert ind.any()
# These interpolators understand NaN, but not masks.
values[ma.getmaskarray(values)] = np.nan
values_out = griddata(
np.atleast_1d(np.squeeze(points[:, ind])),
values,
np.atleast_1d(np.squeeze(points_out[:, ind]))
)
# Remap the interpolated value back into a 4D array
idx = np.isfinite(values_out)
for [t, z, y, x], out in zip(points_out[idx], values_out[idx]):
output[v][t==doy, z==depth, y==lat, x==lon] = out
output[v] = ma.fix_invalid(output[v])
return output | [
"def",
"interpolate",
"(",
"self",
",",
"doy",
",",
"depth",
",",
"lat",
",",
"lon",
",",
"var",
")",
":",
"subset",
",",
"dims",
"=",
"self",
".",
"crop",
"(",
"doy",
",",
"depth",
",",
"lat",
",",
"lon",
",",
"var",
")",
"if",
"np",
".",
"a... | Interpolate each var on the coordinates requested | [
"Interpolate",
"each",
"var",
"on",
"the",
"coordinates",
"requested"
] | train | https://github.com/castelao/oceansdb/blob/a154c5b845845a602800f9bc53d1702d4cb0f9c5/oceansdb/cars.py#L273-L343 |
mikeylight/GitterPy | gitterpy/client.py | User.mark_as_read | def mark_as_read(self, room_name):
"""
message_ids return an array
with unread message ids ['131313231', '323131']
"""
api_meth = self.set_user_items_url(room_name)
message_ids = self.unread_items(room_name).get('chat')
if message_ids:
return self.post(api_meth, data={'chat': message_ids})
else:
raise GitterItemsError(room_name) | python | def mark_as_read(self, room_name):
"""
message_ids return an array
with unread message ids ['131313231', '323131']
"""
api_meth = self.set_user_items_url(room_name)
message_ids = self.unread_items(room_name).get('chat')
if message_ids:
return self.post(api_meth, data={'chat': message_ids})
else:
raise GitterItemsError(room_name) | [
"def",
"mark_as_read",
"(",
"self",
",",
"room_name",
")",
":",
"api_meth",
"=",
"self",
".",
"set_user_items_url",
"(",
"room_name",
")",
"message_ids",
"=",
"self",
".",
"unread_items",
"(",
"room_name",
")",
".",
"get",
"(",
"'chat'",
")",
"if",
"messag... | message_ids return an array
with unread message ids ['131313231', '323131'] | [
"message_ids",
"return",
"an",
"array",
"with",
"unread",
"message",
"ids",
"[",
"131313231",
"323131",
"]"
] | train | https://github.com/mikeylight/GitterPy/blob/ef88ae2154bd6b7324068d2fbb3ac5f436b618cb/gitterpy/client.py#L199-L209 |
natea/django-deployer | django_deployer/providers.py | PaaSProvider.init | def init(cls, site):
"""
put site settings in the header of the script
"""
bash_header = ""
for k,v in site.items():
bash_header += "%s=%s" % (k.upper(), v)
bash_header += '\n'
site['bash_header'] = bash_header
# TODO: execute before_deploy
# P.S. running init_before seems like impossible, because the file hasn't been rendered.
if cls.git_template:
# do render from git repo
print "Cloning template files..."
repo_local_copy = utils.clone_git_repo(cls.git_template_url)
print "Rendering files from templates..."
target_path = os.getcwd()
settings_dir = '/'.join(site['django_settings'].split('.')[:-1])
site['project_name'] = settings_dir.replace('/', '.')
settings_dir_path = target_path
if settings_dir:
settings_dir_path += '/' + settings_dir
utils.render_from_repo(repo_local_copy, target_path, site, settings_dir_path)
else:
cls._create_configs(site)
print cls.setup_instructions
# TODO: execute after_deploy
run_hooks('init_after') | python | def init(cls, site):
"""
put site settings in the header of the script
"""
bash_header = ""
for k,v in site.items():
bash_header += "%s=%s" % (k.upper(), v)
bash_header += '\n'
site['bash_header'] = bash_header
# TODO: execute before_deploy
# P.S. running init_before seems like impossible, because the file hasn't been rendered.
if cls.git_template:
# do render from git repo
print "Cloning template files..."
repo_local_copy = utils.clone_git_repo(cls.git_template_url)
print "Rendering files from templates..."
target_path = os.getcwd()
settings_dir = '/'.join(site['django_settings'].split('.')[:-1])
site['project_name'] = settings_dir.replace('/', '.')
settings_dir_path = target_path
if settings_dir:
settings_dir_path += '/' + settings_dir
utils.render_from_repo(repo_local_copy, target_path, site, settings_dir_path)
else:
cls._create_configs(site)
print cls.setup_instructions
# TODO: execute after_deploy
run_hooks('init_after') | [
"def",
"init",
"(",
"cls",
",",
"site",
")",
":",
"bash_header",
"=",
"\"\"",
"for",
"k",
",",
"v",
"in",
"site",
".",
"items",
"(",
")",
":",
"bash_header",
"+=",
"\"%s=%s\"",
"%",
"(",
"k",
".",
"upper",
"(",
")",
",",
"v",
")",
"bash_header",
... | put site settings in the header of the script | [
"put",
"site",
"settings",
"in",
"the",
"header",
"of",
"the",
"script"
] | train | https://github.com/natea/django-deployer/blob/5ce7d972db2f8500ec53ad89e7eb312d3360d074/django_deployer/providers.py#L35-L63 |
natea/django-deployer | django_deployer/providers.py | PaaSProvider._create_configs | def _create_configs(cls, site):
"""
This is going to generate the following configuration:
* wsgi.py
* <provider>.yml
* settings_<provider>.py
"""
provider = cls.name
cls._render_config('wsgi.py', 'wsgi.py', site)
# create yaml file
yaml_template_name = os.path.join(provider, cls.provider_yml_name)
cls._render_config(cls.provider_yml_name, yaml_template_name, site)
# create requirements file
# don't do anything if the requirements file is called requirements.txt and in the root of the project
requirements_filename = "requirements.txt"
if site['requirements'] != requirements_filename: # providers expect the file to be called requirements.txt
requirements_template_name = os.path.join(provider, requirements_filename)
cls._render_config(requirements_filename, requirements_template_name, site)
# create settings file
settings_template_name = os.path.join(provider, 'settings_%s.py' % provider)
settings_path = site['django_settings'].replace('.', '/') + '_%s.py' % provider
cls._render_config(settings_path, settings_template_name, site) | python | def _create_configs(cls, site):
"""
This is going to generate the following configuration:
* wsgi.py
* <provider>.yml
* settings_<provider>.py
"""
provider = cls.name
cls._render_config('wsgi.py', 'wsgi.py', site)
# create yaml file
yaml_template_name = os.path.join(provider, cls.provider_yml_name)
cls._render_config(cls.provider_yml_name, yaml_template_name, site)
# create requirements file
# don't do anything if the requirements file is called requirements.txt and in the root of the project
requirements_filename = "requirements.txt"
if site['requirements'] != requirements_filename: # providers expect the file to be called requirements.txt
requirements_template_name = os.path.join(provider, requirements_filename)
cls._render_config(requirements_filename, requirements_template_name, site)
# create settings file
settings_template_name = os.path.join(provider, 'settings_%s.py' % provider)
settings_path = site['django_settings'].replace('.', '/') + '_%s.py' % provider
cls._render_config(settings_path, settings_template_name, site) | [
"def",
"_create_configs",
"(",
"cls",
",",
"site",
")",
":",
"provider",
"=",
"cls",
".",
"name",
"cls",
".",
"_render_config",
"(",
"'wsgi.py'",
",",
"'wsgi.py'",
",",
"site",
")",
"# create yaml file",
"yaml_template_name",
"=",
"os",
".",
"path",
".",
"... | This is going to generate the following configuration:
* wsgi.py
* <provider>.yml
* settings_<provider>.py | [
"This",
"is",
"going",
"to",
"generate",
"the",
"following",
"configuration",
":",
"*",
"wsgi",
".",
"py",
"*",
"<provider",
">",
".",
"yml",
"*",
"settings_<provider",
">",
".",
"py"
] | train | https://github.com/natea/django-deployer/blob/5ce7d972db2f8500ec53ad89e7eb312d3360d074/django_deployer/providers.py#L76-L101 |
natea/django-deployer | django_deployer/providers.py | PaaSProvider._render_config | def _render_config(cls, dest, template_name, template_args):
"""
Renders and writes a template_name to a dest given some template_args.
This is for platform-specific configurations
"""
template_args = template_args.copy()
# Substitute values here
pyversion = template_args['pyversion']
template_args['pyversion'] = cls.PYVERSIONS[pyversion]
template = template_env.get_template(template_name)
contents = template.render(**template_args)
_write_file(dest, contents) | python | def _render_config(cls, dest, template_name, template_args):
"""
Renders and writes a template_name to a dest given some template_args.
This is for platform-specific configurations
"""
template_args = template_args.copy()
# Substitute values here
pyversion = template_args['pyversion']
template_args['pyversion'] = cls.PYVERSIONS[pyversion]
template = template_env.get_template(template_name)
contents = template.render(**template_args)
_write_file(dest, contents) | [
"def",
"_render_config",
"(",
"cls",
",",
"dest",
",",
"template_name",
",",
"template_args",
")",
":",
"template_args",
"=",
"template_args",
".",
"copy",
"(",
")",
"# Substitute values here",
"pyversion",
"=",
"template_args",
"[",
"'pyversion'",
"]",
"template_... | Renders and writes a template_name to a dest given some template_args.
This is for platform-specific configurations | [
"Renders",
"and",
"writes",
"a",
"template_name",
"to",
"a",
"dest",
"given",
"some",
"template_args",
"."
] | train | https://github.com/natea/django-deployer/blob/5ce7d972db2f8500ec53ad89e7eb312d3360d074/django_deployer/providers.py#L104-L118 |
michaelpb/omnic | omnic/cli/commandparser.py | CommandParser.gen_subcommand_help | def gen_subcommand_help(self):
'''
Generates s
'''
commands = sorted(self.subcommands.items(), key=lambda i: i[0])
return '\n'.join(
'%s %s' % (
subcommand.ljust(15),
textwrap.shorten(description, width=61),
)
for subcommand, (description, action, opts) in commands
) | python | def gen_subcommand_help(self):
'''
Generates s
'''
commands = sorted(self.subcommands.items(), key=lambda i: i[0])
return '\n'.join(
'%s %s' % (
subcommand.ljust(15),
textwrap.shorten(description, width=61),
)
for subcommand, (description, action, opts) in commands
) | [
"def",
"gen_subcommand_help",
"(",
"self",
")",
":",
"commands",
"=",
"sorted",
"(",
"self",
".",
"subcommands",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"i",
":",
"i",
"[",
"0",
"]",
")",
"return",
"'\\n'",
".",
"join",
"(",
"'%s %s'",
"... | Generates s | [
"Generates",
"s"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/cli/commandparser.py#L16-L27 |
michaelpb/omnic | omnic/cli/commandparser.py | CommandParser.parse_args_to_action_args | def parse_args_to_action_args(self, argv=None):
'''
Parses args and returns an action and the args that were parsed
'''
args = self.parse_args(argv)
action = self.subcommands[args.subcommand][1]
return action, args | python | def parse_args_to_action_args(self, argv=None):
'''
Parses args and returns an action and the args that were parsed
'''
args = self.parse_args(argv)
action = self.subcommands[args.subcommand][1]
return action, args | [
"def",
"parse_args_to_action_args",
"(",
"self",
",",
"argv",
"=",
"None",
")",
":",
"args",
"=",
"self",
".",
"parse_args",
"(",
"argv",
")",
"action",
"=",
"self",
".",
"subcommands",
"[",
"args",
".",
"subcommand",
"]",
"[",
"1",
"]",
"return",
"act... | Parses args and returns an action and the args that were parsed | [
"Parses",
"args",
"and",
"returns",
"an",
"action",
"and",
"the",
"args",
"that",
"were",
"parsed"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/cli/commandparser.py#L64-L70 |
michaelpb/omnic | omnic/cli/commandparser.py | CommandParser.register_subparser | def register_subparser(self, action, name, description='', arguments={}):
'''
Registers a new subcommand with a given function action.
If the function action is synchronous
'''
action = coerce_to_synchronous(action)
opts = []
for flags, kwargs in arguments.items():
if isinstance(flags, str):
flags = tuple([flags])
opts.append((flags, kwargs))
self.subcommands[name] = (description, action, opts) | python | def register_subparser(self, action, name, description='', arguments={}):
'''
Registers a new subcommand with a given function action.
If the function action is synchronous
'''
action = coerce_to_synchronous(action)
opts = []
for flags, kwargs in arguments.items():
if isinstance(flags, str):
flags = tuple([flags])
opts.append((flags, kwargs))
self.subcommands[name] = (description, action, opts) | [
"def",
"register_subparser",
"(",
"self",
",",
"action",
",",
"name",
",",
"description",
"=",
"''",
",",
"arguments",
"=",
"{",
"}",
")",
":",
"action",
"=",
"coerce_to_synchronous",
"(",
"action",
")",
"opts",
"=",
"[",
"]",
"for",
"flags",
",",
"kwa... | Registers a new subcommand with a given function action.
If the function action is synchronous | [
"Registers",
"a",
"new",
"subcommand",
"with",
"a",
"given",
"function",
"action",
"."
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/cli/commandparser.py#L72-L84 |
michaelpb/omnic | omnic/cli/commandparser.py | CommandParser.subcommand | def subcommand(self, description='', arguments={}):
'''
Decorator for quickly adding subcommands to the omnic CLI
'''
def decorator(func):
self.register_subparser(
func,
func.__name__.replace('_', '-'),
description=description,
arguments=arguments,
)
return func
return decorator | python | def subcommand(self, description='', arguments={}):
'''
Decorator for quickly adding subcommands to the omnic CLI
'''
def decorator(func):
self.register_subparser(
func,
func.__name__.replace('_', '-'),
description=description,
arguments=arguments,
)
return func
return decorator | [
"def",
"subcommand",
"(",
"self",
",",
"description",
"=",
"''",
",",
"arguments",
"=",
"{",
"}",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"self",
".",
"register_subparser",
"(",
"func",
",",
"func",
".",
"__name__",
".",
"replace",
"(",
... | Decorator for quickly adding subcommands to the omnic CLI | [
"Decorator",
"for",
"quickly",
"adding",
"subcommands",
"to",
"the",
"omnic",
"CLI"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/cli/commandparser.py#L86-L98 |
michaelpb/omnic | omnic/cli/commandparser.py | CommandParser.print | def print(self, *args, **kwargs):
'''
Utility function that behaves identically to 'print' except it only
prints if verbose
'''
if self._last_args and self._last_args.verbose:
print(*args, **kwargs) | python | def print(self, *args, **kwargs):
'''
Utility function that behaves identically to 'print' except it only
prints if verbose
'''
if self._last_args and self._last_args.verbose:
print(*args, **kwargs) | [
"def",
"print",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_last_args",
"and",
"self",
".",
"_last_args",
".",
"verbose",
":",
"print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Utility function that behaves identically to 'print' except it only
prints if verbose | [
"Utility",
"function",
"that",
"behaves",
"identically",
"to",
"print",
"except",
"it",
"only",
"prints",
"if",
"verbose"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/cli/commandparser.py#L100-L106 |
biocore/burrito-fillings | bfillings/uclust.py | process_uclust_pw_alignment_results | def process_uclust_pw_alignment_results(fasta_pairs_lines, uc_lines):
""" Process results of uclust search and align """
alignments = get_next_two_fasta_records(fasta_pairs_lines)
for hit in get_next_record_type(uc_lines, 'H'):
matching_strand = hit[4]
if matching_strand == '-':
strand_id = '-'
target_rev_match = True
elif matching_strand == '+':
strand_id = '+'
target_rev_match = False
elif matching_strand == '.':
# protein sequence, so no strand information
strand_id = ''
target_rev_match = False
else:
raise UclustParseError("Unknown strand type: %s" % matching_strand)
uc_query_id = hit[8]
uc_target_id = hit[9]
percent_id = float(hit[3])
fasta_pair = alignments.next()
fasta_query_id = fasta_pair[0][0]
aligned_query = fasta_pair[0][1]
if fasta_query_id != uc_query_id:
raise UclustParseError("Order of fasta and uc files do not match." +
" Got query %s but expected %s." %
(fasta_query_id, uc_query_id))
fasta_target_id = fasta_pair[1][0]
aligned_target = fasta_pair[1][1]
if fasta_target_id != uc_target_id + strand_id:
raise UclustParseError("Order of fasta and uc files do not match." +
" Got target %s but expected %s." %
(fasta_target_id, uc_target_id + strand_id))
if target_rev_match:
query_id = uc_query_id + ' RC'
aligned_query = DNA.rc(aligned_query)
target_id = uc_target_id
aligned_target = DNA.rc(aligned_target)
else:
query_id = uc_query_id
aligned_query = aligned_query
target_id = uc_target_id
aligned_target = aligned_target
yield (query_id, target_id, aligned_query, aligned_target, percent_id) | python | def process_uclust_pw_alignment_results(fasta_pairs_lines, uc_lines):
""" Process results of uclust search and align """
alignments = get_next_two_fasta_records(fasta_pairs_lines)
for hit in get_next_record_type(uc_lines, 'H'):
matching_strand = hit[4]
if matching_strand == '-':
strand_id = '-'
target_rev_match = True
elif matching_strand == '+':
strand_id = '+'
target_rev_match = False
elif matching_strand == '.':
# protein sequence, so no strand information
strand_id = ''
target_rev_match = False
else:
raise UclustParseError("Unknown strand type: %s" % matching_strand)
uc_query_id = hit[8]
uc_target_id = hit[9]
percent_id = float(hit[3])
fasta_pair = alignments.next()
fasta_query_id = fasta_pair[0][0]
aligned_query = fasta_pair[0][1]
if fasta_query_id != uc_query_id:
raise UclustParseError("Order of fasta and uc files do not match." +
" Got query %s but expected %s." %
(fasta_query_id, uc_query_id))
fasta_target_id = fasta_pair[1][0]
aligned_target = fasta_pair[1][1]
if fasta_target_id != uc_target_id + strand_id:
raise UclustParseError("Order of fasta and uc files do not match." +
" Got target %s but expected %s." %
(fasta_target_id, uc_target_id + strand_id))
if target_rev_match:
query_id = uc_query_id + ' RC'
aligned_query = DNA.rc(aligned_query)
target_id = uc_target_id
aligned_target = DNA.rc(aligned_target)
else:
query_id = uc_query_id
aligned_query = aligned_query
target_id = uc_target_id
aligned_target = aligned_target
yield (query_id, target_id, aligned_query, aligned_target, percent_id) | [
"def",
"process_uclust_pw_alignment_results",
"(",
"fasta_pairs_lines",
",",
"uc_lines",
")",
":",
"alignments",
"=",
"get_next_two_fasta_records",
"(",
"fasta_pairs_lines",
")",
"for",
"hit",
"in",
"get_next_record_type",
"(",
"uc_lines",
",",
"'H'",
")",
":",
"match... | Process results of uclust search and align | [
"Process",
"results",
"of",
"uclust",
"search",
"and",
"align"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/uclust.py#L213-L263 |
biocore/burrito-fillings | bfillings/uclust.py | clusters_from_uc_file | def clusters_from_uc_file(uc_lines,
error_on_multiple_hits=True):
""" Given an open .uc file, return lists (clusters, failures, new_seeds)
uc_lines: open .uc file, or similar object -- this is the output
generated by uclust's -uc parameter
error_on_multiple_hits: if True (default), when a single query hits
to multiple seeds, as can happen when --allhits is passed to uclust,
throw a UclustParseError. if False, when a single query hits to
multiple seeds, it will appear in each cluster.
This function processes all hit (H), seed (S), and no hit (N) lines
to return all clusters, failures, and new_seeds generated in
a uclust run. failures should only arise when users have passed
--lib and --libonly, and a sequence doesn't cluster to any existing
reference database sequences.
"""
clusters = {}
failures = []
seeds = []
all_hits = set()
# the types of hit lines we're interested in here
# are hit (H), seed (S), library seed (L) and no hit (N)
hit_types = {}.fromkeys(list('HSNL'))
for record in get_next_record_type(uc_lines, hit_types):
hit_type = record[0]
# sequence identifiers from the fasta header lines only
# (no comment data) are stored to identify a sequence in
# a cluster -- strip off any comments here as this value
# is used in several places
query_id = record[8].split()[0]
target_cluster = record[9].split()[0]
if hit_type == 'H':
if error_on_multiple_hits and query_id in all_hits:
raise UclustParseError("Query id " + query_id + " hit multiple seeds. "
"This can happen if --allhits is "
"enabled in the call to uclust, which isn't supported by default. "
"Call clusters_from_uc_file(lines, error_on_multiple_hits=False) to "
"allow a query to cluster to multiple seeds.")
else:
# add the hit to its existing cluster (either library
# or new cluster)
clusters[target_cluster].append(query_id)
all_hits.add(query_id)
elif hit_type == 'S':
# a new seed was identified -- create a cluster with this
# sequence as the first instance
if query_id in clusters:
raise UclustParseError("A seq id was provided as a seed, but that seq id already "
"represents a cluster. Are there overlapping seq ids in your "
"reference and input files or repeated seq ids in either? "
"Offending seq id is %s" % query_id)
clusters[query_id] = [query_id]
seeds.append(query_id)
elif hit_type == 'L':
# a library seed was identified -- create a cluster with this
# id as the index, but don't give it any instances yet bc the hit
# line will be specified separately. note we need to handle these
# lines separately from the H lines to detect overlapping seq ids
# between the reference and the input fasta files
if query_id in clusters:
raise UclustParseError("A seq id was provided as a seed, but that seq id already "
"represents a cluster. Are there overlapping seq ids in your "
"reference and input files or repeated seq ids in either? "
"Offending seq id is %s" % query_id)
clusters[query_id] = []
elif hit_type == 'N':
# a failure was identified -- add it to the failures list
failures.append(query_id)
else:
# shouldn't be possible to get here, but provided for
# clarity
raise UclustParseError(
"Unexpected result parsing line:\n%s" %
'\t'.join(record))
# will need to return the full clusters dict, I think, to support
# useful identifiers in reference database clustering
# return clusters.values(), failures, seeds
return clusters, failures, seeds | python | def clusters_from_uc_file(uc_lines,
error_on_multiple_hits=True):
""" Given an open .uc file, return lists (clusters, failures, new_seeds)
uc_lines: open .uc file, or similar object -- this is the output
generated by uclust's -uc parameter
error_on_multiple_hits: if True (default), when a single query hits
to multiple seeds, as can happen when --allhits is passed to uclust,
throw a UclustParseError. if False, when a single query hits to
multiple seeds, it will appear in each cluster.
This function processes all hit (H), seed (S), and no hit (N) lines
to return all clusters, failures, and new_seeds generated in
a uclust run. failures should only arise when users have passed
--lib and --libonly, and a sequence doesn't cluster to any existing
reference database sequences.
"""
clusters = {}
failures = []
seeds = []
all_hits = set()
# the types of hit lines we're interested in here
# are hit (H), seed (S), library seed (L) and no hit (N)
hit_types = {}.fromkeys(list('HSNL'))
for record in get_next_record_type(uc_lines, hit_types):
hit_type = record[0]
# sequence identifiers from the fasta header lines only
# (no comment data) are stored to identify a sequence in
# a cluster -- strip off any comments here as this value
# is used in several places
query_id = record[8].split()[0]
target_cluster = record[9].split()[0]
if hit_type == 'H':
if error_on_multiple_hits and query_id in all_hits:
raise UclustParseError("Query id " + query_id + " hit multiple seeds. "
"This can happen if --allhits is "
"enabled in the call to uclust, which isn't supported by default. "
"Call clusters_from_uc_file(lines, error_on_multiple_hits=False) to "
"allow a query to cluster to multiple seeds.")
else:
# add the hit to its existing cluster (either library
# or new cluster)
clusters[target_cluster].append(query_id)
all_hits.add(query_id)
elif hit_type == 'S':
# a new seed was identified -- create a cluster with this
# sequence as the first instance
if query_id in clusters:
raise UclustParseError("A seq id was provided as a seed, but that seq id already "
"represents a cluster. Are there overlapping seq ids in your "
"reference and input files or repeated seq ids in either? "
"Offending seq id is %s" % query_id)
clusters[query_id] = [query_id]
seeds.append(query_id)
elif hit_type == 'L':
# a library seed was identified -- create a cluster with this
# id as the index, but don't give it any instances yet bc the hit
# line will be specified separately. note we need to handle these
# lines separately from the H lines to detect overlapping seq ids
# between the reference and the input fasta files
if query_id in clusters:
raise UclustParseError("A seq id was provided as a seed, but that seq id already "
"represents a cluster. Are there overlapping seq ids in your "
"reference and input files or repeated seq ids in either? "
"Offending seq id is %s" % query_id)
clusters[query_id] = []
elif hit_type == 'N':
# a failure was identified -- add it to the failures list
failures.append(query_id)
else:
# shouldn't be possible to get here, but provided for
# clarity
raise UclustParseError(
"Unexpected result parsing line:\n%s" %
'\t'.join(record))
# will need to return the full clusters dict, I think, to support
# useful identifiers in reference database clustering
# return clusters.values(), failures, seeds
return clusters, failures, seeds | [
"def",
"clusters_from_uc_file",
"(",
"uc_lines",
",",
"error_on_multiple_hits",
"=",
"True",
")",
":",
"clusters",
"=",
"{",
"}",
"failures",
"=",
"[",
"]",
"seeds",
"=",
"[",
"]",
"all_hits",
"=",
"set",
"(",
")",
"# the types of hit lines we're interested in h... | Given an open .uc file, return lists (clusters, failures, new_seeds)
uc_lines: open .uc file, or similar object -- this is the output
generated by uclust's -uc parameter
error_on_multiple_hits: if True (default), when a single query hits
to multiple seeds, as can happen when --allhits is passed to uclust,
throw a UclustParseError. if False, when a single query hits to
multiple seeds, it will appear in each cluster.
This function processes all hit (H), seed (S), and no hit (N) lines
to return all clusters, failures, and new_seeds generated in
a uclust run. failures should only arise when users have passed
--lib and --libonly, and a sequence doesn't cluster to any existing
reference database sequences. | [
"Given",
"an",
"open",
".",
"uc",
"file",
"return",
"lists",
"(",
"clusters",
"failures",
"new_seeds",
")"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/uclust.py#L266-L346 |
biocore/burrito-fillings | bfillings/uclust.py | uclust_fasta_sort_from_filepath | def uclust_fasta_sort_from_filepath(
fasta_filepath,
output_filepath=None,
tmp_dir=gettempdir(),
HALT_EXEC=False):
"""Generates sorted fasta file via uclust --mergesort."""
if not output_filepath:
_, output_filepath = mkstemp(dir=tmp_dir, prefix='uclust_fasta_sort',
suffix='.fasta')
app = Uclust(params={'--tmpdir': tmp_dir},
TmpDir=tmp_dir, HALT_EXEC=HALT_EXEC)
app_result = app(data={'--mergesort': fasta_filepath,
'--output': output_filepath})
return app_result | python | def uclust_fasta_sort_from_filepath(
fasta_filepath,
output_filepath=None,
tmp_dir=gettempdir(),
HALT_EXEC=False):
"""Generates sorted fasta file via uclust --mergesort."""
if not output_filepath:
_, output_filepath = mkstemp(dir=tmp_dir, prefix='uclust_fasta_sort',
suffix='.fasta')
app = Uclust(params={'--tmpdir': tmp_dir},
TmpDir=tmp_dir, HALT_EXEC=HALT_EXEC)
app_result = app(data={'--mergesort': fasta_filepath,
'--output': output_filepath})
return app_result | [
"def",
"uclust_fasta_sort_from_filepath",
"(",
"fasta_filepath",
",",
"output_filepath",
"=",
"None",
",",
"tmp_dir",
"=",
"gettempdir",
"(",
")",
",",
"HALT_EXEC",
"=",
"False",
")",
":",
"if",
"not",
"output_filepath",
":",
"_",
",",
"output_filepath",
"=",
... | Generates sorted fasta file via uclust --mergesort. | [
"Generates",
"sorted",
"fasta",
"file",
"via",
"uclust",
"--",
"mergesort",
"."
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/uclust.py#L352-L368 |
biocore/burrito-fillings | bfillings/uclust.py | uclust_search_and_align_from_fasta_filepath | def uclust_search_and_align_from_fasta_filepath(
query_fasta_filepath,
subject_fasta_filepath,
percent_ID=0.75,
enable_rev_strand_matching=True,
max_accepts=8,
max_rejects=32,
tmp_dir=gettempdir(),
HALT_EXEC=False):
""" query seqs against subject fasta using uclust,
return global pw alignment of best match
"""
# Explanation of parameter settings
# id - min percent id to count a match
# maxaccepts = 8 , searches for best match rather than first match
# (0 => infinite accepts, or good matches before
# quitting search)
# maxaccepts = 32,
# libonly = True , does not add sequences to the library if they don't
# match something there already. this effectively makes
# uclust a search tool rather than a clustering tool
params = {'--id': percent_ID,
'--maxaccepts': max_accepts,
'--maxrejects': max_rejects,
'--libonly': True,
'--lib': subject_fasta_filepath,
'--tmpdir': tmp_dir}
if enable_rev_strand_matching:
params['--rev'] = True
# instantiate the application controller
app = Uclust(params,
TmpDir=tmp_dir, HALT_EXEC=HALT_EXEC)
# apply uclust
_, alignment_filepath = mkstemp(dir=tmp_dir, prefix='uclust_alignments',
suffix='.fasta')
_, uc_filepath = mkstemp(dir=tmp_dir, prefix='uclust_results',
suffix='.uc')
input_data = {'--input': query_fasta_filepath,
'--fastapairs': alignment_filepath,
'--uc': uc_filepath}
app_result = app(input_data)
# yield the pairwise alignments
for result in process_uclust_pw_alignment_results(
app_result['PairwiseAlignments'], app_result['ClusterFile']):
try:
yield result
except GeneratorExit:
break
# clean up the temp files that were generated
app_result.cleanUp()
return | python | def uclust_search_and_align_from_fasta_filepath(
query_fasta_filepath,
subject_fasta_filepath,
percent_ID=0.75,
enable_rev_strand_matching=True,
max_accepts=8,
max_rejects=32,
tmp_dir=gettempdir(),
HALT_EXEC=False):
""" query seqs against subject fasta using uclust,
return global pw alignment of best match
"""
# Explanation of parameter settings
# id - min percent id to count a match
# maxaccepts = 8 , searches for best match rather than first match
# (0 => infinite accepts, or good matches before
# quitting search)
# maxaccepts = 32,
# libonly = True , does not add sequences to the library if they don't
# match something there already. this effectively makes
# uclust a search tool rather than a clustering tool
params = {'--id': percent_ID,
'--maxaccepts': max_accepts,
'--maxrejects': max_rejects,
'--libonly': True,
'--lib': subject_fasta_filepath,
'--tmpdir': tmp_dir}
if enable_rev_strand_matching:
params['--rev'] = True
# instantiate the application controller
app = Uclust(params,
TmpDir=tmp_dir, HALT_EXEC=HALT_EXEC)
# apply uclust
_, alignment_filepath = mkstemp(dir=tmp_dir, prefix='uclust_alignments',
suffix='.fasta')
_, uc_filepath = mkstemp(dir=tmp_dir, prefix='uclust_results',
suffix='.uc')
input_data = {'--input': query_fasta_filepath,
'--fastapairs': alignment_filepath,
'--uc': uc_filepath}
app_result = app(input_data)
# yield the pairwise alignments
for result in process_uclust_pw_alignment_results(
app_result['PairwiseAlignments'], app_result['ClusterFile']):
try:
yield result
except GeneratorExit:
break
# clean up the temp files that were generated
app_result.cleanUp()
return | [
"def",
"uclust_search_and_align_from_fasta_filepath",
"(",
"query_fasta_filepath",
",",
"subject_fasta_filepath",
",",
"percent_ID",
"=",
"0.75",
",",
"enable_rev_strand_matching",
"=",
"True",
",",
"max_accepts",
"=",
"8",
",",
"max_rejects",
"=",
"32",
",",
"tmp_dir",... | query seqs against subject fasta using uclust,
return global pw alignment of best match | [
"query",
"seqs",
"against",
"subject",
"fasta",
"using",
"uclust"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/uclust.py#L371-L430 |
biocore/burrito-fillings | bfillings/uclust.py | uclust_cluster_from_sorted_fasta_filepath | def uclust_cluster_from_sorted_fasta_filepath(
fasta_filepath,
uc_save_filepath=None,
percent_ID=0.97,
max_accepts=1,
max_rejects=8,
stepwords=8,
word_length=8,
optimal=False,
exact=False,
suppress_sort=False,
enable_rev_strand_matching=False,
subject_fasta_filepath=None,
suppress_new_clusters=False,
stable_sort=False,
tmp_dir=gettempdir(),
HALT_EXEC=False):
""" Returns clustered uclust file from sorted fasta"""
output_filepath = uc_save_filepath
if not output_filepath:
_, output_filepath = mkstemp(dir=tmp_dir, prefix='uclust_clusters',
suffix='.uc')
params = {'--id': percent_ID,
'--maxaccepts': max_accepts,
'--maxrejects': max_rejects,
'--stepwords': stepwords,
'--w': word_length,
'--tmpdir': tmp_dir}
app = Uclust(params,
TmpDir=tmp_dir, HALT_EXEC=HALT_EXEC)
# Set any additional parameters specified by the user
if enable_rev_strand_matching:
app.Parameters['--rev'].on()
if optimal:
app.Parameters['--optimal'].on()
if exact:
app.Parameters['--exact'].on()
if suppress_sort:
app.Parameters['--usersort'].on()
if subject_fasta_filepath:
app.Parameters['--lib'].on(subject_fasta_filepath)
if suppress_new_clusters:
app.Parameters['--libonly'].on()
if stable_sort:
app.Parameters['--stable_sort'].on()
app_result = app({'--input': fasta_filepath, '--uc': output_filepath})
return app_result | python | def uclust_cluster_from_sorted_fasta_filepath(
fasta_filepath,
uc_save_filepath=None,
percent_ID=0.97,
max_accepts=1,
max_rejects=8,
stepwords=8,
word_length=8,
optimal=False,
exact=False,
suppress_sort=False,
enable_rev_strand_matching=False,
subject_fasta_filepath=None,
suppress_new_clusters=False,
stable_sort=False,
tmp_dir=gettempdir(),
HALT_EXEC=False):
""" Returns clustered uclust file from sorted fasta"""
output_filepath = uc_save_filepath
if not output_filepath:
_, output_filepath = mkstemp(dir=tmp_dir, prefix='uclust_clusters',
suffix='.uc')
params = {'--id': percent_ID,
'--maxaccepts': max_accepts,
'--maxrejects': max_rejects,
'--stepwords': stepwords,
'--w': word_length,
'--tmpdir': tmp_dir}
app = Uclust(params,
TmpDir=tmp_dir, HALT_EXEC=HALT_EXEC)
# Set any additional parameters specified by the user
if enable_rev_strand_matching:
app.Parameters['--rev'].on()
if optimal:
app.Parameters['--optimal'].on()
if exact:
app.Parameters['--exact'].on()
if suppress_sort:
app.Parameters['--usersort'].on()
if subject_fasta_filepath:
app.Parameters['--lib'].on(subject_fasta_filepath)
if suppress_new_clusters:
app.Parameters['--libonly'].on()
if stable_sort:
app.Parameters['--stable_sort'].on()
app_result = app({'--input': fasta_filepath, '--uc': output_filepath})
return app_result | [
"def",
"uclust_cluster_from_sorted_fasta_filepath",
"(",
"fasta_filepath",
",",
"uc_save_filepath",
"=",
"None",
",",
"percent_ID",
"=",
"0.97",
",",
"max_accepts",
"=",
"1",
",",
"max_rejects",
"=",
"8",
",",
"stepwords",
"=",
"8",
",",
"word_length",
"=",
"8",... | Returns clustered uclust file from sorted fasta | [
"Returns",
"clustered",
"uclust",
"file",
"from",
"sorted",
"fasta"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/uclust.py#L433-L482 |
biocore/burrito-fillings | bfillings/uclust.py | get_clusters_from_fasta_filepath | def get_clusters_from_fasta_filepath(
fasta_filepath,
original_fasta_path,
percent_ID=0.97,
max_accepts=1,
max_rejects=8,
stepwords=8,
word_length=8,
optimal=False,
exact=False,
suppress_sort=False,
output_dir=None,
enable_rev_strand_matching=False,
subject_fasta_filepath=None,
suppress_new_clusters=False,
return_cluster_maps=False,
stable_sort=False,
tmp_dir=gettempdir(),
save_uc_files=True,
HALT_EXEC=False):
""" Main convenience wrapper for using uclust to generate cluster files
A source fasta file is required for the fasta_filepath. This will be
sorted to be in order of longest to shortest length sequences. Following
this, the sorted fasta file is used to generate a cluster file in the
uclust (.uc) format. Next the .uc file is converted to cd-hit format
(.clstr). Finally this file is parsed and returned as a list of lists,
where each sublist a cluster of sequences. If an output_dir is
specified, the intermediate files will be preserved, otherwise all
files created are temporary and will be deleted at the end of this
function
The percent_ID parameter specifies the percent identity for a clusters,
i.e., if 99% were the parameter, all sequences that were 99% identical
would be grouped as a cluster.
"""
# Create readable intermediate filenames if they are to be kept
fasta_output_filepath = None
uc_output_filepath = None
cd_hit_filepath = None
if output_dir and not output_dir.endswith('/'):
output_dir += '/'
if save_uc_files:
uc_save_filepath = get_output_filepaths(
output_dir,
original_fasta_path)
else:
uc_save_filepath = None
sorted_fasta_filepath = ""
uc_filepath = ""
clstr_filepath = ""
# Error check in case any app controller fails
files_to_remove = []
try:
if not suppress_sort:
# Sort fasta input file from largest to smallest sequence
sort_fasta = uclust_fasta_sort_from_filepath(fasta_filepath,
output_filepath=fasta_output_filepath)
# Get sorted fasta name from application wrapper
sorted_fasta_filepath = sort_fasta['Output'].name
files_to_remove.append(sorted_fasta_filepath)
else:
sort_fasta = None
sorted_fasta_filepath = fasta_filepath
# Generate uclust cluster file (.uc format)
uclust_cluster = uclust_cluster_from_sorted_fasta_filepath(
sorted_fasta_filepath,
uc_save_filepath,
percent_ID=percent_ID,
max_accepts=max_accepts,
max_rejects=max_rejects,
stepwords=stepwords,
word_length=word_length,
optimal=optimal,
exact=exact,
suppress_sort=suppress_sort,
enable_rev_strand_matching=enable_rev_strand_matching,
subject_fasta_filepath=subject_fasta_filepath,
suppress_new_clusters=suppress_new_clusters,
stable_sort=stable_sort,
tmp_dir=tmp_dir,
HALT_EXEC=HALT_EXEC)
# Get cluster file name from application wrapper
remove_files(files_to_remove)
except ApplicationError:
remove_files(files_to_remove)
raise ApplicationError('Error running uclust. Possible causes are '
'unsupported version (current supported version is v1.2.22) is installed or '
'improperly formatted input file was provided')
except ApplicationNotFoundError:
remove_files(files_to_remove)
raise ApplicationNotFoundError('uclust not found, is it properly ' +
'installed?')
# Get list of lists for each cluster
clusters, failures, seeds = \
clusters_from_uc_file(uclust_cluster['ClusterFile'])
# Remove temp files unless user specifies output filepath
if not save_uc_files:
uclust_cluster.cleanUp()
if return_cluster_maps:
return clusters, failures, seeds
else:
return clusters.values(), failures, seeds | python | def get_clusters_from_fasta_filepath(
fasta_filepath,
original_fasta_path,
percent_ID=0.97,
max_accepts=1,
max_rejects=8,
stepwords=8,
word_length=8,
optimal=False,
exact=False,
suppress_sort=False,
output_dir=None,
enable_rev_strand_matching=False,
subject_fasta_filepath=None,
suppress_new_clusters=False,
return_cluster_maps=False,
stable_sort=False,
tmp_dir=gettempdir(),
save_uc_files=True,
HALT_EXEC=False):
""" Main convenience wrapper for using uclust to generate cluster files
A source fasta file is required for the fasta_filepath. This will be
sorted to be in order of longest to shortest length sequences. Following
this, the sorted fasta file is used to generate a cluster file in the
uclust (.uc) format. Next the .uc file is converted to cd-hit format
(.clstr). Finally this file is parsed and returned as a list of lists,
where each sublist a cluster of sequences. If an output_dir is
specified, the intermediate files will be preserved, otherwise all
files created are temporary and will be deleted at the end of this
function
The percent_ID parameter specifies the percent identity for a clusters,
i.e., if 99% were the parameter, all sequences that were 99% identical
would be grouped as a cluster.
"""
# Create readable intermediate filenames if they are to be kept
fasta_output_filepath = None
uc_output_filepath = None
cd_hit_filepath = None
if output_dir and not output_dir.endswith('/'):
output_dir += '/'
if save_uc_files:
uc_save_filepath = get_output_filepaths(
output_dir,
original_fasta_path)
else:
uc_save_filepath = None
sorted_fasta_filepath = ""
uc_filepath = ""
clstr_filepath = ""
# Error check in case any app controller fails
files_to_remove = []
try:
if not suppress_sort:
# Sort fasta input file from largest to smallest sequence
sort_fasta = uclust_fasta_sort_from_filepath(fasta_filepath,
output_filepath=fasta_output_filepath)
# Get sorted fasta name from application wrapper
sorted_fasta_filepath = sort_fasta['Output'].name
files_to_remove.append(sorted_fasta_filepath)
else:
sort_fasta = None
sorted_fasta_filepath = fasta_filepath
# Generate uclust cluster file (.uc format)
uclust_cluster = uclust_cluster_from_sorted_fasta_filepath(
sorted_fasta_filepath,
uc_save_filepath,
percent_ID=percent_ID,
max_accepts=max_accepts,
max_rejects=max_rejects,
stepwords=stepwords,
word_length=word_length,
optimal=optimal,
exact=exact,
suppress_sort=suppress_sort,
enable_rev_strand_matching=enable_rev_strand_matching,
subject_fasta_filepath=subject_fasta_filepath,
suppress_new_clusters=suppress_new_clusters,
stable_sort=stable_sort,
tmp_dir=tmp_dir,
HALT_EXEC=HALT_EXEC)
# Get cluster file name from application wrapper
remove_files(files_to_remove)
except ApplicationError:
remove_files(files_to_remove)
raise ApplicationError('Error running uclust. Possible causes are '
'unsupported version (current supported version is v1.2.22) is installed or '
'improperly formatted input file was provided')
except ApplicationNotFoundError:
remove_files(files_to_remove)
raise ApplicationNotFoundError('uclust not found, is it properly ' +
'installed?')
# Get list of lists for each cluster
clusters, failures, seeds = \
clusters_from_uc_file(uclust_cluster['ClusterFile'])
# Remove temp files unless user specifies output filepath
if not save_uc_files:
uclust_cluster.cleanUp()
if return_cluster_maps:
return clusters, failures, seeds
else:
return clusters.values(), failures, seeds | [
"def",
"get_clusters_from_fasta_filepath",
"(",
"fasta_filepath",
",",
"original_fasta_path",
",",
"percent_ID",
"=",
"0.97",
",",
"max_accepts",
"=",
"1",
",",
"max_rejects",
"=",
"8",
",",
"stepwords",
"=",
"8",
",",
"word_length",
"=",
"8",
",",
"optimal",
... | Main convenience wrapper for using uclust to generate cluster files
A source fasta file is required for the fasta_filepath. This will be
sorted to be in order of longest to shortest length sequences. Following
this, the sorted fasta file is used to generate a cluster file in the
uclust (.uc) format. Next the .uc file is converted to cd-hit format
(.clstr). Finally this file is parsed and returned as a list of lists,
where each sublist a cluster of sequences. If an output_dir is
specified, the intermediate files will be preserved, otherwise all
files created are temporary and will be deleted at the end of this
function
The percent_ID parameter specifies the percent identity for a clusters,
i.e., if 99% were the parameter, all sequences that were 99% identical
would be grouped as a cluster. | [
"Main",
"convenience",
"wrapper",
"for",
"using",
"uclust",
"to",
"generate",
"cluster",
"files"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/uclust.py#L491-L604 |
biocore/burrito-fillings | bfillings/uclust.py | Uclust._input_as_parameters | def _input_as_parameters(self, data):
""" Set the input path (a fasta filepath)
"""
# The list of values which can be passed on a per-run basis
allowed_values = ['--input', '--uc', '--fastapairs',
'--uc2clstr', '--output', '--mergesort']
unsupported_parameters = set(data.keys()) - set(allowed_values)
if unsupported_parameters:
raise ApplicationError(
"Unsupported parameter(s) passed when calling uclust: %s" %
' '.join(unsupported_parameters))
for v in allowed_values:
# turn the parameter off so subsequent runs are not
# affected by parameter settings from previous runs
self.Parameters[v].off()
if v in data:
# turn the parameter on if specified by the user
self.Parameters[v].on(data[v])
return '' | python | def _input_as_parameters(self, data):
""" Set the input path (a fasta filepath)
"""
# The list of values which can be passed on a per-run basis
allowed_values = ['--input', '--uc', '--fastapairs',
'--uc2clstr', '--output', '--mergesort']
unsupported_parameters = set(data.keys()) - set(allowed_values)
if unsupported_parameters:
raise ApplicationError(
"Unsupported parameter(s) passed when calling uclust: %s" %
' '.join(unsupported_parameters))
for v in allowed_values:
# turn the parameter off so subsequent runs are not
# affected by parameter settings from previous runs
self.Parameters[v].off()
if v in data:
# turn the parameter on if specified by the user
self.Parameters[v].on(data[v])
return '' | [
"def",
"_input_as_parameters",
"(",
"self",
",",
"data",
")",
":",
"# The list of values which can be passed on a per-run basis",
"allowed_values",
"=",
"[",
"'--input'",
",",
"'--uc'",
",",
"'--fastapairs'",
",",
"'--uc2clstr'",
",",
"'--output'",
",",
"'--mergesort'",
... | Set the input path (a fasta filepath) | [
"Set",
"the",
"input",
"path",
"(",
"a",
"fasta",
"filepath",
")"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/uclust.py#L127-L148 |
biocore/burrito-fillings | bfillings/uclust.py | Uclust._get_result_paths | def _get_result_paths(self, data):
""" Set the result paths """
result = {}
result['Output'] = ResultPath(
Path=self.Parameters['--output'].Value,
IsWritten=self.Parameters['--output'].isOn())
result['ClusterFile'] = ResultPath(
Path=self.Parameters['--uc'].Value,
IsWritten=self.Parameters['--uc'].isOn())
result['PairwiseAlignments'] = ResultPath(
Path=self.Parameters['--fastapairs'].Value,
IsWritten=self.Parameters['--fastapairs'].isOn())
return result | python | def _get_result_paths(self, data):
""" Set the result paths """
result = {}
result['Output'] = ResultPath(
Path=self.Parameters['--output'].Value,
IsWritten=self.Parameters['--output'].isOn())
result['ClusterFile'] = ResultPath(
Path=self.Parameters['--uc'].Value,
IsWritten=self.Parameters['--uc'].isOn())
result['PairwiseAlignments'] = ResultPath(
Path=self.Parameters['--fastapairs'].Value,
IsWritten=self.Parameters['--fastapairs'].isOn())
return result | [
"def",
"_get_result_paths",
"(",
"self",
",",
"data",
")",
":",
"result",
"=",
"{",
"}",
"result",
"[",
"'Output'",
"]",
"=",
"ResultPath",
"(",
"Path",
"=",
"self",
".",
"Parameters",
"[",
"'--output'",
"]",
".",
"Value",
",",
"IsWritten",
"=",
"self"... | Set the result paths | [
"Set",
"the",
"result",
"paths"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/uclust.py#L150-L167 |
EndurantDevs/webargs-sanic | examples/user_simple_storage/extentions/helpers.py | format_error | def format_error(status=None, title=None, detail=None, code=None):
'''Formatting JSON API Error Object
Constructing an error object based on JSON API standard
ref: http://jsonapi.org/format/#error-objects
Args:
status: Can be a http status codes
title: A summary of error
detail: A descriptive error message
code: Application error codes (if any)
Returns:
A dictionary contains of status, title, detail and code
'''
error = {}
error.update({ 'title': title })
if status is not None:
error.update({ 'status': status })
if detail is not None:
error.update({ 'detail': detail })
if code is not None:
error.update({ 'code': code })
return error | python | def format_error(status=None, title=None, detail=None, code=None):
'''Formatting JSON API Error Object
Constructing an error object based on JSON API standard
ref: http://jsonapi.org/format/#error-objects
Args:
status: Can be a http status codes
title: A summary of error
detail: A descriptive error message
code: Application error codes (if any)
Returns:
A dictionary contains of status, title, detail and code
'''
error = {}
error.update({ 'title': title })
if status is not None:
error.update({ 'status': status })
if detail is not None:
error.update({ 'detail': detail })
if code is not None:
error.update({ 'code': code })
return error | [
"def",
"format_error",
"(",
"status",
"=",
"None",
",",
"title",
"=",
"None",
",",
"detail",
"=",
"None",
",",
"code",
"=",
"None",
")",
":",
"error",
"=",
"{",
"}",
"error",
".",
"update",
"(",
"{",
"'title'",
":",
"title",
"}",
")",
"if",
"stat... | Formatting JSON API Error Object
Constructing an error object based on JSON API standard
ref: http://jsonapi.org/format/#error-objects
Args:
status: Can be a http status codes
title: A summary of error
detail: A descriptive error message
code: Application error codes (if any)
Returns:
A dictionary contains of status, title, detail and code | [
"Formatting",
"JSON",
"API",
"Error",
"Object",
"Constructing",
"an",
"error",
"object",
"based",
"on",
"JSON",
"API",
"standard",
"ref",
":",
"http",
":",
"//",
"jsonapi",
".",
"org",
"/",
"format",
"/",
"#error",
"-",
"objects",
"Args",
":",
"status",
... | train | https://github.com/EndurantDevs/webargs-sanic/blob/8861a3b7d16d43a0b7e6669115eb93b0553f1b63/examples/user_simple_storage/extentions/helpers.py#L1-L25 |
EndurantDevs/webargs-sanic | examples/user_simple_storage/extentions/helpers.py | return_an_error | def return_an_error(*args):
'''List of errors
Put all errors into a list of errors
ref: http://jsonapi.org/format/#errors
Args:
*args: A tuple contain errors
Returns:
A dictionary contains a list of errors
'''
list_errors = []
list_errors.extend(list(args))
errors = { 'errors': list_errors }
return errors | python | def return_an_error(*args):
'''List of errors
Put all errors into a list of errors
ref: http://jsonapi.org/format/#errors
Args:
*args: A tuple contain errors
Returns:
A dictionary contains a list of errors
'''
list_errors = []
list_errors.extend(list(args))
errors = { 'errors': list_errors }
return errors | [
"def",
"return_an_error",
"(",
"*",
"args",
")",
":",
"list_errors",
"=",
"[",
"]",
"list_errors",
".",
"extend",
"(",
"list",
"(",
"args",
")",
")",
"errors",
"=",
"{",
"'errors'",
":",
"list_errors",
"}",
"return",
"errors"
] | List of errors
Put all errors into a list of errors
ref: http://jsonapi.org/format/#errors
Args:
*args: A tuple contain errors
Returns:
A dictionary contains a list of errors | [
"List",
"of",
"errors",
"Put",
"all",
"errors",
"into",
"a",
"list",
"of",
"errors",
"ref",
":",
"http",
":",
"//",
"jsonapi",
".",
"org",
"/",
"format",
"/",
"#errors",
"Args",
":",
"*",
"args",
":",
"A",
"tuple",
"contain",
"errors",
"Returns",
":"... | train | https://github.com/EndurantDevs/webargs-sanic/blob/8861a3b7d16d43a0b7e6669115eb93b0553f1b63/examples/user_simple_storage/extentions/helpers.py#L27-L40 |
bitlabstudio/django-document-library | document_library/south_migrations/0013_transfer_is_published_from_document_to_title.py | Migration.forwards | def forwards(self, orm):
"Write your forwards methods here."
for doc in orm['document_library.Document'].objects.all():
for title in doc.documenttitle_set.all():
title.is_published = doc.is_published
title.save() | python | def forwards(self, orm):
"Write your forwards methods here."
for doc in orm['document_library.Document'].objects.all():
for title in doc.documenttitle_set.all():
title.is_published = doc.is_published
title.save() | [
"def",
"forwards",
"(",
"self",
",",
"orm",
")",
":",
"for",
"doc",
"in",
"orm",
"[",
"'document_library.Document'",
"]",
".",
"objects",
".",
"all",
"(",
")",
":",
"for",
"title",
"in",
"doc",
".",
"documenttitle_set",
".",
"all",
"(",
")",
":",
"ti... | Write your forwards methods here. | [
"Write",
"your",
"forwards",
"methods",
"here",
"."
] | train | https://github.com/bitlabstudio/django-document-library/blob/508737277455f182e81780cfca8d8eceb989a45b/document_library/south_migrations/0013_transfer_is_published_from_document_to_title.py#L24-L29 |
kejbaly2/metrique | metrique/cubes/sqldata/generic.py | Generic._activity_import_doc | def _activity_import_doc(self, time_doc, activities):
'''
Import activities for a single document into timeline.
'''
batch_updates = [time_doc]
# We want to consider only activities that happend before time_doc
# do not move this, because time_doc._start changes
# time_doc['_start'] is a timestamp, whereas act[0] is a datetime
# we need to be sure to convert act[0] (when) to timestamp!
td_start = time_doc['_start']
activities = filter(lambda act: (act[0] < td_start and
act[1] in time_doc), activities)
creation_field = self.lconfig.get('cfield')
# make sure that activities are sorted by when descending
activities.sort(reverse=True, key=lambda o: o[0])
new_doc = {}
for when, field, removed, added in activities:
last_doc = batch_updates.pop()
# check if this activity happened at the same time as the last one,
# if it did then we need to group them together
if last_doc['_end'] == when:
new_doc = deepcopy(last_doc)
last_doc = batch_updates.pop()
else:
new_doc = deepcopy(last_doc)
new_doc['_start'] = when
new_doc['_end'] = when
last_doc['_start'] = when
last_val = last_doc[field]
new_val, inconsistent = self._activity_backwards(new_doc[field],
removed, added)
new_doc[field] = new_val
# Check if the object has the correct field value.
if inconsistent:
self._log_inconsistency(last_doc, last_val, field,
removed, added, when)
new_doc['_e'] = {} if not new_doc.get('_e') else new_doc['_e']
# set curreupted field value to the the value that was added
# and continue processing as if that issue didn't exist
new_doc['_e'][field] = added
# Add the objects to the batch
batch_updates.extend([last_doc, new_doc])
# try to set the _start of the first version to the creation time
try:
# set start to creation time if available
last_doc = batch_updates[-1]
if creation_field:
# again, we expect _start to be epoch float...
creation_ts = dt2ts(last_doc[creation_field])
if creation_ts < last_doc['_start']:
last_doc['_start'] = creation_ts
elif len(batch_updates) == 1:
# we have only one version, that we did not change
return []
else:
pass # leave as-is
except Exception as e:
logger.error('Error updating creation time; %s' % e)
return batch_updates | python | def _activity_import_doc(self, time_doc, activities):
'''
Import activities for a single document into timeline.
'''
batch_updates = [time_doc]
# We want to consider only activities that happend before time_doc
# do not move this, because time_doc._start changes
# time_doc['_start'] is a timestamp, whereas act[0] is a datetime
# we need to be sure to convert act[0] (when) to timestamp!
td_start = time_doc['_start']
activities = filter(lambda act: (act[0] < td_start and
act[1] in time_doc), activities)
creation_field = self.lconfig.get('cfield')
# make sure that activities are sorted by when descending
activities.sort(reverse=True, key=lambda o: o[0])
new_doc = {}
for when, field, removed, added in activities:
last_doc = batch_updates.pop()
# check if this activity happened at the same time as the last one,
# if it did then we need to group them together
if last_doc['_end'] == when:
new_doc = deepcopy(last_doc)
last_doc = batch_updates.pop()
else:
new_doc = deepcopy(last_doc)
new_doc['_start'] = when
new_doc['_end'] = when
last_doc['_start'] = when
last_val = last_doc[field]
new_val, inconsistent = self._activity_backwards(new_doc[field],
removed, added)
new_doc[field] = new_val
# Check if the object has the correct field value.
if inconsistent:
self._log_inconsistency(last_doc, last_val, field,
removed, added, when)
new_doc['_e'] = {} if not new_doc.get('_e') else new_doc['_e']
# set curreupted field value to the the value that was added
# and continue processing as if that issue didn't exist
new_doc['_e'][field] = added
# Add the objects to the batch
batch_updates.extend([last_doc, new_doc])
# try to set the _start of the first version to the creation time
try:
# set start to creation time if available
last_doc = batch_updates[-1]
if creation_field:
# again, we expect _start to be epoch float...
creation_ts = dt2ts(last_doc[creation_field])
if creation_ts < last_doc['_start']:
last_doc['_start'] = creation_ts
elif len(batch_updates) == 1:
# we have only one version, that we did not change
return []
else:
pass # leave as-is
except Exception as e:
logger.error('Error updating creation time; %s' % e)
return batch_updates | [
"def",
"_activity_import_doc",
"(",
"self",
",",
"time_doc",
",",
"activities",
")",
":",
"batch_updates",
"=",
"[",
"time_doc",
"]",
"# We want to consider only activities that happend before time_doc",
"# do not move this, because time_doc._start changes",
"# time_doc['_start'] i... | Import activities for a single document into timeline. | [
"Import",
"activities",
"for",
"a",
"single",
"document",
"into",
"timeline",
"."
] | train | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/cubes/sqldata/generic.py#L125-L184 |
kejbaly2/metrique | metrique/cubes/sqldata/generic.py | Generic.get_changed_oids | def get_changed_oids(self, last_update=None):
'''
Returns a list of object ids of those objects that have changed since
`mtime`. This method expects that the changed objects can be
determined based on the `delta_mtime` property of the cube which
specifies the field name that carries the time of the last change.
This method is expected to be overriden in the cube if it is not
possible to use a single field to determine the time of the change and
if another approach of determining the oids is available. In such
cubes the `delta_mtime` property is expected to be set to `True`.
If `delta_mtime` evaluates to False then this method is not expected
to be used.
:param mtime: datetime string used as 'change since date'
'''
mtime_columns = self.lconfig.get('delta_mtime', [])
if not (mtime_columns and last_update):
return []
mtime_columns = str2list(mtime_columns)
where = []
for _column in mtime_columns:
_sql = "%s >= %s" % (_column, last_update)
where.append(_sql)
return self.sql_get_oids(where) | python | def get_changed_oids(self, last_update=None):
'''
Returns a list of object ids of those objects that have changed since
`mtime`. This method expects that the changed objects can be
determined based on the `delta_mtime` property of the cube which
specifies the field name that carries the time of the last change.
This method is expected to be overriden in the cube if it is not
possible to use a single field to determine the time of the change and
if another approach of determining the oids is available. In such
cubes the `delta_mtime` property is expected to be set to `True`.
If `delta_mtime` evaluates to False then this method is not expected
to be used.
:param mtime: datetime string used as 'change since date'
'''
mtime_columns = self.lconfig.get('delta_mtime', [])
if not (mtime_columns and last_update):
return []
mtime_columns = str2list(mtime_columns)
where = []
for _column in mtime_columns:
_sql = "%s >= %s" % (_column, last_update)
where.append(_sql)
return self.sql_get_oids(where) | [
"def",
"get_changed_oids",
"(",
"self",
",",
"last_update",
"=",
"None",
")",
":",
"mtime_columns",
"=",
"self",
".",
"lconfig",
".",
"get",
"(",
"'delta_mtime'",
",",
"[",
"]",
")",
"if",
"not",
"(",
"mtime_columns",
"and",
"last_update",
")",
":",
"ret... | Returns a list of object ids of those objects that have changed since
`mtime`. This method expects that the changed objects can be
determined based on the `delta_mtime` property of the cube which
specifies the field name that carries the time of the last change.
This method is expected to be overriden in the cube if it is not
possible to use a single field to determine the time of the change and
if another approach of determining the oids is available. In such
cubes the `delta_mtime` property is expected to be set to `True`.
If `delta_mtime` evaluates to False then this method is not expected
to be used.
:param mtime: datetime string used as 'change since date' | [
"Returns",
"a",
"list",
"of",
"object",
"ids",
"of",
"those",
"objects",
"that",
"have",
"changed",
"since",
"mtime",
".",
"This",
"method",
"expects",
"that",
"the",
"changed",
"objects",
"can",
"be",
"determined",
"based",
"on",
"the",
"delta_mtime",
"prop... | train | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/cubes/sqldata/generic.py#L228-L253 |
kejbaly2/metrique | metrique/cubes/sqldata/generic.py | Generic.fieldmap | def fieldmap(self):
'''
Dictionary of field_id: field_name, as defined in self.fields property
'''
if hasattr(self, '_sql_fieldmap') and self._sql_fieldmap:
fieldmap = self._sql_fieldmap
else:
fieldmap = defaultdict(str)
fields = copy(self.fields)
for field, opts in fields.iteritems():
field_id = opts.get('what')
if field_id is not None:
fieldmap[field_id] = field
self._sql_fieldmap = fieldmap
return fieldmap | python | def fieldmap(self):
'''
Dictionary of field_id: field_name, as defined in self.fields property
'''
if hasattr(self, '_sql_fieldmap') and self._sql_fieldmap:
fieldmap = self._sql_fieldmap
else:
fieldmap = defaultdict(str)
fields = copy(self.fields)
for field, opts in fields.iteritems():
field_id = opts.get('what')
if field_id is not None:
fieldmap[field_id] = field
self._sql_fieldmap = fieldmap
return fieldmap | [
"def",
"fieldmap",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_sql_fieldmap'",
")",
"and",
"self",
".",
"_sql_fieldmap",
":",
"fieldmap",
"=",
"self",
".",
"_sql_fieldmap",
"else",
":",
"fieldmap",
"=",
"defaultdict",
"(",
"str",
")",
"f... | Dictionary of field_id: field_name, as defined in self.fields property | [
"Dictionary",
"of",
"field_id",
":",
"field_name",
"as",
"defined",
"in",
"self",
".",
"fields",
"property"
] | train | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/cubes/sqldata/generic.py#L272-L286 |
kejbaly2/metrique | metrique/cubes/sqldata/generic.py | Generic.get_objects | def get_objects(self, force=None, last_update=None, flush=False):
'''
Extract routine for SQL based cubes.
:param force:
for querying for all objects (True) or only those passed in as list
:param last_update: manual override for 'changed since date'
'''
return self._run_object_import(force=force, last_update=last_update,
flush=flush, full_history=False) | python | def get_objects(self, force=None, last_update=None, flush=False):
'''
Extract routine for SQL based cubes.
:param force:
for querying for all objects (True) or only those passed in as list
:param last_update: manual override for 'changed since date'
'''
return self._run_object_import(force=force, last_update=last_update,
flush=flush, full_history=False) | [
"def",
"get_objects",
"(",
"self",
",",
"force",
"=",
"None",
",",
"last_update",
"=",
"None",
",",
"flush",
"=",
"False",
")",
":",
"return",
"self",
".",
"_run_object_import",
"(",
"force",
"=",
"force",
",",
"last_update",
"=",
"last_update",
",",
"fl... | Extract routine for SQL based cubes.
:param force:
for querying for all objects (True) or only those passed in as list
:param last_update: manual override for 'changed since date' | [
"Extract",
"routine",
"for",
"SQL",
"based",
"cubes",
"."
] | train | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/cubes/sqldata/generic.py#L322-L331 |
kejbaly2/metrique | metrique/cubes/sqldata/generic.py | Generic.get_new_oids | def get_new_oids(self):
'''
Returns a list of unique oids that have not been extracted yet.
Essentially, a diff of distinct oids in the source database
compared to cube.
'''
table = self.lconfig.get('table')
_oid = self.lconfig.get('_oid')
if is_array(_oid):
_oid = _oid[0] # get the db column, not the field alias
last_id = self.container.get_last_field(field='_oid')
ids = []
if last_id:
try: # try to convert to integer... if not, assume unicode value
last_id = float(last_id)
where = "%s.%s > %s" % (table, _oid, last_id)
except (TypeError, ValueError):
where = "%s.%s > '%s'" % (table, _oid, last_id)
ids = self.sql_get_oids(where)
return ids | python | def get_new_oids(self):
'''
Returns a list of unique oids that have not been extracted yet.
Essentially, a diff of distinct oids in the source database
compared to cube.
'''
table = self.lconfig.get('table')
_oid = self.lconfig.get('_oid')
if is_array(_oid):
_oid = _oid[0] # get the db column, not the field alias
last_id = self.container.get_last_field(field='_oid')
ids = []
if last_id:
try: # try to convert to integer... if not, assume unicode value
last_id = float(last_id)
where = "%s.%s > %s" % (table, _oid, last_id)
except (TypeError, ValueError):
where = "%s.%s > '%s'" % (table, _oid, last_id)
ids = self.sql_get_oids(where)
return ids | [
"def",
"get_new_oids",
"(",
"self",
")",
":",
"table",
"=",
"self",
".",
"lconfig",
".",
"get",
"(",
"'table'",
")",
"_oid",
"=",
"self",
".",
"lconfig",
".",
"get",
"(",
"'_oid'",
")",
"if",
"is_array",
"(",
"_oid",
")",
":",
"_oid",
"=",
"_oid",
... | Returns a list of unique oids that have not been extracted yet.
Essentially, a diff of distinct oids in the source database
compared to cube. | [
"Returns",
"a",
"list",
"of",
"unique",
"oids",
"that",
"have",
"not",
"been",
"extracted",
"yet",
"."
] | train | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/cubes/sqldata/generic.py#L344-L364 |
kejbaly2/metrique | metrique/cubes/sqldata/generic.py | Generic.get_full_history | def get_full_history(self, force=None, last_update=None, flush=False):
'''
Fields change depending on when you run activity_import,
such as "last_updated" type fields which don't have activity
being tracked, which means we'll always end up with different
hash values, so we need to always remove all existing object
states and import fresh
'''
return self._run_object_import(force=force, last_update=last_update,
flush=flush, full_history=True) | python | def get_full_history(self, force=None, last_update=None, flush=False):
'''
Fields change depending on when you run activity_import,
such as "last_updated" type fields which don't have activity
being tracked, which means we'll always end up with different
hash values, so we need to always remove all existing object
states and import fresh
'''
return self._run_object_import(force=force, last_update=last_update,
flush=flush, full_history=True) | [
"def",
"get_full_history",
"(",
"self",
",",
"force",
"=",
"None",
",",
"last_update",
"=",
"None",
",",
"flush",
"=",
"False",
")",
":",
"return",
"self",
".",
"_run_object_import",
"(",
"force",
"=",
"force",
",",
"last_update",
"=",
"last_update",
",",
... | Fields change depending on when you run activity_import,
such as "last_updated" type fields which don't have activity
being tracked, which means we'll always end up with different
hash values, so we need to always remove all existing object
states and import fresh | [
"Fields",
"change",
"depending",
"on",
"when",
"you",
"run",
"activity_import",
"such",
"as",
"last_updated",
"type",
"fields",
"which",
"don",
"t",
"have",
"activity",
"being",
"tracked",
"which",
"means",
"we",
"ll",
"always",
"end",
"up",
"with",
"different... | train | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/cubes/sqldata/generic.py#L366-L375 |
kejbaly2/metrique | metrique/cubes/sqldata/generic.py | Generic.sql_get_oids | def sql_get_oids(self, where=None):
'''
Query source database for a distinct list of oids.
'''
table = self.lconfig.get('table')
db = self.lconfig.get('db_schema_name') or self.lconfig.get('db')
_oid = self.lconfig.get('_oid')
if is_array(_oid):
_oid = _oid[0] # get the db column, not the field alias
sql = 'SELECT DISTINCT %s.%s FROM %s.%s' % (table, _oid, db, table)
if where:
where = [where] if isinstance(where, basestring) else list(where)
sql += ' WHERE %s' % ' OR '.join(where)
result = sorted([r[_oid] for r in self._load_sql(sql)])
return result | python | def sql_get_oids(self, where=None):
'''
Query source database for a distinct list of oids.
'''
table = self.lconfig.get('table')
db = self.lconfig.get('db_schema_name') or self.lconfig.get('db')
_oid = self.lconfig.get('_oid')
if is_array(_oid):
_oid = _oid[0] # get the db column, not the field alias
sql = 'SELECT DISTINCT %s.%s FROM %s.%s' % (table, _oid, db, table)
if where:
where = [where] if isinstance(where, basestring) else list(where)
sql += ' WHERE %s' % ' OR '.join(where)
result = sorted([r[_oid] for r in self._load_sql(sql)])
return result | [
"def",
"sql_get_oids",
"(",
"self",
",",
"where",
"=",
"None",
")",
":",
"table",
"=",
"self",
".",
"lconfig",
".",
"get",
"(",
"'table'",
")",
"db",
"=",
"self",
".",
"lconfig",
".",
"get",
"(",
"'db_schema_name'",
")",
"or",
"self",
".",
"lconfig",... | Query source database for a distinct list of oids. | [
"Query",
"source",
"database",
"for",
"a",
"distinct",
"list",
"of",
"oids",
"."
] | train | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/cubes/sqldata/generic.py#L494-L508 |
kejbaly2/metrique | metrique/metrique.py | Metrique.get_objects | def get_objects(self, flush=False, autosnap=True, **kwargs):
'''
Main API method for sub-classed cubes to override for the
generation of the objects which are to (potentially) be added
to the cube (assuming no duplicates)
'''
logger.debug('Running get_objects(flush=%s, autosnap=%s, %s)' % (
flush, autosnap, kwargs))
if flush:
s = time()
result = self.flush(autosnap=autosnap, **kwargs)
diff = time() - s
logger.debug("Flush complete (%ss)" % int(diff))
return result
else:
return self | python | def get_objects(self, flush=False, autosnap=True, **kwargs):
'''
Main API method for sub-classed cubes to override for the
generation of the objects which are to (potentially) be added
to the cube (assuming no duplicates)
'''
logger.debug('Running get_objects(flush=%s, autosnap=%s, %s)' % (
flush, autosnap, kwargs))
if flush:
s = time()
result = self.flush(autosnap=autosnap, **kwargs)
diff = time() - s
logger.debug("Flush complete (%ss)" % int(diff))
return result
else:
return self | [
"def",
"get_objects",
"(",
"self",
",",
"flush",
"=",
"False",
",",
"autosnap",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"'Running get_objects(flush=%s, autosnap=%s, %s)'",
"%",
"(",
"flush",
",",
"autosnap",
",",
"kwargs"... | Main API method for sub-classed cubes to override for the
generation of the objects which are to (potentially) be added
to the cube (assuming no duplicates) | [
"Main",
"API",
"method",
"for",
"sub",
"-",
"classed",
"cubes",
"to",
"override",
"for",
"the",
"generation",
"of",
"the",
"objects",
"which",
"are",
"to",
"(",
"potentially",
")",
"be",
"added",
"to",
"the",
"cube",
"(",
"assuming",
"no",
"duplicates",
... | train | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/metrique.py#L315-L330 |
kejbaly2/metrique | metrique/metrique.py | Metrique.get_cube | def get_cube(self, cube, init=True, name=None, copy_config=True, **kwargs):
'''wrapper for :func:`metrique.utils.get_cube`
Locates and loads a metrique cube
:param cube: name of cube to load
:param init: (bool) initialize cube before returning?
:param name: override the name of the cube
:param copy_config: apply config of calling cube to new?
Implies init=True.
:param kwargs: additional :func:`metrique.utils.get_cube`
'''
name = name or cube
config = copy(self.config) if copy_config else {}
config_file = self.config_file
container = type(self.container)
container_config = copy(self.container_config)
proxy = str(type(self.proxy))
return get_cube(cube=cube, init=init, name=name, config=config,
config_file=config_file, container=container,
container_config=container_config,
proxy=proxy, proxy_config=self.proxy_config, **kwargs) | python | def get_cube(self, cube, init=True, name=None, copy_config=True, **kwargs):
'''wrapper for :func:`metrique.utils.get_cube`
Locates and loads a metrique cube
:param cube: name of cube to load
:param init: (bool) initialize cube before returning?
:param name: override the name of the cube
:param copy_config: apply config of calling cube to new?
Implies init=True.
:param kwargs: additional :func:`metrique.utils.get_cube`
'''
name = name or cube
config = copy(self.config) if copy_config else {}
config_file = self.config_file
container = type(self.container)
container_config = copy(self.container_config)
proxy = str(type(self.proxy))
return get_cube(cube=cube, init=init, name=name, config=config,
config_file=config_file, container=container,
container_config=container_config,
proxy=proxy, proxy_config=self.proxy_config, **kwargs) | [
"def",
"get_cube",
"(",
"self",
",",
"cube",
",",
"init",
"=",
"True",
",",
"name",
"=",
"None",
",",
"copy_config",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"name",
"or",
"cube",
"config",
"=",
"copy",
"(",
"self",
".",
"conf... | wrapper for :func:`metrique.utils.get_cube`
Locates and loads a metrique cube
:param cube: name of cube to load
:param init: (bool) initialize cube before returning?
:param name: override the name of the cube
:param copy_config: apply config of calling cube to new?
Implies init=True.
:param kwargs: additional :func:`metrique.utils.get_cube` | [
"wrapper",
"for",
":",
"func",
":",
"metrique",
".",
"utils",
".",
"get_cube"
] | train | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/metrique.py#L332-L353 |
biocore/burrito-fillings | bfillings/pplacer.py | insert_sequences_into_tree | def insert_sequences_into_tree(aln, moltype, params={},
write_log=True):
"""Returns a tree from Alignment object aln.
aln: an xxx.Alignment object, or data that can be used to build one.
moltype: cogent.core.moltype.MolType object
params: dict of parameters to pass in to the RAxML app controller.
The result will be an xxx.Alignment object, or None if tree fails.
"""
# convert aln to phy since seq_names need fixed to run through pplacer
new_aln=get_align_for_phylip(StringIO(aln))
# convert aln to fasta in case it is not already a fasta file
aln2 = Alignment(new_aln)
seqs = aln2.toFasta()
ih = '_input_as_multiline_string'
pplacer_app = Pplacer(params=params,
InputHandler=ih,
WorkingDir=None,
SuppressStderr=False,
SuppressStdout=False)
pplacer_result = pplacer_app(seqs)
# write a log file
if write_log:
log_fp = join(params["--out-dir"],'log_pplacer_' + \
split(get_tmp_filename())[-1])
log_file=open(log_fp,'w')
log_file.write(pplacer_result['StdOut'].read())
log_file.close()
# use guppy to convert json file into a placement tree
guppy_params={'tog':None}
new_tree=build_tree_from_json_using_params(pplacer_result['json'].name, \
output_dir=params['--out-dir'], \
params=guppy_params)
pplacer_result.cleanUp()
return new_tree | python | def insert_sequences_into_tree(aln, moltype, params={},
write_log=True):
"""Returns a tree from Alignment object aln.
aln: an xxx.Alignment object, or data that can be used to build one.
moltype: cogent.core.moltype.MolType object
params: dict of parameters to pass in to the RAxML app controller.
The result will be an xxx.Alignment object, or None if tree fails.
"""
# convert aln to phy since seq_names need fixed to run through pplacer
new_aln=get_align_for_phylip(StringIO(aln))
# convert aln to fasta in case it is not already a fasta file
aln2 = Alignment(new_aln)
seqs = aln2.toFasta()
ih = '_input_as_multiline_string'
pplacer_app = Pplacer(params=params,
InputHandler=ih,
WorkingDir=None,
SuppressStderr=False,
SuppressStdout=False)
pplacer_result = pplacer_app(seqs)
# write a log file
if write_log:
log_fp = join(params["--out-dir"],'log_pplacer_' + \
split(get_tmp_filename())[-1])
log_file=open(log_fp,'w')
log_file.write(pplacer_result['StdOut'].read())
log_file.close()
# use guppy to convert json file into a placement tree
guppy_params={'tog':None}
new_tree=build_tree_from_json_using_params(pplacer_result['json'].name, \
output_dir=params['--out-dir'], \
params=guppy_params)
pplacer_result.cleanUp()
return new_tree | [
"def",
"insert_sequences_into_tree",
"(",
"aln",
",",
"moltype",
",",
"params",
"=",
"{",
"}",
",",
"write_log",
"=",
"True",
")",
":",
"# convert aln to phy since seq_names need fixed to run through pplacer",
"new_aln",
"=",
"get_align_for_phylip",
"(",
"StringIO",
"("... | Returns a tree from Alignment object aln.
aln: an xxx.Alignment object, or data that can be used to build one.
moltype: cogent.core.moltype.MolType object
params: dict of parameters to pass in to the RAxML app controller.
The result will be an xxx.Alignment object, or None if tree fails. | [
"Returns",
"a",
"tree",
"from",
"Alignment",
"object",
"aln",
"."
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/pplacer.py#L153-L201 |
biocore/burrito-fillings | bfillings/pplacer.py | Pplacer.getTmpFilename | def getTmpFilename(self, tmp_dir="/tmp",prefix='tmp',suffix='.fasta',\
include_class_id=False,result_constructor=FilePath):
""" Define Tmp filename to contain .fasta suffix, since pplacer requires
the suffix to be .fasta """
return super(Pplacer,self).getTmpFilename(tmp_dir=tmp_dir,
prefix=prefix,
suffix=suffix,
include_class_id=include_class_id,
result_constructor=result_constructor) | python | def getTmpFilename(self, tmp_dir="/tmp",prefix='tmp',suffix='.fasta',\
include_class_id=False,result_constructor=FilePath):
""" Define Tmp filename to contain .fasta suffix, since pplacer requires
the suffix to be .fasta """
return super(Pplacer,self).getTmpFilename(tmp_dir=tmp_dir,
prefix=prefix,
suffix=suffix,
include_class_id=include_class_id,
result_constructor=result_constructor) | [
"def",
"getTmpFilename",
"(",
"self",
",",
"tmp_dir",
"=",
"\"/tmp\"",
",",
"prefix",
"=",
"'tmp'",
",",
"suffix",
"=",
"'.fasta'",
",",
"include_class_id",
"=",
"False",
",",
"result_constructor",
"=",
"FilePath",
")",
":",
"return",
"super",
"(",
"Pplacer"... | Define Tmp filename to contain .fasta suffix, since pplacer requires
the suffix to be .fasta | [
"Define",
"Tmp",
"filename",
"to",
"contain",
".",
"fasta",
"suffix",
"since",
"pplacer",
"requires",
"the",
"suffix",
"to",
"be",
".",
"fasta"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/pplacer.py#L127-L136 |
biocore/burrito-fillings | bfillings/pplacer.py | Pplacer._get_result_paths | def _get_result_paths(self,data):
""" Define the output filepaths """
output_dir = self.Parameters['--out-dir'].Value
result = {}
result['json'] = ResultPath(Path=join(output_dir,
splitext(split(self._input_filename)[-1])[0] + \
'.jplace'))
return result | python | def _get_result_paths(self,data):
""" Define the output filepaths """
output_dir = self.Parameters['--out-dir'].Value
result = {}
result['json'] = ResultPath(Path=join(output_dir,
splitext(split(self._input_filename)[-1])[0] + \
'.jplace'))
return result | [
"def",
"_get_result_paths",
"(",
"self",
",",
"data",
")",
":",
"output_dir",
"=",
"self",
".",
"Parameters",
"[",
"'--out-dir'",
"]",
".",
"Value",
"result",
"=",
"{",
"}",
"result",
"[",
"'json'",
"]",
"=",
"ResultPath",
"(",
"Path",
"=",
"join",
"("... | Define the output filepaths | [
"Define",
"the",
"output",
"filepaths"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/pplacer.py#L144-L151 |
rstoneback/pysatMagVect | pysatMagVect/satellite.py | add_mag_drift_unit_vectors_ecef | def add_mag_drift_unit_vectors_ecef(inst, steps=None, max_steps=40000, step_size=10.,
ref_height=120.):
"""Adds unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in ECEF coordinates.
Parameters
----------
inst : pysat.Instrument
Instrument object that will get unit vectors
max_steps : int
Maximum number of steps allowed for field line tracing
step_size : float
Maximum step size (km) allowed when field line tracing
ref_height : float
Altitude used as cutoff for labeling a field line location a footpoint
Returns
-------
None
unit vectors are added to the passed Instrument object with a naming
scheme:
'unit_zon_ecef_*' : unit zonal vector, component along ECEF-(X,Y,or Z)
'unit_fa_ecef_*' : unit field-aligned vector, component along ECEF-(X,Y,or Z)
'unit_mer_ecef_*' : unit meridional vector, component along ECEF-(X,Y,or Z)
"""
# add unit vectors for magnetic drifts in ecef coordinates
zvx, zvy, zvz, bx, by, bz, mx, my, mz = calculate_mag_drift_unit_vectors_ecef(inst['latitude'],
inst['longitude'], inst['altitude'], inst.data.index,
steps=steps, max_steps=max_steps, step_size=step_size, ref_height=ref_height)
inst['unit_zon_ecef_x'] = zvx
inst['unit_zon_ecef_y'] = zvy
inst['unit_zon_ecef_z'] = zvz
inst['unit_fa_ecef_x'] = bx
inst['unit_fa_ecef_y'] = by
inst['unit_fa_ecef_z'] = bz
inst['unit_mer_ecef_x'] = mx
inst['unit_mer_ecef_y'] = my
inst['unit_mer_ecef_z'] = mz
inst.meta['unit_zon_ecef_x'] = {'long_name': 'Zonal unit vector along ECEF-x',
'desc': 'Zonal unit vector along ECEF-x',
'label': 'Zonal unit vector along ECEF-x',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Zonal unit vector along ECEF-x',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_zon_ecef_y'] = {'long_name': 'Zonal unit vector along ECEF-y',
'desc': 'Zonal unit vector along ECEF-y',
'label': 'Zonal unit vector along ECEF-y',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Zonal unit vector along ECEF-y',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_zon_ecef_z'] = {'long_name': 'Zonal unit vector along ECEF-z',
'desc': 'Zonal unit vector along ECEF-z',
'label': 'Zonal unit vector along ECEF-z',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Zonal unit vector along ECEF-z',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_fa_ecef_x'] = {'long_name': 'Field-aligned unit vector along ECEF-x',
'desc': 'Field-aligned unit vector along ECEF-x',
'label': 'Field-aligned unit vector along ECEF-x',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Field-aligned unit vector along ECEF-x',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_fa_ecef_y'] = {'long_name': 'Field-aligned unit vector along ECEF-y',
'desc': 'Field-aligned unit vector along ECEF-y',
'label': 'Field-aligned unit vector along ECEF-y',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Field-aligned unit vector along ECEF-y',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_fa_ecef_z'] = {'long_name': 'Field-aligned unit vector along ECEF-z',
'desc': 'Field-aligned unit vector along ECEF-z',
'label': 'Field-aligned unit vector along ECEF-z',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Field-aligned unit vector along ECEF-z',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_mer_ecef_x'] = {'long_name': 'Meridional unit vector along ECEF-x',
'desc': 'Meridional unit vector along ECEF-x',
'label': 'Meridional unit vector along ECEF-x',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Meridional unit vector along ECEF-x',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_mer_ecef_y'] = {'long_name': 'Meridional unit vector along ECEF-y',
'desc': 'Meridional unit vector along ECEF-y',
'label': 'Meridional unit vector along ECEF-y',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Meridional unit vector along ECEF-y',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_mer_ecef_z'] = {'long_name': 'Meridional unit vector along ECEF-z',
'desc': 'Meridional unit vector along ECEF-z',
'label': 'Meridional unit vector along ECEF-z',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Meridional unit vector along ECEF-z',
'value_min': -1.,
'value_max': 1.,
}
return | python | def add_mag_drift_unit_vectors_ecef(inst, steps=None, max_steps=40000, step_size=10.,
ref_height=120.):
"""Adds unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in ECEF coordinates.
Parameters
----------
inst : pysat.Instrument
Instrument object that will get unit vectors
max_steps : int
Maximum number of steps allowed for field line tracing
step_size : float
Maximum step size (km) allowed when field line tracing
ref_height : float
Altitude used as cutoff for labeling a field line location a footpoint
Returns
-------
None
unit vectors are added to the passed Instrument object with a naming
scheme:
'unit_zon_ecef_*' : unit zonal vector, component along ECEF-(X,Y,or Z)
'unit_fa_ecef_*' : unit field-aligned vector, component along ECEF-(X,Y,or Z)
'unit_mer_ecef_*' : unit meridional vector, component along ECEF-(X,Y,or Z)
"""
# add unit vectors for magnetic drifts in ecef coordinates
zvx, zvy, zvz, bx, by, bz, mx, my, mz = calculate_mag_drift_unit_vectors_ecef(inst['latitude'],
inst['longitude'], inst['altitude'], inst.data.index,
steps=steps, max_steps=max_steps, step_size=step_size, ref_height=ref_height)
inst['unit_zon_ecef_x'] = zvx
inst['unit_zon_ecef_y'] = zvy
inst['unit_zon_ecef_z'] = zvz
inst['unit_fa_ecef_x'] = bx
inst['unit_fa_ecef_y'] = by
inst['unit_fa_ecef_z'] = bz
inst['unit_mer_ecef_x'] = mx
inst['unit_mer_ecef_y'] = my
inst['unit_mer_ecef_z'] = mz
inst.meta['unit_zon_ecef_x'] = {'long_name': 'Zonal unit vector along ECEF-x',
'desc': 'Zonal unit vector along ECEF-x',
'label': 'Zonal unit vector along ECEF-x',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Zonal unit vector along ECEF-x',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_zon_ecef_y'] = {'long_name': 'Zonal unit vector along ECEF-y',
'desc': 'Zonal unit vector along ECEF-y',
'label': 'Zonal unit vector along ECEF-y',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Zonal unit vector along ECEF-y',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_zon_ecef_z'] = {'long_name': 'Zonal unit vector along ECEF-z',
'desc': 'Zonal unit vector along ECEF-z',
'label': 'Zonal unit vector along ECEF-z',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Zonal unit vector along ECEF-z',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_fa_ecef_x'] = {'long_name': 'Field-aligned unit vector along ECEF-x',
'desc': 'Field-aligned unit vector along ECEF-x',
'label': 'Field-aligned unit vector along ECEF-x',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Field-aligned unit vector along ECEF-x',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_fa_ecef_y'] = {'long_name': 'Field-aligned unit vector along ECEF-y',
'desc': 'Field-aligned unit vector along ECEF-y',
'label': 'Field-aligned unit vector along ECEF-y',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Field-aligned unit vector along ECEF-y',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_fa_ecef_z'] = {'long_name': 'Field-aligned unit vector along ECEF-z',
'desc': 'Field-aligned unit vector along ECEF-z',
'label': 'Field-aligned unit vector along ECEF-z',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Field-aligned unit vector along ECEF-z',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_mer_ecef_x'] = {'long_name': 'Meridional unit vector along ECEF-x',
'desc': 'Meridional unit vector along ECEF-x',
'label': 'Meridional unit vector along ECEF-x',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Meridional unit vector along ECEF-x',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_mer_ecef_y'] = {'long_name': 'Meridional unit vector along ECEF-y',
'desc': 'Meridional unit vector along ECEF-y',
'label': 'Meridional unit vector along ECEF-y',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Meridional unit vector along ECEF-y',
'value_min': -1.,
'value_max': 1.,
}
inst.meta['unit_mer_ecef_z'] = {'long_name': 'Meridional unit vector along ECEF-z',
'desc': 'Meridional unit vector along ECEF-z',
'label': 'Meridional unit vector along ECEF-z',
'notes': ('Unit vector expressed using Earth Centered Earth Fixed (ECEF) frame. '
'Vector system is calcluated by field-line tracing along IGRF values '
'down to reference altitudes of 120 km in both the Northern and Southern '
'hemispheres. These two points, along with the satellite position, are '
'used to define the magnetic meridian. Vector math from here generates '
'the orthogonal system.'),
'axis': 'Meridional unit vector along ECEF-z',
'value_min': -1.,
'value_max': 1.,
}
return | [
"def",
"add_mag_drift_unit_vectors_ecef",
"(",
"inst",
",",
"steps",
"=",
"None",
",",
"max_steps",
"=",
"40000",
",",
"step_size",
"=",
"10.",
",",
"ref_height",
"=",
"120.",
")",
":",
"# add unit vectors for magnetic drifts in ecef coordinates",
"zvx",
",",
"zvy",... | Adds unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in ECEF coordinates.
Parameters
----------
inst : pysat.Instrument
Instrument object that will get unit vectors
max_steps : int
Maximum number of steps allowed for field line tracing
step_size : float
Maximum step size (km) allowed when field line tracing
ref_height : float
Altitude used as cutoff for labeling a field line location a footpoint
Returns
-------
None
unit vectors are added to the passed Instrument object with a naming
scheme:
'unit_zon_ecef_*' : unit zonal vector, component along ECEF-(X,Y,or Z)
'unit_fa_ecef_*' : unit field-aligned vector, component along ECEF-(X,Y,or Z)
'unit_mer_ecef_*' : unit meridional vector, component along ECEF-(X,Y,or Z) | [
"Adds",
"unit",
"vectors",
"expressing",
"the",
"ion",
"drift",
"coordinate",
"system",
"organized",
"by",
"the",
"geomagnetic",
"field",
".",
"Unit",
"vectors",
"are",
"expressed",
"in",
"ECEF",
"coordinates",
".",
"Parameters",
"----------",
"inst",
":",
"pysa... | train | https://github.com/rstoneback/pysatMagVect/blob/3fdc87ffbe05be58123f80f880d1237c2f34c7be/pysatMagVect/satellite.py#L3-L168 |
rstoneback/pysatMagVect | pysatMagVect/satellite.py | add_mag_drift_unit_vectors | def add_mag_drift_unit_vectors(inst, max_steps=40000, step_size=10.):
"""Add unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in S/C coordinates.
Interally, routine calls add_mag_drift_unit_vectors_ecef.
See function for input parameter description.
Requires the orientation of the S/C basis vectors in ECEF using naming,
'sc_xhat_x' where *hat (*=x,y,z) is the S/C basis vector and _* (*=x,y,z)
is the ECEF direction.
Parameters
----------
inst : pysat.Instrument object
Instrument object to be modified
max_steps : int
Maximum number of steps taken for field line integration
step_size : float
Maximum step size (km) allowed for field line tracer
Returns
-------
None
Modifies instrument object in place. Adds 'unit_zon_*' where * = x,y,z
'unit_fa_*' and 'unit_mer_*' for zonal, field aligned, and meridional
directions. Note that vector components are expressed in the S/C basis.
"""
# vectors are returned in geo/ecef coordinate system
add_mag_drift_unit_vectors_ecef(inst, max_steps=max_steps, step_size=step_size)
# convert them to S/C using transformation supplied by OA
inst['unit_zon_x'], inst['unit_zon_y'], inst['unit_zon_z'] = project_ecef_vector_onto_basis(inst['unit_zon_ecef_x'], inst['unit_zon_ecef_y'], inst['unit_zon_ecef_z'],
inst['sc_xhat_x'], inst['sc_xhat_y'], inst['sc_xhat_z'],
inst['sc_yhat_x'], inst['sc_yhat_y'], inst['sc_yhat_z'],
inst['sc_zhat_x'], inst['sc_zhat_y'], inst['sc_zhat_z'])
inst['unit_fa_x'], inst['unit_fa_y'], inst['unit_fa_z'] = project_ecef_vector_onto_basis(inst['unit_fa_ecef_x'], inst['unit_fa_ecef_y'], inst['unit_fa_ecef_z'],
inst['sc_xhat_x'], inst['sc_xhat_y'], inst['sc_xhat_z'],
inst['sc_yhat_x'], inst['sc_yhat_y'], inst['sc_yhat_z'],
inst['sc_zhat_x'], inst['sc_zhat_y'], inst['sc_zhat_z'])
inst['unit_mer_x'], inst['unit_mer_y'], inst['unit_mer_z'] = project_ecef_vector_onto_basis(inst['unit_mer_ecef_x'], inst['unit_mer_ecef_y'], inst['unit_mer_ecef_z'],
inst['sc_xhat_x'], inst['sc_xhat_y'], inst['sc_xhat_z'],
inst['sc_yhat_x'], inst['sc_yhat_y'], inst['sc_yhat_z'],
inst['sc_zhat_x'], inst['sc_zhat_y'], inst['sc_zhat_z'])
inst.meta['unit_zon_x'] = { 'long_name':'Zonal direction along IVM-x',
'desc': 'Unit vector for the zonal geomagnetic direction.',
'label': 'Zonal Unit Vector: IVM-X component',
'axis': 'Zonal Unit Vector: IVM-X component',
'notes': ('Positive towards the east. Zonal vector is normal to magnetic meridian plane. '
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_zon_y'] = {'long_name':'Zonal direction along IVM-y',
'desc': 'Unit vector for the zonal geomagnetic direction.',
'label': 'Zonal Unit Vector: IVM-Y component',
'axis': 'Zonal Unit Vector: IVM-Y component',
'notes': ('Positive towards the east. Zonal vector is normal to magnetic meridian plane. '
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_zon_z'] = {'long_name':'Zonal direction along IVM-z',
'desc': 'Unit vector for the zonal geomagnetic direction.',
'label': 'Zonal Unit Vector: IVM-Z component',
'axis': 'Zonal Unit Vector: IVM-Z component',
'notes': ('Positive towards the east. Zonal vector is normal to magnetic meridian plane. '
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_fa_x'] = {'long_name':'Field-aligned direction along IVM-x',
'desc': 'Unit vector for the geomagnetic field line direction.',
'label': 'Field Aligned Unit Vector: IVM-X component',
'axis': 'Field Aligned Unit Vector: IVM-X component',
'notes': ('Positive along the field, generally northward. Unit vector is along the geomagnetic field. '
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_fa_y'] = {'long_name':'Field-aligned direction along IVM-y',
'desc': 'Unit vector for the geomagnetic field line direction.',
'label': 'Field Aligned Unit Vector: IVM-Y component',
'axis': 'Field Aligned Unit Vector: IVM-Y component',
'notes': ('Positive along the field, generally northward. Unit vector is along the geomagnetic field. '
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_fa_z'] = {'long_name':'Field-aligned direction along IVM-z',
'desc': 'Unit vector for the geomagnetic field line direction.',
'label': 'Field Aligned Unit Vector: IVM-Z component',
'axis': 'Field Aligned Unit Vector: IVM-Z component',
'notes': ('Positive along the field, generally northward. Unit vector is along the geomagnetic field. '
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_mer_x'] = {'long_name':'Meridional direction along IVM-x',
'desc': 'Unit vector for the geomagnetic meridional direction.',
'label': 'Meridional Unit Vector: IVM-X component',
'axis': 'Meridional Unit Vector: IVM-X component',
'notes': ('Positive is aligned with vertical at '
'geomagnetic equator. Unit vector is perpendicular to the geomagnetic field '
'and in the plane of the meridian.'
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_mer_y'] = {'long_name':'Meridional direction along IVM-y',
'desc': 'Unit vector for the geomagnetic meridional direction.',
'label': 'Meridional Unit Vector: IVM-Y component',
'axis': 'Meridional Unit Vector: IVM-Y component',
'notes': ('Positive is aligned with vertical at '
'geomagnetic equator. Unit vector is perpendicular to the geomagnetic field '
'and in the plane of the meridian.'
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_mer_z'] = {'long_name':'Meridional direction along IVM-z',
'desc': 'Unit vector for the geomagnetic meridional direction.',
'label': 'Meridional Unit Vector: IVM-Z component',
'axis': 'Meridional Unit Vector: IVM-Z component',
'notes': ('Positive is aligned with vertical at '
'geomagnetic equator. Unit vector is perpendicular to the geomagnetic field '
'and in the plane of the meridian.'
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
return | python | def add_mag_drift_unit_vectors(inst, max_steps=40000, step_size=10.):
"""Add unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in S/C coordinates.
Interally, routine calls add_mag_drift_unit_vectors_ecef.
See function for input parameter description.
Requires the orientation of the S/C basis vectors in ECEF using naming,
'sc_xhat_x' where *hat (*=x,y,z) is the S/C basis vector and _* (*=x,y,z)
is the ECEF direction.
Parameters
----------
inst : pysat.Instrument object
Instrument object to be modified
max_steps : int
Maximum number of steps taken for field line integration
step_size : float
Maximum step size (km) allowed for field line tracer
Returns
-------
None
Modifies instrument object in place. Adds 'unit_zon_*' where * = x,y,z
'unit_fa_*' and 'unit_mer_*' for zonal, field aligned, and meridional
directions. Note that vector components are expressed in the S/C basis.
"""
# vectors are returned in geo/ecef coordinate system
add_mag_drift_unit_vectors_ecef(inst, max_steps=max_steps, step_size=step_size)
# convert them to S/C using transformation supplied by OA
inst['unit_zon_x'], inst['unit_zon_y'], inst['unit_zon_z'] = project_ecef_vector_onto_basis(inst['unit_zon_ecef_x'], inst['unit_zon_ecef_y'], inst['unit_zon_ecef_z'],
inst['sc_xhat_x'], inst['sc_xhat_y'], inst['sc_xhat_z'],
inst['sc_yhat_x'], inst['sc_yhat_y'], inst['sc_yhat_z'],
inst['sc_zhat_x'], inst['sc_zhat_y'], inst['sc_zhat_z'])
inst['unit_fa_x'], inst['unit_fa_y'], inst['unit_fa_z'] = project_ecef_vector_onto_basis(inst['unit_fa_ecef_x'], inst['unit_fa_ecef_y'], inst['unit_fa_ecef_z'],
inst['sc_xhat_x'], inst['sc_xhat_y'], inst['sc_xhat_z'],
inst['sc_yhat_x'], inst['sc_yhat_y'], inst['sc_yhat_z'],
inst['sc_zhat_x'], inst['sc_zhat_y'], inst['sc_zhat_z'])
inst['unit_mer_x'], inst['unit_mer_y'], inst['unit_mer_z'] = project_ecef_vector_onto_basis(inst['unit_mer_ecef_x'], inst['unit_mer_ecef_y'], inst['unit_mer_ecef_z'],
inst['sc_xhat_x'], inst['sc_xhat_y'], inst['sc_xhat_z'],
inst['sc_yhat_x'], inst['sc_yhat_y'], inst['sc_yhat_z'],
inst['sc_zhat_x'], inst['sc_zhat_y'], inst['sc_zhat_z'])
inst.meta['unit_zon_x'] = { 'long_name':'Zonal direction along IVM-x',
'desc': 'Unit vector for the zonal geomagnetic direction.',
'label': 'Zonal Unit Vector: IVM-X component',
'axis': 'Zonal Unit Vector: IVM-X component',
'notes': ('Positive towards the east. Zonal vector is normal to magnetic meridian plane. '
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_zon_y'] = {'long_name':'Zonal direction along IVM-y',
'desc': 'Unit vector for the zonal geomagnetic direction.',
'label': 'Zonal Unit Vector: IVM-Y component',
'axis': 'Zonal Unit Vector: IVM-Y component',
'notes': ('Positive towards the east. Zonal vector is normal to magnetic meridian plane. '
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_zon_z'] = {'long_name':'Zonal direction along IVM-z',
'desc': 'Unit vector for the zonal geomagnetic direction.',
'label': 'Zonal Unit Vector: IVM-Z component',
'axis': 'Zonal Unit Vector: IVM-Z component',
'notes': ('Positive towards the east. Zonal vector is normal to magnetic meridian plane. '
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_fa_x'] = {'long_name':'Field-aligned direction along IVM-x',
'desc': 'Unit vector for the geomagnetic field line direction.',
'label': 'Field Aligned Unit Vector: IVM-X component',
'axis': 'Field Aligned Unit Vector: IVM-X component',
'notes': ('Positive along the field, generally northward. Unit vector is along the geomagnetic field. '
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_fa_y'] = {'long_name':'Field-aligned direction along IVM-y',
'desc': 'Unit vector for the geomagnetic field line direction.',
'label': 'Field Aligned Unit Vector: IVM-Y component',
'axis': 'Field Aligned Unit Vector: IVM-Y component',
'notes': ('Positive along the field, generally northward. Unit vector is along the geomagnetic field. '
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_fa_z'] = {'long_name':'Field-aligned direction along IVM-z',
'desc': 'Unit vector for the geomagnetic field line direction.',
'label': 'Field Aligned Unit Vector: IVM-Z component',
'axis': 'Field Aligned Unit Vector: IVM-Z component',
'notes': ('Positive along the field, generally northward. Unit vector is along the geomagnetic field. '
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_mer_x'] = {'long_name':'Meridional direction along IVM-x',
'desc': 'Unit vector for the geomagnetic meridional direction.',
'label': 'Meridional Unit Vector: IVM-X component',
'axis': 'Meridional Unit Vector: IVM-X component',
'notes': ('Positive is aligned with vertical at '
'geomagnetic equator. Unit vector is perpendicular to the geomagnetic field '
'and in the plane of the meridian.'
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_mer_y'] = {'long_name':'Meridional direction along IVM-y',
'desc': 'Unit vector for the geomagnetic meridional direction.',
'label': 'Meridional Unit Vector: IVM-Y component',
'axis': 'Meridional Unit Vector: IVM-Y component',
'notes': ('Positive is aligned with vertical at '
'geomagnetic equator. Unit vector is perpendicular to the geomagnetic field '
'and in the plane of the meridian.'
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
inst.meta['unit_mer_z'] = {'long_name':'Meridional direction along IVM-z',
'desc': 'Unit vector for the geomagnetic meridional direction.',
'label': 'Meridional Unit Vector: IVM-Z component',
'axis': 'Meridional Unit Vector: IVM-Z component',
'notes': ('Positive is aligned with vertical at '
'geomagnetic equator. Unit vector is perpendicular to the geomagnetic field '
'and in the plane of the meridian.'
'The unit vector is expressed in the IVM coordinate system, x - along RAM, '
'z - towards nadir, y - completes the system, generally southward. '
'Calculated using the corresponding unit vector in ECEF and the orientation '
'of the IVM also expressed in ECEF (sc_*hat_*).'),
'scale': 'linear',
'units': '',
'value_min':-1.,
'value_max':1}
return | [
"def",
"add_mag_drift_unit_vectors",
"(",
"inst",
",",
"max_steps",
"=",
"40000",
",",
"step_size",
"=",
"10.",
")",
":",
"# vectors are returned in geo/ecef coordinate system",
"add_mag_drift_unit_vectors_ecef",
"(",
"inst",
",",
"max_steps",
"=",
"max_steps",
",",
"st... | Add unit vectors expressing the ion drift coordinate system
organized by the geomagnetic field. Unit vectors are expressed
in S/C coordinates.
Interally, routine calls add_mag_drift_unit_vectors_ecef.
See function for input parameter description.
Requires the orientation of the S/C basis vectors in ECEF using naming,
'sc_xhat_x' where *hat (*=x,y,z) is the S/C basis vector and _* (*=x,y,z)
is the ECEF direction.
Parameters
----------
inst : pysat.Instrument object
Instrument object to be modified
max_steps : int
Maximum number of steps taken for field line integration
step_size : float
Maximum step size (km) allowed for field line tracer
Returns
-------
None
Modifies instrument object in place. Adds 'unit_zon_*' where * = x,y,z
'unit_fa_*' and 'unit_mer_*' for zonal, field aligned, and meridional
directions. Note that vector components are expressed in the S/C basis. | [
"Add",
"unit",
"vectors",
"expressing",
"the",
"ion",
"drift",
"coordinate",
"system",
"organized",
"by",
"the",
"geomagnetic",
"field",
".",
"Unit",
"vectors",
"are",
"expressed",
"in",
"S",
"/",
"C",
"coordinates",
".",
"Interally",
"routine",
"calls",
"add_... | train | https://github.com/rstoneback/pysatMagVect/blob/3fdc87ffbe05be58123f80f880d1237c2f34c7be/pysatMagVect/satellite.py#L171-L342 |
rstoneback/pysatMagVect | pysatMagVect/satellite.py | add_mag_drifts | def add_mag_drifts(inst):
"""Adds ion drifts in magnetic coordinates using ion drifts in S/C coordinates
along with pre-calculated unit vectors for magnetic coordinates.
Note
----
Requires ion drifts under labels 'iv_*' where * = (x,y,z) along with
unit vectors labels 'unit_zonal_*', 'unit_fa_*', and 'unit_mer_*',
where the unit vectors are expressed in S/C coordinates. These
vectors are calculated by add_mag_drift_unit_vectors.
Parameters
----------
inst : pysat.Instrument
Instrument object will be modified to include new ion drift magnitudes
Returns
-------
None
Instrument object modified in place
"""
inst['iv_zon'] = {'data':inst['unit_zon_x'] * inst['iv_x'] + inst['unit_zon_y']*inst['iv_y'] + inst['unit_zon_z']*inst['iv_z'],
'units':'m/s',
'long_name':'Zonal ion velocity',
'notes':('Ion velocity relative to co-rotation along zonal '
'direction, normal to meridional plane. Positive east. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. '),
'label': 'Zonal Ion Velocity',
'axis': 'Zonal Ion Velocity',
'desc': 'Zonal ion velocity',
'scale': 'Linear',
'value_min':-500.,
'value_max':500.}
inst['iv_fa'] = {'data':inst['unit_fa_x'] * inst['iv_x'] + inst['unit_fa_y'] * inst['iv_y'] + inst['unit_fa_z'] * inst['iv_z'],
'units':'m/s',
'long_name':'Field-Aligned ion velocity',
'notes':('Ion velocity relative to co-rotation along magnetic field line. Positive along the field. ',
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. '),
'label':'Field-Aligned Ion Velocity',
'axis':'Field-Aligned Ion Velocity',
'desc':'Field-Aligned Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
inst['iv_mer'] = {'data':inst['unit_mer_x'] * inst['iv_x'] + inst['unit_mer_y']*inst['iv_y'] + inst['unit_mer_z']*inst['iv_z'],
'units':'m/s',
'long_name':'Meridional ion velocity',
'notes':('Velocity along meridional direction, perpendicular '
'to field and within meridional plane. Positive is up at magnetic equator. ',
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. '),
'label':'Meridional Ion Velocity',
'axis':'Meridional Ion Velocity',
'desc':'Meridional Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
return | python | def add_mag_drifts(inst):
"""Adds ion drifts in magnetic coordinates using ion drifts in S/C coordinates
along with pre-calculated unit vectors for magnetic coordinates.
Note
----
Requires ion drifts under labels 'iv_*' where * = (x,y,z) along with
unit vectors labels 'unit_zonal_*', 'unit_fa_*', and 'unit_mer_*',
where the unit vectors are expressed in S/C coordinates. These
vectors are calculated by add_mag_drift_unit_vectors.
Parameters
----------
inst : pysat.Instrument
Instrument object will be modified to include new ion drift magnitudes
Returns
-------
None
Instrument object modified in place
"""
inst['iv_zon'] = {'data':inst['unit_zon_x'] * inst['iv_x'] + inst['unit_zon_y']*inst['iv_y'] + inst['unit_zon_z']*inst['iv_z'],
'units':'m/s',
'long_name':'Zonal ion velocity',
'notes':('Ion velocity relative to co-rotation along zonal '
'direction, normal to meridional plane. Positive east. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. '),
'label': 'Zonal Ion Velocity',
'axis': 'Zonal Ion Velocity',
'desc': 'Zonal ion velocity',
'scale': 'Linear',
'value_min':-500.,
'value_max':500.}
inst['iv_fa'] = {'data':inst['unit_fa_x'] * inst['iv_x'] + inst['unit_fa_y'] * inst['iv_y'] + inst['unit_fa_z'] * inst['iv_z'],
'units':'m/s',
'long_name':'Field-Aligned ion velocity',
'notes':('Ion velocity relative to co-rotation along magnetic field line. Positive along the field. ',
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. '),
'label':'Field-Aligned Ion Velocity',
'axis':'Field-Aligned Ion Velocity',
'desc':'Field-Aligned Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
inst['iv_mer'] = {'data':inst['unit_mer_x'] * inst['iv_x'] + inst['unit_mer_y']*inst['iv_y'] + inst['unit_mer_z']*inst['iv_z'],
'units':'m/s',
'long_name':'Meridional ion velocity',
'notes':('Velocity along meridional direction, perpendicular '
'to field and within meridional plane. Positive is up at magnetic equator. ',
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. '),
'label':'Meridional Ion Velocity',
'axis':'Meridional Ion Velocity',
'desc':'Meridional Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
return | [
"def",
"add_mag_drifts",
"(",
"inst",
")",
":",
"inst",
"[",
"'iv_zon'",
"]",
"=",
"{",
"'data'",
":",
"inst",
"[",
"'unit_zon_x'",
"]",
"*",
"inst",
"[",
"'iv_x'",
"]",
"+",
"inst",
"[",
"'unit_zon_y'",
"]",
"*",
"inst",
"[",
"'iv_y'",
"]",
"+",
"... | Adds ion drifts in magnetic coordinates using ion drifts in S/C coordinates
along with pre-calculated unit vectors for magnetic coordinates.
Note
----
Requires ion drifts under labels 'iv_*' where * = (x,y,z) along with
unit vectors labels 'unit_zonal_*', 'unit_fa_*', and 'unit_mer_*',
where the unit vectors are expressed in S/C coordinates. These
vectors are calculated by add_mag_drift_unit_vectors.
Parameters
----------
inst : pysat.Instrument
Instrument object will be modified to include new ion drift magnitudes
Returns
-------
None
Instrument object modified in place | [
"Adds",
"ion",
"drifts",
"in",
"magnetic",
"coordinates",
"using",
"ion",
"drifts",
"in",
"S",
"/",
"C",
"coordinates",
"along",
"with",
"pre",
"-",
"calculated",
"unit",
"vectors",
"for",
"magnetic",
"coordinates",
".",
"Note",
"----",
"Requires",
"ion",
"d... | train | https://github.com/rstoneback/pysatMagVect/blob/3fdc87ffbe05be58123f80f880d1237c2f34c7be/pysatMagVect/satellite.py#L345-L415 |
rstoneback/pysatMagVect | pysatMagVect/satellite.py | add_footpoint_and_equatorial_drifts | def add_footpoint_and_equatorial_drifts(inst, equ_mer_scalar='equ_mer_drifts_scalar',
equ_zonal_scalar='equ_zon_drifts_scalar',
north_mer_scalar='north_footpoint_mer_drifts_scalar',
north_zon_scalar='north_footpoint_zon_drifts_scalar',
south_mer_scalar='south_footpoint_mer_drifts_scalar',
south_zon_scalar='south_footpoint_zon_drifts_scalar',
mer_drift='iv_mer',
zon_drift='iv_zon'):
"""Translates geomagnetic ion velocities to those at footpoints and magnetic equator.
Note
----
Presumes scalar values for mapping ion velocities are already in the inst, labeled
by north_footpoint_zon_drifts_scalar, north_footpoint_mer_drifts_scalar,
equ_mer_drifts_scalar, equ_zon_drifts_scalar.
Also presumes that ion motions in the geomagnetic system are present and labeled
as 'iv_mer' and 'iv_zon' for meridional and zonal ion motions.
This naming scheme is used by the other pysat oriented routines
in this package.
Parameters
----------
inst : pysat.Instrument
equ_mer_scalar : string
Label used to identify equatorial scalar for meridional ion drift
equ_zon_scalar : string
Label used to identify equatorial scalar for zonal ion drift
north_mer_scalar : string
Label used to identify northern footpoint scalar for meridional ion drift
north_zon_scalar : string
Label used to identify northern footpoint scalar for zonal ion drift
south_mer_scalar : string
Label used to identify northern footpoint scalar for meridional ion drift
south_zon_scalar : string
Label used to identify southern footpoint scalar for zonal ion drift
mer_drift : string
Label used to identify meridional ion drifts within inst
zon_drift : string
Label used to identify zonal ion drifts within inst
Returns
-------
None
Modifies pysat.Instrument object in place. Drifts mapped to the magnetic equator
are labeled 'equ_mer_drift' and 'equ_zon_drift'. Mappings to the northern
and southern footpoints are labeled 'south_footpoint_mer_drift' and
'south_footpoint_zon_drift'. Similarly for the northern hemisphere.
"""
inst['equ_mer_drift'] = {'data' : inst[equ_mer_scalar]*inst[mer_drift],
'units':'m/s',
'long_name':'Equatorial meridional ion velocity',
'notes':('Velocity along meridional direction, perpendicular '
'to field and within meridional plane, scaled to '
'magnetic equator. Positive is up at magnetic equator. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. Field-line mapping and '
'the assumption of equi-potential field lines '
'is used to translate the locally measured ion '
'motion to the magnetic equator. The mapping '
'is used to determine the change in magnetic '
'field line distance, which, under assumption of '
'equipotential field lines, in turn alters '
'the electric field at that location (E=V/d). '),
'label':'Equatorial Meridional Ion Velocity',
'axis':'Equatorial Meridional Ion Velocity',
'desc':'Equatorial Meridional Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
inst['equ_zon_drift'] = {'data' : inst[equ_zonal_scalar]*inst[zon_drift],
'units':'m/s',
'long_name':'Equatorial zonal ion velocity',
'notes':('Velocity along zonal direction, perpendicular '
'to field and the meridional plane, scaled to '
'magnetic equator. Positive is generally eastward. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. Field-line mapping and '
'the assumption of equi-potential field lines '
'is used to translate the locally measured ion '
'motion to the magnetic equator. The mapping '
'is used to determine the change in magnetic '
'field line distance, which, under assumption of '
'equipotential field lines, in turn alters '
'the electric field at that location (E=V/d). '),
'label':'Equatorial Zonal Ion Velocity',
'axis':'Equatorial Zonal Ion Velocity',
'desc':'Equatorial Zonal Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
inst['south_footpoint_mer_drift'] = {'data' : inst[south_mer_scalar]*inst[mer_drift],
'units':'m/s',
'long_name':'Southern meridional ion velocity',
'notes':('Velocity along meridional direction, perpendicular '
'to field and within meridional plane, scaled to '
'southern footpoint. Positive is up at magnetic equator. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. Field-line mapping and '
'the assumption of equi-potential field lines '
'is used to translate the locally measured ion '
'motion to the magnetic footpoint. The mapping '
'is used to determine the change in magnetic '
'field line distance, which, under assumption of '
'equipotential field lines, in turn alters '
'the electric field at that location (E=V/d). '),
'label':'Southern Meridional Ion Velocity',
'axis':'Southern Meridional Ion Velocity',
'desc':'Southern Meridional Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
inst['south_footpoint_zon_drift'] = {'data':inst[south_zon_scalar]*inst[zon_drift],
'units':'m/s',
'long_name':'Southern zonal ion velocity',
'notes':('Velocity along zonal direction, perpendicular '
'to field and the meridional plane, scaled to '
'southern footpoint. Positive is generally eastward. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. Field-line mapping and '
'the assumption of equi-potential field lines '
'is used to translate the locally measured ion '
'motion to the southern footpoint. The mapping '
'is used to determine the change in magnetic '
'field line distance, which, under assumption of '
'equipotential field lines, in turn alters '
'the electric field at that location (E=V/d). '),
'label':'Southern Zonal Ion Velocity',
'axis':'Southern Zonal Ion Velocity',
'desc':'Southern Zonal Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
inst['north_footpoint_mer_drift'] = {'data':inst[north_mer_scalar]*inst[mer_drift],
'units':'m/s',
'long_name':'Northern meridional ion velocity',
'notes':('Velocity along meridional direction, perpendicular '
'to field and within meridional plane, scaled to '
'northern footpoint. Positive is up at magnetic equator. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. Field-line mapping and '
'the assumption of equi-potential field lines '
'is used to translate the locally measured ion '
'motion to the magnetic footpoint. The mapping '
'is used to determine the change in magnetic '
'field line distance, which, under assumption of '
'equipotential field lines, in turn alters '
'the electric field at that location (E=V/d). '),
'label':'Northern Meridional Ion Velocity',
'axis':'Northern Meridional Ion Velocity',
'desc':'Northern Meridional Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
inst['north_footpoint_zon_drift'] = {'data':inst[north_zon_scalar]*inst[zon_drift],
'units':'m/s',
'long_name':'Northern zonal ion velocity',
'notes':('Velocity along zonal direction, perpendicular '
'to field and the meridional plane, scaled to '
'northern footpoint. Positive is generally eastward. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. Field-line mapping and '
'the assumption of equi-potential field lines '
'is used to translate the locally measured ion '
'motion to the northern footpoint. The mapping '
'is used to determine the change in magnetic '
'field line distance, which, under assumption of '
'equipotential field lines, in turn alters '
'the electric field at that location (E=V/d). '),
'label':'Northern Zonal Ion Velocity',
'axis':'Northern Zonal Ion Velocity',
'desc':'Northern Zonal Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.} | python | def add_footpoint_and_equatorial_drifts(inst, equ_mer_scalar='equ_mer_drifts_scalar',
equ_zonal_scalar='equ_zon_drifts_scalar',
north_mer_scalar='north_footpoint_mer_drifts_scalar',
north_zon_scalar='north_footpoint_zon_drifts_scalar',
south_mer_scalar='south_footpoint_mer_drifts_scalar',
south_zon_scalar='south_footpoint_zon_drifts_scalar',
mer_drift='iv_mer',
zon_drift='iv_zon'):
"""Translates geomagnetic ion velocities to those at footpoints and magnetic equator.
Note
----
Presumes scalar values for mapping ion velocities are already in the inst, labeled
by north_footpoint_zon_drifts_scalar, north_footpoint_mer_drifts_scalar,
equ_mer_drifts_scalar, equ_zon_drifts_scalar.
Also presumes that ion motions in the geomagnetic system are present and labeled
as 'iv_mer' and 'iv_zon' for meridional and zonal ion motions.
This naming scheme is used by the other pysat oriented routines
in this package.
Parameters
----------
inst : pysat.Instrument
equ_mer_scalar : string
Label used to identify equatorial scalar for meridional ion drift
equ_zon_scalar : string
Label used to identify equatorial scalar for zonal ion drift
north_mer_scalar : string
Label used to identify northern footpoint scalar for meridional ion drift
north_zon_scalar : string
Label used to identify northern footpoint scalar for zonal ion drift
south_mer_scalar : string
Label used to identify northern footpoint scalar for meridional ion drift
south_zon_scalar : string
Label used to identify southern footpoint scalar for zonal ion drift
mer_drift : string
Label used to identify meridional ion drifts within inst
zon_drift : string
Label used to identify zonal ion drifts within inst
Returns
-------
None
Modifies pysat.Instrument object in place. Drifts mapped to the magnetic equator
are labeled 'equ_mer_drift' and 'equ_zon_drift'. Mappings to the northern
and southern footpoints are labeled 'south_footpoint_mer_drift' and
'south_footpoint_zon_drift'. Similarly for the northern hemisphere.
"""
inst['equ_mer_drift'] = {'data' : inst[equ_mer_scalar]*inst[mer_drift],
'units':'m/s',
'long_name':'Equatorial meridional ion velocity',
'notes':('Velocity along meridional direction, perpendicular '
'to field and within meridional plane, scaled to '
'magnetic equator. Positive is up at magnetic equator. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. Field-line mapping and '
'the assumption of equi-potential field lines '
'is used to translate the locally measured ion '
'motion to the magnetic equator. The mapping '
'is used to determine the change in magnetic '
'field line distance, which, under assumption of '
'equipotential field lines, in turn alters '
'the electric field at that location (E=V/d). '),
'label':'Equatorial Meridional Ion Velocity',
'axis':'Equatorial Meridional Ion Velocity',
'desc':'Equatorial Meridional Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
inst['equ_zon_drift'] = {'data' : inst[equ_zonal_scalar]*inst[zon_drift],
'units':'m/s',
'long_name':'Equatorial zonal ion velocity',
'notes':('Velocity along zonal direction, perpendicular '
'to field and the meridional plane, scaled to '
'magnetic equator. Positive is generally eastward. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. Field-line mapping and '
'the assumption of equi-potential field lines '
'is used to translate the locally measured ion '
'motion to the magnetic equator. The mapping '
'is used to determine the change in magnetic '
'field line distance, which, under assumption of '
'equipotential field lines, in turn alters '
'the electric field at that location (E=V/d). '),
'label':'Equatorial Zonal Ion Velocity',
'axis':'Equatorial Zonal Ion Velocity',
'desc':'Equatorial Zonal Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
inst['south_footpoint_mer_drift'] = {'data' : inst[south_mer_scalar]*inst[mer_drift],
'units':'m/s',
'long_name':'Southern meridional ion velocity',
'notes':('Velocity along meridional direction, perpendicular '
'to field and within meridional plane, scaled to '
'southern footpoint. Positive is up at magnetic equator. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. Field-line mapping and '
'the assumption of equi-potential field lines '
'is used to translate the locally measured ion '
'motion to the magnetic footpoint. The mapping '
'is used to determine the change in magnetic '
'field line distance, which, under assumption of '
'equipotential field lines, in turn alters '
'the electric field at that location (E=V/d). '),
'label':'Southern Meridional Ion Velocity',
'axis':'Southern Meridional Ion Velocity',
'desc':'Southern Meridional Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
inst['south_footpoint_zon_drift'] = {'data':inst[south_zon_scalar]*inst[zon_drift],
'units':'m/s',
'long_name':'Southern zonal ion velocity',
'notes':('Velocity along zonal direction, perpendicular '
'to field and the meridional plane, scaled to '
'southern footpoint. Positive is generally eastward. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. Field-line mapping and '
'the assumption of equi-potential field lines '
'is used to translate the locally measured ion '
'motion to the southern footpoint. The mapping '
'is used to determine the change in magnetic '
'field line distance, which, under assumption of '
'equipotential field lines, in turn alters '
'the electric field at that location (E=V/d). '),
'label':'Southern Zonal Ion Velocity',
'axis':'Southern Zonal Ion Velocity',
'desc':'Southern Zonal Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
inst['north_footpoint_mer_drift'] = {'data':inst[north_mer_scalar]*inst[mer_drift],
'units':'m/s',
'long_name':'Northern meridional ion velocity',
'notes':('Velocity along meridional direction, perpendicular '
'to field and within meridional plane, scaled to '
'northern footpoint. Positive is up at magnetic equator. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. Field-line mapping and '
'the assumption of equi-potential field lines '
'is used to translate the locally measured ion '
'motion to the magnetic footpoint. The mapping '
'is used to determine the change in magnetic '
'field line distance, which, under assumption of '
'equipotential field lines, in turn alters '
'the electric field at that location (E=V/d). '),
'label':'Northern Meridional Ion Velocity',
'axis':'Northern Meridional Ion Velocity',
'desc':'Northern Meridional Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.}
inst['north_footpoint_zon_drift'] = {'data':inst[north_zon_scalar]*inst[zon_drift],
'units':'m/s',
'long_name':'Northern zonal ion velocity',
'notes':('Velocity along zonal direction, perpendicular '
'to field and the meridional plane, scaled to '
'northern footpoint. Positive is generally eastward. '
'Velocity obtained using ion velocities relative '
'to co-rotation in the instrument frame along '
'with the corresponding unit vectors expressed in '
'the instrument frame. Field-line mapping and '
'the assumption of equi-potential field lines '
'is used to translate the locally measured ion '
'motion to the northern footpoint. The mapping '
'is used to determine the change in magnetic '
'field line distance, which, under assumption of '
'equipotential field lines, in turn alters '
'the electric field at that location (E=V/d). '),
'label':'Northern Zonal Ion Velocity',
'axis':'Northern Zonal Ion Velocity',
'desc':'Northern Zonal Ion Velocity',
'scale':'Linear',
'value_min':-500.,
'value_max':500.} | [
"def",
"add_footpoint_and_equatorial_drifts",
"(",
"inst",
",",
"equ_mer_scalar",
"=",
"'equ_mer_drifts_scalar'",
",",
"equ_zonal_scalar",
"=",
"'equ_zon_drifts_scalar'",
",",
"north_mer_scalar",
"=",
"'north_footpoint_mer_drifts_scalar'",
",",
"north_zon_scalar",
"=",
"'north_... | Translates geomagnetic ion velocities to those at footpoints and magnetic equator.
Note
----
Presumes scalar values for mapping ion velocities are already in the inst, labeled
by north_footpoint_zon_drifts_scalar, north_footpoint_mer_drifts_scalar,
equ_mer_drifts_scalar, equ_zon_drifts_scalar.
Also presumes that ion motions in the geomagnetic system are present and labeled
as 'iv_mer' and 'iv_zon' for meridional and zonal ion motions.
This naming scheme is used by the other pysat oriented routines
in this package.
Parameters
----------
inst : pysat.Instrument
equ_mer_scalar : string
Label used to identify equatorial scalar for meridional ion drift
equ_zon_scalar : string
Label used to identify equatorial scalar for zonal ion drift
north_mer_scalar : string
Label used to identify northern footpoint scalar for meridional ion drift
north_zon_scalar : string
Label used to identify northern footpoint scalar for zonal ion drift
south_mer_scalar : string
Label used to identify northern footpoint scalar for meridional ion drift
south_zon_scalar : string
Label used to identify southern footpoint scalar for zonal ion drift
mer_drift : string
Label used to identify meridional ion drifts within inst
zon_drift : string
Label used to identify zonal ion drifts within inst
Returns
-------
None
Modifies pysat.Instrument object in place. Drifts mapped to the magnetic equator
are labeled 'equ_mer_drift' and 'equ_zon_drift'. Mappings to the northern
and southern footpoints are labeled 'south_footpoint_mer_drift' and
'south_footpoint_zon_drift'. Similarly for the northern hemisphere. | [
"Translates",
"geomagnetic",
"ion",
"velocities",
"to",
"those",
"at",
"footpoints",
"and",
"magnetic",
"equator",
".",
"Note",
"----",
"Presumes",
"scalar",
"values",
"for",
"mapping",
"ion",
"velocities",
"are",
"already",
"in",
"the",
"inst",
"labeled",
"by",... | train | https://github.com/rstoneback/pysatMagVect/blob/3fdc87ffbe05be58123f80f880d1237c2f34c7be/pysatMagVect/satellite.py#L418-L610 |
dailymuse/oz | oz/bandit/__init__.py | chi_squared | def chi_squared(*choices):
"""Calculates the chi squared"""
term = lambda expected, observed: float((expected - observed) ** 2) / max(expected, 1)
mean_success_rate = float(sum([c.rewards for c in choices])) / max(sum([c.plays for c in choices]), 1)
mean_failure_rate = 1 - mean_success_rate
return sum([
term(mean_success_rate * c.plays, c.rewards)
+ term(mean_failure_rate * c.plays, c.plays - c.rewards
) for c in choices]) | python | def chi_squared(*choices):
"""Calculates the chi squared"""
term = lambda expected, observed: float((expected - observed) ** 2) / max(expected, 1)
mean_success_rate = float(sum([c.rewards for c in choices])) / max(sum([c.plays for c in choices]), 1)
mean_failure_rate = 1 - mean_success_rate
return sum([
term(mean_success_rate * c.plays, c.rewards)
+ term(mean_failure_rate * c.plays, c.plays - c.rewards
) for c in choices]) | [
"def",
"chi_squared",
"(",
"*",
"choices",
")",
":",
"term",
"=",
"lambda",
"expected",
",",
"observed",
":",
"float",
"(",
"(",
"expected",
"-",
"observed",
")",
"**",
"2",
")",
"/",
"max",
"(",
"expected",
",",
"1",
")",
"mean_success_rate",
"=",
"... | Calculates the chi squared | [
"Calculates",
"the",
"chi",
"squared"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L42-L52 |
dailymuse/oz | oz/bandit/__init__.py | sync_from_spec | def sync_from_spec(redis, schema):
"""
Takes an input experiment spec and creates/modifies/archives the existing
experiments to match the spec.
If there's an experiment in the spec that currently doesn't exist, it will
be created along with the associated choices.
If there's an experiment in the spec that currently exists, and the set of
choices are different, that experiment's choices will be modified to match
the spec.
If there's an experiment not in the spec that currently exists, it will be
archived.
A spec looks like this:
{
"experiment 1": ["choice 1", "choice 2", "choice 3"],
"experiment 2": ["choice 1", "choice 2"]
}
"""
def get_experiments_dict(active=True):
"""Returns a dictionary of experiment names -> experiment objects"""
return dict((experiment.name, experiment) for experiment in get_experiments(redis, active=active))
# Get the current experiments
active_experiments = get_experiments_dict()
archived_experiments = get_experiments_dict(active=False)
# Get the newly defined experiment names and the names of the experiments
# already setup
new_experiment_names = set(schema.keys())
active_experiment_names = set(active_experiments.keys())
# Find all the experiments that are in the schema and are defined among the
# archived experiments, but not the active ones (we check against active
# experiments to prevent the edge case where an experiment might be defined
# doubly in both active and archived experiments)
unarchivable_experiment_names = (new_experiment_names - active_experiment_names) & set(archived_experiments.keys())
# De-archive the necessary experiments
for unarchivable_experiment_name in unarchivable_experiment_names:
print("- De-archiving %s" % unarchivable_experiment_name)
# Because there is no function to de-archive an experiment, it must
# be done manually
pipe = redis.pipeline(transaction=True)
pipe.sadd(ACTIVE_EXPERIMENTS_REDIS_KEY, unarchivable_experiment_name)
pipe.srem(ARCHIVED_EXPERIMENTS_REDIS_KEY, unarchivable_experiment_name)
pipe.execute()
# Reload the active experiments if we de-archived any
if unarchivable_experiment_names:
active_experiments = get_experiments_dict()
active_experiment_names = set(active_experiments.keys())
# Create the new experiments
for new_experiment_name in new_experiment_names - active_experiment_names:
print("- Creating experiment %s" % new_experiment_name)
experiment = add_experiment(redis, new_experiment_name)
for choice in schema[new_experiment_name]:
print(" - Adding choice %s" % choice)
experiment.add_choice(choice)
# Archive experiments not defined in the schema
for archivable_experiment_name in active_experiment_names - new_experiment_names:
print("- Archiving %s" % archivable_experiment_name)
active_experiments[archivable_experiment_name].archive()
# Update the choices for existing experiments that are also defined in the
# schema
for experiment_name in new_experiment_names & active_experiment_names:
experiment = active_experiments[experiment_name]
new_choice_names = set(schema[experiment_name])
old_choice_names = set(experiment.choice_names)
# Add choices in the schema that do not exist yet
for new_choice_name in new_choice_names - old_choice_names:
print("- Adding choice %s to existing experiment %s" % (new_choice_name, experiment_name))
experiment.add_choice(new_choice_name)
# Remove choices that aren't in the schema
for removable_choice_name in old_choice_names - new_choice_names:
print("- Removing choice %s from existing experiment %s" % (removable_choice_name, experiment_name))
experiment.remove_choice(removable_choice_name) | python | def sync_from_spec(redis, schema):
"""
Takes an input experiment spec and creates/modifies/archives the existing
experiments to match the spec.
If there's an experiment in the spec that currently doesn't exist, it will
be created along with the associated choices.
If there's an experiment in the spec that currently exists, and the set of
choices are different, that experiment's choices will be modified to match
the spec.
If there's an experiment not in the spec that currently exists, it will be
archived.
A spec looks like this:
{
"experiment 1": ["choice 1", "choice 2", "choice 3"],
"experiment 2": ["choice 1", "choice 2"]
}
"""
def get_experiments_dict(active=True):
"""Returns a dictionary of experiment names -> experiment objects"""
return dict((experiment.name, experiment) for experiment in get_experiments(redis, active=active))
# Get the current experiments
active_experiments = get_experiments_dict()
archived_experiments = get_experiments_dict(active=False)
# Get the newly defined experiment names and the names of the experiments
# already setup
new_experiment_names = set(schema.keys())
active_experiment_names = set(active_experiments.keys())
# Find all the experiments that are in the schema and are defined among the
# archived experiments, but not the active ones (we check against active
# experiments to prevent the edge case where an experiment might be defined
# doubly in both active and archived experiments)
unarchivable_experiment_names = (new_experiment_names - active_experiment_names) & set(archived_experiments.keys())
# De-archive the necessary experiments
for unarchivable_experiment_name in unarchivable_experiment_names:
print("- De-archiving %s" % unarchivable_experiment_name)
# Because there is no function to de-archive an experiment, it must
# be done manually
pipe = redis.pipeline(transaction=True)
pipe.sadd(ACTIVE_EXPERIMENTS_REDIS_KEY, unarchivable_experiment_name)
pipe.srem(ARCHIVED_EXPERIMENTS_REDIS_KEY, unarchivable_experiment_name)
pipe.execute()
# Reload the active experiments if we de-archived any
if unarchivable_experiment_names:
active_experiments = get_experiments_dict()
active_experiment_names = set(active_experiments.keys())
# Create the new experiments
for new_experiment_name in new_experiment_names - active_experiment_names:
print("- Creating experiment %s" % new_experiment_name)
experiment = add_experiment(redis, new_experiment_name)
for choice in schema[new_experiment_name]:
print(" - Adding choice %s" % choice)
experiment.add_choice(choice)
# Archive experiments not defined in the schema
for archivable_experiment_name in active_experiment_names - new_experiment_names:
print("- Archiving %s" % archivable_experiment_name)
active_experiments[archivable_experiment_name].archive()
# Update the choices for existing experiments that are also defined in the
# schema
for experiment_name in new_experiment_names & active_experiment_names:
experiment = active_experiments[experiment_name]
new_choice_names = set(schema[experiment_name])
old_choice_names = set(experiment.choice_names)
# Add choices in the schema that do not exist yet
for new_choice_name in new_choice_names - old_choice_names:
print("- Adding choice %s to existing experiment %s" % (new_choice_name, experiment_name))
experiment.add_choice(new_choice_name)
# Remove choices that aren't in the schema
for removable_choice_name in old_choice_names - new_choice_names:
print("- Removing choice %s from existing experiment %s" % (removable_choice_name, experiment_name))
experiment.remove_choice(removable_choice_name) | [
"def",
"sync_from_spec",
"(",
"redis",
",",
"schema",
")",
":",
"def",
"get_experiments_dict",
"(",
"active",
"=",
"True",
")",
":",
"\"\"\"Returns a dictionary of experiment names -> experiment objects\"\"\"",
"return",
"dict",
"(",
"(",
"experiment",
".",
"name",
",... | Takes an input experiment spec and creates/modifies/archives the existing
experiments to match the spec.
If there's an experiment in the spec that currently doesn't exist, it will
be created along with the associated choices.
If there's an experiment in the spec that currently exists, and the set of
choices are different, that experiment's choices will be modified to match
the spec.
If there's an experiment not in the spec that currently exists, it will be
archived.
A spec looks like this:
{
"experiment 1": ["choice 1", "choice 2", "choice 3"],
"experiment 2": ["choice 1", "choice 2"]
} | [
"Takes",
"an",
"input",
"experiment",
"spec",
"and",
"creates",
"/",
"modifies",
"/",
"archives",
"the",
"existing",
"experiments",
"to",
"match",
"the",
"spec",
"."
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L65-L153 |
dailymuse/oz | oz/bandit/__init__.py | add_experiment | def add_experiment(redis, name):
"""Adds a new experiment"""
if not ALLOWED_NAMES.match(name):
raise ExperimentException(name, "Illegal name")
if redis.exists(EXPERIMENT_REDIS_KEY_TEMPLATE % name):
raise ExperimentException(name, "Already exists")
json = dict(creation_date=util.unicode_type(datetime.datetime.now()))
pipe = redis.pipeline(transaction=True)
pipe.sadd(ACTIVE_EXPERIMENTS_REDIS_KEY, name)
pipe.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % name, "metadata", escape.json_encode(json))
pipe.execute()
return Experiment(redis, name) | python | def add_experiment(redis, name):
"""Adds a new experiment"""
if not ALLOWED_NAMES.match(name):
raise ExperimentException(name, "Illegal name")
if redis.exists(EXPERIMENT_REDIS_KEY_TEMPLATE % name):
raise ExperimentException(name, "Already exists")
json = dict(creation_date=util.unicode_type(datetime.datetime.now()))
pipe = redis.pipeline(transaction=True)
pipe.sadd(ACTIVE_EXPERIMENTS_REDIS_KEY, name)
pipe.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % name, "metadata", escape.json_encode(json))
pipe.execute()
return Experiment(redis, name) | [
"def",
"add_experiment",
"(",
"redis",
",",
"name",
")",
":",
"if",
"not",
"ALLOWED_NAMES",
".",
"match",
"(",
"name",
")",
":",
"raise",
"ExperimentException",
"(",
"name",
",",
"\"Illegal name\"",
")",
"if",
"redis",
".",
"exists",
"(",
"EXPERIMENT_REDIS_K... | Adds a new experiment | [
"Adds",
"a",
"new",
"experiment"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L283-L296 |
dailymuse/oz | oz/bandit/__init__.py | get_experiments | def get_experiments(redis, active=True):
"""Gets the full list of experiments"""
key = ACTIVE_EXPERIMENTS_REDIS_KEY if active else ARCHIVED_EXPERIMENTS_REDIS_KEY
return [Experiment(redis, escape.to_unicode(name)) for name in redis.smembers(key)] | python | def get_experiments(redis, active=True):
"""Gets the full list of experiments"""
key = ACTIVE_EXPERIMENTS_REDIS_KEY if active else ARCHIVED_EXPERIMENTS_REDIS_KEY
return [Experiment(redis, escape.to_unicode(name)) for name in redis.smembers(key)] | [
"def",
"get_experiments",
"(",
"redis",
",",
"active",
"=",
"True",
")",
":",
"key",
"=",
"ACTIVE_EXPERIMENTS_REDIS_KEY",
"if",
"active",
"else",
"ARCHIVED_EXPERIMENTS_REDIS_KEY",
"return",
"[",
"Experiment",
"(",
"redis",
",",
"escape",
".",
"to_unicode",
"(",
... | Gets the full list of experiments | [
"Gets",
"the",
"full",
"list",
"of",
"experiments"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L298-L302 |
dailymuse/oz | oz/bandit/__init__.py | Experiment.refresh | def refresh(self):
"""Re-pulls the data from redis"""
pipe = self.redis.pipeline()
pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "metadata")
pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "choices")
pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "default-choice")
results = pipe.execute()
if results[0] == None:
raise ExperimentException(self.name, "Does not exist")
self.metadata = parse_json(results[0])
self.choice_names = parse_json(results[1]) if results[1] != None else []
self.default_choice = escape.to_unicode(results[2])
self._choices = None | python | def refresh(self):
"""Re-pulls the data from redis"""
pipe = self.redis.pipeline()
pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "metadata")
pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "choices")
pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "default-choice")
results = pipe.execute()
if results[0] == None:
raise ExperimentException(self.name, "Does not exist")
self.metadata = parse_json(results[0])
self.choice_names = parse_json(results[1]) if results[1] != None else []
self.default_choice = escape.to_unicode(results[2])
self._choices = None | [
"def",
"refresh",
"(",
"self",
")",
":",
"pipe",
"=",
"self",
".",
"redis",
".",
"pipeline",
"(",
")",
"pipe",
".",
"hget",
"(",
"EXPERIMENT_REDIS_KEY_TEMPLATE",
"%",
"self",
".",
"name",
",",
"\"metadata\"",
")",
"pipe",
".",
"hget",
"(",
"EXPERIMENT_RE... | Re-pulls the data from redis | [
"Re",
"-",
"pulls",
"the",
"data",
"from",
"redis"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L173-L187 |
dailymuse/oz | oz/bandit/__init__.py | Experiment.choices | def choices(self):
"""Gets the experiment choices"""
if self._choices == None:
self._choices = [ExperimentChoice(self, choice_name) for choice_name in self.choice_names]
return self._choices | python | def choices(self):
"""Gets the experiment choices"""
if self._choices == None:
self._choices = [ExperimentChoice(self, choice_name) for choice_name in self.choice_names]
return self._choices | [
"def",
"choices",
"(",
"self",
")",
":",
"if",
"self",
".",
"_choices",
"==",
"None",
":",
"self",
".",
"_choices",
"=",
"[",
"ExperimentChoice",
"(",
"self",
",",
"choice_name",
")",
"for",
"choice_name",
"in",
"self",
".",
"choice_names",
"]",
"return"... | Gets the experiment choices | [
"Gets",
"the",
"experiment",
"choices"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L190-L196 |
dailymuse/oz | oz/bandit/__init__.py | Experiment.confidence | def confidence(self):
"""
Returns a tuple (chi squared, confident) of the experiment. Confident
is simply a boolean specifying whether we're > 95%% sure that the
results are statistically significant.
"""
choices = self.choices
# Get the chi-squared between the top two choices, if more than two choices exist
if len(choices) >= 2:
csq = chi_squared(*choices)
confident = is_confident(csq, len(choices)) if len(choices) <= 10 else None
else:
csq = None
confident = False
return (csq, confident) | python | def confidence(self):
"""
Returns a tuple (chi squared, confident) of the experiment. Confident
is simply a boolean specifying whether we're > 95%% sure that the
results are statistically significant.
"""
choices = self.choices
# Get the chi-squared between the top two choices, if more than two choices exist
if len(choices) >= 2:
csq = chi_squared(*choices)
confident = is_confident(csq, len(choices)) if len(choices) <= 10 else None
else:
csq = None
confident = False
return (csq, confident) | [
"def",
"confidence",
"(",
"self",
")",
":",
"choices",
"=",
"self",
".",
"choices",
"# Get the chi-squared between the top two choices, if more than two choices exist",
"if",
"len",
"(",
"choices",
")",
">=",
"2",
":",
"csq",
"=",
"chi_squared",
"(",
"*",
"choices",... | Returns a tuple (chi squared, confident) of the experiment. Confident
is simply a boolean specifying whether we're > 95%% sure that the
results are statistically significant. | [
"Returns",
"a",
"tuple",
"(",
"chi",
"squared",
"confident",
")",
"of",
"the",
"experiment",
".",
"Confident",
"is",
"simply",
"a",
"boolean",
"specifying",
"whether",
"we",
"re",
">",
"95%%",
"sure",
"that",
"the",
"results",
"are",
"statistically",
"signif... | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L198-L215 |
dailymuse/oz | oz/bandit/__init__.py | Experiment.archive | def archive(self):
"""Archives an experiment"""
pipe = self.redis.pipeline(transaction=True)
pipe.srem(ACTIVE_EXPERIMENTS_REDIS_KEY, self.name)
pipe.sadd(ARCHIVED_EXPERIMENTS_REDIS_KEY, self.name)
pipe.execute() | python | def archive(self):
"""Archives an experiment"""
pipe = self.redis.pipeline(transaction=True)
pipe.srem(ACTIVE_EXPERIMENTS_REDIS_KEY, self.name)
pipe.sadd(ARCHIVED_EXPERIMENTS_REDIS_KEY, self.name)
pipe.execute() | [
"def",
"archive",
"(",
"self",
")",
":",
"pipe",
"=",
"self",
".",
"redis",
".",
"pipeline",
"(",
"transaction",
"=",
"True",
")",
"pipe",
".",
"srem",
"(",
"ACTIVE_EXPERIMENTS_REDIS_KEY",
",",
"self",
".",
"name",
")",
"pipe",
".",
"sadd",
"(",
"ARCHI... | Archives an experiment | [
"Archives",
"an",
"experiment"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L217-L222 |
dailymuse/oz | oz/bandit/__init__.py | Experiment.add_choice | def add_choice(self, choice_name):
"""Adds a choice for the experiment"""
if not ALLOWED_NAMES.match(choice_name):
raise ExperimentException(self.name, "Illegal choice name: %s" % choice_name)
if choice_name in self.choice_names:
raise ExperimentException(self.name, "Choice already exists: %s" % choice_name)
self.choice_names.append(choice_name)
self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "choices", escape.json_encode(self.choice_names))
self.refresh() | python | def add_choice(self, choice_name):
"""Adds a choice for the experiment"""
if not ALLOWED_NAMES.match(choice_name):
raise ExperimentException(self.name, "Illegal choice name: %s" % choice_name)
if choice_name in self.choice_names:
raise ExperimentException(self.name, "Choice already exists: %s" % choice_name)
self.choice_names.append(choice_name)
self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "choices", escape.json_encode(self.choice_names))
self.refresh() | [
"def",
"add_choice",
"(",
"self",
",",
"choice_name",
")",
":",
"if",
"not",
"ALLOWED_NAMES",
".",
"match",
"(",
"choice_name",
")",
":",
"raise",
"ExperimentException",
"(",
"self",
".",
"name",
",",
"\"Illegal choice name: %s\"",
"%",
"choice_name",
")",
"if... | Adds a choice for the experiment | [
"Adds",
"a",
"choice",
"for",
"the",
"experiment"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L224-L235 |
dailymuse/oz | oz/bandit/__init__.py | Experiment.remove_choice | def remove_choice(self, choice_name):
"""Adds a choice for the experiment"""
self.choice_names.remove(choice_name)
self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "choices", escape.json_encode(self.choice_names))
self.refresh() | python | def remove_choice(self, choice_name):
"""Adds a choice for the experiment"""
self.choice_names.remove(choice_name)
self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "choices", escape.json_encode(self.choice_names))
self.refresh() | [
"def",
"remove_choice",
"(",
"self",
",",
"choice_name",
")",
":",
"self",
".",
"choice_names",
".",
"remove",
"(",
"choice_name",
")",
"self",
".",
"redis",
".",
"hset",
"(",
"EXPERIMENT_REDIS_KEY_TEMPLATE",
"%",
"self",
".",
"name",
",",
"\"choices\"",
","... | Adds a choice for the experiment | [
"Adds",
"a",
"choice",
"for",
"the",
"experiment"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L237-L242 |
dailymuse/oz | oz/bandit/__init__.py | Experiment.add_play | def add_play(self, choice, count=1):
"""Increments the play count for a given experiment choice"""
self.redis.hincrby(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "%s:plays" % choice, count)
self._choices = None | python | def add_play(self, choice, count=1):
"""Increments the play count for a given experiment choice"""
self.redis.hincrby(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "%s:plays" % choice, count)
self._choices = None | [
"def",
"add_play",
"(",
"self",
",",
"choice",
",",
"count",
"=",
"1",
")",
":",
"self",
".",
"redis",
".",
"hincrby",
"(",
"EXPERIMENT_REDIS_KEY_TEMPLATE",
"%",
"self",
".",
"name",
",",
"\"%s:plays\"",
"%",
"choice",
",",
"count",
")",
"self",
".",
"... | Increments the play count for a given experiment choice | [
"Increments",
"the",
"play",
"count",
"for",
"a",
"given",
"experiment",
"choice"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L244-L247 |
dailymuse/oz | oz/bandit/__init__.py | Experiment.compute_default_choice | def compute_default_choice(self):
"""Computes and sets the default choice"""
choices = self.choices
if len(choices) == 0:
return None
high_choice = max(choices, key=lambda choice: choice.performance)
self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "default-choice", high_choice.name)
self.refresh()
return high_choice | python | def compute_default_choice(self):
"""Computes and sets the default choice"""
choices = self.choices
if len(choices) == 0:
return None
high_choice = max(choices, key=lambda choice: choice.performance)
self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "default-choice", high_choice.name)
self.refresh()
return high_choice | [
"def",
"compute_default_choice",
"(",
"self",
")",
":",
"choices",
"=",
"self",
".",
"choices",
"if",
"len",
"(",
"choices",
")",
"==",
"0",
":",
"return",
"None",
"high_choice",
"=",
"max",
"(",
"choices",
",",
"key",
"=",
"lambda",
"choice",
":",
"ch... | Computes and sets the default choice | [
"Computes",
"and",
"sets",
"the",
"default",
"choice"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L254-L265 |
dailymuse/oz | oz/bandit/__init__.py | ExperimentChoice.refresh | def refresh(self):
"""Re-pulls the data from redis"""
redis_key = EXPERIMENT_REDIS_KEY_TEMPLATE % self.experiment.name
self.plays = int(self.experiment.redis.hget(redis_key, "%s:plays" % self.name) or 0)
self.rewards = int(self.experiment.redis.hget(redis_key, "%s:rewards" % self.name) or 0)
self.performance = float(self.rewards) / max(self.plays, 1) | python | def refresh(self):
"""Re-pulls the data from redis"""
redis_key = EXPERIMENT_REDIS_KEY_TEMPLATE % self.experiment.name
self.plays = int(self.experiment.redis.hget(redis_key, "%s:plays" % self.name) or 0)
self.rewards = int(self.experiment.redis.hget(redis_key, "%s:rewards" % self.name) or 0)
self.performance = float(self.rewards) / max(self.plays, 1) | [
"def",
"refresh",
"(",
"self",
")",
":",
"redis_key",
"=",
"EXPERIMENT_REDIS_KEY_TEMPLATE",
"%",
"self",
".",
"experiment",
".",
"name",
"self",
".",
"plays",
"=",
"int",
"(",
"self",
".",
"experiment",
".",
"redis",
".",
"hget",
"(",
"redis_key",
",",
"... | Re-pulls the data from redis | [
"Re",
"-",
"pulls",
"the",
"data",
"from",
"redis"
] | train | https://github.com/dailymuse/oz/blob/4329f6a207dc9d2a8fbeb4d16d415dbe4570b5bd/oz/bandit/__init__.py#L275-L281 |
mickybart/python-atlasapi | atlasapi/atlas.py | AlertsGetAll.fetch | def fetch(self, pageNum, itemsPerPage):
"""Intermediate fetching
Args:
pageNum (int): Page number
itemsPerPage (int): Number of Users per Page
Returns:
dict: Response payload
"""
return self.get_all_alerts(self.status, pageNum, itemsPerPage) | python | def fetch(self, pageNum, itemsPerPage):
"""Intermediate fetching
Args:
pageNum (int): Page number
itemsPerPage (int): Number of Users per Page
Returns:
dict: Response payload
"""
return self.get_all_alerts(self.status, pageNum, itemsPerPage) | [
"def",
"fetch",
"(",
"self",
",",
"pageNum",
",",
"itemsPerPage",
")",
":",
"return",
"self",
".",
"get_all_alerts",
"(",
"self",
".",
"status",
",",
"pageNum",
",",
"itemsPerPage",
")"
] | Intermediate fetching
Args:
pageNum (int): Page number
itemsPerPage (int): Number of Users per Page
Returns:
dict: Response payload | [
"Intermediate",
"fetching",
"Args",
":",
"pageNum",
"(",
"int",
")",
":",
"Page",
"number",
"itemsPerPage",
"(",
"int",
")",
":",
"Number",
"of",
"Users",
"per",
"Page",
"Returns",
":",
"dict",
":",
"Response",
"payload"
] | train | https://github.com/mickybart/python-atlasapi/blob/2962c37740998694cb55f82b375b81cc604b953e/atlasapi/atlas.py#L508-L518 |
michaelpb/omnic | omnic/utils/asynctools.py | await_all | async def await_all():
'''
Simple utility function that drains all pending tasks
'''
tasks = asyncio.Task.all_tasks()
for task in tasks:
try:
await task
except RuntimeError as e:
# Python 3.5.x: Error if attempting to await parent task
if 'Task cannot await on itself' not in str(e):
raise e
except AssertionError as e:
# Python 3.6.x: Error if attempting to await parent task
if 'yield from wasn\'t used with future' not in str(e):
raise e | python | async def await_all():
'''
Simple utility function that drains all pending tasks
'''
tasks = asyncio.Task.all_tasks()
for task in tasks:
try:
await task
except RuntimeError as e:
# Python 3.5.x: Error if attempting to await parent task
if 'Task cannot await on itself' not in str(e):
raise e
except AssertionError as e:
# Python 3.6.x: Error if attempting to await parent task
if 'yield from wasn\'t used with future' not in str(e):
raise e | [
"async",
"def",
"await_all",
"(",
")",
":",
"tasks",
"=",
"asyncio",
".",
"Task",
".",
"all_tasks",
"(",
")",
"for",
"task",
"in",
"tasks",
":",
"try",
":",
"await",
"task",
"except",
"RuntimeError",
"as",
"e",
":",
"# Python 3.5.x: Error if attempting to aw... | Simple utility function that drains all pending tasks | [
"Simple",
"utility",
"function",
"that",
"drains",
"all",
"pending",
"tasks"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/utils/asynctools.py#L7-L22 |
michaelpb/omnic | omnic/utils/asynctools.py | coerce_to_synchronous | def coerce_to_synchronous(func):
'''
Given a function that might be async, wrap it in an explicit loop so it can
be run in a synchronous context.
'''
if inspect.iscoroutinefunction(func):
@functools.wraps(func)
def sync_wrapper(*args, **kwargs):
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(func(*args, **kwargs))
finally:
loop.close()
return sync_wrapper
return func | python | def coerce_to_synchronous(func):
'''
Given a function that might be async, wrap it in an explicit loop so it can
be run in a synchronous context.
'''
if inspect.iscoroutinefunction(func):
@functools.wraps(func)
def sync_wrapper(*args, **kwargs):
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(func(*args, **kwargs))
finally:
loop.close()
return sync_wrapper
return func | [
"def",
"coerce_to_synchronous",
"(",
"func",
")",
":",
"if",
"inspect",
".",
"iscoroutinefunction",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"sync_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"lo... | Given a function that might be async, wrap it in an explicit loop so it can
be run in a synchronous context. | [
"Given",
"a",
"function",
"that",
"might",
"be",
"async",
"wrap",
"it",
"in",
"an",
"explicit",
"loop",
"so",
"it",
"can",
"be",
"run",
"in",
"a",
"synchronous",
"context",
"."
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/utils/asynctools.py#L25-L39 |
halfak/deltas | deltas/algorithms/segment_matcher.py | diff | def diff(a, b, segmenter=None):
"""
Performs a diff comparison between two sequences of tokens (`a` and `b`)
using `segmenter` to cluster and match
:class:`deltas.MatchableSegment`.
:Example:
>>> from deltas import segment_matcher, text_split
>>>
>>> a = text_split.tokenize("This is some text. This is some other text.")
>>> b = text_split.tokenize("This is some other text. This is some text.")
>>> operations = segment_matcher.diff(a, b)
>>>
>>> for op in operations:
... print(op.name, repr(''.join(a[op.a1:op.a2])),
... repr(''.join(b[op.b1:op.b2])))
...
equal 'This is some other text.' 'This is some other text.'
insert '' ' '
equal 'This is some text.' 'This is some text.'
delete ' ' ''
:Parameters:
a : `list`(:class:`deltas.tokenizers.Token`)
Initial sequence
b : `list`(:class:`deltas.tokenizers.Token`)
Changed sequence
segmenter : :class:`deltas.Segmenter`
A segmenter to use on the tokens.
:Returns:
An `iterable` of operations.
"""
a, b = list(a), list(b)
segmenter = segmenter or SEGMENTER
# Cluster the input tokens
a_segments = segmenter.segment(a)
b_segments = segmenter.segment(b)
return diff_segments(a_segments, b_segments) | python | def diff(a, b, segmenter=None):
"""
Performs a diff comparison between two sequences of tokens (`a` and `b`)
using `segmenter` to cluster and match
:class:`deltas.MatchableSegment`.
:Example:
>>> from deltas import segment_matcher, text_split
>>>
>>> a = text_split.tokenize("This is some text. This is some other text.")
>>> b = text_split.tokenize("This is some other text. This is some text.")
>>> operations = segment_matcher.diff(a, b)
>>>
>>> for op in operations:
... print(op.name, repr(''.join(a[op.a1:op.a2])),
... repr(''.join(b[op.b1:op.b2])))
...
equal 'This is some other text.' 'This is some other text.'
insert '' ' '
equal 'This is some text.' 'This is some text.'
delete ' ' ''
:Parameters:
a : `list`(:class:`deltas.tokenizers.Token`)
Initial sequence
b : `list`(:class:`deltas.tokenizers.Token`)
Changed sequence
segmenter : :class:`deltas.Segmenter`
A segmenter to use on the tokens.
:Returns:
An `iterable` of operations.
"""
a, b = list(a), list(b)
segmenter = segmenter or SEGMENTER
# Cluster the input tokens
a_segments = segmenter.segment(a)
b_segments = segmenter.segment(b)
return diff_segments(a_segments, b_segments) | [
"def",
"diff",
"(",
"a",
",",
"b",
",",
"segmenter",
"=",
"None",
")",
":",
"a",
",",
"b",
"=",
"list",
"(",
"a",
")",
",",
"list",
"(",
"b",
")",
"segmenter",
"=",
"segmenter",
"or",
"SEGMENTER",
"# Cluster the input tokens",
"a_segments",
"=",
"seg... | Performs a diff comparison between two sequences of tokens (`a` and `b`)
using `segmenter` to cluster and match
:class:`deltas.MatchableSegment`.
:Example:
>>> from deltas import segment_matcher, text_split
>>>
>>> a = text_split.tokenize("This is some text. This is some other text.")
>>> b = text_split.tokenize("This is some other text. This is some text.")
>>> operations = segment_matcher.diff(a, b)
>>>
>>> for op in operations:
... print(op.name, repr(''.join(a[op.a1:op.a2])),
... repr(''.join(b[op.b1:op.b2])))
...
equal 'This is some other text.' 'This is some other text.'
insert '' ' '
equal 'This is some text.' 'This is some text.'
delete ' ' ''
:Parameters:
a : `list`(:class:`deltas.tokenizers.Token`)
Initial sequence
b : `list`(:class:`deltas.tokenizers.Token`)
Changed sequence
segmenter : :class:`deltas.Segmenter`
A segmenter to use on the tokens.
:Returns:
An `iterable` of operations. | [
"Performs",
"a",
"diff",
"comparison",
"between",
"two",
"sequences",
"of",
"tokens",
"(",
"a",
"and",
"b",
")",
"using",
"segmenter",
"to",
"cluster",
"and",
"match",
":",
"class",
":",
"deltas",
".",
"MatchableSegment",
"."
] | train | https://github.com/halfak/deltas/blob/4173f4215b93426a877f4bb4a7a3547834e60ac3/deltas/algorithms/segment_matcher.py#L28-L68 |
halfak/deltas | deltas/algorithms/segment_matcher.py | diff_segments | def diff_segments(a_segments, b_segments):
"""
Performs a diff comparison between two pre-clustered
:class:`deltas.Segment` trees. In most cases, segmentation
takes 100X more time than actually performing the diff.
:Parameters:
a_segments : :class:`deltas.Segment`
An initial sequence
b_segments : :class:`deltas.Segment`
A changed sequence
:Returns:
An `iterable` of operations.
"""
# Match and re-sequence unmatched tokens
a_segment_tokens, b_segment_tokens = _cluster_matching_segments(a_segments,
b_segments)
# Perform a simple LCS over unmatched tokens and clusters
clustered_ops = sequence_matcher.diff(a_segment_tokens, b_segment_tokens)
# Return the expanded (de-clustered) operations
return (op for op in SegmentOperationsExpander(clustered_ops,
a_segment_tokens,
b_segment_tokens).expand()) | python | def diff_segments(a_segments, b_segments):
"""
Performs a diff comparison between two pre-clustered
:class:`deltas.Segment` trees. In most cases, segmentation
takes 100X more time than actually performing the diff.
:Parameters:
a_segments : :class:`deltas.Segment`
An initial sequence
b_segments : :class:`deltas.Segment`
A changed sequence
:Returns:
An `iterable` of operations.
"""
# Match and re-sequence unmatched tokens
a_segment_tokens, b_segment_tokens = _cluster_matching_segments(a_segments,
b_segments)
# Perform a simple LCS over unmatched tokens and clusters
clustered_ops = sequence_matcher.diff(a_segment_tokens, b_segment_tokens)
# Return the expanded (de-clustered) operations
return (op for op in SegmentOperationsExpander(clustered_ops,
a_segment_tokens,
b_segment_tokens).expand()) | [
"def",
"diff_segments",
"(",
"a_segments",
",",
"b_segments",
")",
":",
"# Match and re-sequence unmatched tokens",
"a_segment_tokens",
",",
"b_segment_tokens",
"=",
"_cluster_matching_segments",
"(",
"a_segments",
",",
"b_segments",
")",
"# Perform a simple LCS over unmatched ... | Performs a diff comparison between two pre-clustered
:class:`deltas.Segment` trees. In most cases, segmentation
takes 100X more time than actually performing the diff.
:Parameters:
a_segments : :class:`deltas.Segment`
An initial sequence
b_segments : :class:`deltas.Segment`
A changed sequence
:Returns:
An `iterable` of operations. | [
"Performs",
"a",
"diff",
"comparison",
"between",
"two",
"pre",
"-",
"clustered",
":",
"class",
":",
"deltas",
".",
"Segment",
"trees",
".",
"In",
"most",
"cases",
"segmentation",
"takes",
"100X",
"more",
"time",
"than",
"actually",
"performing",
"the",
"dif... | train | https://github.com/halfak/deltas/blob/4173f4215b93426a877f4bb4a7a3547834e60ac3/deltas/algorithms/segment_matcher.py#L71-L96 |
halfak/deltas | deltas/algorithms/segment_matcher.py | process | def process(texts, *args, **kwargs):
"""
Processes a single sequence of texts with a
:class:`~deltas.SegmentMatcher`.
:Parameters:
texts : `iterable`(`str`)
sequence of texts
args : `tuple`
passed to :class:`~deltas.SegmentMatcher`'s
constructor
kwaths : `dict`
passed to :class:`~deltas.SegmentMatcher`'s
constructor
"""
processor = SegmentMatcher.Processor(*args, **kwargs)
for text in texts:
yield processor.process(text) | python | def process(texts, *args, **kwargs):
"""
Processes a single sequence of texts with a
:class:`~deltas.SegmentMatcher`.
:Parameters:
texts : `iterable`(`str`)
sequence of texts
args : `tuple`
passed to :class:`~deltas.SegmentMatcher`'s
constructor
kwaths : `dict`
passed to :class:`~deltas.SegmentMatcher`'s
constructor
"""
processor = SegmentMatcher.Processor(*args, **kwargs)
for text in texts:
yield processor.process(text) | [
"def",
"process",
"(",
"texts",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"processor",
"=",
"SegmentMatcher",
".",
"Processor",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"text",
"in",
"texts",
":",
"yield",
"processor",
".",
... | Processes a single sequence of texts with a
:class:`~deltas.SegmentMatcher`.
:Parameters:
texts : `iterable`(`str`)
sequence of texts
args : `tuple`
passed to :class:`~deltas.SegmentMatcher`'s
constructor
kwaths : `dict`
passed to :class:`~deltas.SegmentMatcher`'s
constructor | [
"Processes",
"a",
"single",
"sequence",
"of",
"texts",
"with",
"a",
":",
"class",
":",
"~deltas",
".",
"SegmentMatcher",
"."
] | train | https://github.com/halfak/deltas/blob/4173f4215b93426a877f4bb4a7a3547834e60ac3/deltas/algorithms/segment_matcher.py#L99-L116 |
halfak/deltas | deltas/algorithms/segment_matcher.py | _get_matchable_segments | def _get_matchable_segments(segments):
"""
Performs a depth-first search of the segment tree to get all matchable
segments.
"""
for subsegment in segments:
if isinstance(subsegment, Token):
break # No tokens allowed next to segments
if isinstance(subsegment, Segment):
if isinstance(subsegment, MatchableSegment):
yield subsegment
for matchable_subsegment in _get_matchable_segments(subsegment):
yield matchable_subsegment | python | def _get_matchable_segments(segments):
"""
Performs a depth-first search of the segment tree to get all matchable
segments.
"""
for subsegment in segments:
if isinstance(subsegment, Token):
break # No tokens allowed next to segments
if isinstance(subsegment, Segment):
if isinstance(subsegment, MatchableSegment):
yield subsegment
for matchable_subsegment in _get_matchable_segments(subsegment):
yield matchable_subsegment | [
"def",
"_get_matchable_segments",
"(",
"segments",
")",
":",
"for",
"subsegment",
"in",
"segments",
":",
"if",
"isinstance",
"(",
"subsegment",
",",
"Token",
")",
":",
"break",
"# No tokens allowed next to segments",
"if",
"isinstance",
"(",
"subsegment",
",",
"Se... | Performs a depth-first search of the segment tree to get all matchable
segments. | [
"Performs",
"a",
"depth",
"-",
"first",
"search",
"of",
"the",
"segment",
"tree",
"to",
"get",
"all",
"matchable",
"segments",
"."
] | train | https://github.com/halfak/deltas/blob/4173f4215b93426a877f4bb4a7a3547834e60ac3/deltas/algorithms/segment_matcher.py#L250-L263 |
bitlabstudio/django-document-library | document_library/south_migrations/0021_migrate_placeholders.py | Migration.forwards | def forwards(self, orm):
"Write your forwards methods here."
for document in orm['document_library.Document'].objects.all():
self.migrate_placeholder(
orm, document, 'content', 'document_library_content', 'content') | python | def forwards(self, orm):
"Write your forwards methods here."
for document in orm['document_library.Document'].objects.all():
self.migrate_placeholder(
orm, document, 'content', 'document_library_content', 'content') | [
"def",
"forwards",
"(",
"self",
",",
"orm",
")",
":",
"for",
"document",
"in",
"orm",
"[",
"'document_library.Document'",
"]",
".",
"objects",
".",
"all",
"(",
")",
":",
"self",
".",
"migrate_placeholder",
"(",
"orm",
",",
"document",
",",
"'content'",
"... | Write your forwards methods here. | [
"Write",
"your",
"forwards",
"methods",
"here",
"."
] | train | https://github.com/bitlabstudio/django-document-library/blob/508737277455f182e81780cfca8d8eceb989a45b/document_library/south_migrations/0021_migrate_placeholders.py#L55-L59 |
mokelly/wabbit_wappa | wabbit_wappa/__init__.py | make_command_line | def make_command_line(predictions='/dev/stdout',
quiet=True,
save_resume=True,
q_colon=None,
**kwargs
):
"""Construct a command line for VW, with each named argument corresponding
to a VW option.
Single character keys are mapped to single-dash options,
e.g. 'b=20' yields '-b 20',
while multiple character keys map to double-dash options:
'quiet=True' yields '--quiet'
Boolean values are interpreted as flags: present if True, absent if False.
All other values are treated as option arguments, as in the -b example above.
If an option argument is a list, that option is repeated multiple times,
e.g. 'q=['ab', 'bc']' yields '-q ab -q bc'
q_colon is handled specially, mapping to '--q:'.
Run 'vw -h' for a listing of most options.
Defaults are well-suited for use with Wabbit Wappa:
vw --predictions /dev/stdout --quiet --save_resume
NOTE: This function makes no attempt to validate the inputs or
ensure they are compatible with Wabbit Wappa.
Outputs a command line string.
"""
args = ['vw']
if q_colon:
kwargs['q:'] = q_colon
kwargs['predictions'] = predictions
kwargs['quiet'] = quiet
kwargs['save_resume'] = save_resume
for key, value in kwargs.items():
if len(key)==1:
option = '-{}'.format(key)
else:
option = '--{}'.format(key)
if value is True:
arg_list = [option]
elif isinstance(value, basestring):
arg_list = ['{} {}'.format(option, value)]
elif hasattr(value, '__getitem__'): # Listlike value
arg_list = [ '{} {}'.format(option, subvalue) for subvalue in value ]
else:
arg_list = ['{} {}'.format(option, value)]
args.extend(arg_list)
command = ' '.join(args)
return command | python | def make_command_line(predictions='/dev/stdout',
quiet=True,
save_resume=True,
q_colon=None,
**kwargs
):
"""Construct a command line for VW, with each named argument corresponding
to a VW option.
Single character keys are mapped to single-dash options,
e.g. 'b=20' yields '-b 20',
while multiple character keys map to double-dash options:
'quiet=True' yields '--quiet'
Boolean values are interpreted as flags: present if True, absent if False.
All other values are treated as option arguments, as in the -b example above.
If an option argument is a list, that option is repeated multiple times,
e.g. 'q=['ab', 'bc']' yields '-q ab -q bc'
q_colon is handled specially, mapping to '--q:'.
Run 'vw -h' for a listing of most options.
Defaults are well-suited for use with Wabbit Wappa:
vw --predictions /dev/stdout --quiet --save_resume
NOTE: This function makes no attempt to validate the inputs or
ensure they are compatible with Wabbit Wappa.
Outputs a command line string.
"""
args = ['vw']
if q_colon:
kwargs['q:'] = q_colon
kwargs['predictions'] = predictions
kwargs['quiet'] = quiet
kwargs['save_resume'] = save_resume
for key, value in kwargs.items():
if len(key)==1:
option = '-{}'.format(key)
else:
option = '--{}'.format(key)
if value is True:
arg_list = [option]
elif isinstance(value, basestring):
arg_list = ['{} {}'.format(option, value)]
elif hasattr(value, '__getitem__'): # Listlike value
arg_list = [ '{} {}'.format(option, subvalue) for subvalue in value ]
else:
arg_list = ['{} {}'.format(option, value)]
args.extend(arg_list)
command = ' '.join(args)
return command | [
"def",
"make_command_line",
"(",
"predictions",
"=",
"'/dev/stdout'",
",",
"quiet",
"=",
"True",
",",
"save_resume",
"=",
"True",
",",
"q_colon",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"'vw'",
"]",
"if",
"q_colon",
":",
"kwar... | Construct a command line for VW, with each named argument corresponding
to a VW option.
Single character keys are mapped to single-dash options,
e.g. 'b=20' yields '-b 20',
while multiple character keys map to double-dash options:
'quiet=True' yields '--quiet'
Boolean values are interpreted as flags: present if True, absent if False.
All other values are treated as option arguments, as in the -b example above.
If an option argument is a list, that option is repeated multiple times,
e.g. 'q=['ab', 'bc']' yields '-q ab -q bc'
q_colon is handled specially, mapping to '--q:'.
Run 'vw -h' for a listing of most options.
Defaults are well-suited for use with Wabbit Wappa:
vw --predictions /dev/stdout --quiet --save_resume
NOTE: This function makes no attempt to validate the inputs or
ensure they are compatible with Wabbit Wappa.
Outputs a command line string. | [
"Construct",
"a",
"command",
"line",
"for",
"VW",
"with",
"each",
"named",
"argument",
"corresponding",
"to",
"a",
"VW",
"option",
".",
"Single",
"character",
"keys",
"are",
"mapped",
"to",
"single",
"-",
"dash",
"options",
"e",
".",
"g",
".",
"b",
"=",
... | train | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/wabbit_wappa/__init__.py#L396-L446 |
mokelly/wabbit_wappa | wabbit_wappa/__init__.py | Namespace.add_features | def add_features(self, features):
"""Add features to this namespace.
features: An iterable of features. A feature may be either
1) A VW label (not containing characters from escape_dict.keys(),
unless 'escape' mode is on)
2) A tuple (label, value) where value is any float
"""
for feature in features:
if isinstance(feature, basestring):
label = feature
value = None
else:
label, value = feature
self.add_feature(label, value) | python | def add_features(self, features):
"""Add features to this namespace.
features: An iterable of features. A feature may be either
1) A VW label (not containing characters from escape_dict.keys(),
unless 'escape' mode is on)
2) A tuple (label, value) where value is any float
"""
for feature in features:
if isinstance(feature, basestring):
label = feature
value = None
else:
label, value = feature
self.add_feature(label, value) | [
"def",
"add_features",
"(",
"self",
",",
"features",
")",
":",
"for",
"feature",
"in",
"features",
":",
"if",
"isinstance",
"(",
"feature",
",",
"basestring",
")",
":",
"label",
"=",
"feature",
"value",
"=",
"None",
"else",
":",
"label",
",",
"value",
... | Add features to this namespace.
features: An iterable of features. A feature may be either
1) A VW label (not containing characters from escape_dict.keys(),
unless 'escape' mode is on)
2) A tuple (label, value) where value is any float | [
"Add",
"features",
"to",
"this",
"namespace",
".",
"features",
":",
"An",
"iterable",
"of",
"features",
".",
"A",
"feature",
"may",
"be",
"either",
"1",
")",
"A",
"VW",
"label",
"(",
"not",
"containing",
"characters",
"from",
"escape_dict",
".",
"keys",
... | train | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/wabbit_wappa/__init__.py#L101-L114 |
mokelly/wabbit_wappa | wabbit_wappa/__init__.py | Namespace.add_feature | def add_feature(self, label, value=None):
"""
label: A VW label (not containing characters from escape_dict.keys(),
unless 'escape' mode is on)
value: float giving the weight or magnitude of this feature
"""
if self.escape:
label = escape_vw_string(label)
elif self.validate:
validate_vw_string(label)
feature = (label, value)
self.features.append(feature) | python | def add_feature(self, label, value=None):
"""
label: A VW label (not containing characters from escape_dict.keys(),
unless 'escape' mode is on)
value: float giving the weight or magnitude of this feature
"""
if self.escape:
label = escape_vw_string(label)
elif self.validate:
validate_vw_string(label)
feature = (label, value)
self.features.append(feature) | [
"def",
"add_feature",
"(",
"self",
",",
"label",
",",
"value",
"=",
"None",
")",
":",
"if",
"self",
".",
"escape",
":",
"label",
"=",
"escape_vw_string",
"(",
"label",
")",
"elif",
"self",
".",
"validate",
":",
"validate_vw_string",
"(",
"label",
")",
... | label: A VW label (not containing characters from escape_dict.keys(),
unless 'escape' mode is on)
value: float giving the weight or magnitude of this feature | [
"label",
":",
"A",
"VW",
"label",
"(",
"not",
"containing",
"characters",
"from",
"escape_dict",
".",
"keys",
"()",
"unless",
"escape",
"mode",
"is",
"on",
")",
"value",
":",
"float",
"giving",
"the",
"weight",
"or",
"magnitude",
"of",
"this",
"feature"
] | train | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/wabbit_wappa/__init__.py#L116-L127 |
mokelly/wabbit_wappa | wabbit_wappa/__init__.py | Namespace.to_string | def to_string(self):
"""Export this namespace to a string suitable for incorporation
in a VW example line, e.g.
'MetricFeatures:3.28 height:1.5 length:2.0 '
"""
if self._string is None:
tokens = []
if self.name:
if self.scale:
token = self.name + ':' + str(self.scale)
else:
token = self.name
else:
token = '' # Spacing element to indicate next string is a feature
tokens.append(token)
for label, value in self.features:
if value is None:
token = label
else:
token = label + ':' + str(value)
tokens.append(token)
tokens.append('') # Spacing element to separate from next pipe character
output = ' '.join(tokens)
if self.cache_string:
self._string = output
else:
output = self._string
return output | python | def to_string(self):
"""Export this namespace to a string suitable for incorporation
in a VW example line, e.g.
'MetricFeatures:3.28 height:1.5 length:2.0 '
"""
if self._string is None:
tokens = []
if self.name:
if self.scale:
token = self.name + ':' + str(self.scale)
else:
token = self.name
else:
token = '' # Spacing element to indicate next string is a feature
tokens.append(token)
for label, value in self.features:
if value is None:
token = label
else:
token = label + ':' + str(value)
tokens.append(token)
tokens.append('') # Spacing element to separate from next pipe character
output = ' '.join(tokens)
if self.cache_string:
self._string = output
else:
output = self._string
return output | [
"def",
"to_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"_string",
"is",
"None",
":",
"tokens",
"=",
"[",
"]",
"if",
"self",
".",
"name",
":",
"if",
"self",
".",
"scale",
":",
"token",
"=",
"self",
".",
"name",
"+",
"':'",
"+",
"str",
"("... | Export this namespace to a string suitable for incorporation
in a VW example line, e.g.
'MetricFeatures:3.28 height:1.5 length:2.0 ' | [
"Export",
"this",
"namespace",
"to",
"a",
"string",
"suitable",
"for",
"incorporation",
"in",
"a",
"VW",
"example",
"line",
"e",
".",
"g",
".",
"MetricFeatures",
":",
"3",
".",
"28",
"height",
":",
"1",
".",
"5",
"length",
":",
"2",
".",
"0"
] | train | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/wabbit_wappa/__init__.py#L129-L156 |
mokelly/wabbit_wappa | wabbit_wappa/__init__.py | Namespace.export_features | def export_features(self, delimiter='\\'):
"""Export the features from this namespace as a list of feature tokens
with the namespace name prepended (delimited by 'delimiter').
Example:
>>> namespace = Namespace('name1', features=['feature1', 'feature2'])
>>> print namespace.export_features()
['name1\\feature1', 'name1\\feature2']
"""
result_list = []
for feature in self.features:
result = '{}{}{}'.format(self.name, delimiter, feature)
result_list.append(result)
return result_list | python | def export_features(self, delimiter='\\'):
"""Export the features from this namespace as a list of feature tokens
with the namespace name prepended (delimited by 'delimiter').
Example:
>>> namespace = Namespace('name1', features=['feature1', 'feature2'])
>>> print namespace.export_features()
['name1\\feature1', 'name1\\feature2']
"""
result_list = []
for feature in self.features:
result = '{}{}{}'.format(self.name, delimiter, feature)
result_list.append(result)
return result_list | [
"def",
"export_features",
"(",
"self",
",",
"delimiter",
"=",
"'\\\\'",
")",
":",
"result_list",
"=",
"[",
"]",
"for",
"feature",
"in",
"self",
".",
"features",
":",
"result",
"=",
"'{}{}{}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"delimiter",
... | Export the features from this namespace as a list of feature tokens
with the namespace name prepended (delimited by 'delimiter').
Example:
>>> namespace = Namespace('name1', features=['feature1', 'feature2'])
>>> print namespace.export_features()
['name1\\feature1', 'name1\\feature2'] | [
"Export",
"the",
"features",
"from",
"this",
"namespace",
"as",
"a",
"list",
"of",
"feature",
"tokens",
"with",
"the",
"namespace",
"name",
"prepended",
"(",
"delimited",
"by",
"delimiter",
")",
"."
] | train | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/wabbit_wappa/__init__.py#L158-L171 |
mokelly/wabbit_wappa | wabbit_wappa/__init__.py | VW.send_line | def send_line(self, line, parse_result=True):
"""Submit a raw line of text to the VW instance, returning a
VWResult() object.
If 'parse_result' is False, ignore the result and return None.
"""
self.vw_process.sendline(line) # Send line, along with newline
result = self._get_response(parse_result=parse_result)
return result | python | def send_line(self, line, parse_result=True):
"""Submit a raw line of text to the VW instance, returning a
VWResult() object.
If 'parse_result' is False, ignore the result and return None.
"""
self.vw_process.sendline(line) # Send line, along with newline
result = self._get_response(parse_result=parse_result)
return result | [
"def",
"send_line",
"(",
"self",
",",
"line",
",",
"parse_result",
"=",
"True",
")",
":",
"self",
".",
"vw_process",
".",
"sendline",
"(",
"line",
")",
"# Send line, along with newline",
"result",
"=",
"self",
".",
"_get_response",
"(",
"parse_result",
"=",
... | Submit a raw line of text to the VW instance, returning a
VWResult() object.
If 'parse_result' is False, ignore the result and return None. | [
"Submit",
"a",
"raw",
"line",
"of",
"text",
"to",
"the",
"VW",
"instance",
"returning",
"a",
"VWResult",
"()",
"object",
"."
] | train | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/wabbit_wappa/__init__.py#L253-L261 |
mokelly/wabbit_wappa | wabbit_wappa/__init__.py | VW._get_response | def _get_response(self, parse_result=True):
"""If 'parse_result' is False, ignore the received output and return None."""
# expect_exact is faster than just exact, and fine for our purpose
# (http://pexpect.readthedocs.org/en/latest/api/pexpect.html#pexpect.spawn.expect_exact)
# searchwindowsize and other attributes may also affect efficiency
self.vw_process.expect_exact('\r\n', searchwindowsize=-1) # Wait until process outputs a complete line
if parse_result:
output = self.vw_process.before
result_struct = VWResult(output, active_mode=self.active_mode)
else:
result_struct = None
return result_struct | python | def _get_response(self, parse_result=True):
"""If 'parse_result' is False, ignore the received output and return None."""
# expect_exact is faster than just exact, and fine for our purpose
# (http://pexpect.readthedocs.org/en/latest/api/pexpect.html#pexpect.spawn.expect_exact)
# searchwindowsize and other attributes may also affect efficiency
self.vw_process.expect_exact('\r\n', searchwindowsize=-1) # Wait until process outputs a complete line
if parse_result:
output = self.vw_process.before
result_struct = VWResult(output, active_mode=self.active_mode)
else:
result_struct = None
return result_struct | [
"def",
"_get_response",
"(",
"self",
",",
"parse_result",
"=",
"True",
")",
":",
"# expect_exact is faster than just exact, and fine for our purpose",
"# (http://pexpect.readthedocs.org/en/latest/api/pexpect.html#pexpect.spawn.expect_exact)",
"# searchwindowsize and other attributes may also... | If 'parse_result' is False, ignore the received output and return None. | [
"If",
"parse_result",
"is",
"False",
"ignore",
"the",
"received",
"output",
"and",
"return",
"None",
"."
] | train | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/wabbit_wappa/__init__.py#L263-L274 |
mokelly/wabbit_wappa | wabbit_wappa/__init__.py | VW.send_example | def send_example(self,
*args,
**kwargs
):
"""Send a labeled or unlabeled example to the VW instance.
If 'parse_result' kwarg is False, ignore the result and return None.
All other parameters are passed to self.send_line().
Returns a VWResult object.
"""
# Pop out the keyword argument 'parse_result' if given
parse_result = kwargs.pop('parse_result', True)
line = self.make_line(*args, **kwargs)
result = self.send_line(line, parse_result=parse_result)
return result | python | def send_example(self,
*args,
**kwargs
):
"""Send a labeled or unlabeled example to the VW instance.
If 'parse_result' kwarg is False, ignore the result and return None.
All other parameters are passed to self.send_line().
Returns a VWResult object.
"""
# Pop out the keyword argument 'parse_result' if given
parse_result = kwargs.pop('parse_result', True)
line = self.make_line(*args, **kwargs)
result = self.send_line(line, parse_result=parse_result)
return result | [
"def",
"send_example",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Pop out the keyword argument 'parse_result' if given",
"parse_result",
"=",
"kwargs",
".",
"pop",
"(",
"'parse_result'",
",",
"True",
")",
"line",
"=",
"self",
".",
"ma... | Send a labeled or unlabeled example to the VW instance.
If 'parse_result' kwarg is False, ignore the result and return None.
All other parameters are passed to self.send_line().
Returns a VWResult object. | [
"Send",
"a",
"labeled",
"or",
"unlabeled",
"example",
"to",
"the",
"VW",
"instance",
".",
"If",
"parse_result",
"kwarg",
"is",
"False",
"ignore",
"the",
"result",
"and",
"return",
"None",
"."
] | train | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/wabbit_wappa/__init__.py#L276-L291 |
mokelly/wabbit_wappa | wabbit_wappa/__init__.py | VW.make_line | def make_line(self,
response=None,
importance=None,
base=None,
tag=None,
features=None,
namespaces=None,
):
"""Makes and returns an example string in VW syntax.
If given, 'response', 'importance', 'base', and 'tag' are used
to label the example. Features for the example come from
any given features or namespaces, as well as any previously
added namespaces (using them up in the process).
"""
if namespaces is not None:
self.add_namespaces(namespaces)
if features is not None:
namespace = Namespace(features=features)
self.add_namespace(namespace)
substrings = []
tokens = []
if response is not None:
token = str(response)
tokens.append(token)
if importance is not None: # Check only if response is given
token = str(importance)
tokens.append(token)
if base is not None: # Check only if importance is given
token = str(base)
tokens.append(token)
if tag is not None:
token = "'" + str(tag) # Tags are unambiguous if given a ' prefix
tokens.append(token)
else:
token = "" # Spacing element to avoid ambiguity in parsing
tokens.append(token)
substring = ' '.join(tokens)
substrings.append(substring)
if self.namespaces:
for namespace in self.namespaces:
substring = namespace.to_string()
substrings.append(substring)
else:
substrings.append('') # For correct syntax
line = '|'.join(substrings)
self._line = line
self.namespaces = [] # Reset namespaces after their use
return line | python | def make_line(self,
response=None,
importance=None,
base=None,
tag=None,
features=None,
namespaces=None,
):
"""Makes and returns an example string in VW syntax.
If given, 'response', 'importance', 'base', and 'tag' are used
to label the example. Features for the example come from
any given features or namespaces, as well as any previously
added namespaces (using them up in the process).
"""
if namespaces is not None:
self.add_namespaces(namespaces)
if features is not None:
namespace = Namespace(features=features)
self.add_namespace(namespace)
substrings = []
tokens = []
if response is not None:
token = str(response)
tokens.append(token)
if importance is not None: # Check only if response is given
token = str(importance)
tokens.append(token)
if base is not None: # Check only if importance is given
token = str(base)
tokens.append(token)
if tag is not None:
token = "'" + str(tag) # Tags are unambiguous if given a ' prefix
tokens.append(token)
else:
token = "" # Spacing element to avoid ambiguity in parsing
tokens.append(token)
substring = ' '.join(tokens)
substrings.append(substring)
if self.namespaces:
for namespace in self.namespaces:
substring = namespace.to_string()
substrings.append(substring)
else:
substrings.append('') # For correct syntax
line = '|'.join(substrings)
self._line = line
self.namespaces = [] # Reset namespaces after their use
return line | [
"def",
"make_line",
"(",
"self",
",",
"response",
"=",
"None",
",",
"importance",
"=",
"None",
",",
"base",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"features",
"=",
"None",
",",
"namespaces",
"=",
"None",
",",
")",
":",
"if",
"namespaces",
"is",
... | Makes and returns an example string in VW syntax.
If given, 'response', 'importance', 'base', and 'tag' are used
to label the example. Features for the example come from
any given features or namespaces, as well as any previously
added namespaces (using them up in the process). | [
"Makes",
"and",
"returns",
"an",
"example",
"string",
"in",
"VW",
"syntax",
".",
"If",
"given",
"response",
"importance",
"base",
"and",
"tag",
"are",
"used",
"to",
"label",
"the",
"example",
".",
"Features",
"for",
"the",
"example",
"come",
"from",
"any",... | train | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/wabbit_wappa/__init__.py#L293-L340 |
mokelly/wabbit_wappa | wabbit_wappa/__init__.py | VW.add_namespace | def add_namespace(self, *args, **kwargs):
"""Accepts two calling patterns:
add_namespace(namespace): queue a preexisting namespace onto
this VW instance.
add_namespace(name, scale, features, ...): Pass all args and kwargs
to the Namespace constructor to make a new Namespace instance,
and queue it to this VW instance.
Returns self (so that this command can be chained).
"""
if args and isinstance(args[0], Namespace):
namespace = args[0]
elif isinstance(kwargs.get('namespace'), Namespace):
namespace = kwargs.get('namespace')
else:
namespace = Namespace(*args, **kwargs)
self.namespaces.append(namespace)
return self | python | def add_namespace(self, *args, **kwargs):
"""Accepts two calling patterns:
add_namespace(namespace): queue a preexisting namespace onto
this VW instance.
add_namespace(name, scale, features, ...): Pass all args and kwargs
to the Namespace constructor to make a new Namespace instance,
and queue it to this VW instance.
Returns self (so that this command can be chained).
"""
if args and isinstance(args[0], Namespace):
namespace = args[0]
elif isinstance(kwargs.get('namespace'), Namespace):
namespace = kwargs.get('namespace')
else:
namespace = Namespace(*args, **kwargs)
self.namespaces.append(namespace)
return self | [
"def",
"add_namespace",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"Namespace",
")",
":",
"namespace",
"=",
"args",
"[",
"0",
"]",
"elif",
"isinstance",
"(",... | Accepts two calling patterns:
add_namespace(namespace): queue a preexisting namespace onto
this VW instance.
add_namespace(name, scale, features, ...): Pass all args and kwargs
to the Namespace constructor to make a new Namespace instance,
and queue it to this VW instance.
Returns self (so that this command can be chained). | [
"Accepts",
"two",
"calling",
"patterns",
":",
"add_namespace",
"(",
"namespace",
")",
":",
"queue",
"a",
"preexisting",
"namespace",
"onto",
"this",
"VW",
"instance",
".",
"add_namespace",
"(",
"name",
"scale",
"features",
"...",
")",
":",
"Pass",
"all",
"ar... | train | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/wabbit_wappa/__init__.py#L342-L359 |
mokelly/wabbit_wappa | wabbit_wappa/__init__.py | VW.get_prediction | def get_prediction(self, features=None, tag=None, namespaces=None):
"""Send an unlabeled example to the trained VW instance.
Uses any given features or namespaces, as well as any previously
added namespaces (using them up in the process).
Returns a VWResult object."""
if features is not None:
namespace = Namespace(features=features)
self.add_namespace(namespace)
result = self.send_example(tag=tag, namespaces=namespaces)
return result | python | def get_prediction(self, features=None, tag=None, namespaces=None):
"""Send an unlabeled example to the trained VW instance.
Uses any given features or namespaces, as well as any previously
added namespaces (using them up in the process).
Returns a VWResult object."""
if features is not None:
namespace = Namespace(features=features)
self.add_namespace(namespace)
result = self.send_example(tag=tag, namespaces=namespaces)
return result | [
"def",
"get_prediction",
"(",
"self",
",",
"features",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"namespaces",
"=",
"None",
")",
":",
"if",
"features",
"is",
"not",
"None",
":",
"namespace",
"=",
"Namespace",
"(",
"features",
"=",
"features",
")",
"se... | Send an unlabeled example to the trained VW instance.
Uses any given features or namespaces, as well as any previously
added namespaces (using them up in the process).
Returns a VWResult object. | [
"Send",
"an",
"unlabeled",
"example",
"to",
"the",
"trained",
"VW",
"instance",
".",
"Uses",
"any",
"given",
"features",
"or",
"namespaces",
"as",
"well",
"as",
"any",
"previously",
"added",
"namespaces",
"(",
"using",
"them",
"up",
"in",
"the",
"process",
... | train | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/wabbit_wappa/__init__.py#L368-L378 |
mokelly/wabbit_wappa | wabbit_wappa/__init__.py | VW.save_model | def save_model(self, model_filename):
"""Pass a "command example" to the VW subprocess requesting
that the current model be serialized to model_filename immediately.
"""
line = "save_{}|".format(model_filename)
self.vw_process.sendline(line) | python | def save_model(self, model_filename):
"""Pass a "command example" to the VW subprocess requesting
that the current model be serialized to model_filename immediately.
"""
line = "save_{}|".format(model_filename)
self.vw_process.sendline(line) | [
"def",
"save_model",
"(",
"self",
",",
"model_filename",
")",
":",
"line",
"=",
"\"save_{}|\"",
".",
"format",
"(",
"model_filename",
")",
"self",
".",
"vw_process",
".",
"sendline",
"(",
"line",
")"
] | Pass a "command example" to the VW subprocess requesting
that the current model be serialized to model_filename immediately. | [
"Pass",
"a",
"command",
"example",
"to",
"the",
"VW",
"subprocess",
"requesting",
"that",
"the",
"current",
"model",
"be",
"serialized",
"to",
"model_filename",
"immediately",
"."
] | train | https://github.com/mokelly/wabbit_wappa/blob/dfe5bf6d6036079e473c4148335cd6f339d0299b/wabbit_wappa/__init__.py#L380-L385 |
michaelpb/omnic | omnic/web/server.py | WebServer.route_path | def route_path(self, path):
'''
Hacky function that's presently only useful for testing, gets the view
that handles the given path.
Later may be incorporated into the URL routing
'''
path = path.strip('/')
name, _, subpath = path.partition('/')
for service in singletons.settings.load_all('SERVICES'):
if service.SERVICE_NAME == name: # Found service!
break
else:
return [], None # found no service
for partial_url, view in service.urls.items():
partial_url = partial_url.strip('/')
if isinstance(view, str):
view = getattr(service, view)
regexp = re.sub(r'<[^>]+>', r'([^/]+)', partial_url)
matches = re.findall('^%s$' % regexp, subpath)
if matches:
if '(' not in regexp:
matches = []
return matches, view
return [], None | python | def route_path(self, path):
'''
Hacky function that's presently only useful for testing, gets the view
that handles the given path.
Later may be incorporated into the URL routing
'''
path = path.strip('/')
name, _, subpath = path.partition('/')
for service in singletons.settings.load_all('SERVICES'):
if service.SERVICE_NAME == name: # Found service!
break
else:
return [], None # found no service
for partial_url, view in service.urls.items():
partial_url = partial_url.strip('/')
if isinstance(view, str):
view = getattr(service, view)
regexp = re.sub(r'<[^>]+>', r'([^/]+)', partial_url)
matches = re.findall('^%s$' % regexp, subpath)
if matches:
if '(' not in regexp:
matches = []
return matches, view
return [], None | [
"def",
"route_path",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"path",
".",
"strip",
"(",
"'/'",
")",
"name",
",",
"_",
",",
"subpath",
"=",
"path",
".",
"partition",
"(",
"'/'",
")",
"for",
"service",
"in",
"singletons",
".",
"settings",
".... | Hacky function that's presently only useful for testing, gets the view
that handles the given path.
Later may be incorporated into the URL routing | [
"Hacky",
"function",
"that",
"s",
"presently",
"only",
"useful",
"for",
"testing",
"gets",
"the",
"view",
"that",
"handles",
"the",
"given",
"path",
".",
"Later",
"may",
"be",
"incorporated",
"into",
"the",
"URL",
"routing"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/web/server.py#L50-L75 |
biocore/burrito-fillings | bfillings/rtax.py | assign_taxonomy | def assign_taxonomy(dataPath, reference_sequences_fp, id_to_taxonomy_fp, read_1_seqs_fp, read_2_seqs_fp, single_ok=False, no_single_ok_generic=False,
header_id_regex=None, read_id_regex = "\S+\s+(\S+)", amplicon_id_regex = "(\S+)\s+(\S+?)\/",
output_fp=None, log_path=None, HALT_EXEC=False, base_tmp_dir = '/tmp'):
"""Assign taxonomy to each sequence in data with the RTAX classifier
# data: open fasta file object or list of fasta lines
dataPath: path to a fasta file
output_fp: path to write output; if not provided, result will be
returned in a dict of {seq_id:(taxonomy_assignment,confidence)}
"""
usearch_command = "usearch"
if not (exists(usearch_command) or app_path(usearch_command)):
raise ApplicationNotFoundError,\
"Cannot find %s. Is it installed? Is it in your path?"\
% usearch_command
my_tmp_dir = get_tmp_filename(tmp_dir=base_tmp_dir,prefix='rtax_',suffix='',result_constructor=str)
os.makedirs(my_tmp_dir)
try:
# RTAX classifier doesn't necessarily preserve identifiers
# it reports back only the id extracted as $1 using header_id_regex
# since rtax takes the original unclustered sequence files as input,
# the usual case is that the regex extracts the amplicon ID from the second field
# Use lookup table
read_1_id_to_orig_id = {}
readIdExtractor = re.compile(read_id_regex) # OTU clustering produces ">clusterID read_1_id"
data = open(dataPath,'r')
for seq_id, seq in parse_fasta(data):
# apply the regex
extract = readIdExtractor.match(seq_id)
if extract is None:
stderr.write("Matched no ID with read_id_regex " + read_id_regex +" in '" + seq_id + "' from file " + dataPath + "\n")
else:
read_1_id_to_orig_id[extract.group(1)] = seq_id
#stderr.write(extract.group(1) + " => " + seq_id + "\n")
#seq_id_lookup[seq_id.split()[1]] = seq_id
data.close()
# make list of amplicon IDs to pass to RTAX
id_list_fp = open(my_tmp_dir+"/ampliconIdsToClassify", "w")
# Establish mapping of amplicon IDs to read_1 IDs
# simultaneously write the amplicon ID file for those IDs found in the input mapping above
amplicon_to_read_1_id = {}
ampliconIdExtractor = re.compile(amplicon_id_regex) # split_libraries produces >read_1_id ampliconID/1 ... // see also assign_taxonomy 631
read_1_data = open(read_1_seqs_fp,'r')
for seq_id, seq in parse_fasta(read_1_data):
# apply the regex
extract = ampliconIdExtractor.match(seq_id)
if extract is None:
stderr.write("Matched no ID with amplicon_id_regex " + amplicon_id_regex + " in '" + seq_id + "' from file " + read_1_seqs_fp + "\n")
else:
read_1_id = extract.group(1)
amplicon_id = extract.group(2)
try:
amplicon_to_read_1_id[amplicon_id] = read_1_id
bogus = read_1_id_to_orig_id[read_1_id] # verify that the id is valid
id_list_fp.write('%s\n' % (amplicon_id))
except KeyError:
pass
data.close()
id_list_fp.close()
app = Rtax(HALT_EXEC=HALT_EXEC)
temp_output_file = tempfile.NamedTemporaryFile(
prefix='RtaxAssignments_', suffix='.txt')
app.Parameters['-o'].on(temp_output_file.name)
app.Parameters['-r'].on(reference_sequences_fp)
app.Parameters['-t'].on(id_to_taxonomy_fp)
# app.Parameters['-d'].on(delimiter)
app.Parameters['-l'].on(id_list_fp.name) # these are amplicon IDs
app.Parameters['-a'].on(read_1_seqs_fp)
if read_2_seqs_fp is not None:
app.Parameters['-b'].on(read_2_seqs_fp)
app.Parameters['-i'].on(header_id_regex)
app.Parameters['-m'].on(my_tmp_dir)
if single_ok: app.Parameters['-f'].on();
if no_single_ok_generic: app.Parameters['-g'].on();
#app.Parameters['-v'].on()
app_result = app()
if log_path:
f=open(log_path, 'a')
errString=''.join(app_result['StdErr'].readlines()) + '\n'
f.write(errString)
f.close()
assignments = {}
# restore original sequence IDs with spaces
for line in app_result['Assignments']:
toks = line.strip().split('\t')
rtax_id = toks.pop(0)
if len(toks):
bestpcid = toks.pop(0) # ignored
lineage = toks
# RTAX does not provide a measure of confidence. We could pass one in,
# based on the choice of primers, or even look it up on the fly in the tables
# from the "optimal primers" paper; but it would be the same for every
# query sequence anyway.
# we could also return bestpcid, but that's not the same thing as confidence.
confidence = 1.0
read_1_id = amplicon_to_read_1_id[rtax_id]
orig_id = read_1_id_to_orig_id[read_1_id]
if lineage:
assignments[orig_id] = (';'.join(lineage), confidence)
else:
assignments[orig_id] = ('Unclassified', 1.0)
if output_fp:
try:
output_file = open(output_fp, 'w')
except OSError:
raise OSError("Can't open output file for writing: %s" % output_fp)
for seq_id, assignment in assignments.items():
lineage, confidence = assignment
output_file.write(
'%s\t%s\t%1.3f\n' % (seq_id, lineage, confidence))
output_file.close()
return None
else:
return assignments
finally:
try:
rmtree(my_tmp_dir)
except OSError:
pass | python | def assign_taxonomy(dataPath, reference_sequences_fp, id_to_taxonomy_fp, read_1_seqs_fp, read_2_seqs_fp, single_ok=False, no_single_ok_generic=False,
header_id_regex=None, read_id_regex = "\S+\s+(\S+)", amplicon_id_regex = "(\S+)\s+(\S+?)\/",
output_fp=None, log_path=None, HALT_EXEC=False, base_tmp_dir = '/tmp'):
"""Assign taxonomy to each sequence in data with the RTAX classifier
# data: open fasta file object or list of fasta lines
dataPath: path to a fasta file
output_fp: path to write output; if not provided, result will be
returned in a dict of {seq_id:(taxonomy_assignment,confidence)}
"""
usearch_command = "usearch"
if not (exists(usearch_command) or app_path(usearch_command)):
raise ApplicationNotFoundError,\
"Cannot find %s. Is it installed? Is it in your path?"\
% usearch_command
my_tmp_dir = get_tmp_filename(tmp_dir=base_tmp_dir,prefix='rtax_',suffix='',result_constructor=str)
os.makedirs(my_tmp_dir)
try:
# RTAX classifier doesn't necessarily preserve identifiers
# it reports back only the id extracted as $1 using header_id_regex
# since rtax takes the original unclustered sequence files as input,
# the usual case is that the regex extracts the amplicon ID from the second field
# Use lookup table
read_1_id_to_orig_id = {}
readIdExtractor = re.compile(read_id_regex) # OTU clustering produces ">clusterID read_1_id"
data = open(dataPath,'r')
for seq_id, seq in parse_fasta(data):
# apply the regex
extract = readIdExtractor.match(seq_id)
if extract is None:
stderr.write("Matched no ID with read_id_regex " + read_id_regex +" in '" + seq_id + "' from file " + dataPath + "\n")
else:
read_1_id_to_orig_id[extract.group(1)] = seq_id
#stderr.write(extract.group(1) + " => " + seq_id + "\n")
#seq_id_lookup[seq_id.split()[1]] = seq_id
data.close()
# make list of amplicon IDs to pass to RTAX
id_list_fp = open(my_tmp_dir+"/ampliconIdsToClassify", "w")
# Establish mapping of amplicon IDs to read_1 IDs
# simultaneously write the amplicon ID file for those IDs found in the input mapping above
amplicon_to_read_1_id = {}
ampliconIdExtractor = re.compile(amplicon_id_regex) # split_libraries produces >read_1_id ampliconID/1 ... // see also assign_taxonomy 631
read_1_data = open(read_1_seqs_fp,'r')
for seq_id, seq in parse_fasta(read_1_data):
# apply the regex
extract = ampliconIdExtractor.match(seq_id)
if extract is None:
stderr.write("Matched no ID with amplicon_id_regex " + amplicon_id_regex + " in '" + seq_id + "' from file " + read_1_seqs_fp + "\n")
else:
read_1_id = extract.group(1)
amplicon_id = extract.group(2)
try:
amplicon_to_read_1_id[amplicon_id] = read_1_id
bogus = read_1_id_to_orig_id[read_1_id] # verify that the id is valid
id_list_fp.write('%s\n' % (amplicon_id))
except KeyError:
pass
data.close()
id_list_fp.close()
app = Rtax(HALT_EXEC=HALT_EXEC)
temp_output_file = tempfile.NamedTemporaryFile(
prefix='RtaxAssignments_', suffix='.txt')
app.Parameters['-o'].on(temp_output_file.name)
app.Parameters['-r'].on(reference_sequences_fp)
app.Parameters['-t'].on(id_to_taxonomy_fp)
# app.Parameters['-d'].on(delimiter)
app.Parameters['-l'].on(id_list_fp.name) # these are amplicon IDs
app.Parameters['-a'].on(read_1_seqs_fp)
if read_2_seqs_fp is not None:
app.Parameters['-b'].on(read_2_seqs_fp)
app.Parameters['-i'].on(header_id_regex)
app.Parameters['-m'].on(my_tmp_dir)
if single_ok: app.Parameters['-f'].on();
if no_single_ok_generic: app.Parameters['-g'].on();
#app.Parameters['-v'].on()
app_result = app()
if log_path:
f=open(log_path, 'a')
errString=''.join(app_result['StdErr'].readlines()) + '\n'
f.write(errString)
f.close()
assignments = {}
# restore original sequence IDs with spaces
for line in app_result['Assignments']:
toks = line.strip().split('\t')
rtax_id = toks.pop(0)
if len(toks):
bestpcid = toks.pop(0) # ignored
lineage = toks
# RTAX does not provide a measure of confidence. We could pass one in,
# based on the choice of primers, or even look it up on the fly in the tables
# from the "optimal primers" paper; but it would be the same for every
# query sequence anyway.
# we could also return bestpcid, but that's not the same thing as confidence.
confidence = 1.0
read_1_id = amplicon_to_read_1_id[rtax_id]
orig_id = read_1_id_to_orig_id[read_1_id]
if lineage:
assignments[orig_id] = (';'.join(lineage), confidence)
else:
assignments[orig_id] = ('Unclassified', 1.0)
if output_fp:
try:
output_file = open(output_fp, 'w')
except OSError:
raise OSError("Can't open output file for writing: %s" % output_fp)
for seq_id, assignment in assignments.items():
lineage, confidence = assignment
output_file.write(
'%s\t%s\t%1.3f\n' % (seq_id, lineage, confidence))
output_file.close()
return None
else:
return assignments
finally:
try:
rmtree(my_tmp_dir)
except OSError:
pass | [
"def",
"assign_taxonomy",
"(",
"dataPath",
",",
"reference_sequences_fp",
",",
"id_to_taxonomy_fp",
",",
"read_1_seqs_fp",
",",
"read_2_seqs_fp",
",",
"single_ok",
"=",
"False",
",",
"no_single_ok_generic",
"=",
"False",
",",
"header_id_regex",
"=",
"None",
",",
"re... | Assign taxonomy to each sequence in data with the RTAX classifier
# data: open fasta file object or list of fasta lines
dataPath: path to a fasta file
output_fp: path to write output; if not provided, result will be
returned in a dict of {seq_id:(taxonomy_assignment,confidence)} | [
"Assign",
"taxonomy",
"to",
"each",
"sequence",
"in",
"data",
"with",
"the",
"RTAX",
"classifier"
] | train | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/rtax.py#L151-L293 |
michaelpb/omnic | omnic/utils/iters.py | pair_looper | def pair_looper(iterator):
'''
Loop through iterator yielding items in adjacent pairs
'''
left = START
for item in iterator:
if left is not START:
yield (left, item)
left = item | python | def pair_looper(iterator):
'''
Loop through iterator yielding items in adjacent pairs
'''
left = START
for item in iterator:
if left is not START:
yield (left, item)
left = item | [
"def",
"pair_looper",
"(",
"iterator",
")",
":",
"left",
"=",
"START",
"for",
"item",
"in",
"iterator",
":",
"if",
"left",
"is",
"not",
"START",
":",
"yield",
"(",
"left",
",",
"item",
")",
"left",
"=",
"item"
] | Loop through iterator yielding items in adjacent pairs | [
"Loop",
"through",
"iterator",
"yielding",
"items",
"in",
"adjacent",
"pairs"
] | train | https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/utils/iters.py#L6-L14 |
kejbaly2/metrique | metrique/utils.py | batch_gen | def batch_gen(data, batch_size):
'''
Usage::
for batch in batch_gen(iter, 100):
do_something(batch)
'''
data = data or []
for i in range(0, len(data), batch_size):
yield data[i:i + batch_size] | python | def batch_gen(data, batch_size):
'''
Usage::
for batch in batch_gen(iter, 100):
do_something(batch)
'''
data = data or []
for i in range(0, len(data), batch_size):
yield data[i:i + batch_size] | [
"def",
"batch_gen",
"(",
"data",
",",
"batch_size",
")",
":",
"data",
"=",
"data",
"or",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"batch_size",
")",
":",
"yield",
"data",
"[",
"i",
":",
"i",
"+",
"batch_... | Usage::
for batch in batch_gen(iter, 100):
do_something(batch) | [
"Usage",
"::",
"for",
"batch",
"in",
"batch_gen",
"(",
"iter",
"100",
")",
":",
"do_something",
"(",
"batch",
")"
] | train | https://github.com/kejbaly2/metrique/blob/a10b076097441b7dde687949139f702f5c1e1b35/metrique/utils.py#L186-L194 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.