_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q10400 | Request.body | train | def body(self):
"""return the raw version of the body"""
body = None
if self.body_input:
body = self.body_input.read(int(self.get_header('content-length', -1)))
return body | python | {
"resource": ""
} |
q10401 | Request.body_kwargs | train | def body_kwargs(self):
"""
the request body, if this is a POST request
this tries to do the right thing with the body, so if you have set the body and
the content type is json, then it will return the body json decoded, if you need
the original string body, use body
exa... | python | {
"resource": ""
} |
q10402 | Request.kwargs | train | def kwargs(self):
"""combine GET and POST params to be passed to the controller"""
kwargs = dict(self.query_kwargs)
kwargs.update(self.body_kwargs)
return kwargs | python | {
"resource": ""
} |
q10403 | Request.get_auth_bearer | train | def get_auth_bearer(self):
"""return the bearer token in the authorization header if it exists"""
access_token = ''
auth_header = self.get_header('authorization')
if auth_header:
m = re.search(r"^Bearer\s+(\S+)$", auth_header, re.I)
if m: access_token = m.group(1)... | python | {
"resource": ""
} |
q10404 | Request.get_auth_basic | train | def get_auth_basic(self):
"""return the username and password of a basic auth header if it exists"""
username = ''
password = ''
auth_header = self.get_header('authorization')
if auth_header:
m = re.search(r"^Basic\s+(\S+)$", auth_header, re.I)
if m:
... | python | {
"resource": ""
} |
q10405 | Response.code | train | def code(self):
"""the http status code to return to the client, by default, 200 if a body is present otherwise 204"""
code = getattr(self, '_code', None)
if not code:
if self.has_body():
code = 200
else:
code = 204
return code | python | {
"resource": ""
} |
q10406 | Response.normalize_body | train | def normalize_body(self, b):
"""return the body as a string, formatted to the appropriate content type
:param b: mixed, the current raw body
:returns: unicode string
"""
if b is None: return ''
if self.is_json():
# TODO ???
# I don't like this, i... | python | {
"resource": ""
} |
q10407 | TargetDecorator.normalize_target_params | train | def normalize_target_params(self, request, controller_args, controller_kwargs):
"""get params ready for calling target
this method exists because child classes might only really need certain params
passed to the method, this allows the child classes to decided what their
target methods ... | python | {
"resource": ""
} |
q10408 | TargetDecorator.handle_target | train | def handle_target(self, request, controller_args, controller_kwargs):
"""Internal method for this class
handles normalizing the passed in values from the decorator using
.normalize_target_params() and then passes them to the set .target()
"""
try:
param_args, param_k... | python | {
"resource": ""
} |
q10409 | TargetDecorator.decorate | train | def decorate(self, func, target, *anoop, **kwnoop):
"""decorate the passed in func calling target when func is called
:param func: the function being decorated
:param target: the target that will be run when func is called
:returns: the decorated func
"""
if target:
... | python | {
"resource": ""
} |
q10410 | param.normalize_flags | train | def normalize_flags(self, flags):
"""normalize the flags to make sure needed values are there
after this method is called self.flags is available
:param flags: the flags that will be normalized
"""
flags['type'] = flags.get('type', None)
paction = flags.get('action', 's... | python | {
"resource": ""
} |
q10411 | param.normalize_type | train | def normalize_type(self, names):
"""Decide if this param is an arg or a kwarg and set appropriate internal flags"""
self.name = names[0]
self.is_kwarg = False
self.is_arg = False
self.names = []
try:
# http://stackoverflow.com/a/16488383/5006 uses ask forgive... | python | {
"resource": ""
} |
q10412 | param.normalize_param | train | def normalize_param(self, slf, args, kwargs):
"""this is where all the magic happens, this will try and find the param and
put its value in kwargs if it has a default and stuff"""
if self.is_kwarg:
kwargs = self.normalize_kwarg(slf.request, kwargs)
else:
args = se... | python | {
"resource": ""
} |
q10413 | param.find_kwarg | train | def find_kwarg(self, request, names, required, default, kwargs):
"""actually try to retrieve names key from params dict
:param request: the current request instance, handy for child classes
:param names: the names this kwarg can be
:param required: True if a name has to be found in kwar... | python | {
"resource": ""
} |
q10414 | WebsocketClient.open | train | def open(cls, *args, **kwargs):
"""just something to make it easier to quickly open a connection, do something
and then close it"""
c = cls(*args, **kwargs)
c.connect()
try:
yield c
finally:
c.close() | python | {
"resource": ""
} |
q10415 | WebsocketClient.connect | train | def connect(self, path="", headers=None, query=None, timeout=0, **kwargs):
"""
make the actual connection to the websocket
:param headers: dict, key/val pairs of any headers to add to connection, if
you would like to override headers just pass in an empty value
:param query:... | python | {
"resource": ""
} |
q10416 | WebsocketClient.fetch | train | def fetch(self, method, path, query=None, body=None, timeout=0, **kwargs):
"""send a Message
:param method: string, something like "POST" or "GET"
:param path: string, the path part of a uri (eg, /foo/bar)
:param body: dict, what you want to send to "method path"
:param timeout:... | python | {
"resource": ""
} |
q10417 | WebsocketClient.ping | train | def ping(self, timeout=0, **kwargs):
"""THIS DOES NOT WORK, UWSGI DOES NOT RESPOND TO PINGS"""
# http://stackoverflow.com/a/2257449/5006
def rand_id(size=8, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
payload = ra... | python | {
"resource": ""
} |
q10418 | WebsocketClient.recv_raw | train | def recv_raw(self, timeout, opcodes, **kwargs):
"""this is very internal, it will return the raw opcode and data if they
match the passed in opcodes"""
orig_timeout = self.get_timeout(timeout)
timeout = orig_timeout
while timeout > 0.0:
start = time.time()
... | python | {
"resource": ""
} |
q10419 | WebsocketClient.get_fetch_response | train | def get_fetch_response(self, raw):
"""This just makes the payload instance more HTTPClient like"""
p = Payload(raw)
p._body = p.body
return p | python | {
"resource": ""
} |
q10420 | WebsocketClient.recv | train | def recv(self, timeout=0, **kwargs):
"""this will receive data and convert it into a message, really this is more
of an internal method, it is used in recv_callback and recv_msg"""
opcode, data = self.recv_raw(timeout, [websocket.ABNF.OPCODE_TEXT], **kwargs)
return self.get_fetch_respons... | python | {
"resource": ""
} |
q10421 | WebsocketClient.recv_callback | train | def recv_callback(self, callback, **kwargs):
"""receive messages and validate them with the callback, if the callback
returns True then the message is valid and will be returned, if False then
this will try and receive another message until timeout is 0"""
payload = None
timeout... | python | {
"resource": ""
} |
q10422 | Call.create_controller | train | def create_controller(self):
"""Create a controller to handle the request
:returns: Controller, this Controller instance should be able to handle
the request
"""
body = None
req = self.request
res = self.response
rou = self.router
con = None
... | python | {
"resource": ""
} |
q10423 | Call.handle | train | def handle(self):
"""Called from the interface to actually handle the request."""
body = None
req = self.request
res = self.response
rou = self.router
con = None
start = time.time()
try:
con = self.create_controller()
con.call = se... | python | {
"resource": ""
} |
q10424 | Call.handle_error | train | def handle_error(self, e, **kwargs):
"""if an exception is raised while trying to handle the request it will
go through this method
This method will set the response body and then also call Controller.handle_error
for further customization if the Controller is available
:param ... | python | {
"resource": ""
} |
q10425 | Router.module_names | train | def module_names(self):
"""get all the modules in the controller_prefix
:returns: set, a set of string module names
"""
controller_prefix = self.controller_prefix
_module_name_cache = self._module_name_cache
if controller_prefix in _module_name_cache:
return ... | python | {
"resource": ""
} |
q10426 | Router.modules | train | def modules(self):
"""Returns an iterator of the actual modules, not just their names
:returns: generator, each module under self.controller_prefix
"""
for modname in self.module_names:
module = importlib.import_module(modname)
yield module | python | {
"resource": ""
} |
q10427 | Router.find_modules | train | def find_modules(self, path, prefix):
"""recursive method that will find all the submodules of the given module
at prefix with path"""
modules = set([prefix])
# https://docs.python.org/2/library/pkgutil.html#pkgutil.iter_modules
for module_info in pkgutil.iter_modules([path]):
... | python | {
"resource": ""
} |
q10428 | Router.get_module_name | train | def get_module_name(self, path_args):
"""returns the module_name and remaining path args.
return -- tuple -- (module_name, path_args)"""
controller_prefix = self.controller_prefix
cset = self.module_names
module_name = controller_prefix
mod_name = module_name
whi... | python | {
"resource": ""
} |
q10429 | Router.get_class | train | def get_class(self, module, class_name):
"""try and get the class_name from the module and make sure it is a valid
controller"""
# let's get the class
class_object = getattr(module, class_name, None)
if not class_object or not issubclass(class_object, Controller):
cla... | python | {
"resource": ""
} |
q10430 | Controller.OPTIONS | train | def OPTIONS(self, *args, **kwargs):
"""Handles CORS requests for this controller
if self.cors is False then this will raise a 405, otherwise it sets everything
necessary to satisfy the request in self.response
"""
if not self.cors:
raise CallError(405)
req =... | python | {
"resource": ""
} |
q10431 | Controller.handle | train | def handle(self, *controller_args, **controller_kwargs):
"""handles the request and returns the response
This should set any response information directly onto self.response
this method has the same signature as the request handling methods
(eg, GET, POST) so subclasses can override th... | python | {
"resource": ""
} |
q10432 | Controller.find_methods | train | def find_methods(self):
"""Find the methods that could satisfy this request
This will go through and find any method that starts with the request.method,
so if the request was GET /foo then this would find any methods that start
with GET
https://www.w3.org/Protocols/rfc2616/rfc... | python | {
"resource": ""
} |
q10433 | Controller.find_method_params | train | def find_method_params(self):
"""Return the method params
:returns: tuple (args, kwargs) that will be passed as *args, **kwargs
"""
req = self.request
args = req.controller_info["method_args"]
kwargs = req.controller_info["method_kwargs"]
return args, kwargs | python | {
"resource": ""
} |
q10434 | Controller.log_start | train | def log_start(self, start):
"""log all the headers and stuff at the start of the request"""
if not logger.isEnabledFor(logging.INFO): return
try:
req = self.request
logger.info("REQUEST {} {}?{}".format(req.method, req.path, req.query))
logger.info(datetime.... | python | {
"resource": ""
} |
q10435 | Controller.log_stop | train | def log_stop(self, start):
"""log a summary line on how the request went"""
if not logger.isEnabledFor(logging.INFO): return
stop = time.time()
get_elapsed = lambda start, stop, multiplier, rnd: round(abs(stop - start) * float(multiplier), rnd)
elapsed = get_elapsed(start, stop,... | python | {
"resource": ""
} |
q10436 | build_lane_from_yaml | train | def build_lane_from_yaml(path):
"""Builds a `sparklanes.Lane` object from a YAML definition file.
Parameters
----------
path: str
Path to the YAML definition file
Returns
-------
Lane
Lane, built according to definition in YAML file
"""
# Open
with open(path, 'r... | python | {
"resource": ""
} |
q10437 | Lane.add | train | def add(self, cls_or_branch, *args, **kwargs):
"""Adds a task or branch to the lane.
Parameters
----------
cls_or_branch : Class
*args
Variable length argument list to be passed to `cls_or_branch` during instantiation
**kwargs
Variable length keyw... | python | {
"resource": ""
} |
q10438 | get_historical_data | train | def get_historical_data(nmr_problems):
"""Get the historical tank data.
Args:
nmr_problems (int): the number of problems
Returns:
tuple: (observations, nmr_tanks_ground_truth)
"""
observations = np.tile(np.array([[10, 256, 202, 97]]), (nmr_problems, 1))
nmr_tanks_ground_truth =... | python | {
"resource": ""
} |
q10439 | get_simulated_data | train | def get_simulated_data(nmr_problems):
"""Simulate some data.
This returns the simulated tank observations and the corresponding ground truth maximum number of tanks.
Args:
nmr_problems (int): the number of problems
Returns:
tuple: (observations, nmr_tanks_ground_truth)
"""
# T... | python | {
"resource": ""
} |
q10440 | _get_initial_step | train | def _get_initial_step(parameters, lower_bounds, upper_bounds, max_step_sizes):
"""Get an initial step size to use for every parameter.
This chooses the step sizes based on the maximum step size and the lower and upper bounds.
Args:
parameters (ndarray): The parameters at which to evaluate the grad... | python | {
"resource": ""
} |
q10441 | SimpleConfigAction.apply | train | def apply(self):
"""Apply the current action to the current runtime configuration."""
self._old_config = {k: v for k, v in _config.items()}
self._apply() | python | {
"resource": ""
} |
q10442 | SimpleConfigAction.unapply | train | def unapply(self):
"""Reset the current configuration to the previous state."""
for key, value in self._old_config.items():
_config[key] = value | python | {
"resource": ""
} |
q10443 | Task | train | def Task(entry): # pylint: disable=invalid-name
"""
Decorator with which classes, who act as tasks in a `Lane`, must be decorated. When a class is
being decorated, it becomes a child of `LaneTask`.
Parameters
----------
entry: The name of the task's "main" method, i.e. the method which is exec... | python | {
"resource": ""
} |
q10444 | LaneTaskThread.run | train | def run(self):
"""Overwrites `threading.Thread.run`, to allow handling of exceptions thrown by threads
from within the main app."""
self.exc = None
try:
self.task()
except BaseException:
self.exc = sys.exc_info() | python | {
"resource": ""
} |
q10445 | LaneTaskThread.join | train | def join(self, timeout=None):
"""Overwrites `threading.Thread.join`, to allow handling of exceptions thrown by threads
from within the main app."""
Thread.join(self, timeout=timeout)
if self.exc:
msg = "Thread '%s' threw an exception `%s`: %s" \
% (self.getN... | python | {
"resource": ""
} |
q10446 | mock_decorator | train | def mock_decorator(*args, **kwargs):
"""Mocked decorator, needed in the case we need to mock a decorator"""
def _called_decorator(dec_func):
@wraps(dec_func)
def _decorator(*args, **kwargs):
return dec_func()
return _decorator
return _called_decorator | python | {
"resource": ""
} |
q10447 | import_mock | train | def import_mock(name, *args, **kwargs):
"""Mock all modules starting with one of the mock_modules names."""
if any(name.startswith(s) for s in mock_modules):
return MockModule()
return orig_import(name, *args, **kwargs) | python | {
"resource": ""
} |
q10448 | SimpleCLFunction._get_parameter_signatures | train | def _get_parameter_signatures(self):
"""Get the signature of the parameters for the CL function declaration.
This should return the list of signatures of the parameters for use inside the function signature.
Returns:
list: the signatures of the parameters for the use in the CL code... | python | {
"resource": ""
} |
q10449 | SimpleCLFunction._get_cl_dependency_code | train | def _get_cl_dependency_code(self):
"""Get the CL code for all the CL code for all the dependencies.
Returns:
str: The CL code with the actual code.
"""
code = ''
for d in self._dependencies:
code += d.get_cl_code() + "\n"
return code | python | {
"resource": ""
} |
q10450 | _ProcedureWorker._build_kernel | train | def _build_kernel(self, kernel_source, compile_flags=()):
"""Convenience function for building the kernel for this worker.
Args:
kernel_source (str): the kernel source to use for building the kernel
Returns:
cl.Program: a compiled CL kernel
"""
return cl... | python | {
"resource": ""
} |
q10451 | _ProcedureWorker._get_kernel_arguments | train | def _get_kernel_arguments(self):
"""Get the list of kernel arguments for loading the kernel data elements into the kernel.
This will use the sorted keys for looping through the kernel input items.
Returns:
list of str: the list of parameter definitions
"""
declarati... | python | {
"resource": ""
} |
q10452 | _ProcedureWorker.get_scalar_arg_dtypes | train | def get_scalar_arg_dtypes(self):
"""Get the location and types of the input scalars.
Returns:
list: for every kernel input element either None if the data is a buffer or the numpy data type if
if is a scalar.
"""
dtypes = []
for name, data in self._ke... | python | {
"resource": ""
} |
q10453 | _package_and_submit | train | def _package_and_submit(args):
"""
Packages and submits a job, which is defined in a YAML file, to Spark.
Parameters
----------
args (List): Command-line arguments
"""
args = _parse_and_validate_args(args)
logging.debug(args)
dist = __make_tmp_dir()
try:
__package_depen... | python | {
"resource": ""
} |
q10454 | __run_spark_submit | train | def __run_spark_submit(lane_yaml, dist_dir, spark_home, spark_args, silent):
"""
Submits the packaged application to spark using a `spark-submit` subprocess
Parameters
----------
lane_yaml (str): Path to the YAML lane definition file
dist_dir (str): Path to the directory where the packaged code... | python | {
"resource": ""
} |
q10455 | ctype_to_dtype | train | def ctype_to_dtype(cl_type, mot_float_type='float'):
"""Get the numpy dtype of the given cl_type string.
Args:
cl_type (str): the CL data type to match, for example 'float' or 'float4'.
mot_float_type (str): the C name of the ``mot_float_type``. The dtype will be looked up recursively.
Ret... | python | {
"resource": ""
} |
q10456 | convert_data_to_dtype | train | def convert_data_to_dtype(data, data_type, mot_float_type='float'):
"""Convert the given input data to the correct numpy type.
Args:
data (ndarray): The value to convert to the correct numpy type
data_type (str): the data type we need to convert the data to
mot_float_type (str): the dat... | python | {
"resource": ""
} |
q10457 | split_vector_ctype | train | def split_vector_ctype(ctype):
"""Split a vector ctype into a raw ctype and the vector length.
If the given ctype is not a vector type, we raise an error. I
Args:
ctype (str): the ctype to possibly split into a raw ctype and the vector length
Returns:
tuple: the raw ctype and the vec... | python | {
"resource": ""
} |
q10458 | device_type_from_string | train | def device_type_from_string(cl_device_type_str):
"""Converts values like ``gpu`` to a pyopencl device type string.
Supported values are: ``accelerator``, ``cpu``, ``custom``, ``gpu``. If ``all`` is given, None is returned.
Args:
cl_device_type_str (str): The string we want to convert to a device t... | python | {
"resource": ""
} |
q10459 | topological_sort | train | def topological_sort(data):
"""Topological sort the given dictionary structure.
Args:
data (dict); dictionary structure where the value is a list of dependencies for that given key.
For example: ``{'a': (), 'b': ('a',)}``, where ``a`` depends on nothing and ``b`` depends on ``a``.
Retu... | python | {
"resource": ""
} |
q10460 | is_scalar | train | def is_scalar(value):
"""Test if the given value is a scalar.
This function also works with memory mapped array values, in contrast to the numpy is_scalar method.
Args:
value: the value to test for being a scalar value
Returns:
boolean: if the given value is a scalar or not
"""
... | python | {
"resource": ""
} |
q10461 | all_elements_equal | train | def all_elements_equal(value):
"""Checks if all elements in the given value are equal to each other.
If the input is a single value the result is trivial. If not, we compare all the values to see
if they are exactly the same.
Args:
value (ndarray or number): a numpy array or a single number.
... | python | {
"resource": ""
} |
q10462 | get_single_value | train | def get_single_value(value):
"""Get a single value out of the given value.
This is meant to be used after a call to :func:`all_elements_equal` that returned True. With this
function we return a single number from the input value.
Args:
value (ndarray or number): a numpy array or a single numbe... | python | {
"resource": ""
} |
q10463 | all_logging_disabled | train | def all_logging_disabled(highest_level=logging.CRITICAL):
"""Disable all logging temporarily.
A context manager that will prevent any logging messages triggered during the body from being processed.
Args:
highest_level: the maximum logging level that is being blocked
"""
previous_level = l... | python | {
"resource": ""
} |
q10464 | split_in_batches | train | def split_in_batches(nmr_elements, max_batch_size):
"""Split the total number of elements into batches of the specified maximum size.
Examples::
split_in_batches(30, 8) -> [(0, 8), (8, 15), (16, 23), (24, 29)]
for batch_start, batch_end in split_in_batches(2000, 100):
array[batch_s... | python | {
"resource": ""
} |
q10465 | covariance_to_correlations | train | def covariance_to_correlations(covariance):
"""Transform a covariance matrix into a correlations matrix.
This can be seen as dividing a covariance matrix by the outer product of the diagonal.
As post processing we replace the infinities and the NaNs with zeros and clip the result to [-1, 1].
Args:
... | python | {
"resource": ""
} |
q10466 | multiprocess_mapping | train | def multiprocess_mapping(func, iterable):
"""Multiprocess mapping the given function on the given iterable.
This only works in Linux and Mac systems since Windows has no forking capability. On Windows we fall back on
single processing. Also, if we reach memory limits we fall back on single cpu processing.
... | python | {
"resource": ""
} |
q10467 | parse_cl_function | train | def parse_cl_function(cl_code, dependencies=()):
"""Parse the given OpenCL string to a single SimpleCLFunction.
If the string contains more than one function, we will return only the last, with all the other added as a
dependency.
Args:
cl_code (str): the input string containing one or more fu... | python | {
"resource": ""
} |
q10468 | split_cl_function | train | def split_cl_function(cl_str):
"""Split an CL function into a return type, function name, parameters list and the body.
Args:
cl_str (str): the CL code to parse and plit into components
Returns:
tuple: string elements for the return type, function name, parameter list and the body
"""
... | python | {
"resource": ""
} |
q10469 | make_default_logger | train | def make_default_logger(name=INTERNAL_LOGGER_NAME, level=logging.INFO,
fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s'):
"""Create a logger with the default configuration"""
logger = logging.getLogger(name)
logger.setLevel(level)
if not logger.handlers:
handler... | python | {
"resource": ""
} |
q10470 | CLEnvironment.is_gpu | train | def is_gpu(self):
"""Check if the device associated with this environment is a GPU.
Returns:
boolean: True if the device is an GPU, false otherwise.
"""
return self._device.get_info(cl.device_info.TYPE) == cl.device_type.GPU | python | {
"resource": ""
} |
q10471 | CLEnvironment.is_cpu | train | def is_cpu(self):
"""Check if the device associated with this environment is a CPU.
Returns:
boolean: True if the device is an CPU, false otherwise.
"""
return self._device.get_info(cl.device_info.TYPE) == cl.device_type.CPU | python | {
"resource": ""
} |
q10472 | CLEnvironmentFactory.single_device | train | def single_device(cl_device_type='GPU', platform=None, fallback_to_any_device_type=False):
"""Get a list containing a single device environment, for a device of the given type on the given platform.
This will only fetch devices that support double (possibly only double with a pragma
defined, bu... | python | {
"resource": ""
} |
q10473 | CLEnvironmentFactory.all_devices | train | def all_devices(cl_device_type=None, platform=None):
"""Get multiple device environments, optionally only of the indicated type.
This will only fetch devices that support double point precision.
Args:
cl_device_type (cl.device_type.* or string): The type of the device we want,
... | python | {
"resource": ""
} |
q10474 | CLEnvironmentFactory.smart_device_selection | train | def smart_device_selection(preferred_device_type=None):
"""Get a list of device environments that is suitable for use in MOT.
Basically this gets the total list of devices using all_devices() and applies a filter on it.
This filter does the following:
1) if the 'AMD Accelerated Par... | python | {
"resource": ""
} |
q10475 | multivariate_ess | train | def multivariate_ess(samples, batch_size_generator=None):
r"""Estimate the multivariate Effective Sample Size for the samples of every problem.
This essentially applies :func:`estimate_multivariate_ess` to every problem.
Args:
samples (ndarray, dict or generator): either a matrix of shape (d, p, n... | python | {
"resource": ""
} |
q10476 | univariate_ess | train | def univariate_ess(samples, method='standard_error', **kwargs):
r"""Estimate the univariate Effective Sample Size for the samples of every problem.
This computes the ESS using:
.. math::
ESS(X) = n * \frac{\lambda^{2}}{\sigma^{2}}
Where :math:`\lambda` is the standard deviation o... | python | {
"resource": ""
} |
q10477 | _get_sample_generator | train | def _get_sample_generator(samples):
"""Get a sample generator from the given polymorphic input.
Args:
samples (ndarray, dict or generator): either an matrix of shape (d, p, n) with d problems, p parameters and
n samples, or a dictionary with for every parameter a matrix with shape (d, n) or... | python | {
"resource": ""
} |
q10478 | estimate_univariate_ess_standard_error | train | def estimate_univariate_ess_standard_error(chain, batch_size_generator=None, compute_method=None):
r"""Compute the univariate ESS using the standard error method.
This computes the ESS using:
.. math::
ESS(X) = n * \frac{\lambda^{2}}{\sigma^{2}}
Where :math:`\lambda` is the standard deviatio... | python | {
"resource": ""
} |
q10479 | minimum_multivariate_ess | train | def minimum_multivariate_ess(nmr_params, alpha=0.05, epsilon=0.05):
r"""Calculate the minimum multivariate Effective Sample Size you will need to obtain the desired precision.
This implements the inequality from Vats et al. (2016):
.. math::
\widehat{ESS} \geq \frac{2^{2/p}\pi}{(p\Gamma(p/2))^{2/... | python | {
"resource": ""
} |
q10480 | multivariate_ess_precision | train | def multivariate_ess_precision(nmr_params, multi_variate_ess, alpha=0.05):
r"""Calculate the precision given your multivariate Effective Sample Size.
Given that you obtained :math:`ESS` multivariate effective samples in your estimate you can calculate the
precision with which you approximated your desired ... | python | {
"resource": ""
} |
q10481 | estimate_multivariate_ess_sigma | train | def estimate_multivariate_ess_sigma(samples, batch_size):
r"""Calculates the Sigma matrix which is part of the multivariate ESS calculation.
This implementation is based on the Matlab implementation found at: https://github.com/lacerbi/multiESS
The Sigma matrix is defined as:
.. math::
\Sigm... | python | {
"resource": ""
} |
q10482 | monte_carlo_standard_error | train | def monte_carlo_standard_error(chain, batch_size_generator=None, compute_method=None):
"""Compute Monte Carlo standard errors for the expectations
This is a convenience function that calls the compute method for each batch size and returns the lowest ESS
over the used batch sizes.
Args:
chain ... | python | {
"resource": ""
} |
q10483 | fit_gaussian | train | def fit_gaussian(samples, ddof=0):
"""Calculates the mean and the standard deviation of the given samples.
Args:
samples (ndarray): a one or two dimensional array. If one dimensional we calculate the fit using all
values. If two dimensional, we fit the Gaussian for every set of samples over... | python | {
"resource": ""
} |
q10484 | fit_circular_gaussian | train | def fit_circular_gaussian(samples, high=np.pi, low=0):
"""Compute the circular mean for samples in a range
Args:
samples (ndarray): a one or two dimensional array. If one dimensional we calculate the fit using all
values. If two dimensional, we fit the Gaussian for every set of samples over... | python | {
"resource": ""
} |
q10485 | fit_truncated_gaussian | train | def fit_truncated_gaussian(samples, lower_bounds, upper_bounds):
"""Fits a truncated gaussian distribution on the given samples.
This will do a maximum likelihood estimation of a truncated Gaussian on the provided samples, with the
truncation points given by the lower and upper bounds.
Args:
s... | python | {
"resource": ""
} |
q10486 | gaussian_overlapping_coefficient | train | def gaussian_overlapping_coefficient(means_0, stds_0, means_1, stds_1, lower=None, upper=None):
"""Compute the overlapping coefficient of two Gaussian continuous_distributions.
This computes the :math:`\int_{-\infty}^{\infty}{\min(f(x), g(x))\partial x}` where
:math:`f \sim \mathcal{N}(\mu_0, \sigma_0^{2})... | python | {
"resource": ""
} |
q10487 | _TruncatedNormalFitter.truncated_normal_log_likelihood | train | def truncated_normal_log_likelihood(params, low, high, data):
"""Calculate the log likelihood of the truncated normal distribution.
Args:
params: tuple with (mean, std), the parameters under which we evaluate the model
low (float): the lower truncation bound
high (fl... | python | {
"resource": ""
} |
q10488 | _TruncatedNormalFitter.truncated_normal_ll_gradient | train | def truncated_normal_ll_gradient(params, low, high, data):
"""Return the gradient of the log likelihood of the truncated normal at the given position.
Args:
params: tuple with (mean, std), the parameters under which we evaluate the model
low (float): the lower truncation bound
... | python | {
"resource": ""
} |
q10489 | _TruncatedNormalFitter.partial_derivative_mu | train | def partial_derivative_mu(mu, sigma, low, high, data):
"""The partial derivative with respect to the mean.
Args:
mu (float): the mean of the truncated normal
sigma (float): the std of the truncated normal
low (float): the lower truncation bound
high (floa... | python | {
"resource": ""
} |
q10490 | _TruncatedNormalFitter.partial_derivative_sigma | train | def partial_derivative_sigma(mu, sigma, low, high, data):
"""The partial derivative with respect to the standard deviation.
Args:
mu (float): the mean of the truncated normal
sigma (float): the std of the truncated normal
low (float): the lower truncation bound
... | python | {
"resource": ""
} |
q10491 | minimize | train | def minimize(func, x0, data=None, method=None, lower_bounds=None, upper_bounds=None, constraints_func=None,
nmr_observations=None, cl_runtime_info=None, options=None):
"""Minimization of one or more variables.
For an easy wrapper of function maximization, see :func:`maximize`.
All boundary co... | python | {
"resource": ""
} |
q10492 | _bounds_to_array | train | def _bounds_to_array(bounds):
"""Create a CompositeArray to hold the bounds."""
elements = []
for value in bounds:
if all_elements_equal(value):
elements.append(Scalar(get_single_value(value), ctype='mot_float_type'))
else:
elements.append(Array(value, ctype='mot_floa... | python | {
"resource": ""
} |
q10493 | get_minimizer_options | train | def get_minimizer_options(method):
"""Return a dictionary with the default options for the given minimization method.
Args:
method (str): the name of the method we want the options off
Returns:
dict: a dictionary with the default options
"""
if method == 'Powell':
return {'... | python | {
"resource": ""
} |
q10494 | _clean_options | train | def _clean_options(method, provided_options):
"""Clean the given input options.
This will make sure that all options are present, either with their default values or with the given values,
and that no other options are present then those supported.
Args:
method (str): the method name
p... | python | {
"resource": ""
} |
q10495 | validate_schema | train | def validate_schema(yaml_def, branch=False):
"""Validates the schema of a dict
Parameters
----------
yaml_def : dict
dict whose schema shall be validated
branch : bool
Indicates whether `yaml_def` is a dict of a top-level lane, or of a branch
inside a lane (needed for recurs... | python | {
"resource": ""
} |
q10496 | arg_spec | train | def arg_spec(cls, mtd_name):
"""Cross-version argument signature inspection
Parameters
----------
cls : class
mtd_name : str
Name of the method to be inspected
Returns
-------
required_params : list of str
List of required, positional parameters
optional_params : li... | python | {
"resource": ""
} |
q10497 | AbstractSampler.sample | train | def sample(self, nmr_samples, burnin=0, thinning=1):
"""Take additional samples from the given likelihood and prior, using this sampler.
This method can be called multiple times in which the sample state is stored in between.
Args:
nmr_samples (int): the number of samples to return... | python | {
"resource": ""
} |
q10498 | AbstractSampler._sample | train | def _sample(self, nmr_samples, thinning=1, return_output=True):
"""Sample the given number of samples with the given thinning.
If ``return_output`` we will return the samples, log likelihoods and log priors. If not, we will advance the
state of the sampler without returning storing the samples.... | python | {
"resource": ""
} |
q10499 | AbstractSampler._get_kernel_data | train | def _get_kernel_data(self, nmr_samples, thinning, return_output):
"""Get the kernel data we will input to the MCMC sampler.
This sets the items:
* data: the pointer to the user provided data
* method_data: the data specific to the MCMC method
* nmr_iterations: the number of ite... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.