INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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('Not a valid syllable: %s' % s) return pinyin_syllable...
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 original: match = re.search(re_pattern, original, re.IGNOREC...
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.
def pinyin_to_zhuyin(s): """Convert all Pinyin syllables in *s* to Zhuyin. Spaces are added between connected syllables and syllable-separating apostrophes are removed. """ return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_zhuyin, remove_apostrophes=True, separate_syl...
Convert all Pinyin syllables in * s * to IPA.
def pinyin_to_ipa(s): """Convert all Pinyin syllables in *s* to IPA. Spaces are added between connected syllables and syllable-separating apostrophes are removed. """ return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_ipa, remove_apostrophes=True, separate_syllables=Tr...
Convert all Zhuyin syllables in * s * to Pinyin.
def zhuyin_to_pinyin(s, accented=True): """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. """ if accented: function = _zhuyin_syllable_to_accented else: ...
Convert all IPA syllables in * s * to Pinyin.
def ipa_to_pinyin(s, accented=True): """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. """ if accented: function = _ipa_syllable_to_accented else: functio...
Convert * s * to Pinyin.
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``, numbers are used to indicate tone. """ identity = identify(s) if identity == PINYIN: if _has_accented_vowels(s): return s i...
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 valid Chinese transcript...
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 Chinese transcription.")
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.
def is_zhuyin_compatible(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*...
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, s)
Identify a given string s transcription system.
def identify(s): """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* ...
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 if np.linalg.norm(delta) < self.tol: ...
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: alpha = 0 m = g else: ...
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, angles0, **self.optimizer_opt).x
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 len(a) == len(self.smooth_factor): retu...
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
def set_logger(self, logger): """ 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. """ self.__logger = logger...
Return the version number of the Lending Club Investor tool
def version(self): """ Return the version number of the Lending Club Investor tool Returns ------- string The version number string """ this_path = os.path.dirname(os.path.realpath(__file__)) version_file = os.path.join(this_path, 'VERSION') ...
Attempt to authenticate the user.
def authenticate(self, email=None, password=None): """ 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 -...
Returns the account cash balance available for investing
def get_cash_balance(self): """ Returns the account cash balance available for investing Returns ------- float The cash balance in your account. """ cash = False try: response = self.session.get('/browse/cashBalanceAj.action') ...
Get your list of named portfolios from the lendingclub. com
def get_portfolio_list(self, names_only=False): """ 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 ...
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 ]
def assign_to_portfolio(self, portfolio_name, loan_id, order_id): """ 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 ...
Search for a list of notes that can be invested in. ( similar to searching for notes in the Browse section on the site )
def search(self, filters=None, start_index=0, limit=100): """ 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 ...
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 )
def build_portfolio(self, cash, max_per_note=25, min_percent=0, max_percent=20, filters=None, automatically_invest=False, do_not_clear_staging=False): """ 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 s...
Return all the loan notes you ve already invested in. By default it ll return 100 results at a time.
def my_notes(self, start_index=0, limit=100, get_all=False, sort_by='loanId', sort_dir='asc'): """ 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 ...
Get a loan note that you ve invested in by ID
def get_note(self, note_id): """ 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 ---...
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 )
def search_my_notes(self, loan_id=None, order_id=None, grade=None, portfolio_name=None, status=None, term=None): """ 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 ...
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
def add(self, loan_id, amount): """ 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 yo...
Add a batch of loans to your order.
def add_batch(self, loans, batch_amount=None): """ 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, opt...
Place the order with LendingClub
def execute(self, portfolio_name=None): """ 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 -...
Assign all the notes in this order to a portfolio
def assign_to_portfolio(self, portfolio_name=None): """ 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 Retu...
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('Not staging the order...I hope you know wha...
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 ()
def __get_strut_token(self): """ 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 ...
Use the struts token to place the order.
def __place_order(self, token): """ 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. """ ...
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's been too long since the last request attempt to authenticate again. """ now = time.time() diff = abs(now - self.last_request_time) t...
Build a LendingClub URL from a URL path ( without the domain ).
def build_url(self, path): """ 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> """ url = '{0}{1}'.format(self.base_url...
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.
def authenticate(self, email=None, password=None): """ 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 c...
Returns true if we can access LendingClub. com This is also a simple test to see if there s a network connection
def is_site_available(self): """ 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 """ try: response = requests.head(self.base_url)...
Sends HTTP request to LendingClub.
def request(self, method, path, query=None, data=None, redirects=True): """ 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 w...
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
def json_success(self, json): """ Check the JSON response object for the success flag Parameters ---------- json : dict A dictionary representing a JSON object from lendingclub.com """ if type(json) is dict and 'result' in json and json['result'] == '...
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 already exists if key in to_dict: # Make sure the val...
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']: if grade != 'All' and self['grades'][grade] is True: ...
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) progress = int(progress) * 10 self['funding_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 to False """ # Don't normalize if we're already normalizing or intializing if self.__normalizing is True or self.__init...
Validate a single loan result record against the filters
def validate_one(self, loan): """ Validate a single loan result record against the filters Parameters ---------- loan : dict A single loan note record Returns ------- boolean True or raises FilterValidationError Raises ...
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()) # Process template compiler = Compiler() template = compil...
Get a list of all your saved filters
def all_filters(lc): """ 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.Sav...
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.response = response json_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', 11: 'loan_purpose', 13: 'approved', 15: 'fundin...
Copy origin to out and return it.
def _float_copy_to_out(out, origin): """ 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. """ if out is None: out = origin / 1 # The divis...
Real implementation of: func: double_centered.
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. """ out = _float_copy_to_out(out, a) dim = np.size(a, 0) mu = np.sum(a) / (dim * dim) sum_cols = np.sum(a, 0, keepd...
Real implementation of: func: u_centered.
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 = _float_copy_to_out(out, a) dim = np.size(a, 0) u_mu = np.sum(a) / ((dim - 1) * (dim - 2)) sum_cols = np.sum(a, 0, k...
r Inner product in the Hilbert space of: math: U - centered distance matrices.
def u_product(a, b): 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:...
r Return the orthogonal projection function over: math: a.
def u_projection(a): 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 ...
r Return the orthogonal projection function over: math: a^ { \ perp }.
def u_complementary_projection(a): 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 proj...
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, exponent=exponent) # Double centering a = centeri...
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_matrix_power)
Partial distance covariance estimator.
def partial_distance_covariance(x, y, z): """ 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 ---------...
Partial distance correlation estimator.
def partial_distance_correlation(x, y, z): # pylint:disable=too-many-locals """ 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 :ma...
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_yy))
Real implementation of: func: energy_distance.
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 Python 2. """ x = _transform_to_2d(x) y = _transform_to_2d(y) _check_valid_energy_exponent(exponent) distance_xx = ...
Naive biased estimator for distance covariance.
def _distance_covariance_sqr_naive(x, y, exponent=1): """ Naive biased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm. """ a = _distance_matrix(x, exponent=exponent) b = _distance_matrix(y, e...
Naive unbiased estimator for distance covariance.
def _u_distance_covariance_sqr_naive(x, y, exponent=1): """ Naive unbiased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm. """ a = _u_distance_matrix(x, exponent=exponent) b = _u_distance_mat...
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, b) variance_x_sqr = produc...
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, exponent=exponent).correlation_xy
Bias - corrected distance correlation estimator between two matrices.
def _u_distance_correlation_sqr_naive(x, y, exponent=1): """Bias-corrected distance correlation estimator between two matrices.""" return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_u_distance_matrix, product=u_product, exponent=exponent).correlation_xy
Check if the fast algorithm for distance stats can be used.
def _can_use_fast_algorithm(x, y, exponent=1): """ Check if the fast algorithm for distance stats can be used. The fast algorithm has complexity :math:`O(NlogN)`, better than the complexity of the naive algorithm (:math:`O(N^2)`). The algorithm can only be used for random variables (not vectors) w...
Inner function of the fast distance covariance.
def _dyad_update(y, c): # pylint:disable=too-many-locals # This function has many locals so it can be compared # with the original algorithm. """ Inner function of the fast distance covariance. This function is compiled because otherwise it would become a bottleneck. """ n = y.shape[0...
Fast algorithm for the squared distance covariance.
def _distance_covariance_sqr_fast_generic( x, y, unbiased=False): # pylint:disable=too-many-locals # This function has many locals so it can be compared # with the original algorithm. """Fast algorithm for the squared distance covariance.""" x = np.asarray(x) y = np.asarray(y) x = np.r...
Compute the distance stats using the fast algorithm.
def _distance_stats_sqr_fast_generic(x, y, dcov_function): """Compute the distance stats using the fast algorithm.""" covariance_xy_sqr = dcov_function(x, y) variance_x_sqr = dcov_function(x, x) variance_y_sqr = dcov_function(y, y) denominator_sqr_signed = variance_x_sqr * variance_y_sqr denomin...
distance_covariance_sqr ( x y * exponent = 1 )
def distance_covariance_sqr(x, y, **kwargs): """ distance_covariance_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with t...
u_distance_covariance_sqr ( x y * exponent = 1 )
def u_distance_covariance_sqr(x, y, **kwargs): """ u_distance_covariance_sqr(x, y, *, exponent=1) Computes the unbiased estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the...
distance_stats_sqr ( x y * exponent = 1 )
def distance_stats_sqr(x, y, **kwargs): """ distance_stats_sqr(x, y, *, exponent=1) Computes the usual (biased) estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- ...
u_distance_stats_sqr ( x y * exponent = 1 )
def u_distance_stats_sqr(x, y, **kwargs): """ u_distance_stats_sqr(x, y, *, exponent=1) Computes the unbiased estimators for the squared distance covariance and squared distance correlation between two random vectors, and the individual squared distance variances. Parameters ---------- ...
distance_stats ( x y * exponent = 1 )
def distance_stats(x, y, **kwargs): """ distance_stats(x, y, *, exponent=1) Computes the usual (biased) estimators for the distance covariance and distance correlation between two random vectors, and the individual distance variances. Parameters ---------- x: array_like First r...
distance_correlation_sqr ( x y * exponent = 1 )
def distance_correlation_sqr(x, y, **kwargs): """ distance_correlation_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance correlation between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond wit...
u_distance_correlation_sqr ( x y * exponent = 1 )
def u_distance_correlation_sqr(x, y, **kwargs): """ u_distance_correlation_sqr(x, y, *, exponent=1) Computes the bias-corrected estimator for the squared distance correlation between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond...
Square of the affinely invariant distance correlation.
def distance_correlation_af_inv_sqr(x, y): """ Square of the affinely invariant distance correlation. Computes the estimator for the square of the affinely invariant distance correlation between two random vectors. .. warning:: The return value of this function is undefined when the ...
pairwise ( function x y = None * pool = None is_symmetric = None ** kwargs )
def pairwise(function, x, y=None, **kwargs): """ pairwise(function, x, y=None, *, pool=None, is_symmetric=None, **kwargs) Computes a dependency measure between each pair of elements. Parameters ---------- function: Dependency measure function. x: iterable of array_like First list o...
Real implementation of: func: pairwise.
def _pairwise_imp(function, x, y=None, pool=None, is_symmetric=None, **kwargs): """ Real implementation of :func:`pairwise`. This function is used to make several parameters keyword-only in Python 2. """ map_function = pool.map if pool else map if is_symmetric is None: is_symmetri...
Compile a function using a jit compiler.
def _jit(function): """ Compile a function using a jit compiler. The function is always compiled to check errors, but is only used outside tests, so that code coverage analysis can be performed in jitted functions. The tests set sys._called_from_test in conftest.py. """ import sys co...
Return square root of an ndarray.
def _sqrt(x): """ Return square root of an ndarray. This sqrt function for ndarrays tries to use the exponentiation operator if the objects stored do not supply a sqrt method. """ x = np.clip(x, a_min=0, a_max=None) try: return np.sqrt(x) except AttributeError: exponen...
Convert vectors to column matrices to always have a 2d shape.
def _transform_to_2d(t): """Convert vectors to column matrices, to always have a 2d shape.""" t = np.asarray(t) dim = len(t.shape) assert dim <= 2 if dim < 2: t = np.atleast_2d(t).T return t
Return if the array can be safely converted to double.
def _can_be_double(x): """ Return if the array can be safely converted to double. That happens when the dtype is a float with the same size of a double or narrower, or when is an integer that can be safely converted to double (if the roundtrip conversion works). """ return ((np.issubdtype(...
Pairwise distance custom implementation.
def _cdist_naive(x, y, exponent=1): """Pairwise distance, custom implementation.""" squared_norms = ((x[_np.newaxis, :, :] - y[:, _np.newaxis, :]) ** 2).sum(2) exponent = exponent / 2 try: exponent = squared_norms.take(0).from_float(exponent) except AttributeError: pass return ...
Pairwise distance between points in a set.
def _pdist_scipy(x, exponent=1): """Pairwise distance between points in a set.""" metric = 'euclidean' if exponent != 1: metric = 'sqeuclidean' distances = _spatial.distance.pdist(x, metric=metric) distances = _spatial.distance.squareform(distances) if exponent != 1: distances...
Pairwise distance between the points in two sets.
def _cdist_scipy(x, y, exponent=1): """Pairwise distance between the points in two sets.""" metric = 'euclidean' if exponent != 1: metric = 'sqeuclidean' distances = _spatial.distance.cdist(x, y, metric=metric) if exponent != 1: distances **= exponent / 2 return distances
Pairwise distance between points in a set.
def _pdist(x, exponent=1): """ Pairwise distance between points in a set. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double. """ if _can_be_double(x): return _pdist_scipy(x, exponent) ...
Pairwise distance between points in two sets.
def _cdist(x, y, exponent=1): """ Pairwise distance between points in two sets. As Scipy converts every value to double, this wrapper uses a less efficient implementation if the original dtype can not be converted to double. """ if _can_be_double(x) and _can_be_double(y): return _c...