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 |
|---|---|---|---|---|---|---|---|---|---|---|
flo-compbio/genometools | genometools/expression/visualize/util.py | read_colorscale | def read_colorscale(cmap_file):
"""Return a colorscale in the format expected by plotly.
Parameters
----------
cmap_file : str
Path of a plain-text file containing the colorscale.
Returns
-------
list
The colorscale.
Notes
-----
A plotly colorscale is a list where each item is a pair
(i.e., a list with two elements) consisting of
a decimal number x between 0 and 1 and a corresponding "rgb(r,g,b)" string,
where r, g, and b are integers between 0 and 255.
The `cmap_file` is a tab-separated text file containing four columns
(x,r,g,b), so that each row corresponds to an entry in the list
described above.
"""
assert isinstance(cmap_file, str)
cm = np.loadtxt(cmap_file, delimiter='\t', dtype=np.float64)
# x = cm[:, 0]
rgb = np.int64(cm[:, 1:]) # normalize to 0-1?
n = cm.shape[0]
colorscale = []
for i in range(n):
colorscale.append(
[i / float(n - 1),
'rgb(%d, %d, %d)' % (rgb[i, 0], rgb[i, 1], rgb[i, 2])]
)
return colorscale | python | def read_colorscale(cmap_file):
"""Return a colorscale in the format expected by plotly.
Parameters
----------
cmap_file : str
Path of a plain-text file containing the colorscale.
Returns
-------
list
The colorscale.
Notes
-----
A plotly colorscale is a list where each item is a pair
(i.e., a list with two elements) consisting of
a decimal number x between 0 and 1 and a corresponding "rgb(r,g,b)" string,
where r, g, and b are integers between 0 and 255.
The `cmap_file` is a tab-separated text file containing four columns
(x,r,g,b), so that each row corresponds to an entry in the list
described above.
"""
assert isinstance(cmap_file, str)
cm = np.loadtxt(cmap_file, delimiter='\t', dtype=np.float64)
# x = cm[:, 0]
rgb = np.int64(cm[:, 1:]) # normalize to 0-1?
n = cm.shape[0]
colorscale = []
for i in range(n):
colorscale.append(
[i / float(n - 1),
'rgb(%d, %d, %d)' % (rgb[i, 0], rgb[i, 1], rgb[i, 2])]
)
return colorscale | [
"def",
"read_colorscale",
"(",
"cmap_file",
")",
":",
"assert",
"isinstance",
"(",
"cmap_file",
",",
"str",
")",
"cm",
"=",
"np",
".",
"loadtxt",
"(",
"cmap_file",
",",
"delimiter",
"=",
"'\\t'",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"# x = cm[:,... | Return a colorscale in the format expected by plotly.
Parameters
----------
cmap_file : str
Path of a plain-text file containing the colorscale.
Returns
-------
list
The colorscale.
Notes
-----
A plotly colorscale is a list where each item is a pair
(i.e., a list with two elements) consisting of
a decimal number x between 0 and 1 and a corresponding "rgb(r,g,b)" string,
where r, g, and b are integers between 0 and 255.
The `cmap_file` is a tab-separated text file containing four columns
(x,r,g,b), so that each row corresponds to an entry in the list
described above. | [
"Return",
"a",
"colorscale",
"in",
"the",
"format",
"expected",
"by",
"plotly",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/visualize/util.py#L26-L62 |
openfisca/openfisca-web-api | openfisca_web_api/controllers/__init__.py | make_router | def make_router():
"""Return a WSGI application that searches requests to controllers """
global router
routings = [
('GET', '^/$', index),
('GET', '^/api/?$', index),
('POST', '^/api/1/calculate/?$', calculate.api1_calculate),
('GET', '^/api/2/entities/?$', entities.api2_entities),
('GET', '^/api/1/field/?$', field.api1_field),
('GET', '^/api/1/formula/(?P<name>[^/]+)/?$', formula.api1_formula),
('GET', '^/api/2/formula/(?:(?P<period>[A-Za-z0-9:-]*)/)?(?P<names>[A-Za-z0-9_+-]+)/?$', formula.api2_formula),
('GET', '^/api/1/parameters/?$', parameters.api1_parameters),
('GET', '^/api/1/reforms/?$', reforms.api1_reforms),
('POST', '^/api/1/simulate/?$', simulate.api1_simulate),
('GET', '^/api/1/swagger$', swagger.api1_swagger),
('GET', '^/api/1/variables/?$', variables.api1_variables),
]
router = urls.make_router(*routings)
return router | python | def make_router():
"""Return a WSGI application that searches requests to controllers """
global router
routings = [
('GET', '^/$', index),
('GET', '^/api/?$', index),
('POST', '^/api/1/calculate/?$', calculate.api1_calculate),
('GET', '^/api/2/entities/?$', entities.api2_entities),
('GET', '^/api/1/field/?$', field.api1_field),
('GET', '^/api/1/formula/(?P<name>[^/]+)/?$', formula.api1_formula),
('GET', '^/api/2/formula/(?:(?P<period>[A-Za-z0-9:-]*)/)?(?P<names>[A-Za-z0-9_+-]+)/?$', formula.api2_formula),
('GET', '^/api/1/parameters/?$', parameters.api1_parameters),
('GET', '^/api/1/reforms/?$', reforms.api1_reforms),
('POST', '^/api/1/simulate/?$', simulate.api1_simulate),
('GET', '^/api/1/swagger$', swagger.api1_swagger),
('GET', '^/api/1/variables/?$', variables.api1_variables),
]
router = urls.make_router(*routings)
return router | [
"def",
"make_router",
"(",
")",
":",
"global",
"router",
"routings",
"=",
"[",
"(",
"'GET'",
",",
"'^/$'",
",",
"index",
")",
",",
"(",
"'GET'",
",",
"'^/api/?$'",
",",
"index",
")",
",",
"(",
"'POST'",
",",
"'^/api/1/calculate/?$'",
",",
"calculate",
... | Return a WSGI application that searches requests to controllers | [
"Return",
"a",
"WSGI",
"application",
"that",
"searches",
"requests",
"to",
"controllers"
] | train | https://github.com/openfisca/openfisca-web-api/blob/d1cd3bfacac338e80bb0df7e0465b65649dd893b/openfisca_web_api/controllers/__init__.py#L31-L49 |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/ext.py | InvenioJSONSchemasState.register_schemas_dir | def register_schemas_dir(self, directory):
"""Recursively register all json-schemas in a directory.
:param directory: directory path.
"""
for root, dirs, files in os.walk(directory):
dir_path = os.path.relpath(root, directory)
if dir_path == '.':
dir_path = ''
for file_ in files:
if file_.lower().endswith(('.json')):
schema_name = os.path.join(dir_path, file_)
if schema_name in self.schemas:
raise JSONSchemaDuplicate(
schema_name,
self.schemas[schema_name],
directory
)
self.schemas[schema_name] = os.path.abspath(directory) | python | def register_schemas_dir(self, directory):
"""Recursively register all json-schemas in a directory.
:param directory: directory path.
"""
for root, dirs, files in os.walk(directory):
dir_path = os.path.relpath(root, directory)
if dir_path == '.':
dir_path = ''
for file_ in files:
if file_.lower().endswith(('.json')):
schema_name = os.path.join(dir_path, file_)
if schema_name in self.schemas:
raise JSONSchemaDuplicate(
schema_name,
self.schemas[schema_name],
directory
)
self.schemas[schema_name] = os.path.abspath(directory) | [
"def",
"register_schemas_dir",
"(",
"self",
",",
"directory",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory",
")",
":",
"dir_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"root",
",",
"directory",
... | Recursively register all json-schemas in a directory.
:param directory: directory path. | [
"Recursively",
"register",
"all",
"json",
"-",
"schemas",
"in",
"a",
"directory",
"."
] | train | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/ext.py#L51-L69 |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/ext.py | InvenioJSONSchemasState.register_schema | def register_schema(self, directory, path):
"""Register a json-schema.
:param directory: root directory path.
:param path: schema path, relative to the root directory.
"""
self.schemas[path] = os.path.abspath(directory) | python | def register_schema(self, directory, path):
"""Register a json-schema.
:param directory: root directory path.
:param path: schema path, relative to the root directory.
"""
self.schemas[path] = os.path.abspath(directory) | [
"def",
"register_schema",
"(",
"self",
",",
"directory",
",",
"path",
")",
":",
"self",
".",
"schemas",
"[",
"path",
"]",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"directory",
")"
] | Register a json-schema.
:param directory: root directory path.
:param path: schema path, relative to the root directory. | [
"Register",
"a",
"json",
"-",
"schema",
"."
] | train | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/ext.py#L71-L77 |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/ext.py | InvenioJSONSchemasState.get_schema_dir | def get_schema_dir(self, path):
"""Retrieve the directory containing the given schema.
:param path: Schema path, relative to the directory where it was
registered.
:raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema
was found in the specified path.
:returns: The schema directory.
"""
if path not in self.schemas:
raise JSONSchemaNotFound(path)
return self.schemas[path] | python | def get_schema_dir(self, path):
"""Retrieve the directory containing the given schema.
:param path: Schema path, relative to the directory where it was
registered.
:raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema
was found in the specified path.
:returns: The schema directory.
"""
if path not in self.schemas:
raise JSONSchemaNotFound(path)
return self.schemas[path] | [
"def",
"get_schema_dir",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"not",
"in",
"self",
".",
"schemas",
":",
"raise",
"JSONSchemaNotFound",
"(",
"path",
")",
"return",
"self",
".",
"schemas",
"[",
"path",
"]"
] | Retrieve the directory containing the given schema.
:param path: Schema path, relative to the directory where it was
registered.
:raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema
was found in the specified path.
:returns: The schema directory. | [
"Retrieve",
"the",
"directory",
"containing",
"the",
"given",
"schema",
"."
] | train | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/ext.py#L79-L90 |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/ext.py | InvenioJSONSchemasState.get_schema_path | def get_schema_path(self, path):
"""Compute the schema's absolute path from a schema relative path.
:param path: relative path of the schema.
:raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema
was found in the specified path.
:returns: The absolute path.
"""
if path not in self.schemas:
raise JSONSchemaNotFound(path)
return os.path.join(self.schemas[path], path) | python | def get_schema_path(self, path):
"""Compute the schema's absolute path from a schema relative path.
:param path: relative path of the schema.
:raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema
was found in the specified path.
:returns: The absolute path.
"""
if path not in self.schemas:
raise JSONSchemaNotFound(path)
return os.path.join(self.schemas[path], path) | [
"def",
"get_schema_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"not",
"in",
"self",
".",
"schemas",
":",
"raise",
"JSONSchemaNotFound",
"(",
"path",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"schemas",
"[",
"path",
... | Compute the schema's absolute path from a schema relative path.
:param path: relative path of the schema.
:raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema
was found in the specified path.
:returns: The absolute path. | [
"Compute",
"the",
"schema",
"s",
"absolute",
"path",
"from",
"a",
"schema",
"relative",
"path",
"."
] | train | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/ext.py#L92-L102 |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/ext.py | InvenioJSONSchemasState.get_schema | def get_schema(self, path, with_refs=False, resolved=False):
"""Retrieve a schema.
:param path: schema's relative path.
:param with_refs: replace $refs in the schema.
:param resolved: resolve schema using the resolver
:py:const:`invenio_jsonschemas.config.JSONSCHEMAS_RESOLVER_CLS`
:raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema
was found in the specified path.
:returns: The schema in a dictionary form.
"""
if path not in self.schemas:
raise JSONSchemaNotFound(path)
with open(os.path.join(self.schemas[path], path)) as file_:
schema = json.load(file_)
if with_refs:
schema = JsonRef.replace_refs(
schema,
base_uri=request.base_url,
loader=self.loader_cls() if self.loader_cls else None,
)
if resolved:
schema = self.resolver_cls(schema)
return schema | python | def get_schema(self, path, with_refs=False, resolved=False):
"""Retrieve a schema.
:param path: schema's relative path.
:param with_refs: replace $refs in the schema.
:param resolved: resolve schema using the resolver
:py:const:`invenio_jsonschemas.config.JSONSCHEMAS_RESOLVER_CLS`
:raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema
was found in the specified path.
:returns: The schema in a dictionary form.
"""
if path not in self.schemas:
raise JSONSchemaNotFound(path)
with open(os.path.join(self.schemas[path], path)) as file_:
schema = json.load(file_)
if with_refs:
schema = JsonRef.replace_refs(
schema,
base_uri=request.base_url,
loader=self.loader_cls() if self.loader_cls else None,
)
if resolved:
schema = self.resolver_cls(schema)
return schema | [
"def",
"get_schema",
"(",
"self",
",",
"path",
",",
"with_refs",
"=",
"False",
",",
"resolved",
"=",
"False",
")",
":",
"if",
"path",
"not",
"in",
"self",
".",
"schemas",
":",
"raise",
"JSONSchemaNotFound",
"(",
"path",
")",
"with",
"open",
"(",
"os",
... | Retrieve a schema.
:param path: schema's relative path.
:param with_refs: replace $refs in the schema.
:param resolved: resolve schema using the resolver
:py:const:`invenio_jsonschemas.config.JSONSCHEMAS_RESOLVER_CLS`
:raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema
was found in the specified path.
:returns: The schema in a dictionary form. | [
"Retrieve",
"a",
"schema",
"."
] | train | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/ext.py#L105-L128 |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/ext.py | InvenioJSONSchemasState.url_to_path | def url_to_path(self, url):
"""Convert schema URL to path.
:param url: The schema URL.
:returns: The schema path or ``None`` if the schema can't be resolved.
"""
parts = urlsplit(url)
try:
loader, args = self.url_map.bind(parts.netloc).match(parts.path)
path = args.get('path')
if loader == 'schema' and path in self.schemas:
return path
except HTTPException:
return None | python | def url_to_path(self, url):
"""Convert schema URL to path.
:param url: The schema URL.
:returns: The schema path or ``None`` if the schema can't be resolved.
"""
parts = urlsplit(url)
try:
loader, args = self.url_map.bind(parts.netloc).match(parts.path)
path = args.get('path')
if loader == 'schema' and path in self.schemas:
return path
except HTTPException:
return None | [
"def",
"url_to_path",
"(",
"self",
",",
"url",
")",
":",
"parts",
"=",
"urlsplit",
"(",
"url",
")",
"try",
":",
"loader",
",",
"args",
"=",
"self",
".",
"url_map",
".",
"bind",
"(",
"parts",
".",
"netloc",
")",
".",
"match",
"(",
"parts",
".",
"p... | Convert schema URL to path.
:param url: The schema URL.
:returns: The schema path or ``None`` if the schema can't be resolved. | [
"Convert",
"schema",
"URL",
"to",
"path",
"."
] | train | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/ext.py#L138-L151 |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/ext.py | InvenioJSONSchemasState.path_to_url | def path_to_url(self, path):
"""Build URL from a path.
:param path: relative path of the schema.
:returns: The schema complete URL or ``None`` if not found.
"""
if path not in self.schemas:
return None
return self.url_map.bind(
self.app.config['JSONSCHEMAS_HOST'],
url_scheme=self.app.config['JSONSCHEMAS_URL_SCHEME']
).build(
'schema', values={'path': path}, force_external=True) | python | def path_to_url(self, path):
"""Build URL from a path.
:param path: relative path of the schema.
:returns: The schema complete URL or ``None`` if not found.
"""
if path not in self.schemas:
return None
return self.url_map.bind(
self.app.config['JSONSCHEMAS_HOST'],
url_scheme=self.app.config['JSONSCHEMAS_URL_SCHEME']
).build(
'schema', values={'path': path}, force_external=True) | [
"def",
"path_to_url",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"not",
"in",
"self",
".",
"schemas",
":",
"return",
"None",
"return",
"self",
".",
"url_map",
".",
"bind",
"(",
"self",
".",
"app",
".",
"config",
"[",
"'JSONSCHEMAS_HOST'",
"]",
... | Build URL from a path.
:param path: relative path of the schema.
:returns: The schema complete URL or ``None`` if not found. | [
"Build",
"URL",
"from",
"a",
"path",
"."
] | train | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/ext.py#L153-L165 |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/ext.py | InvenioJSONSchemasState.loader_cls | def loader_cls(self):
"""Loader class used in `JsonRef.replace_refs`."""
cls = self.app.config['JSONSCHEMAS_LOADER_CLS']
if isinstance(cls, six.string_types):
return import_string(cls)
return cls | python | def loader_cls(self):
"""Loader class used in `JsonRef.replace_refs`."""
cls = self.app.config['JSONSCHEMAS_LOADER_CLS']
if isinstance(cls, six.string_types):
return import_string(cls)
return cls | [
"def",
"loader_cls",
"(",
"self",
")",
":",
"cls",
"=",
"self",
".",
"app",
".",
"config",
"[",
"'JSONSCHEMAS_LOADER_CLS'",
"]",
"if",
"isinstance",
"(",
"cls",
",",
"six",
".",
"string_types",
")",
":",
"return",
"import_string",
"(",
"cls",
")",
"retur... | Loader class used in `JsonRef.replace_refs`. | [
"Loader",
"class",
"used",
"in",
"JsonRef",
".",
"replace_refs",
"."
] | train | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/ext.py#L168-L173 |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/ext.py | InvenioJSONSchemas.init_app | def init_app(self, app, entry_point_group=None, register_blueprint=True,
register_config_blueprint=None):
"""Flask application initialization.
:param app: The Flask application.
:param entry_point_group: The group entry point to load extensions.
(Default: ``invenio_jsonschemas.schemas``)
:param register_blueprint: Register the blueprints.
:param register_config_blueprint: Register blueprint for the specific
app from a config variable.
"""
self.init_config(app)
if not entry_point_group:
entry_point_group = self.kwargs['entry_point_group'] \
if 'entry_point_group' in self.kwargs \
else 'invenio_jsonschemas.schemas'
state = InvenioJSONSchemasState(app)
# Load the json-schemas from extension points.
if entry_point_group:
for base_entry in pkg_resources.iter_entry_points(
entry_point_group):
directory = os.path.dirname(base_entry.load().__file__)
state.register_schemas_dir(directory)
# Init blueprints
_register_blueprint = app.config.get(register_config_blueprint)
if _register_blueprint is not None:
register_blueprint = _register_blueprint
if register_blueprint:
app.register_blueprint(
create_blueprint(state),
url_prefix=app.config['JSONSCHEMAS_ENDPOINT']
)
self._state = app.extensions['invenio-jsonschemas'] = state
return state | python | def init_app(self, app, entry_point_group=None, register_blueprint=True,
register_config_blueprint=None):
"""Flask application initialization.
:param app: The Flask application.
:param entry_point_group: The group entry point to load extensions.
(Default: ``invenio_jsonschemas.schemas``)
:param register_blueprint: Register the blueprints.
:param register_config_blueprint: Register blueprint for the specific
app from a config variable.
"""
self.init_config(app)
if not entry_point_group:
entry_point_group = self.kwargs['entry_point_group'] \
if 'entry_point_group' in self.kwargs \
else 'invenio_jsonschemas.schemas'
state = InvenioJSONSchemasState(app)
# Load the json-schemas from extension points.
if entry_point_group:
for base_entry in pkg_resources.iter_entry_points(
entry_point_group):
directory = os.path.dirname(base_entry.load().__file__)
state.register_schemas_dir(directory)
# Init blueprints
_register_blueprint = app.config.get(register_config_blueprint)
if _register_blueprint is not None:
register_blueprint = _register_blueprint
if register_blueprint:
app.register_blueprint(
create_blueprint(state),
url_prefix=app.config['JSONSCHEMAS_ENDPOINT']
)
self._state = app.extensions['invenio-jsonschemas'] = state
return state | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"entry_point_group",
"=",
"None",
",",
"register_blueprint",
"=",
"True",
",",
"register_config_blueprint",
"=",
"None",
")",
":",
"self",
".",
"init_config",
"(",
"app",
")",
"if",
"not",
"entry_point_group",
... | Flask application initialization.
:param app: The Flask application.
:param entry_point_group: The group entry point to load extensions.
(Default: ``invenio_jsonschemas.schemas``)
:param register_blueprint: Register the blueprints.
:param register_config_blueprint: Register blueprint for the specific
app from a config variable. | [
"Flask",
"application",
"initialization",
"."
] | train | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/ext.py#L205-L244 |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/ext.py | InvenioJSONSchemas.init_config | def init_config(self, app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('JSONSCHEMAS_'):
app.config.setdefault(k, getattr(config, k))
host_setting = app.config['JSONSCHEMAS_HOST']
if not host_setting or host_setting == 'localhost':
app.logger.warning('JSONSCHEMAS_HOST is set to {0}'.format(
host_setting)) | python | def init_config(self, app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('JSONSCHEMAS_'):
app.config.setdefault(k, getattr(config, k))
host_setting = app.config['JSONSCHEMAS_HOST']
if not host_setting or host_setting == 'localhost':
app.logger.warning('JSONSCHEMAS_HOST is set to {0}'.format(
host_setting)) | [
"def",
"init_config",
"(",
"self",
",",
"app",
")",
":",
"for",
"k",
"in",
"dir",
"(",
"config",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"'JSONSCHEMAS_'",
")",
":",
"app",
".",
"config",
".",
"setdefault",
"(",
"k",
",",
"getattr",
"(",
"confi... | Initialize configuration. | [
"Initialize",
"configuration",
"."
] | train | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/ext.py#L246-L255 |
acorg/dark-matter | dark/graphics.py | alignmentGraph | def alignmentGraph(titlesAlignments, title, addQueryLines=True,
showFeatures=True, logLinearXAxis=False,
logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE, rankScores=False,
colorQueryBases=False, createFigure=True, showFigure=True,
readsAx=None, imageFile=None, quiet=False, idList=False,
xRange='subject', showOrfs=True):
"""
Align a set of matching reads against a BLAST or DIAMOND hit.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param title: A C{str} sequence title that was matched. We plot the
reads that hit this title.
@param addQueryLines: if C{True}, draw query lines in full (these will then
be partly overdrawn by the HSP match against the subject). These are
the 'whiskers' that potentially protrude from each side of a query.
@param showFeatures: if C{True}, look online for features of the subject
sequence (given by hitId).
@param logLinearXAxis: if C{True}, convert read offsets so that empty
regions in the plot we're preparing will only be as wide as their
logged actual values.
@param logBase: The base of the logarithm to use if logLinearXAxis is
C{True}.
@param: rankScores: If C{True}, change the e-values and bit scores for the
reads for each title to be their rank (worst to best).
@param colorQueryBases: if C{True}, color each base of a query string. If
C{True}, then addQueryLines is meaningless since the whole query is
shown colored.
@param createFigure: If C{True}, create a figure and give it a title.
@param showFigure: If C{True}, show the created figure. Set this to
C{False} if you're creating a panel of figures or just want to save an
image (with C{imageFile}).
@param readsAx: If not None, use this as the subplot for displaying reads.
@param imageFile: If not None, specifies a filename to write the image to.
@param quiet: If C{True}, don't print progress / timing output.
@param idList: a dictionary. The keys is a color and the values is a list
of read identifiers that should be colored in the respective color.
@param xRange: set to either 'subject' or 'reads' to indicate the range of
the X axis.
@param showOrfs: If C{True}, open reading frames will be displayed.
"""
startTime = time()
assert xRange in ('subject', 'reads'), (
'xRange must be either "subject" or "reads".')
if createFigure:
width = 20
figure = plt.figure(figsize=(width, 20))
createdReadsAx = readsAx is None
if showFeatures:
if showOrfs:
gs = gridspec.GridSpec(4, 1, height_ratios=[3, 1, 1, 12])
featureAx = plt.subplot(gs[0, 0])
orfAx = plt.subplot(gs[1, 0])
orfReversedAx = plt.subplot(gs[2, 0])
readsAx = readsAx or plt.subplot(gs[3, 0])
else:
gs = gridspec.GridSpec(2, 1, height_ratios=[1, 1])
featureAx = plt.subplot(gs[0, 0])
readsAx = readsAx or plt.subplot(gs[1, 0])
else:
if showOrfs:
gs = gridspec.GridSpec(3, 1, height_ratios=[1, 1, 12])
orfAx = plt.subplot(gs[0, 0])
orfReversedAx = plt.subplot(gs[1, 0])
readsAx = readsAx or plt.subplot(gs[2, 0])
else:
readsAx = readsAx or plt.subplot(111)
# Make a deep copy of the title alignments. We're potentially going to
# change the HSP scores, the X axis offsets, etc., and we don't want to
# interfere with the data we were passed.
titleAlignments = deepcopy(titlesAlignments[title])
readsAlignments = titlesAlignments.readsAlignments
subjectIsNucleotides = readsAlignments.params.subjectIsNucleotides
if showOrfs and not subjectIsNucleotides:
# We cannot show ORFs when displaying protein plots.
showOrfs = False
# Allow the class of titlesAlignments to adjust HSPs for plotting,
# if it has a method for doing so.
try:
adjuster = readsAlignments.adjustHspsForPlotting
except AttributeError:
pass
else:
adjuster(titleAlignments)
if rankScores:
reverse = titlesAlignments.scoreClass is not HigherIsBetterScore
for rank, hsp in enumerate(sorted(titleAlignments.hsps(),
reverse=reverse), start=1):
hsp.score.score = rank
if logLinearXAxis:
readIntervals = ReadIntervals(titleAlignments.subjectLength)
# Examine all HSPs so we can build an offset adjuster.
for hsp in titleAlignments.hsps():
readIntervals.add(hsp.readStartInSubject, hsp.readEndInSubject)
# Now adjust offsets in all HSPs.
offsetAdjuster = OffsetAdjuster(readIntervals, base=logBase)
for hsp in titleAlignments.hsps():
offsetAdjuster.adjustHSP(hsp)
# A function for adjusting other offsets, below.
adjustOffset = offsetAdjuster.adjustOffset
else:
def adjustOffset(offset):
return offset
# It would be more efficient to only walk through all HSPs once and
# compute these values all at once, but for now this is simple and clear.
maxY = int(ceil(titleAlignments.bestHsp().score.score))
minY = int(titleAlignments.worstHsp().score.score)
maxX = max(hsp.readEndInSubject for hsp in titleAlignments.hsps())
minX = min(hsp.readStartInSubject for hsp in titleAlignments.hsps())
if xRange == 'subject':
# We'll display a graph for the full subject range. Adjust X axis
# min/max to make sure we cover at least zero to the sequence length.
maxX = max(titleAlignments.subjectLength, maxX)
minX = min(0, minX)
# Swap min & max Y values, if needed, as it's possible we are dealing
# with LSPs but that the score adjuster made numerically greater values
# for those that were small.
if maxY < minY:
(maxY, minY) = (minY, maxY)
if logLinearXAxis:
# Adjust minX and maxX if we have gaps at the subject start or end.
gaps = list(readIntervals.walk())
if gaps:
# Check start of first gap:
intervalType, (start, stop) = gaps[0]
if intervalType == ReadIntervals.EMPTY:
adjustedStart = adjustOffset(start)
if adjustedStart < minX:
minX = adjustedStart
# Check stop of last gap:
intervalType, (start, stop) = gaps[-1]
if intervalType == ReadIntervals.EMPTY:
adjustedStop = adjustOffset(stop)
if adjustedStop > maxX:
maxX = adjustedStop
# We're all set up to start plotting the graph.
# Add light grey vertical rectangles to show the logarithmic gaps. Add
# these first so that reads will be plotted on top of them. Only draw
# gaps that are more than SMALLEST_LOGGED_GAP_TO_DISPLAY pixels wide as
# we could have millions of tiny gaps for a bacteria and drawing them
# all will be slow and only serves to make the entire background grey.
if logLinearXAxis and len(offsetAdjuster.adjustments()) < 100:
for (intervalType, interval) in readIntervals.walk():
if intervalType == ReadIntervals.EMPTY:
adjustedStart = adjustOffset(interval[0])
adjustedStop = adjustOffset(interval[1])
width = adjustedStop - adjustedStart
if width >= SMALLEST_LOGGED_GAP_TO_DISPLAY:
readsAx.axvspan(adjustedStart, adjustedStop,
color='#f4f4f4')
if colorQueryBases:
# Color each query by its bases.
xScale = 3
yScale = 2
baseImage = BaseImage(
maxX - minX, maxY - minY + (1 if rankScores else 0),
xScale, yScale)
for alignment in titleAlignments:
for hsp in alignment.hsps:
y = hsp.score.score - minY
# If the product of the subject and read frame values is +ve,
# then they're either both +ve or both -ve, so we just use the
# read as is. Otherwise, we need to reverse complement it.
if hsp.subjectFrame * hsp.readFrame > 0:
query = alignment.read.sequence
else:
# One of the subject or query has negative sense.
query = alignment.read.reverseComplement().sequence
readStartInSubject = hsp.readStartInSubject
# There are 3 parts of the query string we need to
# display. 1) the left part (if any) before the matched
# part of the subject. 2) the matched part (which can
# include gaps in the query and/or subject). 3) the right
# part (if any) after the matched part. For each part,
# calculate the ranges in which we have to make the
# comparison between subject and query.
# NOTE: never use hsp['origHsp'].gaps to calculate the number
# of gaps, as this number contains gaps in both subject and
# query.
# 1. Left part:
leftRange = hsp.subjectStart - readStartInSubject
# 2. Match, middle part:
middleRange = len(hsp.readMatchedSequence)
# 3. Right part:
# Using hsp.readEndInSubject - hsp.subjectEnd to calculate the
# length of the right part leads to the part being too long.
# The number of gaps needs to be subtracted to get the right
# length.
origQuery = hsp.readMatchedSequence.upper()
rightRange = (hsp.readEndInSubject - hsp.subjectEnd -
origQuery.count('-'))
# 1. Left part.
xOffset = readStartInSubject - minX
queryOffset = 0
for queryIndex in range(leftRange):
color = QUERY_COLORS.get(query[queryOffset + queryIndex],
DEFAULT_BASE_COLOR)
baseImage.set(xOffset + queryIndex, y, color)
# 2. Match part.
xOffset = hsp.subjectStart - minX
xIndex = 0
queryOffset = hsp.subjectStart - hsp.readStartInSubject
origSubject = hsp.subjectMatchedSequence
for matchIndex in range(middleRange):
if origSubject[matchIndex] == '-':
# A gap in the subject was needed to match the query.
# In our graph we keep the subject the same even in the
# case where BLAST opened gaps in it, so we compensate
# for the gap in the subject by not showing this base
# of the query.
pass
else:
if origSubject[matchIndex] == origQuery[matchIndex]:
# The query matched the subject at this location.
# Matching bases are all colored in the same
# 'match' color.
color = QUERY_COLORS['match']
else:
if origQuery[matchIndex] == '-':
# A gap in the query. All query gaps get the
# same 'gap' color.
color = QUERY_COLORS['gap']
else:
# Query doesn't match subject (and is not a
# gap).
color = QUERY_COLORS.get(origQuery[matchIndex],
DEFAULT_BASE_COLOR)
baseImage.set(xOffset + xIndex, y, color)
xIndex += 1
# 3. Right part.
xOffset = hsp.subjectEnd - minX
backQuery = query[-rightRange:].upper()
for queryIndex in range(rightRange):
color = QUERY_COLORS.get(backQuery[queryIndex],
DEFAULT_BASE_COLOR)
baseImage.set(xOffset + queryIndex, y, color)
readsAx.imshow(baseImage.data, aspect='auto', origin='lower',
interpolation='nearest',
extent=[minX, maxX, minY, maxY])
else:
# Add horizontal lines for all the query sequences. These will be the
# grey 'whiskers' in the plots once we (below) draw the matched part
# on top of part of them.
if addQueryLines:
for hsp in titleAlignments.hsps():
y = hsp.score.score
line = Line2D([hsp.readStartInSubject, hsp.readEndInSubject],
[y, y], color='#aaaaaa')
readsAx.add_line(line)
# Add the horizontal BLAST alignment lines.
# If an idList is given set things up to look up read colors.
readColor = {}
if idList:
for color, reads in idList.items():
for read in reads:
if read in readColor:
raise ValueError('Read %s is specified multiple '
'times in idList' % read)
else:
readColor[read] = color
# Draw the matched region.
for titleAlignment in titleAlignments:
readId = titleAlignment.read.id
for hsp in titleAlignment.hsps:
y = hsp.score.score
line = Line2D([hsp.subjectStart, hsp.subjectEnd], [y, y],
color=readColor.get(readId, 'blue'))
readsAx.add_line(line)
if showOrfs:
subject = readsAlignments.getSubjectSequence(title)
orfs.addORFs(orfAx, subject.sequence, minX, maxX, adjustOffset)
orfs.addReversedORFs(orfReversedAx,
subject.reverseComplement().sequence,
minX, maxX, adjustOffset)
if showFeatures:
if subjectIsNucleotides:
featureAdder = NucleotideFeatureAdder()
else:
featureAdder = ProteinFeatureAdder()
features = featureAdder.add(featureAx, title, minX, maxX,
adjustOffset)
# If there are features and there weren't too many of them, add
# vertical feature lines to the reads and ORF axes.
if features and not featureAdder.tooManyFeaturesToPlot:
for feature in features:
start = feature.start
end = feature.end
color = feature.color
readsAx.axvline(x=start, color=color)
readsAx.axvline(x=end, color='#cccccc')
if showOrfs:
orfAx.axvline(x=start, color=color)
orfAx.axvline(x=end, color='#cccccc')
orfReversedAx.axvline(x=start, color=color)
orfReversedAx.axvline(x=end, color='#cccccc')
else:
features = None
# We'll return some information we've gathered.
result = {
'adjustOffset': adjustOffset,
'features': features,
'minX': minX,
'maxX': maxX,
'minY': minY,
'maxY': maxY,
}
# Allow the class of titlesAlignments to add to the plot, if it has a
# method for doing so.
try:
adjuster = readsAlignments.adjustPlot
except AttributeError:
pass
else:
adjuster(readsAx)
# Titles, axis, etc.
if createFigure:
readCount = titleAlignments.readCount()
hspCount = titleAlignments.hspCount()
figure.suptitle(
'%s\nLength %d %s, %d read%s, %d HSP%s.' %
(
fill(titleAlignments.subjectTitle, 80),
titleAlignments.subjectLength,
'nt' if subjectIsNucleotides else 'aa',
readCount, '' if readCount == 1 else 's',
hspCount, '' if hspCount == 1 else 's'
),
fontsize=20)
# Add a title and y-axis label, but only if we made the reads axes.
if createdReadsAx:
readsAx.set_title('Read alignments', fontsize=20)
ylabel = readsAlignments.params.scoreTitle
if rankScores:
ylabel += ' rank'
plt.ylabel(ylabel, fontsize=17)
# Set the x-axis limits.
readsAx.set_xlim([minX - 1, maxX + 1])
readsAx.set_ylim([0, int(maxY * Y_AXIS_UPPER_PADDING)])
readsAx.grid()
if createFigure:
if showFigure:
plt.show()
if imageFile:
figure.savefig(imageFile)
stop = time()
if not quiet:
report('Graph generated in %.3f mins.' % ((stop - startTime) / 60.0))
return result | python | def alignmentGraph(titlesAlignments, title, addQueryLines=True,
showFeatures=True, logLinearXAxis=False,
logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE, rankScores=False,
colorQueryBases=False, createFigure=True, showFigure=True,
readsAx=None, imageFile=None, quiet=False, idList=False,
xRange='subject', showOrfs=True):
"""
Align a set of matching reads against a BLAST or DIAMOND hit.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param title: A C{str} sequence title that was matched. We plot the
reads that hit this title.
@param addQueryLines: if C{True}, draw query lines in full (these will then
be partly overdrawn by the HSP match against the subject). These are
the 'whiskers' that potentially protrude from each side of a query.
@param showFeatures: if C{True}, look online for features of the subject
sequence (given by hitId).
@param logLinearXAxis: if C{True}, convert read offsets so that empty
regions in the plot we're preparing will only be as wide as their
logged actual values.
@param logBase: The base of the logarithm to use if logLinearXAxis is
C{True}.
@param: rankScores: If C{True}, change the e-values and bit scores for the
reads for each title to be their rank (worst to best).
@param colorQueryBases: if C{True}, color each base of a query string. If
C{True}, then addQueryLines is meaningless since the whole query is
shown colored.
@param createFigure: If C{True}, create a figure and give it a title.
@param showFigure: If C{True}, show the created figure. Set this to
C{False} if you're creating a panel of figures or just want to save an
image (with C{imageFile}).
@param readsAx: If not None, use this as the subplot for displaying reads.
@param imageFile: If not None, specifies a filename to write the image to.
@param quiet: If C{True}, don't print progress / timing output.
@param idList: a dictionary. The keys is a color and the values is a list
of read identifiers that should be colored in the respective color.
@param xRange: set to either 'subject' or 'reads' to indicate the range of
the X axis.
@param showOrfs: If C{True}, open reading frames will be displayed.
"""
startTime = time()
assert xRange in ('subject', 'reads'), (
'xRange must be either "subject" or "reads".')
if createFigure:
width = 20
figure = plt.figure(figsize=(width, 20))
createdReadsAx = readsAx is None
if showFeatures:
if showOrfs:
gs = gridspec.GridSpec(4, 1, height_ratios=[3, 1, 1, 12])
featureAx = plt.subplot(gs[0, 0])
orfAx = plt.subplot(gs[1, 0])
orfReversedAx = plt.subplot(gs[2, 0])
readsAx = readsAx or plt.subplot(gs[3, 0])
else:
gs = gridspec.GridSpec(2, 1, height_ratios=[1, 1])
featureAx = plt.subplot(gs[0, 0])
readsAx = readsAx or plt.subplot(gs[1, 0])
else:
if showOrfs:
gs = gridspec.GridSpec(3, 1, height_ratios=[1, 1, 12])
orfAx = plt.subplot(gs[0, 0])
orfReversedAx = plt.subplot(gs[1, 0])
readsAx = readsAx or plt.subplot(gs[2, 0])
else:
readsAx = readsAx or plt.subplot(111)
# Make a deep copy of the title alignments. We're potentially going to
# change the HSP scores, the X axis offsets, etc., and we don't want to
# interfere with the data we were passed.
titleAlignments = deepcopy(titlesAlignments[title])
readsAlignments = titlesAlignments.readsAlignments
subjectIsNucleotides = readsAlignments.params.subjectIsNucleotides
if showOrfs and not subjectIsNucleotides:
# We cannot show ORFs when displaying protein plots.
showOrfs = False
# Allow the class of titlesAlignments to adjust HSPs for plotting,
# if it has a method for doing so.
try:
adjuster = readsAlignments.adjustHspsForPlotting
except AttributeError:
pass
else:
adjuster(titleAlignments)
if rankScores:
reverse = titlesAlignments.scoreClass is not HigherIsBetterScore
for rank, hsp in enumerate(sorted(titleAlignments.hsps(),
reverse=reverse), start=1):
hsp.score.score = rank
if logLinearXAxis:
readIntervals = ReadIntervals(titleAlignments.subjectLength)
# Examine all HSPs so we can build an offset adjuster.
for hsp in titleAlignments.hsps():
readIntervals.add(hsp.readStartInSubject, hsp.readEndInSubject)
# Now adjust offsets in all HSPs.
offsetAdjuster = OffsetAdjuster(readIntervals, base=logBase)
for hsp in titleAlignments.hsps():
offsetAdjuster.adjustHSP(hsp)
# A function for adjusting other offsets, below.
adjustOffset = offsetAdjuster.adjustOffset
else:
def adjustOffset(offset):
return offset
# It would be more efficient to only walk through all HSPs once and
# compute these values all at once, but for now this is simple and clear.
maxY = int(ceil(titleAlignments.bestHsp().score.score))
minY = int(titleAlignments.worstHsp().score.score)
maxX = max(hsp.readEndInSubject for hsp in titleAlignments.hsps())
minX = min(hsp.readStartInSubject for hsp in titleAlignments.hsps())
if xRange == 'subject':
# We'll display a graph for the full subject range. Adjust X axis
# min/max to make sure we cover at least zero to the sequence length.
maxX = max(titleAlignments.subjectLength, maxX)
minX = min(0, minX)
# Swap min & max Y values, if needed, as it's possible we are dealing
# with LSPs but that the score adjuster made numerically greater values
# for those that were small.
if maxY < minY:
(maxY, minY) = (minY, maxY)
if logLinearXAxis:
# Adjust minX and maxX if we have gaps at the subject start or end.
gaps = list(readIntervals.walk())
if gaps:
# Check start of first gap:
intervalType, (start, stop) = gaps[0]
if intervalType == ReadIntervals.EMPTY:
adjustedStart = adjustOffset(start)
if adjustedStart < minX:
minX = adjustedStart
# Check stop of last gap:
intervalType, (start, stop) = gaps[-1]
if intervalType == ReadIntervals.EMPTY:
adjustedStop = adjustOffset(stop)
if adjustedStop > maxX:
maxX = adjustedStop
# We're all set up to start plotting the graph.
# Add light grey vertical rectangles to show the logarithmic gaps. Add
# these first so that reads will be plotted on top of them. Only draw
# gaps that are more than SMALLEST_LOGGED_GAP_TO_DISPLAY pixels wide as
# we could have millions of tiny gaps for a bacteria and drawing them
# all will be slow and only serves to make the entire background grey.
if logLinearXAxis and len(offsetAdjuster.adjustments()) < 100:
for (intervalType, interval) in readIntervals.walk():
if intervalType == ReadIntervals.EMPTY:
adjustedStart = adjustOffset(interval[0])
adjustedStop = adjustOffset(interval[1])
width = adjustedStop - adjustedStart
if width >= SMALLEST_LOGGED_GAP_TO_DISPLAY:
readsAx.axvspan(adjustedStart, adjustedStop,
color='#f4f4f4')
if colorQueryBases:
# Color each query by its bases.
xScale = 3
yScale = 2
baseImage = BaseImage(
maxX - minX, maxY - minY + (1 if rankScores else 0),
xScale, yScale)
for alignment in titleAlignments:
for hsp in alignment.hsps:
y = hsp.score.score - minY
# If the product of the subject and read frame values is +ve,
# then they're either both +ve or both -ve, so we just use the
# read as is. Otherwise, we need to reverse complement it.
if hsp.subjectFrame * hsp.readFrame > 0:
query = alignment.read.sequence
else:
# One of the subject or query has negative sense.
query = alignment.read.reverseComplement().sequence
readStartInSubject = hsp.readStartInSubject
# There are 3 parts of the query string we need to
# display. 1) the left part (if any) before the matched
# part of the subject. 2) the matched part (which can
# include gaps in the query and/or subject). 3) the right
# part (if any) after the matched part. For each part,
# calculate the ranges in which we have to make the
# comparison between subject and query.
# NOTE: never use hsp['origHsp'].gaps to calculate the number
# of gaps, as this number contains gaps in both subject and
# query.
# 1. Left part:
leftRange = hsp.subjectStart - readStartInSubject
# 2. Match, middle part:
middleRange = len(hsp.readMatchedSequence)
# 3. Right part:
# Using hsp.readEndInSubject - hsp.subjectEnd to calculate the
# length of the right part leads to the part being too long.
# The number of gaps needs to be subtracted to get the right
# length.
origQuery = hsp.readMatchedSequence.upper()
rightRange = (hsp.readEndInSubject - hsp.subjectEnd -
origQuery.count('-'))
# 1. Left part.
xOffset = readStartInSubject - minX
queryOffset = 0
for queryIndex in range(leftRange):
color = QUERY_COLORS.get(query[queryOffset + queryIndex],
DEFAULT_BASE_COLOR)
baseImage.set(xOffset + queryIndex, y, color)
# 2. Match part.
xOffset = hsp.subjectStart - minX
xIndex = 0
queryOffset = hsp.subjectStart - hsp.readStartInSubject
origSubject = hsp.subjectMatchedSequence
for matchIndex in range(middleRange):
if origSubject[matchIndex] == '-':
# A gap in the subject was needed to match the query.
# In our graph we keep the subject the same even in the
# case where BLAST opened gaps in it, so we compensate
# for the gap in the subject by not showing this base
# of the query.
pass
else:
if origSubject[matchIndex] == origQuery[matchIndex]:
# The query matched the subject at this location.
# Matching bases are all colored in the same
# 'match' color.
color = QUERY_COLORS['match']
else:
if origQuery[matchIndex] == '-':
# A gap in the query. All query gaps get the
# same 'gap' color.
color = QUERY_COLORS['gap']
else:
# Query doesn't match subject (and is not a
# gap).
color = QUERY_COLORS.get(origQuery[matchIndex],
DEFAULT_BASE_COLOR)
baseImage.set(xOffset + xIndex, y, color)
xIndex += 1
# 3. Right part.
xOffset = hsp.subjectEnd - minX
backQuery = query[-rightRange:].upper()
for queryIndex in range(rightRange):
color = QUERY_COLORS.get(backQuery[queryIndex],
DEFAULT_BASE_COLOR)
baseImage.set(xOffset + queryIndex, y, color)
readsAx.imshow(baseImage.data, aspect='auto', origin='lower',
interpolation='nearest',
extent=[minX, maxX, minY, maxY])
else:
# Add horizontal lines for all the query sequences. These will be the
# grey 'whiskers' in the plots once we (below) draw the matched part
# on top of part of them.
if addQueryLines:
for hsp in titleAlignments.hsps():
y = hsp.score.score
line = Line2D([hsp.readStartInSubject, hsp.readEndInSubject],
[y, y], color='#aaaaaa')
readsAx.add_line(line)
# Add the horizontal BLAST alignment lines.
# If an idList is given set things up to look up read colors.
readColor = {}
if idList:
for color, reads in idList.items():
for read in reads:
if read in readColor:
raise ValueError('Read %s is specified multiple '
'times in idList' % read)
else:
readColor[read] = color
# Draw the matched region.
for titleAlignment in titleAlignments:
readId = titleAlignment.read.id
for hsp in titleAlignment.hsps:
y = hsp.score.score
line = Line2D([hsp.subjectStart, hsp.subjectEnd], [y, y],
color=readColor.get(readId, 'blue'))
readsAx.add_line(line)
if showOrfs:
subject = readsAlignments.getSubjectSequence(title)
orfs.addORFs(orfAx, subject.sequence, minX, maxX, adjustOffset)
orfs.addReversedORFs(orfReversedAx,
subject.reverseComplement().sequence,
minX, maxX, adjustOffset)
if showFeatures:
if subjectIsNucleotides:
featureAdder = NucleotideFeatureAdder()
else:
featureAdder = ProteinFeatureAdder()
features = featureAdder.add(featureAx, title, minX, maxX,
adjustOffset)
# If there are features and there weren't too many of them, add
# vertical feature lines to the reads and ORF axes.
if features and not featureAdder.tooManyFeaturesToPlot:
for feature in features:
start = feature.start
end = feature.end
color = feature.color
readsAx.axvline(x=start, color=color)
readsAx.axvline(x=end, color='#cccccc')
if showOrfs:
orfAx.axvline(x=start, color=color)
orfAx.axvline(x=end, color='#cccccc')
orfReversedAx.axvline(x=start, color=color)
orfReversedAx.axvline(x=end, color='#cccccc')
else:
features = None
# We'll return some information we've gathered.
result = {
'adjustOffset': adjustOffset,
'features': features,
'minX': minX,
'maxX': maxX,
'minY': minY,
'maxY': maxY,
}
# Allow the class of titlesAlignments to add to the plot, if it has a
# method for doing so.
try:
adjuster = readsAlignments.adjustPlot
except AttributeError:
pass
else:
adjuster(readsAx)
# Titles, axis, etc.
if createFigure:
readCount = titleAlignments.readCount()
hspCount = titleAlignments.hspCount()
figure.suptitle(
'%s\nLength %d %s, %d read%s, %d HSP%s.' %
(
fill(titleAlignments.subjectTitle, 80),
titleAlignments.subjectLength,
'nt' if subjectIsNucleotides else 'aa',
readCount, '' if readCount == 1 else 's',
hspCount, '' if hspCount == 1 else 's'
),
fontsize=20)
# Add a title and y-axis label, but only if we made the reads axes.
if createdReadsAx:
readsAx.set_title('Read alignments', fontsize=20)
ylabel = readsAlignments.params.scoreTitle
if rankScores:
ylabel += ' rank'
plt.ylabel(ylabel, fontsize=17)
# Set the x-axis limits.
readsAx.set_xlim([minX - 1, maxX + 1])
readsAx.set_ylim([0, int(maxY * Y_AXIS_UPPER_PADDING)])
readsAx.grid()
if createFigure:
if showFigure:
plt.show()
if imageFile:
figure.savefig(imageFile)
stop = time()
if not quiet:
report('Graph generated in %.3f mins.' % ((stop - startTime) / 60.0))
return result | [
"def",
"alignmentGraph",
"(",
"titlesAlignments",
",",
"title",
",",
"addQueryLines",
"=",
"True",
",",
"showFeatures",
"=",
"True",
",",
"logLinearXAxis",
"=",
"False",
",",
"logBase",
"=",
"DEFAULT_LOG_LINEAR_X_AXIS_BASE",
",",
"rankScores",
"=",
"False",
",",
... | Align a set of matching reads against a BLAST or DIAMOND hit.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param title: A C{str} sequence title that was matched. We plot the
reads that hit this title.
@param addQueryLines: if C{True}, draw query lines in full (these will then
be partly overdrawn by the HSP match against the subject). These are
the 'whiskers' that potentially protrude from each side of a query.
@param showFeatures: if C{True}, look online for features of the subject
sequence (given by hitId).
@param logLinearXAxis: if C{True}, convert read offsets so that empty
regions in the plot we're preparing will only be as wide as their
logged actual values.
@param logBase: The base of the logarithm to use if logLinearXAxis is
C{True}.
@param: rankScores: If C{True}, change the e-values and bit scores for the
reads for each title to be their rank (worst to best).
@param colorQueryBases: if C{True}, color each base of a query string. If
C{True}, then addQueryLines is meaningless since the whole query is
shown colored.
@param createFigure: If C{True}, create a figure and give it a title.
@param showFigure: If C{True}, show the created figure. Set this to
C{False} if you're creating a panel of figures or just want to save an
image (with C{imageFile}).
@param readsAx: If not None, use this as the subplot for displaying reads.
@param imageFile: If not None, specifies a filename to write the image to.
@param quiet: If C{True}, don't print progress / timing output.
@param idList: a dictionary. The keys is a color and the values is a list
of read identifiers that should be colored in the respective color.
@param xRange: set to either 'subject' or 'reads' to indicate the range of
the X axis.
@param showOrfs: If C{True}, open reading frames will be displayed. | [
"Align",
"a",
"set",
"of",
"matching",
"reads",
"against",
"a",
"BLAST",
"or",
"DIAMOND",
"hit",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/graphics.py#L100-L486 |
acorg/dark-matter | dark/graphics.py | alignmentPanel | def alignmentPanel(titlesAlignments, sortOn='maxScore', idList=False,
equalizeXAxes=False, xRange='subject', logLinearXAxis=False,
rankScores=False, showFeatures=True,
logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE):
"""
Produces a rectangular panel of graphs that each contain an alignment graph
against a given sequence.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param sortOn: The attribute to sort subplots on. Either "maxScore",
"medianScore", "readCount", "length", or "title".
@param idList: A dictionary. Keys are colors and values are lists of read
ids that should be colored using that color.
@param equalizeXAxes: If C{True}, adjust the X axis on each alignment plot
to be the same.
@param xRange: Set to either 'subject' or 'reads' to indicate the range of
the X axis.
@param logLinearXAxis: If C{True}, convert read offsets so that empty
regions in the plots we're preparing will only be as wide as their
logged actual values.
@param logBase: The logarithm base to use if logLinearXAxis is C{True}.
@param: rankScores: If C{True}, change the scores for the reads for each
title to be their rank (worst to best).
@param showFeatures: If C{True}, look online for features of the subject
sequences.
@raise ValueError: If C{outputDir} exists but is not a directory or if
C{xRange} is not "subject" or "reads".
"""
if xRange not in ('subject', 'reads'):
raise ValueError('xRange must be either "subject" or "reads".')
start = time()
titles = titlesAlignments.sortTitles(sortOn)
cols = 5
rows = int(len(titles) / cols) + (0 if len(titles) % cols == 0 else 1)
figure, ax = plt.subplots(rows, cols, squeeze=False)
allGraphInfo = {}
coords = dimensionalIterator((rows, cols))
report('Plotting %d titles in %dx%d grid, sorted on %s' %
(len(titles), rows, cols, sortOn))
for i, title in enumerate(titles):
titleAlignments = titlesAlignments[title]
row, col = next(coords)
report('%d: %s %s' % (i, title, NCBISequenceLinkURL(title, '')))
# Add a small plot to the alignment panel.
graphInfo = alignmentGraph(
titlesAlignments, title, addQueryLines=True,
showFeatures=showFeatures, rankScores=rankScores,
logLinearXAxis=logLinearXAxis, logBase=logBase,
colorQueryBases=False, createFigure=False, showFigure=False,
readsAx=ax[row][col], quiet=True, idList=idList, xRange=xRange,
showOrfs=False)
allGraphInfo[title] = graphInfo
readCount = titleAlignments.readCount()
hspCount = titleAlignments.hspCount()
# Make a short title for the small panel blue plot, ignoring any
# leading NCBI gi / accession numbers.
if title.startswith('gi|') and title.find(' ') > -1:
shortTitle = title.split(' ', 1)[1][:40]
else:
shortTitle = title[:40]
plotTitle = ('%d: %s\nLength %d, %d read%s, %d HSP%s.' % (
i, shortTitle, titleAlignments.subjectLength,
readCount, '' if readCount == 1 else 's',
hspCount, '' if hspCount == 1 else 's'))
if hspCount:
if rankScores:
plotTitle += '\nY axis is ranked score'
else:
plotTitle += '\nmax %.2f, median %.2f' % (
titleAlignments.bestHsp().score.score,
titleAlignments.medianScore())
ax[row][col].set_title(plotTitle, fontsize=10)
maxX = max(graphInfo['maxX'] for graphInfo in allGraphInfo.values())
minX = min(graphInfo['minX'] for graphInfo in allGraphInfo.values())
maxY = max(graphInfo['maxY'] for graphInfo in allGraphInfo.values())
minY = min(graphInfo['minY'] for graphInfo in allGraphInfo.values())
# Post-process graphs to adjust axes, etc.
coords = dimensionalIterator((rows, cols))
for title in titles:
titleAlignments = titlesAlignments[title]
row, col = next(coords)
a = ax[row][col]
a.set_ylim([0, int(maxY * Y_AXIS_UPPER_PADDING)])
if equalizeXAxes:
a.set_xlim([minX, maxX])
a.set_yticks([])
a.set_xticks([])
if xRange == 'subject' and minX < 0:
# Add a vertical line at x=0 so we can see the 'whiskers' of
# reads that extend to the left of the sequence we're aligning
# against.
a.axvline(x=0, color='#cccccc')
# Add a line on the right of each sub-plot so we can see where the
# sequence ends (as all panel graphs have the same width and we
# otherwise couldn't tell).
sequenceLen = titleAlignments.subjectLength
if logLinearXAxis:
sequenceLen = allGraphInfo[title]['adjustOffset'](sequenceLen)
a.axvline(x=sequenceLen, color='#cccccc')
# Hide the final panel graphs (if any) that have no content. We do this
# because the panel is a rectangular grid and some of the plots at the
# end of the last row may be unused.
for row, col in coords:
ax[row][col].axis('off')
# plt.subplots_adjust(left=0.01, bottom=0.01, right=0.99, top=0.93,
# wspace=0.1, hspace=None)
plt.subplots_adjust(hspace=0.4)
figure.suptitle('X: %d to %d, Y (%s): %d to %d' %
(minX, maxX,
titlesAlignments.readsAlignments.params.scoreTitle,
int(minY), int(maxY)), fontsize=20)
figure.set_size_inches(5 * cols, 3 * rows, forward=True)
figure.show()
stop = time()
report('Alignment panel generated in %.3f mins.' % ((stop - start) / 60.0)) | python | def alignmentPanel(titlesAlignments, sortOn='maxScore', idList=False,
equalizeXAxes=False, xRange='subject', logLinearXAxis=False,
rankScores=False, showFeatures=True,
logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE):
"""
Produces a rectangular panel of graphs that each contain an alignment graph
against a given sequence.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param sortOn: The attribute to sort subplots on. Either "maxScore",
"medianScore", "readCount", "length", or "title".
@param idList: A dictionary. Keys are colors and values are lists of read
ids that should be colored using that color.
@param equalizeXAxes: If C{True}, adjust the X axis on each alignment plot
to be the same.
@param xRange: Set to either 'subject' or 'reads' to indicate the range of
the X axis.
@param logLinearXAxis: If C{True}, convert read offsets so that empty
regions in the plots we're preparing will only be as wide as their
logged actual values.
@param logBase: The logarithm base to use if logLinearXAxis is C{True}.
@param: rankScores: If C{True}, change the scores for the reads for each
title to be their rank (worst to best).
@param showFeatures: If C{True}, look online for features of the subject
sequences.
@raise ValueError: If C{outputDir} exists but is not a directory or if
C{xRange} is not "subject" or "reads".
"""
if xRange not in ('subject', 'reads'):
raise ValueError('xRange must be either "subject" or "reads".')
start = time()
titles = titlesAlignments.sortTitles(sortOn)
cols = 5
rows = int(len(titles) / cols) + (0 if len(titles) % cols == 0 else 1)
figure, ax = plt.subplots(rows, cols, squeeze=False)
allGraphInfo = {}
coords = dimensionalIterator((rows, cols))
report('Plotting %d titles in %dx%d grid, sorted on %s' %
(len(titles), rows, cols, sortOn))
for i, title in enumerate(titles):
titleAlignments = titlesAlignments[title]
row, col = next(coords)
report('%d: %s %s' % (i, title, NCBISequenceLinkURL(title, '')))
# Add a small plot to the alignment panel.
graphInfo = alignmentGraph(
titlesAlignments, title, addQueryLines=True,
showFeatures=showFeatures, rankScores=rankScores,
logLinearXAxis=logLinearXAxis, logBase=logBase,
colorQueryBases=False, createFigure=False, showFigure=False,
readsAx=ax[row][col], quiet=True, idList=idList, xRange=xRange,
showOrfs=False)
allGraphInfo[title] = graphInfo
readCount = titleAlignments.readCount()
hspCount = titleAlignments.hspCount()
# Make a short title for the small panel blue plot, ignoring any
# leading NCBI gi / accession numbers.
if title.startswith('gi|') and title.find(' ') > -1:
shortTitle = title.split(' ', 1)[1][:40]
else:
shortTitle = title[:40]
plotTitle = ('%d: %s\nLength %d, %d read%s, %d HSP%s.' % (
i, shortTitle, titleAlignments.subjectLength,
readCount, '' if readCount == 1 else 's',
hspCount, '' if hspCount == 1 else 's'))
if hspCount:
if rankScores:
plotTitle += '\nY axis is ranked score'
else:
plotTitle += '\nmax %.2f, median %.2f' % (
titleAlignments.bestHsp().score.score,
titleAlignments.medianScore())
ax[row][col].set_title(plotTitle, fontsize=10)
maxX = max(graphInfo['maxX'] for graphInfo in allGraphInfo.values())
minX = min(graphInfo['minX'] for graphInfo in allGraphInfo.values())
maxY = max(graphInfo['maxY'] for graphInfo in allGraphInfo.values())
minY = min(graphInfo['minY'] for graphInfo in allGraphInfo.values())
# Post-process graphs to adjust axes, etc.
coords = dimensionalIterator((rows, cols))
for title in titles:
titleAlignments = titlesAlignments[title]
row, col = next(coords)
a = ax[row][col]
a.set_ylim([0, int(maxY * Y_AXIS_UPPER_PADDING)])
if equalizeXAxes:
a.set_xlim([minX, maxX])
a.set_yticks([])
a.set_xticks([])
if xRange == 'subject' and minX < 0:
# Add a vertical line at x=0 so we can see the 'whiskers' of
# reads that extend to the left of the sequence we're aligning
# against.
a.axvline(x=0, color='#cccccc')
# Add a line on the right of each sub-plot so we can see where the
# sequence ends (as all panel graphs have the same width and we
# otherwise couldn't tell).
sequenceLen = titleAlignments.subjectLength
if logLinearXAxis:
sequenceLen = allGraphInfo[title]['adjustOffset'](sequenceLen)
a.axvline(x=sequenceLen, color='#cccccc')
# Hide the final panel graphs (if any) that have no content. We do this
# because the panel is a rectangular grid and some of the plots at the
# end of the last row may be unused.
for row, col in coords:
ax[row][col].axis('off')
# plt.subplots_adjust(left=0.01, bottom=0.01, right=0.99, top=0.93,
# wspace=0.1, hspace=None)
plt.subplots_adjust(hspace=0.4)
figure.suptitle('X: %d to %d, Y (%s): %d to %d' %
(minX, maxX,
titlesAlignments.readsAlignments.params.scoreTitle,
int(minY), int(maxY)), fontsize=20)
figure.set_size_inches(5 * cols, 3 * rows, forward=True)
figure.show()
stop = time()
report('Alignment panel generated in %.3f mins.' % ((stop - start) / 60.0)) | [
"def",
"alignmentPanel",
"(",
"titlesAlignments",
",",
"sortOn",
"=",
"'maxScore'",
",",
"idList",
"=",
"False",
",",
"equalizeXAxes",
"=",
"False",
",",
"xRange",
"=",
"'subject'",
",",
"logLinearXAxis",
"=",
"False",
",",
"rankScores",
"=",
"False",
",",
"... | Produces a rectangular panel of graphs that each contain an alignment graph
against a given sequence.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param sortOn: The attribute to sort subplots on. Either "maxScore",
"medianScore", "readCount", "length", or "title".
@param idList: A dictionary. Keys are colors and values are lists of read
ids that should be colored using that color.
@param equalizeXAxes: If C{True}, adjust the X axis on each alignment plot
to be the same.
@param xRange: Set to either 'subject' or 'reads' to indicate the range of
the X axis.
@param logLinearXAxis: If C{True}, convert read offsets so that empty
regions in the plots we're preparing will only be as wide as their
logged actual values.
@param logBase: The logarithm base to use if logLinearXAxis is C{True}.
@param: rankScores: If C{True}, change the scores for the reads for each
title to be their rank (worst to best).
@param showFeatures: If C{True}, look online for features of the subject
sequences.
@raise ValueError: If C{outputDir} exists but is not a directory or if
C{xRange} is not "subject" or "reads". | [
"Produces",
"a",
"rectangular",
"panel",
"of",
"graphs",
"that",
"each",
"contain",
"an",
"alignment",
"graph",
"against",
"a",
"given",
"sequence",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/graphics.py#L489-L620 |
acorg/dark-matter | dark/graphics.py | alignmentPanelHTML | def alignmentPanelHTML(titlesAlignments, sortOn='maxScore',
outputDir=None, idList=False, equalizeXAxes=False,
xRange='subject', logLinearXAxis=False,
logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE,
rankScores=False, showFeatures=True, showOrfs=True):
"""
Produces an HTML index file in C{outputDir} and a collection of alignment
graphs and FASTA files to summarize the information in C{titlesAlignments}.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param sortOn: The attribute to sort subplots on. Either "maxScore",
"medianScore", "readCount", "length", or "title".
@param outputDir: Specifies a C{str} directory to write the HTML to. If
the directory does not exist it will be created.
@param idList: A dictionary. Keys are colors and values are lists of read
ids that should be colored using that color.
@param equalizeXAxes: If C{True}, adjust the X axis on each alignment plot
to be the same.
@param xRange: Set to either 'subject' or 'reads' to indicate the range of
the X axis.
@param logLinearXAxis: If C{True}, convert read offsets so that empty
regions in the plots we're preparing will only be as wide as their
logged actual values.
@param logBase: The logarithm base to use if logLinearXAxis is C{True}.
@param: rankScores: If C{True}, change the scores for the reads for each
title to be their rank (worst to best).
@param showFeatures: If C{True}, look online for features of the subject
sequences.
@param showOrfs: If C{True}, open reading frames will be displayed.
@raise TypeError: If C{outputDir} is C{None}.
@raise ValueError: If C{outputDir} is None or exists but is not a
directory or if C{xRange} is not "subject" or "reads".
"""
if xRange not in ('subject', 'reads'):
raise ValueError('xRange must be either "subject" or "reads".')
if equalizeXAxes:
raise NotImplementedError('This feature is not yet implemented.')
titles = titlesAlignments.sortTitles(sortOn)
if os.access(outputDir, os.F_OK):
# outputDir exists. Check it's a directory.
if not S_ISDIR(os.stat(outputDir).st_mode):
raise ValueError("%r is not a directory." % outputDir)
else:
if outputDir is None:
raise ValueError("The outputDir needs to be specified.")
else:
os.mkdir(outputDir)
htmlWriter = AlignmentPanelHTMLWriter(outputDir, titlesAlignments)
for i, title in enumerate(titles):
# titleAlignments = titlesAlignments[title]
# If we are writing data to a file too, create a separate file with
# a plot (this will be linked from the summary HTML).
imageBasename = '%d.png' % i
imageFile = '%s/%s' % (outputDir, imageBasename)
graphInfo = alignmentGraph(
titlesAlignments, title, addQueryLines=True,
showFeatures=showFeatures, rankScores=rankScores,
logLinearXAxis=logLinearXAxis, logBase=logBase,
colorQueryBases=False, showFigure=False, imageFile=imageFile,
quiet=True, idList=idList, xRange=xRange, showOrfs=showOrfs)
# Close the image plot to make sure memory is flushed.
plt.close()
htmlWriter.addImage(imageBasename, title, graphInfo)
htmlWriter.close() | python | def alignmentPanelHTML(titlesAlignments, sortOn='maxScore',
outputDir=None, idList=False, equalizeXAxes=False,
xRange='subject', logLinearXAxis=False,
logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE,
rankScores=False, showFeatures=True, showOrfs=True):
"""
Produces an HTML index file in C{outputDir} and a collection of alignment
graphs and FASTA files to summarize the information in C{titlesAlignments}.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param sortOn: The attribute to sort subplots on. Either "maxScore",
"medianScore", "readCount", "length", or "title".
@param outputDir: Specifies a C{str} directory to write the HTML to. If
the directory does not exist it will be created.
@param idList: A dictionary. Keys are colors and values are lists of read
ids that should be colored using that color.
@param equalizeXAxes: If C{True}, adjust the X axis on each alignment plot
to be the same.
@param xRange: Set to either 'subject' or 'reads' to indicate the range of
the X axis.
@param logLinearXAxis: If C{True}, convert read offsets so that empty
regions in the plots we're preparing will only be as wide as their
logged actual values.
@param logBase: The logarithm base to use if logLinearXAxis is C{True}.
@param: rankScores: If C{True}, change the scores for the reads for each
title to be their rank (worst to best).
@param showFeatures: If C{True}, look online for features of the subject
sequences.
@param showOrfs: If C{True}, open reading frames will be displayed.
@raise TypeError: If C{outputDir} is C{None}.
@raise ValueError: If C{outputDir} is None or exists but is not a
directory or if C{xRange} is not "subject" or "reads".
"""
if xRange not in ('subject', 'reads'):
raise ValueError('xRange must be either "subject" or "reads".')
if equalizeXAxes:
raise NotImplementedError('This feature is not yet implemented.')
titles = titlesAlignments.sortTitles(sortOn)
if os.access(outputDir, os.F_OK):
# outputDir exists. Check it's a directory.
if not S_ISDIR(os.stat(outputDir).st_mode):
raise ValueError("%r is not a directory." % outputDir)
else:
if outputDir is None:
raise ValueError("The outputDir needs to be specified.")
else:
os.mkdir(outputDir)
htmlWriter = AlignmentPanelHTMLWriter(outputDir, titlesAlignments)
for i, title in enumerate(titles):
# titleAlignments = titlesAlignments[title]
# If we are writing data to a file too, create a separate file with
# a plot (this will be linked from the summary HTML).
imageBasename = '%d.png' % i
imageFile = '%s/%s' % (outputDir, imageBasename)
graphInfo = alignmentGraph(
titlesAlignments, title, addQueryLines=True,
showFeatures=showFeatures, rankScores=rankScores,
logLinearXAxis=logLinearXAxis, logBase=logBase,
colorQueryBases=False, showFigure=False, imageFile=imageFile,
quiet=True, idList=idList, xRange=xRange, showOrfs=showOrfs)
# Close the image plot to make sure memory is flushed.
plt.close()
htmlWriter.addImage(imageBasename, title, graphInfo)
htmlWriter.close() | [
"def",
"alignmentPanelHTML",
"(",
"titlesAlignments",
",",
"sortOn",
"=",
"'maxScore'",
",",
"outputDir",
"=",
"None",
",",
"idList",
"=",
"False",
",",
"equalizeXAxes",
"=",
"False",
",",
"xRange",
"=",
"'subject'",
",",
"logLinearXAxis",
"=",
"False",
",",
... | Produces an HTML index file in C{outputDir} and a collection of alignment
graphs and FASTA files to summarize the information in C{titlesAlignments}.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param sortOn: The attribute to sort subplots on. Either "maxScore",
"medianScore", "readCount", "length", or "title".
@param outputDir: Specifies a C{str} directory to write the HTML to. If
the directory does not exist it will be created.
@param idList: A dictionary. Keys are colors and values are lists of read
ids that should be colored using that color.
@param equalizeXAxes: If C{True}, adjust the X axis on each alignment plot
to be the same.
@param xRange: Set to either 'subject' or 'reads' to indicate the range of
the X axis.
@param logLinearXAxis: If C{True}, convert read offsets so that empty
regions in the plots we're preparing will only be as wide as their
logged actual values.
@param logBase: The logarithm base to use if logLinearXAxis is C{True}.
@param: rankScores: If C{True}, change the scores for the reads for each
title to be their rank (worst to best).
@param showFeatures: If C{True}, look online for features of the subject
sequences.
@param showOrfs: If C{True}, open reading frames will be displayed.
@raise TypeError: If C{outputDir} is C{None}.
@raise ValueError: If C{outputDir} is None or exists but is not a
directory or if C{xRange} is not "subject" or "reads". | [
"Produces",
"an",
"HTML",
"index",
"file",
"in",
"C",
"{",
"outputDir",
"}",
"and",
"a",
"collection",
"of",
"alignment",
"graphs",
"and",
"FASTA",
"files",
"to",
"summarize",
"the",
"information",
"in",
"C",
"{",
"titlesAlignments",
"}",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/graphics.py#L623-L695 |
acorg/dark-matter | dark/graphics.py | scoreGraph | def scoreGraph(titlesAlignments, find=None, showTitles=False, figureWidth=5,
figureHeight=5):
"""
NOTE: This function has probably bit rotted (but only a little).
Produce a rectangular panel of graphs, each of which shows sorted scores
for a title. Matches against a certain sequence title, as determined by
C{find}, (see below) are highlighted.
@param find: A function that can be passed a sequence title. If the
function returns C{True} a red dot is put into the graph at that point
to highlight the match.
@param showTitles: If C{True} display read sequence names. The panel tends
to look terrible when titles are displayed. If C{False}, show no title.
@param figureWidth: The C{float} width of the figure, in inches.
@param figureHeight: The C{float} height of the figure, in inches.
"""
maxScore = None
maxHsps = 0
cols = 5
rows = int(len(titlesAlignments) / cols) + (
0 if len(titlesAlignments) % cols == 0 else 1)
f, ax = plt.subplots(rows, cols)
coords = dimensionalIterator((rows, cols))
for title in titlesAlignments:
titleAlignments = titlesAlignments[title]
row, col = next(coords)
hspCount = titleAlignments.hspCount()
if hspCount > maxHsps:
maxHsps = hspCount
scores = []
highlightX = []
highlightY = []
for x, titleAlignment in enumerate(titleAlignments):
score = titleAlignment.hsps[0].score.score
scores.append(score)
if find and find(titleAlignment.subjectTitle):
highlightX.append(x)
highlightY.append(score)
a = ax[row][col]
if scores:
max_ = max(scores)
if maxScore is None or max_ > maxScore:
maxScore = max_
x = np.arange(0, len(scores))
a.plot(x, scores)
if highlightX:
a.plot(highlightX, highlightY, 'ro')
if showTitles:
a.set_title('%s' % title, fontsize=10)
# Adjust all plots to have the same dimensions.
coords = dimensionalIterator((rows, cols))
for _ in range(len(titlesAlignments)):
row, col = next(coords)
a = ax[row][col]
a.axis([0, maxHsps, 0, maxScore])
# a.set_yscale('log')
a.set_yticks([])
a.set_xticks([])
# Hide the final panel graphs (if any) that have no content. We do this
# because the panel is a rectangular grid and some of the plots at the
# end of the last row may be unused.
for row, col in coords:
ax[row][col].axis('off')
plt.subplots_adjust(left=0.01, bottom=0.01, right=0.99, top=0.93,
wspace=0.1, hspace=None)
f.suptitle('max HSPs %d, max score %f' % (maxHsps, maxScore))
f.set_size_inches(figureWidth, figureHeight, forward=True)
# f.savefig('scores.png')
plt.show() | python | def scoreGraph(titlesAlignments, find=None, showTitles=False, figureWidth=5,
figureHeight=5):
"""
NOTE: This function has probably bit rotted (but only a little).
Produce a rectangular panel of graphs, each of which shows sorted scores
for a title. Matches against a certain sequence title, as determined by
C{find}, (see below) are highlighted.
@param find: A function that can be passed a sequence title. If the
function returns C{True} a red dot is put into the graph at that point
to highlight the match.
@param showTitles: If C{True} display read sequence names. The panel tends
to look terrible when titles are displayed. If C{False}, show no title.
@param figureWidth: The C{float} width of the figure, in inches.
@param figureHeight: The C{float} height of the figure, in inches.
"""
maxScore = None
maxHsps = 0
cols = 5
rows = int(len(titlesAlignments) / cols) + (
0 if len(titlesAlignments) % cols == 0 else 1)
f, ax = plt.subplots(rows, cols)
coords = dimensionalIterator((rows, cols))
for title in titlesAlignments:
titleAlignments = titlesAlignments[title]
row, col = next(coords)
hspCount = titleAlignments.hspCount()
if hspCount > maxHsps:
maxHsps = hspCount
scores = []
highlightX = []
highlightY = []
for x, titleAlignment in enumerate(titleAlignments):
score = titleAlignment.hsps[0].score.score
scores.append(score)
if find and find(titleAlignment.subjectTitle):
highlightX.append(x)
highlightY.append(score)
a = ax[row][col]
if scores:
max_ = max(scores)
if maxScore is None or max_ > maxScore:
maxScore = max_
x = np.arange(0, len(scores))
a.plot(x, scores)
if highlightX:
a.plot(highlightX, highlightY, 'ro')
if showTitles:
a.set_title('%s' % title, fontsize=10)
# Adjust all plots to have the same dimensions.
coords = dimensionalIterator((rows, cols))
for _ in range(len(titlesAlignments)):
row, col = next(coords)
a = ax[row][col]
a.axis([0, maxHsps, 0, maxScore])
# a.set_yscale('log')
a.set_yticks([])
a.set_xticks([])
# Hide the final panel graphs (if any) that have no content. We do this
# because the panel is a rectangular grid and some of the plots at the
# end of the last row may be unused.
for row, col in coords:
ax[row][col].axis('off')
plt.subplots_adjust(left=0.01, bottom=0.01, right=0.99, top=0.93,
wspace=0.1, hspace=None)
f.suptitle('max HSPs %d, max score %f' % (maxHsps, maxScore))
f.set_size_inches(figureWidth, figureHeight, forward=True)
# f.savefig('scores.png')
plt.show() | [
"def",
"scoreGraph",
"(",
"titlesAlignments",
",",
"find",
"=",
"None",
",",
"showTitles",
"=",
"False",
",",
"figureWidth",
"=",
"5",
",",
"figureHeight",
"=",
"5",
")",
":",
"maxScore",
"=",
"None",
"maxHsps",
"=",
"0",
"cols",
"=",
"5",
"rows",
"=",... | NOTE: This function has probably bit rotted (but only a little).
Produce a rectangular panel of graphs, each of which shows sorted scores
for a title. Matches against a certain sequence title, as determined by
C{find}, (see below) are highlighted.
@param find: A function that can be passed a sequence title. If the
function returns C{True} a red dot is put into the graph at that point
to highlight the match.
@param showTitles: If C{True} display read sequence names. The panel tends
to look terrible when titles are displayed. If C{False}, show no title.
@param figureWidth: The C{float} width of the figure, in inches.
@param figureHeight: The C{float} height of the figure, in inches. | [
"NOTE",
":",
"This",
"function",
"has",
"probably",
"bit",
"rotted",
"(",
"but",
"only",
"a",
"little",
")",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/graphics.py#L698-L771 |
acorg/dark-matter | dark/graphics.py | scatterAlign | def scatterAlign(seq1, seq2, window=7):
"""
Visually align two sequences.
"""
d1 = defaultdict(list)
d2 = defaultdict(list)
for (seq, section_dict) in [(seq1, d1), (seq2, d2)]:
for i in range(len(seq) - window):
section = seq[i:i + window]
section_dict[section].append(i)
matches = set(d1).intersection(d2)
print('%i unique matches' % len(matches))
x = []
y = []
for section in matches:
for i in d1[section]:
for j in d2[section]:
x.append(i)
y.append(j)
# plt.cla() # clear any prior graph
plt.gray()
plt.scatter(x, y)
plt.xlim(0, len(seq1) - window)
plt.ylim(0, len(seq2) - window)
plt.xlabel('length %i bp' % (len(seq1)))
plt.ylabel('length %i bp' % (len(seq2)))
plt.title('Dot plot using window size %i\n(allowing no mis-matches)' %
window)
plt.show() | python | def scatterAlign(seq1, seq2, window=7):
"""
Visually align two sequences.
"""
d1 = defaultdict(list)
d2 = defaultdict(list)
for (seq, section_dict) in [(seq1, d1), (seq2, d2)]:
for i in range(len(seq) - window):
section = seq[i:i + window]
section_dict[section].append(i)
matches = set(d1).intersection(d2)
print('%i unique matches' % len(matches))
x = []
y = []
for section in matches:
for i in d1[section]:
for j in d2[section]:
x.append(i)
y.append(j)
# plt.cla() # clear any prior graph
plt.gray()
plt.scatter(x, y)
plt.xlim(0, len(seq1) - window)
plt.ylim(0, len(seq2) - window)
plt.xlabel('length %i bp' % (len(seq1)))
plt.ylabel('length %i bp' % (len(seq2)))
plt.title('Dot plot using window size %i\n(allowing no mis-matches)' %
window)
plt.show() | [
"def",
"scatterAlign",
"(",
"seq1",
",",
"seq2",
",",
"window",
"=",
"7",
")",
":",
"d1",
"=",
"defaultdict",
"(",
"list",
")",
"d2",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"(",
"seq",
",",
"section_dict",
")",
"in",
"[",
"(",
"seq1",
",",
... | Visually align two sequences. | [
"Visually",
"align",
"two",
"sequences",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/graphics.py#L774-L802 |
acorg/dark-matter | dark/graphics.py | plotAAProperties | def plotAAProperties(sequence, propertyNames, showLines=True, showFigure=True):
"""
Plot amino acid property values for a sequence.
@param sequence: An C{AARead} (or a subclass) instance.
@param propertyNames: An iterable of C{str} property names (each of which
must be a key of a key in the C{dark.aa.PROPERTY_DETAILS} C{dict}).
@param showLines: If C{True}, lines will be drawn between successive AA
property values. If not, just the values will be plotted as a scatter
plot (this greatly reduces visual clutter if the sequence is long and
AA property values are variable).
@param showFigure: If C{True}, display the plot. Passing C{False} is useful
in testing.
@raise ValueError: If an unknown property is given in C{propertyNames}.
@return: The return value from calling dark.aa.propertiesForSequence:
a C{dict} keyed by (lowercase) property name, with values that are
C{list}s of the corresponding property value according to sequence
position.
"""
MISSING_AA_VALUE = -1.1
propertyValues = propertiesForSequence(sequence, propertyNames,
missingAAValue=MISSING_AA_VALUE)
if showFigure:
legend = []
x = np.arange(0, len(sequence))
plot = plt.plot if showLines else plt.scatter
for index, propertyName in enumerate(propertyValues):
color = TABLEAU20[index]
plot(x, propertyValues[propertyName], color=color)
legend.append(patches.Patch(color=color, label=propertyName))
plt.legend(handles=legend, loc=(0, 1.1))
plt.xlim(-0.2, len(sequence) - 0.8)
plt.ylim(min(MISSING_AA_VALUE, -1.1), 1.1)
plt.xlabel('Sequence index')
plt.ylabel('Property value')
plt.title(sequence.id)
plt.show()
return propertyValues | python | def plotAAProperties(sequence, propertyNames, showLines=True, showFigure=True):
"""
Plot amino acid property values for a sequence.
@param sequence: An C{AARead} (or a subclass) instance.
@param propertyNames: An iterable of C{str} property names (each of which
must be a key of a key in the C{dark.aa.PROPERTY_DETAILS} C{dict}).
@param showLines: If C{True}, lines will be drawn between successive AA
property values. If not, just the values will be plotted as a scatter
plot (this greatly reduces visual clutter if the sequence is long and
AA property values are variable).
@param showFigure: If C{True}, display the plot. Passing C{False} is useful
in testing.
@raise ValueError: If an unknown property is given in C{propertyNames}.
@return: The return value from calling dark.aa.propertiesForSequence:
a C{dict} keyed by (lowercase) property name, with values that are
C{list}s of the corresponding property value according to sequence
position.
"""
MISSING_AA_VALUE = -1.1
propertyValues = propertiesForSequence(sequence, propertyNames,
missingAAValue=MISSING_AA_VALUE)
if showFigure:
legend = []
x = np.arange(0, len(sequence))
plot = plt.plot if showLines else plt.scatter
for index, propertyName in enumerate(propertyValues):
color = TABLEAU20[index]
plot(x, propertyValues[propertyName], color=color)
legend.append(patches.Patch(color=color, label=propertyName))
plt.legend(handles=legend, loc=(0, 1.1))
plt.xlim(-0.2, len(sequence) - 0.8)
plt.ylim(min(MISSING_AA_VALUE, -1.1), 1.1)
plt.xlabel('Sequence index')
plt.ylabel('Property value')
plt.title(sequence.id)
plt.show()
return propertyValues | [
"def",
"plotAAProperties",
"(",
"sequence",
",",
"propertyNames",
",",
"showLines",
"=",
"True",
",",
"showFigure",
"=",
"True",
")",
":",
"MISSING_AA_VALUE",
"=",
"-",
"1.1",
"propertyValues",
"=",
"propertiesForSequence",
"(",
"sequence",
",",
"propertyNames",
... | Plot amino acid property values for a sequence.
@param sequence: An C{AARead} (or a subclass) instance.
@param propertyNames: An iterable of C{str} property names (each of which
must be a key of a key in the C{dark.aa.PROPERTY_DETAILS} C{dict}).
@param showLines: If C{True}, lines will be drawn between successive AA
property values. If not, just the values will be plotted as a scatter
plot (this greatly reduces visual clutter if the sequence is long and
AA property values are variable).
@param showFigure: If C{True}, display the plot. Passing C{False} is useful
in testing.
@raise ValueError: If an unknown property is given in C{propertyNames}.
@return: The return value from calling dark.aa.propertiesForSequence:
a C{dict} keyed by (lowercase) property name, with values that are
C{list}s of the corresponding property value according to sequence
position. | [
"Plot",
"amino",
"acid",
"property",
"values",
"for",
"a",
"sequence",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/graphics.py#L805-L845 |
acorg/dark-matter | dark/graphics.py | plotAAClusters | def plotAAClusters(sequence, propertyNames, showLines=True, showFigure=True):
"""
Plot amino acid property cluster numbers for a sequence.
@param sequence: An C{AARead} (or a subclass) instance.
@param propertyNames: An iterable of C{str} property names (each of which
must be a key of a key in the C{dark.aa.PROPERTY_CLUSTERS} C{dict}).
@param showLines: If C{True}, lines will be drawn between successive AA
property values. If not, just the values will be plotted as a scatter
plot (this greatly reduces visual clutter if the sequence is long and
AA property values are variable).
@param showFigure: If C{True}, display the plot. Passing C{False} is useful
in testing.
@raise ValueError: If an unknown property is given in C{propertyNames}.
@return: The return value from calling dark.aa.clustersForSequence:
a C{dict} keyed by (lowercase) property name, with values that are
C{list}s of the corresponding property value according to sequence
position.
"""
MISSING_AA_VALUE = 0
propertyClusters = clustersForSequence(sequence, propertyNames,
missingAAValue=MISSING_AA_VALUE)
if showFigure:
minCluster = 1
maxCluster = -1
legend = []
x = np.arange(0, len(sequence))
plot = plt.plot if showLines else plt.scatter
for index, propertyName in enumerate(propertyClusters):
color = TABLEAU20[index]
clusterNumbers = propertyClusters[propertyName]
plot(x, clusterNumbers, color=color)
legend.append(patches.Patch(color=color, label=propertyName))
propertyMinCluster = min(clusterNumbers)
if propertyMinCluster < minCluster:
minCluster = propertyMinCluster
propertyMaxCluster = max(clusterNumbers)
if propertyMaxCluster > maxCluster:
maxCluster = propertyMaxCluster
plt.legend(handles=legend, loc=(0, 1.1))
plt.xlim(-0.2, len(sequence) - 0.8)
plt.ylim(minCluster - 0.5, maxCluster + 0.5)
plt.yticks(range(maxCluster + 1))
plt.xlabel('Sequence index')
plt.ylabel('Property cluster number')
plt.title(sequence.id)
plt.show()
return propertyClusters | python | def plotAAClusters(sequence, propertyNames, showLines=True, showFigure=True):
"""
Plot amino acid property cluster numbers for a sequence.
@param sequence: An C{AARead} (or a subclass) instance.
@param propertyNames: An iterable of C{str} property names (each of which
must be a key of a key in the C{dark.aa.PROPERTY_CLUSTERS} C{dict}).
@param showLines: If C{True}, lines will be drawn between successive AA
property values. If not, just the values will be plotted as a scatter
plot (this greatly reduces visual clutter if the sequence is long and
AA property values are variable).
@param showFigure: If C{True}, display the plot. Passing C{False} is useful
in testing.
@raise ValueError: If an unknown property is given in C{propertyNames}.
@return: The return value from calling dark.aa.clustersForSequence:
a C{dict} keyed by (lowercase) property name, with values that are
C{list}s of the corresponding property value according to sequence
position.
"""
MISSING_AA_VALUE = 0
propertyClusters = clustersForSequence(sequence, propertyNames,
missingAAValue=MISSING_AA_VALUE)
if showFigure:
minCluster = 1
maxCluster = -1
legend = []
x = np.arange(0, len(sequence))
plot = plt.plot if showLines else plt.scatter
for index, propertyName in enumerate(propertyClusters):
color = TABLEAU20[index]
clusterNumbers = propertyClusters[propertyName]
plot(x, clusterNumbers, color=color)
legend.append(patches.Patch(color=color, label=propertyName))
propertyMinCluster = min(clusterNumbers)
if propertyMinCluster < minCluster:
minCluster = propertyMinCluster
propertyMaxCluster = max(clusterNumbers)
if propertyMaxCluster > maxCluster:
maxCluster = propertyMaxCluster
plt.legend(handles=legend, loc=(0, 1.1))
plt.xlim(-0.2, len(sequence) - 0.8)
plt.ylim(minCluster - 0.5, maxCluster + 0.5)
plt.yticks(range(maxCluster + 1))
plt.xlabel('Sequence index')
plt.ylabel('Property cluster number')
plt.title(sequence.id)
plt.show()
return propertyClusters | [
"def",
"plotAAClusters",
"(",
"sequence",
",",
"propertyNames",
",",
"showLines",
"=",
"True",
",",
"showFigure",
"=",
"True",
")",
":",
"MISSING_AA_VALUE",
"=",
"0",
"propertyClusters",
"=",
"clustersForSequence",
"(",
"sequence",
",",
"propertyNames",
",",
"mi... | Plot amino acid property cluster numbers for a sequence.
@param sequence: An C{AARead} (or a subclass) instance.
@param propertyNames: An iterable of C{str} property names (each of which
must be a key of a key in the C{dark.aa.PROPERTY_CLUSTERS} C{dict}).
@param showLines: If C{True}, lines will be drawn between successive AA
property values. If not, just the values will be plotted as a scatter
plot (this greatly reduces visual clutter if the sequence is long and
AA property values are variable).
@param showFigure: If C{True}, display the plot. Passing C{False} is useful
in testing.
@raise ValueError: If an unknown property is given in C{propertyNames}.
@return: The return value from calling dark.aa.clustersForSequence:
a C{dict} keyed by (lowercase) property name, with values that are
C{list}s of the corresponding property value according to sequence
position. | [
"Plot",
"amino",
"acid",
"property",
"cluster",
"numbers",
"for",
"a",
"sequence",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/graphics.py#L848-L900 |
nkavaldj/myhdl_lib | myhdl_lib/utils.py | byteorder | def byteorder(bv_di, bv_do, REVERSE=True):
""" Reverses the byte order of an input bit-vector
bv_di - (i) input bit-vector
bv_do - (o) output bit-vector
"""
BITS = len(bv_di)
assert (BITS % 8)==0, "byteorder: expects len(bv_in)=8*x, but len(bv_in)={}".format(BITS)
if REVERSE:
BYTES = BITS//8
y = ConcatSignal(*[bv_di(8*(b+1),8*b) for b in range(BYTES)])
@always_comb
def _reverse():
bv_do.next = y
else:
@always_comb
def _pass():
bv_do.next = bv_di
return instances() | python | def byteorder(bv_di, bv_do, REVERSE=True):
""" Reverses the byte order of an input bit-vector
bv_di - (i) input bit-vector
bv_do - (o) output bit-vector
"""
BITS = len(bv_di)
assert (BITS % 8)==0, "byteorder: expects len(bv_in)=8*x, but len(bv_in)={}".format(BITS)
if REVERSE:
BYTES = BITS//8
y = ConcatSignal(*[bv_di(8*(b+1),8*b) for b in range(BYTES)])
@always_comb
def _reverse():
bv_do.next = y
else:
@always_comb
def _pass():
bv_do.next = bv_di
return instances() | [
"def",
"byteorder",
"(",
"bv_di",
",",
"bv_do",
",",
"REVERSE",
"=",
"True",
")",
":",
"BITS",
"=",
"len",
"(",
"bv_di",
")",
"assert",
"(",
"BITS",
"%",
"8",
")",
"==",
"0",
",",
"\"byteorder: expects len(bv_in)=8*x, but len(bv_in)={}\"",
".",
"format",
"... | Reverses the byte order of an input bit-vector
bv_di - (i) input bit-vector
bv_do - (o) output bit-vector | [
"Reverses",
"the",
"byte",
"order",
"of",
"an",
"input",
"bit",
"-",
"vector",
"bv_di",
"-",
"(",
"i",
")",
"input",
"bit",
"-",
"vector",
"bv_do",
"-",
"(",
"o",
")",
"output",
"bit",
"-",
"vector"
] | train | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/utils.py#L12-L34 |
invenia/Arbiter | arbiter/base.py | task_loop | def task_loop(tasks, execute, wait=None, store=TaskStore()):
"""
The inner task loop for a task runner.
execute: A function that runs a task. It should take a task as its
sole argument, and may optionally return a TaskResult.
wait: (optional, None) A function to run whenever there aren't any
runnable tasks (but there are still tasks listed as running).
If given, this function should take no arguments, and should
return an iterable of TaskResults.
"""
completed = set()
failed = set()
exceptions = []
def collect(task):
args = []
kwargs = {}
for arg in task.args:
if isinstance(arg, Task):
args.append(store.get(arg.name))
else:
args.append(arg)
for key in task.kwargs:
if isinstance(task.kwargs[key], Task):
kwargs[key] = store.get(task.kwargs[key].name)
else:
kwargs[key] = task.kwargs[key]
return args, kwargs
def complete(scheduler, result):
store.put(result.name, result.data)
scheduler.end_task(result.name, result.successful)
if result.exception:
exceptions.append(result.exception)
with Scheduler(tasks, completed=completed, failed=failed) as scheduler:
while not scheduler.is_finished():
task = scheduler.start_task()
while task is not None:
# Collect any dependent results
args, kwargs = collect(task)
func = partial(task.function, *args, **kwargs)
if task.handler:
func = partial(task.handler, func)
result = execute(func, task.name)
# result exists iff execute is synchroous
if result:
complete(scheduler, result)
task = scheduler.start_task()
if wait:
for result in wait():
complete(scheduler, result)
# TODO: if in debug mode print out all failed tasks?
return Results(completed, failed, exceptions) | python | def task_loop(tasks, execute, wait=None, store=TaskStore()):
"""
The inner task loop for a task runner.
execute: A function that runs a task. It should take a task as its
sole argument, and may optionally return a TaskResult.
wait: (optional, None) A function to run whenever there aren't any
runnable tasks (but there are still tasks listed as running).
If given, this function should take no arguments, and should
return an iterable of TaskResults.
"""
completed = set()
failed = set()
exceptions = []
def collect(task):
args = []
kwargs = {}
for arg in task.args:
if isinstance(arg, Task):
args.append(store.get(arg.name))
else:
args.append(arg)
for key in task.kwargs:
if isinstance(task.kwargs[key], Task):
kwargs[key] = store.get(task.kwargs[key].name)
else:
kwargs[key] = task.kwargs[key]
return args, kwargs
def complete(scheduler, result):
store.put(result.name, result.data)
scheduler.end_task(result.name, result.successful)
if result.exception:
exceptions.append(result.exception)
with Scheduler(tasks, completed=completed, failed=failed) as scheduler:
while not scheduler.is_finished():
task = scheduler.start_task()
while task is not None:
# Collect any dependent results
args, kwargs = collect(task)
func = partial(task.function, *args, **kwargs)
if task.handler:
func = partial(task.handler, func)
result = execute(func, task.name)
# result exists iff execute is synchroous
if result:
complete(scheduler, result)
task = scheduler.start_task()
if wait:
for result in wait():
complete(scheduler, result)
# TODO: if in debug mode print out all failed tasks?
return Results(completed, failed, exceptions) | [
"def",
"task_loop",
"(",
"tasks",
",",
"execute",
",",
"wait",
"=",
"None",
",",
"store",
"=",
"TaskStore",
"(",
")",
")",
":",
"completed",
"=",
"set",
"(",
")",
"failed",
"=",
"set",
"(",
")",
"exceptions",
"=",
"[",
"]",
"def",
"collect",
"(",
... | The inner task loop for a task runner.
execute: A function that runs a task. It should take a task as its
sole argument, and may optionally return a TaskResult.
wait: (optional, None) A function to run whenever there aren't any
runnable tasks (but there are still tasks listed as running).
If given, this function should take no arguments, and should
return an iterable of TaskResults. | [
"The",
"inner",
"task",
"loop",
"for",
"a",
"task",
"runner",
"."
] | train | https://github.com/invenia/Arbiter/blob/51008393ae8797da85bcd67807259a157f941dfd/arbiter/base.py#L17-L80 |
acorg/dark-matter | bin/aa-info.py | findOrDie | def findOrDie(s):
"""
Look up an amino acid.
@param s: A C{str} amino acid specifier. This may be a full name,
a 3-letter abbreviation or a 1-letter abbreviation. Case is ignored.
@return: An C{AminoAcid} instance, if one can be found. Else exit.
"""
aa = find(s)
if aa:
return aa
else:
print('Unknown amino acid or codon: %s' % s, file=sys.stderr)
print('Valid arguments are: %s.' % list(CODONS.keys()),
file=sys.stderr)
sys.exit(1) | python | def findOrDie(s):
"""
Look up an amino acid.
@param s: A C{str} amino acid specifier. This may be a full name,
a 3-letter abbreviation or a 1-letter abbreviation. Case is ignored.
@return: An C{AminoAcid} instance, if one can be found. Else exit.
"""
aa = find(s)
if aa:
return aa
else:
print('Unknown amino acid or codon: %s' % s, file=sys.stderr)
print('Valid arguments are: %s.' % list(CODONS.keys()),
file=sys.stderr)
sys.exit(1) | [
"def",
"findOrDie",
"(",
"s",
")",
":",
"aa",
"=",
"find",
"(",
"s",
")",
"if",
"aa",
":",
"return",
"aa",
"else",
":",
"print",
"(",
"'Unknown amino acid or codon: %s'",
"%",
"s",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"print",
"(",
"'Valid ar... | Look up an amino acid.
@param s: A C{str} amino acid specifier. This may be a full name,
a 3-letter abbreviation or a 1-letter abbreviation. Case is ignored.
@return: An C{AminoAcid} instance, if one can be found. Else exit. | [
"Look",
"up",
"an",
"amino",
"acid",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/bin/aa-info.py#L13-L28 |
flo-compbio/genometools | genometools/misc/download.py | http_download | def http_download(url, download_file,
overwrite=False, raise_http_exception=True):
"""Download a file over HTTP(S).
See: http://stackoverflow.com/a/13137873/5651021
Parameters
----------
url : str
The URL.
download_file : str
The path of the local file to write to.
overwrite : bool, optional
Whether to overwrite an existing file (if present). [False]
raise_http_exception : bool, optional
Whether to raise an exception if there is an HTTP error. [True]
Raises
------
OSError
If the file already exists and overwrite is set to False.
`requests.HTTPError`
If an HTTP error occurred and `raise_http_exception` was set to `True`.
"""
assert isinstance(url, (str, _oldstr))
assert isinstance(download_file, (str, _oldstr))
assert isinstance(overwrite, bool)
assert isinstance(raise_http_exception, bool)
u = urlparse.urlparse(url)
assert u.scheme in ['http', 'https']
if os.path.isfile(download_file) and not overwrite:
raise OSError('File "%s" already exists!' % download_file)
r = requests.get(url, stream=True)
if raise_http_exception:
r.raise_for_status()
if r.status_code == 200:
with open(download_file, 'wb') as fh:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, fh)
_logger.info('Downloaded file "%s".', download_file)
else:
_logger.error('Failed to download url "%s": HTTP status %d/%s',
url, r.status_code, r.reason) | python | def http_download(url, download_file,
overwrite=False, raise_http_exception=True):
"""Download a file over HTTP(S).
See: http://stackoverflow.com/a/13137873/5651021
Parameters
----------
url : str
The URL.
download_file : str
The path of the local file to write to.
overwrite : bool, optional
Whether to overwrite an existing file (if present). [False]
raise_http_exception : bool, optional
Whether to raise an exception if there is an HTTP error. [True]
Raises
------
OSError
If the file already exists and overwrite is set to False.
`requests.HTTPError`
If an HTTP error occurred and `raise_http_exception` was set to `True`.
"""
assert isinstance(url, (str, _oldstr))
assert isinstance(download_file, (str, _oldstr))
assert isinstance(overwrite, bool)
assert isinstance(raise_http_exception, bool)
u = urlparse.urlparse(url)
assert u.scheme in ['http', 'https']
if os.path.isfile(download_file) and not overwrite:
raise OSError('File "%s" already exists!' % download_file)
r = requests.get(url, stream=True)
if raise_http_exception:
r.raise_for_status()
if r.status_code == 200:
with open(download_file, 'wb') as fh:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, fh)
_logger.info('Downloaded file "%s".', download_file)
else:
_logger.error('Failed to download url "%s": HTTP status %d/%s',
url, r.status_code, r.reason) | [
"def",
"http_download",
"(",
"url",
",",
"download_file",
",",
"overwrite",
"=",
"False",
",",
"raise_http_exception",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"url",
",",
"(",
"str",
",",
"_oldstr",
")",
")",
"assert",
"isinstance",
"(",
"downl... | Download a file over HTTP(S).
See: http://stackoverflow.com/a/13137873/5651021
Parameters
----------
url : str
The URL.
download_file : str
The path of the local file to write to.
overwrite : bool, optional
Whether to overwrite an existing file (if present). [False]
raise_http_exception : bool, optional
Whether to raise an exception if there is an HTTP error. [True]
Raises
------
OSError
If the file already exists and overwrite is set to False.
`requests.HTTPError`
If an HTTP error occurred and `raise_http_exception` was set to `True`. | [
"Download",
"a",
"file",
"over",
"HTTP",
"(",
"S",
")",
".",
"See",
":",
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"a",
"/",
"13137873",
"/",
"5651021"
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/download.py#L40-L86 |
flo-compbio/genometools | genometools/misc/download.py | ftp_download | def ftp_download(url, download_file, if_exists='error',
user_name='anonymous', password='', blocksize=4194304):
"""Downloads a file from an FTP server.
Parameters
----------
url : str
The URL of the file to download.
download_file : str
The path of the local file to download to.
if_exists : str, optional
Desired behavior when the download file already exists. One of:
'error' - Raise an OSError
'skip' - Do nothing, only report a warning.
'overwrite' - Overwrite the file. reporting a warning.
Default: 'error'.
user_name : str, optional
The user name to use for logging into the FTP server. ['anonymous']
password : str, optional
The password to use for logging into the FTP server. ['']
blocksize : int, optional
The blocksize (in bytes) to use for downloading. [4194304]
Returns
-------
None
"""
assert isinstance(url, (str, _oldstr))
assert isinstance(download_file, (str, _oldstr))
assert isinstance(if_exists, (str, _oldstr))
assert isinstance(user_name, (str, _oldstr))
assert isinstance(password, (str, _oldstr))
u = urlparse.urlparse(url)
assert u.scheme == 'ftp'
if if_exists not in ['error', 'skip', 'overwrite']:
raise ValueError('"if_exists" must be "error", "skip", or "overwrite" '
'(was: "%s").', str(if_exists))
if os.path.isfile(download_file):
if if_exists == 'error':
raise OSError('File "%s" already exists.' % download_file)
elif if_exists == 'skip':
_logger.warning('File "%s" already exists. Skipping...',
download_file)
return
else:
_logger.warning('Overwriting file "%s"...', download_file)
ftp_server = u.netloc
ftp_path = u.path
if six.PY3:
with ftplib.FTP(ftp_server) as ftp:
ftp.login(user_name, password)
with open(download_file, 'wb') as ofh:
ftp.retrbinary('RETR %s' % ftp_path,
callback=ofh.write, blocksize=blocksize)
else:
ftp = ftplib.FTP(ftp_server)
ftp.login(user_name, password)
with open(download_file, 'wb') as ofh:
ftp.retrbinary('RETR %s' % ftp_path,
callback=ofh.write, blocksize=blocksize)
ftp.close()
_logger.info('Downloaded file "%s" over FTP.', download_file) | python | def ftp_download(url, download_file, if_exists='error',
user_name='anonymous', password='', blocksize=4194304):
"""Downloads a file from an FTP server.
Parameters
----------
url : str
The URL of the file to download.
download_file : str
The path of the local file to download to.
if_exists : str, optional
Desired behavior when the download file already exists. One of:
'error' - Raise an OSError
'skip' - Do nothing, only report a warning.
'overwrite' - Overwrite the file. reporting a warning.
Default: 'error'.
user_name : str, optional
The user name to use for logging into the FTP server. ['anonymous']
password : str, optional
The password to use for logging into the FTP server. ['']
blocksize : int, optional
The blocksize (in bytes) to use for downloading. [4194304]
Returns
-------
None
"""
assert isinstance(url, (str, _oldstr))
assert isinstance(download_file, (str, _oldstr))
assert isinstance(if_exists, (str, _oldstr))
assert isinstance(user_name, (str, _oldstr))
assert isinstance(password, (str, _oldstr))
u = urlparse.urlparse(url)
assert u.scheme == 'ftp'
if if_exists not in ['error', 'skip', 'overwrite']:
raise ValueError('"if_exists" must be "error", "skip", or "overwrite" '
'(was: "%s").', str(if_exists))
if os.path.isfile(download_file):
if if_exists == 'error':
raise OSError('File "%s" already exists.' % download_file)
elif if_exists == 'skip':
_logger.warning('File "%s" already exists. Skipping...',
download_file)
return
else:
_logger.warning('Overwriting file "%s"...', download_file)
ftp_server = u.netloc
ftp_path = u.path
if six.PY3:
with ftplib.FTP(ftp_server) as ftp:
ftp.login(user_name, password)
with open(download_file, 'wb') as ofh:
ftp.retrbinary('RETR %s' % ftp_path,
callback=ofh.write, blocksize=blocksize)
else:
ftp = ftplib.FTP(ftp_server)
ftp.login(user_name, password)
with open(download_file, 'wb') as ofh:
ftp.retrbinary('RETR %s' % ftp_path,
callback=ofh.write, blocksize=blocksize)
ftp.close()
_logger.info('Downloaded file "%s" over FTP.', download_file) | [
"def",
"ftp_download",
"(",
"url",
",",
"download_file",
",",
"if_exists",
"=",
"'error'",
",",
"user_name",
"=",
"'anonymous'",
",",
"password",
"=",
"''",
",",
"blocksize",
"=",
"4194304",
")",
":",
"assert",
"isinstance",
"(",
"url",
",",
"(",
"str",
... | Downloads a file from an FTP server.
Parameters
----------
url : str
The URL of the file to download.
download_file : str
The path of the local file to download to.
if_exists : str, optional
Desired behavior when the download file already exists. One of:
'error' - Raise an OSError
'skip' - Do nothing, only report a warning.
'overwrite' - Overwrite the file. reporting a warning.
Default: 'error'.
user_name : str, optional
The user name to use for logging into the FTP server. ['anonymous']
password : str, optional
The password to use for logging into the FTP server. ['']
blocksize : int, optional
The blocksize (in bytes) to use for downloading. [4194304]
Returns
-------
None | [
"Downloads",
"a",
"file",
"from",
"an",
"FTP",
"server",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/misc/download.py#L89-L156 |
flo-compbio/genometools | genometools/ensembl/cdna.py | get_cdna_url | def get_cdna_url(species, release=None, ftp=None):
"""Returns the URL for a cDNA file hosted on the Ensembl FTP server.
Parameters
----------
species: str
The scientific name of the species. It should be all lower-case,
and the genus and species parts should be separated by an underscore
(e.g., "homo_sapiens").
release: int or ``None``, optional
The Ensembl release number. If ``None``, the latest release is used.
[None]
ftp: ftplib.FTP or ``None``, optional
The FTP connection. If ``None``, create a new connection. [None]
"""
#species_list, release=None, ftp=None
# type checks
assert isinstance(species, (str, _oldstr))
if release is not None:
assert isinstance(release, int)
if ftp is not None:
assert isinstance(ftp, ftplib.FTP)
# open FTP connection, if necessary
close_connection = False
if ftp is None:
ftp_server = 'ftp.ensembl.org'
ftp_user = 'anonymous'
ftp = ftplib.FTP(ftp_server)
ftp.login(ftp_user)
close_connection = True
# determine latest release, if necessary
if release is None:
release = util.get_latest_release(ftp=ftp)
# check if species exists
fasta_dir = '/pub/release-%d/fasta' % release
ftp.cwd(fasta_dir)
if not species in ftp.nlst():
logger.error('Species "%s" not found on Ensembl FTP server.', species)
fasta_url = 'ftp://%s%s' %(ftp_server, fasta_dir)
raise ValueError('Species "%s" not found. '
'See %s for a list of species available.'
% (species, fasta_url))
# determine URL of the cdna file
# (file names are not consistent across species)
cdna_dir = '/pub/release-%d/fasta/%s/cdna' %(release, species)
ftp.cwd(cdna_dir)
files = ftp.nlst()
cdna_file = [f for f in files if f.endswith('.cdna.all.fa.gz')][0]
cdna_url = 'ftp://%s%s/%s' %(ftp_server, cdna_dir, cdna_file)
# close FTP connection, if we opened it
if close_connection:
ftp.close()
return cdna_url | python | def get_cdna_url(species, release=None, ftp=None):
"""Returns the URL for a cDNA file hosted on the Ensembl FTP server.
Parameters
----------
species: str
The scientific name of the species. It should be all lower-case,
and the genus and species parts should be separated by an underscore
(e.g., "homo_sapiens").
release: int or ``None``, optional
The Ensembl release number. If ``None``, the latest release is used.
[None]
ftp: ftplib.FTP or ``None``, optional
The FTP connection. If ``None``, create a new connection. [None]
"""
#species_list, release=None, ftp=None
# type checks
assert isinstance(species, (str, _oldstr))
if release is not None:
assert isinstance(release, int)
if ftp is not None:
assert isinstance(ftp, ftplib.FTP)
# open FTP connection, if necessary
close_connection = False
if ftp is None:
ftp_server = 'ftp.ensembl.org'
ftp_user = 'anonymous'
ftp = ftplib.FTP(ftp_server)
ftp.login(ftp_user)
close_connection = True
# determine latest release, if necessary
if release is None:
release = util.get_latest_release(ftp=ftp)
# check if species exists
fasta_dir = '/pub/release-%d/fasta' % release
ftp.cwd(fasta_dir)
if not species in ftp.nlst():
logger.error('Species "%s" not found on Ensembl FTP server.', species)
fasta_url = 'ftp://%s%s' %(ftp_server, fasta_dir)
raise ValueError('Species "%s" not found. '
'See %s for a list of species available.'
% (species, fasta_url))
# determine URL of the cdna file
# (file names are not consistent across species)
cdna_dir = '/pub/release-%d/fasta/%s/cdna' %(release, species)
ftp.cwd(cdna_dir)
files = ftp.nlst()
cdna_file = [f for f in files if f.endswith('.cdna.all.fa.gz')][0]
cdna_url = 'ftp://%s%s/%s' %(ftp_server, cdna_dir, cdna_file)
# close FTP connection, if we opened it
if close_connection:
ftp.close()
return cdna_url | [
"def",
"get_cdna_url",
"(",
"species",
",",
"release",
"=",
"None",
",",
"ftp",
"=",
"None",
")",
":",
"#species_list, release=None, ftp=None",
"# type checks",
"assert",
"isinstance",
"(",
"species",
",",
"(",
"str",
",",
"_oldstr",
")",
")",
"if",
"release",... | Returns the URL for a cDNA file hosted on the Ensembl FTP server.
Parameters
----------
species: str
The scientific name of the species. It should be all lower-case,
and the genus and species parts should be separated by an underscore
(e.g., "homo_sapiens").
release: int or ``None``, optional
The Ensembl release number. If ``None``, the latest release is used.
[None]
ftp: ftplib.FTP or ``None``, optional
The FTP connection. If ``None``, create a new connection. [None] | [
"Returns",
"the",
"URL",
"for",
"a",
"cDNA",
"file",
"hosted",
"on",
"the",
"Ensembl",
"FTP",
"server",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ensembl/cdna.py#L33-L92 |
flo-compbio/genometools | genometools/ontology/ontology.py | GeneOntology.write_pickle | def write_pickle(self, path, compress=False):
"""Serialize the current `GOParser` object and store it in a pickle file.
Parameters
----------
path: str
Path of the output file.
compress: bool, optional
Whether to compress the file using gzip.
Returns
-------
None
Notes
-----
Compression with gzip is significantly slower than storing the file
in uncompressed form.
"""
logger.info('Writing pickle to "%s"...', path)
if compress:
with gzip.open(path, 'wb') as ofh:
pickle.dump(self, ofh, pickle.HIGHEST_PROTOCOL)
else:
with open(path, 'wb') as ofh:
pickle.dump(self, ofh, pickle.HIGHEST_PROTOCOL) | python | def write_pickle(self, path, compress=False):
"""Serialize the current `GOParser` object and store it in a pickle file.
Parameters
----------
path: str
Path of the output file.
compress: bool, optional
Whether to compress the file using gzip.
Returns
-------
None
Notes
-----
Compression with gzip is significantly slower than storing the file
in uncompressed form.
"""
logger.info('Writing pickle to "%s"...', path)
if compress:
with gzip.open(path, 'wb') as ofh:
pickle.dump(self, ofh, pickle.HIGHEST_PROTOCOL)
else:
with open(path, 'wb') as ofh:
pickle.dump(self, ofh, pickle.HIGHEST_PROTOCOL) | [
"def",
"write_pickle",
"(",
"self",
",",
"path",
",",
"compress",
"=",
"False",
")",
":",
"logger",
".",
"info",
"(",
"'Writing pickle to \"%s\"...'",
",",
"path",
")",
"if",
"compress",
":",
"with",
"gzip",
".",
"open",
"(",
"path",
",",
"'wb'",
")",
... | Serialize the current `GOParser` object and store it in a pickle file.
Parameters
----------
path: str
Path of the output file.
compress: bool, optional
Whether to compress the file using gzip.
Returns
-------
None
Notes
-----
Compression with gzip is significantly slower than storing the file
in uncompressed form. | [
"Serialize",
"the",
"current",
"GOParser",
"object",
"and",
"store",
"it",
"in",
"a",
"pickle",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/ontology.py#L159-L184 |
flo-compbio/genometools | genometools/ontology/ontology.py | GeneOntology.read_pickle | def read_pickle(fn):
"""Load a GOParser object from a pickle file.
The function automatically detects whether the file is compressed
with gzip.
Parameters
----------
fn: str
Path of the pickle file.
Returns
-------
`GOParser`
The GOParser object stored in the pickle file.
"""
with misc.open_plain_or_gzip(fn, 'rb') as fh:
parser = pickle.load(fh)
return parser | python | def read_pickle(fn):
"""Load a GOParser object from a pickle file.
The function automatically detects whether the file is compressed
with gzip.
Parameters
----------
fn: str
Path of the pickle file.
Returns
-------
`GOParser`
The GOParser object stored in the pickle file.
"""
with misc.open_plain_or_gzip(fn, 'rb') as fh:
parser = pickle.load(fh)
return parser | [
"def",
"read_pickle",
"(",
"fn",
")",
":",
"with",
"misc",
".",
"open_plain_or_gzip",
"(",
"fn",
",",
"'rb'",
")",
"as",
"fh",
":",
"parser",
"=",
"pickle",
".",
"load",
"(",
"fh",
")",
"return",
"parser"
] | Load a GOParser object from a pickle file.
The function automatically detects whether the file is compressed
with gzip.
Parameters
----------
fn: str
Path of the pickle file.
Returns
-------
`GOParser`
The GOParser object stored in the pickle file. | [
"Load",
"a",
"GOParser",
"object",
"from",
"a",
"pickle",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/ontology.py#L187-L205 |
flo-compbio/genometools | genometools/ontology/ontology.py | GeneOntology.get_term_by_name | def get_term_by_name(self, name):
"""Get the GO term with the given GO term name.
If the given name is not associated with any GO term, the function will
search for it among synonyms.
Parameters
----------
name: str
The name of the GO term.
Returns
-------
`GOTerm`
The GO term with the given name.
Raises
------
ValueError
If the given name is found neither among the GO term names, nor
among synonyms.
"""
term = None
try:
term = self.terms[self.name2id[name]]
except KeyError:
try:
term = self.terms[self.syn2id[name]]
except KeyError:
pass
else:
logger.info('GO term name "%s" is a synonym for "%s".',
name, term.name)
if term is None:
raise ValueError('GO term name "%s" not found!' % name)
return term | python | def get_term_by_name(self, name):
"""Get the GO term with the given GO term name.
If the given name is not associated with any GO term, the function will
search for it among synonyms.
Parameters
----------
name: str
The name of the GO term.
Returns
-------
`GOTerm`
The GO term with the given name.
Raises
------
ValueError
If the given name is found neither among the GO term names, nor
among synonyms.
"""
term = None
try:
term = self.terms[self.name2id[name]]
except KeyError:
try:
term = self.terms[self.syn2id[name]]
except KeyError:
pass
else:
logger.info('GO term name "%s" is a synonym for "%s".',
name, term.name)
if term is None:
raise ValueError('GO term name "%s" not found!' % name)
return term | [
"def",
"get_term_by_name",
"(",
"self",
",",
"name",
")",
":",
"term",
"=",
"None",
"try",
":",
"term",
"=",
"self",
".",
"terms",
"[",
"self",
".",
"name2id",
"[",
"name",
"]",
"]",
"except",
"KeyError",
":",
"try",
":",
"term",
"=",
"self",
".",
... | Get the GO term with the given GO term name.
If the given name is not associated with any GO term, the function will
search for it among synonyms.
Parameters
----------
name: str
The name of the GO term.
Returns
-------
`GOTerm`
The GO term with the given name.
Raises
------
ValueError
If the given name is found neither among the GO term names, nor
among synonyms. | [
"Get",
"the",
"GO",
"term",
"with",
"the",
"given",
"GO",
"term",
"name",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/ontology.py#L237-L274 |
flo-compbio/genometools | genometools/ontology/ontology.py | GeneOntology.read_obo | def read_obo(cls, path, flatten=True, part_of_cc_only=False):
""" Parse an OBO file and store GO term information.
Parameters
----------
path: str
Path of the OBO file.
flatten: bool, optional
If set to False, do not generate a list of all ancestors and
descendants for each GO term.
part_of_cc_only: bool, optional
Legacy parameter for backwards compatibility. If set to True,
ignore ``part_of`` relations outside the ``cellular_component``
domain.
Notes
-----
The OBO file must end with a line break.
"""
name2id = {}
alt_id = {}
syn2id = {}
terms = []
with open(path) as fh:
n = 0
while True:
try:
nextline = next(fh)
except StopIteration:
break
if nextline == '[Term]\n':
n += 1
id_ = next(fh)[4:-1]
# acc = get_acc(id_)
name = next(fh)[6:-1]
name2id[name] = id_
domain = next(fh)[11:-1]
def_ = None
is_a = set()
part_of = set()
l = next(fh)
while l != '\n':
if l.startswith('alt_id:'):
alt_id[l[8:-1]] = id_
elif l.startswith('def: '):
idx = l[6:].index('"')
def_ = l[6:(idx+6)]
elif l.startswith('is_a:'):
is_a.add(l[6:16])
elif l.startswith('synonym:'):
idx = l[10:].index('"')
if l[(10+idx+2):].startswith("EXACT"):
s = l[10:(10+idx)]
syn2id[s] = id_
elif l.startswith('relationship: part_of'):
if part_of_cc_only:
if domain == 'cellular_component':
part_of.add(l[22:32])
else:
part_of.add(l[22:32])
l = next(fh)
assert def_ is not None
terms.append(GOTerm(id_, name, domain, def_, is_a, part_of))
logger.info('Parsed %d GO term definitions.', n)
ontology = cls(terms, syn2id, alt_id, name2id)
# store children and parts
logger.info('Adding child and part relationships...')
for term in ontology:
for parent in term.is_a:
ontology[parent].children.add(term.id)
for whole in term.part_of:
ontology[whole].parts.add(term.id)
if flatten:
logger.info('Flattening ancestors...')
ontology._flatten_ancestors()
logger.info('Flattening descendants...')
ontology._flatten_descendants()
ontology._flattened = True
return ontology | python | def read_obo(cls, path, flatten=True, part_of_cc_only=False):
""" Parse an OBO file and store GO term information.
Parameters
----------
path: str
Path of the OBO file.
flatten: bool, optional
If set to False, do not generate a list of all ancestors and
descendants for each GO term.
part_of_cc_only: bool, optional
Legacy parameter for backwards compatibility. If set to True,
ignore ``part_of`` relations outside the ``cellular_component``
domain.
Notes
-----
The OBO file must end with a line break.
"""
name2id = {}
alt_id = {}
syn2id = {}
terms = []
with open(path) as fh:
n = 0
while True:
try:
nextline = next(fh)
except StopIteration:
break
if nextline == '[Term]\n':
n += 1
id_ = next(fh)[4:-1]
# acc = get_acc(id_)
name = next(fh)[6:-1]
name2id[name] = id_
domain = next(fh)[11:-1]
def_ = None
is_a = set()
part_of = set()
l = next(fh)
while l != '\n':
if l.startswith('alt_id:'):
alt_id[l[8:-1]] = id_
elif l.startswith('def: '):
idx = l[6:].index('"')
def_ = l[6:(idx+6)]
elif l.startswith('is_a:'):
is_a.add(l[6:16])
elif l.startswith('synonym:'):
idx = l[10:].index('"')
if l[(10+idx+2):].startswith("EXACT"):
s = l[10:(10+idx)]
syn2id[s] = id_
elif l.startswith('relationship: part_of'):
if part_of_cc_only:
if domain == 'cellular_component':
part_of.add(l[22:32])
else:
part_of.add(l[22:32])
l = next(fh)
assert def_ is not None
terms.append(GOTerm(id_, name, domain, def_, is_a, part_of))
logger.info('Parsed %d GO term definitions.', n)
ontology = cls(terms, syn2id, alt_id, name2id)
# store children and parts
logger.info('Adding child and part relationships...')
for term in ontology:
for parent in term.is_a:
ontology[parent].children.add(term.id)
for whole in term.part_of:
ontology[whole].parts.add(term.id)
if flatten:
logger.info('Flattening ancestors...')
ontology._flatten_ancestors()
logger.info('Flattening descendants...')
ontology._flatten_descendants()
ontology._flattened = True
return ontology | [
"def",
"read_obo",
"(",
"cls",
",",
"path",
",",
"flatten",
"=",
"True",
",",
"part_of_cc_only",
"=",
"False",
")",
":",
"name2id",
"=",
"{",
"}",
"alt_id",
"=",
"{",
"}",
"syn2id",
"=",
"{",
"}",
"terms",
"=",
"[",
"]",
"with",
"open",
"(",
"pat... | Parse an OBO file and store GO term information.
Parameters
----------
path: str
Path of the OBO file.
flatten: bool, optional
If set to False, do not generate a list of all ancestors and
descendants for each GO term.
part_of_cc_only: bool, optional
Legacy parameter for backwards compatibility. If set to True,
ignore ``part_of`` relations outside the ``cellular_component``
domain.
Notes
-----
The OBO file must end with a line break. | [
"Parse",
"an",
"OBO",
"file",
"and",
"store",
"GO",
"term",
"information",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/ontology.py#L277-L362 |
flo-compbio/genometools | genometools/ontology/ontology.py | GeneOntology._flatten_descendants | def _flatten_descendants(self, include_parts=True):
"""Determines and stores all descendants of each GO term.
Parameters
----------
include_parts: bool, optional
Whether to include ``part_of`` relations in determining
descendants.
Returns
-------
None
"""
def get_all_descendants(term):
descendants = set()
for id_ in term.children:
descendants.add(id_)
descendants.update(get_all_descendants(self[id_]))
if include_parts:
for id_ in term.parts:
descendants.add(id_)
descendants.update(get_all_descendants(self[id_]))
return descendants
for term in self:
term.descendants = get_all_descendants(term) | python | def _flatten_descendants(self, include_parts=True):
"""Determines and stores all descendants of each GO term.
Parameters
----------
include_parts: bool, optional
Whether to include ``part_of`` relations in determining
descendants.
Returns
-------
None
"""
def get_all_descendants(term):
descendants = set()
for id_ in term.children:
descendants.add(id_)
descendants.update(get_all_descendants(self[id_]))
if include_parts:
for id_ in term.parts:
descendants.add(id_)
descendants.update(get_all_descendants(self[id_]))
return descendants
for term in self:
term.descendants = get_all_descendants(term) | [
"def",
"_flatten_descendants",
"(",
"self",
",",
"include_parts",
"=",
"True",
")",
":",
"def",
"get_all_descendants",
"(",
"term",
")",
":",
"descendants",
"=",
"set",
"(",
")",
"for",
"id_",
"in",
"term",
".",
"children",
":",
"descendants",
".",
"add",
... | Determines and stores all descendants of each GO term.
Parameters
----------
include_parts: bool, optional
Whether to include ``part_of`` relations in determining
descendants.
Returns
-------
None | [
"Determines",
"and",
"stores",
"all",
"descendants",
"of",
"each",
"GO",
"term",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/ontology.py#L391-L416 |
flo-compbio/genometools | genometools/gcloud/compute/instance_config.py | InstanceConfig.create_instance | def create_instance(self, credentials, name, **kwargs):
"""Create an instance based on the configuration data.
TODO: docstring"""
op_name = create_instance(
credentials, self.project, self.zone, name,
machine_type=self.machine_type,
disk_size_gb=self.disk_size_gb,
**kwargs)
return op_name | python | def create_instance(self, credentials, name, **kwargs):
"""Create an instance based on the configuration data.
TODO: docstring"""
op_name = create_instance(
credentials, self.project, self.zone, name,
machine_type=self.machine_type,
disk_size_gb=self.disk_size_gb,
**kwargs)
return op_name | [
"def",
"create_instance",
"(",
"self",
",",
"credentials",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"op_name",
"=",
"create_instance",
"(",
"credentials",
",",
"self",
".",
"project",
",",
"self",
".",
"zone",
",",
"name",
",",
"machine_type",
"="... | Create an instance based on the configuration data.
TODO: docstring | [
"Create",
"an",
"instance",
"based",
"on",
"the",
"configuration",
"data",
".",
"TODO",
":",
"docstring"
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/compute/instance_config.py#L18-L28 |
flo-compbio/genometools | genometools/gcloud/compute/instance_config.py | InstanceConfig.delete_instance | def delete_instance(self, credentials, name, **kwargs):
"""Delete an instance based on the configuration data.
TODO: docstring"""
op_name = delete_instance(
credentials, self.project, self.zone, name, **kwargs)
return op_name | python | def delete_instance(self, credentials, name, **kwargs):
"""Delete an instance based on the configuration data.
TODO: docstring"""
op_name = delete_instance(
credentials, self.project, self.zone, name, **kwargs)
return op_name | [
"def",
"delete_instance",
"(",
"self",
",",
"credentials",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"op_name",
"=",
"delete_instance",
"(",
"credentials",
",",
"self",
".",
"project",
",",
"self",
".",
"zone",
",",
"name",
",",
"*",
"*",
"kwargs... | Delete an instance based on the configuration data.
TODO: docstring | [
"Delete",
"an",
"instance",
"based",
"on",
"the",
"configuration",
"data",
".",
"TODO",
":",
"docstring"
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/compute/instance_config.py#L30-L37 |
flo-compbio/genometools | genometools/gcloud/compute/instance_config.py | InstanceConfig.wait_for_instance_deletion | def wait_for_instance_deletion(self, credentials, name, **kwargs):
"""Wait for deletion of instance based on the configuration data.
TODO: docstring"""
op_name = wait_for_instance_deletion(
credentials, self.project, self.zone, name, **kwargs)
return op_name | python | def wait_for_instance_deletion(self, credentials, name, **kwargs):
"""Wait for deletion of instance based on the configuration data.
TODO: docstring"""
op_name = wait_for_instance_deletion(
credentials, self.project, self.zone, name, **kwargs)
return op_name | [
"def",
"wait_for_instance_deletion",
"(",
"self",
",",
"credentials",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"op_name",
"=",
"wait_for_instance_deletion",
"(",
"credentials",
",",
"self",
".",
"project",
",",
"self",
".",
"zone",
",",
"name",
",",
... | Wait for deletion of instance based on the configuration data.
TODO: docstring | [
"Wait",
"for",
"deletion",
"of",
"instance",
"based",
"on",
"the",
"configuration",
"data",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/compute/instance_config.py#L39-L46 |
biocommons/bioutils | src/bioutils/cytobands.py | get_cytoband_names | def get_cytoband_names():
"""Returns the names of available cytoband data files
>> get_cytoband_names()
['ucsc-hg38', 'ucsc-hg19']
"""
return [
n.replace(".json.gz", "")
for n in pkg_resources.resource_listdir(__name__, _data_dir)
if n.endswith(".json.gz")
] | python | def get_cytoband_names():
"""Returns the names of available cytoband data files
>> get_cytoband_names()
['ucsc-hg38', 'ucsc-hg19']
"""
return [
n.replace(".json.gz", "")
for n in pkg_resources.resource_listdir(__name__, _data_dir)
if n.endswith(".json.gz")
] | [
"def",
"get_cytoband_names",
"(",
")",
":",
"return",
"[",
"n",
".",
"replace",
"(",
"\".json.gz\"",
",",
"\"\"",
")",
"for",
"n",
"in",
"pkg_resources",
".",
"resource_listdir",
"(",
"__name__",
",",
"_data_dir",
")",
"if",
"n",
".",
"endswith",
"(",
"\... | Returns the names of available cytoband data files
>> get_cytoband_names()
['ucsc-hg38', 'ucsc-hg19'] | [
"Returns",
"the",
"names",
"of",
"available",
"cytoband",
"data",
"files"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/cytobands.py#L13-L23 |
biocommons/bioutils | src/bioutils/cytobands.py | get_cytoband_map | def get_cytoband_map(name):
"""Fetch one cytoband map by name
>>> map = get_cytoband_map("ucsc-hg38")
>>> map["1"]["p32.2"]
[55600000, 58500000, 'gpos50']
"""
fn = pkg_resources.resource_filename(
__name__, _data_path_fmt.format(name=name))
return json.load(gzip.open(fn, mode="rt", encoding="utf-8")) | python | def get_cytoband_map(name):
"""Fetch one cytoband map by name
>>> map = get_cytoband_map("ucsc-hg38")
>>> map["1"]["p32.2"]
[55600000, 58500000, 'gpos50']
"""
fn = pkg_resources.resource_filename(
__name__, _data_path_fmt.format(name=name))
return json.load(gzip.open(fn, mode="rt", encoding="utf-8")) | [
"def",
"get_cytoband_map",
"(",
"name",
")",
":",
"fn",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"__name__",
",",
"_data_path_fmt",
".",
"format",
"(",
"name",
"=",
"name",
")",
")",
"return",
"json",
".",
"load",
"(",
"gzip",
".",
"open",
"(... | Fetch one cytoband map by name
>>> map = get_cytoband_map("ucsc-hg38")
>>> map["1"]["p32.2"]
[55600000, 58500000, 'gpos50'] | [
"Fetch",
"one",
"cytoband",
"map",
"by",
"name"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/cytobands.py#L26-L36 |
biocommons/bioutils | src/bioutils/cytobands.py | get_cytoband_maps | def get_cytoband_maps(names=[]):
"""Load all cytoband maps
>>> maps = get_cytoband_maps()
>>> maps["ucsc-hg38"]["1"]["p32.2"]
[55600000, 58500000, 'gpos50']
>>> maps["ucsc-hg19"]["1"]["p32.2"]
[56100000, 59000000, 'gpos50']
"""
if names == []:
names = get_cytoband_names()
return {name: get_cytoband_map(name) for name in names} | python | def get_cytoband_maps(names=[]):
"""Load all cytoband maps
>>> maps = get_cytoband_maps()
>>> maps["ucsc-hg38"]["1"]["p32.2"]
[55600000, 58500000, 'gpos50']
>>> maps["ucsc-hg19"]["1"]["p32.2"]
[56100000, 59000000, 'gpos50']
"""
if names == []:
names = get_cytoband_names()
return {name: get_cytoband_map(name) for name in names} | [
"def",
"get_cytoband_maps",
"(",
"names",
"=",
"[",
"]",
")",
":",
"if",
"names",
"==",
"[",
"]",
":",
"names",
"=",
"get_cytoband_names",
"(",
")",
"return",
"{",
"name",
":",
"get_cytoband_map",
"(",
"name",
")",
"for",
"name",
"in",
"names",
"}"
] | Load all cytoband maps
>>> maps = get_cytoband_maps()
>>> maps["ucsc-hg38"]["1"]["p32.2"]
[55600000, 58500000, 'gpos50']
>>> maps["ucsc-hg19"]["1"]["p32.2"]
[56100000, 59000000, 'gpos50'] | [
"Load",
"all",
"cytoband",
"maps"
] | train | https://github.com/biocommons/bioutils/blob/88bcbdfa707268fed1110800e91b6d4f8e9475a0/src/bioutils/cytobands.py#L39-L50 |
openfisca/openfisca-web-api | openfisca_web_api/environment.py | get_relative_file_path | def get_relative_file_path(absolute_file_path):
'''
Example:
absolute_file_path = "/home/xxx/Dev/openfisca/openfisca-france/openfisca_france/param/param.xml"
result = "openfisca_france/param/param.xml"
'''
global country_package_dir_path
assert country_package_dir_path is not None
relative_file_path = absolute_file_path[len(country_package_dir_path):]
if relative_file_path.startswith('/'):
relative_file_path = relative_file_path[1:]
return relative_file_path | python | def get_relative_file_path(absolute_file_path):
'''
Example:
absolute_file_path = "/home/xxx/Dev/openfisca/openfisca-france/openfisca_france/param/param.xml"
result = "openfisca_france/param/param.xml"
'''
global country_package_dir_path
assert country_package_dir_path is not None
relative_file_path = absolute_file_path[len(country_package_dir_path):]
if relative_file_path.startswith('/'):
relative_file_path = relative_file_path[1:]
return relative_file_path | [
"def",
"get_relative_file_path",
"(",
"absolute_file_path",
")",
":",
"global",
"country_package_dir_path",
"assert",
"country_package_dir_path",
"is",
"not",
"None",
"relative_file_path",
"=",
"absolute_file_path",
"[",
"len",
"(",
"country_package_dir_path",
")",
":",
"... | Example:
absolute_file_path = "/home/xxx/Dev/openfisca/openfisca-france/openfisca_france/param/param.xml"
result = "openfisca_france/param/param.xml" | [
"Example",
":",
"absolute_file_path",
"=",
"/",
"home",
"/",
"xxx",
"/",
"Dev",
"/",
"openfisca",
"/",
"openfisca",
"-",
"france",
"/",
"openfisca_france",
"/",
"param",
"/",
"param",
".",
"xml",
"result",
"=",
"openfisca_france",
"/",
"param",
"/",
"param... | train | https://github.com/openfisca/openfisca-web-api/blob/d1cd3bfacac338e80bb0df7e0465b65649dd893b/openfisca_web_api/environment.py#L36-L47 |
openfisca/openfisca-web-api | openfisca_web_api/environment.py | load_environment | def load_environment(global_conf, app_conf):
"""Configure the application environment."""
conf.update(strings.deep_decode(global_conf))
conf.update(strings.deep_decode(app_conf))
conf.update(conv.check(conv.struct(
{
'app_conf': conv.set_value(app_conf),
'app_dir': conv.set_value(app_dir),
'country_package': conv.pipe(
conv.make_input_to_slug(separator = u'_'),
conv.not_none,
),
'debug': conv.pipe(conv.guess_bool, conv.default(False)),
'global_conf': conv.set_value(global_conf),
'i18n_dir': conv.default(os.path.join(app_dir, 'i18n')),
'load_alert': conv.pipe(conv.guess_bool, conv.default(False)),
'log_level': conv.pipe(
conv.default('WARNING'),
conv.function(lambda log_level: getattr(logging, log_level.upper())),
),
'package_name': conv.default('openfisca-web-api'),
'realm': conv.default(u'OpenFisca Web API'),
'reforms': conv.ini_str_to_list, # Another validation is done below.
'extensions': conv.ini_str_to_list,
},
default = 'drop',
))(conf))
# Configure logging.
logging.basicConfig(level = conf['log_level'], stream = sys.stderr)
errorware = conf.setdefault('errorware', {})
errorware['debug'] = conf['debug']
if not errorware['debug']:
errorware['error_email'] = conf['email_to']
errorware['error_log'] = conf.get('error_log', None)
errorware['error_message'] = conf.get('error_message', 'An internal server error occurred')
errorware['error_subject_prefix'] = conf.get('error_subject_prefix', 'OpenFisca Web API Error: ')
errorware['from_address'] = conf['from_address']
errorware['smtp_server'] = conf.get('smtp_server', 'localhost')
errorware['show_exceptions_in_wsgi_errors'] = conf.get('show_exceptions_in_wsgi_errors', True)
# Initialize tax-benefit system.
country_package = importlib.import_module(conf['country_package'])
tax_benefit_system = country_package.CountryTaxBenefitSystem()
extensions = conf['extensions']
if extensions is not None:
for extension in extensions:
tax_benefit_system.load_extension(extension)
class Scenario(tax_benefit_system.Scenario):
instance_and_error_couple_cache = {} if conf['debug'] else weakref.WeakValueDictionary() # class attribute
@classmethod
def make_json_to_cached_or_new_instance(cls, ctx, repair, tax_benefit_system):
def json_to_cached_or_new_instance(value, state = None):
key = (unicode(ctx.lang), unicode(value), repair, tax_benefit_system)
instance_and_error_couple = cls.instance_and_error_couple_cache.get(key)
if instance_and_error_couple is None:
instance_and_error_couple = cls.make_json_to_instance(repair, tax_benefit_system)(
value, state = state or conv.default_state)
# Note: Call to ValueAndError() is needed below, otherwise it raises TypeError: cannot create
# weak reference to 'tuple' object.
cls.instance_and_error_couple_cache[key] = ValueAndError(instance_and_error_couple)
return instance_and_error_couple
return json_to_cached_or_new_instance
tax_benefit_system.Scenario = Scenario
model.tax_benefit_system = tax_benefit_system
log.debug(u'Pre-fill tax and benefit system cache.')
tax_benefit_system.prefill_cache()
log.debug(u'Initialize reforms.')
reforms = conv.check(
conv.uniform_sequence(
conv.module_and_function_str_to_function,
)
)(conf['reforms'])
model.reforms = {}
model.reformed_tbs = {}
if reforms is not None:
for reform in reforms:
reformed_tbs = reform(tax_benefit_system)
key = reformed_tbs.key
full_key = reformed_tbs.full_key
model.reforms[key] = reform
model.reformed_tbs[full_key] = reformed_tbs
log.debug(u'Cache default decomposition.')
if tax_benefit_system.decomposition_file_path is not None:
# Ignore the returned value, because we just want to pre-compute the cache.
model.get_cached_or_new_decomposition_json(tax_benefit_system)
log.debug(u'Initialize lib2to3-based input variables extractor.')
global country_package_dir_path
# - Do not use pkg_resources.get_distribution(conf["country_package"]).location
# because it returns a wrong path in virtualenvs (<venv>/lib versus <venv>/local/lib)
# - Use os.path.abspath because when the web API is runned in development with "paster serve",
# __path__[0] == 'openfisca_france' for example. Then, get_relative_file_path won't be able
# to find the relative path of an already relative path.
country_package_dir_path = os.path.abspath(country_package.__path__[0])
global api_package_version
api_package_version = pkg_resources.get_distribution('openfisca_web_api').version
global country_package_version
country_package_version = pkg_resources.get_distribution(conf["country_package"]).version
log.debug(u'Cache legislation parmeters')
legislation = tax_benefit_system.parameters
parameters = []
walk_legislation(
legislation,
descriptions = [],
parameters = parameters,
path_fragments = [],
)
model.parameters_cache = parameters
if not conf['debug']:
# Do this after tax_benefit_system.get_legislation().
log.debug(u'Compute and cache compact legislation for each first day of month since at least 2 legal years.')
today = periods.instant(datetime.date.today())
first_day_of_year = today.offset('first-of', 'year')
instant = first_day_of_year.offset(-2, 'year')
two_years_later = first_day_of_year.offset(2, 'year')
while instant < two_years_later:
tax_benefit_system.get_parameters_at_instant(instant)
instant = instant.offset(1, 'month')
# Initialize multiprocessing and load_alert
if conf['load_alert']:
global cpu_count
cpu_count = multiprocessing.cpu_count()
if conf.get('tracker_url') and conf.get('tracker_idsite'):
wsgihelpers.init_tracker(conf['tracker_url'], conf['tracker_idsite']) | python | def load_environment(global_conf, app_conf):
"""Configure the application environment."""
conf.update(strings.deep_decode(global_conf))
conf.update(strings.deep_decode(app_conf))
conf.update(conv.check(conv.struct(
{
'app_conf': conv.set_value(app_conf),
'app_dir': conv.set_value(app_dir),
'country_package': conv.pipe(
conv.make_input_to_slug(separator = u'_'),
conv.not_none,
),
'debug': conv.pipe(conv.guess_bool, conv.default(False)),
'global_conf': conv.set_value(global_conf),
'i18n_dir': conv.default(os.path.join(app_dir, 'i18n')),
'load_alert': conv.pipe(conv.guess_bool, conv.default(False)),
'log_level': conv.pipe(
conv.default('WARNING'),
conv.function(lambda log_level: getattr(logging, log_level.upper())),
),
'package_name': conv.default('openfisca-web-api'),
'realm': conv.default(u'OpenFisca Web API'),
'reforms': conv.ini_str_to_list, # Another validation is done below.
'extensions': conv.ini_str_to_list,
},
default = 'drop',
))(conf))
# Configure logging.
logging.basicConfig(level = conf['log_level'], stream = sys.stderr)
errorware = conf.setdefault('errorware', {})
errorware['debug'] = conf['debug']
if not errorware['debug']:
errorware['error_email'] = conf['email_to']
errorware['error_log'] = conf.get('error_log', None)
errorware['error_message'] = conf.get('error_message', 'An internal server error occurred')
errorware['error_subject_prefix'] = conf.get('error_subject_prefix', 'OpenFisca Web API Error: ')
errorware['from_address'] = conf['from_address']
errorware['smtp_server'] = conf.get('smtp_server', 'localhost')
errorware['show_exceptions_in_wsgi_errors'] = conf.get('show_exceptions_in_wsgi_errors', True)
# Initialize tax-benefit system.
country_package = importlib.import_module(conf['country_package'])
tax_benefit_system = country_package.CountryTaxBenefitSystem()
extensions = conf['extensions']
if extensions is not None:
for extension in extensions:
tax_benefit_system.load_extension(extension)
class Scenario(tax_benefit_system.Scenario):
instance_and_error_couple_cache = {} if conf['debug'] else weakref.WeakValueDictionary() # class attribute
@classmethod
def make_json_to_cached_or_new_instance(cls, ctx, repair, tax_benefit_system):
def json_to_cached_or_new_instance(value, state = None):
key = (unicode(ctx.lang), unicode(value), repair, tax_benefit_system)
instance_and_error_couple = cls.instance_and_error_couple_cache.get(key)
if instance_and_error_couple is None:
instance_and_error_couple = cls.make_json_to_instance(repair, tax_benefit_system)(
value, state = state or conv.default_state)
# Note: Call to ValueAndError() is needed below, otherwise it raises TypeError: cannot create
# weak reference to 'tuple' object.
cls.instance_and_error_couple_cache[key] = ValueAndError(instance_and_error_couple)
return instance_and_error_couple
return json_to_cached_or_new_instance
tax_benefit_system.Scenario = Scenario
model.tax_benefit_system = tax_benefit_system
log.debug(u'Pre-fill tax and benefit system cache.')
tax_benefit_system.prefill_cache()
log.debug(u'Initialize reforms.')
reforms = conv.check(
conv.uniform_sequence(
conv.module_and_function_str_to_function,
)
)(conf['reforms'])
model.reforms = {}
model.reformed_tbs = {}
if reforms is not None:
for reform in reforms:
reformed_tbs = reform(tax_benefit_system)
key = reformed_tbs.key
full_key = reformed_tbs.full_key
model.reforms[key] = reform
model.reformed_tbs[full_key] = reformed_tbs
log.debug(u'Cache default decomposition.')
if tax_benefit_system.decomposition_file_path is not None:
# Ignore the returned value, because we just want to pre-compute the cache.
model.get_cached_or_new_decomposition_json(tax_benefit_system)
log.debug(u'Initialize lib2to3-based input variables extractor.')
global country_package_dir_path
# - Do not use pkg_resources.get_distribution(conf["country_package"]).location
# because it returns a wrong path in virtualenvs (<venv>/lib versus <venv>/local/lib)
# - Use os.path.abspath because when the web API is runned in development with "paster serve",
# __path__[0] == 'openfisca_france' for example. Then, get_relative_file_path won't be able
# to find the relative path of an already relative path.
country_package_dir_path = os.path.abspath(country_package.__path__[0])
global api_package_version
api_package_version = pkg_resources.get_distribution('openfisca_web_api').version
global country_package_version
country_package_version = pkg_resources.get_distribution(conf["country_package"]).version
log.debug(u'Cache legislation parmeters')
legislation = tax_benefit_system.parameters
parameters = []
walk_legislation(
legislation,
descriptions = [],
parameters = parameters,
path_fragments = [],
)
model.parameters_cache = parameters
if not conf['debug']:
# Do this after tax_benefit_system.get_legislation().
log.debug(u'Compute and cache compact legislation for each first day of month since at least 2 legal years.')
today = periods.instant(datetime.date.today())
first_day_of_year = today.offset('first-of', 'year')
instant = first_day_of_year.offset(-2, 'year')
two_years_later = first_day_of_year.offset(2, 'year')
while instant < two_years_later:
tax_benefit_system.get_parameters_at_instant(instant)
instant = instant.offset(1, 'month')
# Initialize multiprocessing and load_alert
if conf['load_alert']:
global cpu_count
cpu_count = multiprocessing.cpu_count()
if conf.get('tracker_url') and conf.get('tracker_idsite'):
wsgihelpers.init_tracker(conf['tracker_url'], conf['tracker_idsite']) | [
"def",
"load_environment",
"(",
"global_conf",
",",
"app_conf",
")",
":",
"conf",
".",
"update",
"(",
"strings",
".",
"deep_decode",
"(",
"global_conf",
")",
")",
"conf",
".",
"update",
"(",
"strings",
".",
"deep_decode",
"(",
"app_conf",
")",
")",
"conf",... | Configure the application environment. | [
"Configure",
"the",
"application",
"environment",
"."
] | train | https://github.com/openfisca/openfisca-web-api/blob/d1cd3bfacac338e80bb0df7e0465b65649dd893b/openfisca_web_api/environment.py#L50-L191 |
flo-compbio/genometools | genometools/expression/profile.py | ExpProfile.filter_genes | def filter_genes(self, gene_names : Iterable[str]):
"""Filter the expression matrix against a set of genes.
Parameters
----------
gene_names: list of str
The genome to filter the genes against.
Returns
-------
ExpMatrix
The filtered expression matrix.
"""
filt = self.loc[self.index & gene_names]
return filt | python | def filter_genes(self, gene_names : Iterable[str]):
"""Filter the expression matrix against a set of genes.
Parameters
----------
gene_names: list of str
The genome to filter the genes against.
Returns
-------
ExpMatrix
The filtered expression matrix.
"""
filt = self.loc[self.index & gene_names]
return filt | [
"def",
"filter_genes",
"(",
"self",
",",
"gene_names",
":",
"Iterable",
"[",
"str",
"]",
")",
":",
"filt",
"=",
"self",
".",
"loc",
"[",
"self",
".",
"index",
"&",
"gene_names",
"]",
"return",
"filt"
] | Filter the expression matrix against a set of genes.
Parameters
----------
gene_names: list of str
The genome to filter the genes against.
Returns
-------
ExpMatrix
The filtered expression matrix. | [
"Filter",
"the",
"expression",
"matrix",
"against",
"a",
"set",
"of",
"genes",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/profile.py#L205-L220 |
flo-compbio/genometools | genometools/expression/profile.py | ExpProfile.read_tsv | def read_tsv(cls, filepath_or_buffer: str, gene_table: ExpGeneTable = None,
encoding='UTF-8'):
"""Read expression profile from a tab-delimited text file.
Parameters
----------
path: str
The path of the text file.
gene_table: `ExpGeneTable` object, optional
The set of valid genes. If given, the genes in the text file will
be filtered against this set of genes. (None)
encoding: str, optional
The file encoding. ("UTF-8")
Returns
-------
`ExpProfile`
The expression profile.
"""
# "squeeze = True" ensures that a pd.read_tsv returns a series
# as long as there is only one column
e = cls(pd.read_csv(filepath_or_buffer, sep='\t',
index_col=0, header=0,
encoding=encoding, squeeze=True))
if gene_table is not None:
# filter genes
e = e.filter_genes(gene_table.gene_names)
return e | python | def read_tsv(cls, filepath_or_buffer: str, gene_table: ExpGeneTable = None,
encoding='UTF-8'):
"""Read expression profile from a tab-delimited text file.
Parameters
----------
path: str
The path of the text file.
gene_table: `ExpGeneTable` object, optional
The set of valid genes. If given, the genes in the text file will
be filtered against this set of genes. (None)
encoding: str, optional
The file encoding. ("UTF-8")
Returns
-------
`ExpProfile`
The expression profile.
"""
# "squeeze = True" ensures that a pd.read_tsv returns a series
# as long as there is only one column
e = cls(pd.read_csv(filepath_or_buffer, sep='\t',
index_col=0, header=0,
encoding=encoding, squeeze=True))
if gene_table is not None:
# filter genes
e = e.filter_genes(gene_table.gene_names)
return e | [
"def",
"read_tsv",
"(",
"cls",
",",
"filepath_or_buffer",
":",
"str",
",",
"gene_table",
":",
"ExpGeneTable",
"=",
"None",
",",
"encoding",
"=",
"'UTF-8'",
")",
":",
"# \"squeeze = True\" ensures that a pd.read_tsv returns a series",
"# as long as there is only one column",... | Read expression profile from a tab-delimited text file.
Parameters
----------
path: str
The path of the text file.
gene_table: `ExpGeneTable` object, optional
The set of valid genes. If given, the genes in the text file will
be filtered against this set of genes. (None)
encoding: str, optional
The file encoding. ("UTF-8")
Returns
-------
`ExpProfile`
The expression profile. | [
"Read",
"expression",
"profile",
"from",
"a",
"tab",
"-",
"delimited",
"text",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/profile.py#L224-L253 |
flo-compbio/genometools | genometools/expression/profile.py | ExpProfile.write_tsv | def write_tsv(self, path, encoding='UTF-8'):
"""Write expression matrix to a tab-delimited text file.
Parameters
----------
path: str
The path of the output file.
encoding: str, optional
The file encoding. ("UTF-8")
Returns
-------
None
"""
assert isinstance(path, (str, _oldstr))
assert isinstance(encoding, (str, _oldstr))
sep = '\t'
if six.PY2:
sep = sep.encode('UTF-8')
self.to_csv(
path, sep=sep, float_format='%.5f', mode='w',
encoding=encoding, header=True
)
logger.info('Wrote expression profile "%s" with %d genes to "%s".',
self.name, self.p, path) | python | def write_tsv(self, path, encoding='UTF-8'):
"""Write expression matrix to a tab-delimited text file.
Parameters
----------
path: str
The path of the output file.
encoding: str, optional
The file encoding. ("UTF-8")
Returns
-------
None
"""
assert isinstance(path, (str, _oldstr))
assert isinstance(encoding, (str, _oldstr))
sep = '\t'
if six.PY2:
sep = sep.encode('UTF-8')
self.to_csv(
path, sep=sep, float_format='%.5f', mode='w',
encoding=encoding, header=True
)
logger.info('Wrote expression profile "%s" with %d genes to "%s".',
self.name, self.p, path) | [
"def",
"write_tsv",
"(",
"self",
",",
"path",
",",
"encoding",
"=",
"'UTF-8'",
")",
":",
"assert",
"isinstance",
"(",
"path",
",",
"(",
"str",
",",
"_oldstr",
")",
")",
"assert",
"isinstance",
"(",
"encoding",
",",
"(",
"str",
",",
"_oldstr",
")",
")... | Write expression matrix to a tab-delimited text file.
Parameters
----------
path: str
The path of the output file.
encoding: str, optional
The file encoding. ("UTF-8")
Returns
-------
None | [
"Write",
"expression",
"matrix",
"to",
"a",
"tab",
"-",
"delimited",
"text",
"file",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/profile.py#L256-L283 |
danifus/django-override-storage | override_storage/utils.py | override_storage.setup_storage | def setup_storage(self):
"""Save existing FileField storages and patch them with test instance(s).
If storage_per_field is False (default) this function will create a
single instance here and assign it to self.storage to be used for all
filefields.
If storage_per_field is True, an independent storage instance will be
used for each FileField .
"""
if self.storage_callable is not None and not self.storage_per_field:
self.storage = self.get_storage_from_callable(field=None)
super(override_storage, self).setup_storage() | python | def setup_storage(self):
"""Save existing FileField storages and patch them with test instance(s).
If storage_per_field is False (default) this function will create a
single instance here and assign it to self.storage to be used for all
filefields.
If storage_per_field is True, an independent storage instance will be
used for each FileField .
"""
if self.storage_callable is not None and not self.storage_per_field:
self.storage = self.get_storage_from_callable(field=None)
super(override_storage, self).setup_storage() | [
"def",
"setup_storage",
"(",
"self",
")",
":",
"if",
"self",
".",
"storage_callable",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"storage_per_field",
":",
"self",
".",
"storage",
"=",
"self",
".",
"get_storage_from_callable",
"(",
"field",
"=",
"None",
... | Save existing FileField storages and patch them with test instance(s).
If storage_per_field is False (default) this function will create a
single instance here and assign it to self.storage to be used for all
filefields.
If storage_per_field is True, an independent storage instance will be
used for each FileField . | [
"Save",
"existing",
"FileField",
"storages",
"and",
"patch",
"them",
"with",
"test",
"instance",
"(",
"s",
")",
"."
] | train | https://github.com/danifus/django-override-storage/blob/a1e6c19ca102147762d09aa1f633734224f84926/override_storage/utils.py#L320-L331 |
flo-compbio/genometools | genometools/gcloud/tasks/fastq.py | run_fastqc | def run_fastqc(credentials, instance_config, instance_name,
script_dir, input_file, output_dir, self_destruct=True,
**kwargs):
"""Run FASTQC.
TODO: docstring"""
template = _TEMPLATE_ENV.get_template('fastqc.sh')
startup_script = template.render(
script_dir=script_dir,
input_file=input_file,
output_dir=output_dir,
self_destruct=self_destruct)
if len(startup_script) > 32768:
raise ValueError('Startup script larger than 32,768 bytes!')
#print(startup_script)
op_name = instance_config.create_instance(
credentials, instance_name, startup_script=startup_script, **kwargs)
return op_name | python | def run_fastqc(credentials, instance_config, instance_name,
script_dir, input_file, output_dir, self_destruct=True,
**kwargs):
"""Run FASTQC.
TODO: docstring"""
template = _TEMPLATE_ENV.get_template('fastqc.sh')
startup_script = template.render(
script_dir=script_dir,
input_file=input_file,
output_dir=output_dir,
self_destruct=self_destruct)
if len(startup_script) > 32768:
raise ValueError('Startup script larger than 32,768 bytes!')
#print(startup_script)
op_name = instance_config.create_instance(
credentials, instance_name, startup_script=startup_script, **kwargs)
return op_name | [
"def",
"run_fastqc",
"(",
"credentials",
",",
"instance_config",
",",
"instance_name",
",",
"script_dir",
",",
"input_file",
",",
"output_dir",
",",
"self_destruct",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"template",
"=",
"_TEMPLATE_ENV",
".",
"get_te... | Run FASTQC.
TODO: docstring | [
"Run",
"FASTQC",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/tasks/fastq.py#L15-L36 |
flo-compbio/genometools | genometools/gcloud/tasks/fastq.py | sra_download_paired_end | def sra_download_paired_end(credentials, instance_config, instance_name,
script_dir, sra_run_acc, output_dir, **kwargs):
"""Download paired-end reads from SRA and convert to gzip'ed FASTQ files.
TODO: docstring"""
template = _TEMPLATE_ENV.get_template('sra_download_paired-end.sh')
startup_script = template.render(
script_dir=script_dir,
sra_run_acc=sra_run_acc,
output_dir=output_dir)
if len(startup_script) > 32768:
raise ValueError('Startup script larger than 32,768 bytes!')
#print(startup_script)
instance_config.create_instance(
credentials, instance_name, startup_script=startup_script, **kwargs) | python | def sra_download_paired_end(credentials, instance_config, instance_name,
script_dir, sra_run_acc, output_dir, **kwargs):
"""Download paired-end reads from SRA and convert to gzip'ed FASTQ files.
TODO: docstring"""
template = _TEMPLATE_ENV.get_template('sra_download_paired-end.sh')
startup_script = template.render(
script_dir=script_dir,
sra_run_acc=sra_run_acc,
output_dir=output_dir)
if len(startup_script) > 32768:
raise ValueError('Startup script larger than 32,768 bytes!')
#print(startup_script)
instance_config.create_instance(
credentials, instance_name, startup_script=startup_script, **kwargs) | [
"def",
"sra_download_paired_end",
"(",
"credentials",
",",
"instance_config",
",",
"instance_name",
",",
"script_dir",
",",
"sra_run_acc",
",",
"output_dir",
",",
"*",
"*",
"kwargs",
")",
":",
"template",
"=",
"_TEMPLATE_ENV",
".",
"get_template",
"(",
"'sra_downl... | Download paired-end reads from SRA and convert to gzip'ed FASTQ files.
TODO: docstring | [
"Download",
"paired",
"-",
"end",
"reads",
"from",
"SRA",
"and",
"convert",
"to",
"gzip",
"ed",
"FASTQ",
"files",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/tasks/fastq.py#L39-L57 |
flo-compbio/genometools | genometools/gcloud/tasks/fastq.py | trim_fastq | def trim_fastq(credentials, instance_config, instance_name,
script_dir, input_file, output_file,
trim_crop, trim_headcrop=0, self_destruct=True,
**kwargs):
"""Trims a FASTQ file.
TODO: docstring"""
template = _TEMPLATE_ENV.get_template('trim_fastq.sh')
startup_script = template.render(
script_dir=script_dir,
input_file=input_file,
output_file=output_file,
trim_crop=trim_crop,
trim_headcrop=trim_headcrop,
self_destruct=self_destruct)
if len(startup_script) > 32768:
raise ValueError('Startup script larger than 32,768 bytes!')
#print(startup_script)
instance_config.create_instance(
credentials, instance_name, startup_script=startup_script, **kwargs) | python | def trim_fastq(credentials, instance_config, instance_name,
script_dir, input_file, output_file,
trim_crop, trim_headcrop=0, self_destruct=True,
**kwargs):
"""Trims a FASTQ file.
TODO: docstring"""
template = _TEMPLATE_ENV.get_template('trim_fastq.sh')
startup_script = template.render(
script_dir=script_dir,
input_file=input_file,
output_file=output_file,
trim_crop=trim_crop,
trim_headcrop=trim_headcrop,
self_destruct=self_destruct)
if len(startup_script) > 32768:
raise ValueError('Startup script larger than 32,768 bytes!')
#print(startup_script)
instance_config.create_instance(
credentials, instance_name, startup_script=startup_script, **kwargs) | [
"def",
"trim_fastq",
"(",
"credentials",
",",
"instance_config",
",",
"instance_name",
",",
"script_dir",
",",
"input_file",
",",
"output_file",
",",
"trim_crop",
",",
"trim_headcrop",
"=",
"0",
",",
"self_destruct",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
... | Trims a FASTQ file.
TODO: docstring | [
"Trims",
"a",
"FASTQ",
"file",
".",
"TODO",
":",
"docstring"
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gcloud/tasks/fastq.py#L60-L82 |
udragon/pybrctl | pybrctl/pybrctl.py | _runshell | def _runshell(cmd, exception):
""" Run a shell command. if fails, raise a proper exception. """
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if p.wait() != 0:
raise BridgeException(exception)
return p | python | def _runshell(cmd, exception):
""" Run a shell command. if fails, raise a proper exception. """
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if p.wait() != 0:
raise BridgeException(exception)
return p | [
"def",
"_runshell",
"(",
"cmd",
",",
"exception",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"if",
"p",
".",
"wait",
"(",
")",
"!=",... | Run a shell command. if fails, raise a proper exception. | [
"Run",
"a",
"shell",
"command",
".",
"if",
"fails",
"raise",
"a",
"proper",
"exception",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L145-L150 |
udragon/pybrctl | pybrctl/pybrctl.py | Bridge.addif | def addif(self, iname):
""" Add an interface to the bridge """
_runshell([brctlexe, 'addif', self.name, iname],
"Could not add interface %s to %s." % (iname, self.name)) | python | def addif(self, iname):
""" Add an interface to the bridge """
_runshell([brctlexe, 'addif', self.name, iname],
"Could not add interface %s to %s." % (iname, self.name)) | [
"def",
"addif",
"(",
"self",
",",
"iname",
")",
":",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'addif'",
",",
"self",
".",
"name",
",",
"iname",
"]",
",",
"\"Could not add interface %s to %s.\"",
"%",
"(",
"iname",
",",
"self",
".",
"name",
")",
")"
] | Add an interface to the bridge | [
"Add",
"an",
"interface",
"to",
"the",
"bridge"
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L24-L27 |
udragon/pybrctl | pybrctl/pybrctl.py | Bridge.delif | def delif(self, iname):
""" Delete an interface from the bridge. """
_runshell([brctlexe, 'delif', self.name, iname],
"Could not delete interface %s from %s." % (iname, self.name)) | python | def delif(self, iname):
""" Delete an interface from the bridge. """
_runshell([brctlexe, 'delif', self.name, iname],
"Could not delete interface %s from %s." % (iname, self.name)) | [
"def",
"delif",
"(",
"self",
",",
"iname",
")",
":",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'delif'",
",",
"self",
".",
"name",
",",
"iname",
"]",
",",
"\"Could not delete interface %s from %s.\"",
"%",
"(",
"iname",
",",
"self",
".",
"name",
")",
")"
... | Delete an interface from the bridge. | [
"Delete",
"an",
"interface",
"from",
"the",
"bridge",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L29-L32 |
udragon/pybrctl | pybrctl/pybrctl.py | Bridge.hairpin | def hairpin(self, port, val=True):
""" Turn harpin on/off on a port. """
if val: state = 'on'
else: state = 'off'
_runshell([brctlexe, 'hairpin', self.name, port, state],
"Could not set hairpin in port %s in %s." % (port, self.name)) | python | def hairpin(self, port, val=True):
""" Turn harpin on/off on a port. """
if val: state = 'on'
else: state = 'off'
_runshell([brctlexe, 'hairpin', self.name, port, state],
"Could not set hairpin in port %s in %s." % (port, self.name)) | [
"def",
"hairpin",
"(",
"self",
",",
"port",
",",
"val",
"=",
"True",
")",
":",
"if",
"val",
":",
"state",
"=",
"'on'",
"else",
":",
"state",
"=",
"'off'",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'hairpin'",
",",
"self",
".",
"name",
",",
"port",
... | Turn harpin on/off on a port. | [
"Turn",
"harpin",
"on",
"/",
"off",
"on",
"a",
"port",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L34-L39 |
udragon/pybrctl | pybrctl/pybrctl.py | Bridge.stp | def stp(self, val=True):
""" Turn STP protocol on/off. """
if val: state = 'on'
else: state = 'off'
_runshell([brctlexe, 'stp', self.name, state],
"Could not set stp on %s." % self.name) | python | def stp(self, val=True):
""" Turn STP protocol on/off. """
if val: state = 'on'
else: state = 'off'
_runshell([brctlexe, 'stp', self.name, state],
"Could not set stp on %s." % self.name) | [
"def",
"stp",
"(",
"self",
",",
"val",
"=",
"True",
")",
":",
"if",
"val",
":",
"state",
"=",
"'on'",
"else",
":",
"state",
"=",
"'off'",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'stp'",
",",
"self",
".",
"name",
",",
"state",
"]",
",",
"\"Could ... | Turn STP protocol on/off. | [
"Turn",
"STP",
"protocol",
"on",
"/",
"off",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L41-L46 |
udragon/pybrctl | pybrctl/pybrctl.py | Bridge.setageing | def setageing(self, time):
""" Set bridge ageing time. """
_runshell([brctlexe, 'setageing', self.name, str(time)],
"Could not set ageing time in %s." % self.name) | python | def setageing(self, time):
""" Set bridge ageing time. """
_runshell([brctlexe, 'setageing', self.name, str(time)],
"Could not set ageing time in %s." % self.name) | [
"def",
"setageing",
"(",
"self",
",",
"time",
")",
":",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'setageing'",
",",
"self",
".",
"name",
",",
"str",
"(",
"time",
")",
"]",
",",
"\"Could not set ageing time in %s.\"",
"%",
"self",
".",
"name",
")"
] | Set bridge ageing time. | [
"Set",
"bridge",
"ageing",
"time",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L48-L51 |
udragon/pybrctl | pybrctl/pybrctl.py | Bridge.setbridgeprio | def setbridgeprio(self, prio):
""" Set bridge priority value. """
_runshell([brctlexe, 'setbridgeprio', self.name, str(prio)],
"Could not set bridge priority in %s." % self.name) | python | def setbridgeprio(self, prio):
""" Set bridge priority value. """
_runshell([brctlexe, 'setbridgeprio', self.name, str(prio)],
"Could not set bridge priority in %s." % self.name) | [
"def",
"setbridgeprio",
"(",
"self",
",",
"prio",
")",
":",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'setbridgeprio'",
",",
"self",
".",
"name",
",",
"str",
"(",
"prio",
")",
"]",
",",
"\"Could not set bridge priority in %s.\"",
"%",
"self",
".",
"name",
"... | Set bridge priority value. | [
"Set",
"bridge",
"priority",
"value",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L53-L56 |
udragon/pybrctl | pybrctl/pybrctl.py | Bridge.setfd | def setfd(self, time):
""" Set bridge forward delay time value. """
_runshell([brctlexe, 'setfd', self.name, str(time)],
"Could not set forward delay in %s." % self.name) | python | def setfd(self, time):
""" Set bridge forward delay time value. """
_runshell([brctlexe, 'setfd', self.name, str(time)],
"Could not set forward delay in %s." % self.name) | [
"def",
"setfd",
"(",
"self",
",",
"time",
")",
":",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'setfd'",
",",
"self",
".",
"name",
",",
"str",
"(",
"time",
")",
"]",
",",
"\"Could not set forward delay in %s.\"",
"%",
"self",
".",
"name",
")"
] | Set bridge forward delay time value. | [
"Set",
"bridge",
"forward",
"delay",
"time",
"value",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L58-L61 |
udragon/pybrctl | pybrctl/pybrctl.py | Bridge.sethello | def sethello(self, time):
""" Set bridge hello time value. """
_runshell([brctlexe, 'sethello', self.name, str(time)],
"Could not set hello time in %s." % self.name) | python | def sethello(self, time):
""" Set bridge hello time value. """
_runshell([brctlexe, 'sethello', self.name, str(time)],
"Could not set hello time in %s." % self.name) | [
"def",
"sethello",
"(",
"self",
",",
"time",
")",
":",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'sethello'",
",",
"self",
".",
"name",
",",
"str",
"(",
"time",
")",
"]",
",",
"\"Could not set hello time in %s.\"",
"%",
"self",
".",
"name",
")"
] | Set bridge hello time value. | [
"Set",
"bridge",
"hello",
"time",
"value",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L63-L66 |
udragon/pybrctl | pybrctl/pybrctl.py | Bridge.setmaxage | def setmaxage(self, time):
""" Set bridge max message age time. """
_runshell([brctlexe, 'setmaxage', self.name, str(time)],
"Could not set max message age in %s." % self.name) | python | def setmaxage(self, time):
""" Set bridge max message age time. """
_runshell([brctlexe, 'setmaxage', self.name, str(time)],
"Could not set max message age in %s." % self.name) | [
"def",
"setmaxage",
"(",
"self",
",",
"time",
")",
":",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'setmaxage'",
",",
"self",
".",
"name",
",",
"str",
"(",
"time",
")",
"]",
",",
"\"Could not set max message age in %s.\"",
"%",
"self",
".",
"name",
")"
] | Set bridge max message age time. | [
"Set",
"bridge",
"max",
"message",
"age",
"time",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L68-L71 |
udragon/pybrctl | pybrctl/pybrctl.py | Bridge.setpathcost | def setpathcost(self, port, cost):
""" Set port path cost value for STP protocol. """
_runshell([brctlexe, 'setpathcost', self.name, port, str(cost)],
"Could not set path cost in port %s in %s." % (port, self.name)) | python | def setpathcost(self, port, cost):
""" Set port path cost value for STP protocol. """
_runshell([brctlexe, 'setpathcost', self.name, port, str(cost)],
"Could not set path cost in port %s in %s." % (port, self.name)) | [
"def",
"setpathcost",
"(",
"self",
",",
"port",
",",
"cost",
")",
":",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'setpathcost'",
",",
"self",
".",
"name",
",",
"port",
",",
"str",
"(",
"cost",
")",
"]",
",",
"\"Could not set path cost in port %s in %s.\"",
... | Set port path cost value for STP protocol. | [
"Set",
"port",
"path",
"cost",
"value",
"for",
"STP",
"protocol",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L73-L76 |
udragon/pybrctl | pybrctl/pybrctl.py | Bridge.setportprio | def setportprio(self, port, prio):
""" Set port priority value. """
_runshell([brctlexe, 'setportprio', self.name, port, str(prio)],
"Could not set priority in port %s in %s." % (port, self.name)) | python | def setportprio(self, port, prio):
""" Set port priority value. """
_runshell([brctlexe, 'setportprio', self.name, port, str(prio)],
"Could not set priority in port %s in %s." % (port, self.name)) | [
"def",
"setportprio",
"(",
"self",
",",
"port",
",",
"prio",
")",
":",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'setportprio'",
",",
"self",
".",
"name",
",",
"port",
",",
"str",
"(",
"prio",
")",
"]",
",",
"\"Could not set priority in port %s in %s.\"",
"... | Set port priority value. | [
"Set",
"port",
"priority",
"value",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L78-L81 |
udragon/pybrctl | pybrctl/pybrctl.py | Bridge._show | def _show(self):
""" Return a list of unsorted bridge details. """
p = _runshell([brctlexe, 'show', self.name],
"Could not show %s." % self.name)
return p.stdout.read().split()[7:] | python | def _show(self):
""" Return a list of unsorted bridge details. """
p = _runshell([brctlexe, 'show', self.name],
"Could not show %s." % self.name)
return p.stdout.read().split()[7:] | [
"def",
"_show",
"(",
"self",
")",
":",
"p",
"=",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'show'",
",",
"self",
".",
"name",
"]",
",",
"\"Could not show %s.\"",
"%",
"self",
".",
"name",
")",
"return",
"p",
".",
"stdout",
".",
"read",
"(",
")",
"."... | Return a list of unsorted bridge details. | [
"Return",
"a",
"list",
"of",
"unsorted",
"bridge",
"details",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L83-L87 |
udragon/pybrctl | pybrctl/pybrctl.py | BridgeController.addbr | def addbr(self, name):
""" Create a bridge and set the device up. """
_runshell([brctlexe, 'addbr', name],
"Could not create bridge %s." % name)
_runshell([ipexe, 'link', 'set', 'dev', name, 'up'],
"Could not set link up for %s." % name)
return Bridge(name) | python | def addbr(self, name):
""" Create a bridge and set the device up. """
_runshell([brctlexe, 'addbr', name],
"Could not create bridge %s." % name)
_runshell([ipexe, 'link', 'set', 'dev', name, 'up'],
"Could not set link up for %s." % name)
return Bridge(name) | [
"def",
"addbr",
"(",
"self",
",",
"name",
")",
":",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'addbr'",
",",
"name",
"]",
",",
"\"Could not create bridge %s.\"",
"%",
"name",
")",
"_runshell",
"(",
"[",
"ipexe",
",",
"'link'",
",",
"'set'",
",",
"'dev'",
... | Create a bridge and set the device up. | [
"Create",
"a",
"bridge",
"and",
"set",
"the",
"device",
"up",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L112-L118 |
udragon/pybrctl | pybrctl/pybrctl.py | BridgeController.delbr | def delbr(self, name):
""" Set the device down and delete the bridge. """
self.getbr(name) # Check if exists
_runshell([ipexe, 'link', 'set', 'dev', name, 'down'],
"Could not set link down for %s." % name)
_runshell([brctlexe, 'delbr', name],
"Could not delete bridge %s." % name) | python | def delbr(self, name):
""" Set the device down and delete the bridge. """
self.getbr(name) # Check if exists
_runshell([ipexe, 'link', 'set', 'dev', name, 'down'],
"Could not set link down for %s." % name)
_runshell([brctlexe, 'delbr', name],
"Could not delete bridge %s." % name) | [
"def",
"delbr",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"getbr",
"(",
"name",
")",
"# Check if exists",
"_runshell",
"(",
"[",
"ipexe",
",",
"'link'",
",",
"'set'",
",",
"'dev'",
",",
"name",
",",
"'down'",
"]",
",",
"\"Could not set link down f... | Set the device down and delete the bridge. | [
"Set",
"the",
"device",
"down",
"and",
"delete",
"the",
"bridge",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L120-L126 |
udragon/pybrctl | pybrctl/pybrctl.py | BridgeController.showall | def showall(self):
""" Return a list of all available bridges. """
p = _runshell([brctlexe, 'show'],
"Could not show bridges.")
wlist = map(str.split, p.stdout.read().splitlines()[1:])
brwlist = filter(lambda x: len(x) != 1, wlist)
brlist = map(lambda x: x[0], brwlist)
return map(Bridge, brlist) | python | def showall(self):
""" Return a list of all available bridges. """
p = _runshell([brctlexe, 'show'],
"Could not show bridges.")
wlist = map(str.split, p.stdout.read().splitlines()[1:])
brwlist = filter(lambda x: len(x) != 1, wlist)
brlist = map(lambda x: x[0], brwlist)
return map(Bridge, brlist) | [
"def",
"showall",
"(",
"self",
")",
":",
"p",
"=",
"_runshell",
"(",
"[",
"brctlexe",
",",
"'show'",
"]",
",",
"\"Could not show bridges.\"",
")",
"wlist",
"=",
"map",
"(",
"str",
".",
"split",
",",
"p",
".",
"stdout",
".",
"read",
"(",
")",
".",
"... | Return a list of all available bridges. | [
"Return",
"a",
"list",
"of",
"all",
"available",
"bridges",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L128-L135 |
udragon/pybrctl | pybrctl/pybrctl.py | BridgeController.getbr | def getbr(self, name):
""" Return a bridge object."""
for br in self.showall():
if br.name == name:
return br
raise BridgeException("Bridge does not exist.") | python | def getbr(self, name):
""" Return a bridge object."""
for br in self.showall():
if br.name == name:
return br
raise BridgeException("Bridge does not exist.") | [
"def",
"getbr",
"(",
"self",
",",
"name",
")",
":",
"for",
"br",
"in",
"self",
".",
"showall",
"(",
")",
":",
"if",
"br",
".",
"name",
"==",
"name",
":",
"return",
"br",
"raise",
"BridgeException",
"(",
"\"Bridge does not exist.\"",
")"
] | Return a bridge object. | [
"Return",
"a",
"bridge",
"object",
"."
] | train | https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L137-L142 |
closeio/cleancat | cleancat/base.py | Field.clean | def clean(self, value):
"""Take a dirty value and clean it."""
if (
self.base_type is not None and
value is not None and
not isinstance(value, self.base_type)
):
if isinstance(self.base_type, tuple):
allowed_types = [typ.__name__ for typ in self.base_type]
allowed_types_text = ' or '.join(allowed_types)
else:
allowed_types_text = self.base_type.__name__
err_msg = 'Value must be of %s type.' % allowed_types_text
raise ValidationError(err_msg)
if not self.has_value(value):
if self.default is not None:
raise StopValidation(self.default)
if self.required:
raise ValidationError('This field is required.')
else:
raise StopValidation(self.blank_value)
return value | python | def clean(self, value):
"""Take a dirty value and clean it."""
if (
self.base_type is not None and
value is not None and
not isinstance(value, self.base_type)
):
if isinstance(self.base_type, tuple):
allowed_types = [typ.__name__ for typ in self.base_type]
allowed_types_text = ' or '.join(allowed_types)
else:
allowed_types_text = self.base_type.__name__
err_msg = 'Value must be of %s type.' % allowed_types_text
raise ValidationError(err_msg)
if not self.has_value(value):
if self.default is not None:
raise StopValidation(self.default)
if self.required:
raise ValidationError('This field is required.')
else:
raise StopValidation(self.blank_value)
return value | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"if",
"(",
"self",
".",
"base_type",
"is",
"not",
"None",
"and",
"value",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"value",
",",
"self",
".",
"base_type",
")",
")",
":",
"if",
"isins... | Take a dirty value and clean it. | [
"Take",
"a",
"dirty",
"value",
"and",
"clean",
"it",
"."
] | train | https://github.com/closeio/cleancat/blob/59df1422b3ebea9477026ca80cd7af1ae9734d89/cleancat/base.py#L54-L78 |
closeio/cleancat | cleancat/base.py | EmbeddedReference.clean_new | def clean_new(self, value):
"""Return a new object instantiated with cleaned data."""
value = self.schema_class(value).full_clean()
return self.object_class(**value) | python | def clean_new(self, value):
"""Return a new object instantiated with cleaned data."""
value = self.schema_class(value).full_clean()
return self.object_class(**value) | [
"def",
"clean_new",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"self",
".",
"schema_class",
"(",
"value",
")",
".",
"full_clean",
"(",
")",
"return",
"self",
".",
"object_class",
"(",
"*",
"*",
"value",
")"
] | Return a new object instantiated with cleaned data. | [
"Return",
"a",
"new",
"object",
"instantiated",
"with",
"cleaned",
"data",
"."
] | train | https://github.com/closeio/cleancat/blob/59df1422b3ebea9477026ca80cd7af1ae9734d89/cleancat/base.py#L446-L449 |
closeio/cleancat | cleancat/base.py | EmbeddedReference.clean_existing | def clean_existing(self, value):
"""Clean the data and return an existing document with its fields
updated based on the cleaned values.
"""
existing_pk = value[self.pk_field]
try:
obj = self.fetch_existing(existing_pk)
except ReferenceNotFoundError:
raise ValidationError('Object does not exist.')
orig_data = self.get_orig_data_from_existing(obj)
# Clean the data (passing the new data dict and the original data to
# the schema).
value = self.schema_class(value, orig_data).full_clean()
# Set cleaned data on the object (except for the pk_field).
for field_name, field_value in value.items():
if field_name != self.pk_field:
setattr(obj, field_name, field_value)
return obj | python | def clean_existing(self, value):
"""Clean the data and return an existing document with its fields
updated based on the cleaned values.
"""
existing_pk = value[self.pk_field]
try:
obj = self.fetch_existing(existing_pk)
except ReferenceNotFoundError:
raise ValidationError('Object does not exist.')
orig_data = self.get_orig_data_from_existing(obj)
# Clean the data (passing the new data dict and the original data to
# the schema).
value = self.schema_class(value, orig_data).full_clean()
# Set cleaned data on the object (except for the pk_field).
for field_name, field_value in value.items():
if field_name != self.pk_field:
setattr(obj, field_name, field_value)
return obj | [
"def",
"clean_existing",
"(",
"self",
",",
"value",
")",
":",
"existing_pk",
"=",
"value",
"[",
"self",
".",
"pk_field",
"]",
"try",
":",
"obj",
"=",
"self",
".",
"fetch_existing",
"(",
"existing_pk",
")",
"except",
"ReferenceNotFoundError",
":",
"raise",
... | Clean the data and return an existing document with its fields
updated based on the cleaned values. | [
"Clean",
"the",
"data",
"and",
"return",
"an",
"existing",
"document",
"with",
"its",
"fields",
"updated",
"based",
"on",
"the",
"cleaned",
"values",
"."
] | train | https://github.com/closeio/cleancat/blob/59df1422b3ebea9477026ca80cd7af1ae9734d89/cleancat/base.py#L451-L471 |
closeio/cleancat | cleancat/base.py | Schema.get_fields | def get_fields(cls):
"""
Returns a dictionary of fields and field instances for this schema.
"""
fields = {}
for field_name in dir(cls):
if isinstance(getattr(cls, field_name), Field):
field = getattr(cls, field_name)
field_name = field.field_name or field_name
fields[field_name] = field
return fields | python | def get_fields(cls):
"""
Returns a dictionary of fields and field instances for this schema.
"""
fields = {}
for field_name in dir(cls):
if isinstance(getattr(cls, field_name), Field):
field = getattr(cls, field_name)
field_name = field.field_name or field_name
fields[field_name] = field
return fields | [
"def",
"get_fields",
"(",
"cls",
")",
":",
"fields",
"=",
"{",
"}",
"for",
"field_name",
"in",
"dir",
"(",
"cls",
")",
":",
"if",
"isinstance",
"(",
"getattr",
"(",
"cls",
",",
"field_name",
")",
",",
"Field",
")",
":",
"field",
"=",
"getattr",
"("... | Returns a dictionary of fields and field instances for this schema. | [
"Returns",
"a",
"dictionary",
"of",
"fields",
"and",
"field",
"instances",
"for",
"this",
"schema",
"."
] | train | https://github.com/closeio/cleancat/blob/59df1422b3ebea9477026ca80cd7af1ae9734d89/cleancat/base.py#L674-L684 |
closeio/cleancat | cleancat/base.py | Schema.obj_to_dict | def obj_to_dict(cls, obj):
"""
Takes a model object and converts it into a dictionary suitable for
passing to the constructor's data attribute.
"""
data = {}
for field_name in cls.get_fields():
try:
value = getattr(obj, field_name)
except AttributeError:
# If the field doesn't exist on the object, fail gracefully
# and don't include the field in the data dict at all. Fail
# loudly if the field exists but produces a different error
# (edge case: accessing an *existing* field could technically
# produce an unrelated AttributeError).
continue
if callable(value):
value = value()
data[field_name] = value
return data | python | def obj_to_dict(cls, obj):
"""
Takes a model object and converts it into a dictionary suitable for
passing to the constructor's data attribute.
"""
data = {}
for field_name in cls.get_fields():
try:
value = getattr(obj, field_name)
except AttributeError:
# If the field doesn't exist on the object, fail gracefully
# and don't include the field in the data dict at all. Fail
# loudly if the field exists but produces a different error
# (edge case: accessing an *existing* field could technically
# produce an unrelated AttributeError).
continue
if callable(value):
value = value()
data[field_name] = value
return data | [
"def",
"obj_to_dict",
"(",
"cls",
",",
"obj",
")",
":",
"data",
"=",
"{",
"}",
"for",
"field_name",
"in",
"cls",
".",
"get_fields",
"(",
")",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
"field_name",
")",
"except",
"AttributeError",
":... | Takes a model object and converts it into a dictionary suitable for
passing to the constructor's data attribute. | [
"Takes",
"a",
"model",
"object",
"and",
"converts",
"it",
"into",
"a",
"dictionary",
"suitable",
"for",
"passing",
"to",
"the",
"constructor",
"s",
"data",
"attribute",
"."
] | train | https://github.com/closeio/cleancat/blob/59df1422b3ebea9477026ca80cd7af1ae9734d89/cleancat/base.py#L687-L708 |
thunder-project/thunder-registration | registration/model.py | RegistrationModel.toarray | def toarray(self):
"""
Return transformations as an array with shape (n,x1,x2,...)
where n is the number of images, and remaining dimensions depend
on the particular transformations
"""
return asarray([value.toarray() for (key, value) in sorted(self.transformations.items())]) | python | def toarray(self):
"""
Return transformations as an array with shape (n,x1,x2,...)
where n is the number of images, and remaining dimensions depend
on the particular transformations
"""
return asarray([value.toarray() for (key, value) in sorted(self.transformations.items())]) | [
"def",
"toarray",
"(",
"self",
")",
":",
"return",
"asarray",
"(",
"[",
"value",
".",
"toarray",
"(",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"sorted",
"(",
"self",
".",
"transformations",
".",
"items",
"(",
")",
")",
"]",
")"
] | Return transformations as an array with shape (n,x1,x2,...)
where n is the number of images, and remaining dimensions depend
on the particular transformations | [
"Return",
"transformations",
"as",
"an",
"array",
"with",
"shape",
"(",
"n",
"x1",
"x2",
"...",
")",
"where",
"n",
"is",
"the",
"number",
"of",
"images",
"and",
"remaining",
"dimensions",
"depend",
"on",
"the",
"particular",
"transformations"
] | train | https://github.com/thunder-project/thunder-registration/blob/286f091e6c402d592e9686d4821e0fd80dbf86ec/registration/model.py#L16-L22 |
thunder-project/thunder-registration | registration/model.py | RegistrationModel.transform | def transform(self, images):
"""
Apply the transformation to an Images object.
Will apply the underlying dictionary of transformations to
the images or volumes of the Images object. The dictionary acts as a lookup
table specifying which transformation should be applied to which record of the
Images object based on the key. Because transformations are small,
we broadcast the transformations rather than using a join.
Parameters
----------
images : array-like or thunder images
The sequence of images / volumes to register.
"""
images = check_images(images)
def apply(item):
(k, v) = item
return self.transformations[k].apply(v)
return images.map(apply, value_shape=images.value_shape, dtype=images.dtype, with_keys=True) | python | def transform(self, images):
"""
Apply the transformation to an Images object.
Will apply the underlying dictionary of transformations to
the images or volumes of the Images object. The dictionary acts as a lookup
table specifying which transformation should be applied to which record of the
Images object based on the key. Because transformations are small,
we broadcast the transformations rather than using a join.
Parameters
----------
images : array-like or thunder images
The sequence of images / volumes to register.
"""
images = check_images(images)
def apply(item):
(k, v) = item
return self.transformations[k].apply(v)
return images.map(apply, value_shape=images.value_shape, dtype=images.dtype, with_keys=True) | [
"def",
"transform",
"(",
"self",
",",
"images",
")",
":",
"images",
"=",
"check_images",
"(",
"images",
")",
"def",
"apply",
"(",
"item",
")",
":",
"(",
"k",
",",
"v",
")",
"=",
"item",
"return",
"self",
".",
"transformations",
"[",
"k",
"]",
".",
... | Apply the transformation to an Images object.
Will apply the underlying dictionary of transformations to
the images or volumes of the Images object. The dictionary acts as a lookup
table specifying which transformation should be applied to which record of the
Images object based on the key. Because transformations are small,
we broadcast the transformations rather than using a join.
Parameters
----------
images : array-like or thunder images
The sequence of images / volumes to register. | [
"Apply",
"the",
"transformation",
"to",
"an",
"Images",
"object",
"."
] | train | https://github.com/thunder-project/thunder-registration/blob/286f091e6c402d592e9686d4821e0fd80dbf86ec/registration/model.py#L24-L45 |
xonsh/lazyasd | lazyasd-py2.py | load_module_in_background | def load_module_in_background(name, package=None, debug='DEBUG', env=None,
replacements=None):
"""Entry point for loading modules in background thread.
Parameters
----------
name : str
Module name to load in background thread.
package : str or None, optional
Package name, has the same meaning as in importlib.import_module().
debug : str, optional
Debugging symbol name to look up in the environment.
env : Mapping or None, optional
Environment this will default to __xonsh_env__, if available, and
os.environ otherwise.
replacements : Mapping or None, optional
Dictionary mapping fully qualified module names (eg foo.bar.baz) that
import the lazily loaded moudle, with the variable name in that
module. For example, suppose that foo.bar imports module a as b,
this dict is then {'foo.bar': 'b'}.
Returns
-------
module : ModuleType
This is either the original module that is found in sys.modules or
a proxy module that will block until delay attribute access until the
module is fully loaded.
"""
modname = resolve_name(name, package)
if modname in sys.modules:
return sys.modules[modname]
if env is None:
try:
import builtins
env = getattr(builtins, '__xonsh_env__', os.environ)
except:
return os.environ
if env.get(debug, None):
mod = importlib.import_module(name, package=package)
return mod
proxy = sys.modules[modname] = BackgroundModuleProxy(modname)
BackgroundModuleLoader(name, package, replacements or {})
return proxy | python | def load_module_in_background(name, package=None, debug='DEBUG', env=None,
replacements=None):
"""Entry point for loading modules in background thread.
Parameters
----------
name : str
Module name to load in background thread.
package : str or None, optional
Package name, has the same meaning as in importlib.import_module().
debug : str, optional
Debugging symbol name to look up in the environment.
env : Mapping or None, optional
Environment this will default to __xonsh_env__, if available, and
os.environ otherwise.
replacements : Mapping or None, optional
Dictionary mapping fully qualified module names (eg foo.bar.baz) that
import the lazily loaded moudle, with the variable name in that
module. For example, suppose that foo.bar imports module a as b,
this dict is then {'foo.bar': 'b'}.
Returns
-------
module : ModuleType
This is either the original module that is found in sys.modules or
a proxy module that will block until delay attribute access until the
module is fully loaded.
"""
modname = resolve_name(name, package)
if modname in sys.modules:
return sys.modules[modname]
if env is None:
try:
import builtins
env = getattr(builtins, '__xonsh_env__', os.environ)
except:
return os.environ
if env.get(debug, None):
mod = importlib.import_module(name, package=package)
return mod
proxy = sys.modules[modname] = BackgroundModuleProxy(modname)
BackgroundModuleLoader(name, package, replacements or {})
return proxy | [
"def",
"load_module_in_background",
"(",
"name",
",",
"package",
"=",
"None",
",",
"debug",
"=",
"'DEBUG'",
",",
"env",
"=",
"None",
",",
"replacements",
"=",
"None",
")",
":",
"modname",
"=",
"resolve_name",
"(",
"name",
",",
"package",
")",
"if",
"modn... | Entry point for loading modules in background thread.
Parameters
----------
name : str
Module name to load in background thread.
package : str or None, optional
Package name, has the same meaning as in importlib.import_module().
debug : str, optional
Debugging symbol name to look up in the environment.
env : Mapping or None, optional
Environment this will default to __xonsh_env__, if available, and
os.environ otherwise.
replacements : Mapping or None, optional
Dictionary mapping fully qualified module names (eg foo.bar.baz) that
import the lazily loaded moudle, with the variable name in that
module. For example, suppose that foo.bar imports module a as b,
this dict is then {'foo.bar': 'b'}.
Returns
-------
module : ModuleType
This is either the original module that is found in sys.modules or
a proxy module that will block until delay attribute access until the
module is fully loaded. | [
"Entry",
"point",
"for",
"loading",
"modules",
"in",
"background",
"thread",
"."
] | train | https://github.com/xonsh/lazyasd/blob/5f40b193f1602e723f7ede82435836e218e0e5ec/lazyasd-py2.py#L331-L373 |
jordanh/neurio-python | neurio/__init__.py | TokenProvider.get_token | def get_token(self):
"""Performs Neurio API token authentication using provided key and secret.
Note:
This method is generally not called by hand; rather it is usually
called as-needed by a Neurio Client object.
Returns:
string: the access token
"""
if self.__token is not None:
return self.__token
url = "https://api.neur.io/v1/oauth2/token"
creds = b64encode(":".join([self.__key,self.__secret]).encode()).decode()
headers = {
"Authorization": " ".join(["Basic", creds]),
}
payload = {
"grant_type": "client_credentials"
}
r = requests.post(url, data=payload, headers=headers)
self.__token = r.json()["access_token"]
return self.__token | python | def get_token(self):
"""Performs Neurio API token authentication using provided key and secret.
Note:
This method is generally not called by hand; rather it is usually
called as-needed by a Neurio Client object.
Returns:
string: the access token
"""
if self.__token is not None:
return self.__token
url = "https://api.neur.io/v1/oauth2/token"
creds = b64encode(":".join([self.__key,self.__secret]).encode()).decode()
headers = {
"Authorization": " ".join(["Basic", creds]),
}
payload = {
"grant_type": "client_credentials"
}
r = requests.post(url, data=payload, headers=headers)
self.__token = r.json()["access_token"]
return self.__token | [
"def",
"get_token",
"(",
"self",
")",
":",
"if",
"self",
".",
"__token",
"is",
"not",
"None",
":",
"return",
"self",
".",
"__token",
"url",
"=",
"\"https://api.neur.io/v1/oauth2/token\"",
"creds",
"=",
"b64encode",
"(",
"\":\"",
".",
"join",
"(",
"[",
"sel... | Performs Neurio API token authentication using provided key and secret.
Note:
This method is generally not called by hand; rather it is usually
called as-needed by a Neurio Client object.
Returns:
string: the access token | [
"Performs",
"Neurio",
"API",
"token",
"authentication",
"using",
"provided",
"key",
"and",
"secret",
"."
] | train | https://github.com/jordanh/neurio-python/blob/3a1bcadadb3bb3ad48f2df41c039d8b828ffd9c8/neurio/__init__.py#L51-L79 |
jordanh/neurio-python | neurio/__init__.py | Client.__append_url_params | def __append_url_params(self, url, params):
"""Utility method formatting url request parameters."""
url_parts = list(urlparse(url))
query = dict(parse_qsl(url_parts[4]))
query.update(params)
url_parts[4] = urlencode(query)
return urlunparse(url_parts) | python | def __append_url_params(self, url, params):
"""Utility method formatting url request parameters."""
url_parts = list(urlparse(url))
query = dict(parse_qsl(url_parts[4]))
query.update(params)
url_parts[4] = urlencode(query)
return urlunparse(url_parts) | [
"def",
"__append_url_params",
"(",
"self",
",",
"url",
",",
"params",
")",
":",
"url_parts",
"=",
"list",
"(",
"urlparse",
"(",
"url",
")",
")",
"query",
"=",
"dict",
"(",
"parse_qsl",
"(",
"url_parts",
"[",
"4",
"]",
")",
")",
"query",
".",
"update"... | Utility method formatting url request parameters. | [
"Utility",
"method",
"formatting",
"url",
"request",
"parameters",
"."
] | train | https://github.com/jordanh/neurio-python/blob/3a1bcadadb3bb3ad48f2df41c039d8b828ffd9c8/neurio/__init__.py#L106-L113 |
jordanh/neurio-python | neurio/__init__.py | Client.get_appliance | def get_appliance(self, appliance_id):
"""Get the information for a specified appliance
Args:
appliance_id (string): identifiying string of appliance
Returns:
list: dictionary object containing information about the specified appliance
"""
url = "https://api.neur.io/v1/appliances/%s"%(appliance_id)
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
r = requests.get(url, headers=headers)
return r.json() | python | def get_appliance(self, appliance_id):
"""Get the information for a specified appliance
Args:
appliance_id (string): identifiying string of appliance
Returns:
list: dictionary object containing information about the specified appliance
"""
url = "https://api.neur.io/v1/appliances/%s"%(appliance_id)
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
r = requests.get(url, headers=headers)
return r.json() | [
"def",
"get_appliance",
"(",
"self",
",",
"appliance_id",
")",
":",
"url",
"=",
"\"https://api.neur.io/v1/appliances/%s\"",
"%",
"(",
"appliance_id",
")",
"headers",
"=",
"self",
".",
"__gen_headers",
"(",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"ap... | Get the information for a specified appliance
Args:
appliance_id (string): identifiying string of appliance
Returns:
list: dictionary object containing information about the specified appliance | [
"Get",
"the",
"information",
"for",
"a",
"specified",
"appliance"
] | train | https://github.com/jordanh/neurio-python/blob/3a1bcadadb3bb3ad48f2df41c039d8b828ffd9c8/neurio/__init__.py#L115-L130 |
jordanh/neurio-python | neurio/__init__.py | Client.get_appliances | def get_appliances(self, location_id):
"""Get the appliances added for a specified location.
Args:
location_id (string): identifiying string of appliance
Returns:
list: dictionary objects containing appliances data
"""
url = "https://api.neur.io/v1/appliances"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = {
"locationId": location_id,
}
url = self.__append_url_params(url, params)
r = requests.get(url, headers=headers)
return r.json() | python | def get_appliances(self, location_id):
"""Get the appliances added for a specified location.
Args:
location_id (string): identifiying string of appliance
Returns:
list: dictionary objects containing appliances data
"""
url = "https://api.neur.io/v1/appliances"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = {
"locationId": location_id,
}
url = self.__append_url_params(url, params)
r = requests.get(url, headers=headers)
return r.json() | [
"def",
"get_appliances",
"(",
"self",
",",
"location_id",
")",
":",
"url",
"=",
"\"https://api.neur.io/v1/appliances\"",
"headers",
"=",
"self",
".",
"__gen_headers",
"(",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"application/json\"",
"params",
"=",
"{... | Get the appliances added for a specified location.
Args:
location_id (string): identifiying string of appliance
Returns:
list: dictionary objects containing appliances data | [
"Get",
"the",
"appliances",
"added",
"for",
"a",
"specified",
"location",
"."
] | train | https://github.com/jordanh/neurio-python/blob/3a1bcadadb3bb3ad48f2df41c039d8b828ffd9c8/neurio/__init__.py#L132-L152 |
jordanh/neurio-python | neurio/__init__.py | Client.get_appliance_event_after_time | def get_appliance_event_after_time(self, location_id, since, per_page=None, page=None, min_power=None):
"""Get appliance events by location Id after defined time.
Args:
location_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
since (string): ISO 8601 start time for getting the events that are created or updated after it.
Maxiumim value allowed is 1 day from the current time.
min_power (string): The minimum average power (in watts) for filtering.
Only events with an average power above this value will be returned.
(default: 400)
per_page (string, optional): the number of returned results per page
(min 1, max 500) (default: 10)
page (string, optional): the page number to return (min 1, max 100000)
(default: 1)
Returns:
list: dictionary objects containing appliance events meeting specified criteria
"""
url = "https://api.neur.io/v1/appliances/events"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = {
"locationId": location_id,
"since": since
}
if min_power:
params["minPower"] = min_power
if per_page:
params["perPage"] = per_page
if page:
params["page"] = page
url = self.__append_url_params(url, params)
r = requests.get(url, headers=headers)
return r.json() | python | def get_appliance_event_after_time(self, location_id, since, per_page=None, page=None, min_power=None):
"""Get appliance events by location Id after defined time.
Args:
location_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
since (string): ISO 8601 start time for getting the events that are created or updated after it.
Maxiumim value allowed is 1 day from the current time.
min_power (string): The minimum average power (in watts) for filtering.
Only events with an average power above this value will be returned.
(default: 400)
per_page (string, optional): the number of returned results per page
(min 1, max 500) (default: 10)
page (string, optional): the page number to return (min 1, max 100000)
(default: 1)
Returns:
list: dictionary objects containing appliance events meeting specified criteria
"""
url = "https://api.neur.io/v1/appliances/events"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = {
"locationId": location_id,
"since": since
}
if min_power:
params["minPower"] = min_power
if per_page:
params["perPage"] = per_page
if page:
params["page"] = page
url = self.__append_url_params(url, params)
r = requests.get(url, headers=headers)
return r.json() | [
"def",
"get_appliance_event_after_time",
"(",
"self",
",",
"location_id",
",",
"since",
",",
"per_page",
"=",
"None",
",",
"page",
"=",
"None",
",",
"min_power",
"=",
"None",
")",
":",
"url",
"=",
"\"https://api.neur.io/v1/appliances/events\"",
"headers",
"=",
"... | Get appliance events by location Id after defined time.
Args:
location_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
since (string): ISO 8601 start time for getting the events that are created or updated after it.
Maxiumim value allowed is 1 day from the current time.
min_power (string): The minimum average power (in watts) for filtering.
Only events with an average power above this value will be returned.
(default: 400)
per_page (string, optional): the number of returned results per page
(min 1, max 500) (default: 10)
page (string, optional): the page number to return (min 1, max 100000)
(default: 1)
Returns:
list: dictionary objects containing appliance events meeting specified criteria | [
"Get",
"appliance",
"events",
"by",
"location",
"Id",
"after",
"defined",
"time",
"."
] | train | https://github.com/jordanh/neurio-python/blob/3a1bcadadb3bb3ad48f2df41c039d8b828ffd9c8/neurio/__init__.py#L195-L232 |
jordanh/neurio-python | neurio/__init__.py | Client.get_appliance_stats_by_location | def get_appliance_stats_by_location(self, location_id, start, end, granularity=None, per_page=None, page=None,
min_power=None):
"""Get appliance usage data for a given location within a given time range.
Stats are generated by fetching appliance events that match the supplied
criteria and then aggregating them together based on the granularity
specified with the request.
Note:
This endpoint uses the location's time zone when generating time intervals
for the stats, which is relevant if that time zone uses daylight saving
time (some days will be 23 or 25 hours long).
Args:
location_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
start (string): ISO 8601 start time for getting the events of appliances.
end (string): ISO 8601 stop time for getting the events of appliances.
Cannot be larger than 1 month from start time
granularity (string): granularity of stats. If the granularity is
'unknown', the stats for the appliances between the start and
end time is returned.;
must be one of "minutes", "hours", "days", "weeks", "months", or "unknown"
(default: days)
min_power (string): The minimum average power (in watts) for filtering.
Only events with an average power above this value will be returned.
(default: 400)
per_page (string, optional): the number of returned results per page
(min 1, max 500) (default: 10)
page (string, optional): the page number to return (min 1, max 100000)
(default: 1)
Returns:
list: dictionary objects containing appliance events meeting specified criteria
"""
url = "https://api.neur.io/v1/appliances/stats"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = {
"locationId": location_id,
"start": start,
"end": end
}
if granularity:
params["granularity"] = granularity
if min_power:
params["minPower"] = min_power
if per_page:
params["perPage"] = per_page
if page:
params["page"] = page
url = self.__append_url_params(url, params)
r = requests.get(url, headers=headers)
return r.json() | python | def get_appliance_stats_by_location(self, location_id, start, end, granularity=None, per_page=None, page=None,
min_power=None):
"""Get appliance usage data for a given location within a given time range.
Stats are generated by fetching appliance events that match the supplied
criteria and then aggregating them together based on the granularity
specified with the request.
Note:
This endpoint uses the location's time zone when generating time intervals
for the stats, which is relevant if that time zone uses daylight saving
time (some days will be 23 or 25 hours long).
Args:
location_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
start (string): ISO 8601 start time for getting the events of appliances.
end (string): ISO 8601 stop time for getting the events of appliances.
Cannot be larger than 1 month from start time
granularity (string): granularity of stats. If the granularity is
'unknown', the stats for the appliances between the start and
end time is returned.;
must be one of "minutes", "hours", "days", "weeks", "months", or "unknown"
(default: days)
min_power (string): The minimum average power (in watts) for filtering.
Only events with an average power above this value will be returned.
(default: 400)
per_page (string, optional): the number of returned results per page
(min 1, max 500) (default: 10)
page (string, optional): the page number to return (min 1, max 100000)
(default: 1)
Returns:
list: dictionary objects containing appliance events meeting specified criteria
"""
url = "https://api.neur.io/v1/appliances/stats"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = {
"locationId": location_id,
"start": start,
"end": end
}
if granularity:
params["granularity"] = granularity
if min_power:
params["minPower"] = min_power
if per_page:
params["perPage"] = per_page
if page:
params["page"] = page
url = self.__append_url_params(url, params)
r = requests.get(url, headers=headers)
return r.json() | [
"def",
"get_appliance_stats_by_location",
"(",
"self",
",",
"location_id",
",",
"start",
",",
"end",
",",
"granularity",
"=",
"None",
",",
"per_page",
"=",
"None",
",",
"page",
"=",
"None",
",",
"min_power",
"=",
"None",
")",
":",
"url",
"=",
"\"https://ap... | Get appliance usage data for a given location within a given time range.
Stats are generated by fetching appliance events that match the supplied
criteria and then aggregating them together based on the granularity
specified with the request.
Note:
This endpoint uses the location's time zone when generating time intervals
for the stats, which is relevant if that time zone uses daylight saving
time (some days will be 23 or 25 hours long).
Args:
location_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
start (string): ISO 8601 start time for getting the events of appliances.
end (string): ISO 8601 stop time for getting the events of appliances.
Cannot be larger than 1 month from start time
granularity (string): granularity of stats. If the granularity is
'unknown', the stats for the appliances between the start and
end time is returned.;
must be one of "minutes", "hours", "days", "weeks", "months", or "unknown"
(default: days)
min_power (string): The minimum average power (in watts) for filtering.
Only events with an average power above this value will be returned.
(default: 400)
per_page (string, optional): the number of returned results per page
(min 1, max 500) (default: 10)
page (string, optional): the page number to return (min 1, max 100000)
(default: 1)
Returns:
list: dictionary objects containing appliance events meeting specified criteria | [
"Get",
"appliance",
"usage",
"data",
"for",
"a",
"given",
"location",
"within",
"a",
"given",
"time",
"range",
".",
"Stats",
"are",
"generated",
"by",
"fetching",
"appliance",
"events",
"that",
"match",
"the",
"supplied",
"criteria",
"and",
"then",
"aggregatin... | train | https://github.com/jordanh/neurio-python/blob/3a1bcadadb3bb3ad48f2df41c039d8b828ffd9c8/neurio/__init__.py#L332-L387 |
jordanh/neurio-python | neurio/__init__.py | Client.get_local_current_sample | def get_local_current_sample(ip):
"""Gets current sample from *local* Neurio device IP address.
This is a static method. It doesn't require a token to authenticate.
Note, call get_user_information to determine local Neurio IP addresses.
Args:
ip (string): address of local Neurio device
Returns:
dictionary object containing current sample information
"""
valid_ip_pat = re.compile(
"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
)
if not valid_ip_pat.match(ip):
raise ValueError("ip address invalid")
url = "http://%s/current-sample" % (ip)
headers = { "Content-Type": "application/json" }
r = requests.get(url, headers=headers)
return r.json() | python | def get_local_current_sample(ip):
"""Gets current sample from *local* Neurio device IP address.
This is a static method. It doesn't require a token to authenticate.
Note, call get_user_information to determine local Neurio IP addresses.
Args:
ip (string): address of local Neurio device
Returns:
dictionary object containing current sample information
"""
valid_ip_pat = re.compile(
"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
)
if not valid_ip_pat.match(ip):
raise ValueError("ip address invalid")
url = "http://%s/current-sample" % (ip)
headers = { "Content-Type": "application/json" }
r = requests.get(url, headers=headers)
return r.json() | [
"def",
"get_local_current_sample",
"(",
"ip",
")",
":",
"valid_ip_pat",
"=",
"re",
".",
"compile",
"(",
"\"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$\"",
")",
"if",
"not",
"valid_ip_pat",
".",
"match",
"(",
"ip",
")",
":",
"ra... | Gets current sample from *local* Neurio device IP address.
This is a static method. It doesn't require a token to authenticate.
Note, call get_user_information to determine local Neurio IP addresses.
Args:
ip (string): address of local Neurio device
Returns:
dictionary object containing current sample information | [
"Gets",
"current",
"sample",
"from",
"*",
"local",
"*",
"Neurio",
"device",
"IP",
"address",
"."
] | train | https://github.com/jordanh/neurio-python/blob/3a1bcadadb3bb3ad48f2df41c039d8b828ffd9c8/neurio/__init__.py#L390-L413 |
jordanh/neurio-python | neurio/__init__.py | Client.get_samples_live | def get_samples_live(self, sensor_id, last=None):
"""Get recent samples, one sample per second for up to the last 2 minutes.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
last (string): starting range, as ISO8601 timestamp
Returns:
list: dictionary objects containing sample data
"""
url = "https://api.neur.io/v1/samples/live"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = { "sensorId": sensor_id }
if last:
params["last"] = last
url = self.__append_url_params(url, params)
r = requests.get(url, headers=headers)
return r.json() | python | def get_samples_live(self, sensor_id, last=None):
"""Get recent samples, one sample per second for up to the last 2 minutes.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
last (string): starting range, as ISO8601 timestamp
Returns:
list: dictionary objects containing sample data
"""
url = "https://api.neur.io/v1/samples/live"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = { "sensorId": sensor_id }
if last:
params["last"] = last
url = self.__append_url_params(url, params)
r = requests.get(url, headers=headers)
return r.json() | [
"def",
"get_samples_live",
"(",
"self",
",",
"sensor_id",
",",
"last",
"=",
"None",
")",
":",
"url",
"=",
"\"https://api.neur.io/v1/samples/live\"",
"headers",
"=",
"self",
".",
"__gen_headers",
"(",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"applicat... | Get recent samples, one sample per second for up to the last 2 minutes.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
last (string): starting range, as ISO8601 timestamp
Returns:
list: dictionary objects containing sample data | [
"Get",
"recent",
"samples",
"one",
"sample",
"per",
"second",
"for",
"up",
"to",
"the",
"last",
"2",
"minutes",
"."
] | train | https://github.com/jordanh/neurio-python/blob/3a1bcadadb3bb3ad48f2df41c039d8b828ffd9c8/neurio/__init__.py#L415-L437 |
jordanh/neurio-python | neurio/__init__.py | Client.get_samples_live_last | def get_samples_live_last(self, sensor_id):
"""Get the last sample recorded by the sensor.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
Returns:
list: dictionary objects containing sample data
"""
url = "https://api.neur.io/v1/samples/live/last"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = { "sensorId": sensor_id }
url = self.__append_url_params(url, params)
r = requests.get(url, headers=headers)
return r.json() | python | def get_samples_live_last(self, sensor_id):
"""Get the last sample recorded by the sensor.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
Returns:
list: dictionary objects containing sample data
"""
url = "https://api.neur.io/v1/samples/live/last"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = { "sensorId": sensor_id }
url = self.__append_url_params(url, params)
r = requests.get(url, headers=headers)
return r.json() | [
"def",
"get_samples_live_last",
"(",
"self",
",",
"sensor_id",
")",
":",
"url",
"=",
"\"https://api.neur.io/v1/samples/live/last\"",
"headers",
"=",
"self",
".",
"__gen_headers",
"(",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"application/json\"",
"params",... | Get the last sample recorded by the sensor.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
Returns:
list: dictionary objects containing sample data | [
"Get",
"the",
"last",
"sample",
"recorded",
"by",
"the",
"sensor",
"."
] | train | https://github.com/jordanh/neurio-python/blob/3a1bcadadb3bb3ad48f2df41c039d8b828ffd9c8/neurio/__init__.py#L439-L458 |
jordanh/neurio-python | neurio/__init__.py | Client.get_samples | def get_samples(self, sensor_id, start, granularity, end=None,
frequency=None, per_page=None, page=None,
full=False):
"""Get a sensor's samples for a specified time interval.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
start (string): ISO 8601 start time of sampling; depends on the
``granularity`` parameter value, the maximum supported time ranges are:
1 day for minutes or hours granularities, 1 month for days,
6 months for weeks, 1 year for months granularity, and 10 years for
years granularity
granularity (string): granularity of the sampled data; must be one of
"minutes", "hours", "days", "weeks", "months", or "years"
end (string, optional): ISO 8601 stop time for sampling; should be later
than start time (default: the current time)
frequency (string, optional): frequency of the sampled data (e.g. with
granularity set to days, a value of 3 will result in a sample for every
third day, should be a multiple of 5 when using minutes granularity)
(default: 1) (example: "1, 5")
per_page (string, optional): the number of returned results per page
(min 1, max 500) (default: 10)
page (string, optional): the page number to return (min 1, max 100000)
(default: 1)
full (bool, optional): include additional information per sample
(default: False)
Returns:
list: dictionary objects containing sample data
"""
url = "https://api.neur.io/v1/samples"
if full:
url = "https://api.neur.io/v1/samples/full"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = {
"sensorId": sensor_id,
"start": start,
"granularity": granularity
}
if end:
params["end"] = end
if frequency:
params["frequency"] = frequency
if per_page:
params["perPage"] = per_page
if page:
params["page"] = page
url = self.__append_url_params(url, params)
r = requests.get(url, headers=headers)
return r.json() | python | def get_samples(self, sensor_id, start, granularity, end=None,
frequency=None, per_page=None, page=None,
full=False):
"""Get a sensor's samples for a specified time interval.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
start (string): ISO 8601 start time of sampling; depends on the
``granularity`` parameter value, the maximum supported time ranges are:
1 day for minutes or hours granularities, 1 month for days,
6 months for weeks, 1 year for months granularity, and 10 years for
years granularity
granularity (string): granularity of the sampled data; must be one of
"minutes", "hours", "days", "weeks", "months", or "years"
end (string, optional): ISO 8601 stop time for sampling; should be later
than start time (default: the current time)
frequency (string, optional): frequency of the sampled data (e.g. with
granularity set to days, a value of 3 will result in a sample for every
third day, should be a multiple of 5 when using minutes granularity)
(default: 1) (example: "1, 5")
per_page (string, optional): the number of returned results per page
(min 1, max 500) (default: 10)
page (string, optional): the page number to return (min 1, max 100000)
(default: 1)
full (bool, optional): include additional information per sample
(default: False)
Returns:
list: dictionary objects containing sample data
"""
url = "https://api.neur.io/v1/samples"
if full:
url = "https://api.neur.io/v1/samples/full"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
params = {
"sensorId": sensor_id,
"start": start,
"granularity": granularity
}
if end:
params["end"] = end
if frequency:
params["frequency"] = frequency
if per_page:
params["perPage"] = per_page
if page:
params["page"] = page
url = self.__append_url_params(url, params)
r = requests.get(url, headers=headers)
return r.json() | [
"def",
"get_samples",
"(",
"self",
",",
"sensor_id",
",",
"start",
",",
"granularity",
",",
"end",
"=",
"None",
",",
"frequency",
"=",
"None",
",",
"per_page",
"=",
"None",
",",
"page",
"=",
"None",
",",
"full",
"=",
"False",
")",
":",
"url",
"=",
... | Get a sensor's samples for a specified time interval.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
start (string): ISO 8601 start time of sampling; depends on the
``granularity`` parameter value, the maximum supported time ranges are:
1 day for minutes or hours granularities, 1 month for days,
6 months for weeks, 1 year for months granularity, and 10 years for
years granularity
granularity (string): granularity of the sampled data; must be one of
"minutes", "hours", "days", "weeks", "months", or "years"
end (string, optional): ISO 8601 stop time for sampling; should be later
than start time (default: the current time)
frequency (string, optional): frequency of the sampled data (e.g. with
granularity set to days, a value of 3 will result in a sample for every
third day, should be a multiple of 5 when using minutes granularity)
(default: 1) (example: "1, 5")
per_page (string, optional): the number of returned results per page
(min 1, max 500) (default: 10)
page (string, optional): the page number to return (min 1, max 100000)
(default: 1)
full (bool, optional): include additional information per sample
(default: False)
Returns:
list: dictionary objects containing sample data | [
"Get",
"a",
"sensor",
"s",
"samples",
"for",
"a",
"specified",
"time",
"interval",
"."
] | train | https://github.com/jordanh/neurio-python/blob/3a1bcadadb3bb3ad48f2df41c039d8b828ffd9c8/neurio/__init__.py#L460-L514 |
jordanh/neurio-python | neurio/__init__.py | Client.get_user_information | def get_user_information(self):
"""Gets the current user information, including sensor ID
Args:
None
Returns:
dictionary object containing information about the current user
"""
url = "https://api.neur.io/v1/users/current"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
r = requests.get(url, headers=headers)
return r.json() | python | def get_user_information(self):
"""Gets the current user information, including sensor ID
Args:
None
Returns:
dictionary object containing information about the current user
"""
url = "https://api.neur.io/v1/users/current"
headers = self.__gen_headers()
headers["Content-Type"] = "application/json"
r = requests.get(url, headers=headers)
return r.json() | [
"def",
"get_user_information",
"(",
"self",
")",
":",
"url",
"=",
"\"https://api.neur.io/v1/users/current\"",
"headers",
"=",
"self",
".",
"__gen_headers",
"(",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"application/json\"",
"r",
"=",
"requests",
".",
"... | Gets the current user information, including sensor ID
Args:
None
Returns:
dictionary object containing information about the current user | [
"Gets",
"the",
"current",
"user",
"information",
"including",
"sensor",
"ID"
] | train | https://github.com/jordanh/neurio-python/blob/3a1bcadadb3bb3ad48f2df41c039d8b828ffd9c8/neurio/__init__.py#L572-L587 |
flo-compbio/genometools | genometools/expression/visualize/heatmap.py | ExpHeatmap.get_figure | def get_figure(
self, emin=None, emax=None,
width=800, height=400,
margin_left=100, margin_bottom=60, margin_top=30, margin_right=0,
colorbar_size=0.4,
xaxis_label=None, yaxis_label=None,
xaxis_nticks=None, yaxis_nticks=None,
xtick_angle=30,
font='"Droid Serif", "Open Serif", serif',
font_size=12, title_font_size=None,
show_sample_labels=True, **kwargs):
"""Generate a plotly figure of the heatmap.
Parameters
----------
emin : int, float, or None, optional
The expression value corresponding to the lower end of the
colorscale. If None, determine, automatically. [None]
emax : int, float, or None, optional
The expression value corresponding to the upper end of the
colorscale. If None, determine automatically. [None]
margin_left : int, optional
The size of the left margin (in px). [100]
margin_right : int, optional
The size of the right margin (in px). [0]
margin_top : int, optional
The size of the top margin (in px). [30]
margin_bottom : int, optional
The size of the bottom margin (in px). [60]
colorbar_size : int or float, optional
The sze of the colorbar, relative to the figure size. [0.4]
xaxis_label : str or None, optional
X-axis label. If None, use `ExpMatrix` default. [None]
yaxis_label : str or None, optional
y-axis label. If None, use `ExpMatrix` default. [None]
xtick_angle : int or float, optional
X-axis tick angle (in degrees). [30]
font : str, optional
Name of font to use. Can be multiple, separated by comma, to
specify a prioritized list.
[' "Droid Serif", "Open Serif", "serif"']
font_size : int or float, optional
Font size to use throughout the figure, in points. [12]
title_font_size : int or float or None, optional
Font size to use for labels on axes and the colorbar. If None,
use `font_size` value. [None]
show_sample_labels : bool, optional
Whether to show the sample labels. [True]
Returns
-------
`plotly.graph_objs.Figure`
The plotly figure.
"""
# emin and/or emax are unspecified, set to data min/max values
if emax is None:
emax = self.matrix.X.max()
if emin is None:
emin = self.matrix.X.min()
title = self.title
if title_font_size is None:
title_font_size = font_size
colorbar_label = self.colorbar_label or 'Expression'
colorbar = go.ColorBar(
lenmode='fraction',
len=colorbar_size,
title=colorbar_label,
titlefont=dict(
size=title_font_size,
),
titleside='right',
xpad=0,
ypad=0,
outlinewidth=0, # no border
thickness=20, # in pixels
# outlinecolor = '#000000',
)
def fix_plotly_label_bug(labels):
"""
This fixes a bug whereby plotly treats labels that look
like numbers (integers or floats) as numeric instead of
categorical, even when they are passed as strings. The fix consists
of appending an underscore to any label that looks like a number.
"""
assert isinstance(labels, Iterable)
fixed_labels = []
for l in labels:
try:
float(l)
except (ValueError, TypeError):
fixed_labels.append(str(l))
else:
fixed_labels.append(str(l) + '_')
return fixed_labels
x = fix_plotly_label_bug(self.matrix.samples)
gene_labels = self.matrix.genes.tolist()
if self.gene_aliases:
for i, gene in enumerate(gene_labels):
try:
alias = self.gene_aliases[gene]
except KeyError:
pass
else:
gene_labels[i] = '%s/%s' % (gene, alias)
gene_labels = fix_plotly_label_bug(gene_labels)
data = [
go.Heatmap(
z=self.matrix.X,
x=x,
y=gene_labels,
zmin=emin,
zmax=emax,
colorscale=self.colorscale,
colorbar=colorbar,
hoverinfo='x+y+z',
**kwargs
),
]
xticks = 'outside'
if not show_sample_labels:
xticks = ''
if xaxis_label is None:
if self.matrix.samples.name is not None:
xaxis_label = self.matrix.samples.name
else:
xaxis_label = 'Samples'
xaxis_label = xaxis_label + ' (n = %d)' % self.matrix.n
if yaxis_label is None:
if self.matrix.genes.name is not None:
yaxis_label = self.matrix.genes.name
else:
yaxis_label = 'Genes'
yaxis_label = yaxis_label + ' (p = %d)' % self.matrix.p
layout = go.Layout(
width=width,
height=height,
title=title,
titlefont=go.Font(
size=title_font_size
),
font=go.Font(
size=font_size,
family=font
),
xaxis=go.XAxis(
title=xaxis_label,
titlefont=dict(size=title_font_size),
showticklabels=show_sample_labels,
ticks=xticks,
nticks=xaxis_nticks,
tickangle=xtick_angle,
showline=True
),
yaxis=go.YAxis(
title=yaxis_label,
titlefont=dict(size=title_font_size),
nticks=yaxis_nticks,
autorange='reversed',
showline=True
),
margin=go.Margin(
l=margin_left,
t=margin_top,
b=margin_bottom,
r=margin_right,
pad=0
),
)
# add annotations
# we need separate, but overlaying, axes to place the annotations
layout['xaxis2'] = go.XAxis(
overlaying = 'x',
showline = False,
tickfont = dict(size=0),
autorange=False,
range=[-0.5, self.matrix.n-0.5],
ticks='',
showticklabels=False
)
layout['yaxis2'] = go.YAxis(
overlaying='y',
showline=False,
tickfont=dict(size=0),
autorange=False,
range=[self.matrix.p-0.5, -0.5],
ticks='',
showticklabels=False
)
# gene (row) annotations
for ann in self.gene_annotations:
i = self.matrix.genes.get_loc(ann.gene)
xmn = -0.5
xmx = self.matrix.n-0.5
ymn = i-0.5
ymx = i+0.5
#logger.debug('Transparency is %.1f', ann.transparency)
data.append(
go.Scatter(
x=[xmn, xmx, xmx, xmn, xmn],
y=[ymn, ymn, ymx, ymx, ymn],
mode='lines',
hoverinfo='none',
showlegend=False,
line=dict(color=ann.color),
xaxis='x2',
yaxis='y2',
#opacity=0.5,
opacity=1-ann.transparency,
)
)
if ann.label is not None:
layout.annotations.append(
go.Annotation(
text=ann.label,
x=0.01,
y=i-0.5,
#y=i+0.5,
xref='paper',
yref='y2',
xanchor='left',
yanchor='bottom',
showarrow=False,
bgcolor='white',
#opacity=1-ann.transparency,
opacity=0.8,
borderpad=0,
#textangle=30,
font=dict(color=ann.color)
)
)
# sample (column) annotations
for ann in self.sample_annotations:
j = self.matrix.samples.get_loc(ann.sample)
xmn = j-0.5
xmx = j+0.5
ymn = -0.5
ymx = self.matrix.p-0.5
data.append(
go.Scatter(
x=[xmn, xmx, xmx, xmn, xmn],
y=[ymn, ymn, ymx, ymx, ymn],
mode='lines',
hoverinfo='none',
showlegend=False,
line=dict(color=ann.color),
xaxis='x2',
yaxis='y2',
opacity=1.0)
)
if ann.label is not None:
layout.annotations.append(
go.Annotation(
text=ann.label,
y=0.99,
x=j+0.5,
#y=i+0.5,
xref='x2',
yref='paper',
xanchor='left',
yanchor='top',
showarrow=False,
bgcolor='white',
opacity=1-ann.transparency,
borderpad=0,
textangle=90,
font=dict(color=ann.color)
)
)
fig = go.Figure(
data=data,
layout=layout
)
return fig | python | def get_figure(
self, emin=None, emax=None,
width=800, height=400,
margin_left=100, margin_bottom=60, margin_top=30, margin_right=0,
colorbar_size=0.4,
xaxis_label=None, yaxis_label=None,
xaxis_nticks=None, yaxis_nticks=None,
xtick_angle=30,
font='"Droid Serif", "Open Serif", serif',
font_size=12, title_font_size=None,
show_sample_labels=True, **kwargs):
"""Generate a plotly figure of the heatmap.
Parameters
----------
emin : int, float, or None, optional
The expression value corresponding to the lower end of the
colorscale. If None, determine, automatically. [None]
emax : int, float, or None, optional
The expression value corresponding to the upper end of the
colorscale. If None, determine automatically. [None]
margin_left : int, optional
The size of the left margin (in px). [100]
margin_right : int, optional
The size of the right margin (in px). [0]
margin_top : int, optional
The size of the top margin (in px). [30]
margin_bottom : int, optional
The size of the bottom margin (in px). [60]
colorbar_size : int or float, optional
The sze of the colorbar, relative to the figure size. [0.4]
xaxis_label : str or None, optional
X-axis label. If None, use `ExpMatrix` default. [None]
yaxis_label : str or None, optional
y-axis label. If None, use `ExpMatrix` default. [None]
xtick_angle : int or float, optional
X-axis tick angle (in degrees). [30]
font : str, optional
Name of font to use. Can be multiple, separated by comma, to
specify a prioritized list.
[' "Droid Serif", "Open Serif", "serif"']
font_size : int or float, optional
Font size to use throughout the figure, in points. [12]
title_font_size : int or float or None, optional
Font size to use for labels on axes and the colorbar. If None,
use `font_size` value. [None]
show_sample_labels : bool, optional
Whether to show the sample labels. [True]
Returns
-------
`plotly.graph_objs.Figure`
The plotly figure.
"""
# emin and/or emax are unspecified, set to data min/max values
if emax is None:
emax = self.matrix.X.max()
if emin is None:
emin = self.matrix.X.min()
title = self.title
if title_font_size is None:
title_font_size = font_size
colorbar_label = self.colorbar_label or 'Expression'
colorbar = go.ColorBar(
lenmode='fraction',
len=colorbar_size,
title=colorbar_label,
titlefont=dict(
size=title_font_size,
),
titleside='right',
xpad=0,
ypad=0,
outlinewidth=0, # no border
thickness=20, # in pixels
# outlinecolor = '#000000',
)
def fix_plotly_label_bug(labels):
"""
This fixes a bug whereby plotly treats labels that look
like numbers (integers or floats) as numeric instead of
categorical, even when they are passed as strings. The fix consists
of appending an underscore to any label that looks like a number.
"""
assert isinstance(labels, Iterable)
fixed_labels = []
for l in labels:
try:
float(l)
except (ValueError, TypeError):
fixed_labels.append(str(l))
else:
fixed_labels.append(str(l) + '_')
return fixed_labels
x = fix_plotly_label_bug(self.matrix.samples)
gene_labels = self.matrix.genes.tolist()
if self.gene_aliases:
for i, gene in enumerate(gene_labels):
try:
alias = self.gene_aliases[gene]
except KeyError:
pass
else:
gene_labels[i] = '%s/%s' % (gene, alias)
gene_labels = fix_plotly_label_bug(gene_labels)
data = [
go.Heatmap(
z=self.matrix.X,
x=x,
y=gene_labels,
zmin=emin,
zmax=emax,
colorscale=self.colorscale,
colorbar=colorbar,
hoverinfo='x+y+z',
**kwargs
),
]
xticks = 'outside'
if not show_sample_labels:
xticks = ''
if xaxis_label is None:
if self.matrix.samples.name is not None:
xaxis_label = self.matrix.samples.name
else:
xaxis_label = 'Samples'
xaxis_label = xaxis_label + ' (n = %d)' % self.matrix.n
if yaxis_label is None:
if self.matrix.genes.name is not None:
yaxis_label = self.matrix.genes.name
else:
yaxis_label = 'Genes'
yaxis_label = yaxis_label + ' (p = %d)' % self.matrix.p
layout = go.Layout(
width=width,
height=height,
title=title,
titlefont=go.Font(
size=title_font_size
),
font=go.Font(
size=font_size,
family=font
),
xaxis=go.XAxis(
title=xaxis_label,
titlefont=dict(size=title_font_size),
showticklabels=show_sample_labels,
ticks=xticks,
nticks=xaxis_nticks,
tickangle=xtick_angle,
showline=True
),
yaxis=go.YAxis(
title=yaxis_label,
titlefont=dict(size=title_font_size),
nticks=yaxis_nticks,
autorange='reversed',
showline=True
),
margin=go.Margin(
l=margin_left,
t=margin_top,
b=margin_bottom,
r=margin_right,
pad=0
),
)
# add annotations
# we need separate, but overlaying, axes to place the annotations
layout['xaxis2'] = go.XAxis(
overlaying = 'x',
showline = False,
tickfont = dict(size=0),
autorange=False,
range=[-0.5, self.matrix.n-0.5],
ticks='',
showticklabels=False
)
layout['yaxis2'] = go.YAxis(
overlaying='y',
showline=False,
tickfont=dict(size=0),
autorange=False,
range=[self.matrix.p-0.5, -0.5],
ticks='',
showticklabels=False
)
# gene (row) annotations
for ann in self.gene_annotations:
i = self.matrix.genes.get_loc(ann.gene)
xmn = -0.5
xmx = self.matrix.n-0.5
ymn = i-0.5
ymx = i+0.5
#logger.debug('Transparency is %.1f', ann.transparency)
data.append(
go.Scatter(
x=[xmn, xmx, xmx, xmn, xmn],
y=[ymn, ymn, ymx, ymx, ymn],
mode='lines',
hoverinfo='none',
showlegend=False,
line=dict(color=ann.color),
xaxis='x2',
yaxis='y2',
#opacity=0.5,
opacity=1-ann.transparency,
)
)
if ann.label is not None:
layout.annotations.append(
go.Annotation(
text=ann.label,
x=0.01,
y=i-0.5,
#y=i+0.5,
xref='paper',
yref='y2',
xanchor='left',
yanchor='bottom',
showarrow=False,
bgcolor='white',
#opacity=1-ann.transparency,
opacity=0.8,
borderpad=0,
#textangle=30,
font=dict(color=ann.color)
)
)
# sample (column) annotations
for ann in self.sample_annotations:
j = self.matrix.samples.get_loc(ann.sample)
xmn = j-0.5
xmx = j+0.5
ymn = -0.5
ymx = self.matrix.p-0.5
data.append(
go.Scatter(
x=[xmn, xmx, xmx, xmn, xmn],
y=[ymn, ymn, ymx, ymx, ymn],
mode='lines',
hoverinfo='none',
showlegend=False,
line=dict(color=ann.color),
xaxis='x2',
yaxis='y2',
opacity=1.0)
)
if ann.label is not None:
layout.annotations.append(
go.Annotation(
text=ann.label,
y=0.99,
x=j+0.5,
#y=i+0.5,
xref='x2',
yref='paper',
xanchor='left',
yanchor='top',
showarrow=False,
bgcolor='white',
opacity=1-ann.transparency,
borderpad=0,
textangle=90,
font=dict(color=ann.color)
)
)
fig = go.Figure(
data=data,
layout=layout
)
return fig | [
"def",
"get_figure",
"(",
"self",
",",
"emin",
"=",
"None",
",",
"emax",
"=",
"None",
",",
"width",
"=",
"800",
",",
"height",
"=",
"400",
",",
"margin_left",
"=",
"100",
",",
"margin_bottom",
"=",
"60",
",",
"margin_top",
"=",
"30",
",",
"margin_rig... | Generate a plotly figure of the heatmap.
Parameters
----------
emin : int, float, or None, optional
The expression value corresponding to the lower end of the
colorscale. If None, determine, automatically. [None]
emax : int, float, or None, optional
The expression value corresponding to the upper end of the
colorscale. If None, determine automatically. [None]
margin_left : int, optional
The size of the left margin (in px). [100]
margin_right : int, optional
The size of the right margin (in px). [0]
margin_top : int, optional
The size of the top margin (in px). [30]
margin_bottom : int, optional
The size of the bottom margin (in px). [60]
colorbar_size : int or float, optional
The sze of the colorbar, relative to the figure size. [0.4]
xaxis_label : str or None, optional
X-axis label. If None, use `ExpMatrix` default. [None]
yaxis_label : str or None, optional
y-axis label. If None, use `ExpMatrix` default. [None]
xtick_angle : int or float, optional
X-axis tick angle (in degrees). [30]
font : str, optional
Name of font to use. Can be multiple, separated by comma, to
specify a prioritized list.
[' "Droid Serif", "Open Serif", "serif"']
font_size : int or float, optional
Font size to use throughout the figure, in points. [12]
title_font_size : int or float or None, optional
Font size to use for labels on axes and the colorbar. If None,
use `font_size` value. [None]
show_sample_labels : bool, optional
Whether to show the sample labels. [True]
Returns
-------
`plotly.graph_objs.Figure`
The plotly figure. | [
"Generate",
"a",
"plotly",
"figure",
"of",
"the",
"heatmap",
".",
"Parameters",
"----------",
"emin",
":",
"int",
"float",
"or",
"None",
"optional",
"The",
"expression",
"value",
"corresponding",
"to",
"the",
"lower",
"end",
"of",
"the",
"colorscale",
".",
"... | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/expression/visualize/heatmap.py#L117-L413 |
openfisca/openfisca-web-api | openfisca_web_api/controllers/formula.py | api2_formula | def api2_formula(req):
"""
A simple `GET`-, URL-based API to OpenFisca, making the assumption of computing formulas for a single person.
Combination
-----------
You can compute several formulas at once by combining the paths and joining them with `+`.
Example:
```
/salaire_super_brut+salaire_net_a_payer?salaire_de_base=1440
```
This will compute both `salaire_super_brut` and `salaire_net_a_payer` in a single request.
Reforms
-----------
Reforms can be requested to patch the simulation system.
To keep this endpoint URL simple, they are requested as a list in a custom HTTP header.
```
X-OpenFisca-Extensions: de_net_a_brut, landais_piketty_saez
```
This header is of course optional.
URL size limit
--------------
Using combination with a lot of parameters may lead to long URLs.
If used within the browser, make sure the resulting URL is kept
[under 2047 characters](http://stackoverflow.com/questions/417142)
for cross-browser compatibility, by splitting combined requests.
On a server, just test what your library handles.
"""
API_VERSION = '2.1.0'
wsgihelpers.track(req.url.decode('utf-8'))
params = dict(req.GET)
data = dict()
try:
extensions_header = req.headers.get('X-Openfisca-Extensions')
tax_benefit_system = model.get_cached_composed_reform(
reform_keys = extensions_header.split(','),
tax_benefit_system = model.tax_benefit_system,
) if extensions_header is not None else model.tax_benefit_system
params = normalize(params, tax_benefit_system)
formula_names = req.urlvars.get('names').split('+')
data['values'] = dict()
data['period'] = parse_period(req.urlvars.get('period'))
simulation = create_simulation(params, data['period'], tax_benefit_system)
for formula_name in formula_names:
column = get_column_from_formula_name(formula_name, tax_benefit_system)
data['values'][formula_name] = compute(column.name, simulation)
except Exception as error:
if isinstance(error.args[0], dict): # we raised it ourselves, in this controller
error = error.args[0]
else:
error = dict(
message = unicode(error),
code = 500
)
data['error'] = error
finally:
return respond(req, API_VERSION, data, params) | python | def api2_formula(req):
"""
A simple `GET`-, URL-based API to OpenFisca, making the assumption of computing formulas for a single person.
Combination
-----------
You can compute several formulas at once by combining the paths and joining them with `+`.
Example:
```
/salaire_super_brut+salaire_net_a_payer?salaire_de_base=1440
```
This will compute both `salaire_super_brut` and `salaire_net_a_payer` in a single request.
Reforms
-----------
Reforms can be requested to patch the simulation system.
To keep this endpoint URL simple, they are requested as a list in a custom HTTP header.
```
X-OpenFisca-Extensions: de_net_a_brut, landais_piketty_saez
```
This header is of course optional.
URL size limit
--------------
Using combination with a lot of parameters may lead to long URLs.
If used within the browser, make sure the resulting URL is kept
[under 2047 characters](http://stackoverflow.com/questions/417142)
for cross-browser compatibility, by splitting combined requests.
On a server, just test what your library handles.
"""
API_VERSION = '2.1.0'
wsgihelpers.track(req.url.decode('utf-8'))
params = dict(req.GET)
data = dict()
try:
extensions_header = req.headers.get('X-Openfisca-Extensions')
tax_benefit_system = model.get_cached_composed_reform(
reform_keys = extensions_header.split(','),
tax_benefit_system = model.tax_benefit_system,
) if extensions_header is not None else model.tax_benefit_system
params = normalize(params, tax_benefit_system)
formula_names = req.urlvars.get('names').split('+')
data['values'] = dict()
data['period'] = parse_period(req.urlvars.get('period'))
simulation = create_simulation(params, data['period'], tax_benefit_system)
for formula_name in formula_names:
column = get_column_from_formula_name(formula_name, tax_benefit_system)
data['values'][formula_name] = compute(column.name, simulation)
except Exception as error:
if isinstance(error.args[0], dict): # we raised it ourselves, in this controller
error = error.args[0]
else:
error = dict(
message = unicode(error),
code = 500
)
data['error'] = error
finally:
return respond(req, API_VERSION, data, params) | [
"def",
"api2_formula",
"(",
"req",
")",
":",
"API_VERSION",
"=",
"'2.1.0'",
"wsgihelpers",
".",
"track",
"(",
"req",
".",
"url",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"params",
"=",
"dict",
"(",
"req",
".",
"GET",
")",
"data",
"=",
"dict",
"(",
... | A simple `GET`-, URL-based API to OpenFisca, making the assumption of computing formulas for a single person.
Combination
-----------
You can compute several formulas at once by combining the paths and joining them with `+`.
Example:
```
/salaire_super_brut+salaire_net_a_payer?salaire_de_base=1440
```
This will compute both `salaire_super_brut` and `salaire_net_a_payer` in a single request.
Reforms
-----------
Reforms can be requested to patch the simulation system.
To keep this endpoint URL simple, they are requested as a list in a custom HTTP header.
```
X-OpenFisca-Extensions: de_net_a_brut, landais_piketty_saez
```
This header is of course optional.
URL size limit
--------------
Using combination with a lot of parameters may lead to long URLs.
If used within the browser, make sure the resulting URL is kept
[under 2047 characters](http://stackoverflow.com/questions/417142)
for cross-browser compatibility, by splitting combined requests.
On a server, just test what your library handles. | [
"A",
"simple",
"GET",
"-",
"URL",
"-",
"based",
"API",
"to",
"OpenFisca",
"making",
"the",
"assumption",
"of",
"computing",
"formulas",
"for",
"a",
"single",
"person",
"."
] | train | https://github.com/openfisca/openfisca-web-api/blob/d1cd3bfacac338e80bb0df7e0465b65649dd893b/openfisca_web_api/controllers/formula.py#L37-L109 |
nkavaldj/myhdl_lib | examples/pipeline_control_stop_tx.py | arithmetic_mean4 | def arithmetic_mean4(rst, clk, rx_rdy, rx_vld, rx_dat, tx_rdy, tx_vld, tx_dat):
''' Calculates the arithmetic mean of every 4 consecutive input numbers
Input handshake & data
rx_rdy - (o) Ready
rx_vld - (i) Valid
rx_dat - (i) Data
Output handshake & data
tx_rdy - (i) Ready
tx_vld - (o) Valid
tx_dat - (o) Data
Implementation: 3-stage pipeline
stage 0: registers input data
stage 1: sum each 4 consecutive numbers and produce the sum as a single result
stage 2: divide the sum by 4
Each stage is implemented as a separate process controlled by a central pipeline control unit via an enable signal
The pipeline control unit manages the handshake and synchronizes the operation of the stages
'''
DATA_WIDTH = len(rx_dat)
NUM_STAGES = 3
stage_en = Signal(intbv(0)[NUM_STAGES:])
stop_tx = Signal(intbv(0)[NUM_STAGES:])
pipe_ctrl = pipeline_control( rst = rst,
clk = clk,
rx_vld = rx_vld,
rx_rdy = rx_rdy,
tx_vld = tx_vld,
tx_rdy = tx_rdy,
stage_enable = stage_en,
stop_tx = stop_tx)
s0_dat = Signal(intbv(0)[DATA_WIDTH:])
@always_seq(clk.posedge, reset=rst)
def stage_0():
''' Register input data'''
if (stage_en[0]):
s0_dat.next = rx_dat
s1_sum = Signal(intbv(0)[DATA_WIDTH+2:])
s1_cnt = Signal(intbv(0, min=0, max=4))
@always(clk.posedge)
def stage_1():
''' Sum each 4 consecutive data'''
if (rst):
s1_cnt.next = 0
stop_tx.next[1] = 1
elif (stage_en[1]):
# Count input data
s1_cnt.next = (s1_cnt + 1) % 4
if (s1_cnt == 0):
s1_sum.next = s0_dat
else:
s1_sum.next = s1_sum.next + s0_dat
# Produce result only after data 0, 1, 2, and 3 have been summed
if (s1_cnt == 3):
stop_tx.next[1] = 0
else:
stop_tx.next[1] = 1
''' stop_tx[1] concerns the data currently registered in stage 1 - it determines whether
the data will be sent to the next pipeline stage (stop_tx==0) or will be dropped (stop_tx==1 ).
The signals stop_rx and stop_tx must be registered '''
s2_dat = Signal(intbv(0)[DATA_WIDTH:])
@always_seq(clk.posedge, reset=rst)
def stage_2():
''' Divide by 4'''
if (stage_en[2]):
s2_dat.next = s1_sum // 4
@always_comb
def comb():
tx_dat.next = s2_dat
return instances() | python | def arithmetic_mean4(rst, clk, rx_rdy, rx_vld, rx_dat, tx_rdy, tx_vld, tx_dat):
''' Calculates the arithmetic mean of every 4 consecutive input numbers
Input handshake & data
rx_rdy - (o) Ready
rx_vld - (i) Valid
rx_dat - (i) Data
Output handshake & data
tx_rdy - (i) Ready
tx_vld - (o) Valid
tx_dat - (o) Data
Implementation: 3-stage pipeline
stage 0: registers input data
stage 1: sum each 4 consecutive numbers and produce the sum as a single result
stage 2: divide the sum by 4
Each stage is implemented as a separate process controlled by a central pipeline control unit via an enable signal
The pipeline control unit manages the handshake and synchronizes the operation of the stages
'''
DATA_WIDTH = len(rx_dat)
NUM_STAGES = 3
stage_en = Signal(intbv(0)[NUM_STAGES:])
stop_tx = Signal(intbv(0)[NUM_STAGES:])
pipe_ctrl = pipeline_control( rst = rst,
clk = clk,
rx_vld = rx_vld,
rx_rdy = rx_rdy,
tx_vld = tx_vld,
tx_rdy = tx_rdy,
stage_enable = stage_en,
stop_tx = stop_tx)
s0_dat = Signal(intbv(0)[DATA_WIDTH:])
@always_seq(clk.posedge, reset=rst)
def stage_0():
''' Register input data'''
if (stage_en[0]):
s0_dat.next = rx_dat
s1_sum = Signal(intbv(0)[DATA_WIDTH+2:])
s1_cnt = Signal(intbv(0, min=0, max=4))
@always(clk.posedge)
def stage_1():
''' Sum each 4 consecutive data'''
if (rst):
s1_cnt.next = 0
stop_tx.next[1] = 1
elif (stage_en[1]):
# Count input data
s1_cnt.next = (s1_cnt + 1) % 4
if (s1_cnt == 0):
s1_sum.next = s0_dat
else:
s1_sum.next = s1_sum.next + s0_dat
# Produce result only after data 0, 1, 2, and 3 have been summed
if (s1_cnt == 3):
stop_tx.next[1] = 0
else:
stop_tx.next[1] = 1
''' stop_tx[1] concerns the data currently registered in stage 1 - it determines whether
the data will be sent to the next pipeline stage (stop_tx==0) or will be dropped (stop_tx==1 ).
The signals stop_rx and stop_tx must be registered '''
s2_dat = Signal(intbv(0)[DATA_WIDTH:])
@always_seq(clk.posedge, reset=rst)
def stage_2():
''' Divide by 4'''
if (stage_en[2]):
s2_dat.next = s1_sum // 4
@always_comb
def comb():
tx_dat.next = s2_dat
return instances() | [
"def",
"arithmetic_mean4",
"(",
"rst",
",",
"clk",
",",
"rx_rdy",
",",
"rx_vld",
",",
"rx_dat",
",",
"tx_rdy",
",",
"tx_vld",
",",
"tx_dat",
")",
":",
"DATA_WIDTH",
"=",
"len",
"(",
"rx_dat",
")",
"NUM_STAGES",
"=",
"3",
"stage_en",
"=",
"Signal",
"(",... | Calculates the arithmetic mean of every 4 consecutive input numbers
Input handshake & data
rx_rdy - (o) Ready
rx_vld - (i) Valid
rx_dat - (i) Data
Output handshake & data
tx_rdy - (i) Ready
tx_vld - (o) Valid
tx_dat - (o) Data
Implementation: 3-stage pipeline
stage 0: registers input data
stage 1: sum each 4 consecutive numbers and produce the sum as a single result
stage 2: divide the sum by 4
Each stage is implemented as a separate process controlled by a central pipeline control unit via an enable signal
The pipeline control unit manages the handshake and synchronizes the operation of the stages | [
"Calculates",
"the",
"arithmetic",
"mean",
"of",
"every",
"4",
"consecutive",
"input",
"numbers"
] | train | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/examples/pipeline_control_stop_tx.py#L7-L96 |
nkavaldj/myhdl_lib | examples/pipeline_control_stop_tx.py | pipeline_control_stop_tx | def pipeline_control_stop_tx():
''' Instantiates the arithmetic_mean4 pipeline, feeds it with data and drains its output '''
clk = sim.Clock(val=0, period=10, units="ns")
rst = sim.ResetSync(clk=clk, val=0, active=1)
rx_rdy, rx_vld, tx_rdy, tx_vld = [Signal(bool(0)) for _ in range(4)]
rx_dat = Signal(intbv(0)[8:])
tx_dat = Signal(intbv(0)[8:])
clkgen = clk.gen()
dut = arithmetic_mean4(rst, clk, rx_rdy, rx_vld, rx_dat, tx_rdy, tx_vld, tx_dat)
# dut = traceSignals(arithmetic_mean4, rst, clk, rx_rdy, rx_vld, rx_dat, tx_rdy, tx_vld, tx_dat)
drv = Driver(rst, clk, rx_rdy, rx_vld, rx_dat)
cap = Capture(rst, clk, tx_rdy, tx_vld, tx_dat)
data_in = []
data_out = []
def stim(GAP=0):
''' Stimulates the pipeline input '''
@instance
def _stim():
yield rst.pulse(10)
yield clk.posedge
for i in range(5*4):
yield drv.write(i)
data_in.append(i)
for _ in range(GAP):
yield clk.posedge
for _ in range(10):
yield clk.posedge
raise StopSimulation
return _stim
def drain(GAP=0):
''' Drains the pipeline output '''
@instance
def _drain():
yield clk.posedge
while True:
yield cap.read()
data_out.append(cap.d)
for _ in range(GAP):
yield clk.posedge
return _drain
# You can play with the gap size at the input and at the output to see how the pipeline responds (see time diagrams)
Simulation(clkgen, dut, stim(GAP=0), drain(GAP=0)).run()
print "data_in ({}): {}".format(len(data_in), data_in)
print "data_out ({}): {}".format(len(data_out), data_out)
data_out_expected = [sum(data_in[i:i+4])//4 for i in range(0, len(data_in), 4)]
assert cmp(data_out_expected, data_out)==0, "expected: data_out ({}): {}".format(len(data_out_expected), data_out_expected) | python | def pipeline_control_stop_tx():
''' Instantiates the arithmetic_mean4 pipeline, feeds it with data and drains its output '''
clk = sim.Clock(val=0, period=10, units="ns")
rst = sim.ResetSync(clk=clk, val=0, active=1)
rx_rdy, rx_vld, tx_rdy, tx_vld = [Signal(bool(0)) for _ in range(4)]
rx_dat = Signal(intbv(0)[8:])
tx_dat = Signal(intbv(0)[8:])
clkgen = clk.gen()
dut = arithmetic_mean4(rst, clk, rx_rdy, rx_vld, rx_dat, tx_rdy, tx_vld, tx_dat)
# dut = traceSignals(arithmetic_mean4, rst, clk, rx_rdy, rx_vld, rx_dat, tx_rdy, tx_vld, tx_dat)
drv = Driver(rst, clk, rx_rdy, rx_vld, rx_dat)
cap = Capture(rst, clk, tx_rdy, tx_vld, tx_dat)
data_in = []
data_out = []
def stim(GAP=0):
''' Stimulates the pipeline input '''
@instance
def _stim():
yield rst.pulse(10)
yield clk.posedge
for i in range(5*4):
yield drv.write(i)
data_in.append(i)
for _ in range(GAP):
yield clk.posedge
for _ in range(10):
yield clk.posedge
raise StopSimulation
return _stim
def drain(GAP=0):
''' Drains the pipeline output '''
@instance
def _drain():
yield clk.posedge
while True:
yield cap.read()
data_out.append(cap.d)
for _ in range(GAP):
yield clk.posedge
return _drain
# You can play with the gap size at the input and at the output to see how the pipeline responds (see time diagrams)
Simulation(clkgen, dut, stim(GAP=0), drain(GAP=0)).run()
print "data_in ({}): {}".format(len(data_in), data_in)
print "data_out ({}): {}".format(len(data_out), data_out)
data_out_expected = [sum(data_in[i:i+4])//4 for i in range(0, len(data_in), 4)]
assert cmp(data_out_expected, data_out)==0, "expected: data_out ({}): {}".format(len(data_out_expected), data_out_expected) | [
"def",
"pipeline_control_stop_tx",
"(",
")",
":",
"clk",
"=",
"sim",
".",
"Clock",
"(",
"val",
"=",
"0",
",",
"period",
"=",
"10",
",",
"units",
"=",
"\"ns\"",
")",
"rst",
"=",
"sim",
".",
"ResetSync",
"(",
"clk",
"=",
"clk",
",",
"val",
"=",
"0"... | Instantiates the arithmetic_mean4 pipeline, feeds it with data and drains its output | [
"Instantiates",
"the",
"arithmetic_mean4",
"pipeline",
"feeds",
"it",
"with",
"data",
"and",
"drains",
"its",
"output"
] | train | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/examples/pipeline_control_stop_tx.py#L152-L207 |
closeio/cleancat | cleancat/mongo.py | MongoEmbedded.clean | def clean(self, value):
"""Clean the provided dict of values and then return an
EmbeddedDocument instantiated with them.
"""
value = super(MongoEmbedded, self).clean(value)
return self.document_class(**value) | python | def clean(self, value):
"""Clean the provided dict of values and then return an
EmbeddedDocument instantiated with them.
"""
value = super(MongoEmbedded, self).clean(value)
return self.document_class(**value) | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"super",
"(",
"MongoEmbedded",
",",
"self",
")",
".",
"clean",
"(",
"value",
")",
"return",
"self",
".",
"document_class",
"(",
"*",
"*",
"value",
")"
] | Clean the provided dict of values and then return an
EmbeddedDocument instantiated with them. | [
"Clean",
"the",
"provided",
"dict",
"of",
"values",
"and",
"then",
"return",
"an",
"EmbeddedDocument",
"instantiated",
"with",
"them",
"."
] | train | https://github.com/closeio/cleancat/blob/59df1422b3ebea9477026ca80cd7af1ae9734d89/cleancat/mongo.py#L24-L29 |
closeio/cleancat | cleancat/mongo.py | MongoReference.fetch_object | def fetch_object(self, doc_id):
"""Fetch the document by its PK."""
try:
return self.object_class.objects.get(pk=doc_id)
except self.object_class.DoesNotExist:
raise ReferenceNotFoundError | python | def fetch_object(self, doc_id):
"""Fetch the document by its PK."""
try:
return self.object_class.objects.get(pk=doc_id)
except self.object_class.DoesNotExist:
raise ReferenceNotFoundError | [
"def",
"fetch_object",
"(",
"self",
",",
"doc_id",
")",
":",
"try",
":",
"return",
"self",
".",
"object_class",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"doc_id",
")",
"except",
"self",
".",
"object_class",
".",
"DoesNotExist",
":",
"raise",
"Referenc... | Fetch the document by its PK. | [
"Fetch",
"the",
"document",
"by",
"its",
"PK",
"."
] | train | https://github.com/closeio/cleancat/blob/59df1422b3ebea9477026ca80cd7af1ae9734d89/cleancat/mongo.py#L69-L74 |
flo-compbio/genometools | genometools/ncbi/geo/generate_sample_sheet.py | get_argument_parser | def get_argument_parser():
"""Create the argument parser for the script.
Parameters
----------
Returns
-------
`argparse.ArgumentParser`
The arguemnt parser.
"""
desc = 'Generate a sample sheet based on a GEO series matrix.'
parser = cli.get_argument_parser(desc=desc)
g = parser.add_argument_group('Input and output files')
g.add_argument(
'-s', '--series-matrix-file', type=cli.str_type, required=True,
metavar=cli.file_mv, help='The GEO series matrix file.'
)
g.add_argument(
'-o', '--output-file', type=cli.str_type,
required=True,
metavar=cli.file_mv, help='The output file.'
)
g.add_argument(
'-e', '--encoding', type=cli.str_type,
metavar=cli.str_mv, default='UTF-8',
help='The encoding of the series matrix file. [UTF-8]'
)
cli.add_reporting_args(parser)
return parser | python | def get_argument_parser():
"""Create the argument parser for the script.
Parameters
----------
Returns
-------
`argparse.ArgumentParser`
The arguemnt parser.
"""
desc = 'Generate a sample sheet based on a GEO series matrix.'
parser = cli.get_argument_parser(desc=desc)
g = parser.add_argument_group('Input and output files')
g.add_argument(
'-s', '--series-matrix-file', type=cli.str_type, required=True,
metavar=cli.file_mv, help='The GEO series matrix file.'
)
g.add_argument(
'-o', '--output-file', type=cli.str_type,
required=True,
metavar=cli.file_mv, help='The output file.'
)
g.add_argument(
'-e', '--encoding', type=cli.str_type,
metavar=cli.str_mv, default='UTF-8',
help='The encoding of the series matrix file. [UTF-8]'
)
cli.add_reporting_args(parser)
return parser | [
"def",
"get_argument_parser",
"(",
")",
":",
"desc",
"=",
"'Generate a sample sheet based on a GEO series matrix.'",
"parser",
"=",
"cli",
".",
"get_argument_parser",
"(",
"desc",
"=",
"desc",
")",
"g",
"=",
"parser",
".",
"add_argument_group",
"(",
"'Input and output... | Create the argument parser for the script.
Parameters
----------
Returns
-------
`argparse.ArgumentParser`
The arguemnt parser. | [
"Create",
"the",
"argument",
"parser",
"for",
"the",
"script",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/geo/generate_sample_sheet.py#L38-L73 |
flo-compbio/genometools | genometools/ncbi/geo/generate_sample_sheet.py | read_series_matrix | def read_series_matrix(path, encoding):
"""Read the series matrix."""
assert isinstance(path, str)
accessions = None
titles = None
celfile_urls = None
with misc.smart_open_read(path, mode='rb', try_gzip=True) as fh:
reader = csv.reader(fh, dialect='excel-tab', encoding=encoding)
for l in reader:
if not l:
continue
if l[0] == '!Sample_geo_accession':
accessions = l[1:]
elif l[0] == '!Sample_title':
titles = l[1:]
elif l[0] == '!Sample_supplementary_file' and celfile_urls is None:
celfile_urls = l[1:]
elif l[0] == '!series_matrix_table_begin':
# we've read the end of the section containing metadata
break
return accessions, titles, celfile_urls | python | def read_series_matrix(path, encoding):
"""Read the series matrix."""
assert isinstance(path, str)
accessions = None
titles = None
celfile_urls = None
with misc.smart_open_read(path, mode='rb', try_gzip=True) as fh:
reader = csv.reader(fh, dialect='excel-tab', encoding=encoding)
for l in reader:
if not l:
continue
if l[0] == '!Sample_geo_accession':
accessions = l[1:]
elif l[0] == '!Sample_title':
titles = l[1:]
elif l[0] == '!Sample_supplementary_file' and celfile_urls is None:
celfile_urls = l[1:]
elif l[0] == '!series_matrix_table_begin':
# we've read the end of the section containing metadata
break
return accessions, titles, celfile_urls | [
"def",
"read_series_matrix",
"(",
"path",
",",
"encoding",
")",
":",
"assert",
"isinstance",
"(",
"path",
",",
"str",
")",
"accessions",
"=",
"None",
"titles",
"=",
"None",
"celfile_urls",
"=",
"None",
"with",
"misc",
".",
"smart_open_read",
"(",
"path",
"... | Read the series matrix. | [
"Read",
"the",
"series",
"matrix",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/geo/generate_sample_sheet.py#L76-L97 |
flo-compbio/genometools | genometools/ncbi/geo/generate_sample_sheet.py | write_sample_sheet | def write_sample_sheet(path, accessions, names, celfile_urls, sel=None):
"""Write the sample sheet."""
with open(path, 'wb') as ofh:
writer = csv.writer(ofh, dialect='excel-tab',
lineterminator=os.linesep,
quoting=csv.QUOTE_NONE)
# write header
writer.writerow(['Accession', 'Name', 'CEL file', 'CEL file URL'])
n = len(names)
if sel is None:
sel = range(n)
for i in sel:
cf = celfile_urls[i].split('/')[-1]
# row = [accessions[i], names[i], cf, celfile_urls[i]]
writer.writerow([accessions[i], names[i], cf, celfile_urls[i]]) | python | def write_sample_sheet(path, accessions, names, celfile_urls, sel=None):
"""Write the sample sheet."""
with open(path, 'wb') as ofh:
writer = csv.writer(ofh, dialect='excel-tab',
lineterminator=os.linesep,
quoting=csv.QUOTE_NONE)
# write header
writer.writerow(['Accession', 'Name', 'CEL file', 'CEL file URL'])
n = len(names)
if sel is None:
sel = range(n)
for i in sel:
cf = celfile_urls[i].split('/')[-1]
# row = [accessions[i], names[i], cf, celfile_urls[i]]
writer.writerow([accessions[i], names[i], cf, celfile_urls[i]]) | [
"def",
"write_sample_sheet",
"(",
"path",
",",
"accessions",
",",
"names",
",",
"celfile_urls",
",",
"sel",
"=",
"None",
")",
":",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"ofh",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"ofh",
",",
... | Write the sample sheet. | [
"Write",
"the",
"sample",
"sheet",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/geo/generate_sample_sheet.py#L100-L114 |
flo-compbio/genometools | genometools/ncbi/geo/generate_sample_sheet.py | main | def main(args=None):
"""Script entry point."""
if args is None:
parser = get_argument_parser()
args = parser.parse_args()
#series_matrix_file = newstr(args.series_matrix_file, 'utf-8')
#output_file = newstr(args.output_file, 'utf-8')
#encoding = newstr(args.encoding, 'utf-8')
series_matrix_file = args.series_matrix_file
output_file = args.output_file
encoding = args.encoding
# log_file = args.log_file
# quiet = args.quiet
# verbose = args.verbose
# logger = misc.get_logger(log_file = log_file, quiet = quiet,
# verbose = verbose)
accessions, titles, celfile_urls = read_series_matrix(
series_matrix_file, encoding=encoding)
write_sample_sheet(output_file, accessions, titles, celfile_urls)
return 0 | python | def main(args=None):
"""Script entry point."""
if args is None:
parser = get_argument_parser()
args = parser.parse_args()
#series_matrix_file = newstr(args.series_matrix_file, 'utf-8')
#output_file = newstr(args.output_file, 'utf-8')
#encoding = newstr(args.encoding, 'utf-8')
series_matrix_file = args.series_matrix_file
output_file = args.output_file
encoding = args.encoding
# log_file = args.log_file
# quiet = args.quiet
# verbose = args.verbose
# logger = misc.get_logger(log_file = log_file, quiet = quiet,
# verbose = verbose)
accessions, titles, celfile_urls = read_series_matrix(
series_matrix_file, encoding=encoding)
write_sample_sheet(output_file, accessions, titles, celfile_urls)
return 0 | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"parser",
"=",
"get_argument_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"#series_matrix_file = newstr(args.series_matrix_file, 'utf-8')",
"#output_file ... | Script entry point. | [
"Script",
"entry",
"point",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ncbi/geo/generate_sample_sheet.py#L117-L142 |
inveniosoftware/invenio-jsonschemas | invenio_jsonschemas/views.py | create_blueprint | def create_blueprint(state):
"""Create blueprint serving JSON schemas.
:param state: :class:`invenio_jsonschemas.ext.InvenioJSONSchemasState`
instance used to retrieve the schemas.
"""
blueprint = Blueprint(
'invenio_jsonschemas',
__name__,
)
@blueprint.route('/<path:schema_path>')
def get_schema(schema_path):
"""Retrieve a schema."""
try:
schema_dir = state.get_schema_dir(schema_path)
except JSONSchemaNotFound:
abort(404)
resolved = request.args.get(
'resolved',
current_app.config.get('JSONSCHEMAS_RESOLVE_SCHEMA'),
type=int
)
with_refs = request.args.get(
'refs',
current_app.config.get('JSONSCHEMAS_REPLACE_REFS'),
type=int
) or resolved
if resolved or with_refs:
schema = state.get_schema(
schema_path,
with_refs=with_refs,
resolved=resolved
)
return jsonify(schema)
else:
return send_from_directory(schema_dir, schema_path)
return blueprint | python | def create_blueprint(state):
"""Create blueprint serving JSON schemas.
:param state: :class:`invenio_jsonschemas.ext.InvenioJSONSchemasState`
instance used to retrieve the schemas.
"""
blueprint = Blueprint(
'invenio_jsonschemas',
__name__,
)
@blueprint.route('/<path:schema_path>')
def get_schema(schema_path):
"""Retrieve a schema."""
try:
schema_dir = state.get_schema_dir(schema_path)
except JSONSchemaNotFound:
abort(404)
resolved = request.args.get(
'resolved',
current_app.config.get('JSONSCHEMAS_RESOLVE_SCHEMA'),
type=int
)
with_refs = request.args.get(
'refs',
current_app.config.get('JSONSCHEMAS_REPLACE_REFS'),
type=int
) or resolved
if resolved or with_refs:
schema = state.get_schema(
schema_path,
with_refs=with_refs,
resolved=resolved
)
return jsonify(schema)
else:
return send_from_directory(schema_dir, schema_path)
return blueprint | [
"def",
"create_blueprint",
"(",
"state",
")",
":",
"blueprint",
"=",
"Blueprint",
"(",
"'invenio_jsonschemas'",
",",
"__name__",
",",
")",
"@",
"blueprint",
".",
"route",
"(",
"'/<path:schema_path>'",
")",
"def",
"get_schema",
"(",
"schema_path",
")",
":",
"\"... | Create blueprint serving JSON schemas.
:param state: :class:`invenio_jsonschemas.ext.InvenioJSONSchemasState`
instance used to retrieve the schemas. | [
"Create",
"blueprint",
"serving",
"JSON",
"schemas",
"."
] | train | https://github.com/inveniosoftware/invenio-jsonschemas/blob/93019b8fe3bf549335e94c84198c9c0b76d8fde2/invenio_jsonschemas/views.py#L23-L64 |
flo-compbio/genometools | genometools/gdc/download.py | download_files | def download_files(manifest, download_dir, auth_token=None,
chunk_size=1048576, avoid_redownload=True):
"""Individually download files from GDC.
Params
------
manifest : `pandas.DataFrame`
GDC manifest that contains a list of files. The data frame should
have five columns: id, filename, md5, size, and state.
download_dir : str
The path of the download directory.
auth_token : str, optional
Authentication token for downloading protected data.
If None, do not send authentication header. [None]
chunk_size : int, optional
The chunk size (in bytes) to use for downloading data. [1048576]
Returns
-------
None
"""
assert isinstance(manifest, pd.DataFrame)
assert isinstance(download_dir, str)
assert isinstance(chunk_size, int)
if auth_token is not None:
assert isinstance(auth_token, str)
def get_file_md5hash(path):
"""Calculate the MD5 hash for a file."""
with open(path, 'rb') as fh:
h = hashlib.md5(fh.read()).hexdigest()
return h
headers = {}
if auth_token is not None:
headers['X-Auth-Token'] = auth_token
#payload = {'ids': file_ids}
#logger.info('Downloading data to "%s"...', download_dir)
num_files = manifest.shape[0]
logger.info('Downloading %d files to "%s"...', num_files, download_dir)
for i, row in manifest.iterrows():
#(uuid, (file_name, file_hash))
success = False
download_file = os.path.join(download_dir, row['filename'])
if ((i+1) % 100) == 0:
logger.info('Downloading file %d / %d...', i+1, num_files)
if avoid_redownload and os.path.isfile(download_file) and \
get_file_md5hash(download_file) == row['md5']:
logger.info('File %s already downloaded...skipping.',
download_file)
success = True
while not success:
with closing(
requests.get('https://gdc-api.nci.nih.gov/data/%s'
% row['id'], headers=headers, stream=True)) \
as r:
# get suggested file name from "Content-Disposition" header
# suggested_file_name = re.findall(
# "filename=(.+)", r.headers['Content-Disposition'])[0]
r.raise_for_status()
with open(download_file, 'wb') as ofh:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
ofh.write(chunk)
with open(download_file, 'rb') as fh:
h = hashlib.md5(fh.read()).hexdigest()
if h == row['md5']:
success = True
if not success:
logger.warning('Hash value mismatch (should be: %s; is: %s). '
'Attempting to re-download file...',
row['md5'], h) | python | def download_files(manifest, download_dir, auth_token=None,
chunk_size=1048576, avoid_redownload=True):
"""Individually download files from GDC.
Params
------
manifest : `pandas.DataFrame`
GDC manifest that contains a list of files. The data frame should
have five columns: id, filename, md5, size, and state.
download_dir : str
The path of the download directory.
auth_token : str, optional
Authentication token for downloading protected data.
If None, do not send authentication header. [None]
chunk_size : int, optional
The chunk size (in bytes) to use for downloading data. [1048576]
Returns
-------
None
"""
assert isinstance(manifest, pd.DataFrame)
assert isinstance(download_dir, str)
assert isinstance(chunk_size, int)
if auth_token is not None:
assert isinstance(auth_token, str)
def get_file_md5hash(path):
"""Calculate the MD5 hash for a file."""
with open(path, 'rb') as fh:
h = hashlib.md5(fh.read()).hexdigest()
return h
headers = {}
if auth_token is not None:
headers['X-Auth-Token'] = auth_token
#payload = {'ids': file_ids}
#logger.info('Downloading data to "%s"...', download_dir)
num_files = manifest.shape[0]
logger.info('Downloading %d files to "%s"...', num_files, download_dir)
for i, row in manifest.iterrows():
#(uuid, (file_name, file_hash))
success = False
download_file = os.path.join(download_dir, row['filename'])
if ((i+1) % 100) == 0:
logger.info('Downloading file %d / %d...', i+1, num_files)
if avoid_redownload and os.path.isfile(download_file) and \
get_file_md5hash(download_file) == row['md5']:
logger.info('File %s already downloaded...skipping.',
download_file)
success = True
while not success:
with closing(
requests.get('https://gdc-api.nci.nih.gov/data/%s'
% row['id'], headers=headers, stream=True)) \
as r:
# get suggested file name from "Content-Disposition" header
# suggested_file_name = re.findall(
# "filename=(.+)", r.headers['Content-Disposition'])[0]
r.raise_for_status()
with open(download_file, 'wb') as ofh:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
ofh.write(chunk)
with open(download_file, 'rb') as fh:
h = hashlib.md5(fh.read()).hexdigest()
if h == row['md5']:
success = True
if not success:
logger.warning('Hash value mismatch (should be: %s; is: %s). '
'Attempting to re-download file...',
row['md5'], h) | [
"def",
"download_files",
"(",
"manifest",
",",
"download_dir",
",",
"auth_token",
"=",
"None",
",",
"chunk_size",
"=",
"1048576",
",",
"avoid_redownload",
"=",
"True",
")",
":",
"assert",
"isinstance",
"(",
"manifest",
",",
"pd",
".",
"DataFrame",
")",
"asse... | Individually download files from GDC.
Params
------
manifest : `pandas.DataFrame`
GDC manifest that contains a list of files. The data frame should
have five columns: id, filename, md5, size, and state.
download_dir : str
The path of the download directory.
auth_token : str, optional
Authentication token for downloading protected data.
If None, do not send authentication header. [None]
chunk_size : int, optional
The chunk size (in bytes) to use for downloading data. [1048576]
Returns
-------
None | [
"Individually",
"download",
"files",
"from",
"GDC",
".",
"Params",
"------",
"manifest",
":",
"pandas",
".",
"DataFrame",
"GDC",
"manifest",
"that",
"contains",
"a",
"list",
"of",
"files",
".",
"The",
"data",
"frame",
"should",
"have",
"five",
"columns",
":"... | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/gdc/download.py#L36-L112 |
acorg/dark-matter | dark/blast/records.py | printBlastRecord | def printBlastRecord(record):
"""
Print a BLAST record.
@param record: A BioPython C{Bio.Blast.Record.Blast} instance.
"""
for key in sorted(record.__dict__.keys()):
if key not in ['alignments', 'descriptions', 'reference']:
print('%s: %r' % (key, record.__dict__[key]))
print('alignments: (%d in total):' % len(record.alignments))
for i, alignment in enumerate(record.alignments):
print(' description %d:' % (i + 1))
for attr in ['accession', 'bits', 'e', 'num_alignments', 'score']:
print(' %s: %s' % (attr, getattr(record.descriptions[i], attr)))
print(' alignment %d:' % (i + 1))
for attr in 'accession', 'hit_def', 'hit_id', 'length', 'title':
print(' %s: %s' % (attr, getattr(alignment, attr)))
print(' HSPs (%d in total):' % len(alignment.hsps))
for hspIndex, hsp in enumerate(alignment.hsps, start=1):
print(' hsp %d:' % hspIndex)
printHSP(hsp, ' ') | python | def printBlastRecord(record):
"""
Print a BLAST record.
@param record: A BioPython C{Bio.Blast.Record.Blast} instance.
"""
for key in sorted(record.__dict__.keys()):
if key not in ['alignments', 'descriptions', 'reference']:
print('%s: %r' % (key, record.__dict__[key]))
print('alignments: (%d in total):' % len(record.alignments))
for i, alignment in enumerate(record.alignments):
print(' description %d:' % (i + 1))
for attr in ['accession', 'bits', 'e', 'num_alignments', 'score']:
print(' %s: %s' % (attr, getattr(record.descriptions[i], attr)))
print(' alignment %d:' % (i + 1))
for attr in 'accession', 'hit_def', 'hit_id', 'length', 'title':
print(' %s: %s' % (attr, getattr(alignment, attr)))
print(' HSPs (%d in total):' % len(alignment.hsps))
for hspIndex, hsp in enumerate(alignment.hsps, start=1):
print(' hsp %d:' % hspIndex)
printHSP(hsp, ' ') | [
"def",
"printBlastRecord",
"(",
"record",
")",
":",
"for",
"key",
"in",
"sorted",
"(",
"record",
".",
"__dict__",
".",
"keys",
"(",
")",
")",
":",
"if",
"key",
"not",
"in",
"[",
"'alignments'",
",",
"'descriptions'",
",",
"'reference'",
"]",
":",
"prin... | Print a BLAST record.
@param record: A BioPython C{Bio.Blast.Record.Blast} instance. | [
"Print",
"a",
"BLAST",
"record",
"."
] | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/records.py#L4-L24 |
acorg/dark-matter | dark/blast/hsp.py | normalizeHSP | def normalizeHSP(hsp, readLen, blastApplication):
"""
Examine an HSP and return information about where the query and subject
match begins and ends. Return a dict with keys that allow the query to
be displayed against the subject. The returned readStartInSubject and
readEndInSubject indices are offsets into the subject. I.e., they
indicate where in the subject the query falls.
In the returned object, all indices are suitable for Python string
slicing etc. We must be careful to convert from the 1-based offsets
found in BLAST output properly.
hsp['frame'] is a (query, subject) 2-tuple, with both values coming from
{-3, -2, -1, 1, 2, 3}. The sign indicates negative or positive sense
(i.e., the direction of reading through the query or subject to get the
alignment). The value is the nucleotide match offset modulo 3, plus one
(i.e., it tells us which of the 3 possible reading frames is used in
the match). The value is redundant because that information could also
be obtained from the mod 3 value of the match offset.
NOTE: the returned readStartInSubject value may be negative. We consider
the hit sequence to start at offset 0. So if the read string has
sufficient additional nucleotides before the start of the alignment
match, it may protrude to the left of the hit. Similarly, the returned
readEndInSubject can be greater than the subjectEnd.
@param hsp: an HSP in the form of a C{dict}, built from a BLAST record.
All passed hsp offsets are 1-based.
@param readLen: the length of the read sequence.
@param blastApplication: The C{str} command line program that was
run (e.g., 'blastn', 'blastx').
"""
def debugPrint(locals, msg=None):
"""
Print debugging information showing the local variables from
a call to normalizeHSP and then raise an C{AssertionError}.
@param locals: A C{dict} of local variables.
@param msg: A C{str} message to raise C{AssertionError} with.
"""
print('normalizeHSP error:')
print(' readLen: %d' % readLen)
for var in sorted(locals.keys()):
if var in ('debugPrint', 'hsp'):
continue
print(' %s: %s' % (var, locals[var]))
print(' Original HSP:')
printHSP(hsp, ' ')
if msg:
raise AssertionError(msg)
else:
raise AssertionError()
readPositive = hsp['frame'][0] > 0
hitPositive = hsp['frame'][1] > 0
# The following variable names with underscores match the names of
# attributes BioPython uses and the values (1-based) match those
# reported by BLAST.
read_start = hsp['query_start']
read_end = hsp['query_end']
sbjct_start = hsp['sbjct_start']
sbjct_end = hsp['sbjct_end']
# When the read is positive, BLASTN and TBLASTX give read offsets
# ascending.
#
# TBLASTX reports negative read sense with indices ascending.
# BLASTN does not report negative read sense.
#
# In all cases the read offsets should be ascending.
if read_start > read_end:
debugPrint(locals(),
'Assertion "read_start <= read_end" failed. Read '
'positive is %s. read_start = %d, read_end = %d' %
(readPositive, read_start, read_end))
if hitPositive:
# Make sure indices are ascending.
if sbjct_start > sbjct_end:
debugPrint(locals())
else:
# Hit is negative. Its indices will be ascending for TBLASTX
# output but descending for BLASTN :-( Make sure we have them
# ascending.
if sbjct_start > sbjct_end:
sbjct_start, sbjct_end = sbjct_end, sbjct_start
# Now that we have asserted what we can about the original HSP values
# and gotten them into ascending order, make some sane 0-based offsets.
readStartInSubject = read_start - 1
readEndInSubject = read_end
subjectStart = sbjct_start - 1
subjectEnd = sbjct_end
if blastApplication == 'blastx':
# In Blastx output, hit offsets are based on protein sequence
# length but queries (and the reported offsets) are nucleotide.
# Convert the read offsets to protein because we will plot against
# the hit (protein).
#
# Note that readStartInSubject and readEndInSubject may not be 0 mod
# 3. They are offsets into the read string giving the position of
# the AA, which depends on the translation frame.
readStartInSubject = int(readStartInSubject / 3)
readEndInSubject = int(readEndInSubject / 3)
# No operations on original 1-based HSP variables (with underscores)
# should appear beyond this point.
subjectLength = subjectEnd - subjectStart
readLength = readEndInSubject - readStartInSubject
# NOTE: readLength (above) is a really bad name. It's actually going to
# hold the length of the match in the query. I don't know why
# readEndInSubject - readStartInSubject is used (I mean why those two
# variables are not named readEnd and readStart). Maybe someone made a
# find and replace editing error which changed their names. Anyway, the
# readLength variable is confusingly named because this function is
# passed a 'readLen' argument, which does happen to be the full length
# of the read. This should be cleaned up. See ../diamond/hsp.py for
# something cleaner.
hitGaps = hsp['sbjct'].count('-')
readGaps = hsp['query'].count('-')
# Sanity check that the length of the matches in the hit and read
# are identical, taking into account gaps in either (indicated by '-'
# characters in the match sequences, as returned by BLAST).
subjectLengthWithGaps = subjectLength + hitGaps
readLengthWithGaps = readLength + readGaps
if subjectLengthWithGaps != readLengthWithGaps:
debugPrint(locals(),
'Including gaps, hit match length (%d) != Read match '
'length (%d)' % (subjectLengthWithGaps,
readLengthWithGaps))
# TODO: check the mod 3 value of the start offsets.
# Calculate read indices. These are indices relative to the hit!
# unmatchedReadLeft is the number of read bases that will be sticking
# out to the left of the start of the hit in our plots.
if readPositive:
unmatchedReadLeft = readStartInSubject
else:
unmatchedReadLeft = readLen - readEndInSubject
# Set the read offsets based on the direction the match with the
# hit takes.
if hitPositive:
readStartInSubject = subjectStart - unmatchedReadLeft
readEndInSubject = readStartInSubject + readLen + readGaps
else:
readEndInSubject = subjectEnd + unmatchedReadLeft
readStartInSubject = readEndInSubject - readLen - readGaps
# Final sanity checks.
if readStartInSubject > subjectStart:
debugPrint(locals(), 'readStartInSubject > subjectStart')
if readEndInSubject < subjectEnd:
debugPrint(locals(), 'readEndInSubject < subjectEnd')
return {
'readStart': read_start - 1,
'readEnd': read_end,
'readStartInSubject': readStartInSubject,
'readEndInSubject': readEndInSubject,
'subjectStart': subjectStart,
'subjectEnd': subjectEnd,
} | python | def normalizeHSP(hsp, readLen, blastApplication):
"""
Examine an HSP and return information about where the query and subject
match begins and ends. Return a dict with keys that allow the query to
be displayed against the subject. The returned readStartInSubject and
readEndInSubject indices are offsets into the subject. I.e., they
indicate where in the subject the query falls.
In the returned object, all indices are suitable for Python string
slicing etc. We must be careful to convert from the 1-based offsets
found in BLAST output properly.
hsp['frame'] is a (query, subject) 2-tuple, with both values coming from
{-3, -2, -1, 1, 2, 3}. The sign indicates negative or positive sense
(i.e., the direction of reading through the query or subject to get the
alignment). The value is the nucleotide match offset modulo 3, plus one
(i.e., it tells us which of the 3 possible reading frames is used in
the match). The value is redundant because that information could also
be obtained from the mod 3 value of the match offset.
NOTE: the returned readStartInSubject value may be negative. We consider
the hit sequence to start at offset 0. So if the read string has
sufficient additional nucleotides before the start of the alignment
match, it may protrude to the left of the hit. Similarly, the returned
readEndInSubject can be greater than the subjectEnd.
@param hsp: an HSP in the form of a C{dict}, built from a BLAST record.
All passed hsp offsets are 1-based.
@param readLen: the length of the read sequence.
@param blastApplication: The C{str} command line program that was
run (e.g., 'blastn', 'blastx').
"""
def debugPrint(locals, msg=None):
"""
Print debugging information showing the local variables from
a call to normalizeHSP and then raise an C{AssertionError}.
@param locals: A C{dict} of local variables.
@param msg: A C{str} message to raise C{AssertionError} with.
"""
print('normalizeHSP error:')
print(' readLen: %d' % readLen)
for var in sorted(locals.keys()):
if var in ('debugPrint', 'hsp'):
continue
print(' %s: %s' % (var, locals[var]))
print(' Original HSP:')
printHSP(hsp, ' ')
if msg:
raise AssertionError(msg)
else:
raise AssertionError()
readPositive = hsp['frame'][0] > 0
hitPositive = hsp['frame'][1] > 0
# The following variable names with underscores match the names of
# attributes BioPython uses and the values (1-based) match those
# reported by BLAST.
read_start = hsp['query_start']
read_end = hsp['query_end']
sbjct_start = hsp['sbjct_start']
sbjct_end = hsp['sbjct_end']
# When the read is positive, BLASTN and TBLASTX give read offsets
# ascending.
#
# TBLASTX reports negative read sense with indices ascending.
# BLASTN does not report negative read sense.
#
# In all cases the read offsets should be ascending.
if read_start > read_end:
debugPrint(locals(),
'Assertion "read_start <= read_end" failed. Read '
'positive is %s. read_start = %d, read_end = %d' %
(readPositive, read_start, read_end))
if hitPositive:
# Make sure indices are ascending.
if sbjct_start > sbjct_end:
debugPrint(locals())
else:
# Hit is negative. Its indices will be ascending for TBLASTX
# output but descending for BLASTN :-( Make sure we have them
# ascending.
if sbjct_start > sbjct_end:
sbjct_start, sbjct_end = sbjct_end, sbjct_start
# Now that we have asserted what we can about the original HSP values
# and gotten them into ascending order, make some sane 0-based offsets.
readStartInSubject = read_start - 1
readEndInSubject = read_end
subjectStart = sbjct_start - 1
subjectEnd = sbjct_end
if blastApplication == 'blastx':
# In Blastx output, hit offsets are based on protein sequence
# length but queries (and the reported offsets) are nucleotide.
# Convert the read offsets to protein because we will plot against
# the hit (protein).
#
# Note that readStartInSubject and readEndInSubject may not be 0 mod
# 3. They are offsets into the read string giving the position of
# the AA, which depends on the translation frame.
readStartInSubject = int(readStartInSubject / 3)
readEndInSubject = int(readEndInSubject / 3)
# No operations on original 1-based HSP variables (with underscores)
# should appear beyond this point.
subjectLength = subjectEnd - subjectStart
readLength = readEndInSubject - readStartInSubject
# NOTE: readLength (above) is a really bad name. It's actually going to
# hold the length of the match in the query. I don't know why
# readEndInSubject - readStartInSubject is used (I mean why those two
# variables are not named readEnd and readStart). Maybe someone made a
# find and replace editing error which changed their names. Anyway, the
# readLength variable is confusingly named because this function is
# passed a 'readLen' argument, which does happen to be the full length
# of the read. This should be cleaned up. See ../diamond/hsp.py for
# something cleaner.
hitGaps = hsp['sbjct'].count('-')
readGaps = hsp['query'].count('-')
# Sanity check that the length of the matches in the hit and read
# are identical, taking into account gaps in either (indicated by '-'
# characters in the match sequences, as returned by BLAST).
subjectLengthWithGaps = subjectLength + hitGaps
readLengthWithGaps = readLength + readGaps
if subjectLengthWithGaps != readLengthWithGaps:
debugPrint(locals(),
'Including gaps, hit match length (%d) != Read match '
'length (%d)' % (subjectLengthWithGaps,
readLengthWithGaps))
# TODO: check the mod 3 value of the start offsets.
# Calculate read indices. These are indices relative to the hit!
# unmatchedReadLeft is the number of read bases that will be sticking
# out to the left of the start of the hit in our plots.
if readPositive:
unmatchedReadLeft = readStartInSubject
else:
unmatchedReadLeft = readLen - readEndInSubject
# Set the read offsets based on the direction the match with the
# hit takes.
if hitPositive:
readStartInSubject = subjectStart - unmatchedReadLeft
readEndInSubject = readStartInSubject + readLen + readGaps
else:
readEndInSubject = subjectEnd + unmatchedReadLeft
readStartInSubject = readEndInSubject - readLen - readGaps
# Final sanity checks.
if readStartInSubject > subjectStart:
debugPrint(locals(), 'readStartInSubject > subjectStart')
if readEndInSubject < subjectEnd:
debugPrint(locals(), 'readEndInSubject < subjectEnd')
return {
'readStart': read_start - 1,
'readEnd': read_end,
'readStartInSubject': readStartInSubject,
'readEndInSubject': readEndInSubject,
'subjectStart': subjectStart,
'subjectEnd': subjectEnd,
} | [
"def",
"normalizeHSP",
"(",
"hsp",
",",
"readLen",
",",
"blastApplication",
")",
":",
"def",
"debugPrint",
"(",
"locals",
",",
"msg",
"=",
"None",
")",
":",
"\"\"\"\n Print debugging information showing the local variables from\n a call to normalizeHSP and then ... | Examine an HSP and return information about where the query and subject
match begins and ends. Return a dict with keys that allow the query to
be displayed against the subject. The returned readStartInSubject and
readEndInSubject indices are offsets into the subject. I.e., they
indicate where in the subject the query falls.
In the returned object, all indices are suitable for Python string
slicing etc. We must be careful to convert from the 1-based offsets
found in BLAST output properly.
hsp['frame'] is a (query, subject) 2-tuple, with both values coming from
{-3, -2, -1, 1, 2, 3}. The sign indicates negative or positive sense
(i.e., the direction of reading through the query or subject to get the
alignment). The value is the nucleotide match offset modulo 3, plus one
(i.e., it tells us which of the 3 possible reading frames is used in
the match). The value is redundant because that information could also
be obtained from the mod 3 value of the match offset.
NOTE: the returned readStartInSubject value may be negative. We consider
the hit sequence to start at offset 0. So if the read string has
sufficient additional nucleotides before the start of the alignment
match, it may protrude to the left of the hit. Similarly, the returned
readEndInSubject can be greater than the subjectEnd.
@param hsp: an HSP in the form of a C{dict}, built from a BLAST record.
All passed hsp offsets are 1-based.
@param readLen: the length of the read sequence.
@param blastApplication: The C{str} command line program that was
run (e.g., 'blastn', 'blastx'). | [
"Examine",
"an",
"HSP",
"and",
"return",
"information",
"about",
"where",
"the",
"query",
"and",
"subject",
"match",
"begins",
"and",
"ends",
".",
"Return",
"a",
"dict",
"with",
"keys",
"that",
"allow",
"the",
"query",
"to",
"be",
"displayed",
"against",
"... | train | https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/blast/hsp.py#L7-L180 |
flo-compbio/genometools | genometools/ontology/gaf.py | parse_gaf | def parse_gaf(path_or_buffer, gene_ontology, valid_genes=None,
db=None, ev_codes=None):
"""Parse a GAF 2.1 file containing GO annotations.
Parameters
----------
path_or_buffer : str or buffer
The GAF file.
gene_ontology : `GeneOntology`
The Gene Ontology.
valid_genes : Iterable of str, optional
A list of valid gene names. [None]
db : str, optional
Select only annotations with this "DB"" value. [None]
ev_codes : str or set of str, optional
Select only annotations with this/these evidence codes. [None]
Returns
-------
list of `GOAnnotation`
The list of GO annotations.
"""
#if path == '-':
# path = sys.stdin
assert isinstance(gene_ontology, GeneOntology)
if db is not None:
assert isinstance(db, (str, _oldstr))
if (ev_codes is not None) and ev_codes:
assert isinstance(ev_codes, (str, _oldstr)) or \
isinstance(ev_codes, Iterable)
if isinstance(ev_codes, str):
ev_codes = set([ev_codes])
elif (ev_codes is not None) and ev_codes:
ev_codes = set(ev_codes)
else:
ev_codes = None
# open file, if necessary
if isinstance(path_or_buffer, (str, _oldstr)):
buffer = misc.gzip_open_text(path_or_buffer, encoding='ascii')
else:
buffer = path_or_buffer
if valid_genes is not None:
valid_genes = set(valid_genes)
# use pandas to parse the file quickly
df = pd.read_csv(buffer, sep='\t', comment='!', header=None, dtype=_oldstr)
# replace pandas' NaNs with empty strings
df.fillna('', inplace=True)
# exclude annotations with unknown Gene Ontology terms
all_go_term_ids = set(gene_ontology._term_dict.keys())
sel = df.iloc[:, 4].isin(all_go_term_ids)
logger.info(
'Ignoring %d / %d annotations (%.1f %%) with unknown GO terms.',
(~sel).sum(), sel.size, 100*((~sel).sum()/float(sel.size)))
df = df.loc[sel]
# filter rows for valid genes
if valid_genes is not None:
sel = df.iloc[:, 2].isin(valid_genes)
logger.info(
'Ignoring %d / %d annotations (%.1f %%) with unknown genes.',
(~sel).sum(), sel.size, 100*((~sel).sum()/float(sel.size)))
df = df.loc[sel]
# filter rows for DB value
if db is not None:
sel = (df.iloc[:, 0] == db)
logger.info(
'Excluding %d / %d annotations (%.1f %%) with wrong DB values.',
(~sel).sum(), sel.size, 100*((~sel).sum()/float(sel.size)))
df = df.loc[sel]
# filter rows for evidence value
if ev_codes is not None:
sel = (df.iloc[:, 6].isin(ev_codes))
logger.info(
'Excluding %d / %d annotations (%.1f %%) based on evidence code.',
(~sel).sum(), sel.size, 100*((~sel).sum()/float(sel.size)))
df = df.loc[sel]
# convert each row into a GOAnnotation object
go_annotations = []
for i, l in df.iterrows():
ann = GOAnnotation.from_list(gene_ontology, l.tolist())
go_annotations.append(ann)
logger.info('Read %d GO annotations.', len(go_annotations))
return go_annotations | python | def parse_gaf(path_or_buffer, gene_ontology, valid_genes=None,
db=None, ev_codes=None):
"""Parse a GAF 2.1 file containing GO annotations.
Parameters
----------
path_or_buffer : str or buffer
The GAF file.
gene_ontology : `GeneOntology`
The Gene Ontology.
valid_genes : Iterable of str, optional
A list of valid gene names. [None]
db : str, optional
Select only annotations with this "DB"" value. [None]
ev_codes : str or set of str, optional
Select only annotations with this/these evidence codes. [None]
Returns
-------
list of `GOAnnotation`
The list of GO annotations.
"""
#if path == '-':
# path = sys.stdin
assert isinstance(gene_ontology, GeneOntology)
if db is not None:
assert isinstance(db, (str, _oldstr))
if (ev_codes is not None) and ev_codes:
assert isinstance(ev_codes, (str, _oldstr)) or \
isinstance(ev_codes, Iterable)
if isinstance(ev_codes, str):
ev_codes = set([ev_codes])
elif (ev_codes is not None) and ev_codes:
ev_codes = set(ev_codes)
else:
ev_codes = None
# open file, if necessary
if isinstance(path_or_buffer, (str, _oldstr)):
buffer = misc.gzip_open_text(path_or_buffer, encoding='ascii')
else:
buffer = path_or_buffer
if valid_genes is not None:
valid_genes = set(valid_genes)
# use pandas to parse the file quickly
df = pd.read_csv(buffer, sep='\t', comment='!', header=None, dtype=_oldstr)
# replace pandas' NaNs with empty strings
df.fillna('', inplace=True)
# exclude annotations with unknown Gene Ontology terms
all_go_term_ids = set(gene_ontology._term_dict.keys())
sel = df.iloc[:, 4].isin(all_go_term_ids)
logger.info(
'Ignoring %d / %d annotations (%.1f %%) with unknown GO terms.',
(~sel).sum(), sel.size, 100*((~sel).sum()/float(sel.size)))
df = df.loc[sel]
# filter rows for valid genes
if valid_genes is not None:
sel = df.iloc[:, 2].isin(valid_genes)
logger.info(
'Ignoring %d / %d annotations (%.1f %%) with unknown genes.',
(~sel).sum(), sel.size, 100*((~sel).sum()/float(sel.size)))
df = df.loc[sel]
# filter rows for DB value
if db is not None:
sel = (df.iloc[:, 0] == db)
logger.info(
'Excluding %d / %d annotations (%.1f %%) with wrong DB values.',
(~sel).sum(), sel.size, 100*((~sel).sum()/float(sel.size)))
df = df.loc[sel]
# filter rows for evidence value
if ev_codes is not None:
sel = (df.iloc[:, 6].isin(ev_codes))
logger.info(
'Excluding %d / %d annotations (%.1f %%) based on evidence code.',
(~sel).sum(), sel.size, 100*((~sel).sum()/float(sel.size)))
df = df.loc[sel]
# convert each row into a GOAnnotation object
go_annotations = []
for i, l in df.iterrows():
ann = GOAnnotation.from_list(gene_ontology, l.tolist())
go_annotations.append(ann)
logger.info('Read %d GO annotations.', len(go_annotations))
return go_annotations | [
"def",
"parse_gaf",
"(",
"path_or_buffer",
",",
"gene_ontology",
",",
"valid_genes",
"=",
"None",
",",
"db",
"=",
"None",
",",
"ev_codes",
"=",
"None",
")",
":",
"#if path == '-':",
"# path = sys.stdin",
"assert",
"isinstance",
"(",
"gene_ontology",
",",
"Gen... | Parse a GAF 2.1 file containing GO annotations.
Parameters
----------
path_or_buffer : str or buffer
The GAF file.
gene_ontology : `GeneOntology`
The Gene Ontology.
valid_genes : Iterable of str, optional
A list of valid gene names. [None]
db : str, optional
Select only annotations with this "DB"" value. [None]
ev_codes : str or set of str, optional
Select only annotations with this/these evidence codes. [None]
Returns
-------
list of `GOAnnotation`
The list of GO annotations. | [
"Parse",
"a",
"GAF",
"2",
".",
"1",
"file",
"containing",
"GO",
"annotations",
".",
"Parameters",
"----------",
"path_or_buffer",
":",
"str",
"or",
"buffer",
"The",
"GAF",
"file",
".",
"gene_ontology",
":",
"GeneOntology",
"The",
"Gene",
"Ontology",
".",
"va... | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/gaf.py#L40-L133 |
flo-compbio/genometools | genometools/ontology/gaf.py | get_goa_gene_sets | def get_goa_gene_sets(go_annotations):
"""Generate a list of gene sets from a collection of GO annotations.
Each gene set corresponds to all genes annotated with a certain GO term.
"""
go_term_genes = OrderedDict()
term_ids = {}
for ann in go_annotations:
term_ids[ann.go_term.id] = ann.go_term
try:
go_term_genes[ann.go_term.id].append(ann.db_symbol)
except KeyError:
go_term_genes[ann.go_term.id] = [ann.db_symbol]
go_term_genes = OrderedDict(sorted(go_term_genes.items()))
gene_sets = []
for tid, genes in go_term_genes.items():
go_term = term_ids[tid]
gs = GeneSet(id=tid, name=go_term.name, genes=genes,
source='GO',
collection=go_term.domain_short,
description=go_term.definition)
gene_sets.append(gs)
gene_sets = GeneSetCollection(gene_sets)
return gene_sets | python | def get_goa_gene_sets(go_annotations):
"""Generate a list of gene sets from a collection of GO annotations.
Each gene set corresponds to all genes annotated with a certain GO term.
"""
go_term_genes = OrderedDict()
term_ids = {}
for ann in go_annotations:
term_ids[ann.go_term.id] = ann.go_term
try:
go_term_genes[ann.go_term.id].append(ann.db_symbol)
except KeyError:
go_term_genes[ann.go_term.id] = [ann.db_symbol]
go_term_genes = OrderedDict(sorted(go_term_genes.items()))
gene_sets = []
for tid, genes in go_term_genes.items():
go_term = term_ids[tid]
gs = GeneSet(id=tid, name=go_term.name, genes=genes,
source='GO',
collection=go_term.domain_short,
description=go_term.definition)
gene_sets.append(gs)
gene_sets = GeneSetCollection(gene_sets)
return gene_sets | [
"def",
"get_goa_gene_sets",
"(",
"go_annotations",
")",
":",
"go_term_genes",
"=",
"OrderedDict",
"(",
")",
"term_ids",
"=",
"{",
"}",
"for",
"ann",
"in",
"go_annotations",
":",
"term_ids",
"[",
"ann",
".",
"go_term",
".",
"id",
"]",
"=",
"ann",
".",
"go... | Generate a list of gene sets from a collection of GO annotations.
Each gene set corresponds to all genes annotated with a certain GO term. | [
"Generate",
"a",
"list",
"of",
"gene",
"sets",
"from",
"a",
"collection",
"of",
"GO",
"annotations",
"."
] | train | https://github.com/flo-compbio/genometools/blob/dd962bb26d60a0f14ca14d8c9a4dd75768962c7d/genometools/ontology/gaf.py#L136-L160 |
nkavaldj/myhdl_lib | myhdl_lib/pipeline_control.py | pipeline_control | def pipeline_control(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_enable, stop_rx=None, stop_tx=None):
""" Synchronizes data flow in a processing pipeline.
rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline)
tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back of the pipeline)
stage_enable - (o) vector of enable signals, one signal per stage, that controls the data registration in the stages;
The length of this vector determines the number of stages in the pipeline
stop_rx - (i) optional, vector of signals, one signal per stage; when asserted, the corresponding stage stops consuming data;
allows for multicycle execution in a stage (e.g. consume a data, then process it multiple cycles)
stop_tx - (i) optional, vector of signals, one signal per stage; when asserted, the corresponding stage stops producing data;
allows for multicycle execution in a stage (consume multiple data to produce single data )
stop_rx and stop_tx - If you do not need them, then do not connect them
"""
NUM_STAGES = len(stage_enable)
if (stop_rx == None):
stop_rx = Signal(intbv(0)[NUM_STAGES:])
if (stop_tx == None):
stop_tx = Signal(intbv(0)[NUM_STAGES:])
assert (len(stop_rx)==NUM_STAGES), "pipeline_control: expects len(stop_rx)=len(stage_enable), but len(stop_rx)={} len(stage_enable)={}".format(len(stop_rx),NUM_STAGES)
assert (len(stop_tx)==NUM_STAGES), "pipeline_control: expects len(stop_tx)=len(stage_enable), but len(stop_tx)={} len(stage_enable)={}".format(len(stop_tx),NUM_STAGES)
vld_reg = Signal(intbv(0)[NUM_STAGES:])
vld = Signal(intbv(0)[NUM_STAGES:])
rdy = Signal(intbv(0)[NUM_STAGES:])
rdy_s = Signal(intbv(0)[NUM_STAGES:])
@always_seq(clk.posedge, reset=rst)
def regs():
for s in range(NUM_STAGES):
if rdy[s]:
vld_reg.next[s] = vld[s]
@always_comb
def comb_chain():
vld.next[0] = rx_vld or stop_rx[0]
rdy.next[NUM_STAGES-1] = tx_rdy or stop_tx[NUM_STAGES-1] or not vld_reg[NUM_STAGES-1]
for i in range(1,NUM_STAGES):
vld.next[i] = (vld_reg[i-1] and not stop_tx[i-1]) or stop_rx[i]
rdy.next[NUM_STAGES-1-i] = (rdy_s[NUM_STAGES-1-i+1] and not stop_rx[NUM_STAGES-1-i+1]) or stop_tx[NUM_STAGES-1-i]
@always_comb
def comb_assign():
tx_vld.next = vld_reg[NUM_STAGES-1] and not stop_tx[NUM_STAGES-1]
rx_rdy.next = rdy[0] and not stop_rx[0]
stage_enable.next = vld[NUM_STAGES:] & rdy[NUM_STAGES:]
rdy_s.next = rdy
return instances() | python | def pipeline_control(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_enable, stop_rx=None, stop_tx=None):
""" Synchronizes data flow in a processing pipeline.
rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline)
tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back of the pipeline)
stage_enable - (o) vector of enable signals, one signal per stage, that controls the data registration in the stages;
The length of this vector determines the number of stages in the pipeline
stop_rx - (i) optional, vector of signals, one signal per stage; when asserted, the corresponding stage stops consuming data;
allows for multicycle execution in a stage (e.g. consume a data, then process it multiple cycles)
stop_tx - (i) optional, vector of signals, one signal per stage; when asserted, the corresponding stage stops producing data;
allows for multicycle execution in a stage (consume multiple data to produce single data )
stop_rx and stop_tx - If you do not need them, then do not connect them
"""
NUM_STAGES = len(stage_enable)
if (stop_rx == None):
stop_rx = Signal(intbv(0)[NUM_STAGES:])
if (stop_tx == None):
stop_tx = Signal(intbv(0)[NUM_STAGES:])
assert (len(stop_rx)==NUM_STAGES), "pipeline_control: expects len(stop_rx)=len(stage_enable), but len(stop_rx)={} len(stage_enable)={}".format(len(stop_rx),NUM_STAGES)
assert (len(stop_tx)==NUM_STAGES), "pipeline_control: expects len(stop_tx)=len(stage_enable), but len(stop_tx)={} len(stage_enable)={}".format(len(stop_tx),NUM_STAGES)
vld_reg = Signal(intbv(0)[NUM_STAGES:])
vld = Signal(intbv(0)[NUM_STAGES:])
rdy = Signal(intbv(0)[NUM_STAGES:])
rdy_s = Signal(intbv(0)[NUM_STAGES:])
@always_seq(clk.posedge, reset=rst)
def regs():
for s in range(NUM_STAGES):
if rdy[s]:
vld_reg.next[s] = vld[s]
@always_comb
def comb_chain():
vld.next[0] = rx_vld or stop_rx[0]
rdy.next[NUM_STAGES-1] = tx_rdy or stop_tx[NUM_STAGES-1] or not vld_reg[NUM_STAGES-1]
for i in range(1,NUM_STAGES):
vld.next[i] = (vld_reg[i-1] and not stop_tx[i-1]) or stop_rx[i]
rdy.next[NUM_STAGES-1-i] = (rdy_s[NUM_STAGES-1-i+1] and not stop_rx[NUM_STAGES-1-i+1]) or stop_tx[NUM_STAGES-1-i]
@always_comb
def comb_assign():
tx_vld.next = vld_reg[NUM_STAGES-1] and not stop_tx[NUM_STAGES-1]
rx_rdy.next = rdy[0] and not stop_rx[0]
stage_enable.next = vld[NUM_STAGES:] & rdy[NUM_STAGES:]
rdy_s.next = rdy
return instances() | [
"def",
"pipeline_control",
"(",
"rst",
",",
"clk",
",",
"rx_rdy",
",",
"rx_vld",
",",
"tx_rdy",
",",
"tx_vld",
",",
"stage_enable",
",",
"stop_rx",
"=",
"None",
",",
"stop_tx",
"=",
"None",
")",
":",
"NUM_STAGES",
"=",
"len",
"(",
"stage_enable",
")",
... | Synchronizes data flow in a processing pipeline.
rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline)
tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back of the pipeline)
stage_enable - (o) vector of enable signals, one signal per stage, that controls the data registration in the stages;
The length of this vector determines the number of stages in the pipeline
stop_rx - (i) optional, vector of signals, one signal per stage; when asserted, the corresponding stage stops consuming data;
allows for multicycle execution in a stage (e.g. consume a data, then process it multiple cycles)
stop_tx - (i) optional, vector of signals, one signal per stage; when asserted, the corresponding stage stops producing data;
allows for multicycle execution in a stage (consume multiple data to produce single data )
stop_rx and stop_tx - If you do not need them, then do not connect them | [
"Synchronizes",
"data",
"flow",
"in",
"a",
"processing",
"pipeline",
".",
"rx_rdy",
"rx_vld",
"-",
"(",
"o",
")",
"(",
"i",
")",
"handshake",
"at",
"the",
"pipeline",
"input",
"(",
"front",
"of",
"the",
"pipeline",
")",
"tx_rdy",
"tx_vld",
"-",
"(",
"i... | train | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/pipeline_control.py#L4-L56 |
nkavaldj/myhdl_lib | myhdl_lib/pipeline_control.py | pipeline_control_new | def pipeline_control_new(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_enable, stop_rx=None, stop_tx=None):
""" Pipeline control unit
rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline)
tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back of the pipeline)
stage_enable - (o) vector of enable signals, one signal per stage, that controls the data registration in the stages;
The length of this vector determines the number of stages in the pipeline
stop_rx - (i) optional, vector of signals, one signal per stage; when asserted, the corresponding stage stops consuming data;
allows for multicycle execution in a stage (e.g. consume a data, then process it multiple cycles)
stop_tx - (i) optional, vector of signals, one signal per stage; when asserted, the corresponding stage stops producing data;
allows for multicycle execution in a stage (consume multiple data to produce single data )
stop_rx and stop_tx - If you do not need them, then do not connect them
"""
NUM_STAGES = len(stage_enable)
if (stop_rx == None):
stop_rx = Signal(intbv(0)[NUM_STAGES:])
if (stop_tx == None):
stop_tx = Signal(intbv(0)[NUM_STAGES:])
assert (len(stop_rx)==NUM_STAGES), "pipeline_control: expects len(stop_rx)=len(stage_enable), but len(stop_rx)={} len(stage_enable)={}".format(len(stop_rx),NUM_STAGES)
assert (len(stop_tx)==NUM_STAGES), "pipeline_control: expects len(stop_tx)=len(stage_enable), but len(stop_tx)={} len(stage_enable)={}".format(len(stop_tx),NUM_STAGES)
rdy = [Signal(bool(0)) for _ in range(NUM_STAGES+1)]
vld = [Signal(bool(0)) for _ in range(NUM_STAGES+1)]
BC = NUM_STAGES*[False]
en = [Signal(bool(0)) for _ in range(NUM_STAGES)]
stop_rx_s = [Signal(bool(0)) for _ in range(NUM_STAGES)]
stop_tx_s = [Signal(bool(0)) for _ in range(NUM_STAGES)]
rdy[0] = rx_rdy
vld[0] = rx_vld
rdy[-1] = tx_rdy
vld[-1] = tx_vld
BC[-1] = True
stg = [None for _ in range(NUM_STAGES)]
for i in range(NUM_STAGES):
stg[i] = _stage_ctrl(rst = rst,
clk = clk,
rx_rdy = rdy[i],
rx_vld = vld[i],
tx_rdy = rdy[i+1],
tx_vld = vld[i+1],
stage_en = en[i],
stop_rx = stop_rx_s[i],
stop_tx = stop_tx_s[i],
BC = BC[i])
x = en[0] if NUM_STAGES==1 else ConcatSignal(*reversed(en))
@always_comb
def _comb():
stage_enable.next = x
for i in range(NUM_STAGES):
stop_rx_s[i].next = stop_rx[i]
stop_tx_s[i].next = stop_tx[i]
return instances() | python | def pipeline_control_new(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_enable, stop_rx=None, stop_tx=None):
""" Pipeline control unit
rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline)
tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back of the pipeline)
stage_enable - (o) vector of enable signals, one signal per stage, that controls the data registration in the stages;
The length of this vector determines the number of stages in the pipeline
stop_rx - (i) optional, vector of signals, one signal per stage; when asserted, the corresponding stage stops consuming data;
allows for multicycle execution in a stage (e.g. consume a data, then process it multiple cycles)
stop_tx - (i) optional, vector of signals, one signal per stage; when asserted, the corresponding stage stops producing data;
allows for multicycle execution in a stage (consume multiple data to produce single data )
stop_rx and stop_tx - If you do not need them, then do not connect them
"""
NUM_STAGES = len(stage_enable)
if (stop_rx == None):
stop_rx = Signal(intbv(0)[NUM_STAGES:])
if (stop_tx == None):
stop_tx = Signal(intbv(0)[NUM_STAGES:])
assert (len(stop_rx)==NUM_STAGES), "pipeline_control: expects len(stop_rx)=len(stage_enable), but len(stop_rx)={} len(stage_enable)={}".format(len(stop_rx),NUM_STAGES)
assert (len(stop_tx)==NUM_STAGES), "pipeline_control: expects len(stop_tx)=len(stage_enable), but len(stop_tx)={} len(stage_enable)={}".format(len(stop_tx),NUM_STAGES)
rdy = [Signal(bool(0)) for _ in range(NUM_STAGES+1)]
vld = [Signal(bool(0)) for _ in range(NUM_STAGES+1)]
BC = NUM_STAGES*[False]
en = [Signal(bool(0)) for _ in range(NUM_STAGES)]
stop_rx_s = [Signal(bool(0)) for _ in range(NUM_STAGES)]
stop_tx_s = [Signal(bool(0)) for _ in range(NUM_STAGES)]
rdy[0] = rx_rdy
vld[0] = rx_vld
rdy[-1] = tx_rdy
vld[-1] = tx_vld
BC[-1] = True
stg = [None for _ in range(NUM_STAGES)]
for i in range(NUM_STAGES):
stg[i] = _stage_ctrl(rst = rst,
clk = clk,
rx_rdy = rdy[i],
rx_vld = vld[i],
tx_rdy = rdy[i+1],
tx_vld = vld[i+1],
stage_en = en[i],
stop_rx = stop_rx_s[i],
stop_tx = stop_tx_s[i],
BC = BC[i])
x = en[0] if NUM_STAGES==1 else ConcatSignal(*reversed(en))
@always_comb
def _comb():
stage_enable.next = x
for i in range(NUM_STAGES):
stop_rx_s[i].next = stop_rx[i]
stop_tx_s[i].next = stop_tx[i]
return instances() | [
"def",
"pipeline_control_new",
"(",
"rst",
",",
"clk",
",",
"rx_rdy",
",",
"rx_vld",
",",
"tx_rdy",
",",
"tx_vld",
",",
"stage_enable",
",",
"stop_rx",
"=",
"None",
",",
"stop_tx",
"=",
"None",
")",
":",
"NUM_STAGES",
"=",
"len",
"(",
"stage_enable",
")"... | Pipeline control unit
rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline)
tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back of the pipeline)
stage_enable - (o) vector of enable signals, one signal per stage, that controls the data registration in the stages;
The length of this vector determines the number of stages in the pipeline
stop_rx - (i) optional, vector of signals, one signal per stage; when asserted, the corresponding stage stops consuming data;
allows for multicycle execution in a stage (e.g. consume a data, then process it multiple cycles)
stop_tx - (i) optional, vector of signals, one signal per stage; when asserted, the corresponding stage stops producing data;
allows for multicycle execution in a stage (consume multiple data to produce single data )
stop_rx and stop_tx - If you do not need them, then do not connect them | [
"Pipeline",
"control",
"unit",
"rx_rdy",
"rx_vld",
"-",
"(",
"o",
")",
"(",
"i",
")",
"handshake",
"at",
"the",
"pipeline",
"input",
"(",
"front",
"of",
"the",
"pipeline",
")",
"tx_rdy",
"tx_vld",
"-",
"(",
"i",
")",
"(",
"o",
")",
"handshake",
"at",... | train | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/pipeline_control.py#L60-L121 |
nkavaldj/myhdl_lib | myhdl_lib/pipeline_control.py | _stage_ctrl | def _stage_ctrl(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_en, stop_rx=None, stop_tx=None, BC=False):
''' Single stage control
BC - enable bubble compression
'''
if stop_rx==None:
stop_rx = False
if stop_tx==None:
stop_tx = False
state = Signal(bool(0))
a = Signal(bool(0))
b = Signal(bool(0))
bc_link = state if BC else True
@always_comb
def _comb1():
a.next = tx_rdy or stop_tx or not bc_link
b.next = rx_vld or stop_rx
@always_comb
def _comb2():
rx_rdy.next = a and not stop_rx
tx_vld.next = state and not stop_tx
stage_en.next = a and b
@always_seq(clk.posedge, reset=rst)
def _state():
if a:
state.next = b
return _comb1, _comb2, _state | python | def _stage_ctrl(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_en, stop_rx=None, stop_tx=None, BC=False):
''' Single stage control
BC - enable bubble compression
'''
if stop_rx==None:
stop_rx = False
if stop_tx==None:
stop_tx = False
state = Signal(bool(0))
a = Signal(bool(0))
b = Signal(bool(0))
bc_link = state if BC else True
@always_comb
def _comb1():
a.next = tx_rdy or stop_tx or not bc_link
b.next = rx_vld or stop_rx
@always_comb
def _comb2():
rx_rdy.next = a and not stop_rx
tx_vld.next = state and not stop_tx
stage_en.next = a and b
@always_seq(clk.posedge, reset=rst)
def _state():
if a:
state.next = b
return _comb1, _comb2, _state | [
"def",
"_stage_ctrl",
"(",
"rst",
",",
"clk",
",",
"rx_rdy",
",",
"rx_vld",
",",
"tx_rdy",
",",
"tx_vld",
",",
"stage_en",
",",
"stop_rx",
"=",
"None",
",",
"stop_tx",
"=",
"None",
",",
"BC",
"=",
"False",
")",
":",
"if",
"stop_rx",
"==",
"None",
"... | Single stage control
BC - enable bubble compression | [
"Single",
"stage",
"control",
"BC",
"-",
"enable",
"bubble",
"compression"
] | train | https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/pipeline_control.py#L124-L155 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.