text
stringlengths
81
112k
Split on file extensions, allowing for zipped extensions. def splitext_plus(fname): """Split on file extensions, allowing for zipped extensions. """ base, ext = splitext(fname) if ext in [".gz", ".bz2", ".zip"]: base, ext2 = splitext(base) ext = ext2 + ext return base, ext
Put dots instead of empty cells in order to view TSV with column -t def dots_to_empty_cells(config, tsv_fpath): """Put dots instead of empty cells in order to view TSV with column -t """ def proc_line(l, i): while '\t\t' in l: l = l.replace('\t\t', '\t.\t') return l return i...
Wrap file generation in a transaction, moving to output if finishes. def file_transaction(work_dir, *rollback_files): """Wrap file generation in a transaction, moving to output if finishes. """ exts = {".vcf": ".idx", ".bam": ".bai", "vcf.gz": ".tbi"} safe_fpaths, orig_names = _flatten_plus_safe(work_d...
Context manager to create and remove a transactional temporary directory. def tx_tmpdir(base_dir, rollback_dirpath): """Context manager to create and remove a transactional temporary directory. """ # tmp_dir_base = join(base_dir, 'tx', str(uuid.uuid4())) # unique_attempts = 0 # while os.path.exists...
Flatten names of files and create temporary file names. def _flatten_plus_safe(tmp_dir, rollback_files): """Flatten names of files and create temporary file names. """ tx_fpaths, orig_files = [], [] for fnames in rollback_files: if isinstance(fnames, six.string_types): fnames = [fna...
Merge bed file intervals to avoid overlapping regions. Overlapping regions (1:1-100, 1:90-100) cause issues with callers like FreeBayes that don't collapse BEDs prior to using them. def merge_overlaps(work_dir, bed_fpath, distance=None): """Merge bed file intervals to avoid overlapping regions. Overlap...
************************************************************************************************************************************************************ Task: checks the format of the bed file. The only requirements checked are that each line presents at least 3 tab separated columns, the two on...
Trigger callbacks for all keys on all or a subset of subscribers. :param Iterable callbacks: list of callbacks or none for all subscribed :rtype: Iterable[tornado.concurrent.Future] def trigger_all_callbacks(self, callbacks=None): """Trigger callbacks for all keys on all or a subset of subscri...
Set a value at key and return a Future. :rtype: Iterable[tornado.concurrent.Future] def set(self, key, value): """Set a value at key and return a Future. :rtype: Iterable[tornado.concurrent.Future] """ value_encoded = encode(value) if key in self.data and self.data[ke...
Update the datastore. :param func|dict updater: (state) => state_change or dict state_change :rtype: Iterable[tornado.concurrent.Future] def set_state(self, updater=None, **kwargs): """Update the datastore. :param func|dict updater: (state) => state_change or dict state_change ...
Initialize datastore. Only sets values for keys that are not in the datastore already. :param dict key_value_pairs: A set of key value pairs to use to initialize the datastore. :rtype: Iterable[tornado.concurrent.Future] def init(self, key_value_pairs=None, **kwargs): """...
Close and delete instance. def close(self): """Close and delete instance.""" # remove callbacks Datastore.stores[self.domain].remove(self) # delete data after the last instance is gone if self.release_storage and not Datastore.stores[self.domain]: del Datastore.glo...
1. Generates Qualimap2 plots and put into plots_dirpath 2. Adds records to targqc_full_report.plots def run_multisample_qualimap(output_dir, work_dir, samples, targqc_full_report): """ 1. Generates Qualimap2 plots and put into plots_dirpath 2. Adds records to targqc_full_report.plots """ pl...
r"""Convert the ODT object function to refractive index In :abbr:`ODT (Optical Diffraction Tomography)`, the object function is defined by the Helmholtz equation .. math:: f(\mathbf{r}) = k_\mathrm{m}^2 \left[ \left( \frac{n(\mathbf{r})}{n_\mathrm{m}} \right)^2 - 1 \righ...
r"""Convert the OPT object function to refractive index In :abbr:`OPT (Optical Projection Tomography)`, the object function is computed from the raw phase data. This method converts phase data to refractive index data. .. math:: n(\mathbf{r}) = n_\mathrm{m} + \frac{f(\mathbf{r}) ...
rasterize a vector object Parameters ---------- vectorobject: Vector the vector object to be rasterized reference: Raster a reference Raster object to retrieve geo information and extent from outname: str or None the name of the GeoTiff output file; if None, an in-memory obj...
reproject a raster file Parameters ---------- rasterobject: Raster or str the raster image to be reprojected reference: Raster, Vector, str, int or osr.SpatialReference either a projection string or a spatial object with an attribute 'projection' outname: str the name of the...
function for mosaicking, resampling and stacking of multiple raster files into a 3D data cube Parameters ---------- srcfiles: list a list of file names or a list of lists; each sub-list is treated as a task to mosaic its containing files dstfile: str the destination file or a directory ...
Compute some basic raster statistics Parameters ---------- approximate: bool approximate statistics from overviews or a subset of all tiles? Returns ------- list of dicts a list with a dictionary of statistics for each band. Keys: `min`, `max`, `...
read all raster bands into a numpy ndarray Returns ------- numpy.ndarray the array containing all raster data def array(self): """ read all raster bands into a numpy ndarray Returns ------- numpy.ndarray the array containing all ...
set the names of the raster bands Parameters ---------- names: list of str the names to be set; must be of same length as the number of bands Returns ------- def bandnames(self, names): """ set the names of the raster bands Parameters ...
Parameters ---------- outname: str or None the name of the file to write; If `None`, the bounding box is returned as vector object format: str The file format to write overwrite: bool overwrite an already existing file? Returns -------...
extract weighted average of pixels intersecting with a defined radius to a point. Parameters ---------- px: int or float the x coordinate in units of the Raster SRS py: int or float the y coordinate in units of the Raster SRS radius: int or float ...
General image geo information. Returns ------- dict a dictionary with keys `xmin`, `xmax`, `xres`, `rotation_x`, `ymin`, `ymax`, `yres`, `rotation_y` def geo(self): """ General image geo information. Returns ------- dict a dictio...
Check image integrity. Tries to compute the checksum for each raster layer and returns False if this fails. See this forum entry: `How to check if image is valid? <https://lists.osgeo.org/pipermail/gdal-dev/2013-November/037520.html>`_. Returns ------- bool i...
load all raster data to internal memory arrays. This shortens the read time of other methods like :meth:`matrix`. def load(self): """ load all raster data to internal memory arrays. This shortens the read time of other methods like :meth:`matrix`. """ for i in range(1, s...
read a raster band (subset) into a numpy ndarray Parameters ---------- band: int the band to read the matrix from; 1-based indexing mask_nan: bool convert nodata values to :obj:`numpy.nan`? As :obj:`numpy.nan` requires at least float values, any integer array is ...
the raster resolution in x and y direction Returns ------- tuple (xres, yres) def res(self): """ the raster resolution in x and y direction Returns ------- tuple (xres, yres) """ return (abs(float(self.geo['xres']...
perform raster computations with custom functions and assign them to the existing raster object in memory Parameters ---------- fun: function the custom function to compute on the data Examples -------- >>> with Raster('filename') as ras: >>> ras...
write the raster object to a file. Parameters ---------- outname: str the file to be written dtype: str the data type of the written file; data type notations of GDAL (e.g. `Float32`) and numpy (e.g. `int8`) are supported. format: str ...
create a dictionary for mapping numpy data types to GDAL data type codes Returns ------- dict the type map def numpy2gdalint(self): """ create a dictionary for mapping numpy data types to GDAL data type codes Returns ------- dict ...
Parse object describing static routes. Might be a list, a dict or a list of dicts. def static_parser(static): """Parse object describing static routes. Might be a list, a dict or a list of dicts. """ if static is None: return if isinstance(static, dict): ...
Add analyses from the analyses folder. def analyses_info(self): """Add analyses from the analyses folder.""" f_config = os.path.join(self.analyses_path, 'index.yaml') tornado.autoreload.watch(f_config) with io.open(f_config, 'r', encoding='utf8') as f: config = yaml.safe_loa...
register metas def register_metas(self): """register metas""" # concatenate some attributes to global lists: aggregated = {'build': [], 'watch': []} for attribute, values in aggregated.items(): for info in self.info['analyses'] + [self.info]: if attribute in...
Run the build command specified in index.yaml. def build(self): """Run the build command specified in index.yaml.""" for cmd in self.build_cmds: log.info('building command: {}'.format(cmd)) full_cmd = 'cd {}; {}'.format(self.analyses_path, cmd) log.debug('full comman...
Render the List-of-Analyses overview page. def get(self): """Render the List-of-Analyses overview page.""" return self.render( 'index.html', databench_version=DATABENCH_VERSION, meta_infos=self.meta_infos(), **self.info )
Reset Axis and set default parameters for H-bridge def Reset(self): ' Reset Axis and set default parameters for H-bridge ' spi.SPI_write_byte(self.CS, 0xC0) # reset # spi.SPI_write_byte(self.CS, 0x14) # Stall Treshold setup # spi.SPI_write_byte(self.CS, 0xFF) # spi.SPI_...
Initializer for pool for _mprotate def _init_worker(X, X_shape, X_dtype): """Initializer for pool for _mprotate""" # Using a dictionary is not strictly necessary. You can also # use global variables. mprotate_dict["X"] = X mprotate_dict["X_shape"] = X_shape mprotate_dict["X_dtype"] = X_dtype
Uses multiprocessing to wrap around _rotate 4x speedup on an intel i7-3820 CPU @ 3.60GHz with 8 cores. The function calls _rotate which accesses the `mprotate_dict`. Data is rotated in-place. Parameters ---------- ang: float rotation angle in degrees lny: int total number ...
r"""3D backpropagation Three-dimensional diffraction tomography reconstruction algorithm for scattering of a plane wave :math:`u_0(\mathbf{r}) = u_0(x,y,z)` by a dielectric object with refractive index :math:`n(x,y,z)`. This method implements the 3D backpropagation algorithm :cite:`Mueller...
Compute the weight for each angle according to the distance between its neighbors. Parameters ---------- angles: 1d ndarray of length A Angles in radians Returns ------- weights: 1d ndarray of length A The weights for each angle Notes ----- To compute the weights,...
See :meth:`pymlab.sensors.Device.initialize` for more information. Calls `initialize()` on all devices connected to the bus. def initialize(self): """See :meth:`pymlab.sensors.Device.initialize` for more information. Calls `initialize()` on all devices connected to the bus. """ ...
Writes the byte to unaddressed register in a device. def write_byte(self, address, value): """Writes the byte to unaddressed register in a device. """ LOGGER.debug("Writing byte %s to device %s!", bin(value), hex(address)) return self.driver.write_byte(address, value)
Reads unadressed byte from a device. def read_byte(self, address): """Reads unadressed byte from a device. """ LOGGER.debug("Reading byte from device %s!", hex(address)) return self.driver.read_byte(address)
Write a byte value to a device's register. def write_byte_data(self, address, register, value): """Write a byte value to a device's register. """ LOGGER.debug("Writing byte data %s to register %s on device %s", bin(value), hex(register), hex(address)) return self.driver.write_byte_d...
Write a word (two bytes) value to a device's register. def write_wdata(self, address, register, value): """Write a word (two bytes) value to a device's register. """ warnings.warn("write_wdata() is deprecated and will be removed in future versions replace with write_word_data()", DeprecationWarning) ...
Raise an appropriate error for a given response. Arguments: response (:py:class:`aiohttp.ClientResponse`): The API response. Raises: :py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate error for the response's status. This function was taken from the aslack project and m...
Generic Space-Track query coroutine. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **st) st.basicspacedata.tle_publish(*args, **st) st.file(*args, **st) st.filesh...
Get raw predicate information for given request class, and cache for subsequent calls. async def _download_predicate_data(self, class_, controller): """Get raw predicate information for given request class, and cache for subsequent calls. """ await self.authenticate() u...
parses string_value and returns only number-like part def get_numeric_value(string_value): """ parses string_value and returns only number-like part """ num_chars = ['.', '+', '-'] number = '' for c in string_value: if c.isdigit() or c in num_chars: number += c return number
Entry point to run databench. def main(**kwargs): """Entry point to run databench.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--version', action='version', version='%(prog)s {}'.format(DATABENCH_VERSION)) parser.add_argument('--log', dest='log...
Run a single analysis. :param Analysis analysis: Analysis class to run. :param str path: Path of analysis. Can be `__file__`. :param str name: Name of the analysis. :param dict info: Optional entries are ``version``, ``title``, ``readme``, ... :param dict static: Map[url regex, root-folder]...
Convert Python objects to Space-Track compatible strings - Booleans (``True`` -> ``'true'``) - Sequences (``[25544, 34602]`` -> ``'25544,34602'``) - dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``) - ``None`` -> ``'null-val'`` def _stringify_predicate_value(value): """Convert Python ob...
Returns human-readable string representation of both positional and keyword arguments passed to the function. This function uses the built-in :func:`repr()` function to convert individual arguments to string. >>> args_repr("a", (1, 2), some_keyword = list("abc")) "'a', (1, 2), some_keyword = ['a',...
Returns human-readable string representation of an object given that it has been created by calling constructor with the specified positional and keyword arguments. This is a convenience function to help implement custom `__repr__()` methods. For example: >>> class Animal(object): ... def _...
decode a binary object to str and filter out non-printable characters Parameters ---------- text: bytes the binary object to be decoded encoding: str the encoding to be used Returns ------- str the decoded and filtered string def decode_filter(text, encoding='u...
merge two dictionaries def dictmerge(x, y): """ merge two dictionaries """ z = x.copy() z.update(y) return z
list and tuple flattening Parameters ---------- inlist: list the list with sub-lists or tuples to be flattened Returns ------- list the flattened result Examples -------- >>> dissolve([[1, 2], [3, 4]]) [1, 2, 3, 4] >>> dissolve([(1, 2, (3, ...
function for finding files/folders in folders and their subdirectories Parameters ---------- target: str or list of str a directory, zip- or tar-archive or a list of them to be searched matchlist: list a list of search patterns foldermode: int * 0: only files * 1: fi...
wrapper for multicore process execution Parameters ---------- function individual function to be applied to each process item cores: int the number of subprocesses started/CPUs used; this value is reduced in case the number of subprocesses is smaller multiargs: dict ...
return the smallest possible data type for a string or list of strings Parameters ---------- x: str or list a string to be parsed Returns ------- int, float or str the parsing result Examples -------- >>> isinstance(parse_literal('1.5'), float) True ...
rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum) def rescale(inlist, newrange=(0, 1)): """ rescale the values in a list between the values in newrange (a tuple with the new minimum and maximum) """ OldMax = max(inlist) OldMin = min(inlist) ...
| wrapper for subprocess execution including logfile writing and command prompt piping | this is a convenience wrapper around the :mod:`subprocess` module and calls its class :class:`~subprocess.Popen` internally. Parameters ---------- cmd: list the command arguments outdir: str ...
parse a url query def urlQueryParser(url, querydict): """ parse a url query """ address_parse = urlparse(url) return urlunparse(address_parse._replace(query=urlencode(querydict)))
append items to the stack; input can be a single value or a list def push(self, x): """ append items to the stack; input can be a single value or a list """ if isinstance(x, list): for item in x: self.stack.append(item) else: self.stack.ap...
return the last stack element and delete it from the list def pop(self): """ return the last stack element and delete it from the list """ if not self.empty(): val = self.stack[-1] del self.stack[-1] return val
returns measured value in miligauss def axes(self, offset = False): """returns measured value in miligauss""" reg, self._scale = self.SCALES[self._gauss] x = self.bus.read_int16_data(self.address, self.HMC5883L_DXRA) if x == -4096: x = OVERFLOW y = self.bus.read_int16_data(self...
The default default formatter!. def _ToString(x): """The default default formatter!.""" # Some cross-language values for primitives. This is tested in # jsontemplate_test.py. if x is None: return 'null' if isinstance(x, six.string_types): return x return pprint.pformat(x)
dictionary -> list of pairs def _Pairs(data): """dictionary -> list of pairs""" keys = sorted(data) return [{'@key': k, '@value': data[k]} for k in keys]
Formatter to pluralize words. def _Pluralize(value, unused_context, args): """Formatter to pluralize words.""" if len(args) == 0: s, p = '', 's' elif len(args) == 1: s, p = '', args[0] elif len(args) == 2: s, p = args else: # Should have been checked at compile ...
Convert a timestamp in seconds to a string based on the format string. Returns GM time. def _StrftimeGm(value, unused_context, args): """Convert a timestamp in seconds to a string based on the format string. Returns GM time. """ time_tuple = time.gmtime(value) return _StrftimeHelper(args, time_tupl...
Convert a timestamp in seconds to a string based on the format string. Returns local time. def _StrftimeLocal(value, unused_context, args): """Convert a timestamp in seconds to a string based on the format string. Returns local time. """ time_tuple = time.localtime(value) return _StrftimeHelper(arg...
Returns whether the given name is in the current Template's template group. def _TemplateExists(unused_value, context, args): """Returns whether the given name is in the current Template's template group.""" try: name = args[0] except IndexError: raise EvaluationError('The "template" predic...
Split and validate metacharacters. Example: '{}' -> ('{', '}') This is public so the syntax highlighter and other tools can use it. def SplitMeta(meta): """Split and validate metacharacters. Example: '{}' -> ('{', '}') This is public so the syntax highlighter and other tools can use it. """ n = l...
Return a (compiled) regular expression for tokenization. Args: meta_left, meta_right: e.g. '{' and '}' - The regular expressions are memoized. - This function is public so the syntax highlighter can use it. def MakeTokenRegex(meta_left, meta_right): """Return a (compiled) regular expression for tokeniz...
Helper function for matching certain directives. def _MatchDirective(token): """Helper function for matching certain directives.""" # Tokens below must start with '.' if token.startswith('.'): token = token[1:] else: return None, None if token == 'end': return END_TOKEN...
Yields tokens, which are 2-tuples (TOKEN_TYPE, token_string). def _Tokenize(template_str, meta_left, meta_right, whitespace): """Yields tokens, which are 2-tuples (TOKEN_TYPE, token_string).""" trimlen = len(meta_left) token_re = MakeTokenRegex(meta_left, meta_right) do_strip = (whitespace == 'str...
Compile the template string, calling methods on the 'program builder'. Args: template_str: The template string. It should not have any compilation options in the header -- those are parsed by FromString/FromFile builder: The interface of _ProgramBuilder isn't fixed. Use at your own risk. ...
Like FromFile, but takes a string. def FromString(s, **kwargs): """Like FromFile, but takes a string.""" f = StringIO.StringIO(s) return FromFile(f, **kwargs)
Parse a template from a file, using a simple file format. This is useful when you want to include template options in a data file, rather than in the source code. The format is similar to HTTP or E-mail headers. The first lines of the file can specify template options, such as the metacharacters to use. One...
Construct a dictinary { template name -> Template() instance } Args: root_section: _Section instance -- root of the original parse tree def _MakeGroupFromRootSection(root_section, undefined_str): """Construct a dictinary { template name -> Template() instance } Args: root_section: _Section instance -...
Join tokens (which may be a mix of unicode and str values). See notes on unicode at the top. This function allows mixing encoded utf-8 byte string tokens with unicode tokens. (Python's default encoding is ASCII, and we don't want to change that.) We also want to support pure byte strings, so we can't get ri...
{.repeated section foo} def _DoRepeatedSection(args, context, callback, trace): """{.repeated section foo}""" block = args items = context.PushSection(block.section_name, block.pre_formatters) if items: if not isinstance(items, list): raise EvaluationError('Expected a list...
{.section foo} def _DoSection(args, context, callback, trace): """{.section foo}""" block = args # If a section present and "true", push the dictionary onto the stack as the # new context, and show it if context.PushSection(block.section_name, block.pre_formatters): _Execute(block.Statement...
{.predicate?} Here we execute the first clause that evaluates to true, and then stop. def _DoPredicates(args, context, callback, trace): """{.predicate?} Here we execute the first clause that evaluates to true, and then stop. """ block = args value = context.Lookup('@') for (predicate, args, fu...
Variable substitution, i.e. {foo} We also implement template formatters here, i.e. {foo|template bar} as well as {.template FOO} for templates that operate on the root of the data dict rather than a subtree. def _DoSubstitute(args, context, callback, trace): """Variable substitution, i.e. {foo} We also ...
Execute a bunch of template statements in a ScopedContext. Args: callback: Strings are "written" to this callback function. trace: Trace object, or None This is called in a mutually recursive fashion. def _Execute(statements, context, callback, trace): """Execute a bunch of template statements in a S...
Free function to expands a template string with a data dictionary. This is useful for cases where you don't care about saving the result of compilation (similar to re.match('.*', s) vs DOT_STAR.match(s)) def expand(template_str, dictionary, **kwargs): """Free function to expands a template string with a data ...
Takes a nested list structure and flattens it. ['a', ['b', 'c']] -> callback('a'); callback('b'); callback('c'); def _FlattenToCallback(tokens, callback): """Takes a nested list structure and flattens it. ['a', ['b', 'c']] -> callback('a'); callback('b'); callback('c'); """ for t in tokens: if ...
OBSOLETE old API. def execute_with_style_LEGACY(template, style, data, callback, body_subtree='body'): """OBSOLETE old API.""" try: body_data = data[body_subtree] except KeyError: raise EvaluationError('Data dictionary has no subtree %r' % body_subtree) tokens_body = [] template.exe...
Expand a data dictionary with a template AND a style. DEPRECATED -- Remove this entire function in favor of expand(d, style=style) A style is a Template instance that factors out the common strings in several "body" templates. Args: template: Template instance for the inner "page content" style: Temp...
Returns: ref: Either a template instance (itself) or _TemplateRef def LookupWithType(self, user_str): """ Returns: ref: Either a template instance (itself) or _TemplateRef """ prefix = 'template ' ref = None # fail the lookup by default if user_str.startswith(prefix...
The user's formatters are consulted first, then the default formatters. def _GetFormatter(self, format_str): """ The user's formatters are consulted first, then the default formatters. """ formatter, args, func_type = self.formatters.LookupWithType(format_str) if formatter: ...
The user's predicates are consulted first, then the default predicates. def _GetPredicate(self, pred_str, test_attr=False): """ The user's predicates are consulted first, then the default predicates. """ predicate, args, func_type = self.predicates.LookupWithType(pred_str) if predicate:...
For sections or repeated sections. def NewSection(self, token_type, section_name, pre_formatters): """For sections or repeated sections.""" pre_formatters = [self._GetFormatter(f) for f in pre_formatters] # TODO: Consider getting rid of this dispatching, and turn _Do* into methods ...
{.or ...} Can appear inside predicate blocks or section blocks, with slightly different meaning. def NewOrClause(self, pred_str): """ {.or ...} Can appear inside predicate blocks or section blocks, with slightly different meaning. """ if pred_str: pred = self._GetPredicate(p...
For chains of predicate clauses. def NewPredicateSection(self, pred_str, test_attr=False): """For chains of predicate clauses.""" pred = self._GetPredicate(pred_str, test_attr=test_attr) block = _PredicateSection() block.NewOrClause(pred) self._NewSection(_DoPredicates,...
Given a section name, push it on the top of the stack. Returns: The new section, or None if there is no such section. def PushSection(self, name, pre_formatters): """Given a section name, push it on the top of the stack. Returns: The new section, or None if there is no such section. "...
Advance to the next item in a repeated section. Raises: StopIteration if there are no more elements def Next(self): """Advance to the next item in a repeated section. Raises: StopIteration if there are no more elements """ stacktop = self.stack[-1] # Now we're...
Look up the stack for the given name. def _LookUpStack(self, name): """Look up the stack for the given name.""" i = len(self.stack) - 1 while 1: frame = self.stack[i] if name == '@index': if frame.index != -1: # -1 is undefined return...