docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Clean up basic formatting of BEL statement
Args:
stmt: BEL statement as single string
Returns:
cleaned BEL statement | def preprocess_bel_stmt(stmt: str) -> str:
stmt = stmt.strip() # remove newline at end of stmt
stmt = re.sub(r",+", ",", stmt) # remove multiple commas
stmt = re.sub(r",", ", ", stmt) # add space after each comma
stmt = re.sub(r" +", " ", stmt) # remove multiple spaces
return stmt | 721,269 |
Process computed edge rule
Recursively processes BELAst versus a single computed edge rule
Args:
edges (List[Tuple[Union[Function, str], str, Function]]): BEL Edge ASTs
ast (Function): BEL Function AST
rule (Mapping[str, Any]: computed edge rule | def process_rule(edges: Edges, ast: Function, rule: Mapping[str, Any], spec: BELSpec):
ast_type = ast.__class__.__name__
trigger_functions = rule.get("trigger_function", [])
trigger_types = rule.get("trigger_type", [])
rule_subject = rule.get("subject")
rule_relation = rule.get("relation")
... | 721,276 |
Load orthologs into ArangoDB
Args:
fo: file obj - orthologs file
metadata: dict containing the metadata for orthologs | def load_orthologs(fo: IO, metadata: dict):
version = metadata["metadata"]["version"]
# LOAD ORTHOLOGS INTO ArangoDB
with timy.Timer("Load Orthologs") as timer:
arango_client = arangodb.get_client()
belns_db = arangodb.get_belns_handle(arango_client)
arangodb.batch_load_docs(
... | 721,277 |
Create edges (SRO) for assertions given orthologization targets
Args:
assertions: list of BEL statements (SRO object)
orthologize_targets: list of species in TAX:<int> format
bel_version: to be used for processing assertions
api_url: BEL API url endpoint to use for terminologies and... | def generate_assertion_edge_info(
assertions: List[dict],
orthologize_targets: List[str],
bel_version: str,
api_url: str,
nanopub_type: str = "",
) -> dict:
bo = bel.lang.belobj.BEL(bel_version, api_url)
bo_computed = bel.lang.belobj.BEL(bel_version, api_url)
edge_info_list = []
... | 721,283 |
Migrate BEL 1 to 2.0.0
Args:
bel: BEL 1
Returns:
bel: BEL 2 | def migrate(belstr: str) -> str:
bo.ast = bel.lang.partialparse.get_ast_obj(belstr, "2.0.0")
return migrate_ast(bo.ast).to_string() | 721,289 |
Get Edgestore arangodb database handle
Args:
client (arango.client.ArangoClient): Description
username (None, optional): Description
password (None, optional): Description
edgestore_db_name (str, optional): Description
edgestore_edges_name (str, optional): Description
... | def get_edgestore_handle(
client: arango.client.ArangoClient,
username=None,
password=None,
edgestore_db_name: str = edgestore_db_name,
edgestore_edges_name: str = edgestore_edges_name,
edgestore_nodes_name: str = edgestore_nodes_name,
edgestore_pipeline_name: str = edgestore_pipeline_name,
... | 721,306 |
Batch load documents
Args:
db: ArangoDB client database handle
doc_iterator: function that yields (collection_name, doc_key, doc)
on_duplicate: defaults to replace, but can be error, update, replace or ignore
https://python-driver-for-arangodb.readthedocs.io/en/master/specs.html?h... | def batch_load_docs(db, doc_iterator, on_duplicate="replace"):
batch_size = 100
counter = 0
collections = {}
docs = {}
if on_duplicate not in ["error", "update", "replace", "ignore"]:
log.error(f"Bad parameter for on_duplicate: {on_duplicate}")
return
for (collection_nam... | 721,310 |
Remove illegal chars from potential arangodb _key (id)
Args:
_id (str): id to be used as arangodb _key
Returns:
(str): _key value with illegal chars removed | def arango_id_to_key(_id):
key = re.sub(r"[^a-zA-Z0-9\_\-\:\.\@\(\)\+\,\=\;\$\!\*\%]+", r"_", _id)
if len(key) > 254:
log.error(
f"Arango _key cannot be longer than 254 chars: Len={len(key)} Key: {key}"
)
elif len(key) < 1:
log.error(f"Arango _key cannot be an empt... | 721,311 |
Load BEL Resource file
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
resource_url: URL from which to download the resource to load into the BEL API
forceupdate: force full update - e.g. don't leave Elasti... | def load_resource(resource_url: str, forceupdate: bool = False):
log.info(f"Loading resource {resource_url}")
try:
# Download resource
fo = bel.utils.download_file(resource_url)
if not fo:
log.error(f"Could not download and open file {resource_url}")
retur... | 721,312 |
Get equivalents given ns:id
Args:
term_id (str): term id
Returns:
List[Mapping[str, Union[str, bool]]]: e.g. [{'term_id': 'HGNC:5', 'namespace': 'HGNC'}, 'primary': False] | def get_equivalents(term_id: str) -> List[Mapping[str, Union[str, bool]]]:
try:
errors = []
terms = get_terms(term_id)
if len(terms) == 0:
return {"equivalents": [], "errors": errors}
elif len(terms) > 1:
errors.append(
f'Too many primary ... | 721,314 |
Initialize BEL object used for validating/processing/etc BEL statements
Args:
version (str): BEL Version, defaults to config['bel']['lang']['default_bel_version']
api_url (str): BEL API endpoint, defaults to config['bel_api']['servers']['api_url'] | def __init__(self, version: str = None, api_url: str = None) -> None:
bel_versions = bel_specification.get_bel_versions()
# use bel_utils._default_to_version to check if valid version, and if it exists or not
if not version:
self.version = config["bel"]["lang"]["default_be... | 721,325 |
Takes an AST and returns a canonicalized BEL statement string.
Args:
namespace_targets (Mapping[str, List[str]]): override default canonicalization
settings of BEL.bio API api_url - see {api_url}/status to get default canonicalization settings
Returns:
BEL: retu... | def canonicalize(self, namespace_targets: Mapping[str, List[str]] = None) -> "BEL":
# TODO Need to order position independent args
if not self.ast:
return self
# Collect canonical/decanonical NSArg values
if not self.ast.collected_nsarg_norms:
self = s... | 721,327 |
Orthologize BEL AST to given species_id
Will return original entity (ns:value) if no ortholog found.
Args:
species_id (str): species id to convert genes/rna/proteins into
Returns:
BEL: returns self | def orthologize(self, species_id: str) -> "BEL":
if not self.ast:
return self
# Collect canonical/decanonical NSArg values
if not self.ast.collected_orthologs:
self = self.collect_orthologs([species_id])
self.ast.species = set()
self.ast = bel_... | 721,329 |
Convert AST object to BEL triple
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
long = long function and long relation format
Ret... | def to_triple(self, fmt: str = "medium") -> dict:
if self.ast:
return self.ast.to_triple(ast_obj=self.ast, fmt=fmt)
else:
return {} | 721,332 |
Convert Tatsu AST dictionary to BEL AST object
Args:
ast_dict (Mapping[str, Any])
Returns:
BELAst: object representing the BEL Statement AST | def ast_dict_to_objects(ast_dict: Mapping[str, Any], bel_obj) -> BELAst:
ast_subject = ast_dict.get("subject", None)
ast_object = ast_dict.get("object", None)
bel_subject = None
bel_object = None
bel_relation = ast_dict.get("relation")
if ast_subject:
bel_subject = function_ast_to... | 721,340 |
Convert AST object to string
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
long = long function and long relation format
cano... | def to_string(self, ast_obj=None, fmt: str = "medium") -> str:
if not ast_obj:
ast_obj = self
bel_relation = None
if self.bel_relation and fmt == "short":
bel_relation = self.spec["relations"]["to_short"].get(
self.bel_relation, self.bel_relatio... | 721,347 |
Convert AST object to BEL triple
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
long = long function and long relation format
Ret... | def to_triple(self, ast_obj=None, fmt="medium"):
if not ast_obj:
ast_obj = self
if self.bel_subject and self.bel_relation and self.bel_object:
if self.bel_relation.startswith("has"):
bel_relation = self.bel_relation
elif fmt == "short":
... | 721,348 |
Convert AST object to string
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
long = long function and long relation format
Returns... | def to_string(
self,
fmt: str = "medium",
canonicalize: bool = False,
decanonicalize: bool = False,
orthologize: str = None,
) -> str:
arg_string = ", ".join([a.to_string(fmt=fmt) for a in self.args])
if fmt in ["short", "medium"]:
funct... | 721,354 |
Generate subcomponents of the BEL subject or object
These subcomponents are used for matching parts of a BEL
subject or Object in the Edgestore.
Args:
AST
subcomponents: Pass an empty list to start a new subcomponents request
Returns:
List[str]: su... | def subcomponents(self, subcomponents):
for arg in self.args:
if arg.__class__.__name__ == "Function":
subcomponents.append(arg.to_string())
if arg.function_type == "primary":
arg.subcomponents(subcomponents)
else:
... | 721,357 |
Update Namespace and valueast.
Args:
nsval: e.g. HGNC:AKT1
ns: namespace
val: value of entity | def update_nsval(
self, *, nsval: str = None, ns: str = None, val: str = None
) -> None:
if not (ns and val) and nsval:
(ns, val) = nsval.split(":", 1)
elif not (ns and val) and not nsval:
log.error("Did not update NSArg - no ns:val or nsval provided")
... | 721,361 |
Read file and generate nanopubs
If filename has *.gz, will read as a gzip file
If filename has *.jsonl*, will parsed as a JSONLines file
IF filename has *.json*, will be parsed as a JSON file
If filename has *.yaml* or *.yml*, will be parsed as a YAML file
Args:
filename (str): filename t... | def read_nanopubs(fn: str) -> Iterable[Mapping[str, Any]]:
jsonl_flag, json_flag, yaml_flag = False, False, False
if fn == "-" or "jsonl" in fn:
jsonl_flag = True
elif "json" in fn:
json_flag = True
elif re.search("ya?ml", fn):
yaml_flag = True
else:
log.error("... | 721,387 |
Create Nanopubs output filehandle
\b
If output fn is '-' will write JSONlines to STDOUT
If output fn has *.gz, will written as a gzip file
If output fn has *.jsonl*, will written as a JSONLines file
IF output fn has *.json*, will be written as a JSON file
If output fn has *.yaml* or *.yml*, wi... | def create_nanopubs_fh(output_fn: str):
# output file
# set output flags
json_flag, jsonl_flag, yaml_flag = False, False, False
if output_fn:
if re.search("gz$", output_fn):
out_fh = gzip.open(output_fn, "wt")
else:
out_fh = click.open_file(output_fn, mode="... | 721,388 |
Write edges to file
Args:
edges (Mapping[str, Any]): in edges JSON Schema format
filename (str): filename to write
jsonlines (bool): output in JSONLines format?
gzipflag (bool): create gzipped file?
yaml (bool): create yaml file? | def write_edges(
edges: Mapping[str, Any],
filename: str,
jsonlines: bool = False,
gzipflag: bool = False,
yaml: bool = False,
):
pass | 721,390 |
Bulk load docs
Args:
es: elasticsearch handle
docs: Iterator of doc objects - includes index_name | def bulk_load_docs(es, docs):
chunk_size = 200
try:
results = elasticsearch.helpers.bulk(es, docs, chunk_size=chunk_size)
log.debug(f"Elasticsearch documents loaded: {results[0]}")
# elasticsearch.helpers.parallel_bulk(es, terms, chunk_size=chunk_size, thread_count=4)
if ... | 721,396 |
Semantically validate BEL AST
Add errors and warnings to bel_obj.validation_messages
Error Levels are similar to log levels - selecting WARNING includes both
WARNING and ERROR, selecting ERROR just includes ERROR
Args:
bo: main BEL language object
error_level: return ERRORs only or al... | def validate(bo, error_level: str = "WARNING") -> Tuple[bool, List[Tuple[str, str]]]:
if bo.ast:
bo = validate_functions(bo.ast, bo) # No WARNINGs generated in this function
if error_level == "WARNING":
bo = validate_arg_values(bo.ast, bo) # validates NSArg and StrArg values
... | 721,407 |
Recursively validate function signatures
Determine if function matches one of the available signatures. Also,
1. Add entity types to AST NSArg, e.g. Abundance, ...
2. Add optional to AST Arg (optional means it is not a
fixed, required argument and needs to be sorted for
canonicalization, ... | def validate_functions(ast: BELAst, bo):
if isinstance(ast, Function):
log.debug(f"Validating: {ast.name}, {ast.function_type}, {ast.args}")
function_signatures = bo.spec["functions"]["signatures"][ast.name]["signatures"]
function_name = ast.name
(valid_function, messages) = c... | 721,408 |
Recursively validate arg (NSArg and StrArg) values
Check that NSArgs are found in BELbio API and match appropriate entity_type.
Check that StrArgs match their value - either default namespace or regex string
Generate a WARNING if not.
Args:
bo: bel object
Returns:
bel object | def validate_arg_values(ast, bo):
if not bo.api_url:
log.info("No API endpoint defined")
return bo
log.debug(f"AST: {ast}")
# Test NSArg terms
if isinstance(ast, NSArg):
term_id = "{}:{}".format(ast.namespace, ast.value)
value_types = ast.value_types
log.d... | 721,410 |
Override config with additional configuration in override_config or override_config_fn
Used in script to merge CLI options with Config
Args:
config: original configuration
override_config: new configuration to override/extend current config
override_config_fn: new configuration filenam... | def merge_config(
config: Mapping[str, Any],
override_config: Mapping[str, Any] = None,
override_config_fn: str = None,
) -> Mapping[str, Any]:
if override_config_fn:
with open(override_config_fn, "r") as f:
override_config = yaml.load(f, Loader=yaml.SafeLoader)
if not ove... | 721,457 |
Load terms into Elasticsearch and ArangoDB
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
fo: file obj - terminology file
metadata: dict containing the metadata for terminology
forceupdate: force f... | def load_terms(fo: IO, metadata: dict, forceupdate: bool):
version = metadata["metadata"]["version"]
# LOAD TERMS INTO Elasticsearch
with timy.Timer("Load Terms") as timer:
es = bel.db.elasticsearch.get_client()
es_version = version.replace("T", "").replace("-", "").replace(":", "")
... | 721,464 |
Lowercase the term value (not the namespace prefix)
Args:
term_id (str): term identifier with namespace prefix, e.g. MESH:Atherosclerosis
Returns:
str: lowercased, e.g. MESH:atherosclerosis | def lowercase_term_id(term_id: str) -> str:
(ns, val) = term_id.split(":", maxsplit=1)
term_id = f"{ns}:{val.lower()}"
return term_id | 721,467 |
Get pubmed xml for pmid and convert to JSON
Remove MESH terms if they are duplicated in the compound term set
ArticleDate vs PubDate gets complicated: https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html see <ArticleDate> and <PubDate>
Only getting pub_year at this point from the <PubDate> elem... | def get_pubmed(pmid: str) -> Mapping[str, Any]:
pubmed_url = PUBMED_TMPL.replace("PMID", str(pmid))
r = get_url(pubmed_url)
log.info(f"Getting Pubmed URL {pubmed_url}")
try:
root = etree.fromstring(r.content)
doc = {"abstract": ""}
doc["pmid"] = root.xpath("//PMID/text()")[... | 721,471 |
Enhance pubmed namespace IDs
Add additional entity and annotation types to annotations
Use preferred id for namespaces as needed
Add strings from Title, Abstract matching Pubtator BioConcept spans
NOTE - basically duplicated code with bel_api:api.services.pubmed
Args:
pubmed
Returns:... | def enhance_pubmed_annotations(pubmed: Mapping[str, Any]) -> Mapping[str, Any]:
text = pubmed["title"] + pubmed["abstract"]
annotations = {}
for nsarg in pubmed["annotations"]:
url = f'{config["bel_api"]["servers"]["api_url"]}/terms/{url_path_param_quoting(nsarg)}'
log.info(f"URL: {u... | 721,472 |
Get fully annotated pubmed doc with Pubtator and full entity/annotation_types
Args:
pmid: Pubmed PMID
Returns:
Mapping[str, Any]: pubmed dictionary | def get_pubmed_for_beleditor(pmid: str) -> Mapping[str, Any]:
pubmed = get_pubmed(pmid)
pubtator = get_pubtator(pmid)
pubmed["annotations"] = copy.deepcopy(pubtator["annotations"])
# Add entity types and annotation types to annotations
pubmed = enhance_pubmed_annotations(pubmed)
return p... | 721,473 |
Get orthologs for given gene_id and species
Canonicalize prior to ortholog query and decanonicalize
the resulting ortholog
Args:
canonical_gene_id: canonical gene_id for which to retrieve ortholog
species: target species for ortholog - tax id format TAX:<number>
Returns:
List[... | def get_orthologs(canonical_gene_id: str, species: list = []) -> List[dict]:
gene_id_key = bel.db.arangodb.arango_id_to_key(canonical_gene_id)
orthologs = {}
if species:
query_filter = f"FILTER vertex.tax_id IN {species}"
query = f
cursor = belns_db.aql.execute(query, batch_size=20)... | 721,481 |
Wrapper for requests.get(url)
Args:
url: url to retrieve
params: query string parameters
timeout: allow this much time for the request and time it out if over
cache: Cache for up to a day unless this is false
Returns:
Requests Result obj or None if timed out | def get_url(url: str, params: dict = {}, timeout: float = 5.0, cache: bool = True):
try:
if not cache:
with requests_cache.disabled():
r = requests.get(url, params=params, timeout=timeout)
else:
r = requests.get(url, params=params, timeout=timeout)
... | 721,487 |
Create hash Id from edge record
Args:
edge (Mapping[str, Any]): edge record to create hash from
Returns:
str: Murmur3 128 bit hash | def _create_hash_from_doc(doc: Mapping[str, Any]) -> str:
doc_string = json.dumps(doc, sort_keys=True)
return _create_hash(doc_string) | 721,491 |
Add nanopubstore start_dt to belapi.state_mgmt collection
Args:
url: url of nanopubstore
start_dt: datetime of last query against nanopubstore for new ID's | def update_nanopubstore_start_dt(url: str, start_dt: str):
hostname = urllib.parse.urlsplit(url)[1]
start_dates_doc = state_mgmt.get(start_dates_doc_key)
if not start_dates_doc:
start_dates_doc = {
"_key": start_dates_doc_key,
"start_dates": [{"nanopubstore": hostname,... | 721,504 |
Validate nanopub against jsonschema for nanopub
Args:
nanopub (Mapping[str, Any]): nanopub dict
schema (Mapping[str, Any]): nanopub schema
Returns:
Tuple[bool, List[str]]:
bool: Is valid? Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if... | def validate_to_schema(nanopub, schema) -> Tuple[bool, List[Tuple[str, str]]]:
v = jsonschema.Draft4Validator(schema)
messages = []
errors = sorted(v.iter_errors(nanopub), key=lambda e: e.path)
for error in errors:
for suberror in sorted(error.context, key=lambda e: e.schema_path):
... | 721,518 |
Validates using the nanopub schema
Args:
nanopub (Mapping[str, Any]): nanopub dict
Returns:
Tuple[bool, List[Tuple[str, str]]]:
bool: Is valid? Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if valid, tuple is ('ERROR|WAR... | def validate(
self, nanopub: Mapping[str, Any]
) -> Tuple[bool, List[Tuple[str, str]]]:
# Validate nanopub
(is_valid, messages) = validate_to_schema(nanopub, self.nanopub_schema)
if not is_valid:
return messages
# Extract BEL Version
if nanopub[... | 721,520 |
Validate context
Args:
context (Mapping[str, Any]): context dictionary of type, id and label
Returns:
Tuple[bool, List[Tuple[str, str]]]:
bool: Is valid? Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if valid, tuple is (... | def validate_context(
self, context: Mapping[str, Any]
) -> Tuple[bool, List[Tuple[str, str]]]:
url = f'{self.endpoint}/terms/{context["id"]}'
res = requests.get(url)
if res.status_code == 200:
return (True, [])
else:
return (False, [("WARNI... | 721,521 |
provide another way to define the layers (stack)
Parameters:
===========
formula: string
ex: 'CoAg2'
ex: 'Al'
thickness: float (in mm)
density: float (g/cm3) | def add_layer(self, formula='', thickness=np.NaN, density=np.NaN):
if formula == '':
return
_new_stack = _utilities.formula_to_dictionary(formula=formula,
thickness=thickness,
... | 721,869 |
returns the list of isotopes for the element of the compound defined with their stoichiometric values
Parameters:
===========
compound: string (default is empty). If empty, all the stoichiometric will be displayed
element: string (default is same as compound).
Raises:
=... | def get_isotopic_ratio(self, compound='', element=''):
_stack = self.stack
compound = str(compound)
if compound == '':
_list_compounds = _stack.keys()
list_all_dict = {}
for _compound in _list_compounds:
_compound = str(_compound)
... | 721,870 |
returns the list of isotopes for the element of the compound defined with their density
Parameters:
===========
compound: string (default is empty). If empty, all the stoichiometric will be displayed
element: string (default is same as compound).
Raises:
=======
... | def get_density(self, compound='', element=''):
_stack = self.stack
if compound == '':
_list_compounds = _stack.keys()
list_all_dict = {}
for _compound in _list_compounds:
_list_element = _stack[_compound]['elements']
list_all... | 721,872 |
lock (True) the density lock if the density has been been defined during initialization
Store the resulting dictionary into density_lock
Parameters:
===========
stack: dictionary (optional)
if not provided, the entire stack will be used | def __lock_density_if_defined(self, stack: dict):
if self.stack == {}:
density_lock = {}
else:
density_lock = self.density_lock
for _compound in stack.keys():
_density = stack[_compound]['density']['value']
if np.isnan(_density):
... | 721,874 |
Re-calculate the density of the element given due to stoichiometric changes as
well as the compound density (if density is not locked)
Parameters:
===========
compound: string (default is '') name of compound
element: string (default is '') name of element | def __update_density(self, compound='', element=''):
_density_element = 0
list_ratio = self.stack[compound][element]['isotopes']['isotopic_ratio']
list_density = self.stack[compound][element]['isotopes']['density']['value']
ratio_density = zip(list_ratio, list_density)
f... | 721,880 |
Re-calculate the molar mass of the element given due to stoichiometric changes
Parameters:
==========
compound: string (default is '') name of compound
element: string (default is '') name of element | def __update_molar_mass(self, compound='', element=''):
_molar_mass_element = 0
list_ratio = self.stack[compound][element]['isotopes']['isotopic_ratio']
list_mass = self.stack[compound][element]['isotopes']['mass']['value']
ratio_mass = zip(list_ratio, list_mass)
for _ra... | 721,881 |
Tag parts of speech. from: /lexical/pos
Arguments:
text: The text to tag | def getPos(self, text):
kwargs = {'text':text}
kwargs = {k:dumps(v) if type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('text', **kwargs)
url = self._basePath + ('/lexical/pos').format(**kwargs)
requests_params = {k:v for k, v in kwargs.it... | 722,006 |
return a string array of all the element from the database
Parameters:
==========
database: string. Name of database
Raises:
======
ValueError if database can not be found | def get_list_element_from_database(database='ENDF_VII'):
_file_path = os.path.abspath(os.path.dirname(__file__))
_ref_data_folder = os.path.join(_file_path, 'reference_data')
_database_folder = os.path.join(_ref_data_folder, database)
if not os.path.exists(_ref_data_folder):
os.makedirs(_r... | 722,066 |
will try to find the element in the folder (database) specified
Parameters:
==========
element: string. Name of the element. Not case sensitive
database: string (default is 'ENDF_VII'). Name of folder that has the list of elements
Returns:
=======
bool: True if element was found in the dat... | def is_element_in_database(element='', database='ENDF_VII'):
if element == '':
return False
list_entry_from_database = get_list_element_from_database(database=database)
if element in list_entry_from_database:
return True
return False | 722,067 |
return a dictionary with list of isotopes found in database and name of database files
Parameters:
===========
element: string. Name of the element
ex: 'Ag'
database: string (default is ENDF_VII)
Returns:
========
dictionary with isotopes and files
ex: {'Ag': {'isotope... | def get_isotope_dicts(element='', database='ENDF_VII'):
_file_path = os.path.abspath(os.path.dirname(__file__))
_database_folder = os.path.join(_file_path, 'reference_data', database)
_element_search_path = os.path.join(_database_folder, element + '-*.csv')
list_files = glob.glob(_element_search_p... | 722,070 |
return the energy (eV) and Sigma (barn) from the file_name
Parameters:
===========
file_name: string ('' by default) name of csv file
Returns:
========
pandas dataframe
Raises:
=======
IOError if file does not exist | def get_database_data(file_name=''):
if not os.path.exists(file_name):
raise IOError("File {} does not exist!".format(file_name))
df = pd.read_csv(file_name, header=1)
return df | 722,073 |
calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of element/isotope)
sigma_b: np.array of sigma retrieved from database
R... | def calculate_linear_attenuation_coefficient(atoms_per_cm3: np.float, sigma_b: np.array):
miu_per_cm = 1e-24 * sigma_b * atoms_per_cm3
return np.array(miu_per_cm) | 722,077 |
calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of element/isotope)
sigma_b: np.array of sigma retrieved from database
R... | def calculate_trans(thickness_cm: np.float, miu_per_cm: np.array):
transmission = np.exp(-thickness_cm * miu_per_cm)
return np.array(transmission) | 722,078 |
calculate the transmission signal using the formula
transmission = exp( - thickness_cm * atoms_per_cm3 * 1e-24 * sigma_b)
Parameters:
===========
thickness: float (in cm)
atoms_per_cm3: float (number of atoms per cm3 of element/isotope)
sigma_b: np.array of sigma retrieved from databas... | def calculate_transmission(thickness_cm: np.float, atoms_per_cm3: np.float, sigma_b: np.array):
miu_per_cm = calculate_linear_attenuation_coefficient(atoms_per_cm3=atoms_per_cm3, sigma_b=sigma_b)
transmission = calculate_trans(thickness_cm=thickness_cm, miu_per_cm=miu_per_cm)
return miu_per_cm, transmi... | 722,079 |
convert distance into new units
Parameters:
===========
value: float. value to convert
from_units: string. Must be 'mm', 'cm' or 'm'
to_units: string. must be 'mm','cm' or 'm'
Returns:
========
converted value
Raises:
=======
ValueError if from_units is not a v... | def set_distance_units(value=np.NaN, from_units='mm', to_units='cm'):
if from_units == to_units:
return value
if from_units == 'cm':
if to_units == 'mm':
coeff = 10
elif to_units == 'm':
coeff = 0.01
else:
raise ValueError("to_units not s... | 722,080 |
convert energy (eV) to time (us)
Parameters:
===========
array: array (in eV)
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
time: array in s | def ev_to_s(offset_us, source_to_detector_m, array):
# delay values is normal 2.99 us with NONE actual MCP delay settings
# 1000 is used to convert eV to meV
time_s = np.sqrt(81.787 / (array * 1000.)) * source_to_detector_m / 3956.
time_record_s = time_s - offset_us * 1e-6
return time_record_s | 722,081 |
convert time (s) to energy (eV)
Parameters:
===========
numpy array of time in s
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
numpy array of energy in eV | def s_to_ev(offset_us, source_to_detector_m, array):
lambda_a = 3956. * (array + offset_us * 1e-6) / source_to_detector_m
return (81.787 / pow(lambda_a, 2)) / 1000. | 722,082 |
convert energy (eV) to image numbers (#)
Parameters:
===========
numpy array of energy in eV
offset_us: float. Delay of detector in us
source_to_detector_m: float. Distance source to detector in m
Returns:
========
image numbers: array of image number | def ev_to_image_number(offset_us, source_to_detector_m, time_resolution_us, t_start_us, array):
# delay values is normal 2.99 us with NONE actual MCP delay settings
time_tot_us = np.sqrt(81.787 / (array * 1000)) * source_to_detector_m * 100 / 0.3956
time_record_us = (time_tot_us + offset_us)
image_... | 722,083 |
Get a feed
Arguments:
config -- the configuration
url -- The URL of the feed
retval -- a tuple of feed,previous_version,changed | async def get_feed(config, url):
LOGGER.debug("++WAIT: cache get feed %s", url)
previous = config.cache.get(
'feed', url, schema_version=SCHEMA_VERSION) if config.cache else None
LOGGER.debug("++DONE: cache get feed %s", url)
headers = previous.caching if previous else None
LOGGER.de... | 722,607 |
Given an entry URL, return the entry
Arguments:
config -- the configuration
url -- the URL of the entry
Returns: 3-tuple of (current, previous, updated) | async def get_entry(config, url):
previous = config.cache.get(
'entry', url,
schema_version=SCHEMA_VERSION) if config.cache else None
headers = previous.caching if previous else None
request = await utils.retry_get(config, url, headers=headers)
if not request or not request.succe... | 723,320 |
Initialize default select2 attributes.
If width is not provided, sets Select2 width to 250px.
Args:
select2attrs: a dictionary, which then passed to
Select2 constructor function as options. | def __init__(self, select2attrs=None, *args, **kwargs):
self.select2attrs = select2attrs or {}
assert_msg = "select2attrs attribute must be dict, not {}"
assert isinstance(self.select2attrs, dict), assert_msg.format(
self.select2attrs.__class__.__name__
)
... | 723,670 |
Return `Meta` class with Select2-enabled widgets for fields
with choices (e.g. ForeignKey, CharField, etc) for use with
ModelForm.
Arguments:
model - a model class to create `Meta` class for.
meta_fields - dictionary with `Meta` class fields, for
example, {'fields': ['id', 'nam... | def select2_modelform_meta(model,
meta_fields=None,
widgets=None,
attrs=None,
**kwargs):
widgets = widgets or {}
meta_fields = meta_fields or {}
# TODO: assert attrs is of type `dict`
for f... | 723,680 |
Return ModelForm class for model with select2 widgets.
Arguments:
attrs: select2 widget attributes (width, for example) of type `dict`.
form_class: modelform base class, `forms.ModelForm` by default.
::
SomeModelForm = select2_modelform(models.SomeModelBanner)
is the same like::
... | def select2_modelform(
model, attrs=None, form_class=es2_forms.FixedModelForm):
classname = '%sForm' % model._meta.object_name
meta = select2_modelform_meta(model, attrs=attrs)
return type(classname, (form_class,), {'Meta': meta}) | 723,681 |
Initialize a property list representation from an existing file.
Args:
plist_filename: A string containing the full path to a
Doxygen-generated property list file.
Raises:
OSError / FileNotFoundError: Input file cannot be read
RuntimeError: The property ... | def __init__(self, plist_filename):
self.filename = plist_filename
with open(self.filename, 'r') as plist_file:
self.soup = BeautifulSoup(plist_file, 'lxml-xml')
self.properties = self.soup.findChild(name='dict')
if self.properties is None:
... | 723,773 |
Set a new (or updating existing) key value pair.
Args:
key: A string containing the key namespace
value: A str, int, or bool value
Raises:
NotImplementedError: an unsupported value-type was provided | def set_property(self, key, value):
value_type = type(value)
if value_type not in [str, int, bool]:
raise NotImplementedError(
'Only string, integer, and boolean properties are implemented')
key_object = self.properties.findChild(name='key', text=key)
... | 723,774 |
Run a tag processor.
Args:
tag_proc_name: A string key that maps to the TagProcessor to run. | def run_tag_processor(self, tag_proc_name):
tag_processor = self.tag_procs[tag_proc_name]
for tag in tag_processor.find(self.soup):
self.process_tag(tag_proc_name, tag) | 724,189 |
Process a tag with a tag processor and insert a DB entry.
Args:
tag_proc_name: A string key that maps to the TagProcessor to use.
tag: A BeautifulSoup Tag to process. | def process_tag(self, tag_proc_name, tag):
tag_processor = self.tag_procs[tag_proc_name]
db_entry = (tag_processor.get_name(tag),
tag_processor.get_entry_type(tag),
tag_processor.get_filename(tag))
self.zeal_db.insert(*db_entry)
self.en... | 724,190 |
wrapper to itertools.groupby that returns a list of each group, rather
than a generator and accepts integers or strings as the key and
automatically converts them to callables with itemgetter(key)
Arguments:
iterable: iterable
key: string, int or callable that tells how to group
Return... | def groupby(iterable, key=0, filter=None):
if isinstance(key, (basestring, int)):
key = itemgetter(key)
elif isinstance(key, (tuple, list)):
key = itemgetter(*key)
for label, grp in igroupby(iterable, key):
yield label, list(grp) | 724,191 |
Initialize a ZealDB.
A connection is not opened here. To do that, use open() or use this
ZealDB instance as a context manager.
Args:
filename: A string containing full path to database file.
**verbose: If True, extra information may be printed to stderr
... | def __init__(self, filename, **kwargs):
self.filename = filename
self.verbose = kwargs.get('verbose', False)
self.conn = None
self.cursor = None | 724,251 |
Insert an entry into the Zeal database.
Args:
name: A string representing the name of the entry.
entry_type: A string representing the entry type.
filename: A string representing the filename of the documentation
for the entry.
Raises:
Ru... | def insert(self, name, entry_type, filename):
if self.cursor is None:
raise RuntimeError(
'Open DB connection before attempting to call insert!')
db_entry = (name, entry_type, filename)
if self.verbose:
print('Inserting %s "%s" -> %s' % db_entry... | 724,254 |
Yield tags matching the tag criterion from a soup.
There is no need to override this if you are satisfied with finding
tags that match match_criterion.
Args:
soup: A BeautifulSoup to search through.
Yields:
BeautifulSoup Tags that match the criterion. | def find(self, soup):
for tag in soup.recursiveChildGenerator():
if self.match_criterion(tag):
yield tag | 724,466 |
Extract and return a documentation filename from a tag.
Override as necessary, though this default implementation probably
covers all the cases of interest.
Args:
tag: A BeautifulSoup Tag that satisfies match_criterion.
Returns:
A string that would be appropria... | def get_filename(self, tag):
if tag.find('filename', recursive=False) is not None:
return tag.filename.contents[0]
elif tag.find('anchorfile', recursive=False) is not None:
return tag.anchorfile.contents[0] + '#' + tag.anchor.contents[0] | 724,468 |
Initializer.
Args:
entry_type: A string that should be returned by get_entry_type()
for all (matching) tags.
tag_name: The unicode string name that matching tags should have.
tag_kind: The unicode string "kind" attribute that matching tags
sho... | def __init__(self, entry_type, tag_name, tag_kind, **kwargs):
super(TagProcessorWithEntryTypeAndFindByNamePlusKind,
self).__init__(**kwargs)
# Save this to return from get_entry_type override
self.entry_type = entry_type
# Save these for use in match_criterion ov... | 724,469 |
Override. Determine if a tag has the desired name and kind attribute
value.
Args:
tag: A BeautifulSoup Tag.
Returns:
True if tag has the desired name and kind, otherwise False. | def match_criterion(self, tag):
return tag.name == self.reference_tag_name and \
tag.attrs.get('kind', '') == self.reference_tag_kind | 724,470 |
Initializer.
Args:
tag_name: unicode string name of tag to match. Usually u'compound'
or u'member'. | def __init__(self, tag_name, **kwargs):
# Extract entry type from class name, assuming that it is of the format
# "$(entry_type)TagProcessor"
class_name = type(self).__name__
end_idx = class_name.rfind('TagProcessor')
tag_kind = str(class_name[:end_idx])
entry_t... | 724,471 |
Initializer.
Args:
**include_function_signatures: bool. See get_name() for more info. | def __init__(self, **kwargs):
super(functionTagProcessor, self).__init__(**kwargs)
self.include_function_signatures = kwargs.get(
'include_function_signatures', False) | 724,472 |
Override that returns u'Method' for class/struct methods.
Override as necessary.
Args:
tag: A BeautifulSoup Tag for a function.
Returns:
If this is a class/struct method, returns u'Method', otherwise
returns the value from the inherited implementation of
... | def get_entry_type(self, tag):
if tag.findParent().get('kind') in ['class', 'struct']:
return u'Method'
return super(functionTagProcessor, self).get_entry_type(tag) | 724,474 |
parallel map of a function to an iterable
if each item in iterable is itself an iterable, then
automatically call f(*item) instead of f(item)
Arguments:
f: function
iterable: any iterable where each item is sent to f
n: number of cpus (default is number on machine)
dummy: use dummy ... | def pmap(f, iterable, n=None, dummy=False, p=None):
# make it easier to debug.
if n == 1:
for r in it.starmap(f, iterable):
yield r
raise StopIteration
if p is None:
po = pool(n, dummy)
else:
po = p
assert hasattr(po, 'imap')
f = _func_star(f)
... | 724,481 |
Adds permission with the given name to the set. Permission with the same name will be overridden.
Args:
name: name of the permission
permission: permission instance | def set(self, name, permission):
assert isinstance(permission, BasePermission), 'Only permission instances can be added to the set'
self._permissions[name] = permission | 724,674 |
Return information about recent builds across all projects.
Args:
limit (int), Number of builds to return, max=100, defaults=30.
offset (int): Builds returned from this point, default=0.
Returns:
A list of dictionaries. | def recent_all_projects(self, limit=30, offset=0):
method = 'GET'
url = ('/recent-builds?circle-token={token}&limit={limit}&'
'offset={offset}'.format(token=self.client.api_token,
limit=limit,
offset=... | 724,853 |
Returns field humanized value, label and widget which are used to display of instance or view readonly data.
Args:
field_name: name of the field which will be displayed
instance: model instance
view: view instance
fun_kwargs: kwargs that can be used inside method call
Returns:
... | def get_readonly_field_data(field_name, instance, view=None, fun_kwargs=None):
fun_kwargs = fun_kwargs or {}
if view:
view_readonly_data = _get_view_readonly_data(field_name, view, fun_kwargs)
if view_readonly_data is not None:
return view_readonly_data
field_data = _get_m... | 724,960 |
Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL.
If not None is returned.
Args:
pattern_name (str): slug which is used for view registratin to pattern
request (django.http.request.HttpRequest): Django request object
view_... | def get_link_or_none(pattern_name, request, view_kwargs=None):
from is_core.patterns import reverse_pattern
pattern = reverse_pattern(pattern_name)
assert pattern is not None, 'Invalid pattern name {}'.format(pattern_name)
if pattern.has_permission('get', request, view_kwargs=view_kwargs):
... | 724,967 |
Method should return object method that can be used to get field value.
Args:
field_name: name of the field
Returns: method for obtaining a field value | def get_method_returning_field_value(self, field_name):
method = getattr(self, field_name, None)
return method if method and callable(method) else None | 724,968 |
Used to return a base media URL. Depending on whether we're serving
media remotely or locally, this either hands the decision off to the
backend, or just uses the value in settings.STATIC_URL.
args:
with_ssl: (bool) If True, return an HTTPS url (depending on how
... | def media_url(self, with_ssl=False):
if self.serve_remote:
# Hand this off to whichever backend is being used.
url = self.remote_media_url(with_ssl)
else:
# Serving locally, just use the value in settings.py.
url = self.local_media_url
ret... | 725,175 |
Assembles various components to form a complete resource URL.
args:
url: (str) A base media URL.
path: (str) The path on the host (specified in 'url') leading up
to the file.
filename: (str) The file name to serve.
gzip: (bool) True if clien... | def mkpath(self, url, path, filename=None, gzip=False):
if path:
url = "%s/%s" % (url.rstrip('/'), path.strip('/'))
if filename:
url = "%s/%s" % (url, filename.lstrip('/'))
content_type = mimetypes.guess_type(url)[0]
if gzip and content_type in ... | 725,321 |
Returns the base remote media URL. In this case, we can safely make
some assumptions on the URL string based on bucket names, and having
public ACL on.
args:
with_ssl: (bool) If True, return an HTTPS url. | def remote_media_url(self, with_ssl=False):
protocol = 'http' if with_ssl is False else 'https'
url = (self.aws_bucket_cname and "%s://%s" or "%s://s3.amazonaws.com/%s") % (protocol, self.aws_bucket)
if self.aws_prefix:
url = "%s/%s" % (url, self.aws_prefix)
return u... | 725,540 |
Split a string with arbitrary number of separators.
Return a list with the splitted values
Arguments:
string (str): ex. "a:1|2,b:2"
separators (list): ex. [',',':','|']
Returns:
results (list) : ex. ['a','1','2','b','2'] | def split_strings(string, separators):
logger = logging.getLogger('extract_vcf.split_strings')
logger.debug("splitting string '{0}' with separators {1}".format(
string, separators
))
results = []
def recursion(recursive_string, separators, i=1):
if i == len(separat... | 726,403 |
Check for a valid definition of a value.
Args:
iface (Iface): An Iface specification.
cls (type): Some type to check for a definition.
tag (str): The name of the tag attribute used to mark the abstract
methods.
defines (callable): A callable that accepts an attribute and... | def _check_for_definition(iface, cls, tag, defines):
attributes = (
attr
for attr in iface.__abstractmethods__
if hasattr(getattr(iface, attr), tag)
)
for attribute in attributes:
for node in cls.__mro__:
if hasattr(node, attribute) and defines(getattr(node... | 726,681 |
Return the raw entry from the vcf field
If no entry was found return None
Args:
variant_line (str): A vcf formated variant line
vcf_header (list): A list with the vcf header line
individual_id (str): The individual id to g... | def get_raw_entry(self, variant_line=None, variant_dict=None,
vcf_header=None, individual_id=None, dict_key=None):
if variant_line:
variant_line = variant_line.rstrip().split()
entry = None
if self.field == 'CHROM':
if variant_line:
... | 726,707 |
Convert a section with information of priorities to a string dict.
To avoid typos we make all letters lower case when comparing
Arguments:
plugin_info (dict): A dictionary with plugin information
Return:
string_dict (dict): A dictionary with str... | def get_string_dict(self, plugin_info):
string_info = []
string_dict = {}
for key in plugin_info:
try:
string_info.append(dict(plugin_info[key]))
except ValueError:
pass
string_rules = {}
... | 726,789 |
Check if the section is in the proper format vcf format.
Args:
vcf_section (dict): The information from a vcf section
Returns:
True is it is in the proper format | def check_plugin(self, plugin):
vcf_section = self[plugin]
try:
vcf_field = vcf_section['field']
if not vcf_field in self.vcf_columns:
raise ValidateError(
"field has to be in {0}\n"
"Wron... | 726,791 |
Parse block node.
args:
scope (Scope): Current scope
raises:
SyntaxError
returns:
self | def parse(self, scope):
if not self.parsed:
scope.push()
self.name, inner = self.tokens
scope.current = self.name
scope.real.append(self.name)
if not self.name.parsed:
self.name.parse(scope)
if not inner:
... | 726,878 |
Raw block name
args:
clean (bool): clean name
returns:
str | def raw(self, clean=False):
try:
return self.tokens[0].raw(clean)
except (AttributeError, TypeError):
pass | 726,879 |
Format block (CSS)
args:
fills (dict): Fill elements
returns:
str (CSS) | def fmt(self, fills):
f = "%(identifier)s%(ws)s{%(nl)s%(proplist)s}%(eb)s"
out = []
name = self.name.fmt(fills)
if self.parsed and any(
p for p in self.parsed
if str(type(p)) != "<class 'lesscpy.plib.variable.Variable'>"):
fills.update... | 726,880 |
Copy block contents (properties, inner blocks).
Renames inner block from current scope.
Used for mixins.
args:
scope (Scope): Current scope
returns:
list (block contents) | def copy_inner(self, scope):
if self.tokens[1]:
tokens = [u.copy() if u else u for u in self.tokens[1]]
out = [p for p in tokens if p]
utility.rename(out, scope, Block)
return out
return None | 726,882 |
Parse node
args:
scope (Scope): current scope
raises:
SyntaxError
returns:
self | def parse(self, scope):
self.parsed = list(utility.flatten(self.tokens))
if self.parsed[0] == '@import':
if len(self.parsed) > 4:
# Media @import
self.parsed.insert(3, ' ')
return self | 726,883 |
This node represents mixin calls. The calls
to these mixins are deferred until the second
parse cycle. lessc.js allows calls to mixins not
yet defined or known.
args:
mixin (Mixin): Mixin object
args (list): Call arguments | def __init__(self, mixin, args, lineno=0):
self.tokens = [mixin, args]
self.lineno = lineno | 726,884 |
Compile all *.less files in directory
Args:
inpath (str): Path to compile
outpath (str): Output directory
args (object): Argparse Object
scope (Scope): Scope object or None | def ldirectory(inpath, outpath, args, scope):
yacctab = 'yacctab' if args.debug else None
if not outpath:
sys.exit("Compile directory option needs -o ...")
else:
if not os.path.isdir(outpath):
if args.verbose:
print("Creating '%s'" % outpath, file=sys.stderr)... | 726,886 |
Parse node.
args:
scope (Scope): Current scope
raises:
SyntaxError
returns:
self | def parse(self, scope):
self.keyframe, = [
e[0] if isinstance(e, tuple) else e for e in self.tokens
if str(e).strip()
]
self.subparse = False
return self | 726,888 |
Parse node. Block identifiers are stored as
strings with spaces replaced with ?
args:
scope (Scope): Current scope
raises:
SyntaxError
returns:
self | def parse(self, scope):
names = []
name = []
self._subp = ('@media', '@keyframes', '@-moz-keyframes',
'@-webkit-keyframes', '@-ms-keyframes')
if self.tokens and hasattr(self.tokens, 'parse'):
self.tokens = list(
utility.flatten([... | 726,904 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.