INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
validate
def validate(self, value): """validate""" # obj can be None or a DataFrame if value is None: return True else: try: with value.open() as hdulist: self.validate_hdulist(hdulist) except Exception: _type...
Extract tags from serialized file
def extract_db_info(self, obj, keys): """Extract tags from serialized file""" objl = self.convert(obj) result = super(DataFrameType, self).extract_db_info(objl, keys) ext = self.datamodel.extractor_map['fits'] if objl: with objl.open() as hdulist: fo...
Return a single character read from keyboard Parameters ---------- prompt : str Prompt string. default : str Default value. valid : str String providing valid characters. If None, all characters are valid (default). question_mark : bool If True, display q...
def readc(prompt, default=None, valid=None, question_mark=True): """Return a single character read from keyboard Parameters ---------- prompt : str Prompt string. default : str Default value. valid : str String providing valid characters. If None, all characters are ...
Return integer value read from keyboard Parameters ---------- prompt : str Prompt string. default : integer, str or None Default value. minval : integer or None Mininum allowed value. maxval : integer or None Maximum allowed value. allowed_single_chars : st...
def readi(prompt, default=None, minval=None, maxval=None, allowed_single_chars=None, question_mark=True): """Return integer value read from keyboard Parameters ---------- prompt : str Prompt string. default : integer, str or None Default value. minval : integer or Non...
Return integer value read from keyboard Parameters ---------- prompt : str Prompt string. default : float or None Default value. minval : float or None Mininum allowed value. maxval : float or None Maximum allowed value. allowed_single_chars : str S...
def readf(prompt, default=None, minval=None, maxval=None, allowed_single_chars=None, question_mark=True): """Return integer value read from keyboard Parameters ---------- prompt : str Prompt string. default : float or None Default value. minval : float or None ...
Return value read from keyboard Parameters ---------- ftype : int() or float() Function defining the expected type. prompt : str Prompt string. default : int or None Default value. minval : int or None Mininum allowed value. maxval : int or None Maxim...
def read_value(ftype, prompt, default=None, minval=None, maxval=None, allowed_single_chars=None, question_mark=True): """Return value read from keyboard Parameters ---------- ftype : int() or float() Function defining the expected type. prompt : str Prompt string. ...
Load recipe object, according to observing mode
def get_recipe_object(self, mode): """Load recipe object, according to observing mode""" if isinstance(mode, ObservingMode): key_mode = mode.key elif isinstance(mode, str): key_mode = mode else: key_mode = mode recipe_entry = self.recipes[key...
Load product object, according to name
def load_product_object(self, name): """Load product object, according to name""" product_entry = self.products[name] product = self._get_base_object(product_entry) return product
Load recipe object, according to observing mode
def load_product_class(self, mode): """Load recipe object, according to observing mode""" product_entry = self.products[mode] return self._get_base_class(product_entry)
Load all recipes to search for products
def depsolve(self): """Load all recipes to search for products""" # load everything requires = {} provides = {} for mode, r in self.recipes.items(): l = self.load_recipe_object(mode) for field, vv in l.requirements().items(): if vv.type.is...
Return the mode that provides a given product
def query_provides(self, product, pipeline='default', search=False): """Return the mode that provides a given product""" if search: return self.search_mode_provides(product) pipe = self.pipelines[pipeline] try: return pipe.who_provides(product) except Ke...
Search the mode that provides a given product
def search_mode_provides(self, product, pipeline='default'): """Search the mode that provides a given product""" pipeline = self.pipelines[pipeline] for obj, mode, field in self.iterate_mode_provides(self.modes, pipeline): # extract name from obj if obj.name() == product...
Return the mode that provides a given product
def iterate_mode_provides(self, modes, pipeline): """Return the mode that provides a given product""" for mode_key, mode in modes.items(): try: recipe = pipeline.get_recipe_object(mode_key) for key, provide in recipe.products().items(): if...
Select instrument configuration based on OB
def select_configuration(self, obresult): """Select instrument configuration based on OB""" logger = logging.getLogger(__name__) logger.debug('calling default configuration selector') # get first possible image ref = obresult.get_sample_frame() extr = self.datamodel.ext...
Select instrument profile based on OB
def select_profile(self, obresult): """Select instrument profile based on OB""" logger = logging.getLogger(__name__) logger.debug('calling default profile selector') # check configuration insconf = obresult.configuration if insconf != 'default': key = insconf...
Build a recipe object from a given mode name
def get_recipe_object(self, mode_name, pipeline_name='default'): """Build a recipe object from a given mode name""" active_mode = self.modes[mode_name] active_pipeline = self.pipelines[pipeline_name] recipe = active_pipeline.get_recipe_object(active_mode) return recipe
Ask the user to press RETURN to continue after plotting. Parameters ---------- debugplot : int Determines whether intermediate computations and/or plots are displayed: 00 : no debug, no plots 01 : no debug, plots without pauses 02 : no debug, plots with pauses ...
def pause_debugplot(debugplot, optional_prompt=None, pltshow=False, tight_layout=True): """Ask the user to press RETURN to continue after plotting. Parameters ---------- debugplot : int Determines whether intermediate computations and/or plots are displayed: ...
Estimate the mode using the Half Sample mode. A method to estimate the mode, as described in D. R. Bickel and R. Frühwirth (contributed equally), "On a fast, robust estimator of the mode: Comparisons to other robust estimators with applications," Computational Statistics and Data Analysis 50, 3500-...
def mode_half_sample(a, is_sorted=False): ''' Estimate the mode using the Half Sample mode. A method to estimate the mode, as described in D. R. Bickel and R. Frühwirth (contributed equally), "On a fast, robust estimator of the mode: Comparisons to other robust estimators with applications," ...
Overplot a ds9 region file. Parameters ---------- filename : str File name of the ds9 region file. ax : matplotlib axes instance Matplotlib axes instance.
def overplot_ds9reg(filename, ax): """Overplot a ds9 region file. Parameters ---------- filename : str File name of the ds9 region file. ax : matplotlib axes instance Matplotlib axes instance. """ # read ds9 region file with open(filename) as f: file_content = ...
Find indexes of peaks in a 1d array. Note that window_width must be an odd number. The function imposes that the fluxes in the window_width /2 points to the left (and right) of the peak decrease monotonously as one moves away from the peak, except that it allows fpeak constant values around the peak. ...
def find_peaks_indexes(arr, window_width=5, threshold=0.0, fpeak=0): """Find indexes of peaks in a 1d array. Note that window_width must be an odd number. The function imposes that the fluxes in the window_width /2 points to the left (and right) of the peak decrease monotonously as one moves away from ...
Refine the peak location previously found by find_peaks_indexes Parameters ---------- arr : 1d numpy array, float Input 1D spectrum. ipeaks : 1d numpy array (int) Indices of the input array arr in which the peaks were initially found. window_width : int Width of the window w...
def refine_peaks(arr, ipeaks, window_width): """Refine the peak location previously found by find_peaks_indexes Parameters ---------- arr : 1d numpy array, float Input 1D spectrum. ipeaks : 1d numpy array (int) Indices of the input array arr in which the peaks were initially found. ...
Complete config with default values
def complete_config(config): """Complete config with default values""" if not config.has_section('run'): config.add_section('run') values = { 'basedir': os.getcwd(), 'task_control': 'control.yaml', } for k, v in values.items(): if not config.has_option('run', k): ...
returns x, y, background, status, message status is: * 0: not recentering * 1: recentering successful * 2: maximum distance reached * 3: not converged
def centering_centroid(data, xi, yi, box, nloop=10, toldist=1e-3, maxdist=10.0): ''' returns x, y, background, status, message status is: * 0: not recentering * 1: recentering successful * 2: maximum distance reached * 3: not converged ...
Set Cache-Control headers and Expires-header. Expects a timedelta instance.
def cache_for(**timedelta_kw): """ Set Cache-Control headers and Expires-header. Expects a timedelta instance. """ max_age_timedelta = timedelta(**timedelta_kw) def decorate_func(func): @wraps(func) def decorate_func_call(*a, **kw): callback = SetCacheControlHeaders...
Set Cache-Control headers. Expects keyword arguments and/or an item list. Each pair is used to set Flask Response.cache_control attributes, where the key is the attribute name and the value is its value. Use True as value for attributes without values. In case of an invalid attribute, CacheContr...
def cache(*cache_control_items, **cache_control_kw): """ Set Cache-Control headers. Expects keyword arguments and/or an item list. Each pair is used to set Flask Response.cache_control attributes, where the key is the attribute name and the value is its value. Use True as value for attributes...
Set Cache-Control headers for no caching Will generate proxy-revalidate, no-cache, no-store, must-revalidate, max-age=0.
def dont_cache(): """ Set Cache-Control headers for no caching Will generate proxy-revalidate, no-cache, no-store, must-revalidate, max-age=0. """ def decorate_func(func): @wraps(func) def decorate_func_call(*a, **kw): callback = SetCacheControlHeadersForNoCachingCal...
Decorator that is filtering empty parameters. :param func: function that you want wrapping :type func: function
def filter_empty_parameters(func): """Decorator that is filtering empty parameters. :param func: function that you want wrapping :type func: function """ @wraps(func) def func_wrapper(self, *args, **kwargs): my_kwargs = {key: value for key, value in kwargs.items() i...
Detect and normalize an author UID schema. Args: uid (string): a UID string schema (string): try to resolve to schema Returns: Tuple[string, string]: a tuple (uid, schema) where: - uid: the UID normalized to comply with the id.json schema - schema: a schema of the UID o...
def author_id_normalize_and_schema(uid, schema=None): """Detect and normalize an author UID schema. Args: uid (string): a UID string schema (string): try to resolve to schema Returns: Tuple[string, string]: a tuple (uid, schema) where: - uid: the UID normalized to comply wi...
Normalize arXiv category to be schema compliant. This properly capitalizes the category and replaces the dash by a dot if needed. If the category is obsolete, it also gets converted it to its current equivalent. Example: >>> from inspire_schemas.utils import normalize_arxiv_category >>...
def normalize_arxiv_category(category): """Normalize arXiv category to be schema compliant. This properly capitalizes the category and replaces the dash by a dot if needed. If the category is obsolete, it also gets converted it to its current equivalent. Example: >>> from inspire_schemas.u...
List of all arXiv categories that ever existed. Example: >>> from inspire_schemas.utils import valid_arxiv_categories >>> 'funct-an' in valid_arxiv_categories() True
def valid_arxiv_categories(): """List of all arXiv categories that ever existed. Example: >>> from inspire_schemas.utils import valid_arxiv_categories >>> 'funct-an' in valid_arxiv_categories() True """ schema = load_schema('elements/arxiv_categories') categories = schema['...
Normalize ``value`` to an Inspire category. Args: value(str): an Inspire category to properly case, or an arXiv category to translate to the corresponding Inspire category. Returns: str: ``None`` if ``value`` is not a non-empty string, otherwise the corresponding Inspir...
def classify_field(value): """Normalize ``value`` to an Inspire category. Args: value(str): an Inspire category to properly case, or an arXiv category to translate to the corresponding Inspire category. Returns: str: ``None`` if ``value`` is not a non-empty string, ...
Split page_artid into page_start/end and artid.
def split_page_artid(page_artid): """Split page_artid into page_start/end and artid.""" page_start = None page_end = None artid = None if not page_artid: return None, None, None # normalize unicode dashes page_artid = unidecode(six.text_type(page_artid)) if '-' in page_artid: ...
Split pubnote into journal information.
def split_pubnote(pubnote_str): """Split pubnote into journal information.""" pubnote = {} parts = pubnote_str.split(',') if len(parts) > 2: pubnote['journal_title'] = parts[0] pubnote['journal_volume'] = parts[1] pubnote['page_start'], pubnote['page_end'], pubnote['artid'] = sp...
Build pubnote string from parts (reverse of split_pubnote).
def build_pubnote(title, volume, page_start=None, page_end=None, artid=None): """Build pubnote string from parts (reverse of split_pubnote).""" if title and volume and artid and artid != page_start: pubnote_format = u'{title},{volume},{artid}' elif title and volume and page_start and page_end: ...
Retrieve the installed path for the given schema. Args: schema(str): relative or absolute url of the schema to validate, for example, 'records/authors.json' or 'jobs.json', or just the name of the schema, like 'jobs'. resolved(bool): if True, the returned path points to a fu...
def get_schema_path(schema, resolved=False): """Retrieve the installed path for the given schema. Args: schema(str): relative or absolute url of the schema to validate, for example, 'records/authors.json' or 'jobs.json', or just the name of the schema, like 'jobs'. resol...
Load the given schema from wherever it's installed. Args: schema_name(str): Name of the schema to load, for example 'authors'. resolved(bool): If True will return the resolved schema, that is with all the $refs replaced by their targets. Returns: dict: the schema with the g...
def load_schema(schema_name, resolved=False): """Load the given schema from wherever it's installed. Args: schema_name(str): Name of the schema to load, for example 'authors'. resolved(bool): If True will return the resolved schema, that is with all the $refs replaced by their targe...
Load the schema from a given record. Args: data (dict): record data. schema (Union[dict, str]): schema to validate against. Returns: dict: the loaded schema. Raises: SchemaNotFound: if the given schema was not found. SchemaKeyNotFound: if ``schema`` is ``None`` and...
def _load_schema_for_record(data, schema=None): """Load the schema from a given record. Args: data (dict): record data. schema (Union[dict, str]): schema to validate against. Returns: dict: the loaded schema. Raises: SchemaNotFound: if the given schema was not found. ...
Validate the given dictionary against the given schema. Args: data (dict): record to validate. schema (Union[dict, str]): schema to validate against. If it is a string, it is intepreted as the name of the schema to load (e.g. ``authors`` or ``jobs``). If it is ``None``, the ...
def validate(data, schema=None): """Validate the given dictionary against the given schema. Args: data (dict): record to validate. schema (Union[dict, str]): schema to validate against. If it is a string, it is intepreted as the name of the schema to load (e.g. ``authors...
Validation errors for a given record. Args: data (dict): record to validate. schema (Union[dict, str]): schema to validate against. If it is a string, it is intepreted as the name of the schema to load (e.g. ``authors`` or ``jobs``). If it is ``None``, the schema is taken ...
def get_validation_errors(data, schema=None): """Validation errors for a given record. Args: data (dict): record to validate. schema (Union[dict, str]): schema to validate against. If it is a string, it is intepreted as the name of the schema to load (e.g. ``authors`` or...
Normalize collaboration string. Args: collaboration: a string containing collaboration(s) or None Returns: list: List of extracted and normalized collaborations Examples: >>> from inspire_schemas.utils import normalize_collaboration >>> normalize_collaboration('for the CMS...
def normalize_collaboration(collaboration): """Normalize collaboration string. Args: collaboration: a string containing collaboration(s) or None Returns: list: List of extracted and normalized collaborations Examples: >>> from inspire_schemas.utils import normalize_collaborati...
Get the license abbreviation from an URL. Args: url(str): canonical url of the license. Returns: str: the corresponding license abbreviation. Raises: ValueError: when the url is not recognized
def get_license_from_url(url): """Get the license abbreviation from an URL. Args: url(str): canonical url of the license. Returns: str: the corresponding license abbreviation. Raises: ValueError: when the url is not recognized """ if not url: return split_...
Convert a ``publication_info`` value from the old format to the new. On Legacy different series of the same journal were modeled by adding the letter part of the name to the journal volume. For example, a paper published in Physical Review D contained:: { 'publication_info': [ ...
def convert_old_publication_info_to_new(publication_infos): """Convert a ``publication_info`` value from the old format to the new. On Legacy different series of the same journal were modeled by adding the letter part of the name to the journal volume. For example, a paper published in Physical Review ...
Convert back a ``publication_info`` value from the new format to the old. Does the inverse transformation of :func:`convert_old_publication_info_to_new`, to be used whenever we are sending back records from Labs to Legacy. Args: publication_infos: a ``publication_info`` in the new format. Ret...
def convert_new_publication_info_to_old(publication_infos): """Convert back a ``publication_info`` value from the new format to the old. Does the inverse transformation of :func:`convert_old_publication_info_to_new`, to be used whenever we are sending back records from Labs to Legacy. Args: pu...
Used to parse an incorect url to try to fix it with the most common ocurrences for errors. If the fixed url is still incorrect, it returns ``None``. Returns: String containing the fixed url or the original one if it could not be fixed.
def fix_reference_url(url): """Used to parse an incorect url to try to fix it with the most common ocurrences for errors. If the fixed url is still incorrect, it returns ``None``. Returns: String containing the fixed url or the original one if it could not be fixed. """ new_url = url n...
Return ``True`` if ``obj`` contains an arXiv identifier. The ``idutils`` library's ``is_arxiv`` function has been modified here to work with two regular expressions instead of three and adding a check for valid arxiv categories only
def is_arxiv(obj): """Return ``True`` if ``obj`` contains an arXiv identifier. The ``idutils`` library's ``is_arxiv`` function has been modified here to work with two regular expressions instead of three and adding a check for valid arxiv categories only""" arxiv_test = obj.split() if not arxiv...
Return a normalized arXiv identifier from ``obj``.
def normalize_arxiv(obj): """Return a normalized arXiv identifier from ``obj``.""" obj = obj.split()[0] matched_arxiv_pre = RE_ARXIV_PRE_2007_CLASS.match(obj) if matched_arxiv_pre: return ('/'.join(matched_arxiv_pre.group("extraidentifier", "identifier"))).lower() matched_arxiv_post = RE_A...
Resolve a uri or relative path to a schema.
def resolve_remote(self, uri): """Resolve a uri or relative path to a schema.""" try: return super(LocalRefResolver, self).resolve_remote(uri) except ValueError: return super(LocalRefResolver, self).resolve_remote( 'file://' + get_schema_path(uri.rsplit('....
Set the path of the file.
def set_path(self, path): """Set the path of the file.""" if os.path.isabs(path): path = os.path.normpath(os.path.join(self.cwd, path)) self.path = path self.relative = os.path.relpath(self.path, self.base)
Clone the file.
def clone(self, path = None, *, with_contents = True, **options): """Clone the file.""" file = File(path if path else self.path, cwd=options.get("cwd", self.cwd)) file.base = options.get("base", self.base) if with_contents: file.contents = options.get("contents", self.contents) return file
Function called when a file need to be transformed.
async def transform(self, file): """Function called when a file need to be transformed.""" file.contents = await self.loop.run_in_executor(self.exe, read_file, file.path) return file
Launch the CLI.
def launch_cli(): """Launch the CLI.""" # Create the CLI argument parser parser = argparse.ArgumentParser( prog="pylp", description="Call some tasks defined in your pylpfile." ) # Version of Pylp parser.add_argument("-v", "--version", action="version", version="Pylp %s" % version, help="get the Pylp ...
Auxiliary function to display a numpy 2d array. Parameters ---------- image2d : 2d numpy array, float 2d image to be displayed. title : string Plot title. cbar_label : string Color bar label. cbar_orientation : string Color bar orientation: valid options are 'hor...
def ximshow(image2d, title=None, show=True, cbar_label=None, cbar_orientation=None, z1z2=None, cmap="hot", image_bbox=None, first_pixel=(1,1), crpix1=None, crval1=None, cdelt1=None, ds9regfile=None, geometry=(0, 0, 640, 480), tight_layout=True, ...
Function to execute ximshow() as called from command line. Parameters ---------- singlefile : string Name of the FITS file to be displayed. args_cbar_label : string Color bar label. args_cbar_orientation : string Color bar orientation: valid options are 'horizontal' or ...
def ximshow_file(singlefile, args_cbar_label=None, args_cbar_orientation=None, args_z1z2=None, args_bbox=None, args_firstpix=None, args_keystitle=None, args_ds9reg=None, args_geometry="0,0,640,480", pdf=None, show=True, debugplot=None,...
Add an affiliation. Args: value (string): affiliation value curated_relation (bool): is relation curated record (dict): affiliation JSON reference
def add_affiliation(self, value, curated_relation=None, record=None): """Add an affiliation. Args: value (string): affiliation value curated_relation (bool): is relation curated record (dict): affiliation JSON reference """ if value: affil...
Set a unique ID. If a UID of a given schema already exists in a record it will be overwritten, otherwise it will be appended to the record. Args: uid (string): unique identifier. schema (Optional[string]): schema of the unique identifier. If ``None``, th...
def set_uid(self, uid, schema=None): """Set a unique ID. If a UID of a given schema already exists in a record it will be overwritten, otherwise it will be appended to the record. Args: uid (string): unique identifier. schema (Optional[string]): schema of the un...
Create singleton from class
def singleton(klass): """ Create singleton from class """ instances = {} def getinstance(*args, **kwargs): if klass not in instances: instances[klass] = klass(*args, **kwargs) return instances[klass] return wraps(klass)(getinstance)
Activate language only for one method or function
def translation_activate_block(function=None, language=None): """ Activate language only for one method or function """ def _translation_activate_block(function): def _decorator(*args, **kwargs): tmp_language = translation.get_language() try: translation....
Make a request against air-matters.com.
async def request( self, method: str, endpoint: str, *, headers: dict = None, params: dict = None) -> dict: """Make a request against air-matters.com.""" url = '{0}/{1}'.format(API_URL_SCAFFOLD, endpoint) if not headers: ...
Get data on when a UV protection window is.
async def uv_protection_window( self, low: float = 3.5, high: float = 3.5) -> dict: """Get data on when a UV protection window is.""" return await self.request( 'get', 'protection', params={ 'from': str(low), 'to': str(high) })
Return the run number and the file name.
def runstring(self): """Return the run number and the file name.""" cfile = self.template % self.last self.last += 1 return cfile
Returns the first coincidence...
def search_prod_obsid(self, ins, obsid, pipeline): """Returns the first coincidence...""" ins_prod = self.prod_table[ins] # search results of these OBs for prod in ins_prod: if prod['ob'] == obsid: # We have found the result, no more checks re...
Returns the first coincidence...
def search_prod_type_tags(self, tipo, ins, tags, pipeline): """Returns the first coincidence...""" drp = self.drps.query_by_name(ins) label = drp.product_label(tipo) # Strip () is present if label.endswith("()"): label_alt = label[:-2] else: labe...
Override instrument configuration if configuration is not None
def obsres_from_oblock_id(self, obsid, configuration=None): """" Override instrument configuration if configuration is not None """ este = self.ob_table[obsid] obsres = obsres_from_dict(este) _logger.debug("obsres_from_oblock_id id='%s', mode='%s' START", obsid, obsres.mo...
Returns the first coincidence...
def _search_prod_table(self, name, tipo, obsres): """Returns the first coincidence...""" instrument = obsres.instrument conf = obsres.configuration.uuid drp = self.drps.query_by_name(instrument) label = drp.product_label(tipo) # Strip () is present if label.end...
Returns the first coincidence...
def _search_result(self, name, tipo, obsres, resultid): """Returns the first coincidence...""" instrument = obsres.instrument conf = obsres.configuration.uuid drp = self.drps.query_by_name(instrument) label = drp.product_label(tipo) # search results of these OBs ...
load igrf12 coeffs from file :param filename: file which save coeffs (str) :return: g and h list one by one (list(float))
def loadCoeffs(filename): """ load igrf12 coeffs from file :param filename: file which save coeffs (str) :return: g and h list one by one (list(float)) """ gh = [] gh2arr = [] with open(filename) as f: text = f.readlines() for a in text: if a[:2] == 'g ' or a[...
:param gh: list from loadCoeffs :param date: float :return: list: g, list: h
def getCoeffs(date): """ :param gh: list from loadCoeffs :param date: float :return: list: g, list: h """ if date < 1900.0 or date > 2025.0: print('This subroutine will not work with a date of ' + str(date)) print('Date must be in the range 1900.0 <= date <= 2025.0') prin...
Apply function to nodes
def map_tree(visitor, tree): """Apply function to nodes""" newn = [map_tree(visitor, node) for node in tree.nodes] return visitor(tree, newn)
Return parts of the tree that fulfill condition
def filter_tree(condition, tree): """Return parts of the tree that fulfill condition""" if condition(tree): for node in tree.nodes: # this works in python > 3.3 # yield from filter_tree(condition, node) for n in filter_tree(condition, node): yield n ...
Substitute Placeholder nodes by its value in tags
def fill_placeholders(self, tags): """Substitute Placeholder nodes by its value in tags""" def change_p_node_tags(node, children): if isinstance(node, Placeholder): value = ConstExpr(tags[node.name]) return value else: return node.c...
Take a list of molecules and return just a list of atomic symbols, possibly adding hydrogen
def molecules2symbols(molecules, add_hydrogen=True): """Take a list of molecules and return just a list of atomic symbols, possibly adding hydrogen """ symbols = sorted( list(set( ase.symbols.string2symbols(''.join( map( lambda _x: ...
Take a list of symbols and construct gas phase references system, when possible avoiding O2. Candidates can be rearranged, where earlier candidates get higher preference than later candidates assume symbols sorted by atomic number
def construct_reference_system( symbols, candidates=None, options=None, ): """Take a list of symbols and construct gas phase references system, when possible avoiding O2. Candidates can be rearranged, where earlier candidates get higher preference than later candidates assume symbols so...
Given a list of references (tuples of (symbol, molecule)) return stoichiometry matrix that connects atomic symbols to its molecular references.
def get_atomic_stoichiometry(references): """Given a list of references (tuples of (symbol, molecule)) return stoichiometry matrix that connects atomic symbols to its molecular references. """ n = len(references) stoichiometry = np.ndarray((n, n), float) stoichiometry[:] = 0. key_index =...
Take a list of adsorabtes and a corresponding reference system and return a list of dictionaries encoding the stoichiometry factors converting between adsorbates and reference molecules.
def get_stoichiometry_factors(adsorbates, references): """Take a list of adsorabtes and a corresponding reference system and return a list of dictionaries encoding the stoichiometry factors converting between adsorbates and reference molecules. """ stoichiometry = get_atomic_stoichiometry(refere...
Returns a dict of field name and cleaned value pairs to initialize the model. Beware, it aligns the lists of fields and row values with Nones to allow for adding fields not found in the CSV. Whitespace around the value of the cell is stripped.
def get_fields_dict(self, row): """ Returns a dict of field name and cleaned value pairs to initialize the model. Beware, it aligns the lists of fields and row values with Nones to allow for adding fields not found in the CSV. Whitespace around the value of the cell is stripped. ...
Process a node in result.json structure
def process_node(node): """Process a node in result.json structure""" value = node['value'] mname = node['name'] typeid = node['typeid'] if typeid == 52: # StructDataValue obj = {} for el in value['elements']: key, val = process_node(el) obj[key] = val ...
Create a dictionary with the contents of result.json
def build_result(data): """Create a dictionary with the contents of result.json""" more = {} for key, value in data.items(): if key != 'elements': newnode = value else: newnode = {} for el in value: nkey, nvalue = process_node(el) ...
Load all available DRPs in 'entry_point'.
def load(self): """Load all available DRPs in 'entry_point'.""" for drpins in self.iload(self.entry): self.drps[drpins.name] = drpins return self
Load all available DRPs in 'entry_point'.
def load_drp(self, name, entry_point='numina.pipeline.1'): """Load all available DRPs in 'entry_point'.""" for drpins in self.iload(entry_point): if drpins.name == name: return drpins else: raise KeyError('{}'.format(name))
Load all available DRPs in 'entry_point'.
def iload(cls, entry_point='numina.pipeline.1'): """Load all available DRPs in 'entry_point'.""" for entry in pkg_resources.iter_entry_points(group=entry_point): try: drp_loader = entry.load() drpins = drp_loader() if cls.instrumentdrp_check(d...
Access all the instance descriptors This wil trigger an exception if a required parameter is not set
def _finalize(self, all_msg_errors=None): """Access all the instance descriptors This wil trigger an exception if a required parameter is not set """ if all_msg_errors is None: all_msg_errors = [] for key in self.stored(): try: ge...
Validate myself.
def validate(self): """Validate myself.""" for key, req in self.stored().items(): val = getattr(self, key) req.validate(val) # Run checks defined in __checkers__ self._run_checks()
Decorate run method, inputs and outputs are validated
def validate(method): """Decorate run method, inputs and outputs are validated""" @wraps(method) def mod_run(self, rinput): self.validate_input(rinput) # result = method(self, rinput) # self.validate_result(result) return result return mod_run
Convert a scalar validator in a list validator
def as_list(callable): """Convert a scalar validator in a list validator""" @wraps(callable) def wrapper(value_iter): return [callable(value) for value in value_iter] return wrapper
Generates a function that validates that a number is within range Parameters ========== minval: numeric, optional: Values strictly lesser than `minval` are rejected maxval: numeric, optional: Values strictly greater than `maxval` are rejected Returns ======= A function that...
def range_validator(minval=None, maxval=None): """Generates a function that validates that a number is within range Parameters ========== minval: numeric, optional: Values strictly lesser than `minval` are rejected maxval: numeric, optional: Values strictly greater than `maxval` are...
Run a pylpfile.
def run(path, tasks): """Run a pylpfile.""" # Test if the pylpfile exists readable_path = make_readable_path(path) if not os.path.isfile(path): logger.log(logger.red("Can't read pylpfile "), logger.magenta(readable_path)) sys.exit(-1) else: logger.log("Using pylpfile ", logger.magenta(readable_path)) # R...
Wait until all task are executed.
async def wait_and_quit(loop): """Wait until all task are executed.""" from pylp.lib.tasks import running if running: await asyncio.wait(map(lambda runner: runner.future, running))
Return True if a record is published. We say that a record is published if it is citeable, which means that it has enough information in a ``publication_info``, or if we know its DOI and a ``journal_title``, which means it is in press. Returns: bool: whether the record is p...
def is_published(self): """Return True if a record is published. We say that a record is published if it is citeable, which means that it has enough information in a ``publication_info``, or if we know its DOI and a ``journal_title``, which means it is in press. Returns: ...
Return the page range or the article id of a publication_info entry. Args: publication_info(dict): a publication_info field entry of a record separator(basestring): optional page range symbol, defaults to a single dash Returns: string: the page range or the article ...
def get_page_artid_for_publication_info(publication_info, separator): """Return the page range or the article id of a publication_info entry. Args: publication_info(dict): a publication_info field entry of a record separator(basestring): optional page range symbol, defaults to a...
Return the page range or the article id of a record. Args: separator(basestring): optional page range symbol, defaults to a single dash Returns: string: the page range or the article id of the record. Examples: >>> record = { ... 'publicatio...
def get_page_artid(self, separator='-'): """Return the page range or the article id of a record. Args: separator(basestring): optional page range symbol, defaults to a single dash Returns: string: the page range or the article id of the record. Examples: ...
Yield integers of dtype bit-length reverting their bit-order. >>> list(chunkreverse([0b10000000, 0b11000000, 0b00000001], 'B')) [1, 3, 128] >>> list(chunkreverse([0x8000, 0xC000, 0x0001], 'H')) [1, 3, 32768]
def chunkreverse(integers, dtype='L'): """Yield integers of dtype bit-length reverting their bit-order. >>> list(chunkreverse([0b10000000, 0b11000000, 0b00000001], 'B')) [1, 3, 128] >>> list(chunkreverse([0x8000, 0xC000, 0x0001], 'H')) [1, 3, 32768] """ if dtype in ('B', 8): return...
Return integer concatenating integer chunks of r > 0 bit-length. >>> pack([0, 1, 0, 1, 0, 1], 1) 42 >>> pack([0, 1], 8) 256 >>> pack([0, 1], 0) Traceback (most recent call last): ... ValueError: pack needs r > 0
def pack(chunks, r=32): """Return integer concatenating integer chunks of r > 0 bit-length. >>> pack([0, 1, 0, 1, 0, 1], 1) 42 >>> pack([0, 1], 8) 256 >>> pack([0, 1], 0) Traceback (most recent call last): ... ValueError: pack needs r > 0 """ if r < 1: raise Va...
Yield integers concatenating bools in chunks of dtype bit-length. >>> list(packbools([False, True, False, True, False, True], 'B')) [42]
def packbools(bools, dtype='L'): """Yield integers concatenating bools in chunks of dtype bit-length. >>> list(packbools([False, True, False, True, False, True], 'B')) [42] """ r = NBITS[dtype] atoms = ATOMS[dtype] for chunk in zip_longest(*[iter(bools)] * r, fillvalue=False): yiel...
Yield booleans unpacking integers of dtype bit-length. >>> list(unpackbools([42], 'B')) [False, True, False, True, False, True, False, False]
def unpackbools(integers, dtype='L'): """Yield booleans unpacking integers of dtype bit-length. >>> list(unpackbools([42], 'B')) [False, True, False, True, False, True, False, False] """ atoms = ATOMS[dtype] for chunk in integers: for a in atoms: yield not not chunk & a
Select information from valid arc lines to facilitate posterior fits. Parameters ---------- list_of_wvfeatures : list (of WavecalFeature instances) A list of size equal to the number of identified lines, which elements are instances of the class WavecalFeature, containing all the re...
def select_data_for_fit(list_of_wvfeatures): """Select information from valid arc lines to facilitate posterior fits. Parameters ---------- list_of_wvfeatures : list (of WavecalFeature instances) A list of size equal to the number of identified lines, which elements are instances of the...
Fit polynomial to arc calibration list_of_wvfeatures. Parameters ---------- list_of_wvfeatures : list (of WavecalFeature instances) A list of size equal to the number of identified lines, which elements are instances of the class WavecalFeature, containing all the relevant informati...
def fit_list_of_wvfeatures(list_of_wvfeatures, naxis1_arc, crpix1, poly_degree_wfit, weighted=False, plot_title=None, geometry=None, ...
Compute information associated to triplets in master table. Determine all the possible triplets that can be generated from the array `wv_master`. In addition, the relative position of the central line of each triplet is also computed. Parameters ---------- wv_master : 1d numpy array, float ...
def gen_triplets_master(wv_master, geometry=None, debugplot=0): """Compute information associated to triplets in master table. Determine all the possible triplets that can be generated from the array `wv_master`. In addition, the relative position of the central line of each triplet is also computed. ...
Performs arc line identification for arc calibration. This function is a wrapper of two functions, which are responsible of computing all the relevant information concerning the triplets generated from the master table and the actual identification procedure of the arc lines, respectively. The sep...
def arccalibration(wv_master, xpos_arc, naxis1_arc, crpix1, wv_ini_search, wv_end_search, wvmin_useful, wvmax_useful, error_xpos_arc, times_sigma_r, ...
Performs line identification for arc calibration using line triplets. This function assumes that a previous call to the function responsible for the computation of information related to the triplets derived from the master table has been previously executed. Parameters ---------- wv_maste...
def arccalibration_direct(wv_master, ntriplets_master, ratios_master_sorted, triplets_master_sorted_list, xpos_arc, naxis1_arc, crpix1, wv...
Refine wavelength calibration using an initial polynomial. Parameters ---------- sp : numpy array 1D array of length NAXIS1 containing the input spectrum. poly_initial : Polynomial instance Initial wavelength calibration polynomial, providing the wavelength as a function of pixe...
def refine_arccalibration(sp, poly_initial, wv_master, poldeg, nrepeat=3, ntimes_match_wv=2, nwinwidth_initial=7, nwinwidth_refined=5, times_sigma_reject=5, interac...