INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns True if the actual index is a valid superset of the expected index | def is_valid_superset(actual_projection, index):
"""Returns True if the actual index is a valid superset of the expected index"""
projection_type = actual_projection["ProjectionType"]
if projection_type == "ALL":
return True
meta = index.model.Meta
# all index types provide index keys and mo... |
Save an object to DynamoDB. | def save_item(self, item):
"""Save an object to DynamoDB.
:param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.update_item`.
:raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met.
"""
try:
self.dynamodb_client.update_item... |
Delete an object in DynamoDB. | def delete_item(self, item):
"""Delete an object in DynamoDB.
:param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.delete_item`.
:raises bloop.exceptions.ConstraintViolation: if the condition (or atomic) is not met.
"""
try:
self.dynamodb_client.delete_... |
Loads any number of items in chunks handling continuation tokens. | def load_items(self, items):
"""Loads any number of items in chunks, handling continuation tokens.
:param items: Unpacked in chunks into "RequestItems" for :func:`boto3.DynamoDB.Client.batch_get_item`.
"""
loaded_items = {}
requests = collections.deque(create_batch_get_chunks(it... |
Invoke query/ scan by name. | def search_items(self, mode, request):
"""Invoke query/scan by name.
Response always includes "Count" and "ScannedCount"
:param str mode: "query" or "scan"
:param request: Unpacked into :func:`boto3.DynamoDB.Client.query` or :func:`boto3.DynamoDB.Client.scan`
"""
valida... |
Create the model s table. Returns True if the table is being created False otherwise. | def create_table(self, table_name, model):
"""Create the model's table. Returns True if the table is being created, False otherwise.
Does not wait for the table to create, and does not validate an existing table.
Will not raise "ResourceInUseException" if the table exists or is being created.
... |
Polls until the table is ready then returns the first result when the table was ready. | def describe_table(self, table_name):
"""
Polls until the table is ready, then returns the first result when the table was ready.
The returned dict is standardized to ensure all fields are present, even when empty or across different
DynamoDB API versions.
TTL information is als... |
Polls until a creating table is ready then verifies the description against the model s requirements. | def validate_table(self, table_name, model):
"""Polls until a creating table is ready, then verifies the description against the model's requirements.
The model may have a subset of all GSIs and LSIs on the table, but the key structure must be exactly
the same. The table must have a stream if ... |
Calls UpdateTimeToLive on the table according to model. Meta [ ttl ] | def enable_ttl(self, table_name, model):
"""Calls UpdateTimeToLive on the table according to model.Meta["ttl"]
:param table_name: The name of the table to enable the TTL setting on
:param model: The model to get TTL settings from
"""
self._tables.pop(table_name, None)
tt... |
Calls UpdateContinuousBackups on the table according to model. Meta [ continuous_backups ] | def enable_backups(self, table_name, model):
"""Calls UpdateContinuousBackups on the table according to model.Meta["continuous_backups"]
:param table_name: The name of the table to enable Continuous Backups on
:param model: The model to get Continuous Backups settings from
"""
s... |
Wraps: func: boto3. DynamoDBStreams. Client. describe_stream handling continuation tokens. | def describe_stream(self, stream_arn, first_shard=None):
"""Wraps :func:`boto3.DynamoDBStreams.Client.describe_stream`, handling continuation tokens.
:param str stream_arn: Stream arn, usually from the model's ``Meta.stream["arn"]``.
:param str first_shard: *(Optional)* If provided, only shards... |
Wraps: func: boto3. DynamoDBStreams. Client. get_shard_iterator. | def get_shard_iterator(self, *, stream_arn, shard_id, iterator_type, sequence_number=None):
"""Wraps :func:`boto3.DynamoDBStreams.Client.get_shard_iterator`.
:param str stream_arn: Stream arn. Usually :data:`Shard.stream_arn <bloop.stream.shard.Shard.stream_arn>`.
:param str shard_id: Shard id... |
Wraps: func: boto3. DynamoDBStreams. Client. get_records. | def get_stream_records(self, iterator_id):
"""Wraps :func:`boto3.DynamoDBStreams.Client.get_records`.
:param iterator_id: Iterator id. Usually :data:`Shard.iterator_id <bloop.stream.shard.Shard.iterator_id>`.
:return: Dict with "Records" list (may be empty) and "NextShardIterator" str (may not... |
Wraps: func: boto3. DynamoDB. Client. db. transact_get_items. | def transaction_read(self, items):
"""
Wraps :func:`boto3.DynamoDB.Client.db.transact_get_items`.
:param items: Unpacked into "TransactionItems" for :func:`boto3.DynamoDB.Client.transact_get_items`
:raises bloop.exceptions.TransactionCanceled: if the transaction was canceled.
:r... |
Wraps: func: boto3. DynamoDB. Client. db. transact_write_items. | def transaction_write(self, items, client_request_token):
"""
Wraps :func:`boto3.DynamoDB.Client.db.transact_write_items`.
:param items: Unpacked into "TransactionItems" for :func:`boto3.DynamoDB.Client.transact_write_items`
:param client_request_token: Idempotency token valid for 10 mi... |
Only allows == against query_on. hash_key | def check_hash_key(query_on, key):
"""Only allows == against query_on.hash_key"""
return (
isinstance(key, BaseCondition) and
(key.operation == "==") and
(key.column is query_on.hash_key)
) |
BeginsWith Between or any Comparison except ! = against query_on. range_key | def check_range_key(query_on, key):
"""BeginsWith, Between, or any Comparison except '!=' against query_on.range_key"""
return (
isinstance(key, BaseCondition) and
key.operation in ("begins_with", "between", "<", ">", "<=", ">=", "==") and
key.column is query_on.range_key
) |
Constructs a: class: ~bloop. search. PreparedSearch. | def prepare(self):
"""Constructs a :class:`~bloop.search.PreparedSearch`."""
p = PreparedSearch()
p.prepare(
engine=self.engine,
mode=self.mode,
model=self.model,
index=self.index,
key=self.key,
filter=self.filter,
... |
Validates the search parameters and builds the base request dict for each Query/ Scan call. | def prepare(
self, engine=None, mode=None, model=None, index=None, key=None,
filter=None, projection=None, consistent=None, forward=None, parallel=None):
"""Validates the search parameters and builds the base request dict for each Query/Scan call."""
self.prepare_iterator_cls(en... |
Number of items that have been loaded from DynamoDB so far including buffered items. | def count(self):
"""Number of items that have been loaded from DynamoDB so far, including buffered items."""
if self.request["Select"] == "COUNT":
while not self.exhausted:
next(self, None)
return self._count |
Number of items that DynamoDB evaluated before any filter was applied. | def scanned(self):
"""Number of items that DynamoDB evaluated, before any filter was applied."""
if self.request["Select"] == "COUNT":
while not self.exhausted:
next(self, None)
return self._scanned |
Return the first result. If there are no results raises: exc: ~bloop. exceptions. ConstraintViolation. | def first(self):
"""Return the first result. If there are no results, raises :exc:`~bloop.exceptions.ConstraintViolation`.
:return: The first result.
:raises bloop.exceptions.ConstraintViolation: No results.
"""
self.reset()
value = next(self, None)
if value is ... |
Return the unique result. If there is not exactly one result raises: exc: ~bloop. exceptions. ConstraintViolation. | def one(self):
"""Return the unique result. If there is not exactly one result,
raises :exc:`~bloop.exceptions.ConstraintViolation`.
:return: The unique result.
:raises bloop.exceptions.ConstraintViolation: Not exactly one result.
"""
first = self.first()
second... |
Reset to the initial state clearing the buffer and zeroing count and scanned. | def reset(self):
"""Reset to the initial state, clearing the buffer and zeroing count and scanned."""
self.buffer.clear()
self._count = 0
self._scanned = 0
self._exhausted = False
self.request.pop("ExclusiveStartKey", None) |
get a type by the common bloop operation name: get/ check/ delete/ save | def by_alias(cls, name: str) -> "TxType":
"""get a type by the common bloop operation name: get/check/delete/save"""
return {
"get": TxType.Get,
"check": TxType.Check,
"delete": TxType.Delete,
"save": TxType.Update,
}[name] |
Create a new PreparedTransaction that can be committed. | def prepare(self):
"""
Create a new PreparedTransaction that can be committed.
This is called automatically when exiting the transaction as a context:
.. code-block:: python
>>> engine = Engine()
>>> tx = WriteTransaction(engine)
>>> prepared = tx.p... |
Create a unique transaction id and dumps the items into a cached request object. | def prepare(self, engine, mode, items) -> None:
"""
Create a unique transaction id and dumps the items into a cached request object.
"""
self.tx_id = str(uuid.uuid4()).replace("-", "")
self.engine = engine
self.mode = mode
self.items = items
self._prepare_... |
Commit the transaction with a fixed transaction id. | def commit(self) -> None:
"""
Commit the transaction with a fixed transaction id.
A read transaction can call commit() any number of times, while a write transaction can only use the
same tx_id for 10 minutes from the first call.
"""
now = datetime.now(timezone.utc)
... |
Add one or more objects to be loaded in this transaction. | def load(self, *objs) -> "ReadTransaction":
"""
Add one or more objects to be loaded in this transaction.
At most 10 items can be loaded in the same transaction. All objects will be loaded each time you
call commit().
:param objs: Objects to add to the set that are loaded in ... |
Add a condition which must be met for the transaction to commit. | def check(self, obj, condition) -> "WriteTransaction":
"""
Add a condition which must be met for the transaction to commit.
While the condition is checked against the provided object, that object will not be modified. It is only
used to provide the hash and range key to apply the condi... |
Add one or more objects to be saved in this transaction. | def save(self, *objs, condition=None, atomic=False) -> "WriteTransaction":
"""
Add one or more objects to be saved in this transaction.
At most 10 items can be checked, saved, or deleted in the same transaction. The same idempotency token will
be used for a single prepared transaction,... |
Produces a numpy array of integers which encode the supplied cube dimensions. | def encode(self, cube_dimensions):
"""
Produces a numpy array of integers which encode
the supplied cube dimensions.
"""
return np.asarray([getattr(cube_dimensions[d], s)
for d in self._dimensions
for s in self._schema],
dtype=np.int32) |
Produce a list of dictionaries for each dimension in this transcoder | def decode(self, descriptor):
""" Produce a list of dictionaries for each dimension in this transcoder """
i = iter(descriptor)
n = len(self._schema)
# Add the name key to our schema
schema = self._schema + ('name',)
# For each dimensions, generator takes n items off ite... |
Download cub archive from cub_url and store it in cub_archive_name | def dl_cub(cub_url, cub_archive_name):
""" Download cub archive from cub_url and store it in cub_archive_name """
with open(cub_archive_name, 'wb') as f:
remote_file = urllib2.urlopen(cub_url)
meta = remote_file.info()
# The server may provide us with the size of the file.
cl_he... |
Compute the SHA1 hash of filename | def sha_hash_file(filename):
""" Compute the SHA1 hash of filename """
hash_sha = hashlib.sha1()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(1024*1024), b""):
hash_sha.update(chunk)
return hash_sha.hexdigest() |
Downloads and installs cub into mb_inc_path | def install_cub(mb_inc_path):
""" Downloads and installs cub into mb_inc_path """
cub_url = 'https://github.com/NVlabs/cub/archive/1.6.4.zip'
cub_sha_hash = '0d5659200132c2576be0b3959383fa756de6105d'
cub_version_str = 'Current release: v1.6.4 (12/06/2016)'
cub_zip_file = 'cub.zip'
cub_zip_dir = ... |
Emit a list of architecture flags for each CUDA device found [ -- gpu - architecture = sm_30 -- gpu - architecture = sm_52 ] | def cuda_architecture_flags(device_info):
"""
Emit a list of architecture flags for each CUDA device found
['--gpu-architecture=sm_30', '--gpu-architecture=sm_52']
"""
# Figure out the necessary device architectures
if len(device_info['devices']) == 0:
archs = ['--gpu-architecture=sm_30'... |
Create an extension that builds the custom tensorflow ops | def create_tensorflow_extension(nvcc_settings, device_info):
""" Create an extension that builds the custom tensorflow ops """
import tensorflow as tf
import glob
use_cuda = (bool(nvcc_settings['cuda_available'])
and tf.test.is_built_with_cuda())
# Source and includes
source_path = os.... |
Inform montblanc about dimension sizes | def updated_dimensions(self):
""" Inform montblanc about dimension sizes """
return [("ntime", args.ntime), # Timesteps
("nchan", args.nchan), # Channels
("na", args.na), # Antenna
("npsrc", len(lm_coords))] |
Supply point source lm coordinates to montblanc | def point_lm(self, context):
""" Supply point source lm coordinates to montblanc """
# Shape (npsrc, 2)
(ls, us), _ = context.array_extents(context.name)
return np.asarray(lm_coords[ls:us], dtype=context.dtype) |
Supply point source stokes parameters to montblanc | def point_stokes(self, context):
""" Supply point source stokes parameters to montblanc """
# Shape (npsrc, ntime, 4)
(ls, us), (lt, ut), (l, u) = context.array_extents(context.name)
data = np.empty(context.shape, context.dtype)
data[ls:us,:,l:u] = np.asarray(lm_stokes)[ls:us,N... |
Supply UVW antenna coordinates to montblanc | def uvw(self, context):
""" Supply UVW antenna coordinates to montblanc """
# Shape (ntime, na, 3)
(lt, ut), (la, ua), (l, u) = context.array_extents(context.name)
# Create empty UVW coordinates
data = np.empty(context.shape, context.dtype)
data[:,:,0] = np.arange(la+1,... |
Monkeypatch distutils. Distribution. reinitialize_command () to match behavior of Distribution. get_command_obj () This fixes a problem where pip install - e does not reinitialise options using the setup ( options = {... } ) variable for the build_ext command. This also effects other option sourcs such as setup. cfg. | def reinitialize_command(self, command, reinit_subcommands):
"""
Monkeypatch distutils.Distribution.reinitialize_command() to match behavior
of Distribution.get_command_obj()
This fixes a problem where 'pip install -e' does not reinitialise options
using the setup(options={...}) variable for the bui... |
Compute the number of baselines for the given number of antenna. Can specify whether auto - correlations should be taken into account | def nr_of_baselines(na, auto_correlations=False):
"""
Compute the number of baselines for the
given number of antenna. Can specify whether
auto-correlations should be taken into
account
"""
m = (na-1) if auto_correlations is False else (na+1)
return (na*m)//2 |
Compute the number of antenna for the given number of baselines. Can specify whether auto - correlations should be taken into account | def nr_of_antenna(nbl, auto_correlations=False):
"""
Compute the number of antenna for the
given number of baselines. Can specify whether
auto-correlations should be taken into
account
"""
t = 1 if auto_correlations is False else -1
return int(t + math.sqrt(1 + 8*nbl)) // 2 |
Estimates the memory in bytes required for an array of the supplied shape and dtype | def array_bytes(shape, dtype):
""" Estimates the memory in bytes required for an array of the supplied shape and dtype """
return np.product(shape)*np.dtype(dtype).itemsize |
Returns a random array of the same shape and type as the supplied array argument or the supplied shape and dtype | def random_like(ary=None, shape=None, dtype=None):
"""
Returns a random array of the same shape and type as the
supplied array argument, or the supplied shape and dtype
"""
if ary is not None:
shape, dtype = ary.shape, ary.dtype
elif shape is None or dtype is None:
raise ValueErr... |
Return a flatten version of the nested argument | def flatten(nested):
""" Return a flatten version of the nested argument """
flat_return = list()
def __inner_flat(nested,flat):
for i in nested:
__inner_flat(i, flat) if isinstance(i, list) else flat.append(i)
return flat
__inner_flat(nested,flat_return)
return flat_r... |
Return the number of bytes required by an array | def dict_array_bytes(ary, template):
"""
Return the number of bytes required by an array
Arguments
---------------
ary : dict
Dictionary representation of an array
template : dict
A dictionary of key-values, used to replace any
string values in the array with concrete in... |
Return the number of bytes required by a dictionary of arrays. | def dict_array_bytes_required(arrays, template):
"""
Return the number of bytes required by
a dictionary of arrays.
Arguments
---------------
arrays : list
A list of dictionaries defining the arrays
template : dict
A dictionary of key-values, used to replace any
stri... |
Returns the number of timesteps possible given the registered arrays and a memory budget defined by bytes_available | def viable_dim_config(bytes_available, arrays, template,
dim_ord, nsolvers=1):
"""
Returns the number of timesteps possible, given the registered arrays
and a memory budget defined by bytes_available
Arguments
----------------
bytes_available : int
The memory budget, or availabl... |
Substitutes string values in the supplied shape parameter with integer variables stored in a dictionary | def shape_from_str_tuple(sshape, variables, ignore=None):
"""
Substitutes string values in the supplied shape parameter
with integer variables stored in a dictionary
Parameters
----------
sshape : tuple/string composed of integers and strings.
The strings should related to integral prop... |
Shape a list of lists into the appropriate shape and data type | def shape_list(l,shape,dtype):
""" Shape a list of lists into the appropriate shape and data type """
return np.array(l, dtype=dtype).reshape(shape) |
Return a function defining the conversion process between two NumPy arrays of different shapes | def array_convert_function(sshape_one, sshape_two, variables):
""" Return a function defining the conversion process between two NumPy
arrays of different shapes """
if not isinstance(sshape_one, tuple): sshape_one = (sshape_one,)
if not isinstance(sshape_two, tuple): sshape_two = (sshape_two,)
s_o... |
Redistribute threads from the Z dimension towards the X dimension. Also clamp number of threads to the problem dimension size if necessary | def redistribute_threads(blockdimx, blockdimy, blockdimz,
dimx, dimy, dimz):
"""
Redistribute threads from the Z dimension towards the X dimension.
Also clamp number of threads to the problem dimension size,
if necessary
"""
# Shift threads from the z dimension
# into the y dimension
... |
Register the default dimensions for a RIME solver | def register_default_dimensions(cube, slvr_cfg):
""" Register the default dimensions for a RIME solver """
import montblanc.src_types as mbs
# Pull out the configuration options for the basics
autocor = slvr_cfg['auto_correlations']
ntime = 10
na = 7
nbands = 1
nchan = 16
npol = 4... |
Hack to get IP address from the interface | def get_ip_address(ifname):
""" Hack to get IP address from the interface """
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24]) |
Find nvcc and the CUDA installation | def nvcc_compiler_settings():
""" Find nvcc and the CUDA installation """
search_paths = os.environ.get('PATH', '').split(os.pathsep)
nvcc_path = find_in_path('nvcc', search_paths)
default_cuda_path = os.path.join('usr', 'local', 'cuda')
cuda_path = os.environ.get('CUDA_PATH', default_cuda_path)
... |
Poor mans deviceQuery. Returns CUDA_VERSION information and CUDA device information in JSON format | def inspect_cuda_version_and_devices(compiler, settings):
"""
Poor mans deviceQuery. Returns CUDA_VERSION information and
CUDA device information in JSON format
"""
try:
output = build_and_run(compiler, '''
#include <cuda.h>
#include <stdio.h>
__device__ ... |
inject deep into distutils to customize gcc/ nvcc dispatch | def customize_compiler_for_nvcc(compiler, nvcc_settings):
"""inject deep into distutils to customize gcc/nvcc dispatch """
# tell the compiler it can process .cu files
compiler.src_extensions.append('.cu')
# save references to the default compiler_so and _compile methods
default_compiler_so = comp... |
Return cuda device information and nvcc/ cuda setup | def inspect_cuda():
""" Return cuda device information and nvcc/cuda setup """
nvcc_settings = nvcc_compiler_settings()
sysconfig.get_config_vars()
nvcc_compiler = ccompiler.new_compiler()
sysconfig.customize_compiler(nvcc_compiler)
customize_compiler_for_nvcc(nvcc_compiler, nvcc_settings)
... |
Returns a dictionary suitable for templating strings with properties and dimensions related to this Solver object. | def template_dict(self):
"""
Returns a dictionary suitable for templating strings with
properties and dimensions related to this Solver object.
Used in templated GPU kernels.
"""
slvr = self
D = {
# Constants
'LIGHTSPEED': montblanc.const... |
Factory function that produces a RIME solver | def rime_solver(slvr_cfg):
""" Factory function that produces a RIME solver """
from montblanc.impl.rime.tensorflow.RimeSolver import RimeSolver
return RimeSolver(slvr_cfg) |
Returns a dictionary of source methods found on this object keyed on method name. Source methods are identified. by argspec a list of argument specifiers. So for e. g. an argpsec of: code: [[ self context ] [ s c ]] would match methods looking like: | def find_sources(obj, argspec=None):
"""
Returns a dictionary of source methods found on this object,
keyed on method name. Source methods are identified.by argspec,
a list of argument specifiers. So for e.g. an argpsec of
:code:`[['self', 'context'], ['s', 'c']]` would match
methods looking lik... |
Returns a dictionary of source methods found on this object keyed on method name. Source methods are identified by ( self context ) arguments on this object. For example: | def sources(self):
"""
Returns a dictionary of source methods found on this object,
keyed on method name. Source methods are identified by
(self, context) arguments on this object. For example:
.. code-block:: python
def f(self, context):
...
... |
Computes parallactic angles per timestep for the given reference antenna position and field centre. | def parallactic_angles(times, antenna_positions, field_centre):
"""
Computes parallactic angles per timestep for the given
reference antenna position and field centre.
Arguments:
times: ndarray
Array of unique times with shape (ntime,),
obtained from TIME column of MS ta... |
Setup logging configuration | def setup_logging():
""" Setup logging configuration """
# Console formatter, mention name
cfmt = logging.Formatter(('%(name)s - %(levelname)s - %(message)s'))
# File formatter, mention time
ffmt = logging.Formatter(('%(asctime)s - %(levelname)s - %(message)s'))
# Console handler
ch = log... |
Caches constant arrays associated with an array name. | def constant_cache(method):
"""
Caches constant arrays associated with an array name.
The intent of this decorator is to avoid the cost
of recreating and storing many arrays of constant data,
especially data created by np.zeros or np.ones.
Instead, a single array of the first given shape is cre... |
Caches chunks of default data. | def chunk_cache(method):
"""
Caches chunks of default data.
This decorator caches generated default data so as to
avoid recomputing it on a subsequent queries to the
provider.
"""
@functools.wraps(method)
def wrapper(self, context):
# Defer to the method if no caching is enable... |
Create a DefaultsSourceProvider object. This provides default data sources for each array defined on the hypercube. The data sources may either by obtained from the arrays default data source or the test data source. | def _create_defaults_source_provider(cube, data_source):
"""
Create a DefaultsSourceProvider object. This provides default
data sources for each array defined on the hypercube. The data sources
may either by obtained from the arrays 'default' data source
or the 'test' data source.
"""
from m... |
Constructs a tensorflow expression for computing the RIME | def _construct_tensorflow_expression(slvr_cfg, feed_data, device, shard):
""" Constructs a tensorflow expression for computing the RIME """
zero = tf.constant(0)
src_count = zero
src_ph_vars = feed_data.src_ph_vars
LSA = feed_data.local
polarisation_type = slvr_cfg['polarisation_type']
# ... |
Get data from the data source checking the return values | def _get_data(data_source, context):
""" Get data from the data source, checking the return values """
try:
# Get data from the data source
data = data_source.source(context)
# Complain about None values
if data is None:
raise ValueError("'None' returned from "
... |
Supply data to the data sink | def _supply_data(data_sink, context):
""" Supply data to the data sink """
try:
data_sink.sink(context)
except Exception as e:
ex = ValueError("An exception occurred while "
"supplying data to data sink '{ds}'\n\n"
"{e}\n\n"
"{help}".format(ds=context.name... |
Given a list of source_providers apply the list of suggested dimension updates given in provider. updated_dimensions () to the supplied hypercube. | def _apply_source_provider_dim_updates(cube, source_providers, budget_dims):
"""
Given a list of source_providers, apply the list of
suggested dimension updates given in provider.updated_dimensions()
to the supplied hypercube.
Dimension global_sizes are always updated with the supplied sizes and
... |
Sets up the hypercube given a solver configuration | def _setup_hypercube(cube, slvr_cfg):
""" Sets up the hypercube given a solver configuration """
mbu.register_default_dimensions(cube, slvr_cfg)
# Configure the dimensions of the beam cube
cube.register_dimension('beam_lw', 2,
description='E Beam cube l width')
cube.reg... |
Partition data sources into | def _partition(iter_dims, data_sources):
"""
Partition data sources into
1. Dictionary of data sources associated with radio sources.
2. List of data sources to feed multiple times.
3. List of data sources to feed once.
"""
src_nr_vars = set(source_var_types().values())
iter_dims = set... |
Feed stub | def _feed(self, cube, data_sources, data_sinks, global_iter_args):
""" Feed stub """
try:
self._feed_impl(cube, data_sources, data_sinks, global_iter_args)
except Exception as e:
montblanc.log.exception("Feed Exception")
raise |
Implementation of staging_area feeding | def _feed_impl(self, cube, data_sources, data_sinks, global_iter_args):
""" Implementation of staging_area feeding """
session = self._tf_session
FD = self._tf_feed_data
LSA = FD.local
# Get source strides out before the local sizes are modified during
# the source loops... |
Call the tensorflow compute | def _compute(self, feed_dict, shard):
""" Call the tensorflow compute """
try:
descriptor, enq = self._tfrun(self._tf_expr[shard], feed_dict=feed_dict)
self._inputs_waiting.decrement(shard)
except Exception as e:
montblanc.log.exception("Compute Exception")
... |
Consume stub | def _consume(self, data_sinks, cube, global_iter_args):
""" Consume stub """
try:
return self._consume_impl(data_sinks, cube, global_iter_args)
except Exception as e:
montblanc.log.exception("Consumer Exception")
raise e, None, sys.exc_info()[2] |
Consume | def _consume_impl(self, data_sinks, cube, global_iter_args):
""" Consume """
LSA = self._tf_feed_data.local
output = self._tfrun(LSA.output.get_op)
# Expect the descriptor in the first tuple position
assert len(output) > 0
assert LSA.output.fed_arrays[0] == 'descriptor'... |
Produces a SolverConfiguration object inherited from a simple python dict and containing the options required to configure the RIME Solver. | def rime_solver_cfg(**kwargs):
"""
Produces a SolverConfiguration object, inherited from
a simple python dict, and containing the options required
to configure the RIME Solver.
Keyword arguments
-----------------
Any keyword arguments are inserted into the
returned dict.
Returns
... |
Returns a dictionary of beam filename pairs keyed on correlation from the cartesian product of correlations and real imaginary pairs | def _create_filenames(filename_schema, feed_type):
"""
Returns a dictionary of beam filename pairs,
keyed on correlation,from the cartesian product
of correlations and real, imaginary pairs
Given 'beam_$(corr)_$(reim).fits' returns:
{
'xx' : ('beam_xx_re.fits', 'beam_xx_im.fits'),
'... |
Given a { correlation: filename } mapping for filenames returns a { correlation: file handle } mapping | def _open_fits_files(filenames):
"""
Given a {correlation: filename} mapping for filenames
returns a {correlation: file handle} mapping
"""
kw = { 'mode' : 'update', 'memmap' : False }
def _fh(fn):
""" Returns a filehandle or None if file does not exist """
return fits.open(fn, ... |
Create a FitsAxes object | def _create_axes(filenames, file_dict):
""" Create a FitsAxes object """
try:
# Loop through the file_dictionary, finding the
# first open FITS file.
f = iter(f for tup in file_dict.itervalues()
for f in tup if f is not None).next()
except StopIteration as e:
rai... |
Initialise the object by generating appropriate filenames opening associated file handles and inspecting the FITS axes of these files. | def _initialise(self, feed_type="linear"):
"""
Initialise the object by generating appropriate filenames,
opening associated file handles and inspecting the FITS axes
of these files.
"""
self._filenames = filenames = _create_filenames(self._filename_schema,
... |
ebeam cube data source | def ebeam(self, context):
""" ebeam cube data source """
if context.shape != self.shape:
raise ValueError("Partial feeding of the "
"beam cube is not yet supported %s %s." % (context.shape, self.shape))
ebeam = np.empty(context.shape, context.dtype)
# Iterat... |
model visibility data sink | def model_vis(self, context):
""" model visibility data sink """
column = self._vis_column
msshape = None
# Do we have a column descriptor for the supplied column?
try:
coldesc = self._manager.column_descriptors[column]
except KeyError as e:
colde... |
Decorator for caching data source return values | def _cache(method):
"""
Decorator for caching data source return values
Create a key index for the proxied array in the context.
Iterate over the array shape descriptor e.g. (ntime, nbl, 3)
returning tuples containing the lower and upper extents
of string dimensions. Takes (0, d) in the case of... |
Decorator returning a method that proxies a data source. | def _proxy(method):
"""
Decorator returning a method that proxies a data source.
"""
@functools.wraps(method)
def memoizer(self, context):
return method(context)
return memoizer |
Perform any logic on solution start | def start(self, start_context):
""" Perform any logic on solution start """
for p in self._providers:
p.start(start_context)
if self._clear_start:
self.clear_cache() |
Perform any logic on solution stop | def stop(self, stop_context):
""" Perform any logic on solution stop """
for p in self._providers:
p.stop(stop_context)
if self._clear_stop:
self.clear_cache() |
Compute base antenna pairs | def default_base_ant_pairs(self, context):
""" Compute base antenna pairs """
k = 0 if context.cfg['auto_correlations'] == True else 1
na = context.dim_global_size('na')
gen = (i.astype(context.dtype) for i in np.triu_indices(na, k))
# Cache np.triu_indices(na, k) as its likely that (na, k) will
... |
Default antenna1 values | def default_antenna1(self, context):
""" Default antenna1 values """
ant1, ant2 = default_base_ant_pairs(self, context)
(tl, tu), (bl, bu) = context.dim_extents('ntime', 'nbl')
ant1_result = np.empty(context.shape, context.dtype)
ant1_result[:,:] = ant1[np.newaxis,bl:bu]
return ant1_result |
Default antenna2 values | def default_antenna2(self, context):
""" Default antenna2 values """
ant1, ant2 = default_base_ant_pairs(self, context)
(tl, tu), (bl, bu) = context.dim_extents('ntime', 'nbl')
ant2_result = np.empty(context.shape, context.dtype)
ant2_result[:,:] = ant2[np.newaxis,bl:bu]
return ant2_result |
Returns [[ 1 0 ] tiled up to other dimensions [ 0 1 ]] | def identity_on_pols(self, context):
"""
Returns [[1, 0], tiled up to other dimensions
[0, 1]]
"""
A = np.empty(context.shape, context.dtype)
A[:,:,:] = [[[1,0,0,1]]]
return A |
Returns [[ 1 0 ] tiled up to other dimensions [ 0 0 ]] | def default_stokes(self, context):
"""
Returns [[1, 0], tiled up to other dimensions
[0, 0]]
"""
A = np.empty(context.shape, context.dtype)
A[:,:,:] = [[[1,0,0,0]]]
return A |
Frequency data source | def frequency(self, context):
""" Frequency data source """
channels = self._manager.spectral_window_table.getcol(MS.CHAN_FREQ)
return channels.reshape(context.shape).astype(context.dtype) |
Reference frequency data source | def ref_frequency(self, context):
""" Reference frequency data source """
num_chans = self._manager.spectral_window_table.getcol(MS.NUM_CHAN)
ref_freqs = self._manager.spectral_window_table.getcol(MS.REF_FREQUENCY)
data = np.hstack((np.repeat(rf, bs) for bs, rf in zip(num_chans, ref_fre... |
Per - antenna UVW coordinate data source | def uvw(self, context):
""" Per-antenna UVW coordinate data source """
# Hacky access of private member
cube = context._cube
# Create antenna1 source context
a1_actual = cube.array("antenna1", reify=True)
a1_ctx = SourceContext("antenna1", cube, context.cfg,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.