Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def on_assign(self, node): # ('targets', 'value')
val = self.run(node.value)
for tnode in node.targets:
self.node_assign(tnode, val)
return | [
"Simple assignment."
] |
Please provide a description of the function:def on_augassign(self, node): # ('target', 'op', 'value')
return self.on_assign(ast.Assign(targets=[node.target],
value=ast.BinOp(left=node.target,
op=node.o... | [
"Augmented assign."
] |
Please provide a description of the function:def on_slice(self, node): # ():('lower', 'upper', 'step')
return slice(self.run(node.lower),
self.run(node.upper),
self.run(node.step)) | [
"Simple slice."
] |
Please provide a description of the function:def on_extslice(self, node): # ():('dims',)
return tuple([self.run(tnode) for tnode in node.dims]) | [
"Extended slice."
] |
Please provide a description of the function:def on_subscript(self, node): # ('value', 'slice', 'ctx')
val = self.run(node.value)
nslice = self.run(node.slice)
ctx = node.ctx.__class__
if ctx in (ast.Load, ast.Store):
if isinstance(node.slice, (ast.Index, ast.Slic... | [
"Subscript handling -- one of the tricky parts."
] |
Please provide a description of the function:def on_delete(self, node): # ('targets',)
for tnode in node.targets:
if tnode.ctx.__class__ != ast.Del:
break
children = []
while tnode.__class__ == ast.Attribute:
children.append(tnode.a... | [
"Delete statement."
] |
Please provide a description of the function:def on_unaryop(self, node): # ('op', 'operand')
return op2func(node.op)(self.run(node.operand)) | [
"Unary operator."
] |
Please provide a description of the function:def on_binop(self, node): # ('left', 'op', 'right')
return op2func(node.op)(self.run(node.left),
self.run(node.right)) | [
"Binary operator."
] |
Please provide a description of the function:def on_boolop(self, node): # ('op', 'values')
val = self.run(node.values[0])
is_and = ast.And == node.op.__class__
if (is_and and val) or (not is_and and not val):
for n in node.values[1:]:
val = op2func(node.op... | [
"Boolean operator."
] |
Please provide a description of the function:def on_compare(self, node): # ('left', 'ops', 'comparators')
lval = self.run(node.left)
out = True
for op, rnode in zip(node.ops, node.comparators):
rval = self.run(rnode)
out = op2func(op)(lval, rval)
lva... | [
"comparison operators"
] |
Please provide a description of the function:def on_print(self, node): # ('dest', 'values', 'nl')
dest = self.run(node.dest) or self.writer
end = ''
if node.nl:
end = '\n'
out = [self.run(tnode) for tnode in node.values]
if out and len(self.error) == 0:
... | [
"Note: implements Python2 style print statement, not print()\n function.\n\n May need improvement....\n\n "
] |
Please provide a description of the function:def _printer(self, *out, **kws):
flush = kws.pop('flush', True)
fileh = kws.pop('file', self.writer)
sep = kws.pop('sep', ' ')
end = kws.pop('sep', '\n')
print(*out, file=fileh, sep=sep, end=end)
if flush:
... | [
"Generic print function."
] |
Please provide a description of the function:def on_if(self, node): # ('test', 'body', 'orelse')
block = node.body
if not self.run(node.test):
block = node.orelse
for tnode in block:
self.run(tnode) | [
"Regular if-then-else statement."
] |
Please provide a description of the function:def on_ifexp(self, node): # ('test', 'body', 'orelse')
expr = node.orelse
if self.run(node.test):
expr = node.body
return self.run(expr) | [
"If expressions."
] |
Please provide a description of the function:def on_while(self, node): # ('test', 'body', 'orelse')
while self.run(node.test):
self._interrupt = None
for tnode in node.body:
self.run(tnode)
if self._interrupt is not None:
br... | [
"While blocks."
] |
Please provide a description of the function:def on_for(self, node): # ('target', 'iter', 'body', 'orelse')
for val in self.run(node.iter):
self.node_assign(node.target, val)
self._interrupt = None
for tnode in node.body:
self.run(tnode)
... | [
"For blocks."
] |
Please provide a description of the function:def on_listcomp(self, node): # ('elt', 'generators')
out = []
for tnode in node.generators:
if tnode.__class__ == ast.comprehension:
for val in self.run(tnode.iter):
self.node_assign(tnode.target, va... | [
"List comprehension."
] |
Please provide a description of the function:def on_excepthandler(self, node): # ('type', 'name', 'body')
return (self.run(node.type), node.name, node.body) | [
"Exception handler..."
] |
Please provide a description of the function:def on_try(self, node): # ('body', 'handlers', 'orelse', 'finalbody')
no_errors = True
for tnode in node.body:
self.run(tnode, with_raise=False)
no_errors = no_errors and len(self.error) == 0
if len(self.error) ... | [
"Try/except/else/finally blocks."
] |
Please provide a description of the function:def on_raise(self, node): # ('type', 'inst', 'tback')
if version_info[0] == 3:
excnode = node.exc
msgnode = node.cause
else:
excnode = node.type
msgnode = node.inst
out = self.run(excnode)
... | [
"Raise statement: note difference for python 2 and 3."
] |
Please provide a description of the function:def on_call(self, node):
# ('func', 'args', 'keywords'. Py<3.5 has 'starargs' and 'kwargs' too)
func = self.run(node.func)
if not hasattr(func, '__call__') and not isinstance(func, type):
msg = "'%s' is not callable!!" % (func)
... | [
"Function execution."
] |
Please provide a description of the function:def on_functiondef(self, node):
# ('name', 'args', 'body', 'decorator_list')
if node.decorator_list:
raise Warning("decorated procedures not supported!")
kwargs = []
if not valid_symbol_name(node.name) or node.name in sel... | [
"Define procedures."
] |
Please provide a description of the function:def _open(filename, mode='r', buffering=0):
if mode not in ('r', 'rb', 'rU'):
raise RuntimeError("Invalid open file mode, must be 'r', 'rb', or 'rU'")
if buffering > MAX_OPEN_BUFFER:
raise RuntimeError("Invalid buffering value, max buffer size is... | [
"read only version of open()"
] |
Please provide a description of the function:def safe_pow(base, exp):
if exp > MAX_EXPONENT:
raise RuntimeError("Invalid exponent, max exponent is {}".format(MAX_EXPONENT))
return base ** exp | [
"safe version of pow"
] |
Please provide a description of the function:def safe_mult(a, b):
if isinstance(a, str) and isinstance(b, int) and len(a) * b > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a * b | [
"safe version of multiply"
] |
Please provide a description of the function:def safe_add(a, b):
if isinstance(a, str) and isinstance(b, str) and len(a) + len(b) > MAX_STR_LEN:
raise RuntimeError("String length exceeded, max string length is {}".format(MAX_STR_LEN))
return a + b | [
"safe version of add"
] |
Please provide a description of the function:def safe_lshift(a, b):
if b > MAX_SHIFT:
raise RuntimeError("Invalid left shift, max left shift is {}".format(MAX_SHIFT))
return a << b | [
"safe version of lshift"
] |
Please provide a description of the function:def valid_symbol_name(name):
if name in RESERVED_WORDS:
return False
gen = generate_tokens(io.BytesIO(name.encode('utf-8')).readline)
typ, _, start, end, _ = next(gen)
if typ == tk_ENCODING:
typ, _, start, end, _ = next(gen)
return t... | [
"Determine whether the input symbol name is a valid name.\n\n Arguments\n ---------\n name : str\n name to check for validity.\n\n Returns\n --------\n valid : bool\n whether name is a a valid symbol name\n\n This checks for Python reserved words and that the name matches\n... |
Please provide a description of the function:def make_symbol_table(use_numpy=True, **kws):
symtable = {}
for sym in FROM_PY:
if sym in builtins:
symtable[sym] = builtins[sym]
for sym in FROM_MATH:
if hasattr(math, sym):
symtable[sym] = getattr(math, sym)
i... | [
"Create a default symboltable, taking dict of user-defined symbols.\n\n Arguments\n ---------\n numpy : bool, optional\n whether to include symbols from numpy\n kws : optional\n additional symbol name, value pairs to include in symbol table\n\n Returns\n --------\n symbol_table : d... |
Please provide a description of the function:def get_error(self):
col_offset = -1
if self.node is not None:
try:
col_offset = self.node.col_offset
except AttributeError:
pass
try:
exc_name = self.exc.__name__
ex... | [
"Retrieve error data."
] |
Please provide a description of the function:def generic_visit(self, node):
if node.__class__.__name__ == 'Name':
if node.ctx.__class__ == ast.Load and node.id not in self.names:
self.names.append(node.id)
ast.NodeVisitor.generic_visit(self, node) | [
"TODO: docstring in public method."
] |
Please provide a description of the function:def _get_env(self, key):
if self._env_key_replacer is not None:
key = key.replace(*self._env_key_replacer)
return os.getenv(key) | [
"Wrapper around os.getenv() which replaces characters\n in the original key. This allows env vars which have different keys\n than the config object keys.\n "
] |
Please provide a description of the function:def add_config_path(self, path):
abspath = util.abs_pathify(path)
if abspath not in self._config_paths:
log.info("Adding {0} to paths to search".format(abspath))
self._config_paths.append(abspath) | [
"Add a path for Vyper to search for the config file in.\n Can be called multiple times to define multiple search paths.\n "
] |
Please provide a description of the function:def add_remote_provider(self, provider, client, path):
if provider not in constants.SUPPORTED_REMOTE_PROVIDERS:
raise errors.UnsupportedRemoteProviderError(provider)
host = ""
if provider == "etcd":
host = "{0}://{1}:... | [
"Adds a remote configuration source.\n Remote Providers are searched in the order they are added.\n provider is a string value, \"etcd\", \"consul\" and \"zookeeper\" are\n currently supported.\n client is a client object\n path is the path in the k/v store to retrieve configurati... |
Please provide a description of the function:def get(self, key):
path = key.split(self._key_delimiter)
lowercase_key = key.lower()
val = self._find(lowercase_key)
if val is None:
source = self._find(path[0].lower())
if source is not None and isinstance(... | [
"Vyper is essentially repository for configurations.\n `get` can retrieve any value given the key to use.\n `get` has the behavior of returning the value associated with the first\n place from where it is set. Viper will check in the following order:\n override, arg, env, config file, ke... |
Please provide a description of the function:def sub(self, key):
subv = Vyper()
data = self.get(key)
if isinstance(data, dict):
subv._config = data
return subv
else:
return None | [
"Returns new Vyper instance representing a sub tree of this instance.\n "
] |
Please provide a description of the function:def unmarshall_key(self, key, cls):
return setattr(cls, key, self.get(key)) | [
"Takes a single key and unmarshalls it into a class."
] |
Please provide a description of the function:def unmarshall(self, cls):
for k, v in self.all_settings().items():
setattr(cls, k, v)
return cls | [
"Unmarshalls the config into a class. Make sure that the tags on\n the attributes of the class are properly set.\n "
] |
Please provide a description of the function:def bind_env(self, *input_):
if len(input_) == 0:
return "bind_env missing key to bind to"
key = input_[0].lower()
if len(input_) == 1:
env_key = self._merge_with_env_prefix(key)
else:
env_key = i... | [
"Binds a Vyper key to a ENV variable.\n ENV variables are case sensitive.\n If only a key is provided, it will use the env key matching the key,\n uppercased.\n `env_prefix` will be used when set when env name is not provided.\n "
] |
Please provide a description of the function:def _find(self, key):
key = self._real_key(key)
# OVERRIDES
val = self._override.get(key)
if val is not None:
log.debug("{0} found in override: {1}".format(key, val))
return val
# ARGS
val = s... | [
"Given a key, find the value\n Vyper will check in the following order:\n override, arg, env, config file, key/value store, default\n Vyper will check to see if an alias exists first.\n "
] |
Please provide a description of the function:def is_set(self, key):
path = key.split(self._key_delimiter)
lower_case_key = key.lower()
val = self._find(lower_case_key)
if val is None:
source = self._find(path[0].lower())
if source is not None and isinst... | [
"Check to see if the key has been set in any of the data locations.\n "
] |
Please provide a description of the function:def register_alias(self, alias, key):
alias = alias.lower()
key = key.lower()
if alias != key and alias != self._real_key(key):
exists = self._aliases.get(alias)
if exists is None:
# if we alias someth... | [
"Aliases provide another accessor for the same key.\n This enables one to change a name without breaking the application.\n "
] |
Please provide a description of the function:def in_config(self, key):
# if the requested key is an alias, then return the proper key
key = self._real_key(key)
exists = self._config.get(key)
return exists | [
"Check to see if the given key (or an alias) is in the config file.\n "
] |
Please provide a description of the function:def set_default(self, key, value):
k = self._real_key(key.lower())
self._defaults[k] = value | [
"Set the default value for this key.\n Default only used when no value is provided by the user via\n arg, config or env.\n "
] |
Please provide a description of the function:def set(self, key, value):
k = self._real_key(key.lower())
self._override[k] = value | [
"Sets the value for the key in the override register.\n Will be used instead of values obtained via\n args, config file, env, defaults or key/value store.\n "
] |
Please provide a description of the function:def read_in_config(self):
log.info("Attempting to read in config file")
if self._get_config_type() not in constants.SUPPORTED_EXTENSIONS:
raise errors.UnsupportedConfigError(self._get_config_type())
with open(self._get_config_fil... | [
"Vyper will discover and load the configuration file from disk\n and key/value stores, searching in one of the defined paths.\n "
] |
Please provide a description of the function:def _unmarshall_reader(self, file_, d):
return util.unmarshall_config_reader(file_, d, self._get_config_type()) | [
"Unmarshall a file into a `dict`."
] |
Please provide a description of the function:def _get_key_value_config(self):
for rp in self._remote_providers:
val = self._get_remote_config(rp)
self._kvstore = val
return None
raise errors.RemoteConfigError("No Files Found") | [
"Retrieves the first found remote configuration."
] |
Please provide a description of the function:def all_keys(self, uppercase_keys=False):
d = {}
for k in self._override.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._args.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
... | [
"Return all keys regardless where they are set."
] |
Please provide a description of the function:def all_settings(self, uppercase_keys=False):
d = {}
for k in self.all_keys(uppercase_keys):
d[k] = self.get(k)
return d | [
"Return all settings as a `dict`."
] |
Please provide a description of the function:def _find_config_file(self):
log.info("Searching for config in: {0}".format(
", ".join(str(p) for p in self._config_paths)))
for cp in self._config_paths:
f = self._search_in_path(cp)
if f != "":
r... | [
"Search all `config_paths` for any config file.\n Returns the first path that exists (and is a config file).\n "
] |
Please provide a description of the function:def debug(self): # pragma: no cover
print("Aliases:")
pprint.pprint(self._aliases)
print("Override:")
pprint.pprint(self._override)
print("Args:")
pprint.pprint(self._args)
print("Env:")
pprint.pprint... | [
"Prints all configuration registries for debugging purposes."
] |
Please provide a description of the function:def server(**kwargs):
start_server(**{k: v for k, v in kwargs.items() if v},
blocking=True) | [
"\n Starts the Clearly Server.\n\n BROKER: The broker being used by celery, like \"amqp://localhost\".\n "
] |
Please provide a description of the function:def start_server(broker, backend=None, port=12223,
max_tasks=10000, max_workers=100,
blocking=False, debug=False): # pragma: no cover
_setup_logging(debug)
queue_listener_dispatcher = Queue()
listener = EventListener(broke... | [
"Starts a Clearly Server programmatically."
] |
Please provide a description of the function:def _event_to_pb(event):
if isinstance(event, (TaskData, Task)):
key, klass = 'task', clearly_pb2.TaskMessage
elif isinstance(event, (WorkerData, Worker)):
key, klass = 'worker', clearly_pb2.WorkerMessage
else:
... | [
"Supports converting internal TaskData and WorkerData, as well as\n celery Task and Worker to proto buffers messages.\n\n Args:\n event (Union[TaskData|Task|WorkerData|Worker]):\n\n Returns:\n ProtoBuf object\n\n "
] |
Please provide a description of the function:def filter_tasks(self, request, context):
_log_request(request, context)
tasks_pattern, tasks_negate = PATTERN_PARAMS_OP(request.tasks_filter)
state_pattern = request.state_pattern
limit, reverse = request.limit, request.reverse
... | [
"Filter tasks by matching patterns to name, routing key and state."
] |
Please provide a description of the function:def filter_workers(self, request, context):
_log_request(request, context)
workers_pattern, workers_negate = PATTERN_PARAMS_OP(request.workers_filter)
hregex = re.compile(workers_pattern) # hostname filter condition
def hcondition(... | [
"Filter workers by matching a pattern to hostname."
] |
Please provide a description of the function:def find_task(self, request, context):
_log_request(request, context)
task = self.listener.memory.tasks.get(request.task_uuid)
if not task:
return clearly_pb2.TaskMessage()
return ClearlyServer._event_to_pb(task)[1] | [
"Finds one specific task."
] |
Please provide a description of the function:def seen_tasks(self, request, context):
_log_request(request, context)
result = clearly_pb2.SeenTasksMessage()
result.task_types.extend(self.listener.memory.task_types())
return result | [
"Returns all seen task types."
] |
Please provide a description of the function:def reset_tasks(self, request, context):
_log_request(request, context)
self.listener.memory.clear_tasks()
return clearly_pb2.Empty() | [
"Resets all captured tasks."
] |
Please provide a description of the function:def get_stats(self, request, context):
_log_request(request, context)
m = self.listener.memory
return clearly_pb2.StatsMessage(
task_count=m.task_count,
event_count=m.event_count,
len_tasks=len(m.tasks),
... | [
"Returns the server statistics."
] |
Please provide a description of the function:def safe_compile_text(txt, raises=False):
def _convert(node):
if isinstance(node, ast.Tuple):
return tuple(map(_convert, node.elts))
if isinstance(node, ast.List):
return list(map(_convert, node.elts))
if isinstance... | [
"Based on actual ast.literal_eval, but this one supports 'calls', \n like in a repr of a datetime: `datetime.datetime(2017, 5, 20)`.\n \n Clearly uses this to generate actual python objects of the params and \n results of the tasks, to be able to apply the advanced syntax coloring\n scheme implemente... |
Please provide a description of the function:def accepts(regex, negate, *values):
return any(v and regex.search(v) for v in values) != negate | [
"Given a compiled regex and a negate, find if any of the values match.\n\n Args:\n regex (Pattern):\n negate (bool):\n *values (str):\n\n Returns:\n\n "
] |
Please provide a description of the function:def copy_update(pb_message, **kwds):
result = pb_message.__class__()
result.CopyFrom(pb_message)
for k, v in kwds.items():
setattr(result, k, v)
return result | [
"Returns a copy of the PB object, with some fields updated.\n\n Args:\n pb_message:\n **kwds:\n\n Returns:\n\n "
] |
Please provide a description of the function:def __start(self): # pragma: no cover
assert not self.dispatcher_thread
self.dispatcher_thread = threading.Thread(target=self.__run_dispatcher,
name='clearly-dispatcher')
self.dispatcher_th... | [
"Starts the real-time engine that captures tasks."
] |
Please provide a description of the function:def __stop(self): # pragma: no cover
if not self.dispatcher_thread:
return
logger.info('Stopping dispatcher')
self.running = False # graceful shutdown
self.dispatcher_thread.join()
self.dispatcher_thread = None | [
"Stops the background engine."
] |
Please provide a description of the function:def streaming_client(self, tasks_regex, tasks_negate, workers_regex, workers_negate):
cc = CapturingClient(Queue(),
re.compile(tasks_regex), tasks_negate,
re.compile(workers_regex), workers_negate)
... | [
"Connects a client to the streaming capture, filtering the events that are sent\n to it.\n\n Args:\n tasks_regex (str): a pattern to filter tasks to capture.\n ex.: '^dispatch|^email' to filter names starting with that\n or 'dispatch.*123456' to filter th... |
Please provide a description of the function:def immutable_task(task, state, pre_state, created):
# noinspection PyUnresolvedReferences,PyProtectedMember
return TaskData._make(chain(
(getattr(task, f) for f in TASK_OWN_FIELDS),
(state, pre_state, created),
)) | [
"Converts to an immutable slots class to handle internally."
] |
Please provide a description of the function:def immutable_worker(worker, state, pre_state, created):
# noinspection PyUnresolvedReferences,PyProtectedMember
return WorkerData._make(chain(
(getattr(worker, f) for f in WORKER_OWN_FIELDS),
(state, pre_state, created),
(worker.heartbea... | [
"Converts to an immutable slots class to handle internally."
] |
Please provide a description of the function:def __start(self): # pragma: no cover
assert not self._listener_thread
self._listener_thread = threading.Thread(target=self.__run_listener,
name='clearly-listener')
self._listener_thread.dae... | [
"Starts the real-time engine that captures events."
] |
Please provide a description of the function:def __stop(self): # pragma: no cover
if not self._listener_thread:
return
logger.info('Stopping listener')
self._celery_receiver.should_stop = True
self._listener_thread.join()
self._listener_thread = self._cele... | [
"Stops the background engine."
] |
Please provide a description of the function:def capture(self, pattern=None, negate=False, workers=None, negate_workers=False,
params=None, success=False, error=True, stats=False):
request = clearly_pb2.CaptureRequest(
tasks_capture=clearly_pb2.PatternFilter(pattern=pattern ... | [
"Starts capturing selected events in real-time. You can filter exactly what\n you want to see, as the Clearly Server handles all tasks and workers updates\n being sent to celery. Several clients can see different sets of events at the\n same time.\n\n This runs in the foreground, so you ... |
Please provide a description of the function:def stats(self):
stats = self._stub.get_stats(clearly_pb2.Empty())
print(Colors.DIM('Processed:'),
'\ttasks', Colors.RED(stats.task_count),
'\tevents', Colors.RED(stats.event_count))
print(Colors.DIM('Stored:'),
... | [
"Lists some metrics of the capturing system:\n\n Tasks processed: the total number of reentrant tasks processed,\n which includes retry attempts.\n Events processed: number of events captured and processed.\n Tasks stored: actual number of unique tasks processed.\n ... |
Please provide a description of the function:def tasks(self, pattern=None, negate=False, state=None, limit=None, reverse=True,
params=None, success=False, error=True):
request = clearly_pb2.FilterTasksRequest(
tasks_filter=clearly_pb2.PatternFilter(pattern=pattern or '.',
... | [
"Filters stored tasks and displays their current statuses.\n\n Note that, to be able to list the tasks sorted chronologically, celery retrieves\n tasks from the LRU event heap instead of the dict storage, so the total number\n of tasks fetched may be different than the server `max_tasks` settin... |
Please provide a description of the function:def workers(self, pattern=None, negate=False, stats=True):
request = clearly_pb2.FilterWorkersRequest(
workers_filter=clearly_pb2.PatternFilter(pattern=pattern or '.',
negate=negate),
)... | [
"Filters known workers and prints their current status.\n \n Args:\n Filter args:\n\n pattern (Optional[str]): a pattern to filter workers\n ex.: '^dispatch|^email' to filter names starting with that\n or 'dispatch.*123456' to filter that exact... |
Please provide a description of the function:def task(self, task_uuid):
request = clearly_pb2.FindTaskRequest(task_uuid=task_uuid)
task = self._stub.find_task(request)
if task.uuid:
ClearlyClient._display_task(task, True, True, True)
else:
print(EMPTY) | [
"Finds one specific task.\n\n Args:\n task_uuid (str): the task id\n "
] |
Please provide a description of the function:def seen_tasks(self):
print('\n'.join(self._stub.seen_tasks(clearly_pb2.Empty()).task_types)) | [
"Shows a list of seen task types."
] |
Please provide a description of the function:def detail_action(**kwargs):
def decorator(func):
func.action = True
func.detail = True
func.kwargs = kwargs
return func
return decorator | [
"\n Used to mark a method on a ResourceBinding that should be routed for detail actions.\n "
] |
Please provide a description of the function:def list_action(**kwargs):
def decorator(func):
func.action = True
func.detail = False
func.kwargs = kwargs
return func
return decorator | [
"\n Used to mark a method on a ResourceBinding that should be routed for list actions.\n "
] |
Please provide a description of the function:def broadcast_to(array, shape, subok=False):
return _broadcast_to(array, shape, subok=subok, readonly=True) | [
"Broadcast an array to a new shape.\n\n Parameters\n ----------\n array : array_like\n The array to broadcast.\n shape : tuple\n The shape of the desired array.\n subok : bool, optional\n If True, then sub-classes will be passed-through, otherwise\n the returned array will... |
Please provide a description of the function:def deltaW(N, m, h):
return np.random.normal(0.0, np.sqrt(h), (N, m)) | [
"Generate sequence of Wiener increments for m independent Wiener\n processes W_j(t) j=0..m-1 for each of N time intervals of length h. \n\n Returns:\n dW (array of shape (N, m)): The [n, j] element has the value\n W_j((n+1)*h) - W_j(n*h) \n "
] |
Please provide a description of the function:def _Aterm(N, h, m, k, dW):
sqrt2h = np.sqrt(2.0/h)
Xk = np.random.normal(0.0, 1.0, (N, m, 1))
Yk = np.random.normal(0.0, 1.0, (N, m, 1))
term1 = _dot(Xk, _t(Yk + sqrt2h*dW))
term2 = _dot(Yk + sqrt2h*dW, _t(Xk))
return (term1 - term2)/k | [
"kth term in the sum of Wiktorsson2001 equation (2.2)"
] |
Please provide a description of the function:def Ikpw(dW, h, n=5):
N = dW.shape[0]
m = dW.shape[1]
if dW.ndim < 3:
dW = dW.reshape((N, -1, 1)) # change to array of shape (N, m, 1)
if dW.shape[2] != 1 or dW.ndim > 3:
raise(ValueError)
A = _Aterm(N, h, m, 1, dW)
for k in range... | [
"matrix I approximating repeated Ito integrals for each of N time\n intervals, based on the method of Kloeden, Platen and Wright (1992).\n\n Args:\n dW (array of shape (N, m)): giving m independent Weiner increments for\n each time step N. (You can make this array using sdeint.deltaW())\n h (... |
Please provide a description of the function:def Jkpw(dW, h, n=5):
m = dW.shape[1]
A, I = Ikpw(dW, h, n)
J = I + 0.5*h*np.eye(m).reshape((1, m, m))
return (A, J) | [
"matrix J approximating repeated Stratonovich integrals for each of N\n time intervals, based on the method of Kloeden, Platen and Wright (1992).\n\n Args:\n dW (array of shape (N, m)): giving m independent Weiner increments for\n each time step N. (You can make this array using sdeint.deltaW())\n... |
Please provide a description of the function:def _vec(A):
N, m, n = A.shape
return A.reshape((N, m*n, 1), order='F') | [
"\n Linear operator _vec() from Wiktorsson2001 p478\n Args:\n A: a rank 3 array of shape N x m x n, giving a matrix A[j] for each\n interval of time j in 0..N-1\n Returns:\n array of shape N x mn x 1, made by stacking the columns of matrix A[j] on\n top of each other, for each j in 0..N... |
Please provide a description of the function:def _unvec(vecA, m=None):
N = vecA.shape[0]
if m is None:
m = np.sqrt(vecA.shape[1] + 0.25).astype(np.int64)
return vecA.reshape((N, m, -1), order='F') | [
"inverse of _vec() operator"
] |
Please provide a description of the function:def _kp(a, b):
if a.shape != b.shape or a.shape[-1] != 1:
raise(ValueError)
N = a.shape[0]
# take the outer product over the last two axes, then reshape:
return np.einsum('ijk,ilk->ijkl', a, b).reshape(N, -1, 1) | [
"Special case Kronecker tensor product of a[i] and b[i] at each\n time interval i for i = 0 .. N-1\n It is specialized for the case where both a and b are shape N x m x 1\n "
] |
Please provide a description of the function:def _kp2(A, B):
N = A.shape[0]
if B.shape[0] != N:
raise(ValueError)
newshape1 = A.shape[1]*B.shape[1]
return np.einsum('ijk,ilm->ijlkm', A, B).reshape(N, newshape1, -1) | [
"Special case Kronecker tensor product of A[i] and B[i] at each\n time interval i for i = 0 .. N-1\n Specialized for the case A and B rank 3 with A.shape[0]==B.shape[0]\n "
] |
Please provide a description of the function:def _K(m):
M = m*(m - 1)//2
K = np.zeros((M, m**2), dtype=np.int64)
row = 0
for j in range(1, m):
col = (j - 1)*m + j
s = m - j
K[row:(row+s), col:(col+s)] = np.eye(s)
row += s
return K | [
" matrix K_m from Wiktorsson2001 "
] |
Please provide a description of the function:def _AtildeTerm(N, h, m, k, dW, Km0, Pm0):
M = m*(m-1)//2
Xk = np.random.normal(0.0, 1.0, (N, m, 1))
Yk = np.random.normal(0.0, 1.0, (N, m, 1))
factor1 = np.dot(Km0, Pm0 - np.eye(m**2))
factor1 = broadcast_to(factor1, (N, M, m**2))
factor2 = _kp(... | [
"kth term in the sum for Atilde (Wiktorsson2001 p481, 1st eqn)"
] |
Please provide a description of the function:def _sigmainf(N, h, m, dW, Km0, Pm0):
M = m*(m-1)//2
Im = broadcast_to(np.eye(m), (N, m, m))
IM = broadcast_to(np.eye(M), (N, M, M))
Ims0 = np.eye(m**2)
factor1 = broadcast_to((2.0/h)*np.dot(Km0, Ims0 - Pm0), (N, M, m**2))
factor2 = _kp2(Im, _dot... | [
"Asymptotic covariance matrix \\Sigma_\\infty Wiktorsson2001 eqn (4.5)"
] |
Please provide a description of the function:def Iwik(dW, h, n=5):
N = dW.shape[0]
m = dW.shape[1]
if dW.ndim < 3:
dW = dW.reshape((N, -1, 1)) # change to array of shape (N, m, 1)
if dW.shape[2] != 1 or dW.ndim > 3:
raise(ValueError)
if m == 1:
return (np.zeros((N, 1, 1)... | [
"matrix I approximating repeated Ito integrals for each of N time\n intervals, using the method of Wiktorsson (2001).\n\n Args:\n dW (array of shape (N, m)): giving m independent Weiner increments for\n each time step N. (You can make this array using sdeint.deltaW())\n h (float): the time st... |
Please provide a description of the function:def Jwik(dW, h, n=5):
m = dW.shape[1]
Atilde, I = Iwik(dW, h, n)
J = I + 0.5*h*np.eye(m).reshape((1, m, m))
return (Atilde, J) | [
"matrix J approximating repeated Stratonovich integrals for each of N\n time intervals, using the method of Wiktorsson (2001).\n\n Args:\n dW (array of shape (N, m)): giving m independent Weiner increments for\n each time step N. (You can make this array using sdeint.deltaW())\n h (float): th... |
Please provide a description of the function:def _check_args(f, G, y0, tspan, dW=None, IJ=None):
if not np.isclose(min(np.diff(tspan)), max(np.diff(tspan))):
raise SDEValueError('Currently time steps must be equally spaced.')
# Be flexible to allow scalar equations. convert them to a 1D vector syst... | [
"Do some validation common to all algorithms. Find dimension d and number\n of Wiener processes m.\n ",
"y0 has length %d. So G must either be a single function\n returning a matrix of shape (%d, m), or else a list of m separate\n functions each returning a column of G, with shape ... |
Please provide a description of the function:def itoint(f, G, y0, tspan):
# In future versions we can automatically choose here the most suitable
# Ito algorithm based on properties of the system and noise.
(d, m, f, G, y0, tspan, __, __) = _check_args(f, G, y0, tspan, None, None)
chosenAlgorithm =... | [
" Numerically integrate the Ito equation dy = f(y,t)dt + G(y,t)dW\n\n where y is the d-dimensional state vector, f is a vector-valued function,\n G is an d x m matrix-valued function giving the noise coefficients and\n dW(t) = (dW_1, dW_2, ... dW_m) is a vector of independent Wiener increments\n\n Args... |
Please provide a description of the function:def stratint(f, G, y0, tspan):
# In future versions we can automatically choose here the most suitable
# Stratonovich algorithm based on properties of the system and noise.
(d, m, f, G, y0, tspan, __, __) = _check_args(f, G, y0, tspan, None, None)
chosen... | [
" Numerically integrate Stratonovich equation dy = f(y,t)dt + G(y,t).dW\n\n where y is the d-dimensional state vector, f is a vector-valued function,\n G is an d x m matrix-valued function giving the noise coefficients and\n dW(t) = (dW_1, dW_2, ... dW_m) is a vector of independent Wiener increments\n\n ... |
Please provide a description of the function:def itoEuler(f, G, y0, tspan, dW=None):
(d, m, f, G, y0, tspan, dW, __) = _check_args(f, G, y0, tspan, dW, None)
N = len(tspan)
h = (tspan[N-1] - tspan[0])/(N - 1)
# allocate space for result
y = np.zeros((N, d), dtype=type(y0[0]))
if dW is None:... | [
"Use the Euler-Maruyama algorithm to integrate the Ito equation\n dy = f(y,t)dt + G(y,t) dW(t)\n\n where y is the d-dimensional state vector, f is a vector-valued function,\n G is an d x m matrix-valued function giving the noise coefficients and\n dW(t) = (dW_1, dW_2, ... dW_m) is a vector of independen... |
Please provide a description of the function:def stratHeun(f, G, y0, tspan, dW=None):
(d, m, f, G, y0, tspan, dW, __) = _check_args(f, G, y0, tspan, dW, None)
N = len(tspan)
h = (tspan[N-1] - tspan[0])/(N - 1)
# allocate space for result
y = np.zeros((N, d), dtype=type(y0[0]))
if dW is None... | [
"Use the Stratonovich Heun algorithm to integrate Stratonovich equation\n dy = f(y,t)dt + G(y,t) \\circ dW(t)\n\n where y is the d-dimensional state vector, f is a vector-valued function,\n G is an d x m matrix-valued function giving the noise coefficients and\n dW(t) = (dW_1, dW_2, ... dW_m) is a vecto... |
Please provide a description of the function:def itoSRI2(f, G, y0, tspan, Imethod=Ikpw, dW=None, I=None):
return _Roessler2010_SRK2(f, G, y0, tspan, Imethod, dW, I) | [
"Use the Roessler2010 order 1.0 strong Stochastic Runge-Kutta algorithm\n SRI2 to integrate an Ito equation dy = f(y,t)dt + G(y,t)dW(t)\n\n where y is d-dimensional vector variable, f is a vector-valued function,\n G is a d x m matrix-valued function giving the noise coefficients and\n dW(t) is a vector... |
Please provide a description of the function:def stratSRS2(f, G, y0, tspan, Jmethod=Jkpw, dW=None, J=None):
return _Roessler2010_SRK2(f, G, y0, tspan, Jmethod, dW, J) | [
"Use the Roessler2010 order 1.0 strong Stochastic Runge-Kutta algorithm\n SRS2 to integrate a Stratonovich equation dy = f(y,t)dt + G(y,t)\\circ dW(t)\n\n where y is d-dimensional vector variable, f is a vector-valued function,\n G is a d x m matrix-valued function giving the noise coefficients and\n dW... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.