code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def clear_all():
_TABLES.clear()
_COLUMNS.clear()
_STEPS.clear()
_BROADCASTS.clear()
_INJECTABLES.clear()
_TABLE_CACHE.clear()
_COLUMN_CACHE.clear()
_INJECTABLE_CACHE.clear()
for m in _MEMOIZED.values():
m.value.clear_cached()
_MEMOIZED.clear()
logger.debug('pipe... | Clear any and all stored state from Orca. |
def clear_cache(scope=None):
if not scope:
_TABLE_CACHE.clear()
_COLUMN_CACHE.clear()
_INJECTABLE_CACHE.clear()
for m in _MEMOIZED.values():
m.value.clear_cached()
logger.debug('pipeline cache cleared')
else:
for d in (_TABLE_CACHE, _COLUMN_CACHE,... | Clear all cached data.
Parameters
----------
scope : {None, 'step', 'iteration', 'forever'}, optional
Clear cached values with a given scope.
By default all cached values are removed. |
def _collect_variables(names, expressions=None):
# Map registered variable labels to expressions.
if not expressions:
expressions = []
offset = len(names) - len(expressions)
labels_map = dict(tz.concatv(
tz.compatibility.zip(names[:offset], names[:offset]),
tz.compatibility.... | Map labels and expressions to registered variables.
Handles argument matching.
Example:
_collect_variables(names=['zones', 'zone_id'],
expressions=['parcels.zone_id'])
Would return a dict representing:
{'parcels': <DataFrameWrapper for zones>,
'zone_i... |
def add_table(
table_name, table, cache=False, cache_scope=_CS_FOREVER,
copy_col=True):
if isinstance(table, Callable):
table = TableFuncWrapper(table_name, table, cache=cache,
cache_scope=cache_scope, copy_col=copy_col)
else:
table = DataFra... | Register a table with Orca.
Parameters
----------
table_name : str
Should be globally unique to this table.
table : pandas.DataFrame or function
If a function, the function should return a DataFrame.
The function's argument names and keyword argument values
will be match... |
def table(
table_name=None, cache=False, cache_scope=_CS_FOREVER, copy_col=True):
def decorator(func):
if table_name:
name = table_name
else:
name = func.__name__
add_table(
name, func, cache=cache, cache_scope=cache_scope,
copy_co... | Decorates functions that return DataFrames.
Decorator version of `add_table`. Table name defaults to
name of function.
The function's argument names and keyword argument values
will be matched to registered variables when the function
needs to be evaluated by Orca.
The argument name "iter_var"... |
def get_table(table_name):
table = get_raw_table(table_name)
if isinstance(table, TableFuncWrapper):
table = table()
return table | Get a registered table.
Decorated functions will be converted to `DataFrameWrapper`.
Parameters
----------
table_name : str
Returns
-------
table : `DataFrameWrapper` |
def table_type(table_name):
table = get_raw_table(table_name)
if isinstance(table, DataFrameWrapper):
return 'dataframe'
elif isinstance(table, TableFuncWrapper):
return 'function' | Returns the type of a registered table.
The type can be either "dataframe" or "function".
Parameters
----------
table_name : str
Returns
-------
table_type : {'dataframe', 'function'} |
def add_column(
table_name, column_name, column, cache=False, cache_scope=_CS_FOREVER):
if isinstance(column, Callable):
column = \
_ColumnFuncWrapper(
table_name, column_name, column,
cache=cache, cache_scope=cache_scope)
else:
column = _... | Add a new column to a table from a Series or callable.
Parameters
----------
table_name : str
Table with which the column will be associated.
column_name : str
Name for the column.
column : pandas.Series or callable
Series should have an index matching the table to which it
... |
def column(table_name, column_name=None, cache=False, cache_scope=_CS_FOREVER):
def decorator(func):
if column_name:
name = column_name
else:
name = func.__name__
add_column(
table_name, name, func, cache=cache, cache_scope=cache_scope)
return... | Decorates functions that return a Series.
Decorator version of `add_column`. Series index must match
the named table. Column name defaults to name of function.
The function's argument names and keyword argument values
will be matched to registered variables when the function
needs to be evaluated ... |
def _columns_for_table(table_name):
return {cname: col
for (tname, cname), col in _COLUMNS.items()
if tname == table_name} | Return all of the columns registered for a given table.
Parameters
----------
table_name : str
Returns
-------
columns : dict of column wrappers
Keys will be column names. |
def get_raw_column(table_name, column_name):
try:
return _COLUMNS[(table_name, column_name)]
except KeyError:
raise KeyError('column {!r} not found for table {!r}'.format(
column_name, table_name)) | Get a wrapped, registered column.
This function cannot return columns that are part of wrapped
DataFrames, it's only for columns registered directly through Orca.
Parameters
----------
table_name : str
column_name : str
Returns
-------
wrapped : _SeriesWrapper or _ColumnFuncWrappe... |
def _memoize_function(f, name, cache_scope=_CS_FOREVER):
cache = {}
@wraps(f)
def wrapper(*args, **kwargs):
try:
cache_key = (
args or None, frozenset(kwargs.items()) if kwargs else None)
in_cache = cache_key in cache
except TypeError:
... | Wraps a function for memoization and ties it's cache into the
Orca cacheing system.
Parameters
----------
f : function
name : str
Name of injectable.
cache_scope : {'step', 'iteration', 'forever'}, optional
Scope for which to cache data. Default is to cache forever
(or u... |
def add_injectable(
name, value, autocall=True, cache=False, cache_scope=_CS_FOREVER,
memoize=False):
if isinstance(value, Callable):
if autocall:
value = _InjectableFuncWrapper(
name, value, cache=cache, cache_scope=cache_scope)
# clear any cache... | Add a value that will be injected into other functions.
Parameters
----------
name : str
value
If a callable and `autocall` is True then the function's
argument names and keyword argument values will be matched
to registered variables when the function needs to be
evalua... |
def injectable(
name=None, autocall=True, cache=False, cache_scope=_CS_FOREVER,
memoize=False):
def decorator(func):
if name:
n = name
else:
n = func.__name__
add_injectable(
n, func, autocall=autocall, cache=cache, cache_scope=cache_s... | Decorates functions that will be injected into other functions.
Decorator version of `add_injectable`. Name defaults to
name of function.
The function's argument names and keyword argument values
will be matched to registered variables when the function
needs to be evaluated by Orca.
The argum... |
def get_injectable(name):
i = get_raw_injectable(name)
return i() if isinstance(i, _InjectableFuncWrapper) else i | Get an injectable by name. *Does not* evaluate wrapped functions.
Parameters
----------
name : str
Returns
-------
injectable
Original value or evaluated value of an _InjectableFuncWrapper. |
def get_injectable_func_source_data(name):
if injectable_type(name) != 'function':
raise ValueError('injectable {!r} is not a function'.format(name))
inj = get_raw_injectable(name)
if isinstance(inj, _InjectableFuncWrapper):
return utils.func_source_data(inj._func)
elif hasattr(in... | Return data about an injectable function's source, including file name,
line number, and source code.
Parameters
----------
name : str
Returns
-------
filename : str
lineno : int
The line number on which the function starts.
source : str |
def add_step(step_name, func):
if isinstance(func, Callable):
logger.debug('registering step {!r}'.format(step_name))
_STEPS[step_name] = _StepFuncWrapper(step_name, func)
else:
raise TypeError('func must be a callable') | Add a step function to Orca.
The function's argument names and keyword argument values
will be matched to registered variables when the function
needs to be evaluated by Orca.
The argument name "iter_var" may be used to have the current
iteration variable injected.
Parameters
----------
... |
def step(step_name=None):
def decorator(func):
if step_name:
name = step_name
else:
name = func.__name__
add_step(name, func)
return func
return decorator | Decorates functions that will be called by the `run` function.
Decorator version of `add_step`. step name defaults to
name of function.
The function's argument names and keyword argument values
will be matched to registered variables when the function
needs to be evaluated by Orca.
The argumen... |
def broadcast(cast, onto, cast_on=None, onto_on=None,
cast_index=False, onto_index=False):
logger.debug(
'registering broadcast of table {!r} onto {!r}'.format(cast, onto))
_BROADCASTS[(cast, onto)] = \
Broadcast(cast, onto, cast_on, onto_on, cast_index, onto_index) | Register a rule for merging two tables by broadcasting one onto
the other.
Parameters
----------
cast, onto : str
Names of registered tables.
cast_on, onto_on : str, optional
Column names used for merge, equivalent of ``left_on``/``right_on``
parameters of pandas.merge.
... |
def _get_broadcasts(tables):
tables = set(tables)
casts = tz.keyfilter(
lambda x: x[0] in tables and x[1] in tables, _BROADCASTS)
if tables - set(tz.concat(casts.keys())):
raise ValueError('Not enough links to merge all tables.')
return casts | Get the broadcasts associated with a set of tables.
Parameters
----------
tables : sequence of str
Table names for which broadcasts have been registered.
Returns
-------
casts : dict of `Broadcast`
Keys are tuples of strings like (cast_name, onto_name). |
def get_broadcast(cast_name, onto_name):
if is_broadcast(cast_name, onto_name):
return _BROADCASTS[(cast_name, onto_name)]
else:
raise KeyError(
'no rule found for broadcasting {!r} onto {!r}'.format(
cast_name, onto_name)) | Get a single broadcast.
Broadcasts are stored data about how to do a Pandas join.
A Broadcast object is a namedtuple with these attributes:
- cast: the name of the table being broadcast
- onto: the name of the table onto which "cast" is broadcast
- cast_on: The optional name of a colum... |
def _all_reachable_tables(t):
for k, v in t.items():
for tname in _all_reachable_tables(v):
yield tname
yield k | A generator that provides all the names of tables that can be
reached via merges starting at the given target table. |
def _recursive_getitem(d, key):
if key in d:
return d
else:
for v in d.values():
return _recursive_getitem(v, key)
else:
raise KeyError('Key not found: {}'.format(key)) | Descend into a dict of dicts to return the one that contains
a given key. Every value in the dict must be another dict. |
def _dict_value_to_pairs(d):
d = d[tz.first(d)]
for k, v in d.items():
yield {k: v} | Takes the first value of a dictionary (which it self should be
a dictionary) and turns it into a series of {key: value} dicts.
For example, _dict_value_to_pairs({'c': {'a': 1, 'b': 2}}) will yield
{'a': 1} and {'b': 2}. |
def _next_merge(merge_node):
if all(_is_leaf_node(d) for d in _dict_value_to_pairs(merge_node)):
return merge_node
else:
for d in tz.remove(_is_leaf_node, _dict_value_to_pairs(merge_node)):
return _next_merge(d)
else:
raise OrcaError('No node found for next m... | Gets a node that has only leaf nodes below it. This table and
the ones below are ready to be merged to make a new leaf node. |
def get_step_table_names(steps):
table_names = set()
for s in steps:
table_names |= get_step(s)._tables_used()
return list(table_names) | Returns a list of table names injected into the provided steps.
Parameters
----------
steps: list of str
Steps to gather table inputs from.
Returns
-------
list of str |
def write_tables(fname, table_names=None, prefix=None, compress=False, local=False):
if table_names is None:
table_names = list_tables()
tables = (get_table(t) for t in table_names)
key_template = '{}/{{}}'.format(prefix) if prefix is not None else '{}'
# set compression options to zlib l... | Writes tables to a pandas.HDFStore file.
Parameters
----------
fname : str
File name for HDFStore. Will be opened in append mode and closed
at the end of this function.
table_names: list of str, optional, default None
List of tables to write. If None, all registered tables will
... |
def injectables(**kwargs):
global _INJECTABLES
original = _INJECTABLES.copy()
_INJECTABLES.update(kwargs)
yield
_INJECTABLES = original | Temporarily add injectables to the pipeline environment.
Takes only keyword arguments.
Injectables will be returned to their original state when the context
manager exits. |
def temporary_tables(**kwargs):
global _TABLES
original = _TABLES.copy()
for k, v in kwargs.items():
if not isinstance(v, pd.DataFrame):
raise ValueError('tables only accepts DataFrames')
add_table(k, v)
yield
_TABLES = original | Temporarily set DataFrames as registered tables.
Tables will be returned to their original state when the context
manager exits. Caching is not enabled for tables registered via
this function. |
def eval_variable(name, **kwargs):
with injectables(**kwargs):
vars = _collect_variables([name], [name])
return vars[name] | Execute a single variable function registered with Orca
and return the result. Any keyword arguments are temporarily set
as injectables. This gives the value as would be injected into a function.
Parameters
----------
name : str
Name of variable to evaluate.
Use variable expressions... |
def to_frame(self, columns=None):
extra_cols = _columns_for_table(self.name)
if columns is not None:
columns = [columns] if isinstance(columns, str) else columns
columns = set(columns)
set_extra_cols = set(extra_cols)
local_cols = set(self.local.... | Make a DataFrame with the given columns.
Will always return a copy of the underlying table.
Parameters
----------
columns : sequence or string, optional
Sequence of the column names desired in the DataFrame. A string
can also be passed if only one column is desi... |
def update_col(self, column_name, series):
logger.debug('updating column {!r} in table {!r}'.format(
column_name, self.name))
self.local[column_name] = series | Add or replace a column in the underlying DataFrame.
Parameters
----------
column_name : str
Column to add or replace.
series : pandas.Series or sequence
Column data. |
def get_column(self, column_name):
with log_start_finish(
'getting single column {!r} from table {!r}'.format(
column_name, self.name),
logger):
extra_cols = _columns_for_table(self.name)
if column_name in extra_cols:
... | Returns a column as a Series.
Parameters
----------
column_name : str
Returns
-------
column : pandas.Series |
def column_type(self, column_name):
extra_cols = list_columns_for_table(self.name)
if column_name in extra_cols:
col = _COLUMNS[(self.name, column_name)]
if isinstance(col, _SeriesWrapper):
return 'series'
elif isinstance(col, _ColumnFuncWra... | Report column type as one of 'local', 'series', or 'function'.
Parameters
----------
column_name : str
Returns
-------
col_type : {'local', 'series', 'function'}
'local' means that the column is part of the registered table,
'series' means the co... |
def update_col_from_series(self, column_name, series, cast=False):
logger.debug('updating column {!r} in table {!r}'.format(
column_name, self.name))
col_dtype = self.local[column_name].dtype
if series.dtype != col_dtype:
if cast:
series = series... | Update existing values in a column from another series.
Index values must match in both column and series. Optionally
casts data type to match the existing column.
Parameters
---------------
column_name : str
series : panas.Series
cast: bool, optional, default Fa... |
def clear_cached(self):
_TABLE_CACHE.pop(self.name, None)
for col in _columns_for_table(self.name).values():
col.clear_cached()
logger.debug('cleared cached columns for table {!r}'.format(self.name)) | Remove cached results from this table's computed columns. |
def local_columns(self):
if self._columns:
return self._columns
else:
self._call_func()
return self._columns | Only the columns contained in the DataFrame returned by the
wrapped function. (No registered columns included.) |
def _call_func(self):
if _CACHING and self.cache and self.name in _TABLE_CACHE:
logger.debug('returning table {!r} from cache'.format(self.name))
return _TABLE_CACHE[self.name].value
with log_start_finish(
'call function to get frame for table {!r}'.form... | Call the wrapped function and return the result wrapped by
DataFrameWrapper.
Also updates attributes like columns, index, and length. |
def get_column(self, column_name):
frame = self._call_func()
return DataFrameWrapper(self.name, frame,
copy_col=self.copy_col).get_column(column_name) | Returns a column as a Series.
Parameters
----------
column_name : str
Returns
-------
column : pandas.Series |
def clear_cached(self):
x = _COLUMN_CACHE.pop((self.table_name, self.name), None)
if x is not None:
logger.debug(
'cleared cached value for column {!r} in table {!r}'.format(
self.name, self.table_name)) | Remove any cached result of this column. |
def clear_cached(self):
x = _INJECTABLE_CACHE.pop(self.name, None)
if x:
logger.debug(
'injectable {!r} removed from cache'.format(self.name)) | Clear a cached result for this injectable. |
def _tables_used(self):
args = list(self._argspec.args)
if self._argspec.defaults:
default_args = list(self._argspec.defaults)
else:
default_args = []
# Combine names from argument names and argument default values.
names = args[:len(args) - len(d... | Tables injected into the step.
Returns
-------
tables : set of str |
def qbe_tree(graph, nodes, root=None):
if root:
start = root
else:
index = random.randint(0, len(nodes) - 1)
start = nodes[index]
# A queue to BFS instead DFS
to_visit = deque()
cnodes = copy(nodes)
visited = set()
# Format is (parent, parent_edge, neighbor, neig... | Given a graph, nodes to explore and an optinal root, do a breadth-first
search in order to return the tree. |
def combine(items, k=None):
length_items = len(items)
lengths = [len(i) for i in items]
length = reduce(lambda x, y: x * y, lengths)
repeats = [reduce(lambda x, y: x * y, lengths[i:])
for i in range(1, length_items)] + [1]
if k is not None:
k = k % length
# Python... | Create a matrix in wich each row is a tuple containing one of solutions or
solution k-esima. |
def pickle_encode(session_dict):
"Returns the given session dictionary pickled and encoded as a string."
pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL)
return base64.encodestring(pickled + get_query_hash(pickled).encode()f pickle_encode(session_dict):
"Returns the given session dictionary... | Returns the given session dictionary pickled and encoded as a string. |
def func_source_data(func):
filename = inspect.getsourcefile(func)
lineno = inspect.getsourcelines(func)[1]
source = inspect.getsource(func)
return filename, lineno, source | Return data about a function source, including file name,
line number, and source code.
Parameters
----------
func : object
May be anything support by the inspect module, such as a function,
method, or class.
Returns
-------
filename : str
lineno : int
The line ... |
def clean(self):
if any(self.errors):
# Don't bother validating the formset unless each form is valid on
# its own
return
(selects, aliases, froms, wheres, sorts, groups_by,
params) = self.get_query_parts()
if not selects:
validat... | Checks that there is almost one field to select |
def get_results(self, limit=None, offset=None, query=None, admin_name=None,
row_number=False):
add_extra_ids = (admin_name is not None)
if not query:
sql = self.get_raw_query(limit=limit, offset=offset,
add_extra_ids=add_extra... | Fetch all results after perform SQL query and |
def parse_content_type(content_type):
if '; charset=' in content_type:
return tuple(content_type.split('; charset='))
else:
if 'text' in content_type:
encoding = 'ISO-8859-1'
else:
try:
format = formats.find_by_content_type(content_type)
... | Return a tuple of content type and charset.
:param content_type: A string describing a content type. |
def parse_http_accept_header(header):
components = [item.strip() for item in header.split(',')]
l = []
for component in components:
if ';' in component:
subcomponents = [item.strip() for item in component.split(';')]
l.append(
(
subco... | Return a list of content types listed in the HTTP Accept header
ordered by quality.
:param header: A string describing the contents of the HTTP Accept header. |
def parse_multipart_data(request):
return MultiPartParser(
META=request.META,
input_data=StringIO(request.body),
upload_handlers=request.upload_handlers,
encoding=request.encoding
).parse() | Parse a request with multipart data.
:param request: A HttpRequest instance. |
def override_supported_formats(formats):
def decorator(function):
@wraps(function)
def wrapper(self, *args, **kwargs):
self.supported_formats = formats
return function(self, *args, **kwargs)
return wrapper
return decorator | Override the views class' supported formats for the decorated function.
Arguments:
formats -- A list of strings describing formats, e.g. ``['html', 'json']``. |
def route(regex, method, name):
def decorator(function):
function.route = routes.route(
regex = regex,
view = function.__name__,
method = method,
name = name
)
@wraps(function)
def wrapper(self, *args, **kwargs):
retu... | Route the decorated view.
:param regex: A string describing a regular expression to which the request path will be matched.
:param method: A string describing the HTTP method that this view accepts.
:param name: A string describing the name of the URL pattern.
``regex`` may also be a lambda that a... |
def before(method_name):
def decorator(function):
@wraps(function)
def wrapper(self, *args, **kwargs):
returns = getattr(self, method_name)(*args, **kwargs)
if returns is None:
return function(self, *args, **kwargs)
else:
if i... | Run the given method prior to the decorated view.
If you return anything besides ``None`` from the given method,
its return values will replace the arguments of the decorated
view.
If you return an instance of ``HttpResponse`` from the given method,
Respite will return it immediately without deleg... |
def index(self, request):
objects = self.model.objects.all()
return self._render(
request = request,
template = 'index',
context = {
cc2us(pluralize(self.model.__name__)): objects,
},
status = 200
) | Render a list of objects. |
def new(self, request):
form = (self.form or generate_form(self.model))()
return self._render(
request = request,
template = 'new',
context = {
'form': form
},
status = 200
) | Render a form to create a new object. |
def create(self, request):
form = (self.form or generate_form(self.model))(request.POST)
if form.is_valid():
object = form.save()
return self._render(
request = request,
template = 'show',
context = {
... | Create a new object. |
def edit(self, request, id):
try:
object = self.model.objects.get(id=id)
except self.model.DoesNotExist:
return self._render(
request = request,
template = '404',
context = {
'error': 'The %s could not b... | Render a form to edit an object. |
def update(self, request, id):
try:
object = self.model.objects.get(id=id)
except self.model.DoesNotExist:
return self._render(
request = request,
template = '404',
context = {
'error': 'The %s could not... | Update an object. |
def replace(self, request, id):
try:
object = self.model.objects.get(id=id)
except self.model.DoesNotExist:
return self._render(
request = request,
template = '404',
context = {
'error': 'The %s could no... | Replace an object. |
def destroy(self, request, id):
try:
object = self.model.objects.get(id=id)
object.delete()
except self.model.DoesNotExist:
return self._render(
request = request,
template = '404',
context = {
... | Delete an object. |
def get_search_fields(cls):
sfdict = {}
for klass in tuple(cls.__bases__) + (cls, ):
if hasattr(klass, 'search_fields'):
sfdict.update(klass.search_fields)
return sfdict | Returns search fields in sfdict |
def find(identifier):
for format in FORMATS:
if identifier in [format.name, format.acronym, format.extension]:
return format
raise UnknownFormat('No format found with name, acronym or extension "%s"' % identifier) | Find and return a format by name, acronym or extension.
:param identifier: A string describing the format. |
def find_by_name(name):
for format in FORMATS:
if name == format.name:
return format
raise UnknownFormat('No format found with name "%s"' % name) | Find and return a format by name.
:param name: A string describing the name of the format. |
def find_by_extension(extension):
for format in FORMATS:
if extension in format.extensions:
return format
raise UnknownFormat('No format found with extension "%s"' % extension) | Find and return a format by extension.
:param extension: A string describing the extension of the format. |
def find_by_content_type(content_type):
for format in FORMATS:
if content_type in format.content_types:
return format
raise UnknownFormat('No format found with content type "%s"' % content_type) | Find and return a format by content type.
:param content_type: A string describing the internet media type of the format. |
def options(self, request, map, *args, **kwargs):
options = {}
for method, function in map.items():
options[method] = function.__doc__
return self._render(
request = request,
template = 'options',
context = {
'options': op... | List communication options. |
def _error(self, request, status, headers={}, prefix_template_path=False, **kwargs):
return self._render(
request = request,
template = str(status),
status = status,
context = {
'error': kwargs
},
headers = headers... | Convenience method to render an error response. The template is inferred from the status code.
:param request: A django.http.HttpRequest instance.
:param status: An integer describing the HTTP status code to respond with.
:param headers: A dictionary describing HTTP headers.
:param pref... |
def find(format):
try:
serializer = SERIALIZERS[format]
except KeyError:
raise UnknownSerializer('No serializer found for %s' % format.acronym)
return serializer | Find and return a serializer for the given format.
Arguments:
format -- A Format instance. |
def get_form_kwargs(self):
update_data ={}
sfdict = self.filter_class.get_search_fields()
for fieldname in sfdict:
try:
has_multiple = sfdict[fieldname].get('multiple', False)
except:
has_multiple = False
if has_multip... | Returns the keyword arguments for instantiating the search form. |
def us2mc(string):
return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), string) | Transform an underscore_case string to a mixedCase string |
def generate_form(model, form=None, fields=False, exclude=False):
_model, _fields, _exclude = model, fields, exclude
class Form(form or forms.ModelForm):
class Meta:
model = _model
if _fields is not False:
fields = _fields
if _exclude is not Fa... | Generate a form from a model.
:param model: A Django model.
:param form: A Django form.
:param fields: A list of fields to include in this form.
:param exclude: A list of fields to exclude in this form. |
def route(regex, view, method, name):
return _Route(regex, view, method, name) | Route the given view.
:param regex: A string describing a regular expression to which the request path will be matched.
:param view: A string describing the name of the view to delegate the request to.
:param method: A string describing the HTTP method that this view accepts.
:param name: A string ... |
def sample_double_norm(mean, std_upper, std_lower, size):
from scipy.special import erfinv
# There's probably a better way to do this. We first draw percentiles
# uniformly between 0 and 1. We want the peak of the distribution to occur
# at `mean`. However, if we assign 50% of the samples to the l... | Note that this function requires Scipy. |
def sample_gamma(alpha, beta, size):
if alpha <= 0:
raise ValueError('alpha must be positive; got %e' % alpha)
if beta <= 0:
raise ValueError('beta must be positive; got %e' % beta)
return np.random.gamma(alpha, scale=1./beta, size=size) | This is mostly about recording the conversion between Numpy/Scipy
conventions and Wikipedia conventions. Some equations:
mean = alpha / beta
variance = alpha / beta**2
mode = (alpha - 1) / beta [if alpha > 1; otherwise undefined]
skewness = 2 / sqrt(alpha) |
def find_gamma_params(mode, std):
if mode < 0:
raise ValueError('input mode must be positive for gamma; got %e' % mode)
var = std**2
beta = (mode + np.sqrt(mode**2 + 4 * var)) / (2 * var)
j = 2 * var / mode**2
alpha = (j + 1 + np.sqrt(2 * j + 1)) / j
if alpha <= 1:
raise V... | Given a modal value and a standard deviation, compute corresponding
parameters for the gamma distribution.
Intended to be used to replace normal distributions when the value must be
positive and the uncertainty is comparable to the best value. Conversion
equations determined from the relations given in... |
def _lval_add_towards_polarity(x, polarity):
if x < 0:
if polarity < 0:
return Lval('toinf', x)
return Lval('pastzero', x)
elif polarity > 0:
return Lval('toinf', x)
return Lval('pastzero', x) | Compute the appropriate Lval "kind" for the limit of value `x` towards
`polarity`. Either 'toinf' or 'pastzero' depending on the sign of `x` and
the infinity direction of polarity. |
def unwrap(msmt):
if np.isscalar(msmt):
return float(msmt)
if isinstance(msmt, (Uval, Lval)):
return msmt
if isinstance(msmt, Textual):
return msmt.unwrap()
raise ValueError('don\'t know how to treat %r as a measurement' % msmt) | Convert the value into the most basic representation that we can do
math on: float if possible, then Uval, then Lval. |
def repval(msmt, limitsok=False):
if np.isscalar(msmt):
return float(msmt)
if isinstance(msmt, Uval):
return msmt.repvals(uval_default_repval_method)[0]
if isinstance(msmt, Lval):
if not limitsok and msmt.kind in('tozero', 'toinf', 'pastzero'):
raise LimitError()
... | Get a best-effort representative value as a float. This is DANGEROUS
because it discards limit information, which is rarely wise. m_liminfo()
or m_unwrap() are recommended instead. |
def limtype(msmt):
if np.isscalar(msmt):
return 0
if isinstance(msmt, Uval):
return 0
if isinstance(msmt, Lval):
if msmt.kind == 'undef':
raise ValueError('no simple limit type for Lval %r' % msmt)
# Quasi-hack here: limits of ('tozero', [positive number]) ... | Return -1 if this value is some kind of upper limit, 1 if this value
is some kind of lower limit, 0 otherwise. |
def errinfo(msmt):
if isinstance(msmt, Textual):
msmt = msmt.unwrap()
if np.isscalar(msmt):
return 0, msmt, msmt, msmt
if isinstance(msmt, Uval):
rep, plus1, minus1 = msmt.repvals(uval_default_repval_method)
return 0, rep, plus1, minus1
if isinstance(msmt, Lval):... | Return (limtype, repval, errval1, errval2). Like m_liminfo, but also
provides error bar information for values that have it. |
def fmtinfo(value):
if value is None:
raise ValueError('cannot format None!')
if isinstance(value, text_type):
return '', value, False
if isinstance(value, bool):
# Note: isinstance(True, int) = True, so this must come before the next case.
if value:
return... | Returns (typetag, text, is_imprecise). Unlike other functions that operate
on measurements, this also operates on bools, ints, and strings. |
def from_pcount(nevents):
if nevents < 0:
raise ValueError('Poisson parameter `nevents` must be nonnegative')
return Uval(np.random.gamma(nevents + 1, size=uval_nsamples)) | We assume a Poisson process. nevents is the number of events in
some interval. The distribution of values is the distribution of the
Poisson rate parameter given this observed number of events, where the
"rate" is in units of events per interval of the same duration. The
max-likelihood v... |
def repvals(self, method):
if method == 'pct':
return pk_scoreatpercentile(self.d, [50., 84.134, 15.866])
if method == 'gauss':
m, s = self.d.mean(), self.d.std()
return np.asarray([m, m + s, m - s])
raise ValueError('unknown representative-value meth... | Compute representative statistical values for this Uval. `method`
may be either 'pct' or 'gauss'.
Returns (best, plus_one_sigma, minus_one_sigma), where `best` is the
"best" value in some sense, and the others correspond to values at
the ~84 and 16 percentile limits, respectively. Becau... |
def repval(self, limitsok=False):
if not limitsok and self.dkind in ('lower', 'upper'):
raise LimitError()
if self.dkind == 'unif':
lower, upper = map(float, self.data)
v = 0.5 * (lower + upper)
elif self.dkind in _noextra_dkinds:
v = fl... | Get a best-effort representative value as a float. This can be
DANGEROUS because it discards limit information, which is rarely wise. |
def in_casapy (helper, vis=None, figfile=None):
if vis is None:
raise ValueError ('vis')
helper.casans.plotants (vis=vis, figfile=figfile) | This function is run inside the weirdo casapy IPython environment! A
strange set of modules is available, and the
`pwkit.environments.casa.scripting` system sets up a very particular
environment to allow encapsulated scripting. |
def datasets(dataset, node, ll=None, ur=None, start_date=None, end_date=None, api_key=None):
payload = {
"node": node,
"apiKey": api_key
}
if dataset:
payload["datasetName"] = dataset
if ll and ur:
payload["lowerLeft"] = {
"latitude": ll["latitude"],
... | This method is used to find datasets available for searching.
By passing no parameters except node, all available datasets
are returned. Additional parameters such as temporal range
and spatial bounding box can be used to find datasets that
provide more specific data. The dataset name parameter can
... |
def download(dataset, node, entityids, products, api_key=None):
payload = {
"datasetName": dataset,
"node": node,
"apiKey": api_key,
"entityIds": entityids,
"products": products
}
return json.dumps(payload) | The use of this request will be to obtain valid data download URLs.
:param dataset:
:param entityIds:
list
:param products:
list
:param node:
:param api_key:
API key is required. |
def download_options(dataset, node, entityids, api_key=None):
payload = {
"apiKey": api_key,
"datasetName": dataset,
"node": node,
"entityIds": entityids
}
return json.dumps(payload) | The use of the download options request is to discover the different download
options for each scene. Some download options may exist but still be unavailable
due to disk usage and many other factors. If a download is unavailable
it may need to be ordered.
:param dataset:
:param node:
... |
def login(username, password, catalogId='EE'):
payload = {
"username": username,
"password": password,
"authType": "",
"catalogId": catalogId
}
return json.dumps(payload) | This method requires SSL be used due to the sensitive nature of
users passwords. Upon a successful login, an API key will be
returned. This key will be active for one hour and should be
destroyed upon final use of the service by calling the logout
method. Users must have "Machine to Machine" access base... |
def metadata(dataset, node, entityids, api_key=None):
payload = {
"apiKey": api_key,
"datasetName": dataset,
"node": node,
"entityIds": entityids
}
return json.dumps(payload) | The use of the metadata request is intended for those who have
acquired scene IDs from a different source. It will return the
same metadata that is available via the search request.
:param dataset:
:param node:
:param sceneid:
:param api_key: |
def approx_colormap (samples, transform='none', fitfactor=1.):
import scipy.interpolate as SI
values = samples[0]
if transform == 'none':
pass
elif transform == 'reverse':
samples = samples[:,::-1]
elif transform == 'sqrt':
values = np.sqrt (values)
else:
ra... | Given a colormap sampled at various values, compute splines that
interpolate in R, G, and B (separately) for fast evaluation of the
colormap for arbitrary float values. We have primitive support for some
transformations, though these are generally best done upstream of the
color mapping code.
sampl... |
def srgb_to_linsrgb (srgb):
gamma = ((srgb + 0.055) / 1.055)**2.4
scale = srgb / 12.92
return np.where (srgb > 0.04045, gamma, scale) | Convert sRGB values to physically linear ones. The transformation is
uniform in RGB, so *srgb* can be of any shape.
*srgb* values should range between 0 and 1, inclusively. |
def linsrgb_to_srgb (linsrgb):
# From Wikipedia, but easy analogue to the above.
gamma = 1.055 * linsrgb**(1./2.4) - 0.055
scale = linsrgb * 12.92
return np.where (linsrgb > 0.0031308, gamma, scale) | Convert physically linear RGB values into sRGB ones. The transform is
uniform in the components, so *linsrgb* can be of any shape.
*linsrgb* values should range between 0 and 1, inclusively. |
def xyz_to_cielab (xyz, refwhite):
norm = xyz / refwhite
pow = norm**0.333333333333333
scale = 7.787037 * norm + 16./116
mapped = np.where (norm > 0.008856, pow, scale)
cielab = np.empty_like (xyz)
cielab[...,L] = 116 * mapped[...,Y] - 16
cielab[...,A] = 500 * (mapped[...,X] - mapped[.... | Convert CIE XYZ color values to CIE L*a*b*.
*xyz* should be of shape (*, 3). *refwhite* is the reference white value, of
shape (3, ).
Return value will have same shape as *xyz*, but be in CIE L*a*b*
coordinates. |
def cielab_to_xyz (cielab, refwhite):
def func (t):
pow = t**3
scale = 0.128419 * t - 0.0177129
return np.where (t > 0.206897, pow, scale)
xyz = np.empty_like (cielab)
lscale = 1./116 * (cielab[...,L] + 16)
xyz[...,X] = func (lscale + 0.002 * cielab[...,A])
xyz[...,Y] =... | Convert CIE L*a*b* color values to CIE XYZ,
*cielab* should be of shape (*, 3). *refwhite* is the reference white
value in the L*a*b* color space, of shape (3, ).
Return value has same shape as *cielab* |
def cielab_to_msh (cielab):
msh = np.empty_like (cielab)
msh[...,M] = np.sqrt ((cielab**2).sum (axis=-1))
msh[...,S] = np.arccos (cielab[...,L] / msh[...,M])
msh[...,H] = np.arctan2 (cielab[...,B], cielab[...,A])
return msh | Convert CIE L*a*b* to Moreland's Msh colorspace.
*cielab* should be of shape (*, 3).
Return value will have same shape. |
def msh_to_cielab (msh):
cielab = np.empty_like (msh)
cielab[...,L] = msh[...,M] * np.cos (msh[...,S])
cielab[...,A] = msh[...,M] * np.sin (msh[...,S]) * np.cos (msh[...,H])
cielab[...,B] = msh[...,M] * np.sin (msh[...,S]) * np.sin (msh[...,H])
return cielab | Convert Moreland's Msh colorspace to CIE L*a*b*.
*msh* should be of shape (*, 3).
Return value will have same shape. |
def moreland_adjusthue (msh, m_unsat):
if msh[M] >= m_unsat:
return msh[H] # "Best we can do"
hspin = (msh[S] * np.sqrt (m_unsat**2 - msh[M]**2) /
(msh[M] * np.sin (msh[S])))
if msh[H] > -np.pi / 3: # "Spin away from purple"
return msh[H] + hspin
return msh[H] - hspin | Moreland's AdjustHue procedure to adjust the hue value of an Msh color
based on ... some criterion.
*msh* should be of of shape (3, ). *m_unsat* is a scalar.
Return value is the adjusted h (hue) value. |
def get_datasets_in_nodes():
data_dir = os.path.join(scriptdir, "..", "usgs", "data")
cwic = map(lambda d: d["datasetName"], api.datasets(None, CWIC_LSI_EXPLORER_CATALOG_NODE)['data'])
ee = map(lambda d: d["datasetName"], api.datasets(None, EARTH_EXPLORER_CATALOG_NODE)['data'])
hdds = map(lambda ... | Get the node associated with each dataset. Some datasets
will have an ambiguous node since they exists in more than
one node. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.