text stringlengths 81 112k |
|---|
Embed geojson.io in an iframe in Jupyter/IPython notebook.
Parameters
----------
contents - see make_url()
width - string, default '100%' - width of the iframe
height - string / int, default 512 - height of the iframe
kwargs - additional arguments are passed to `make_url()`
def embed(contents=... |
Returns the URL to open given the domain and contents.
If the file contents are large, an anonymous gist will be created.
Parameters
----------
contents
* string - assumed to be GeoJSON
* an object that implements __geo_interface__
A FeatureCollection will be constructed wi... |
Return a GeoJSON string from a variety of inputs.
See the documentation for make_url for the possible contents
input.
Returns
-------
GeoJSON string
def make_geojson(contents):
"""
Return a GeoJSON string from a variety of inputs.
See the documentation for make_url for the possible con... |
Return the URL for embedding the GeoJSON data in the URL hash
Parameters
----------
contents - string of GeoJSON
domain - string, default http://geojson.io
def data_url(contents, domain=DEFAULT_DOMAIN):
"""
Return the URL for embedding the GeoJSON data in the URL hash
Parameters
-----... |
Create and return an anonymous gist with a single file and specified
contents
def _make_gist(contents, description='', filename='data.geojson'):
"""
Create and return an anonymous gist with a single file and specified
contents
"""
ghapi = github3.GitHub()
files = {filename: {'content': con... |
Clenshaw's algorithm for evaluating
S(t) = \\sum a_k P_k(alpha, beta)(t)
where P_k(alpha, beta) is the kth orthogonal polynomial defined by the
recurrence coefficients alpha, beta.
See <https://en.wikipedia.org/wiki/Clenshaw_algorithm> for details.
def clenshaw(a, alpha, beta, t):
"""Clenshaw's ... |
Recurrence coefficients for generalized Laguerre polynomials. Set
alpha=0 (default) to get classical Laguerre.
def tree(X, n, alpha=0, symbolic=False):
"""Recurrence coefficients for generalized Laguerre polynomials. Set
alpha=0 (default) to get classical Laguerre.
"""
args = recurrence_coefficient... |
Recurrence coefficients for generalized Laguerre polynomials.
vals_k = vals_{k-1} * (t*a_k - b_k) - vals{k-2} * c_k
def recurrence_coefficients(n, alpha, standardization="normal", symbolic=False):
"""Recurrence coefficients for generalized Laguerre polynomials.
vals_k = vals_{k-1} * (t*a_k - b_k)... |
Generate the recurrence coefficients a_k, b_k, c_k in
P_{k+1}(x) = (a_k x - b_k)*P_{k}(x) - c_k P_{k-1}(x)
for the Jacobi polynomials which are orthogonal on [-1, 1]
with respect to the weight w(x)=[(1-x)^alpha]*[(1+x)^beta]; see
<https://en.wikipedia.org/wiki/Jacobi_polynomials#Recurrence_relations>.... |
Plot function over a disk.
def plot(f, lcar=1.0e-1):
"""Plot function over a disk.
"""
import matplotlib
import matplotlib.pyplot as plt
import pygmsh
geom = pygmsh.built_in.Geometry()
geom.add_circle([0.0, 0.0, 0.0], 1.0, lcar, num_sections=4, compound=True)
points, cells, _, _, _ = p... |
Evaluates the entire tree of orthogonal polynomials for the n-cube
The computation is organized such that tree returns a list of arrays, L={0,
..., dim}, where each level corresponds to the polynomial degree L.
Further, each level is organized like a discrete (dim-1)-dimensional
simplex. Let's demonstr... |
Evaluate the orthogonal polynomial defined by its recurrence coefficients
a, b, and c at the point(s) t.
def line_evaluate(t, p0, a, b, c):
"""Evaluate the orthogonal polynomial defined by its recurrence coefficients
a, b, and c at the point(s) t.
"""
vals1 = numpy.zeros_like(t, dtype=int)
# Th... |
Plot function over a triangle.
def plot(corners, f, n=100):
"""Plot function over a triangle.
"""
import matplotlib.tri
import matplotlib.pyplot as plt
# discretization points
def partition(boxes, balls):
# <https://stackoverflow.com/a/36748940/353337>
def rec(boxes, balls, par... |
Case-insensitive search for `key` within keys of `lookup_dict`.
def _iget(key, lookup_dict):
"""
Case-insensitive search for `key` within keys of `lookup_dict`.
"""
for k, v in lookup_dict.items():
if k.lower() == key.lower():
return v
return None |
Try to lookup a Language object by name, e.g. 'English', in internal language list.
Returns None if lookup by language name fails in resources/languagelookup.json.
def getlang_by_name(name):
"""
Try to lookup a Language object by name, e.g. 'English', in internal language list.
Returns None if lookup b... |
Try to lookup a Language object by native_name, e.g. 'English', in internal language list.
Returns None if lookup by language name fails in resources/languagelookup.json.
def getlang_by_native_name(native_name):
"""
Try to lookup a Language object by native_name, e.g. 'English', in internal language list.
... |
Lookup a Language object for language code `code` based on these strategies:
- Special case rules for Hebrew and Chinese Hans/Hant scripts
- Using `alpha_2` lookup in `pycountry.languages` followed by lookup for a
language with the same `name` in the internal representaion
Returns `None` if no m... |
Write a function `f` defined in terms of spherical coordinates to a file.
def write(filename, f):
"""Write a function `f` defined in terms of spherical coordinates to a file.
"""
import meshio
import meshzoo
points, cells = meshzoo.iso_sphere(5)
# get spherical coordinates from points
pola... |
Evaluate all spherical harmonics of degree at most `n` at angles `polar`,
`azimuthal`.
def tree_sph(polar, azimuthal, n, standardization, symbolic=False):
"""Evaluate all spherical harmonics of degree at most `n` at angles `polar`,
`azimuthal`.
"""
cos = numpy.vectorize(sympy.cos) if symbolic else ... |
Evaluates the entire tree of associated Legendre polynomials up to depth
n.
There are many recurrence relations that can be used to construct the
associated Legendre polynomials. However, only few are numerically stable.
Many implementations (including this one) use the classical Legendre
recurrence... |
Evaluates the entire tree of orthogonal polynomials on the unit disk.
The return value is a list of arrays, where `out[k]` hosts the `2*k+1`
values of the `k`th level of the tree
(0, 0)
(0, 1) (1, 1)
(0, 2) (1, 2) (2, 2)
... ... ...
def tree(X, n, symbolic=Fa... |
Evaluates the entire tree of orthogonal triangle polynomials.
The return value is a list of arrays, where `out[k]` hosts the `2*k+1`
values of the `k`th level of the tree
(0, 0)
(0, 1) (1, 1)
(0, 2) (1, 2) (2, 2)
... ... ...
For reference, see
Abedal... |
Check if this file exist and if it's a directory
This function will check if the given filename
actually exists and if it's not a Directory
Arguments:
filename {string} -- filename
Return:
True : if it's not a directory and if this file exist
False : If it's not a file and if... |
Handle the command line call
keyword arguments:
cmd = a list
return
0 if error
or a string for the command line output
def command_line(cmd):
"""Handle the command line call
keyword arguments:
cmd = a list
return
0 if error
or a string for the command line output
"""... |
Returns the file exif
def information(filename):
"""Returns the file exif"""
check_if_this_file_exist(filename)
filename = os.path.abspath(filename)
result = get_json(filename)
result = result[0]
return result |
Return a json value of the exif
Get a filename and return a JSON object
Arguments:
filename {string} -- your filename
Returns:
[JSON] -- Return a JSON object
def get_json(filename):
""" Return a json value of the exif
Get a filename and return a JSON object
Arguments:
... |
Return a csv representation of the exif
get a filename and returns a unicode string with a CSV format
Arguments:
filename {string} -- your filename
Returns:
[unicode] -- unicode string
def get_csv(filename):
""" Return a csv representation of the exif
get a filename and returns ... |
Header
This function will output a message in a header
Keyword Arguments:
message {str} -- [the message string] (default: {"-"})
def print_a_header(message="-"):
"""Header
This function will output a message in a header
Keyword Arguments:
message {str} -- [the message string] (d... |
Requirements
This function will check if Exiftool is installed
on your system
Return: True if Exiftool is Installed
False if not
def check_if_exiftool_is_already_installed():
"""Requirements
This function will check if Exiftool is installed
on your system
Return: True if Exi... |
Render email with provided context
Arguments
---------
context : dict
|context| If not specified then the
:attr:`~mail_templated.EmailMessage.context` property is
used.
Keyword Arguments
-----------------
clean : bool
If `... |
Send email message, render if it is not rendered yet.
Note
----
Any extra arguments are passed to
:class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`.
Keyword Arguments
-----------------
clean : bool
If ``True``, remove any templat... |
Easy wrapper for sending a single email message to a recipient list using
django template system.
It works almost the same way as the standard
:func:`send_mail()<django.core.mail.send_mail>` function.
.. |main_difference| replace:: The main
difference is that two first arguments ``subject`` an... |
Compute the mean Silhouette Coefficient of all samples.
The Silhouette Coefficient is calculated using the mean intra-cluster
distance (``a``) and the mean nearest-cluster distance (``b``) for each
sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a,
b)``. To clarify, ``b`` is the di... |
Compute the Silhouette Coefficient for each sample.
The Silhouette Coefficient is a measure of how well samples are clustered
with samples that are similar to themselves. Clustering models with a high
Silhouette Coefficient are said to be dense, where samples in the same
cluster are similar to each oth... |
Compute the Calinski and Harabaz score.
The score is defined as ratio between the within-cluster dispersion and
the between-cluster dispersion.
Read more in the :ref:`User Guide <calinski_harabaz_index>`.
Parameters
----------
X : array-like, shape (``n_samples``, ``n_features``)
List... |
Makes sure that whenever scale is zero, we handle it correctly.
This happens in most scalers when we have constant features.
Adapted from sklearn.preprocessing.data
def handle_zeros_in_scale(scale, copy=True):
''' Makes sure that whenever scale is zero, we handle it correctly.
This happens in most scal... |
Compute joint probabilities p_ij from distances.
Parameters
----------
distances : array, shape (n_samples * (n_samples-1) / 2,)
Distances of samples are stored as condensed matrices, i.e.
we omit the diagonal and duplicate entries and store everything
in a one-dimensional array.
... |
Compute joint probabilities p_ij from distances using just nearest
neighbors.
This method is approximately equal to _joint_probabilities. The latter
is O(N), but limiting the joint probability to nearest neighbors improves
this substantially to O(uN).
Parameters
----------
distances : arra... |
t-SNE objective function: gradient of the KL divergence
of p_ijs and q_ijs and the absolute error.
Parameters
----------
params : array, shape (n_params,)
Unraveled embedding.
P : array, shape (n_samples * (n_samples-1) / 2,)
Condensed joint probability matrix.
degrees_of_free... |
t-SNE objective function: KL divergence of p_ijs and q_ijs.
Uses Barnes-Hut tree methods to calculate the gradient that
runs in O(NlogN) instead of O(N^2)
Parameters
----------
params : array, shape (n_params,)
Unraveled embedding.
P : csr sparse matrix, shape (n_samples, n_sample)
... |
Batch gradient descent with momentum and individual gains.
Parameters
----------
objective : function or callable
Should return a tuple of cost and gradient for a given parameter
vector. When expensive to compute, the cost can optionally
be None and can be computed every n_iter_chec... |
Expresses to what extent the local structure is retained.
The trustworthiness is within [0, 1]. It is defined as
.. math::
T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1}
\sum_{j \in U^{(k)}_i} (r(i, j) - k)
where :math:`r(i, j)` is the rank of the embedded datapoint j
accordi... |
Fit the model using X as training data.
Note that sparse arrays can only be handled by method='exact'.
It is recommended that you convert your sparse array to dense
(e.g. `X.toarray()`) if it fits in memory, or otherwise using a
dimensionality reduction technique (e.g. TruncatedSVD).
... |
Runs t-SNE.
def _tsne(self, P, degrees_of_freedom, n_samples, random_state, X_embedded,
neighbors=None, skip_num_points=0):
"""Runs t-SNE."""
# t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P
# and the Student's t-distributions Q. The optimization algorithm that
... |
Fit X into an embedded space and return that transformed
output.
Parameters
----------
X : array, shape (n_samples, n_features) or (n_samples, n_samples)
If the metric is 'precomputed' X must be a square distance
matrix. Otherwise it contains a sample per row.
... |
Integrate and batch correct a list of data sets.
Parameters
----------
datasets_full : `list` of `scipy.sparse.csr_matrix` or of `numpy.ndarray`
Data sets to integrate and correct.
genes_list: `list` of `list` of `string`
List of genes for each data set.
return_dimred: `bool`, optio... |
Integrate a list of data sets.
Parameters
----------
datasets_full : `list` of `scipy.sparse.csr_matrix` or of `numpy.ndarray`
Data sets to integrate and correct.
genes_list: `list` of `list` of `string`
List of genes for each data set.
batch_size: `int`, optional (default: `5000`)
... |
Batch correct a list of `scanpy.api.AnnData`.
Parameters
----------
adatas : `list` of `scanpy.api.AnnData`
Data sets to integrate and/or correct.
kwargs : `dict`
See documentation for the `correct()` method for a full list of
parameters to use for batch correction.
Returns... |
Integrate a list of `scanpy.api.AnnData`.
Parameters
----------
adatas : `list` of `scanpy.api.AnnData`
Data sets to integrate.
kwargs : `dict`
See documentation for the `integrate()` method for a full list of
parameters to use for batch correction.
Returns
-------
... |
Augment a knot vector.
Parameters:
knots:
Python list or rank-1 array, the original knot vector (without endpoint repeats)
order:
int, >= 0, order of spline
Returns:
list_of_knots:
rank-1 array that has (`order` + 1) copies of ``knots[0]``, then ``knots[1:-1]``, and finally (`order... |
Compute the running average of `k` successive elements of `t`. Return the averaged array.
Parameters:
t:
Python list or rank-1 array
k:
int, >= 2, how many successive elements to average
Returns:
rank-1 array, averaged data. If k > len(t), returns a zero-length array.
Caveat:
This is ... |
Create an acceptable knot vector.
Minimal emulation of MATLAB's ``aptknt``.
The returned knot vector can be used to generate splines of desired `order`
that are suitable for interpolation to the collocation sites `tau`.
Note that this is only possible when ``len(tau)`` >= `order` + 1.
When this condition does not h... |
Count multiplicities of elements in a sorted list or rank-1 array.
Minimal emulation of MATLAB's ``knt2mlt``.
Parameters:
t:
Python list or rank-1 array. Must be sorted!
Returns:
out
rank-1 array such that
out[k] = #{ t[i] == t[k] for i < k }
Example:
If ``t = [1, 1, 2, 3, 3, 3]`... |
Return collocation matrix.
Minimal emulation of MATLAB's ``spcol``.
Parameters:
knots:
rank-1 array, knot vector (with appropriately repeated endpoints; see `augknt`, `aptknt`)
order:
int, >= 0, order of spline
tau:
rank-1 array, collocation sites
Returns:
rank-2 array A such ... |
Order zero basis (for internal use).
def __basis0(self, xi):
"""Order zero basis (for internal use)."""
return np.where(np.all([self.knot_vector[:-1] <= xi,
xi < self.knot_vector[1:]],axis=0), 1.0, 0.0) |
Recursive Cox - de Boor function (for internal use).
Compute basis functions and optionally their first derivatives.
def __basis(self, xi, p, compute_derivatives=False):
"""Recursive Cox - de Boor function (for internal use).
Compute basis functions and optionally their first derivatives.
... |
Convenience function to compute first derivative of basis functions. 'Memoized' for speed.
def d(self, xi):
"""Convenience function to compute first derivative of basis functions. 'Memoized' for speed."""
return self.__basis(xi, self.p, compute_derivatives=True) |
Plot basis functions over full range of knots.
Convenience function. Requires matplotlib.
def plot(self):
"""Plot basis functions over full range of knots.
Convenience function. Requires matplotlib.
"""
try:
import matplotlib.pyplot as plt
except ImportErr... |
Differentiate a B-spline once, and return the resulting coefficients and Bspline objects.
This preserves the Bspline object nature of the data, enabling recursive implementation
of higher-order differentiation (see `diff`).
The value of the first derivative of `B` at a point `x` can be obtained as::
def diff1(B,... |
Differentiate a B-spline `order` number of times.
Parameters:
order:
int, >= 0
Returns:
**lambda** `x`: ... that evaluates the `order`-th derivative of `B` at the point `x`.
The returned function internally uses __call__, which is 'memoized' for speed.
def diff(self, order=1):
... |
Compute collocation matrix.
Parameters:
tau:
Python list or rank-1 array, collocation sites
deriv_order:
int, >=0, order of derivative for which to compute the collocation matrix.
The default is 0, which means the function value itself.
Returns:
A:
if len(tau) > 1, rank-2 a... |
Create new dictionary from INTERFACES hashed by method then
the endpoints name. For use when using the disqusapi by the
method interface instead of the endpoint interface. For
instance:
'blacklists': {
'add': {
'formats': ['json', 'jsonp'],
'method': 'POST',
... |
Returns a normalized request string as described iN OAuth2 MAC spec.
http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.3.1
def get_normalized_request_string(method, url, nonce, params, ext='', body_hash=None):
"""
Returns a normalized request string as described iN OAuth2 MAC spec.
... |
Returns BASE64 ( HASH (text) ) as described in OAuth2 MAC spec.
http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.2
def get_body_hash(params):
"""
Returns BASE64 ( HASH (text) ) as described in OAuth2 MAC spec.
http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.2
... |
Returns HMAC-SHA1 (api secret, normalized request string)
def get_mac_signature(api_secret, norm_request_string):
"""
Returns HMAC-SHA1 (api secret, normalized request string)
"""
hashed = hmac.new(str(api_secret), norm_request_string, hashlib.sha1)
return binascii.b2a_base64(hashed.digest())[:-1] |
input: filename and path.
output: file contents.
def open_file(self, access_mode="r"):
"""
input: filename and path.
output: file contents.
"""
try:
with open(self, access_mode, encoding='utf-8') as file:
return file.read()
... |
Estimation step: Runs the forward-back algorithm on trajectory with index itraj
Parameters
----------
itraj : int
index of the observation trajectory to process
Results
-------
logprob : float
The probability to observe the observation sequence g... |
Maximization step: Updates the HMM model given the hidden state assignment and count matrices
Parameters
----------
gamma : [ ndarray(T,N, dtype=float) ]
list of state probabilities for each trajectory
count_matrix : [ ndarray(N,N, dtype=float) ]
list of the Baum... |
Computes the viterbi paths using the current HMM model
def compute_viterbi_paths(self):
"""
Computes the viterbi paths using the current HMM model
"""
# get parameters
K = len(self._observations)
A = self._hmm.transition_matrix
pi = self._hmm.initial_distributio... |
Maximum-likelihood estimation of the HMM using the Baum-Welch algorithm
Returns
-------
model : HMM
The maximum likelihood HMM model.
def fit(self):
"""
Maximum-likelihood estimation of the HMM using the Baum-Welch algorithm
Returns
-------
... |
Generate random samples from a Gaussian distribution.
Parameters
----------
mean : array_like, shape (n_features,)
Mean of the distribution.
covar : array_like, optional
Covariance of the distribution. The shape depends on `covariance_type`:
scalar if 'spherical',
... |
Performing the covariance M step for diagonal cases
def _covar_mstep_diag(gmm, X, responsibilities, weighted_X_sum, norm,
min_covar):
"""Performing the covariance M step for diagonal cases"""
avg_X2 = np.dot(responsibilities.T, X * X) * norm
avg_means2 = gmm.means_ ** 2
avg_X_mean... |
Performing the covariance M step for spherical cases
def _covar_mstep_spherical(*args):
"""Performing the covariance M step for spherical cases"""
cv = _covar_mstep_diag(*args)
return np.tile(cv.mean(axis=1)[:, np.newaxis], (1, cv.shape[1])) |
Performing the covariance M step for full cases
def _covar_mstep_full(gmm, X, responsibilities, weighted_X_sum, norm,
min_covar):
"""Performing the covariance M step for full cases"""
# Eq. 12 from K. Murphy, "Fitting a Conditional Linear Gaussian
# Distribution"
n_features = X.sh... |
Covariance parameters for each mixture component.
The shape depends on `cvtype`::
(`n_states`, 'n_features') if 'spherical',
(`n_features`, `n_features`) if 'tied',
(`n_states`, `n_features`) if 'diag',
(`n_states`, `n_f... |
Provide values for covariance
def _set_covars(self, covars):
"""Provide values for covariance"""
covars = np.asarray(covars)
_validate_covars(covars, self.covariance_type, self.n_components)
self.covars_ = covars |
Return the per-sample likelihood of the data under the model.
Compute the log probability of X under the model and
return the posterior distribution (responsibilities) of each
mixture component for each element of X.
Parameters
----------
X: array_like, shape (n_samples... |
Compute the log probability under the model.
Parameters
----------
X : array_like, shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single data point.
Returns
-------
logprob : array_like, shape... |
Predict label for data.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = (n_samples,)
def predict(self, X):
"""Predict label for data.
Parameters
----------
X : array-like, shape =... |
Generate random samples from the model.
Parameters
----------
n_samples : int, optional
Number of samples to generate. Defaults to 1.
Returns
-------
X : array_like, shape (n_samples, n_features)
List of samples
def sample(self, n_samples=1, ran... |
Estimate model parameters with the expectation-maximization
algorithm.
A initialization step is performed before entering the em
algorithm. If you want to avoid this step, set the keyword
argument init_params to the empty string '' when creating the
GMM object. Likewise, if you ... |
Perform the Mstep of the EM algorithm and return the class weihgts.
def _do_mstep(self, X, responsibilities, params, min_covar=0):
""" Perform the Mstep of the EM algorithm and return the class weihgts.
"""
weights = responsibilities.sum(axis=0)
weighted_X_sum = np.dot(responsibilities.... |
Return the number of free parameters in the model.
def _n_parameters(self):
"""Return the number of free parameters in the model."""
ndim = self.means_.shape[1]
if self.covariance_type == 'full':
cov_params = self.n_components * ndim * (ndim + 1) / 2.
elif self.covariance_ty... |
Bayesian information criterion for the current model fit
and the proposed data
Parameters
----------
X : array of shape(n_samples, n_dimensions)
Returns
-------
bic: float (the lower the better)
def bic(self, X):
"""Bayesian information criterion for th... |
Get parameter names for the estimator
def _get_param_names(cls):
"""Get parameter names for the estimator"""
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
if init is obje... |
Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects
(such as pipelines). The former have parameters of the form
``<component>__<parameter>`` so that it's possible to update each
component of a nested object.
Returns
-... |
Generate an initial model with 1D-Gaussian output densities
Parameters
----------
observations : list of ndarray((T_i), dtype=float)
list of arrays of length T_i with observation data
nstates : int
The number of states.
Examples
--------
Generate initial model for a gaussi... |
Returns the output probability for symbol o from all hidden states
Parameters
----------
o : float
A single observation.
Return
------
p_o : ndarray (N)
p_o[i] is the probability density of the observation o from state i emission distribution
... |
Returns the output probabilities for an entire trajectory and all hidden states
Parameters
----------
oobs : ndarray((T), dtype=int)
a discrete trajectory of length T
Return
------
p_o : ndarray (T,N)
the probability of generating the symbol at t... |
Fits the output model given the observations and weights
Parameters
----------
observations : [ ndarray(T_k,) ] with K elements
A list of K observation trajectories, each having length T_k and d dimensions
weights : [ ndarray(T_k,nstates) ] with K elements
A list... |
Sample a new set of distribution parameters given a sample of observations from the given state.
Both the internal parameters and the attached HMM model are updated.
Parameters
----------
observations : [ numpy.array with shape (N_k,) ] with `nstates` elements
observations... |
Generate a single synthetic observation data from a given state.
Parameters
----------
state_index : int
Index of the state from which observations are to be generated.
Returns
-------
observation : float
A single observation from the given state... |
Generate synthetic observation data from a given state.
Parameters
----------
state_index : int
Index of the state from which observations are to be generated.
nobs : int
The number of observations to generate.
Returns
-------
observation... |
Generate synthetic observation data from a given state sequence.
Parameters
----------
s_t : numpy.array with shape (T,) of int type
s_t[t] is the hidden state sampled at time t
Returns
-------
o_t : numpy.array with shape (T,) of type dtype
o_t[... |
r""" Samples of the initial distribution
def initial_distribution_samples(self):
r""" Samples of the initial distribution """
res = np.empty((self.nsamples, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :] = self._sampled_hmms[i].stationary_distribution
... |
r""" Samples of the transition matrix
def transition_matrix_samples(self):
r""" Samples of the transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :, :] = self._sampled_hmms[i].transition_matrix
... |
r""" Samples of the eigenvalues
def eigenvalues_samples(self):
r""" Samples of the eigenvalues """
res = np.empty((self.nsamples, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :] = self._sampled_hmms[i].eigenvalues
return res |
r""" Samples of the left eigenvectors of the hidden transition matrix
def eigenvectors_left_samples(self):
r""" Samples of the left eigenvectors of the hidden transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
... |
r""" Samples of the right eigenvectors of the hidden transition matrix
def eigenvectors_right_samples(self):
r""" Samples of the right eigenvectors of the hidden transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
... |
r""" Samples of the timescales
def timescales_samples(self):
r""" Samples of the timescales """
res = np.empty((self.nsamples, self.nstates-1), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :] = self._sampled_hmms[i].timescales
return res |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.