text stringlengths 81 112k |
|---|
Entry point for the batcher thread.
def _batch_entry(self):
"""Entry point for the batcher thread."""
try:
while True:
self._batch_entry_run()
except:
self.exc_info = sys.exc_info()
os.kill(self.pid, signal.SIGUSR1) |
The inside of ``run``'s infinite loop.
Separate from BatchingBolt's implementation because
we need to be able to acquire the batch lock after
reading the tuple.
We can't acquire the lock before reading the tuple because if
that hangs (i.e. the topology is shutting down) the loc... |
Serialize a message dictionary and write it to the output stream.
def send_message(self, msg_dict):
"""Serialize a message dictionary and write it to the output stream."""
with self._writer_lock:
try:
self.output_stream.flush()
self.output_stream.write(self.s... |
Convert the FFI result to Python data structures
def _void_array_to_list(restuple, _func, _args):
""" Convert the FFI result to Python data structures """
shape = (restuple.e.len, 1)
array_size = np.prod(shape)
mem_size = 8 * array_size
array_str_e = string_at(restuple.e.data, mem_size)
array_... |
Load a data file and return it as a list of lines.
Parameters:
filename: The name of the file (no directories included).
encoding: The file encoding. Defaults to utf-8.
def load_data_file(filename, encoding='utf-8'):
"""Load a data file and return it as a list of lines.
Parameters:
... |
Load the word and character mapping data into a dictionary.
In the data files, each line is formatted like this:
HANZI PINYIN_READING/PINYIN_READING
So, lines need to be split by '\t' and then the Pinyin readings need to be
split by '/'.
def _load_data():
"""Load the word and character mapp... |
Return the Pinyin reading for a Chinese word.
If the given string *hanzi* matches a CC-CEDICT word, the return value is
formatted like this: [WORD_READING1, WORD_READING2, ...]
If the given string *hanzi* doesn't match a CC-CEDICT word, the return
value is formatted like this: [[CHAR_READING1, CHAR_RE... |
Enclose a reading within a container, e.g. '[]'.
def _enclose_readings(container, readings):
"""Enclose a reading within a container, e.g. '[]'."""
container_start, container_end = tuple(container)
enclosed_readings = '%(container_start)s%(readings)s%(container_end)s' % {
'container_start': contain... |
Convert a string's Chinese characters to Pinyin readings.
*s* is a string containing Chinese characters. *accented* is a
boolean value indicating whether to return accented or numbered Pinyin
readings.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differenti... |
Convert a string's Chinese characters to Zhuyin readings.
*s* is a string containing Chinese characters.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and characters so that a more
accurate reading can be returned.
*all_readings*... |
Convert a string's Chinese characters to IPA.
*s* is a string containing Chinese characters.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and characters so that a more
accurate reading can be returned.
*all_readings* is a boolea... |
Load the transcription mapping data into a dictionary.
def _load_data():
"""Load the transcription mapping data into a dictionary."""
lines = dragonmapper.data.load_data_file('transcriptions.csv')
pinyin_map, zhuyin_map, ipa_map = {}, {}, {}
for line in lines:
p, z, i = line.split(',')
... |
Convert a numbered Pinyin vowel to an accented Pinyin vowel.
def _numbered_vowel_to_accented(vowel, tone):
"""Convert a numbered Pinyin vowel to an accented Pinyin vowel."""
if isinstance(tone, int):
tone = str(tone)
return _PINYIN_TONES[vowel + tone] |
Convert an accented Pinyin vowel to a numbered Pinyin vowel.
def _accented_vowel_to_numbered(vowel):
"""Convert an accented Pinyin vowel to a numbered Pinyin vowel."""
for numbered_vowel, accented_vowel in _PINYIN_TONES.items():
if vowel == accented_vowel:
return tuple(numbered_vowel) |
Return the syllable and tone of a numbered Pinyin syllable.
def _parse_numbered_syllable(unparsed_syllable):
"""Return the syllable and tone of a numbered Pinyin syllable."""
tone_number = unparsed_syllable[-1]
if not tone_number.isdigit():
syllable, tone = unparsed_syllable, '5'
elif tone_numb... |
Return the syllable and tone of an accented Pinyin syllable.
Any accented vowels are returned without their accents.
Implements the following algorithm:
1. If the syllable has an accent mark, convert that vowel to a
regular vowel and add the tone to the end of the syllable.
2. Otherwise, assu... |
Return the syllable and tone of a Zhuyin syllable.
def _parse_zhuyin_syllable(unparsed_syllable):
"""Return the syllable and tone of a Zhuyin syllable."""
zhuyin_tone = unparsed_syllable[-1]
if zhuyin_tone in zhon.zhuyin.characters:
syllable, tone = unparsed_syllable, '1'
elif zhuyin_tone in zh... |
Return the syllable and tone of an IPA syllable.
def _parse_ipa_syllable(unparsed_syllable):
"""Return the syllable and tone of an IPA syllable."""
ipa_tone = re.search('[%(marks)s]+' % {'marks': _IPA_MARKS},
unparsed_syllable)
if not ipa_tone:
syllable, tone = unparsed_syl... |
Restore a lowercase string's characters to their original case.
def _restore_case(s, memory):
"""Restore a lowercase string's characters to their original case."""
cased_s = []
for i, c in enumerate(s):
if i + 1 > len(memory):
break
cased_s.append(c if memory[i] else c.upper())
... |
Convert numbered Pinyin syllable *s* to an accented Pinyin syllable.
It implements the following algorithm to determine where to place tone
marks:
1. If the syllable has an 'a', 'e', or 'o' (in that order), put the
tone mark over that vowel.
2. Otherwise, put the tone mark on the last vowel.
... |
Convert accented Pinyin syllable *s* to a numbered Pinyin syllable.
def accented_syllable_to_numbered(s):
"""Convert accented Pinyin syllable *s* to a numbered Pinyin syllable."""
if s[0] == '\u00B7':
lowercase_syllable, case_memory = _lower_case(s[1:])
lowercase_syllable = '\u00B7' + lowercase... |
Convert Pinyin syllable *s* to a Zhuyin syllable.
def pinyin_syllable_to_zhuyin(s):
"""Convert Pinyin syllable *s* to a Zhuyin syllable."""
pinyin_syllable, tone = _parse_pinyin_syllable(s)
try:
zhuyin_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['Zhuyin']
except KeyError:
raise Valu... |
Convert Pinyin syllable *s* to an IPA syllable.
def pinyin_syllable_to_ipa(s):
"""Convert Pinyin syllable *s* to an IPA syllable."""
pinyin_syllable, tone = _parse_pinyin_syllable(s)
try:
ipa_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['IPA']
except KeyError:
raise ValueError('Not a... |
Convert Zhuyin syllable *s* to a numbered Pinyin syllable.
def _zhuyin_syllable_to_numbered(s):
"""Convert Zhuyin syllable *s* to a numbered Pinyin syllable."""
zhuyin_syllable, tone = _parse_zhuyin_syllable(s)
try:
pinyin_syllable = _ZHUYIN_MAP[zhuyin_syllable]['Pinyin']
except KeyError:
... |
Convert IPA syllable *s* to a numbered Pinyin syllable.
def _ipa_syllable_to_numbered(s):
"""Convert IPA syllable *s* to a numbered Pinyin syllable."""
ipa_syllable, tone = _parse_ipa_syllable(s)
try:
pinyin_syllable = _IPA_MAP[ipa_syllable]['Pinyin']
except KeyError:
raise ValueError('... |
Convert a string's syllables to a different transcription system.
def _convert(s, re_pattern, syllable_function, add_apostrophes=False,
remove_apostrophes=False, separate_syllables=False):
"""Convert a string's syllables to a different transcription system."""
original = s
new = ''
while o... |
Convert all numbered Pinyin syllables in *s* to accented Pinyin.
def numbered_to_accented(s):
"""Convert all numbered Pinyin syllables in *s* to accented Pinyin."""
return _convert(s, zhon.pinyin.syllable, numbered_syllable_to_accented,
add_apostrophes=True) |
Convert all Pinyin syllables in *s* to Zhuyin.
Spaces are added between connected syllables and syllable-separating
apostrophes are removed.
def pinyin_to_zhuyin(s):
"""Convert all Pinyin syllables in *s* to Zhuyin.
Spaces are added between connected syllables and syllable-separating
apostrophes ... |
Convert all Pinyin syllables in *s* to IPA.
Spaces are added between connected syllables and syllable-separating
apostrophes are removed.
def pinyin_to_ipa(s):
"""Convert all Pinyin syllables in *s* to IPA.
Spaces are added between connected syllables and syllable-separating
apostrophes are remov... |
Convert all Zhuyin syllables in *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone.
def zhuyin_to_pinyin(s, accented=True):
"""Convert all Zhuyin syllables in *s* to Pinyin.
If *accented* is ``True``, diacritics... |
Convert all IPA syllables in *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone.
def ipa_to_pinyin(s, accented=True):
"""Convert all IPA syllables in *s* to Pinyin.
If *accented* is ``True``, diacritics are adde... |
Convert *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone.
def to_pinyin(s, accented=True):
"""Convert *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False... |
Convert *s* to Zhuyin.
def to_zhuyin(s):
"""Convert *s* to Zhuyin."""
identity = identify(s)
if identity == ZHUYIN:
return s
elif identity == PINYIN:
return pinyin_to_zhuyin(s)
elif identity == IPA:
return ipa_to_zhuyin(s)
else:
raise ValueError("String is not a ... |
Convert *s* to IPA.
def to_ipa(s):
"""Convert *s* to IPA."""
identity = identify(s)
if identity == IPA:
return s
elif identity == PINYIN:
return pinyin_to_ipa(s)
elif identity == ZHUYIN:
return zhuyin_to_ipa(s)
else:
raise ValueError("String is not a valid Chines... |
Check if a re pattern expression matches an entire string.
def _is_pattern_match(re_pattern, s):
"""Check if a re pattern expression matches an entire string."""
match = re.match(re_pattern, s, re.I)
return match.group() == s if match else False |
Check if *s* consists of valid Pinyin.
def is_pinyin(s):
"""Check if *s* consists of valid Pinyin."""
re_pattern = ('(?:%(word)s|[ \t%(punctuation)s])+' %
{'word': zhon.pinyin.word,
'punctuation': zhon.pinyin.punctuation})
return _is_pattern_match(re_pattern, s) |
Checks if *s* is consists of Zhuyin-compatible characters.
This does not check if *s* contains valid Zhuyin syllables; for that
see :func:`is_zhuyin`.
Besides Zhuyin characters and tone marks, spaces are also accepted.
This function checks that all characters in *s* exist in
:data:`zhon.zhuyin.cha... |
Check if *s* consists of valid Chinese IPA.
def is_ipa(s):
"""Check if *s* consists of valid Chinese IPA."""
re_pattern = ('(?:%(syllable)s|[ \t%(punctuation)s])+' %
{'syllable': _IPA_SYLLABLE,
'punctuation': zhon.pinyin.punctuation})
return _is_pattern_match(re_pattern... |
Identify a given string's transcription system.
*s* is the string to identify. The string is checked to see if its
contents are valid Pinyin, Zhuyin, or IPA. The :data:`PINYIN`,
:data:`ZHUYIN`, and :data:`IPA` constants are returned to indicate the
string's identity.
If *s* is not a valid transcrip... |
Accept an objective function for optimization.
def prepare(self, f):
"""Accept an objective function for optimization."""
self.g = autograd.grad(f)
self.h = autograd.hessian(f) |
Calculate an optimum argument of an objective function.
def optimize(self, x0, target):
"""Calculate an optimum argument of an objective function."""
x = x0
for _ in range(self.maxiter):
delta = np.linalg.solve(self.h(x, target), -self.g(x, target))
x = x + delta
... |
Calculate an optimum argument of an objective function.
def optimize(self, x0, target):
"""Calculate an optimum argument of an objective function."""
x = x0
for i in range(self.maxiter):
g = self.g(x, target)
h = self.h(x, target)
if i == 0:
a... |
Calculate an optimum argument of an objective function.
def optimize(self, angles0, target):
"""Calculate an optimum argument of an objective function."""
def new_objective(angles):
return self.f(angles, target)
return scipy.optimize.minimize(
new_objective,
... |
Calculate an optimum argument of an objective function.
def optimize(self, angles0, target):
"""Calculate an optimum argument of an objective function."""
def new_objective(angles):
a = angles - angles0
if isinstance(self.smooth_factor, (np.ndarray, list)):
if le... |
Calculate a position of the end-effector and return it.
def solve(self, angles):
"""Calculate a position of the end-effector and return it."""
return reduce(
lambda a, m: np.dot(m, a),
reversed(self._matrices(angles)),
np.array([0., 0., 0., 1.])
)[:3] |
Calculate joint angles and returns it.
def solve(self, angles0, target):
"""Calculate joint angles and returns it."""
return self.optimizer.optimize(np.array(angles0), target) |
Return translation matrix in homogeneous coordinates.
def matrix(self, _):
"""Return translation matrix in homogeneous coordinates."""
x, y, z = self.coord
return np.array([
[1., 0., 0., x],
[0., 1., 0., y],
[0., 0., 1., z],
[0., 0., 0., 1.]
... |
Return rotation matrix in homogeneous coordinates.
def matrix(self, angle):
"""Return rotation matrix in homogeneous coordinates."""
_rot_mat = {
'x': self._x_rot,
'y': self._y_rot,
'z': self._z_rot
}
return _rot_mat[self.axis](angle) |
Set a logger to send debug messages to
Parameters
----------
logger : `Logger <http://docs.python.org/2/library/logging.html>`_
A python logger used to get debugging output from this module.
def set_logger(self, logger):
"""
Set a logger to send debug messages to
... |
Return the version number of the Lending Club Investor tool
Returns
-------
string
The version number string
def version(self):
"""
Return the version number of the Lending Club Investor tool
Returns
-------
string
The version nu... |
Attempt to authenticate the user.
Parameters
----------
email : string
The email of a user on Lending Club
password : string
The user's password, for authentication.
Returns
-------
boolean
True if the user authenticated or ra... |
Returns the account cash balance available for investing
Returns
-------
float
The cash balance in your account.
def get_cash_balance(self):
"""
Returns the account cash balance available for investing
Returns
-------
float
The c... |
Get your list of named portfolios from the lendingclub.com
Parameters
----------
names_only : boolean, optional
If set to True, the function will return a list of portfolio names, instead of portfolio objects
Returns
-------
list
A list of portfo... |
Assign a note to a named portfolio. `loan_id` and `order_id` can be either
integer values or lists. If choosing lists, they both **MUST** be the same length
and line up. For example, `order_id[5]` must be the order ID for `loan_id[5]`
Parameters
----------
portfolio_name : strin... |
Search for a list of notes that can be invested in.
(similar to searching for notes in the Browse section on the site)
Parameters
----------
filters : lendingclub.filters.*, optional
The filter to use to search for notes. If no filter is passed, a wildcard search
... |
Returns a list of loan notes that are diversified by your min/max percent request and filters.
One way to invest in these loan notes, is to start an order and use add_batch to add all the
loan fragments to them. (see examples)
Parameters
----------
cash : int
The tot... |
Return all the loan notes you've already invested in. By default it'll return 100 results at a time.
Parameters
----------
start_index : int, optional
The result index to start on. By default only 100 records will be returned at a time, so use this
to start at a later in... |
Get a loan note that you've invested in by ID
Parameters
----------
note_id : int
The note ID
Returns
-------
dict
A dictionary representing the matching note or False
Examples
--------
>>> from lendingclub import Len... |
Search for notes you are invested in. Use the parameters to define how to search.
Passing no parameters is the same as calling `my_notes(get_all=True)`
Parameters
----------
loan_id : int, optional
Search for notes for a specific loan. Since a loan is broken up into a pool o... |
Add a loan and amount you want to invest, to your order.
If this loan is already in your order, it's amount will be replaced
with the this new amount
Parameters
----------
loan_id : int or dict
The ID of the loan you want to add or a dictionary containing a `loan_id`... |
Add a batch of loans to your order.
Parameters
----------
loans : list
A list of dictionary objects representing each loan and the amount you want to invest in it (see examples below).
batch_amount : int, optional
The dollar amount you want to set on ALL loans in... |
Place the order with LendingClub
Parameters
----------
portfolio_name : string
The name of the portfolio to add the invested loan notes to.
This can be a new or existing portfolio name.
Raises
------
LendingClubError
Returns
----... |
Assign all the notes in this order to a portfolio
Parameters
----------
portfolio_name -- The name of the portfolio to assign it to (new or existing)
Raises
------
LendingClubError
Returns
-------
boolean
True on success
def ass... |
Add all the loans to the LC order session
def __stage_order(self):
"""
Add all the loans to the LC order session
"""
# Skip staging...probably not a good idea...you've been warned
if self.__already_staged is True and self.__i_know_what_im_doing is True:
self.__log('... |
Move the staged loan notes to the order stage and get the struts token
from the place order HTML.
The order will not be placed until calling _confirm_order()
Returns
-------
dict
A dict with the token name and value
def __get_strut_token(self):
"""
M... |
Use the struts token to place the order.
Parameters
----------
token : string
The struts token received from the place order page
Returns
-------
int
The completed order ID.
def __place_order(self, token):
"""
Use the struts toke... |
Check if the time since the last HTTP request is under the
session timeout limit. If it's been too long since the last request
attempt to authenticate again.
def __continue_session(self):
"""
Check if the time since the last HTTP request is under the
session timeout limit. If it... |
Build a LendingClub URL from a URL path (without the domain).
Parameters
----------
path : string
The path part of the URL after the domain. i.e. https://www.lendingclub.com/<path>
def build_url(self, path):
"""
Build a LendingClub URL from a URL path (without the d... |
Authenticate with LendingClub and preserve the user session for future requests.
This will raise an exception if the login appears to have failed, otherwise it returns True.
Since Lending Club doesn't seem to have a login API, the code has to try to decide if the login
worked or not by looking ... |
Returns true if we can access LendingClub.com
This is also a simple test to see if there's a network connection
Returns
-------
boolean
True or False
def is_site_available(self):
"""
Returns true if we can access LendingClub.com
This is also a simple... |
Sends HTTP request to LendingClub.
Parameters
----------
method : {GET, POST, HEAD, DELETE}
The HTTP method to use: GET, POST, HEAD or DELETE
path : string
The path that will be appended to the domain defined in :attr:`base_url`.
query : dict
... |
POST request wrapper for :func:`request()`
def post(self, path, query=None, data=None, redirects=True):
"""
POST request wrapper for :func:`request()`
"""
return self.request('POST', path, query, data, redirects) |
GET request wrapper for :func:`request()`
def get(self, path, query=None, redirects=True):
"""
GET request wrapper for :func:`request()`
"""
return self.request('GET', path, query, None, redirects) |
HEAD request wrapper for :func:`request()`
def head(self, path, query=None, data=None, redirects=True):
"""
HEAD request wrapper for :func:`request()`
"""
return self.request('HEAD', path, query, None, redirects) |
Check the JSON response object for the success flag
Parameters
----------
json : dict
A dictionary representing a JSON object from lendingclub.com
def json_success(self, json):
"""
Check the JSON response object for the success flag
Parameters
-----... |
Merge dictionary objects recursively, by only updating keys existing in to_dict
def __merge_values(self, from_dict, to_dict):
"""
Merge dictionary objects recursively, by only updating keys existing in to_dict
"""
for key, value in from_dict.iteritems():
# Only if the key a... |
Adjust the grades list.
If a grade has been set, set All to false
def __normalize_grades(self):
"""
Adjust the grades list.
If a grade has been set, set All to false
"""
if 'grades' in self and self['grades']['All'] is True:
for grade in self['grades']:
... |
Adjust the funding progress filter to be a factor of 10
def __normalize_progress(self):
"""
Adjust the funding progress filter to be a factor of 10
"""
progress = self['funding_progress']
if progress % 10 != 0:
progress = round(float(progress) / 10)
prog... |
Adjusts the values of the filters to be correct.
For example, if you set grade 'B' to True, then 'All'
should be set to False
def __normalize(self):
"""
Adjusts the values of the filters to be correct.
For example, if you set grade 'B' to True, then 'All'
should be set t... |
Validate a single loan result record against the filters
Parameters
----------
loan : dict
A single loan note record
Returns
-------
boolean
True or raises FilterValidationError
Raises
------
FilterValidationError
... |
Returns the JSON string that LendingClub expects for it's search
def search_string(self):
""""
Returns the JSON string that LendingClub expects for it's search
"""
self.__normalize()
# Get the template
tmpl_source = unicode(open(self.tmpl_file).read())
# Proces... |
Get a list of all your saved filters
Parameters
----------
lc : :py:class:`lendingclub.LendingClub`
An instance of the authenticated LendingClub class
Returns
-------
list
A list of lendingclub.filters.SavedFilter objects
def all_filters(lc):
... |
Load the filter from the server
def load(self):
"""
Load the filter from the server
"""
# Attempt to load the saved filter
payload = {
'id': self.id
}
response = self.lc.session.get('/browse/getSavedFilterAj.action', query=payload)
self.respo... |
Analyze the filter JSON and attempt to parse out the individual filters.
def __analyze(self):
"""
Analyze the filter JSON and attempt to parse out the individual filters.
"""
filter_values = {}
# ID to filter name mapping
name_map = {
10: 'grades',
... |
Copy origin to out and return it.
If ``out`` is None, a new copy (casted to floating point) is used. If
``out`` and ``origin`` are the same, we simply return it. Otherwise we
copy the values.
def _float_copy_to_out(out, origin):
"""
Copy origin to out and return it.
If ``out`` is None, a new ... |
Real implementation of :func:`double_centered`.
This function is used to make parameter ``out`` keyword-only in
Python 2.
def _double_centered_imp(a, out=None):
"""
Real implementation of :func:`double_centered`.
This function is used to make parameter ``out`` keyword-only in
Python 2.
"... |
Real implementation of :func:`u_centered`.
This function is used to make parameter ``out`` keyword-only in
Python 2.
def _u_centered_imp(a, out=None):
"""
Real implementation of :func:`u_centered`.
This function is used to make parameter ``out`` keyword-only in
Python 2.
"""
out = _f... |
r"""
Inner product in the Hilbert space of :math:`U`-centered distance matrices.
This inner product is defined as
.. math::
\frac{1}{n(n-3)} \sum_{i,j=1}^n a_{i, j} b_{i, j}
Parameters
----------
a: array_like
First input array to be multiplied.
b: array_like
Secon... |
r"""
Return the orthogonal projection function over :math:`a`.
The function returned computes the orthogonal projection over
:math:`a` in the Hilbert space of :math:`U`-centered distance
matrices.
The projection of a matrix :math:`B` over a matrix :math:`A`
is defined as
.. math::
... |
r"""
Return the orthogonal projection function over :math:`a^{\perp}`.
The function returned computes the orthogonal projection over
:math:`a^{\perp}` (the complementary projection over a)
in the Hilbert space of :math:`U`-centered distance matrices.
The projection of a matrix :math:`B` over a mat... |
Compute a centered distance matrix given a matrix.
def _distance_matrix_generic(x, centering, exponent=1):
"""Compute a centered distance matrix given a matrix."""
_check_valid_dcov_exponent(exponent)
x = _transform_to_2d(x)
# Calculate distance matrices
a = distances.pairwise_distances(x, expone... |
Scale a random vector for using the affinely invariant measures
def _af_inv_scaled(x):
"""Scale a random vector for using the affinely invariant measures"""
x = _transform_to_2d(x)
cov_matrix = np.atleast_2d(np.cov(x, rowvar=False))
cov_matrix_power = _mat_sqrt_inv(cov_matrix)
return x.dot(cov_m... |
Partial distance covariance estimator.
Compute the estimator for the partial distance covariance of the
random vectors corresponding to :math:`x` and :math:`y` with respect
to the random variable corresponding to :math:`z`.
Parameters
----------
x: array_like
First random vector. The c... |
Partial distance correlation estimator.
Compute the estimator for the partial distance correlation of the
random vectors corresponding to :math:`x` and :math:`y` with respect
to the random variable corresponding to :math:`z`.
Parameters
----------
x: array_like
First random vector. The... |
Compute energy distance with precalculated distance matrices.
def _energy_distance_from_distance_matrices(
distance_xx, distance_yy, distance_xy):
"""Compute energy distance with precalculated distance matrices."""
return (2 * np.mean(distance_xy) - np.mean(distance_xx) -
np.mean(distance_y... |
Real implementation of :func:`energy_distance`.
This function is used to make parameter ``exponent`` keyword-only in
Python 2.
def _energy_distance_imp(x, y, exponent=1):
"""
Real implementation of :func:`energy_distance`.
This function is used to make parameter ``exponent`` keyword-only in
P... |
Naive biased estimator for distance covariance.
Computes the unbiased estimator for distance covariance between two
matrices, using an :math:`O(N^2)` algorithm.
def _distance_covariance_sqr_naive(x, y, exponent=1):
"""
Naive biased estimator for distance covariance.
Computes the unbiased estimato... |
Naive unbiased estimator for distance covariance.
Computes the unbiased estimator for distance covariance between two
matrices, using an :math:`O(N^2)` algorithm.
def _u_distance_covariance_sqr_naive(x, y, exponent=1):
"""
Naive unbiased estimator for distance covariance.
Computes the unbiased es... |
Compute generic squared stats.
def _distance_sqr_stats_naive_generic(x, y, matrix_centered, product,
exponent=1):
"""Compute generic squared stats."""
a = matrix_centered(x, exponent=exponent)
b = matrix_centered(y, exponent=exponent)
covariance_xy_sqr = product(a... |
Biased distance correlation estimator between two matrices.
def _distance_correlation_sqr_naive(x, y, exponent=1):
"""Biased distance correlation estimator between two matrices."""
return _distance_sqr_stats_naive_generic(
x, y,
matrix_centered=_distance_matrix,
product=mean_product,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.