repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
jwass/geojsonio.py
geojsonio/geojsonio.py
embed
def embed(contents='', width='100%', height=512, *args, **kwargs): """ 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 ...
python
def embed(contents='', width='100%', height=512, *args, **kwargs): """ 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 ...
[ "def", "embed", "(", "contents", "=", "''", ",", "width", "=", "'100%'", ",", "height", "=", "512", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "IPython", ".", "display", "import", "HTML", "url", "=", "make_url", "(", "contents", "...
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()`
[ "Embed", "geojson", ".", "io", "in", "an", "iframe", "in", "Jupyter", "/", "IPython", "notebook", "." ]
8229a48238f128837e6dce49f18310df84968825
https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L43-L60
train
jwass/geojsonio.py
geojsonio/geojsonio.py
make_url
def make_url(contents, domain=DEFAULT_DOMAIN, force_gist=False, size_for_gist=MAX_URL_LEN): """ 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...
python
def make_url(contents, domain=DEFAULT_DOMAIN, force_gist=False, size_for_gist=MAX_URL_LEN): """ 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...
[ "def", "make_url", "(", "contents", ",", "domain", "=", "DEFAULT_DOMAIN", ",", "force_gist", "=", "False", ",", "size_for_gist", "=", "MAX_URL_LEN", ")", ":", "contents", "=", "make_geojson", "(", "contents", ")", "if", "len", "(", "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...
[ "Returns", "the", "URL", "to", "open", "given", "the", "domain", "and", "contents", "." ]
8229a48238f128837e6dce49f18310df84968825
https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L63-L96
train
jwass/geojsonio.py
geojsonio/geojsonio.py
make_geojson
def make_geojson(contents): """ Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string """ if isinstance(contents, six.string_types): return contents if hasattr(contents, '__g...
python
def make_geojson(contents): """ Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string """ if isinstance(contents, six.string_types): return contents if hasattr(contents, '__g...
[ "def", "make_geojson", "(", "contents", ")", ":", "if", "isinstance", "(", "contents", ",", "six", ".", "string_types", ")", ":", "return", "contents", "if", "hasattr", "(", "contents", ",", "'__geo_interface__'", ")", ":", "features", "=", "[", "_geo_to_fea...
Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string
[ "Return", "a", "GeoJSON", "string", "from", "a", "variety", "of", "inputs", ".", "See", "the", "documentation", "for", "make_url", "for", "the", "possible", "contents", "input", "." ]
8229a48238f128837e6dce49f18310df84968825
https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L99-L128
train
jwass/geojsonio.py
geojsonio/geojsonio.py
data_url
def data_url(contents, domain=DEFAULT_DOMAIN): """ Return the URL for embedding the GeoJSON data in the URL hash Parameters ---------- contents - string of GeoJSON domain - string, default http://geojson.io """ url = (domain + '#data=data:application/json,' + urllib.parse.qu...
python
def data_url(contents, domain=DEFAULT_DOMAIN): """ Return the URL for embedding the GeoJSON data in the URL hash Parameters ---------- contents - string of GeoJSON domain - string, default http://geojson.io """ url = (domain + '#data=data:application/json,' + urllib.parse.qu...
[ "def", "data_url", "(", "contents", ",", "domain", "=", "DEFAULT_DOMAIN", ")", ":", "url", "=", "(", "domain", "+", "'#data=data:application/json,'", "+", "urllib", ".", "parse", ".", "quote", "(", "contents", ")", ")", "return", "url" ]
Return the URL for embedding the GeoJSON data in the URL hash Parameters ---------- contents - string of GeoJSON domain - string, default http://geojson.io
[ "Return", "the", "URL", "for", "embedding", "the", "GeoJSON", "data", "in", "the", "URL", "hash" ]
8229a48238f128837e6dce49f18310df84968825
https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L149-L161
train
jwass/geojsonio.py
geojsonio/geojsonio.py
_make_gist
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': contents}} gist = ghapi.create_gist(description, files) return gist
python
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': contents}} gist = ghapi.create_gist(description, files) return gist
[ "def", "_make_gist", "(", "contents", ",", "description", "=", "''", ",", "filename", "=", "'data.geojson'", ")", ":", "ghapi", "=", "github3", ".", "GitHub", "(", ")", "files", "=", "{", "filename", ":", "{", "'content'", ":", "contents", "}", "}", "g...
Create and return an anonymous gist with a single file and specified contents
[ "Create", "and", "return", "an", "anonymous", "gist", "with", "a", "single", "file", "and", "specified", "contents" ]
8229a48238f128837e6dce49f18310df84968825
https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L164-L174
train
nschloe/orthopy
orthopy/line_segment/tools.py
clenshaw
def clenshaw(a, alpha, beta, t): """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. """ ...
python
def clenshaw(a, alpha, beta, t): """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", ")", ":", "n", "=", "len", "(", "alpha", ")", "assert", "len", "(", "beta", ")", "==", "n", "assert", "len", "(", "a", ")", "==", "n", "+", "1", "try", ":", "b", "=", "numpy"...
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.
[ "Clenshaw", "s", "algorithm", "for", "evaluating" ]
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/line_segment/tools.py#L8-L39
train
nschloe/orthopy
orthopy/e1r/orth.py
tree
def tree(X, n, alpha=0, symbolic=False): """Recurrence coefficients for generalized Laguerre polynomials. Set alpha=0 (default) to get classical Laguerre. """ args = recurrence_coefficients(n, alpha=alpha, symbolic=symbolic) return line_tree(X, *args)
python
def tree(X, n, alpha=0, symbolic=False): """Recurrence coefficients for generalized Laguerre polynomials. Set alpha=0 (default) to get classical Laguerre. """ args = recurrence_coefficients(n, alpha=alpha, symbolic=symbolic) return line_tree(X, *args)
[ "def", "tree", "(", "X", ",", "n", ",", "alpha", "=", "0", ",", "symbolic", "=", "False", ")", ":", "args", "=", "recurrence_coefficients", "(", "n", ",", "alpha", "=", "alpha", ",", "symbolic", "=", "symbolic", ")", "return", "line_tree", "(", "X", ...
Recurrence coefficients for generalized Laguerre polynomials. Set alpha=0 (default) to get classical Laguerre.
[ "Recurrence", "coefficients", "for", "generalized", "Laguerre", "polynomials", ".", "Set", "alpha", "=", "0", "(", "default", ")", "to", "get", "classical", "Laguerre", "." ]
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/e1r/orth.py#L12-L17
train
nschloe/orthopy
orthopy/e1r/orth.py
recurrence_coefficients
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) - vals{k-2} * c_k """ S = sympy.S if symbolic else lambda x: x sqrt = sympy.sqrt if symbolic else numpy.sqrt ...
python
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) - vals{k-2} * c_k """ S = sympy.S if symbolic else lambda x: x sqrt = sympy.sqrt if symbolic else numpy.sqrt ...
[ "def", "recurrence_coefficients", "(", "n", ",", "alpha", ",", "standardization", "=", "\"normal\"", ",", "symbolic", "=", "False", ")", ":", "S", "=", "sympy", ".", "S", "if", "symbolic", "else", "lambda", "x", ":", "x", "sqrt", "=", "sympy", ".", "sq...
Recurrence coefficients for generalized Laguerre polynomials. vals_k = vals_{k-1} * (t*a_k - b_k) - vals{k-2} * c_k
[ "Recurrence", "coefficients", "for", "generalized", "Laguerre", "polynomials", "." ]
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/e1r/orth.py#L20-L53
train
nschloe/orthopy
orthopy/line_segment/recurrence_coefficients.py
jacobi
def jacobi(n, alpha, beta, standardization, symbolic=False): """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 <htt...
python
def jacobi(n, alpha, beta, standardization, symbolic=False): """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 <htt...
[ "def", "jacobi", "(", "n", ",", "alpha", ",", "beta", ",", "standardization", ",", "symbolic", "=", "False", ")", ":", "gamma", "=", "sympy", ".", "gamma", "if", "symbolic", "else", "lambda", "x", ":", "scipy", ".", "special", ".", "gamma", "(", "flo...
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>.
[ "Generate", "the", "recurrence", "coefficients", "a_k", "b_k", "c_k", "in" ]
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/line_segment/recurrence_coefficients.py#L28-L211
train
nschloe/orthopy
orthopy/disk/tools.py
plot
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, _, _, _ = pygmsh.generate_mesh(geom, ve...
python
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, _, _, _ = pygmsh.generate_mesh(geom, ve...
[ "def", "plot", "(", "f", ",", "lcar", "=", "1.0e-1", ")", ":", "import", "matplotlib", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "pygmsh", "geom", "=", "pygmsh", ".", "built_in", ".", "Geometry", "(", ")", "geom", ".", "add_circle", ...
Plot function over a disk.
[ "Plot", "function", "over", "a", "disk", "." ]
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/disk/tools.py#L13-L45
train
nschloe/orthopy
orthopy/ncube/orth.py
tree
def tree(X, n, symbolic=False): """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)-...
python
def tree(X, n, symbolic=False): """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)-...
[ "def", "tree", "(", "X", ",", "n", ",", "symbolic", "=", "False", ")", ":", "p0", ",", "a", ",", "b", ",", "c", "=", "legendre", "(", "n", "+", "1", ",", "\"normal\"", ",", "symbolic", "=", "symbolic", ")", "dim", "=", "X", ".", "shape", "[",...
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...
[ "Evaluates", "the", "entire", "tree", "of", "orthogonal", "polynomials", "for", "the", "n", "-", "cube" ]
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/ncube/orth.py#L11-L76
train
nschloe/orthopy
orthopy/tools.py
line_evaluate
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) # The order is important here; see # <https://github.com/sympy/sympy/issues/13637>. vals2 = numpy.ones_lik...
python
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) # The order is important here; see # <https://github.com/sympy/sympy/issues/13637>. vals2 = numpy.ones_lik...
[ "def", "line_evaluate", "(", "t", ",", "p0", ",", "a", ",", "b", ",", "c", ")", ":", "vals1", "=", "numpy", ".", "zeros_like", "(", "t", ",", "dtype", "=", "int", ")", "# The order is important here; see", "# <https://github.com/sympy/sympy/issues/13637>.", "v...
Evaluate the orthogonal polynomial defined by its recurrence coefficients a, b, and c at the point(s) t.
[ "Evaluate", "the", "orthogonal", "polynomial", "defined", "by", "its", "recurrence", "coefficients", "a", "b", "and", "c", "at", "the", "point", "(", "s", ")", "t", "." ]
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/tools.py#L21-L33
train
nschloe/orthopy
orthopy/triangle/tools.py
plot
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, parent=tuple()): if box...
python
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, parent=tuple()): if box...
[ "def", "plot", "(", "corners", ",", "f", ",", "n", "=", "100", ")", ":", "import", "matplotlib", ".", "tri", "import", "matplotlib", ".", "pyplot", "as", "plt", "# discretization points", "def", "partition", "(", "boxes", ",", "balls", ")", ":", "# <http...
Plot function over a triangle.
[ "Plot", "function", "over", "a", "triangle", "." ]
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/triangle/tools.py#L16-L63
train
learningequality/le-utils
le_utils/constants/languages.py
_iget
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
python
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
[ "def", "_iget", "(", "key", ",", "lookup_dict", ")", ":", "for", "k", ",", "v", "in", "lookup_dict", ".", "items", "(", ")", ":", "if", "k", ".", "lower", "(", ")", "==", "key", ".", "lower", "(", ")", ":", "return", "v", "return", "None" ]
Case-insensitive search for `key` within keys of `lookup_dict`.
[ "Case", "-", "insensitive", "search", "for", "key", "within", "keys", "of", "lookup_dict", "." ]
07a776e3d5c288818764a25170de2e9ec5850c0d
https://github.com/learningequality/le-utils/blob/07a776e3d5c288818764a25170de2e9ec5850c0d/le_utils/constants/languages.py#L83-L90
train
learningequality/le-utils
le_utils/constants/languages.py
getlang_by_name
def getlang_by_name(name): """ 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. """ direct_match = _iget(name, _LANGUAGE_NAME_LOOKUP) if direct_match: return direct_match ...
python
def getlang_by_name(name): """ 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. """ direct_match = _iget(name, _LANGUAGE_NAME_LOOKUP) if direct_match: return direct_match ...
[ "def", "getlang_by_name", "(", "name", ")", ":", "direct_match", "=", "_iget", "(", "name", ",", "_LANGUAGE_NAME_LOOKUP", ")", "if", "direct_match", ":", "return", "direct_match", "else", ":", "simple_name", "=", "name", ".", "split", "(", "','", ")", "[", ...
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.
[ "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", ".", ...
07a776e3d5c288818764a25170de2e9ec5850c0d
https://github.com/learningequality/le-utils/blob/07a776e3d5c288818764a25170de2e9ec5850c0d/le_utils/constants/languages.py#L146-L157
train
learningequality/le-utils
le_utils/constants/languages.py
getlang_by_native_name
def getlang_by_native_name(native_name): """ 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. """ direct_match = _iget(native_name, _LANGUAGE_NATIVE_NAME_LOOKUP) if direct_ma...
python
def getlang_by_native_name(native_name): """ 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. """ direct_match = _iget(native_name, _LANGUAGE_NATIVE_NAME_LOOKUP) if direct_ma...
[ "def", "getlang_by_native_name", "(", "native_name", ")", ":", "direct_match", "=", "_iget", "(", "native_name", ",", "_LANGUAGE_NATIVE_NAME_LOOKUP", ")", "if", "direct_match", ":", "return", "direct_match", "else", ":", "simple_native_name", "=", "native_name", ".", ...
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.
[ "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", ...
07a776e3d5c288818764a25170de2e9ec5850c0d
https://github.com/learningequality/le-utils/blob/07a776e3d5c288818764a25170de2e9ec5850c0d/le_utils/constants/languages.py#L185-L196
train
learningequality/le-utils
le_utils/constants/languages.py
getlang_by_alpha2
def getlang_by_alpha2(code): """ 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...
python
def getlang_by_alpha2(code): """ 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...
[ "def", "getlang_by_alpha2", "(", "code", ")", ":", "# Handle special cases for language codes returned by YouTube API", "if", "code", "==", "'iw'", ":", "# handle old Hebrew code 'iw' and return modern code 'he'", "return", "getlang", "(", "'he'", ")", "elif", "'zh-Hans'", "i...
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...
[ "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", ...
07a776e3d5c288818764a25170de2e9ec5850c0d
https://github.com/learningequality/le-utils/blob/07a776e3d5c288818764a25170de2e9ec5850c0d/le_utils/constants/languages.py#L200-L231
train
nschloe/orthopy
orthopy/sphere/tools.py
write
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 polar = numpy.arccos(points[:, 2]) azimuthal = numpy.arctan2(points[:, 1], ...
python
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 polar = numpy.arccos(points[:, 2]) azimuthal = numpy.arctan2(points[:, 1], ...
[ "def", "write", "(", "filename", ",", "f", ")", ":", "import", "meshio", "import", "meshzoo", "points", ",", "cells", "=", "meshzoo", ".", "iso_sphere", "(", "5", ")", "# get spherical coordinates from points", "polar", "=", "numpy", ".", "arccos", "(", "poi...
Write a function `f` defined in terms of spherical coordinates to a file.
[ "Write", "a", "function", "f", "defined", "in", "terms", "of", "spherical", "coordinates", "to", "a", "file", "." ]
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/sphere/tools.py#L6-L18
train
nschloe/orthopy
orthopy/sphere/orth.py
tree_sph
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 numpy.cos # Conventions from # <https://en.wikipedia.org/wiki/Spherical_harmonics#O...
python
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 numpy.cos # Conventions from # <https://en.wikipedia.org/wiki/Spherical_harmonics#O...
[ "def", "tree_sph", "(", "polar", ",", "azimuthal", ",", "n", ",", "standardization", ",", "symbolic", "=", "False", ")", ":", "cos", "=", "numpy", ".", "vectorize", "(", "sympy", ".", "cos", ")", "if", "symbolic", "else", "numpy", ".", "cos", "# Conven...
Evaluate all spherical harmonics of degree at most `n` at angles `polar`, `azimuthal`.
[ "Evaluate", "all", "spherical", "harmonics", "of", "degree", "at", "most", "n", "at", "angles", "polar", "azimuthal", "." ]
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/sphere/orth.py#L9-L33
train
nschloe/orthopy
orthopy/line_segment/orth.py
tree_alp
def tree_alp( x, n, standardization, phi=None, with_condon_shortley_phase=True, symbolic=False ): """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 ar...
python
def tree_alp( x, n, standardization, phi=None, with_condon_shortley_phase=True, symbolic=False ): """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 ar...
[ "def", "tree_alp", "(", "x", ",", "n", ",", "standardization", ",", "phi", "=", "None", ",", "with_condon_shortley_phase", "=", "True", ",", "symbolic", "=", "False", ")", ":", "# assert numpy.all(numpy.abs(x) <= 1.0)", "d", "=", "{", "\"natural\"", ":", "(", ...
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", "associated", "Legendre", "polynomials", "up", "to", "depth", "n", ".", "There", "are", "many", "recurrence", "relations", "that", "can", "be", "used", "to", "construct", "the", "associated", "Legendre", "polynomials",...
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/line_segment/orth.py#L186-L260
train
nschloe/orthopy
orthopy/disk/orth.py
tree
def tree(X, n, symbolic=False): """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) ... ....
python
def tree(X, n, symbolic=False): """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", "=", "False", ")", ":", "frac", "=", "sympy", ".", "Rational", "if", "symbolic", "else", "lambda", "x", ",", "y", ":", "x", "/", "y", "sqrt", "=", "sympy", ".", "sqrt", "if", "symbolic", "else",...
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) ... ... ...
[ "Evaluates", "the", "entire", "tree", "of", "orthogonal", "polynomials", "on", "the", "unit", "disk", "." ]
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/disk/orth.py#L9-L89
train
nschloe/orthopy
orthopy/triangle/orth.py
tree
def tree(bary, n, standardization, symbolic=False): """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) ...
python
def tree(bary, n, standardization, symbolic=False): """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) ...
[ "def", "tree", "(", "bary", ",", "n", ",", "standardization", ",", "symbolic", "=", "False", ")", ":", "S", "=", "numpy", ".", "vectorize", "(", "sympy", ".", "S", ")", "if", "symbolic", "else", "lambda", "x", ":", "x", "sqrt", "=", "numpy", ".", ...
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...
[ "Evaluates", "the", "entire", "tree", "of", "orthogonal", "triangle", "polynomials", "." ]
64713d0533b0af042810a7535fff411b8e0aea9e
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/triangle/orth.py#L9-L126
train
guinslym/pyexifinfo
pyexifinfo/pyexifinfo.py
check_if_this_file_exist
def check_if_this_file_exist(filename): """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 ...
python
def check_if_this_file_exist(filename): """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 ...
[ "def", "check_if_this_file_exist", "(", "filename", ")", ":", "#get the absolute path", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "#Boolean", "this_file_exist", "=", "os", ".", "path", ".", "exists", "(", "filename", ")", "a_dir...
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...
[ "Check", "if", "this", "file", "exist", "and", "if", "it", "s", "a", "directory" ]
56e5b44e77ee17b018a530ec858f19a9c6c07018
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/pyexifinfo/pyexifinfo.py#L17-L41
train
guinslym/pyexifinfo
pyexifinfo/pyexifinfo.py
command_line
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 """ try: s = subprocess.Popen(cmd, stdout=subprocess.PIPE) s = s.stdout.read() return s.strip() except subproce...
python
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 """ try: s = subprocess.Popen(cmd, stdout=subprocess.PIPE) s = s.stdout.read() return s.strip() except subproce...
[ "def", "command_line", "(", "cmd", ")", ":", "try", ":", "s", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "s", "=", "s", ".", "stdout", ".", "read", "(", ")", "return", "s", ".", "strip", "(", ...
Handle the command line call keyword arguments: cmd = a list return 0 if error or a string for the command line output
[ "Handle", "the", "command", "line", "call" ]
56e5b44e77ee17b018a530ec858f19a9c6c07018
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/pyexifinfo/pyexifinfo.py#L45-L62
train
guinslym/pyexifinfo
pyexifinfo/pyexifinfo.py
information
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
python
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
[ "def", "information", "(", "filename", ")", ":", "check_if_this_file_exist", "(", "filename", ")", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "result", "=", "get_json", "(", "filename", ")", "result", "=", "result", "[", "0",...
Returns the file exif
[ "Returns", "the", "file", "exif" ]
56e5b44e77ee17b018a530ec858f19a9c6c07018
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/pyexifinfo/pyexifinfo.py#L64-L70
train
guinslym/pyexifinfo
pyexifinfo/pyexifinfo.py
get_json
def get_json(filename): """ 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 """ check_if_this_file_exist(filename) #Process this function filename = os.path.a...
python
def get_json(filename): """ 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 """ check_if_this_file_exist(filename) #Process this function filename = os.path.a...
[ "def", "get_json", "(", "filename", ")", ":", "check_if_this_file_exist", "(", "filename", ")", "#Process this function", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "s", "=", "command_line", "(", "[", "'exiftool'", ",", "'-G'", ...
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
[ "Return", "a", "json", "value", "of", "the", "exif" ]
56e5b44e77ee17b018a530ec858f19a9c6c07018
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/pyexifinfo/pyexifinfo.py#L100-L121
train
guinslym/pyexifinfo
pyexifinfo/pyexifinfo.py
get_csv
def get_csv(filename): """ 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 """ check_if_this_file_exist(filename) #Process this functio...
python
def get_csv(filename): """ 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 """ check_if_this_file_exist(filename) #Process this functio...
[ "def", "get_csv", "(", "filename", ")", ":", "check_if_this_file_exist", "(", "filename", ")", "#Process this function", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "s", "=", "command_line", "(", "[", "'exiftool'", ",", "'-G'", ...
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
[ "Return", "a", "csv", "representation", "of", "the", "exif" ]
56e5b44e77ee17b018a530ec858f19a9c6c07018
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/pyexifinfo/pyexifinfo.py#L123-L144
train
guinslym/pyexifinfo
setup.py
print_a_header
def print_a_header(message="-"): """Header This function will output a message in a header Keyword Arguments: message {str} -- [the message string] (default: {"-"}) """ print("-".center(60,'-')) print(message.center(60,'-')) print("-".center(60,'-')) print()
python
def print_a_header(message="-"): """Header This function will output a message in a header Keyword Arguments: message {str} -- [the message string] (default: {"-"}) """ print("-".center(60,'-')) print(message.center(60,'-')) print("-".center(60,'-')) print()
[ "def", "print_a_header", "(", "message", "=", "\"-\"", ")", ":", "print", "(", "\"-\"", ".", "center", "(", "60", ",", "'-'", ")", ")", "print", "(", "message", ".", "center", "(", "60", ",", "'-'", ")", ")", "print", "(", "\"-\"", ".", "center", ...
Header This function will output a message in a header Keyword Arguments: message {str} -- [the message string] (default: {"-"})
[ "Header" ]
56e5b44e77ee17b018a530ec858f19a9c6c07018
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/setup.py#L22-L33
train
guinslym/pyexifinfo
setup.py
check_if_exiftool_is_already_installed
def check_if_exiftool_is_already_installed(): """Requirements This function will check if Exiftool is installed on your system Return: True if Exiftool is Installed False if not """ result = 1; command = ["exiftool", "-ver"] with open(os.devnull, "w") as fnull: res...
python
def check_if_exiftool_is_already_installed(): """Requirements This function will check if Exiftool is installed on your system Return: True if Exiftool is Installed False if not """ result = 1; command = ["exiftool", "-ver"] with open(os.devnull, "w") as fnull: res...
[ "def", "check_if_exiftool_is_already_installed", "(", ")", ":", "result", "=", "1", "command", "=", "[", "\"exiftool\"", ",", "\"-ver\"", "]", "with", "open", "(", "os", ".", "devnull", ",", "\"w\"", ")", "as", "fnull", ":", "result", "=", "subprocess", "....
Requirements This function will check if Exiftool is installed on your system Return: True if Exiftool is Installed False if not
[ "Requirements" ]
56e5b44e77ee17b018a530ec858f19a9c6c07018
https://github.com/guinslym/pyexifinfo/blob/56e5b44e77ee17b018a530ec858f19a9c6c07018/setup.py#L35-L59
train
artemrizhov/django-mail-templated
mail_templated/message.py
EmailMessage.render
def render(self, context=None, clean=False): """ Render email with provided context Arguments --------- context : dict |context| If not specified then the :attr:`~mail_templated.EmailMessage.context` property is used. Keyword Argument...
python
def render(self, context=None, clean=False): """ Render email with provided context Arguments --------- context : dict |context| If not specified then the :attr:`~mail_templated.EmailMessage.context` property is used. Keyword Argument...
[ "def", "render", "(", "self", ",", "context", "=", "None", ",", "clean", "=", "False", ")", ":", "# Load template if it is not loaded yet.", "if", "not", "self", ".", "template", ":", "self", ".", "load_template", "(", "self", ".", "template_name", ")", "# T...
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 `...
[ "Render", "email", "with", "provided", "context" ]
1b428e7b6e02a5cf775bc83d6f5fd8c5f56d7932
https://github.com/artemrizhov/django-mail-templated/blob/1b428e7b6e02a5cf775bc83d6f5fd8c5f56d7932/mail_templated/message.py#L153-L205
train
artemrizhov/django-mail-templated
mail_templated/message.py
EmailMessage.send
def send(self, *args, **kwargs): """ 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 ----------------- cle...
python
def send(self, *args, **kwargs): """ 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 ----------------- cle...
[ "def", "send", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "clean", "=", "kwargs", ".", "pop", "(", "'clean'", ",", "False", ")", "if", "not", "self", ".", "_is_rendered", ":", "self", ".", "render", "(", ")", "if", "clean",...
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...
[ "Send", "email", "message", "render", "if", "it", "is", "not", "rendered", "yet", "." ]
1b428e7b6e02a5cf775bc83d6f5fd8c5f56d7932
https://github.com/artemrizhov/django-mail-templated/blob/1b428e7b6e02a5cf775bc83d6f5fd8c5f56d7932/mail_templated/message.py#L207-L227
train
artemrizhov/django-mail-templated
mail_templated/utils.py
send_mail
def send_mail(template_name, context, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, **kwargs): """ Easy wrapper for sending a single email message to a recipient list using django template system. It works almost the sa...
python
def send_mail(template_name, context, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, **kwargs): """ Easy wrapper for sending a single email message to a recipient list using django template system. It works almost the sa...
[ "def", "send_mail", "(", "template_name", ",", "context", ",", "from_email", ",", "recipient_list", ",", "fail_silently", "=", "False", ",", "auth_user", "=", "None", ",", "auth_password", "=", "None", ",", "connection", "=", "None", ",", "*", "*", "kwargs",...
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...
[ "Easy", "wrapper", "for", "sending", "a", "single", "email", "message", "to", "a", "recipient", "list", "using", "django", "template", "system", "." ]
1b428e7b6e02a5cf775bc83d6f5fd8c5f56d7932
https://github.com/artemrizhov/django-mail-templated/blob/1b428e7b6e02a5cf775bc83d6f5fd8c5f56d7932/mail_templated/utils.py#L13-L93
train
brianhie/scanorama
bin/unsupervised.py
silhouette_score
def silhouette_score(X, labels, metric='euclidean', sample_size=None, random_state=None, **kwds): """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...
python
def silhouette_score(X, labels, metric='euclidean', sample_size=None, random_state=None, **kwds): """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...
[ "def", "silhouette_score", "(", "X", ",", "labels", ",", "metric", "=", "'euclidean'", ",", "sample_size", "=", "None", ",", "random_state", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "sample_size", "is", "not", "None", ":", "X", ",", "labels"...
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", "mean", "Silhouette", "Coefficient", "of", "all", "samples", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/bin/unsupervised.py#L27-L106
train
brianhie/scanorama
bin/unsupervised.py
silhouette_samples
def silhouette_samples(X, labels, metric='euclidean', **kwds): """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 b...
python
def silhouette_samples(X, labels, metric='euclidean', **kwds): """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 b...
[ "def", "silhouette_samples", "(", "X", ",", "labels", ",", "metric", "=", "'euclidean'", ",", "*", "*", "kwds", ")", ":", "X", ",", "labels", "=", "check_X_y", "(", "X", ",", "labels", ",", "accept_sparse", "=", "[", "'csc'", ",", "'csr'", "]", ")", ...
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", "Silhouette", "Coefficient", "for", "each", "sample", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/bin/unsupervised.py#L109-L213
train
brianhie/scanorama
bin/unsupervised.py
calinski_harabaz_score
def calinski_harabaz_score(X, labels): """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, shap...
python
def calinski_harabaz_score(X, labels): """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, shap...
[ "def", "calinski_harabaz_score", "(", "X", ",", "labels", ")", ":", "X", ",", "labels", "=", "check_X_y", "(", "X", ",", "labels", ")", "le", "=", "LabelEncoder", "(", ")", "labels", "=", "le", ".", "fit_transform", "(", "labels", ")", "n_samples", ","...
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...
[ "Compute", "the", "Calinski", "and", "Harabaz", "score", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/bin/unsupervised.py#L216-L263
train
brianhie/scanorama
scanorama/utils.py
handle_zeros_in_scale
def handle_zeros_in_scale(scale, copy=True): ''' 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''' # if we are fitting on 1D arrays, scale might be a scalar if np.isscalar(scale): ...
python
def handle_zeros_in_scale(scale, copy=True): ''' 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''' # if we are fitting on 1D arrays, scale might be a scalar if np.isscalar(scale): ...
[ "def", "handle_zeros_in_scale", "(", "scale", ",", "copy", "=", "True", ")", ":", "# if we are fitting on 1D arrays, scale might be a scalar", "if", "np", ".", "isscalar", "(", "scale", ")", ":", "if", "scale", "==", ".0", ":", "scale", "=", "1.", "return", "s...
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
[ "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"...
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/utils.py#L124-L139
train
brianhie/scanorama
scanorama/t_sne_approx.py
_joint_probabilities
def _joint_probabilities(distances, desired_perplexity, verbose): """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 dupl...
python
def _joint_probabilities(distances, desired_perplexity, verbose): """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 dupl...
[ "def", "_joint_probabilities", "(", "distances", ",", "desired_perplexity", ",", "verbose", ")", ":", "# Compute conditional probabilities such that they approximately match", "# the desired perplexity", "distances", "=", "distances", ".", "astype", "(", "np", ".", "float32",...
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", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L39-L68
train
brianhie/scanorama
scanorama/t_sne_approx.py
_joint_probabilities_nn
def _joint_probabilities_nn(distances, neighbors, desired_perplexity, verbose): """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 improv...
python
def _joint_probabilities_nn(distances, neighbors, desired_perplexity, verbose): """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 improv...
[ "def", "_joint_probabilities_nn", "(", "distances", ",", "neighbors", ",", "desired_perplexity", ",", "verbose", ")", ":", "t0", "=", "time", "(", ")", "# Compute conditional probabilities such that they approximately match", "# the desired perplexity", "n_samples", ",", "k...
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...
[ "Compute", "joint", "probabilities", "p_ij", "from", "distances", "using", "just", "nearest", "neighbors", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L71-L124
train
brianhie/scanorama
scanorama/t_sne_approx.py
_kl_divergence
def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components, skip_num_points=0): """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...
python
def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components, skip_num_points=0): """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...
[ "def", "_kl_divergence", "(", "params", ",", "P", ",", "degrees_of_freedom", ",", "n_samples", ",", "n_components", ",", "skip_num_points", "=", "0", ")", ":", "X_embedded", "=", "params", ".", "reshape", "(", "n_samples", ",", "n_components", ")", "# Q is a h...
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", ":", "gradient", "of", "the", "KL", "divergence", "of", "p_ijs", "and", "q_ijs", "and", "the", "absolute", "error", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L127-L189
train
brianhie/scanorama
scanorama/t_sne_approx.py
_kl_divergence_bh
def _kl_divergence_bh(params, P, degrees_of_freedom, n_samples, n_components, angle=0.5, skip_num_points=0, verbose=False): """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) ...
python
def _kl_divergence_bh(params, P, degrees_of_freedom, n_samples, n_components, angle=0.5, skip_num_points=0, verbose=False): """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) ...
[ "def", "_kl_divergence_bh", "(", "params", ",", "P", ",", "degrees_of_freedom", ",", "n_samples", ",", "n_components", ",", "angle", "=", "0.5", ",", "skip_num_points", "=", "0", ",", "verbose", "=", "False", ")", ":", "params", "=", "params", ".", "astype...
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) ...
[ "t", "-", "SNE", "objective", "function", ":", "KL", "divergence", "of", "p_ijs", "and", "q_ijs", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L192-L258
train
brianhie/scanorama
scanorama/t_sne_approx.py
_gradient_descent
def _gradient_descent(objective, p0, it, n_iter, n_iter_check=1, n_iter_without_progress=300, momentum=0.8, learning_rate=200.0, min_gain=0.01, min_grad_norm=1e-7, verbose=0, args=None, kwargs=None): """Batch gradient descent with momentum and indivi...
python
def _gradient_descent(objective, p0, it, n_iter, n_iter_check=1, n_iter_without_progress=300, momentum=0.8, learning_rate=200.0, min_gain=0.01, min_grad_norm=1e-7, verbose=0, args=None, kwargs=None): """Batch gradient descent with momentum and indivi...
[ "def", "_gradient_descent", "(", "objective", ",", "p0", ",", "it", ",", "n_iter", ",", "n_iter_check", "=", "1", ",", "n_iter_without_progress", "=", "300", ",", "momentum", "=", "0.8", ",", "learning_rate", "=", "200.0", ",", "min_gain", "=", "0.01", ","...
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...
[ "Batch", "gradient", "descent", "with", "momentum", "and", "individual", "gains", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L261-L383
train
brianhie/scanorama
scanorama/t_sne_approx.py
trustworthiness
def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False): """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) ...
python
def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False): """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) ...
[ "def", "trustworthiness", "(", "X", ",", "X_embedded", ",", "n_neighbors", "=", "5", ",", "precomputed", "=", "False", ")", ":", "if", "precomputed", ":", "dist_X", "=", "X", "else", ":", "dist_X", "=", "pairwise_distances", "(", "X", ",", "squared", "="...
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...
[ "Expresses", "to", "what", "extent", "the", "local", "structure", "is", "retained", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L386-L445
train
brianhie/scanorama
scanorama/t_sne_approx.py
TSNEApprox._fit
def _fit(self, X, skip_num_points=0): """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 dimension...
python
def _fit(self, X, skip_num_points=0): """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 dimension...
[ "def", "_fit", "(", "self", ",", "X", ",", "skip_num_points", "=", "0", ")", ":", "if", "self", ".", "method", "not", "in", "[", "'barnes_hut'", ",", "'exact'", "]", ":", "raise", "ValueError", "(", "\"'method' must be 'barnes_hut' or 'exact'\"", ")", "if", ...
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). ...
[ "Fit", "the", "model", "using", "X", "as", "training", "data", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L621-L784
train
brianhie/scanorama
scanorama/t_sne_approx.py
TSNEApprox._tsne
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 # we ...
python
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 # we ...
[ "def", "_tsne", "(", "self", ",", "P", ",", "degrees_of_freedom", ",", "n_samples", ",", "random_state", ",", "X_embedded", ",", "neighbors", "=", "None", ",", "skip_num_points", "=", "0", ")", ":", "# t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P"...
Runs t-SNE.
[ "Runs", "t", "-", "SNE", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L792-L853
train
brianhie/scanorama
scanorama/t_sne_approx.py
TSNEApprox.fit_transform
def fit_transform(self, X, y=None): """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 mat...
python
def fit_transform(self, X, y=None): """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 mat...
[ "def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "embedding", "=", "self", ".", "_fit", "(", "X", ")", "self", ".", "embedding_", "=", "embedding", "return", "self", ".", "embedding_" ]
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. ...
[ "Fit", "X", "into", "an", "embedded", "space", "and", "return", "that", "transformed", "output", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L855-L872
train
brianhie/scanorama
scanorama/scanorama.py
correct
def correct(datasets_full, genes_list, return_dimred=False, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, return_dense=False, hvg=None, union=False, geosketch=False, geosketch_max=20000): """Int...
python
def correct(datasets_full, genes_list, return_dimred=False, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, return_dense=False, hvg=None, union=False, geosketch=False, geosketch_max=20000): """Int...
[ "def", "correct", "(", "datasets_full", ",", "genes_list", ",", "return_dimred", "=", "False", ",", "batch_size", "=", "BATCH_SIZE", ",", "verbose", "=", "VERBOSE", ",", "ds_names", "=", "None", ",", "dimred", "=", "DIMRED", ",", "approx", "=", "APPROX", "...
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", "and", "batch", "correct", "a", "list", "of", "data", "sets", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L37-L111
train
brianhie/scanorama
scanorama/scanorama.py
integrate
def integrate(datasets_full, genes_list, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, geosketch=False, geosketch_max=20000, n_iter=1, union=False, hvg=None): """Integrate a list of data sets. Pa...
python
def integrate(datasets_full, genes_list, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, geosketch=False, geosketch_max=20000, n_iter=1, union=False, hvg=None): """Integrate a list of data sets. Pa...
[ "def", "integrate", "(", "datasets_full", ",", "genes_list", ",", "batch_size", "=", "BATCH_SIZE", ",", "verbose", "=", "VERBOSE", ",", "ds_names", "=", "None", ",", "dimred", "=", "DIMRED", ",", "approx", "=", "APPROX", ",", "sigma", "=", "SIGMA", ",", ...
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`) ...
[ "Integrate", "a", "list", "of", "data", "sets", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L114-L169
train
brianhie/scanorama
scanorama/scanorama.py
correct_scanpy
def correct_scanpy(adatas, **kwargs): """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 paramet...
python
def correct_scanpy(adatas, **kwargs): """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 paramet...
[ "def", "correct_scanpy", "(", "adatas", ",", "*", "*", "kwargs", ")", ":", "if", "'return_dimred'", "in", "kwargs", "and", "kwargs", "[", "'return_dimred'", "]", ":", "datasets_dimred", ",", "datasets", ",", "genes", "=", "correct", "(", "[", "adata", ".",...
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...
[ "Batch", "correct", "a", "list", "of", "scanpy", ".", "api", ".", "AnnData", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L172-L216
train
brianhie/scanorama
scanorama/scanorama.py
integrate_scanpy
def integrate_scanpy(adatas, **kwargs): """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 ...
python
def integrate_scanpy(adatas, **kwargs): """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 ...
[ "def", "integrate_scanpy", "(", "adatas", ",", "*", "*", "kwargs", ")", ":", "datasets_dimred", ",", "genes", "=", "integrate", "(", "[", "adata", ".", "X", "for", "adata", "in", "adatas", "]", ",", "[", "adata", ".", "var_names", ".", "values", "for",...
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 ------- ...
[ "Integrate", "a", "list", "of", "scanpy", ".", "api", ".", "AnnData", "." ]
57aafac87d07a8d682f57450165dd07f066ebb3c
https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L219-L242
train
johntfoster/bspline
bspline/splinelab.py
augknt
def augknt(knots, order): """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 ``k...
python
def augknt(knots, order): """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 ``k...
[ "def", "augknt", "(", "knots", ",", "order", ")", ":", "if", "isinstance", "(", "knots", ",", "np", ".", "ndarray", ")", "and", "knots", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"knots must be a list or a rank-1 array\"", ")", "knots", "="...
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...
[ "Augment", "a", "knot", "vector", "." ]
366085a665da6fe907258eafcc8032c58a0601e0
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/splinelab.py#L23-L47
train
johntfoster/bspline
bspline/splinelab.py
aveknt
def aveknt(t, k): """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 arr...
python
def aveknt(t, k): """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 arr...
[ "def", "aveknt", "(", "t", ",", "k", ")", ":", "t", "=", "np", ".", "atleast_1d", "(", "t", ")", "if", "t", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"t must be a list or a rank-1 array\"", ")", "n", "=", "t", ".", "shape", "[", "0"...
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 ...
[ "Compute", "the", "running", "average", "of", "k", "successive", "elements", "of", "t", ".", "Return", "the", "averaged", "array", "." ]
366085a665da6fe907258eafcc8032c58a0601e0
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/splinelab.py#L50-L78
train
johntfoster/bspline
bspline/splinelab.py
aptknt
def aptknt(tau, order): """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. ...
python
def aptknt(tau, order): """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. ...
[ "def", "aptknt", "(", "tau", ",", "order", ")", ":", "tau", "=", "np", ".", "atleast_1d", "(", "tau", ")", "k", "=", "order", "+", "1", "if", "tau", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"tau must be a list or a rank-1 array\"", ")"...
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...
[ "Create", "an", "acceptable", "knot", "vector", "." ]
366085a665da6fe907258eafcc8032c58a0601e0
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/splinelab.py#L81-L145
train
johntfoster/bspline
bspline/splinelab.py
knt2mlt
def knt2mlt(t): """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 ``...
python
def knt2mlt(t): """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 ``...
[ "def", "knt2mlt", "(", "t", ")", ":", "t", "=", "np", ".", "atleast_1d", "(", "t", ")", "if", "t", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "\"t must be a list or a rank-1 array\"", ")", "out", "=", "[", "]", "e", "=", "None", "for", ...
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]`...
[ "Count", "multiplicities", "of", "elements", "in", "a", "sorted", "list", "or", "rank", "-", "1", "array", "." ]
366085a665da6fe907258eafcc8032c58a0601e0
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/splinelab.py#L148-L182
train
johntfoster/bspline
bspline/splinelab.py
spcol
def spcol(knots, order, tau): """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 sit...
python
def spcol(knots, order, tau): """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 sit...
[ "def", "spcol", "(", "knots", ",", "order", ",", "tau", ")", ":", "m", "=", "knt2mlt", "(", "tau", ")", "B", "=", "bspline", ".", "Bspline", "(", "knots", ",", "order", ")", "dummy", "=", "B", "(", "0.", ")", "nbasis", "=", "len", "(", "dummy",...
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 ...
[ "Return", "collocation", "matrix", "." ]
366085a665da6fe907258eafcc8032c58a0601e0
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/splinelab.py#L185-L220
train
johntfoster/bspline
bspline/bspline.py
Bspline.__basis0
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)
python
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)
[ "def", "__basis0", "(", "self", ",", "xi", ")", ":", "return", "np", ".", "where", "(", "np", ".", "all", "(", "[", "self", ".", "knot_vector", "[", ":", "-", "1", "]", "<=", "xi", ",", "xi", "<", "self", ".", "knot_vector", "[", "1", ":", "]...
Order zero basis (for internal use).
[ "Order", "zero", "basis", "(", "for", "internal", "use", ")", "." ]
366085a665da6fe907258eafcc8032c58a0601e0
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L83-L86
train
johntfoster/bspline
bspline/bspline.py
Bspline.__basis
def __basis(self, xi, p, compute_derivatives=False): """Recursive Cox - de Boor function (for internal use). Compute basis functions and optionally their first derivatives. """ if p == 0: return self.__basis0(xi) else: basis_p_minus_1 = self.__basis(xi, ...
python
def __basis(self, xi, p, compute_derivatives=False): """Recursive Cox - de Boor function (for internal use). Compute basis functions and optionally their first derivatives. """ if p == 0: return self.__basis0(xi) else: basis_p_minus_1 = self.__basis(xi, ...
[ "def", "__basis", "(", "self", ",", "xi", ",", "p", ",", "compute_derivatives", "=", "False", ")", ":", "if", "p", "==", "0", ":", "return", "self", ".", "__basis0", "(", "xi", ")", "else", ":", "basis_p_minus_1", "=", "self", ".", "__basis", "(", ...
Recursive Cox - de Boor function (for internal use). Compute basis functions and optionally their first derivatives.
[ "Recursive", "Cox", "-", "de", "Boor", "function", "(", "for", "internal", "use", ")", "." ]
366085a665da6fe907258eafcc8032c58a0601e0
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L88-L123
train
johntfoster/bspline
bspline/bspline.py
Bspline.d
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)
python
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)
[ "def", "d", "(", "self", ",", "xi", ")", ":", "return", "self", ".", "__basis", "(", "xi", ",", "self", ".", "p", ",", "compute_derivatives", "=", "True", ")" ]
Convenience function to compute first derivative of basis functions. 'Memoized' for speed.
[ "Convenience", "function", "to", "compute", "first", "derivative", "of", "basis", "functions", ".", "Memoized", "for", "speed", "." ]
366085a665da6fe907258eafcc8032c58a0601e0
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L131-L133
train
johntfoster/bspline
bspline/bspline.py
Bspline.plot
def plot(self): """Plot basis functions over full range of knots. Convenience function. Requires matplotlib. """ try: import matplotlib.pyplot as plt except ImportError: from sys import stderr print("ERROR: matplotlib.pyplot not found, matplo...
python
def plot(self): """Plot basis functions over full range of knots. Convenience function. Requires matplotlib. """ try: import matplotlib.pyplot as plt except ImportError: from sys import stderr print("ERROR: matplotlib.pyplot not found, matplo...
[ "def", "plot", "(", "self", ")", ":", "try", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "except", "ImportError", ":", "from", "sys", "import", "stderr", "print", "(", "\"ERROR: matplotlib.pyplot not found, matplotlib must be installed to use this function\...
Plot basis functions over full range of knots. Convenience function. Requires matplotlib.
[ "Plot", "basis", "functions", "over", "full", "range", "of", "knots", "." ]
366085a665da6fe907258eafcc8032c58a0601e0
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L135-L158
train
johntfoster/bspline
bspline/bspline.py
Bspline.__diff_internal
def __diff_internal(self): """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` ...
python
def __diff_internal(self): """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` ...
[ "def", "__diff_internal", "(", "self", ")", ":", "assert", "self", ".", "p", ">", "0", ",", "\"order of Bspline must be > 0\"", "# we already handle the other case in diff()", "# https://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/B-spline/bspline-derv.html", "#", "t", "=",...
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", "once", "and", "return", "the", "resulting", "coefficients", "and", "Bspline", "objects", "." ]
366085a665da6fe907258eafcc8032c58a0601e0
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L186-L222
train
johntfoster/bspline
bspline/bspline.py
Bspline.diff
def diff(self, order=1): """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 ...
python
def diff(self, order=1): """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 ...
[ "def", "diff", "(", "self", ",", "order", "=", "1", ")", ":", "order", "=", "int", "(", "order", ")", "if", "order", "<", "0", ":", "raise", "ValueError", "(", "\"order must be >= 0, got %d\"", "%", "(", "order", ")", ")", "if", "order", "==", "0", ...
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.
[ "Differentiate", "a", "B", "-", "spline", "order", "number", "of", "times", "." ]
366085a665da6fe907258eafcc8032c58a0601e0
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L225-L262
train
johntfoster/bspline
bspline/bspline.py
Bspline.collmat
def collmat(self, tau, deriv_order=0): """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. ...
python
def collmat(self, tau, deriv_order=0): """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. ...
[ "def", "collmat", "(", "self", ",", "tau", ",", "deriv_order", "=", "0", ")", ":", "# get number of basis functions and output dtype", "dummy", "=", "self", ".", "__call__", "(", "0.", ")", "nbasis", "=", "dummy", ".", "shape", "[", "0", "]", "tau", "=", ...
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...
[ "Compute", "collocation", "matrix", "." ]
366085a665da6fe907258eafcc8032c58a0601e0
https://github.com/johntfoster/bspline/blob/366085a665da6fe907258eafcc8032c58a0601e0/bspline/bspline.py#L265-L309
train
disqus/disqus-python
disqusapi/utils.py
build_interfaces_by_method
def build_interfaces_by_method(interfaces): """ 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': ['jso...
python
def build_interfaces_by_method(interfaces): """ 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': ['jso...
[ "def", "build_interfaces_by_method", "(", "interfaces", ")", ":", "def", "traverse", "(", "block", ",", "parts", ")", ":", "try", ":", "method", "=", "block", "[", "'method'", "]", ".", "lower", "(", ")", "except", "KeyError", ":", "for", "k", ",", "v"...
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', ...
[ "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", ".",...
605f33c7b735fcb85e16041c27658fbba49d7a7b
https://github.com/disqus/disqus-python/blob/605f33c7b735fcb85e16041c27658fbba49d7a7b/disqusapi/utils.py#L8-L48
train
disqus/disqus-python
disqusapi/utils.py
get_normalized_request_string
def get_normalized_request_string(method, url, nonce, params, ext='', body_hash=None): """ 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 """ urlparts = urlparse.urlparse(url) if urlparts.query: ...
python
def get_normalized_request_string(method, url, nonce, params, ext='', body_hash=None): """ 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 """ urlparts = urlparse.urlparse(url) if urlparts.query: ...
[ "def", "get_normalized_request_string", "(", "method", ",", "url", ",", "nonce", ",", "params", ",", "ext", "=", "''", ",", "body_hash", "=", "None", ")", ":", "urlparts", "=", "urlparse", ".", "urlparse", "(", "url", ")", "if", "urlparts", ".", "query",...
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
[ "Returns", "a", "normalized", "request", "string", "as", "described", "iN", "OAuth2", "MAC", "spec", "." ]
605f33c7b735fcb85e16041c27658fbba49d7a7b
https://github.com/disqus/disqus-python/blob/605f33c7b735fcb85e16041c27658fbba49d7a7b/disqusapi/utils.py#L59-L87
train
disqus/disqus-python
disqusapi/utils.py
get_body_hash
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 """ norm_params = get_normalized_params(params) return binascii.b2a_base64(hashlib.sha1(norm_params).digest())[:-1]
python
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 """ norm_params = get_normalized_params(params) return binascii.b2a_base64(hashlib.sha1(norm_params).digest())[:-1]
[ "def", "get_body_hash", "(", "params", ")", ":", "norm_params", "=", "get_normalized_params", "(", "params", ")", "return", "binascii", ".", "b2a_base64", "(", "hashlib", ".", "sha1", "(", "norm_params", ")", ".", "digest", "(", ")", ")", "[", ":", "-", ...
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", "BASE64", "(", "HASH", "(", "text", ")", ")", "as", "described", "in", "OAuth2", "MAC", "spec", "." ]
605f33c7b735fcb85e16041c27658fbba49d7a7b
https://github.com/disqus/disqus-python/blob/605f33c7b735fcb85e16041c27658fbba49d7a7b/disqusapi/utils.py#L90-L98
train
disqus/disqus-python
disqusapi/utils.py
get_mac_signature
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]
python
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]
[ "def", "get_mac_signature", "(", "api_secret", ",", "norm_request_string", ")", ":", "hashed", "=", "hmac", ".", "new", "(", "str", "(", "api_secret", ")", ",", "norm_request_string", ",", "hashlib", ".", "sha1", ")", "return", "binascii", ".", "b2a_base64", ...
Returns HMAC-SHA1 (api secret, normalized request string)
[ "Returns", "HMAC", "-", "SHA1", "(", "api", "secret", "normalized", "request", "string", ")" ]
605f33c7b735fcb85e16041c27658fbba49d7a7b
https://github.com/disqus/disqus-python/blob/605f33c7b735fcb85e16041c27658fbba49d7a7b/disqusapi/utils.py#L101-L106
train
codesardine/Jade-Application-Kit
j/Api.py
Fs.open_file
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() except IOError: print(self + " File not found."...
python
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() except IOError: print(self + " File not found."...
[ "def", "open_file", "(", "self", ",", "access_mode", "=", "\"r\"", ")", ":", "try", ":", "with", "open", "(", "self", ",", "access_mode", ",", "encoding", "=", "'utf-8'", ")", "as", "file", ":", "return", "file", ".", "read", "(", ")", "except", "IOE...
input: filename and path. output: file contents.
[ "input", ":", "filename", "and", "path", ".", "output", ":", "file", "contents", "." ]
f94ba061f1e71c812f23ef4297473a5fce712367
https://github.com/codesardine/Jade-Application-Kit/blob/f94ba061f1e71c812f23ef4297473a5fce712367/j/Api.py#L8-L19
train
bhmm/bhmm
bhmm/estimators/maximum_likelihood.py
MaximumLikelihoodEstimator._forward_backward
def _forward_backward(self, itraj): """ 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 ...
python
def _forward_backward(self, itraj): """ 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 ...
[ "def", "_forward_backward", "(", "self", ",", "itraj", ")", ":", "# get parameters", "A", "=", "self", ".", "_hmm", ".", "transition_matrix", "pi", "=", "self", ".", "_hmm", ".", "initial_distribution", "obs", "=", "self", ".", "_observations", "[", "itraj",...
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...
[ "Estimation", "step", ":", "Runs", "the", "forward", "-", "back", "algorithm", "on", "trajectory", "with", "index", "itraj" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/maximum_likelihood.py#L221-L269
train
bhmm/bhmm
bhmm/estimators/maximum_likelihood.py
MaximumLikelihoodEstimator._update_model
def _update_model(self, gammas, count_matrices, maxiter=10000000): """ 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 traje...
python
def _update_model(self, gammas, count_matrices, maxiter=10000000): """ 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 traje...
[ "def", "_update_model", "(", "self", ",", "gammas", ",", "count_matrices", ",", "maxiter", "=", "10000000", ")", ":", "gamma0_sum", "=", "self", ".", "_init_counts", "(", "gammas", ")", "C", "=", "self", ".", "_transition_counts", "(", "count_matrices", ")",...
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...
[ "Maximization", "step", ":", "Updates", "the", "HMM", "model", "given", "the", "hidden", "state", "assignment", "and", "count", "matrices" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/maximum_likelihood.py#L284-L330
train
bhmm/bhmm
bhmm/estimators/maximum_likelihood.py
MaximumLikelihoodEstimator.compute_viterbi_paths
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_distribution # compute viterbi path for each trajectory ...
python
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_distribution # compute viterbi path for each trajectory ...
[ "def", "compute_viterbi_paths", "(", "self", ")", ":", "# get parameters", "K", "=", "len", "(", "self", ".", "_observations", ")", "A", "=", "self", ".", "_hmm", ".", "transition_matrix", "pi", "=", "self", ".", "_hmm", ".", "initial_distribution", "# compu...
Computes the viterbi paths using the current HMM model
[ "Computes", "the", "viterbi", "paths", "using", "the", "current", "HMM", "model" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/maximum_likelihood.py#L332-L352
train
bhmm/bhmm
bhmm/estimators/maximum_likelihood.py
MaximumLikelihoodEstimator.fit
def fit(self): """ Maximum-likelihood estimation of the HMM using the Baum-Welch algorithm Returns ------- model : HMM The maximum likelihood HMM model. """ logger().info("=================================================================") lo...
python
def fit(self): """ Maximum-likelihood estimation of the HMM using the Baum-Welch algorithm Returns ------- model : HMM The maximum likelihood HMM model. """ logger().info("=================================================================") lo...
[ "def", "fit", "(", "self", ")", ":", "logger", "(", ")", ".", "info", "(", "\"=================================================================\"", ")", "logger", "(", ")", ".", "info", "(", "\"Running Baum-Welch:\"", ")", "logger", "(", ")", ".", "info", "(", ...
Maximum-likelihood estimation of the HMM using the Baum-Welch algorithm Returns ------- model : HMM The maximum likelihood HMM model.
[ "Maximum", "-", "likelihood", "estimation", "of", "the", "HMM", "using", "the", "Baum", "-", "Welch", "algorithm" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/maximum_likelihood.py#L354-L446
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
sample_gaussian
def sample_gaussian(mean, covar, covariance_type='diag', n_samples=1, random_state=None): """Generate random samples from a Gaussian distribution. Parameters ---------- mean : array_like, shape (n_features,) Mean of the distribution. covar : array_like, optional ...
python
def sample_gaussian(mean, covar, covariance_type='diag', n_samples=1, random_state=None): """Generate random samples from a Gaussian distribution. Parameters ---------- mean : array_like, shape (n_features,) Mean of the distribution. covar : array_like, optional ...
[ "def", "sample_gaussian", "(", "mean", ",", "covar", ",", "covariance_type", "=", "'diag'", ",", "n_samples", "=", "1", ",", "random_state", "=", "None", ")", ":", "rng", "=", "check_random_state", "(", "random_state", ")", "n_dim", "=", "len", "(", "mean"...
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', ...
[ "Generate", "random", "samples", "from", "a", "Gaussian", "distribution", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L63-L107
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
_covar_mstep_diag
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_means = gmm.means_ * weighted_X_sum * norm return avg...
python
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_means = gmm.means_ * weighted_X_sum * norm return avg...
[ "def", "_covar_mstep_diag", "(", "gmm", ",", "X", ",", "responsibilities", ",", "weighted_X_sum", ",", "norm", ",", "min_covar", ")", ":", "avg_X2", "=", "np", ".", "dot", "(", "responsibilities", ".", "T", ",", "X", "*", "X", ")", "*", "norm", "avg_me...
Performing the covariance M step for diagonal cases
[ "Performing", "the", "covariance", "M", "step", "for", "diagonal", "cases" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L684-L690
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
_covar_mstep_spherical
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]))
python
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]))
[ "def", "_covar_mstep_spherical", "(", "*", "args", ")", ":", "cv", "=", "_covar_mstep_diag", "(", "*", "args", ")", "return", "np", ".", "tile", "(", "cv", ".", "mean", "(", "axis", "=", "1", ")", "[", ":", ",", "np", ".", "newaxis", "]", ",", "(...
Performing the covariance M step for spherical cases
[ "Performing", "the", "covariance", "M", "step", "for", "spherical", "cases" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L693-L696
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
_covar_mstep_full
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.shape[1] cv = np.empty((gmm.n_components, n_fea...
python
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.shape[1] cv = np.empty((gmm.n_components, n_fea...
[ "def", "_covar_mstep_full", "(", "gmm", ",", "X", ",", "responsibilities", ",", "weighted_X_sum", ",", "norm", ",", "min_covar", ")", ":", "# Eq. 12 from K. Murphy, \"Fitting a Conditional Linear Gaussian", "# Distribution\"", "n_features", "=", "X", ".", "shape", "[", ...
Performing the covariance M step for full cases
[ "Performing", "the", "covariance", "M", "step", "for", "full", "cases" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L699-L714
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM._get_covars
def _get_covars(self): """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 'di...
python
def _get_covars(self): """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 'di...
[ "def", "_get_covars", "(", "self", ")", ":", "if", "self", ".", "covariance_type", "==", "'full'", ":", "return", "self", ".", "covars_", "elif", "self", ".", "covariance_type", "==", "'diag'", ":", "return", "[", "np", ".", "diag", "(", "cov", ")", "f...
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...
[ "Covariance", "parameters", "for", "each", "mixture", "component", ".", "The", "shape", "depends", "on", "cvtype", "::" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L261-L277
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM._set_covars
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
python
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
[ "def", "_set_covars", "(", "self", ",", "covars", ")", ":", "covars", "=", "np", ".", "asarray", "(", "covars", ")", "_validate_covars", "(", "covars", ",", "self", ".", "covariance_type", ",", "self", ".", "n_components", ")", "self", ".", "covars_", "=...
Provide values for covariance
[ "Provide", "values", "for", "covariance" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L279-L283
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM.score_samples
def score_samples(self, X): """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 ---------- ...
python
def score_samples(self, X): """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 ---------- ...
[ "def", "score_samples", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "'means_'", ")", "X", "=", "check_array", "(", "X", ")", "if", "X", ".", "ndim", "==", "1", ":", "X", "=", "X", "[", ":", ",", "np", ".", "newaxis", "...
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...
[ "Return", "the", "per", "-", "sample", "likelihood", "of", "the", "data", "under", "the", "model", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L285-L322
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM.score
def score(self, X, y=None): """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 ----...
python
def score(self, X, y=None): """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 ----...
[ "def", "score", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "logprob", ",", "_", "=", "self", ".", "score_samples", "(", "X", ")", "return", "logprob" ]
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...
[ "Compute", "the", "log", "probability", "under", "the", "model", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L324-L339
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM.predict
def predict(self, X): """Predict label for data. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array, shape = (n_samples,) """ logprob, responsibilities = self.score_samples(X) return responsibi...
python
def predict(self, X): """Predict label for data. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array, shape = (n_samples,) """ logprob, responsibilities = self.score_samples(X) return responsibi...
[ "def", "predict", "(", "self", ",", "X", ")", ":", "logprob", ",", "responsibilities", "=", "self", ".", "score_samples", "(", "X", ")", "return", "responsibilities", ".", "argmax", "(", "axis", "=", "1", ")" ]
Predict label for data. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array, shape = (n_samples,)
[ "Predict", "label", "for", "data", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L341-L353
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM.sample
def sample(self, n_samples=1, random_state=None): """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) ...
python
def sample(self, n_samples=1, random_state=None): """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) ...
[ "def", "sample", "(", "self", ",", "n_samples", "=", "1", ",", "random_state", "=", "None", ")", ":", "check_is_fitted", "(", "self", ",", "'means_'", ")", "if", "random_state", "is", "None", ":", "random_state", "=", "self", ".", "random_state", "random_s...
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
[ "Generate", "random", "samples", "from", "the", "model", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L372-L412
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM.fit
def fit(self, X, y=None): """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 ...
python
def fit(self, X, y=None): """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 ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "# initialization step", "X", "=", "check_array", "(", "X", ",", "dtype", "=", "np", ".", "float64", ")", "if", "X", ".", "shape", "[", "0", "]", "<", "self", ".", "n_component...
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 ...
[ "Estimate", "model", "parameters", "with", "the", "expectation", "-", "maximization", "algorithm", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L414-L509
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM._do_mstep
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.T, X) inverse_weights = 1.0 / (weights[:, np.newaxis] + 10 * ...
python
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.T, X) inverse_weights = 1.0 / (weights[:, np.newaxis] + 10 * ...
[ "def", "_do_mstep", "(", "self", ",", "X", ",", "responsibilities", ",", "params", ",", "min_covar", "=", "0", ")", ":", "weights", "=", "responsibilities", ".", "sum", "(", "axis", "=", "0", ")", "weighted_X_sum", "=", "np", ".", "dot", "(", "responsi...
Perform the Mstep of the EM algorithm and return the class weihgts.
[ "Perform", "the", "Mstep", "of", "the", "EM", "algorithm", "and", "return", "the", "class", "weihgts", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L511-L527
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM._n_parameters
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_type == 'diag': cov_params = self.n_compon...
python
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_type == 'diag': cov_params = self.n_compon...
[ "def", "_n_parameters", "(", "self", ")", ":", "ndim", "=", "self", ".", "means_", ".", "shape", "[", "1", "]", "if", "self", ".", "covariance_type", "==", "'full'", ":", "cov_params", "=", "self", ".", "n_components", "*", "ndim", "*", "(", "ndim", ...
Return the number of free parameters in the model.
[ "Return", "the", "number", "of", "free", "parameters", "in", "the", "model", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L529-L541
train
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM.bic
def bic(self, X): """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) """ return (-2 * self....
python
def bic(self, X): """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) """ return (-2 * self....
[ "def", "bic", "(", "self", ",", "X", ")", ":", "return", "(", "-", "2", "*", "self", ".", "score", "(", "X", ")", ".", "sum", "(", ")", "+", "self", ".", "_n_parameters", "(", ")", "*", "np", ".", "log", "(", "X", ".", "shape", "[", "0", ...
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)
[ "Bayesian", "information", "criterion", "for", "the", "current", "model", "fit", "and", "the", "proposed", "data" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L543-L556
train
bhmm/bhmm
bhmm/_external/sklearn/base.py
BaseEstimator._get_param_names
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 object.__init__: # No explicit ...
python
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 object.__init__: # No explicit ...
[ "def", "_get_param_names", "(", "cls", ")", ":", "# fetch the constructor or the original constructor before", "# deprecation wrapping if any", "init", "=", "getattr", "(", "cls", ".", "__init__", ",", "'deprecated_original'", ",", "cls", ".", "__init__", ")", "if", "in...
Get parameter names for the estimator
[ "Get", "parameter", "names", "for", "the", "estimator" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/base.py#L67-L90
train
bhmm/bhmm
bhmm/_external/sklearn/base.py
BaseEstimator.set_params
def set_params(self, **params): """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 ...
python
def set_params(self, **params): """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 ...
[ "def", "set_params", "(", "self", ",", "*", "*", "params", ")", ":", "if", "not", "params", ":", "# Simple optimisation to gain speed (inspect is slow)", "return", "self", "valid_params", "=", "self", ".", "get_params", "(", "deep", "=", "True", ")", "for", "k...
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 -...
[ "Set", "the", "parameters", "of", "this", "estimator", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/base.py#L129-L161
train
bhmm/bhmm
bhmm/init/gaussian.py
init_model_gaussian1d
def init_model_gaussian1d(observations, nstates, reversible=True): """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 s...
python
def init_model_gaussian1d(observations, nstates, reversible=True): """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 s...
[ "def", "init_model_gaussian1d", "(", "observations", ",", "nstates", ",", "reversible", "=", "True", ")", ":", "ntrajectories", "=", "len", "(", "observations", ")", "# Concatenate all observations.", "collected_observations", "=", "np", ".", "array", "(", "[", "]...
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...
[ "Generate", "an", "initial", "model", "with", "1D", "-", "Gaussian", "output", "densities" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/init/gaussian.py#L26-L92
train
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel._p_o
def _p_o(self, o): """ 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...
python
def _p_o(self, o): """ 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...
[ "def", "_p_o", "(", "self", ",", "o", ")", ":", "if", "self", ".", "__impl__", "==", "self", ".", "__IMPL_C__", ":", "return", "gc", ".", "p_o", "(", "o", ",", "self", ".", "means", ",", "self", ".", "sigmas", ",", "out", "=", "None", ",", "dty...
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", "probability", "for", "symbol", "o", "from", "all", "hidden", "states" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L132-L168
train
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel.p_obs
def p_obs(self, obs, out=None): """ 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) ...
python
def p_obs(self, obs, out=None): """ 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) ...
[ "def", "p_obs", "(", "self", ",", "obs", ",", "out", "=", "None", ")", ":", "if", "self", ".", "__impl__", "==", "self", ".", "__IMPL_C__", ":", "res", "=", "gc", ".", "p_obs", "(", "obs", ",", "self", ".", "means", ",", "self", ".", "sigmas", ...
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...
[ "Returns", "the", "output", "probabilities", "for", "an", "entire", "trajectory", "and", "all", "hidden", "states" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L170-L212
train
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel.estimate
def estimate(self, observations, weights): """ 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 weight...
python
def estimate(self, observations, weights): """ 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 weight...
[ "def", "estimate", "(", "self", ",", "observations", ",", "weights", ")", ":", "# sizes", "N", "=", "self", ".", "nstates", "K", "=", "len", "(", "observations", ")", "# fit means", "self", ".", "_means", "=", "np", ".", "zeros", "(", "N", ")", "w_su...
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...
[ "Fits", "the", "output", "model", "given", "the", "observations", "and", "weights" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L214-L272
train
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel.sample
def sample(self, observations, prior=None): """ 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...
python
def sample(self, observations, prior=None): """ 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...
[ "def", "sample", "(", "self", ",", "observations", ",", "prior", "=", "None", ")", ":", "for", "state_index", "in", "range", "(", "self", ".", "nstates", ")", ":", "# Update state emission distribution parameters.", "observations_in_state", "=", "observations", "[...
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...
[ "Sample", "a", "new", "set", "of", "distribution", "parameters", "given", "a", "sample", "of", "observations", "from", "the", "given", "state", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L274-L320
train
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel.generate_observation_from_state
def generate_observation_from_state(self, state_index): """ 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 ------- ...
python
def generate_observation_from_state(self, state_index): """ 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 ------- ...
[ "def", "generate_observation_from_state", "(", "self", ",", "state_index", ")", ":", "observation", "=", "self", ".", "sigmas", "[", "state_index", "]", "*", "np", ".", "random", ".", "randn", "(", ")", "+", "self", ".", "means", "[", "state_index", "]", ...
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", "a", "single", "synthetic", "observation", "data", "from", "a", "given", "state", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L322-L349
train
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel.generate_observations_from_state
def generate_observations_from_state(self, state_index, nobs): """ 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 numbe...
python
def generate_observations_from_state(self, state_index, nobs): """ 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 numbe...
[ "def", "generate_observations_from_state", "(", "self", ",", "state_index", ",", "nobs", ")", ":", "observations", "=", "self", ".", "sigmas", "[", "state_index", "]", "*", "np", ".", "random", ".", "randn", "(", "nobs", ")", "+", "self", ".", "means", "...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L351-L380
train
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel.generate_observation_trajectory
def generate_observation_trajectory(self, s_t): """ 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 ------- ...
python
def generate_observation_trajectory(self, s_t): """ 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 ------- ...
[ "def", "generate_observation_trajectory", "(", "self", ",", "s_t", ")", ":", "# Determine number of samples to generate.", "T", "=", "s_t", ".", "shape", "[", "0", "]", "o_t", "=", "np", ".", "zeros", "(", "[", "T", "]", ",", "dtype", "=", "config", ".", ...
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[...
[ "Generate", "synthetic", "observation", "data", "from", "a", "given", "state", "sequence", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L382-L418
train
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.initial_distribution_samples
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 return res
python
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 return res
[ "def", "initial_distribution_samples", "(", "self", ")", ":", "res", "=", "np", ".", "empty", "(", "(", "self", ".", "nsamples", ",", "self", ".", "nstates", ")", ",", "dtype", "=", "config", ".", "dtype", ")", "for", "i", "in", "range", "(", "self",...
r""" Samples of the initial distribution
[ "r", "Samples", "of", "the", "initial", "distribution" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L70-L75
train
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.transition_matrix_samples
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 return res
python
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 return res
[ "def", "transition_matrix_samples", "(", "self", ")", ":", "res", "=", "np", ".", "empty", "(", "(", "self", ".", "nsamples", ",", "self", ".", "nstates", ",", "self", ".", "nstates", ")", ",", "dtype", "=", "config", ".", "dtype", ")", "for", "i", ...
r""" Samples of the transition matrix
[ "r", "Samples", "of", "the", "transition", "matrix" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L116-L121
train
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.eigenvalues_samples
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
python
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
[ "def", "eigenvalues_samples", "(", "self", ")", ":", "res", "=", "np", ".", "empty", "(", "(", "self", ".", "nsamples", ",", "self", ".", "nstates", ")", ",", "dtype", "=", "config", ".", "dtype", ")", "for", "i", "in", "range", "(", "self", ".", ...
r""" Samples of the eigenvalues
[ "r", "Samples", "of", "the", "eigenvalues" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L139-L144
train
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.eigenvectors_left_samples
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): res[i, :, :] = self._sampled_hmms[i].eigenvectors_left ...
python
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): res[i, :, :] = self._sampled_hmms[i].eigenvectors_left ...
[ "def", "eigenvectors_left_samples", "(", "self", ")", ":", "res", "=", "np", ".", "empty", "(", "(", "self", ".", "nsamples", ",", "self", ".", "nstates", ",", "self", ".", "nstates", ")", ",", "dtype", "=", "config", ".", "dtype", ")", "for", "i", ...
r""" Samples of the left eigenvectors of the hidden transition matrix
[ "r", "Samples", "of", "the", "left", "eigenvectors", "of", "the", "hidden", "transition", "matrix" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L162-L167
train
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.eigenvectors_right_samples
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): res[i, :, :] = self._sampled_hmms[i].eigenvectors_right ...
python
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): res[i, :, :] = self._sampled_hmms[i].eigenvectors_right ...
[ "def", "eigenvectors_right_samples", "(", "self", ")", ":", "res", "=", "np", ".", "empty", "(", "(", "self", ".", "nsamples", ",", "self", ".", "nstates", ",", "self", ".", "nstates", ")", ",", "dtype", "=", "config", ".", "dtype", ")", "for", "i", ...
r""" Samples of the right eigenvectors of the hidden transition matrix
[ "r", "Samples", "of", "the", "right", "eigenvectors", "of", "the", "hidden", "transition", "matrix" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L185-L190
train
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.timescales_samples
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
python
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
[ "def", "timescales_samples", "(", "self", ")", ":", "res", "=", "np", ".", "empty", "(", "(", "self", ".", "nsamples", ",", "self", ".", "nstates", "-", "1", ")", ",", "dtype", "=", "config", ".", "dtype", ")", "for", "i", "in", "range", "(", "se...
r""" Samples of the timescales
[ "r", "Samples", "of", "the", "timescales" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L208-L213
train