text stringlengths 18 773k |
|---|
def run(self):
"""Run when button is pressed."""
inside = 0
for draws in range(1, self.data['samples']):
# generate points and check whether they are inside the unit circle
r1, r2 = (random(), random())
if r1 ** 2 + r2 ** 2 < 1.0:
inside += 1
... |
def on(f):
"""Decorator for action handlers.
The action name is inferred from the function name.
This also decorates the method with `tornado.gen.coroutine` so that
`~tornado.concurrent.Future` can be yielded.
"""
action = f.__name__
f.action = action
@wrapt.decorator
@tornado.gen... |
def on_action(action):
"""Decorator for action handlers.
:param str action: explicit action name
This also decorates the method with `tornado.gen.coroutine` so that
`~tornado.concurrent.Future` can be yielded.
"""
@wrapt.decorator
@tornado.gen.coroutine
def _execute(wrapped, instance, ... |
def init_datastores(self):
"""Initialize datastores for this analysis instance.
This creates instances of :class:`.Datastore` at ``data`` and
``class_data`` with the datastore domains being the current id
and the class name of this analysis respectively.
Overwrite this method t... |
def emit(self, signal, message='__nomessagetoken__'):
"""Emit a signal to the frontend.
:param str signal: name of the signal
:param message: message to send
:returns: return value from frontend emit function
:rtype: tornado.concurrent.Future
"""
# call pre-emit ... |
def set(self, i, value):
"""Set value at position i and return a Future.
:rtype: tornado.concurrent.Future
"""
value_encoded = encode(value, self.get_change_trigger(i))
if i in self.data and self.data[i] == value_encoded:
return self
self.data[i] = value_en... |
def set(self, key, value):
"""Set a value at key and return a Future.
:rtype: tornado.concurrent.Future
"""
value_encoded = encode(value, self.get_change_trigger(key))
if key in self.data and self.data[key] == value_encoded:
return self
self.data[key] = val... |
def update(self, new_data):
"""Update."""
for k, v in new_data.items():
self[k] = v
return self |
def trigger_all_change_callbacks(self):
"""Trigger all callbacks that were set with on_change()."""
return [
ret
for key in DatastoreLegacy.store[self.domain].keys()
for ret in self.trigger_change_callbacks(key)
] |
def set(self, key, value):
"""Set value at key and return a Future
:rtype: tornado.concurrent.Future
"""
return DatastoreLegacy.store[self.domain].set(key, value) |
def init(self, key_value_pairs):
"""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.
"""
for k, v in key_value_pairs.items():
... |
def close(self):
"""Close and delete instance."""
# remove callbacks
DatastoreLegacy.datastores[self.domain].remove(self)
# delete data after the last instance is gone
if self.release_storage and \
not DatastoreLegacy.datastores[self.domain]:
del Datastor... |
def AddIndex(node, index=None):
"""
Recursively add the current index (with respect to a repeated section) in all
data dictionaries.
"""
if isinstance(node, list):
for i, item in enumerate(node):
AddIndex(item, index=i)
elif isinstance(node, dict):
if index is not None:
node['index'] = i... |
def watch():
"""Renerate documentation when it changes."""
# Start with a clean build
sphinx_build['-b', 'html', '-E', 'docs', 'docs/_build/html'] & FG
handler = ShellCommandTrick(
shell_command='sphinx-build -b html docs docs/_build/html',
patterns=['*.rst', '*.py'],
ignore_pa... |
def gen(skipdirhtml=False):
"""Generate html and dirhtml output."""
docs_changelog = 'docs/changelog.rst'
check_git_unchanged(docs_changelog)
pandoc('--from=markdown', '--to=rst', '--output=' + docs_changelog, 'CHANGELOG.md')
if not skipdirhtml:
sphinx_build['-b', 'dirhtml', '-W', '-E', 'doc... |
def __reset_crosshair(self):
"""
redraw the cross-hair on the horizontal slice plot
Parameters
----------
x: int
the x image coordinate
y: int
the y image coordinate
Returns
-------
"""
self.lhor.set_ydata(self.y_c... |
def __init_vertical_plot(self):
"""
set up the vertical profile plot
Returns
-------
"""
# clear the plot if lines have already been drawn on it
if len(self.ax2.lines) > 0:
self.ax2.cla()
# set up the vertical profile plot
self.ax2.set... |
def __onclick(self, event):
"""
respond to mouse clicks in the plot.
This function responds to clicks on the first (horizontal slice) plot and updates the vertical profile and
slice plots
Parameters
----------
event: matplotlib.backend_bases.MouseEvent
... |
def LookupChain(lookup_func_list):
"""Returns a *function* suitable for passing as the more_formatters argument
to Template.
NOTE: In Java, this would be implemented using the 'Composite' pattern. A
*list* of formatter lookup function behaves the same as a *single* formatter
lookup funcion.
Note the dist... |
def PythonPercentFormat(format_str):
"""Use Python % format strings as template format specifiers."""
if format_str.startswith('printf '):
fmt = format_str[len('printf '):]
return lambda value: fmt % value
else:
return None |
def Plural(format_str):
"""Returns whether the value should be considered a plural value.
Integers greater than 1 are plural, and lists with length greater than one are
too.
"""
if format_str.startswith('plural?'):
i = len('plural?')
try:
splitchar = format_str[i] # Usually a space, but could... |
def get_merged_cds(genome):
"""
Returns all CDS merged, used:
- for TargQC general reports CDS coverage statistics for WGS
- for Seq2C CNV calling when no capture BED available
"""
bed = get_all_features(genome)
debug('Filtering BEDTool for high confidence CDS and stop codons')
return be... |
def _get(relative_path, genome=None):
"""
:param relative_path: relative path of the file inside the repository
:param genome: genome name. Can contain chromosome name after comma, like hg19-chr20,
in case of BED, the returning BedTool will be with added filter.
:return: BedTools obje... |
def run(cmd, output_fpath=None, input_fpath=None, checks=None, stdout_to_outputfile=True,
stdout_tx=True, reuse=False, env_vars=None):
"""Run the provided command, logging details and checking for errors.
"""
if output_fpath and reuse:
if verify_file(output_fpath, silent=True):
i... |
def _correct_qualimap_genome_results(samples):
""" fixing java.lang.Double.parseDouble error on entries like "6,082.49"
"""
for s in samples:
if verify_file(s.qualimap_genome_results_fpath):
correction_is_needed = False
with open(s.qualimap_genome_results_fpath, 'r') as f:
... |
def _correct_qualimap_insert_size_histogram(work_dir, samples):
""" replacing Qualimap insert size histogram with Picard one.
"""
for s in samples:
qualimap1_dirname = dirname(s.qualimap_ins_size_hist_fpath).replace('raw_data_qualimapReport', 'raw_data')
qualimap2_dirname = dirname(s.qualima... |
def norm_vec(vector):
"""Normalize the length of a vector to one"""
assert len(vector) == 3
v = np.array(vector)
return v/np.sqrt(np.sum(v**2)) |
def rotate_points_to_axis(points, axis):
"""Rotate all points of a list, such that `axis==[0,1,0]`
This is accomplished by rotating in the x-z-plane by phi into the
y-z-plane, then rotation in the y-z-plane by theta up to [0,1,0],
and finally rotating back in the x-z-plane by -phi.
Parameters
... |
def rotation_matrix_from_point(point, ret_inv=False):
"""Compute rotation matrix to go from [0,0,1] to `point`.
First, the matrix rotates to in the polar direction. Then,
a rotation about the y-axis is performed to match the
azimuthal angle in the x-z-plane.
This rotation matrix is required for th... |
def rotation_matrix_from_point_planerot(point, plane_angle, ret_inv=False):
"""
Compute rotation matrix to go from [0,0,1] to `point`,
while taking into account the tilted axis of rotation.
First, the matrix rotates to in the polar direction. Then,
a rotation about the y-axis is performed to match ... |
def sphere_points_from_angles_and_tilt(angles, tilted_axis):
"""
For a given tilt of the rotational axis `tilted_axis`, compute
the points on a unit sphere that correspond to the distribution
`angles` along the great circle about this axis.
Parameters
----------
angles: 1d ndarray
T... |
def backpropagate_3d_tilted(uSin, angles, res, nm, lD=0,
tilted_axis=[0, 1, 0],
coords=None, weight_angles=True, onlyreal=False,
padding=(True, True), padfac=1.75, padval=None,
intp_order=2, dtype=None,
... |
def filenames_to_uniq(names,new_delim='.'):
'''
Given a set of file names, produce a list of names consisting of the
uniq parts of the names. This works from the end of the name. Chunks of
the name are split on '.' and '-'.
For example:
A.foo.bar.txt
B.foo.bar.txt
retur... |
def run_process(self, analysis, action_name, message='__nomessagetoken__'):
"""Executes an process in the analysis with the given message.
It also handles the start and stop signals in case a process_id
is given.
"""
if action_name == 'connect':
analysis.on_connect(... |
def check_git_unchanged(filename, yes=False):
"""Check git to avoid overwriting user changes."""
if check_staged(filename):
s = 'There are staged changes in {}, overwrite? [y/n] '.format(filename)
if yes or input(s) in ('y', 'yes'):
return
else:
raise RuntimeError... |
def check_staged(filename=None):
"""Check if there are 'changes to be committed' in the index."""
retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD',
filename].run(retcode=None)
if retcode == 1:
return True
elif retcode == 0:
return False
... |
def run_process(analysis, action_name, message='__nomessagetoken__'):
"""Executes an action in the analysis with the given message.
It also handles the start and stop signals in the case that message
is a `dict` with a key ``__process_id``.
:param str action_name: Name of the action to... |
def dl_file(url, dest, chunk_size=6553):
"""Download `url` to `dest`"""
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', url, preload_content=False)
with dest.open('wb') as out:
while True:
data = r.read(chunk_size)
if data is None or len(data) == 0... |
def extract_lzma(path):
"""Extract an lzma file and return the temporary file name"""
tlfile = pathlib.Path(path)
# open lzma file
with tlfile.open("rb") as td:
data = lzma.decompress(td.read())
# write temporary tar file
fd, tmpname = tempfile.mkstemp(prefix="odt_ex_", suffix=".tar")
... |
def get_file(fname, datapath=datapath):
"""Return path of an example data file
Return the full path to an example data file name.
If the file does not exist in the `datapath` directory,
tries to download it from the ODTbrain GitHub repository.
"""
# download location
datapath = pathlib.Path... |
def load_data(fname, **kwargs):
"""Load example data"""
fname = get_file(fname)
if fname.suffix == ".lzma":
return load_tar_lzma_data(fname)
elif fname.suffix == ".zip":
return load_zip_data(fname, **kwargs) |
def load_tar_lzma_data(tlfile):
"""Load example sinogram data from a .tar.lzma file"""
tmpname = extract_lzma(tlfile)
# open tar file
fields_real = []
fields_imag = []
phantom = []
parms = {}
with tarfile.open(tmpname, "r") as t:
members = t.getmembers()
members.sort(ke... |
def load_zip_data(zipname, f_sino_real, f_sino_imag,
f_angles=None, f_phantom=None, f_info=None):
"""Load example sinogram data from a .zip file"""
ret = []
with zipfile.ZipFile(str(zipname)) as arc:
sino_real = np.loadtxt(arc.open(f_sino_real))
sino_imag = np.loadtxt(arc.o... |
def fourier_map_2d(uSin, angles, res, nm, lD=0, semi_coverage=False,
coords=None, count=None, max_count=None, verbose=0):
r"""2D Fourier mapping with the Fourier diffraction theorem
Two-dimensional diffraction tomography reconstruction
algorithm for scattering of a plane wave
:math:`... |
def transform_to(ext):
"""
Decorator to create an output filename from an output filename with
the specified extension. Changes the extension, in_file is transformed
to a new type.
Takes functions like this to decorate:
f(in_file, out_dir=None, out_file=None) or,
f(in_file=in_file, out_dir=... |
def filter_to(word):
"""
Decorator to create an output filename from an input filename by
adding a word onto the stem. in_file is filtered by the function
and the results are written to out_file. You would want to use
this over transform_to if you don't know the extension of the file
going in. T... |
def chdir(new_dir):
"""Context manager to temporarily change to a new directory.
http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/
"""
cur_dir = os.getcwd()
safe_mkdir(new_dir)
os.chdir(new_dir)
try:
yield
finally:
os.chdir(cur_dir) |
def file_uptodate(fname, cmp_fname):
"""Check if a file exists, is non-empty and is more recent than cmp_fname.
"""
try:
return (file_exists(fname) and file_exists(cmp_fname) and
getmtime(fname) >= getmtime(cmp_fname))
except OSError:
return False |
def save_diskspace(fname, reason, config):
"""Overwrite a file in place with a short message to save disk.
This keeps files as a sanity check on processes working, but saves
disk by replacing them with a short message.
"""
if config["algorithm"].get("save_diskspace", False):
with open(fname... |
def symlink_plus(orig, new):
"""Create relative symlinks and handle associated biological index files.
"""
for ext in ["", ".idx", ".gbi", ".tbi", ".bai"]:
if os.path.exists(orig + ext) and not os.path.lexists(new + ext):
with chdir(os.path.dirname(new)):
os.symlink(os.pa... |
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = itertools.tee(iterable)
try:
return itertools.ifilterfalse(pred, t1), itertools.ifilter(pred, t2)
except:
r... |
def get_in(d, t, default=None):
"""
look up if you can get a tuple of values from a nested dictionary,
each item in the tuple a deeper layer
example: get_in({1: {2: 3}}, (1, 2)) -> 3
example: get_in({1: {2: 3}}, (2, 3)) -> {}
"""
result = reduce(lambda d, t: d.get(t, {}), t, d)
if not r... |
def which(program):
"""
returns the path to an executable or None if it can't be found
"""
def is_exe(_fpath):
return os.path.isfile(_fpath) and os.access(_fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
... |
def expanduser(path):
"""Expand ~ and ~user constructs.
If user or $HOME is unknown, do nothing."""
if path[:1] != '~':
return path
i, n = 1, len(path)
while i < n and path[i] not in '/\\':
i = i + 1
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERP... |
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 |
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 iterate_file(config, tsv_fpath, proc_line, suffix='dots') |
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_dir, rollback_files)
__remove_files(safe_fpaths) # remove any half... |
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(tmp_dir_base):
# if unique_attempts > 5:
# break
#... |
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 = [fnames]
for fname in fnames:
tx_file = f... |
def merge_overlaps(work_dir, bed_fpath, distance=None):
"""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.
"""
output_fpath = intermediate_fname(work_dir, bed_fpath, ... |
def checkformat(self):
"""************************************************************************************************************************************************************
Task: checks the format of the bed file. The only requirements checked are that each line presents at least 3 tab separat... |
def trigger_all_callbacks(self, callbacks=None):
"""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]
"""
return [ret
for key in se... |
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[key] == value_encoded:
return []
self.data[key] = value_encoded
ret... |
def set_state(self, updater=None, **kwargs):
"""Update the datastore.
:param func|dict updater: (state) => state_change or dict state_change
:rtype: Iterable[tornado.concurrent.Future]
"""
if callable(updater):
state_change = updater(self)
elif updater is not... |
def init(self, key_value_pairs=None, **kwargs):
"""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 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.global_data[self.domain]
... |
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
"""
plots_dirpath = join(output_dir, 'plots')
individual_report_fpaths = [s.qualimap_html_fpath for s in sample... |
def odt_to_ri(f, res, nm):
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}} ... |
def opt_to_ri(f, res, nm):
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} +
... |
def rasterize(vectorobject, reference, outname=None, burn_values=1, expressions=None, nodata=0, append=False):
"""
rasterize a vector object
Parameters
----------
vectorobject: Vector
the vector object to be rasterized
reference: Raster
a reference Raster object to retrieve geo ... |
def reproject(rasterobject, reference, outname, targetres=None, resampling='bilinear', format='GTiff'):
"""
reproject a raster file
Parameters
----------
rasterobject: Raster or str
the raster image to be reprojected
reference: Raster, Vector, str, int or osr.SpatialReference
ei... |
def stack(srcfiles, dstfile, resampling, targetres, dstnodata, srcnodata=None, shapefile=None, layernames=None,
sortfun=None, separate=False, overwrite=False, compress=True, cores=4):
"""
function for mosaicking, resampling and stacking of multiple raster files into a 3D data cube
Parameters
... |
def allstats(self, approximate=False):
"""
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 di... |
def array(self):
"""
read all raster bands into a numpy ndarray
Returns
-------
numpy.ndarray
the array containing all raster data
"""
if self.bands == 1:
return self.matrix()
else:
arr = self.raster.ReadAsArray().trans... |
def bandnames(self, names):
"""
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
-------
"""
if not isinstance(names, list):
... |
def bbox(self, outname=None, format='ESRI Shapefile', overwrite=True):
"""
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
overw... |
def extract(self, px, py, radius=1, nodata=None):
"""
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 coord... |
def geo(self):
"""
General image geo information.
Returns
-------
dict
a dictionary with keys `xmin`, `xmax`, `xres`, `rotation_x`, `ymin`, `ymax`, `yres`, `rotation_y`
"""
out = dict(zip(['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres'],
... |
def is_valid(self):
"""
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
... |
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, self.bands + 1):
self.__data[i - 1] = self.matrix(i) |
def matrix(self, band=1, mask_nan=True):
"""
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:`num... |
def res(self):
"""
the raster resolution in x and y direction
Returns
-------
tuple
(xres, yres)
"""
return (abs(float(self.geo['xres'])), abs(float(self.geo['yres']))) |
def rescale(self, fun):
"""
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 Ra... |
def write(self, outname, dtype='default', format='ENVI', nodata='default', compress_tif=False, overwrite=False):
"""
write the raster object to a file.
Parameters
----------
outname: str
the file to be written
dtype: str
the data type of the writt... |
def numpy2gdalint(self):
"""
create a dictionary for mapping numpy data types to GDAL data type codes
Returns
-------
dict
the type map
"""
if not hasattr(self, '__numpy2gdalint'):
tmap = {}
for group in ['int', 'u... |
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):
static = static.items()
for group in static:
if not isinstanc... |
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_load(f)
self.info.update(config... |
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 info:
... |
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 command: {}'.format(full_cmd))
subprocess.... |
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
) |
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_write_byte(self.CS, 0x13) # Over Current Tresho... |
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 |
def _mprotate(ang, lny, pool, order):
"""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 ... |
def backpropagate_3d(uSin, angles, res, nm, lD=0, coords=None,
weight_angles=True, onlyreal=False,
padding=(True, True), padfac=1.75, padval=None,
intp_order=2, dtype=None,
num_cores=ncores,
save_memory=False,
... |
def compute_angle_weights_1d(angles):
"""
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 ang... |
def initialize(self):
"""See :meth:`pymlab.sensors.Device.initialize` for more information.
Calls `initialize()` on all devices connected to the bus.
"""
Device.initialize(self)
for child in iter(self.children.values()):
child.initialize() |
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) |
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) |
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_data(address, register, value) |
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)
LOGGER.debug("Writing word data %s to register %s ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.