text stringlengths 81 112k |
|---|
Download file
def download_file(url):
"""Download file"""
response = requests.get(url, stream=True)
fp = tempfile.NamedTemporaryFile()
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
fp.write(chunk)
# log.info(f'Download file ... |
Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true.
def first_true(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
If no true value is found, r... |
Create hash Id from edge record
Args:
edge (Mapping[str, Any]): edge record to create hash from
Returns:
str: Murmur3 128 bit hash
def _create_hash_from_doc(doc: Mapping[str, Any]) -> str:
"""Create hash Id from edge record
Args:
edge (Mapping[str, Any]): edge record to creat... |
Return the current elapsed time since start
If the `elapsed` property is called in the context manager scope,
the elapsed time bewteen start and property access is returned.
However, if it is accessed outside of the context manager scope,
it returns the elapsed time bewteen entering and ... |
Load edges into Edgestore
def load_edges_into_db(
nanopub_id: str,
nanopub_url: str,
edges: list = [],
edges_coll_name: str = edges_coll_name,
nodes_coll_name: str = nodes_coll_name,
):
"""Load edges into Edgestore"""
start_time = datetime.datetime.now()
# Clean out edges for nanopub ... |
Yield documents from edge for loading into ArangoDB
def edge_iterator(edges=[], edges_fn=None):
"""Yield documents from edge for loading into ArangoDB"""
for edge in itertools.chain(edges, files.read_edges(edges_fn)):
subj = copy.deepcopy(edge["edge"]["subject"])
subj_id = str(utils._create_h... |
Add nanopubstore start_dt to belapi.state_mgmt collection
Args:
url: url of nanopubstore
start_dt: datetime of last query against nanopubstore for new ID's
def update_nanopubstore_start_dt(url: str, start_dt: str):
"""Add nanopubstore start_dt to belapi.state_mgmt collection
Args:
... |
Get last start_dt recorded for getting new nanopub ID's
def get_nanopubstore_start_dt(url: str):
"""Get last start_dt recorded for getting new nanopub ID's"""
hostname = urllib.parse.urlsplit(url)[1]
start_dates_doc = state_mgmt.get(start_dates_doc_key)
if start_dates_doc and start_dates_doc.get("sta... |
Get modified and deleted nanopub urls
Limited by last datetime retrieved (start_dt). Modified includes new and updated nanopubs
Returns:
dict: {'modified': [], 'deleted': []}
def get_nanopub_urls(ns_root_url: str = None, start_dt: str = None) -> dict:
"""Get modified and deleted nanopub urls
... |
Get Nanopub from nanopubstore given url
def get_nanopub(url):
"""Get Nanopub from nanopubstore given url"""
r = bel.utils.get_url(url, cache=False)
if r and r.json():
return r.json()
else:
return {} |
BEL Pipeline - BEL Nanopubs into BEL Edges
This will process BEL Nanopubs into BEL Edges by validating, orthologizing (if requested),
canonicalizing, and then computing the BEL Edges based on the given rule_set.
\b
input_fn:
If input fn has *.gz, will read as a gzip file
If input fn ha... |
Validate nanopubs
def nanopub_validate(ctx, input_fn, output_fn, api, config_fn):
"""Validate nanopubs"""
if config_fn:
config = bel.db.Config.merge_config(ctx.config, override_config_fn=config_fn)
else:
config = ctx.config
api = utils.first_true(
[api, config["bel_api"]["serv... |
Convert belscript to nanopubs_bel format
This will convert the OpenBEL BELScript file format to
nanopub_bel-1.0.0 format.
\b
input_fn:
If input fn has *.gz, will read as a gzip file
\b
output_fn:
If output fn has *.gz, will written as a gzip file
If output fn has *.jso... |
Reformat between JSON, YAML, JSONLines formats
\b
input_fn:
If input fn has *.gz, will read as a gzip file
\b
output_fn:
If output fn has *.gz, will written as a gzip file
If output fn has *.jsonl*, will written as a JSONLines file
IF output fn has *.json*, will be writ... |
Collect statistics on nanopub file
input_fn can be json, jsonl or yaml and additionally gzipped
def nanopub_stats(ctx, input_fn):
"""Collect statistics on nanopub file
input_fn can be json, jsonl or yaml and additionally gzipped
"""
counts = {
"nanopubs": 0,
"assertions": {"total... |
Canonicalize statement
Target namespaces can be provided in the following manner:
bel stmt canonicalize "<BELStmt>" --namespace_targets '{"HGNC": ["EG", "SP"], "CHEMBL": ["CHEBI"]}'
the value of target_namespaces must be JSON and embedded in single quotes
reserving double quotes fo... |
Create BEL Edges from BEL Statement
def edges(ctx, statement, rules, species, namespace_targets, version, api, config_fn):
"""Create BEL Edges from BEL Statement"""
if config_fn:
config = bel.db.Config.merge_config(ctx.config, override_config_fn=config_fn)
else:
config = ctx.config
# ... |
Setup Elasticsearch namespace indexes
This will by default only create the indexes and run the namespace index mapping
if the indexes don't exist. The --delete option will force removal of the
index if it exists.
The index_name should be aliased to the index 'terms' when it's ready
def elasticsearch... |
Setup ArangoDB database
db_name: Either 'belns' or 'edgestore' - must be one or the other
This will create the database, collections and indexes on the collection if it doesn't exist.
The --delete option will force removal of the database if it exists.
def arangodb(delete, db_name):
"""Setup ArangoD... |
Validate nanopub against jsonschema for nanopub
Args:
nanopub (Mapping[str, Any]): nanopub dict
schema (Mapping[str, Any]): nanopub schema
Returns:
Tuple[bool, List[str]]:
bool: Is valid? Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if... |
Create CityHash64 from nanopub for duplicate check
TODO - check that this hash value is consistent between C# and Python running on
laptop and server
Build string to hash
Collect flat array of (all values.strip()):
nanopub.type.name
nanopub.type.version
One of:
na... |
Validates using the nanopub schema
Args:
nanopub (Mapping[str, Any]): nanopub dict
Returns:
Tuple[bool, List[Tuple[str, str]]]:
bool: Is valid? Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if valid, tuple is ('ERROR|WAR... |
Validate context
Args:
context (Mapping[str, Any]): context dictionary of type, id and label
Returns:
Tuple[bool, List[Tuple[str, str]]]:
bool: Is valid? Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if valid, tuple is (... |
Create BEL Edges from BEL nanopub
Args:
nanopub (Mapping[str, Any]): bel nanopub
namespace_targets (Mapping[str, List[str]]): what namespaces to canonicalize
rules (List[str]): which computed edge rules to process, default is all,
look at BEL Specification yam... |
parse command line options and run commands.
def main_hrun():
""" parse command line options and run commands."""
parser = argparse.ArgumentParser(description="Tools for http(s) test. Base on rtsf.")
parser.add_argument(
'--log-level', default='INFO',
help="Specify ... |
Return path to .pyd after successful build command.
:return: Path to .pyd file or None.
def find_pyd_file():
"""
Return path to .pyd after successful build command.
:return: Path to .pyd file or None.
"""
if not os.path.isdir("./build"):
raise NotADirectoryError
for path, dirs, fi... |
Dereference the FFI result to a list of coordinates
def _void_array_to_nested_list(res, _func, _args):
""" Dereference the FFI result to a list of coordinates """
try:
shape = res.coords.len, 2
ptr = cast(res.coords.data, POINTER(c_double))
array = np.ctypeslib.as_array(ptr, shape)
... |
Parse file extension.
- *.json: uncompressed, utf-8 encode json file
- *.gz: compressed, utf-8 encode json file
def is_json_file(abspath):
"""Parse file extension.
- *.json: uncompressed, utf-8 encode json file
- *.gz: compressed, utf-8 encode json file
"""
abspath = abspath.lower()
f... |
Convert file extension to lowercase.
def lower_ext(abspath):
"""Convert file extension to lowercase.
"""
fname, ext = os.path.splitext(abspath)
return fname + ext.lower() |
Load Json from file. If file are not exists, returns ``default``.
:param abspath: file path. use absolute path as much as you can.
extension has to be ``.json`` or ``.gz`` (for compressed Json).
:type abspath: string
:param default: default ``dict()``, if ``abspath`` not exists, return the
... |
Dump Json serializable object to file.
Provides multiple choice to customize the behavior.
:param data: Serializable python object.
:type data: dict or list
:param abspath: ``save as`` path, file extension has to be ``.json`` or ``.gz``
(for compressed Json)
:type abspath: string
:par... |
A stable version of :func:`dump`, this method will silently overwrite
existing file.
There's a issue with :func:`dump`: If your program is interrupted while
writing, you got an incomplete file, and you also lose the original file.
So this method write json to a temporary file first, then rename to wh... |
Return json string in pretty format.
**中文文档**
将字典转化成格式化后的字符串。
def pretty_dumps(data):
"""Return json string in pretty format.
**中文文档**
将字典转化成格式化后的字符串。
"""
try:
return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=False)
except:
return json.dumps(data, sort_... |
Compute left and right padding values.
Here we use the convention that if the padding
size is odd, we pad the odd part to the right
and the even part to the left.
Parameters
----------
small : int
Old size of original 1D array
large : int
New size off padded 1D array
R... |
Perform linear padding for complex array
The input array `av` is padded with a linear ramp starting at the
edges and going outwards to an average value computed from a band
of thickness `stlen` at the outer boundary of the array.
Pads will only be appended, not prepended to the array.
If the inpu... |
2D component of `pad_add`
def _pad_add_1d(av, size, stlen):
""" 2D component of `pad_add`
"""
assert len(size) == 1
padx = _get_pad_left_right(av.shape[0], size[0])
mask = np.zeros(av.shape, dtype=bool)
mask[stlen:-stlen] = True
border = av[~mask]
if av.dtype.name.count("complex"):
... |
Removes linear padding from array
This is a convenience function that does the opposite
of `pad_add`.
Parameters
----------
pv : 1D or 2D ndarray
The array from which the padding will be removed.
size : tuple of length 1 (1D) or 2 (2D), optional
The final size of the un-padded ... |
Simple rate limit function using redis
def rate_limit(self):
"""
Simple rate limit function using redis
"""
rate_limited_msg = False
while True:
is_rate_limited = self.limit.is_rate_limited(uuid)
if is_rate_limited:
time.sleep(0.3) # sav... |
Sends a file to virus total for assessment
def scan_file(self, filename, apikey):
"""
Sends a file to virus total for assessment
"""
url = self.base_url + "file/scan"
params = {'apikey': apikey}
scanfile = {"file": open(filename, 'rb')}
response = requests.post(u... |
just send the hash, check the date
def rescan_file(self, filename, sha256hash, apikey):
"""
just send the hash, check the date
"""
url = self.base_url + "file/rescan"
params = {
'apikey': apikey,
'resource': sha256hash
}
rate_limit_clear ... |
retrieve report from file scan
def binary_report(self, sha256sum, apikey):
"""
retrieve report from file scan
"""
url = self.base_url + "file/report"
params = {"apikey": apikey, "resource": sha256sum}
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
... |
Send IP address for list of past malicous domain associations
def send_ip(self, ipaddr, apikey):
"""
Send IP address for list of past malicous domain associations
"""
url = self.base_url + "ip-address/report"
parameters = {"ip": ipaddr, "apikey": apikey}
rate_limit_clear... |
Send URLS for list of past malicous associations
def url_report(self, scan_url, apikey):
"""
Send URLS for list of past malicous associations
"""
url = self.base_url + "url/report"
params = {"apikey": apikey, 'resource': scan_url}
rate_limit_clear = self.rate_limit()
... |
Returns a list of package requirements read from the file.
def _read_requirements(filename, extra_packages):
"""Returns a list of package requirements read from the file."""
requirements_file = open(filename).read()
hard_requirements = []
for line in requirements_file.splitlines():
if _is_requ... |
Reference a field in string separated by a delimiter
def field(ctx, text, index, delimiter=' '):
"""
Reference a field in string separated by a delimiter
"""
splits = text.split(delimiter)
# remove our delimiters and whitespace
splits = [f for f in splits if f != delimiter and len(f.strip()) >... |
Converts the given date to the number of seconds since January 1st, 1970 UTC
def epoch(ctx, datetime):
"""
Converts the given date to the number of seconds since January 1st, 1970 UTC
"""
return conversions.to_decimal(str(conversions.to_datetime(datetime, ctx).timestamp()), ctx) |
Formats digits in text for reading in TTS
def read_digits(ctx, text):
"""
Formats digits in text for reading in TTS
"""
def chunk(value, chunk_size):
return [value[i: i + chunk_size] for i in range(0, len(value), chunk_size)]
text = conversions.to_string(text, ctx).strip()
if not text:... |
Removes the first word from the given text string
def remove_first_word(ctx, text):
"""
Removes the first word from the given text string
"""
text = conversions.to_string(text, ctx).lstrip()
first = first_word(ctx, text)
return text[len(first):].lstrip() if first else '' |
Extracts the nth word from the given text string
def word(ctx, text, number, by_spaces=False):
"""
Extracts the nth word from the given text string
"""
return word_slice(ctx, text, number, conversions.to_integer(number, ctx) + 1, by_spaces) |
Returns the number of words in the given text string
def word_count(ctx, text, by_spaces=False):
"""
Returns the number of words in the given text string
"""
text = conversions.to_string(text, ctx)
by_spaces = conversions.to_boolean(by_spaces, ctx)
return len(__get_words(text, by_spaces)) |
Extracts a substring spanning from start up to but not-including stop
def word_slice(ctx, text, start, stop=0, by_spaces=False):
"""
Extracts a substring spanning from start up to but not-including stop
"""
text = conversions.to_string(text, ctx)
start = conversions.to_integer(start, ctx)
stop ... |
Takes a single parameter (date as string) and returns it in the format defined by the org
def format_date(ctx, text):
"""
Takes a single parameter (date as string) and returns it in the format defined by the org
"""
dt = conversions.to_datetime(text, ctx)
return dt.astimezone(ctx.timezone).strftime... |
Takes a single parameter (administrative boundary as a string) and returns the name of the leaf boundary
def format_location(ctx, text):
"""
Takes a single parameter (administrative boundary as a string) and returns the name of the leaf boundary
"""
text = conversions.to_string(text, ctx)
return te... |
Tries to match the text with the given pattern and returns the value of matching group
def regex_group(ctx, text, pattern, group_num):
"""
Tries to match the text with the given pattern and returns the value of matching group
"""
text = conversions.to_string(text, ctx)
pattern = conversions.to_stri... |
Helper function which splits the given text string into words. If by_spaces is false, then text like
'01-02-2014' will be split into 3 separate words. For backwards compatibility, this is the default for all
expression functions.
:param text: the text to split
:param by_spaces: whether words should be s... |
Rounding for decimals with support for negative digits
def decimal_round(number, num_digits, rounding=ROUND_HALF_UP):
"""
Rounding for decimals with support for negative digits
"""
exp = Decimal(10) ** -num_digits
if num_digits >= 0:
return number.quantize(exp, rounding)
else:
... |
Parses an ISO8601 formatted datetime from a string value
def parse_json_date(value):
"""
Parses an ISO8601 formatted datetime from a string value
"""
if not value:
return None
return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC) |
Formats a datetime as ISO8601 in UTC with millisecond precision, e.g. "2014-10-03T09:41:12.790Z"
def format_json_date(value):
"""
Formats a datetime as ISO8601 in UTC with millisecond precision, e.g. "2014-10-03T09:41:12.790Z"
"""
if not value:
return None
# %f will include 6 microsecond d... |
Removes all non-printable characters from a text string
def clean(ctx, text):
"""
Removes all non-printable characters from a text string
"""
text = conversions.to_string(text, ctx)
return ''.join([c for c in text if ord(c) >= 32]) |
Joins text strings into one text string
def concatenate(ctx, *text):
"""
Joins text strings into one text string
"""
result = ''
for arg in text:
result += conversions.to_string(arg, ctx)
return result |
Formats the given number in decimal format using a period and commas
def fixed(ctx, number, decimals=2, no_commas=False):
"""
Formats the given number in decimal format using a period and commas
"""
value = _round(ctx, number, decimals)
format_str = '{:f}' if no_commas else '{:,f}'
return forma... |
Returns the first characters in a text string
def left(ctx, text, num_chars):
"""
Returns the first characters in a text string
"""
num_chars = conversions.to_integer(num_chars, ctx)
if num_chars < 0:
raise ValueError("Number of chars can't be negative")
return conversions.to_string(tex... |
Repeats text a given number of times
def rept(ctx, text, number_times):
"""
Repeats text a given number of times
"""
if number_times < 0:
raise ValueError("Number of times can't be negative")
return conversions.to_string(text, ctx) * conversions.to_integer(number_times, ctx) |
Returns the last characters in a text string
def right(ctx, text, num_chars):
"""
Returns the last characters in a text string
"""
num_chars = conversions.to_integer(num_chars, ctx)
if num_chars < 0:
raise ValueError("Number of chars can't be negative")
elif num_chars == 0:
retu... |
Substitutes new_text for old_text in a text string
def substitute(ctx, text, old_text, new_text, instance_num=-1):
"""
Substitutes new_text for old_text in a text string
"""
text = conversions.to_string(text, ctx)
old_text = conversions.to_string(old_text, ctx)
new_text = conversions.to_string(... |
Returns a numeric code for the first character in a text string
def _unicode(ctx, text):
"""
Returns a numeric code for the first character in a text string
"""
text = conversions.to_string(text, ctx)
if len(text) == 0:
raise ValueError("Text can't be empty")
return ord(text[0]) |
Defines a date value
def date(ctx, year, month, day):
"""
Defines a date value
"""
return _date(conversions.to_integer(year, ctx), conversions.to_integer(month, ctx), conversions.to_integer(day, ctx)) |
Calculates the number of days, months, or years between two dates.
def datedif(ctx, start_date, end_date, unit):
"""
Calculates the number of days, months, or years between two dates.
"""
start_date = conversions.to_date(start_date, ctx)
end_date = conversions.to_date(end_date, ctx)
unit = conv... |
Moves a date by the given number of months
def edate(ctx, date, months):
"""
Moves a date by the given number of months
"""
return conversions.to_date_or_datetime(date, ctx) + relativedelta(months=conversions.to_integer(months, ctx)) |
Defines a time value
def time(ctx, hours, minutes, seconds):
"""
Defines a time value
"""
return _time(conversions.to_integer(hours, ctx), conversions.to_integer(minutes, ctx), conversions.to_integer(seconds, ctx)) |
Returns the absolute value of a number
def _abs(ctx, number):
"""
Returns the absolute value of a number
"""
return conversions.to_decimal(abs(conversions.to_decimal(number, ctx)), ctx) |
Rounds a number down to the nearest integer
def _int(ctx, number):
"""
Rounds a number down to the nearest integer
"""
return conversions.to_integer(conversions.to_decimal(number, ctx).to_integral_value(ROUND_FLOOR), ctx) |
Returns the maximum value of all arguments
def _max(ctx, *number):
"""
Returns the maximum value of all arguments
"""
if len(number) == 0:
raise ValueError("Wrong number of arguments")
result = conversions.to_decimal(number[0], ctx)
for arg in number[1:]:
arg = conversions.to_d... |
Returns the remainder after number is divided by divisor
def mod(ctx, number, divisor):
"""
Returns the remainder after number is divided by divisor
"""
number = conversions.to_decimal(number, ctx)
divisor = conversions.to_decimal(divisor, ctx)
return number - divisor * _int(ctx, number / divis... |
Returns the result of a number raised to a power
def _power(ctx, number, power):
"""
Returns the result of a number raised to a power
"""
return decimal_pow(conversions.to_decimal(number, ctx), conversions.to_decimal(power, ctx)) |
Returns a random integer number between the numbers you specify
def randbetween(ctx, bottom, top):
"""
Returns a random integer number between the numbers you specify
"""
bottom = conversions.to_integer(bottom, ctx)
top = conversions.to_integer(top, ctx)
return random.randint(bottom, top) |
Rounds a number to a specified number of digits
def _round(ctx, number, num_digits):
"""
Rounds a number to a specified number of digits
"""
number = conversions.to_decimal(number, ctx)
num_digits = conversions.to_integer(num_digits, ctx)
return decimal_round(number, num_digits, ROUND_HALF_UP) |
Rounds a number down, toward zero
def rounddown(ctx, number, num_digits):
"""
Rounds a number down, toward zero
"""
number = conversions.to_decimal(number, ctx)
num_digits = conversions.to_integer(num_digits, ctx)
return decimal_round(number, num_digits, ROUND_DOWN) |
Rounds a number up, away from zero
def roundup(ctx, number, num_digits):
"""
Rounds a number up, away from zero
"""
number = conversions.to_decimal(number, ctx)
num_digits = conversions.to_integer(num_digits, ctx)
return decimal_round(number, num_digits, ROUND_UP) |
Returns the sum of all arguments
def _sum(ctx, *number):
"""
Returns the sum of all arguments
"""
if len(number) == 0:
raise ValueError("Wrong number of arguments")
result = Decimal(0)
for arg in number:
result += conversions.to_decimal(arg, ctx)
return result |
Truncates a number to an integer by removing the fractional part of the number
def trunc(ctx, number):
"""
Truncates a number to an integer by removing the fractional part of the number
"""
return conversions.to_integer(conversions.to_decimal(number, ctx).to_integral_value(ROUND_DOWN), ctx) |
Returns TRUE if and only if all its arguments evaluate to TRUE
def _and(ctx, *logical):
"""
Returns TRUE if and only if all its arguments evaluate to TRUE
"""
for arg in logical:
if not conversions.to_boolean(arg, ctx):
return False
return True |
Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE
def _if(ctx, logical_test, value_if_true=0, value_if_false=False):
"""
Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE
"""
return value_if_true if conversion... |
Returns TRUE if any argument is TRUE
def _or(ctx, *logical):
"""
Returns TRUE if any argument is TRUE
"""
for arg in logical:
if conversions.to_boolean(arg, ctx):
return True
return False |
Return the sum1_ij and sum2_ij values given
the input indices and data instances.
Notes
-----
This is called in `Binning.update_sums` to compute
the `sum1` and `sum2` contributions for indices `(i,j)`
Parameters
----------
i,j : array_like
the bin indices for these pairs
da... |
Set the binning info we need from the `edges`
def _setup(self):
"""
Set the binning info we need from the `edges`
"""
dtype = [('inv', 'f8'), ('min', 'f8'), ('max', 'f8'),('N', 'i4'), ('spacing','object')]
dtype = numpy.dtype(dtype)
self._info = numpy.empty(self... |
Linearize bin indices.
This function is called by subclasses. Refer to the source
code of :py:class:`RBinning` for an example.
Parameters
----------
args : list
a list of bin index, (xi, yi, zi, ..)
Returns
-------
linearlized bin index
... |
The main function that digitizes the pair counts,
calls bincount for the appropriate `sum1` and `sum2`
values, and adds them to the input arrays,
will modify sum1, sum2, N, and centers_sum inplace.
def update_sums(self, r, i, j, data1, data2, sum1, sum2, N=None, centers_sum=None):
"""
... |
Return the shapes of the summation arrays,
given the input data and shape of the bins
def sum_shapes(self, data1, data2):
"""
Return the shapes of the summation arrays,
given the input data and shape of the bins
"""
# the linear shape (put extra dimensions first)
... |
Update the mean coordinate sums
def _update_mean_coords(self, dig, N, centers_sum, **paircoords):
"""
Update the mean coordinate sums
"""
if N is None or centers_sum is None: return
N.flat[:] += utils.bincount(dig, 1., minlength=N.size)
for i, dim in enumerate(self.dims... |
Internal function that performs the pair-counting
def work(self, i):
"""
Internal function that performs the pair-counting
"""
n1, n2 = self.p[i]
# initialize the total arrays for this process
sum1 = numpy.zeros_like(self.sum1g)
sum2 = 1.
if not self.pts... |
The internal reduce function that sums the results from various
processors
def reduce(self, sum1, sum2, *args):
"""
The internal reduce function that sums the results from various
processors
"""
self.sum1g[...] += sum1
if not self.pts_only: self.sum2g[...] += sum... |
r"""PSIS leave-one-out log predictive densities.
Computes the log predictive densities given posterior samples of the log
likelihood terms :math:`p(y_i|\theta^s)` in input parameter `log_lik`.
Returns a sum of the leave-one-out log predictive densities `loo`,
individual leave-one-out log predictive den... |
Pareto smoothed importance sampling (PSIS).
Parameters
----------
lw : ndarray
Array of size n x m containing m sets of n log weights. It is also
possible to provide one dimensional array of length n.
Reff : scalar, optional
relative MCMC efficiency ``N_eff / N``
overwrite... |
Estimate the paramaters for the Generalized Pareto Distribution (GPD)
Returns empirical Bayes estimate for the parameters of the two-parameter
generalized Parato distribution given the data.
Parameters
----------
x : ndarray
One dimensional data array
sort : bool or ndarray, optional
... |
Inverse Generalised Pareto distribution function.
def gpinv(p, k, sigma):
"""Inverse Generalised Pareto distribution function."""
x = np.empty(p.shape)
x.fill(np.nan)
if sigma <= 0:
return x
ok = (p > 0) & (p < 1)
if np.all(ok):
if np.abs(k) < np.finfo(float).eps:
np... |
Sum of vector where numbers are represented by their logarithms.
Calculates ``np.log(np.sum(np.exp(x), axis=axis))`` in such a fashion that
it works even when elements have large magnitude.
def sumlogs(x, axis=None, out=None):
"""Sum of vector where numbers are represented by their logarithms.
Calcul... |
Adds functions from a library module
:param library: the library module
:return:
def add_library(self, library):
"""
Adds functions from a library module
:param library: the library module
:return:
"""
for fn in library.__dict__.copy().values():
... |
Invokes the given function
:param ctx: the evaluation context
:param name: the function name (case insensitive)
:param arguments: the arguments to be passed to the function
:return: the function return value
def invoke_function(self, ctx, name, arguments):
"""
Invokes th... |
Builds a listing of all functions sorted A-Z, with their names and descriptions
def build_listing(self):
"""
Builds a listing of all functions sorted A-Z, with their names and descriptions
"""
def func_entry(name, func):
args, varargs, defaults = self._get_arg_spec(func)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.