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
3 values
summary
stringlengths
4
350
gunthercox/jsondb
jsondb/db.py
Database.filter
def filter(self, filter_arguments): """ Takes a dictionary of filter parameters. Return a list of objects based on a list of parameters. """ results = self._get_content() # Filter based on a dictionary of search parameters if isinstance(filter_arguments, dict): ...
python
def filter(self, filter_arguments): """ Takes a dictionary of filter parameters. Return a list of objects based on a list of parameters. """ results = self._get_content() # Filter based on a dictionary of search parameters if isinstance(filter_arguments, dict): ...
[ "def", "filter", "(", "self", ",", "filter_arguments", ")", ":", "results", "=", "self", ".", "_get_content", "(", ")", "# Filter based on a dictionary of search parameters", "if", "isinstance", "(", "filter_arguments", ",", "dict", ")", ":", "for", "item", ",", ...
Takes a dictionary of filter parameters. Return a list of objects based on a list of parameters.
[ "Takes", "a", "dictionary", "of", "filter", "parameters", ".", "Return", "a", "list", "of", "objects", "based", "on", "a", "list", "of", "parameters", "." ]
d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/db.py#L125-L149
train
Returns a list of objects based on a dictionary of filter parameters.
gunthercox/jsondb
jsondb/db.py
Database.drop
def drop(self): """ Remove the database by deleting the JSON file. """ import os if self.path: if os.path.exists(self.path): os.remove(self.path) else: # Clear the in-memory data if there is no file path self._data = {}
python
def drop(self): """ Remove the database by deleting the JSON file. """ import os if self.path: if os.path.exists(self.path): os.remove(self.path) else: # Clear the in-memory data if there is no file path self._data = {}
[ "def", "drop", "(", "self", ")", ":", "import", "os", "if", "self", ".", "path", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "path", ")", ":", "os", ".", "remove", "(", "self", ".", "path", ")", "else", ":", "# Clear the in-mem...
Remove the database by deleting the JSON file.
[ "Remove", "the", "database", "by", "deleting", "the", "JSON", "file", "." ]
d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/db.py#L151-L162
train
Drop the database by deleting the JSON file.
gunthercox/jsondb
jsondb/file_writer.py
read_data
def read_data(file_path): """ Reads a file and returns a json encoded representation of the file. """ if not is_valid(file_path): write_data(file_path, {}) db = open_file_for_reading(file_path) content = db.read() obj = decode(content) db.close() return obj
python
def read_data(file_path): """ Reads a file and returns a json encoded representation of the file. """ if not is_valid(file_path): write_data(file_path, {}) db = open_file_for_reading(file_path) content = db.read() obj = decode(content) db.close() return obj
[ "def", "read_data", "(", "file_path", ")", ":", "if", "not", "is_valid", "(", "file_path", ")", ":", "write_data", "(", "file_path", ",", "{", "}", ")", "db", "=", "open_file_for_reading", "(", "file_path", ")", "content", "=", "db", ".", "read", "(", ...
Reads a file and returns a json encoded representation of the file.
[ "Reads", "a", "file", "and", "returns", "a", "json", "encoded", "representation", "of", "the", "file", "." ]
d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/file_writer.py#L4-L19
train
Reads a file and returns a json encoded representation of the file.
gunthercox/jsondb
jsondb/file_writer.py
write_data
def write_data(path, obj): """ Writes to a file and returns the updated file content. """ with open_file_for_writing(path) as db: db.write(encode(obj)) return obj
python
def write_data(path, obj): """ Writes to a file and returns the updated file content. """ with open_file_for_writing(path) as db: db.write(encode(obj)) return obj
[ "def", "write_data", "(", "path", ",", "obj", ")", ":", "with", "open_file_for_writing", "(", "path", ")", "as", "db", ":", "db", ".", "write", "(", "encode", "(", "obj", ")", ")", "return", "obj" ]
Writes to a file and returns the updated file content.
[ "Writes", "to", "a", "file", "and", "returns", "the", "updated", "file", "content", "." ]
d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/file_writer.py#L21-L28
train
Writes a dictionary to a file and returns the updated file content.
gunthercox/jsondb
jsondb/file_writer.py
is_valid
def is_valid(file_path): """ Check to see if a file exists or is empty. """ from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(fil...
python
def is_valid(file_path): """ Check to see if a file exists or is empty. """ from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(fil...
[ "def", "is_valid", "(", "file_path", ")", ":", "from", "os", "import", "path", ",", "stat", "can_open", "=", "False", "try", ":", "with", "open", "(", "file_path", ")", "as", "fp", ":", "can_open", "=", "True", "except", "IOError", ":", "return", "Fals...
Check to see if a file exists or is empty.
[ "Check", "to", "see", "if", "a", "file", "exists", "or", "is", "empty", "." ]
d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9
https://github.com/gunthercox/jsondb/blob/d0d2c7e5fdb8c3c46c0373d59c130641349b1bc9/jsondb/file_writer.py#L30-L46
train
Check to see if a file exists or is empty.
nschloe/meshzoo
meshzoo/helpers.py
_refine
def _refine(node_coords, cells_nodes, edge_nodes, cells_edges): """Canonically refine a mesh by inserting nodes at all edge midpoints and make four triangular elements where there was one. This is a very crude refinement; don't use for actual applications. """ num_nodes = len(node_coords) num_ne...
python
def _refine(node_coords, cells_nodes, edge_nodes, cells_edges): """Canonically refine a mesh by inserting nodes at all edge midpoints and make four triangular elements where there was one. This is a very crude refinement; don't use for actual applications. """ num_nodes = len(node_coords) num_ne...
[ "def", "_refine", "(", "node_coords", ",", "cells_nodes", ",", "edge_nodes", ",", "cells_edges", ")", ":", "num_nodes", "=", "len", "(", "node_coords", ")", "num_new_nodes", "=", "len", "(", "edge_nodes", ")", "# new_nodes = numpy.empty(num_new_nodes, dtype=numpy.dtyp...
Canonically refine a mesh by inserting nodes at all edge midpoints and make four triangular elements where there was one. This is a very crude refinement; don't use for actual applications.
[ "Canonically", "refine", "a", "mesh", "by", "inserting", "nodes", "at", "all", "edge", "midpoints", "and", "make", "four", "triangular", "elements", "where", "there", "was", "one", ".", "This", "is", "a", "very", "crude", "refinement", ";", "don", "t", "us...
623b84c8b985dcc8e5ccc6250d1dbb989736dcef
https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/helpers.py#L7-L124
train
Refines a mesh by inserting nodes at all edge midpoints and make four triangular elements where there was one.
nschloe/meshzoo
meshzoo/helpers.py
create_edges
def create_edges(cells_nodes): """Setup edge-node and edge-cell relations. Adapted from voropy. """ # Create the idx_hierarchy (nodes->edges->cells), i.e., the value of # `self.idx_hierarchy[0, 2, 27]` is the index of the node of cell 27, edge # 2, node 0. The shape of `self.idx_hierarchy` is `(2, 3...
python
def create_edges(cells_nodes): """Setup edge-node and edge-cell relations. Adapted from voropy. """ # Create the idx_hierarchy (nodes->edges->cells), i.e., the value of # `self.idx_hierarchy[0, 2, 27]` is the index of the node of cell 27, edge # 2, node 0. The shape of `self.idx_hierarchy` is `(2, 3...
[ "def", "create_edges", "(", "cells_nodes", ")", ":", "# Create the idx_hierarchy (nodes->edges->cells), i.e., the value of", "# `self.idx_hierarchy[0, 2, 27]` is the index of the node of cell 27, edge", "# 2, node 0. The shape of `self.idx_hierarchy` is `(2, 3, n)`, where `n` is", "# the number of...
Setup edge-node and edge-cell relations. Adapted from voropy.
[ "Setup", "edge", "-", "node", "and", "edge", "-", "cell", "relations", ".", "Adapted", "from", "voropy", "." ]
623b84c8b985dcc8e5ccc6250d1dbb989736dcef
https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/helpers.py#L127-L158
train
Create edge - node and edge - cell relations. Adapted from voropy.
nschloe/meshzoo
meshzoo/helpers.py
plot2d
def plot2d(points, cells, mesh_color="k", show_axes=False): """Plot a 2D mesh using matplotlib. """ import matplotlib.pyplot as plt from matplotlib.collections import LineCollection fig = plt.figure() ax = fig.gca() plt.axis("equal") if not show_axes: ax.set_axis_off() xmin...
python
def plot2d(points, cells, mesh_color="k", show_axes=False): """Plot a 2D mesh using matplotlib. """ import matplotlib.pyplot as plt from matplotlib.collections import LineCollection fig = plt.figure() ax = fig.gca() plt.axis("equal") if not show_axes: ax.set_axis_off() xmin...
[ "def", "plot2d", "(", "points", ",", "cells", ",", "mesh_color", "=", "\"k\"", ",", "show_axes", "=", "False", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "from", "matplotlib", ".", "collections", "import", "LineCollection", "fig", "=", "...
Plot a 2D mesh using matplotlib.
[ "Plot", "a", "2D", "mesh", "using", "matplotlib", "." ]
623b84c8b985dcc8e5ccc6250d1dbb989736dcef
https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/helpers.py#L169-L203
train
Plot a 2D mesh using matplotlib.
shazow/workerpool
samples/blockingworker.py
BlockingWorkerPool.put
def put(self, job, result): "Perform a job by a member in the pool and return the result." self.job.put(job) r = result.get() return r
python
def put(self, job, result): "Perform a job by a member in the pool and return the result." self.job.put(job) r = result.get() return r
[ "def", "put", "(", "self", ",", "job", ",", "result", ")", ":", "self", ".", "job", ".", "put", "(", "job", ")", "r", "=", "result", ".", "get", "(", ")", "return", "r" ]
Perform a job by a member in the pool and return the result.
[ "Perform", "a", "job", "by", "a", "member", "in", "the", "pool", "and", "return", "the", "result", "." ]
2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/samples/blockingworker.py#L16-L20
train
Perform a job by a member in the pool and return the result.
shazow/workerpool
samples/blockingworker.py
BlockingWorkerPool.contract
def contract(self, jobs, result): """ Perform a contract on a number of jobs and block until a result is retrieved for each job. """ for j in jobs: WorkerPool.put(self, j) r = [] for i in xrange(len(jobs)): r.append(result.get()) ...
python
def contract(self, jobs, result): """ Perform a contract on a number of jobs and block until a result is retrieved for each job. """ for j in jobs: WorkerPool.put(self, j) r = [] for i in xrange(len(jobs)): r.append(result.get()) ...
[ "def", "contract", "(", "self", ",", "jobs", ",", "result", ")", ":", "for", "j", "in", "jobs", ":", "WorkerPool", ".", "put", "(", "self", ",", "j", ")", "r", "=", "[", "]", "for", "i", "in", "xrange", "(", "len", "(", "jobs", ")", ")", ":",...
Perform a contract on a number of jobs and block until a result is retrieved for each job.
[ "Perform", "a", "contract", "on", "a", "number", "of", "jobs", "and", "block", "until", "a", "result", "is", "retrieved", "for", "each", "job", "." ]
2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/samples/blockingworker.py#L22-L34
train
Perform a contract on a number of jobs and block until a result is retrieved for each job.
nschloe/meshzoo
meshzoo/cube.py
cube
def cube( xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, zmin=0.0, zmax=1.0, nx=11, ny=11, nz=11 ): """Canonical tetrahedrization of the cube. Input: Edge lenghts of the cube Number of nodes along the edges. """ # Generate suitable ranges for parametrization x_range = numpy.linspace(xmin, xmax,...
python
def cube( xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, zmin=0.0, zmax=1.0, nx=11, ny=11, nz=11 ): """Canonical tetrahedrization of the cube. Input: Edge lenghts of the cube Number of nodes along the edges. """ # Generate suitable ranges for parametrization x_range = numpy.linspace(xmin, xmax,...
[ "def", "cube", "(", "xmin", "=", "0.0", ",", "xmax", "=", "1.0", ",", "ymin", "=", "0.0", ",", "ymax", "=", "1.0", ",", "zmin", "=", "0.0", ",", "zmax", "=", "1.0", ",", "nx", "=", "11", ",", "ny", "=", "11", ",", "nz", "=", "11", ")", ":...
Canonical tetrahedrization of the cube. Input: Edge lenghts of the cube Number of nodes along the edges.
[ "Canonical", "tetrahedrization", "of", "the", "cube", ".", "Input", ":", "Edge", "lenghts", "of", "the", "cube", "Number", "of", "nodes", "along", "the", "edges", "." ]
623b84c8b985dcc8e5ccc6250d1dbb989736dcef
https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/cube.py#L6-L294
train
Canonical tetrahedrization of the cube.
shazow/workerpool
workerpool/pools.py
WorkerPool.grow
def grow(self): "Add another worker to the pool." t = self.worker_factory(self) t.start() self._size += 1
python
def grow(self): "Add another worker to the pool." t = self.worker_factory(self) t.start() self._size += 1
[ "def", "grow", "(", "self", ")", ":", "t", "=", "self", ".", "worker_factory", "(", "self", ")", "t", ".", "start", "(", ")", "self", ".", "_size", "+=", "1" ]
Add another worker to the pool.
[ "Add", "another", "worker", "to", "the", "pool", "." ]
2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/pools.py#L66-L70
train
Add another worker to the pool.
shazow/workerpool
workerpool/pools.py
WorkerPool.shrink
def shrink(self): "Get rid of one worker from the pool. Raises IndexError if empty." if self._size <= 0: raise IndexError("pool is already empty") self._size -= 1 self.put(SuicideJob())
python
def shrink(self): "Get rid of one worker from the pool. Raises IndexError if empty." if self._size <= 0: raise IndexError("pool is already empty") self._size -= 1 self.put(SuicideJob())
[ "def", "shrink", "(", "self", ")", ":", "if", "self", ".", "_size", "<=", "0", ":", "raise", "IndexError", "(", "\"pool is already empty\"", ")", "self", ".", "_size", "-=", "1", "self", ".", "put", "(", "SuicideJob", "(", ")", ")" ]
Get rid of one worker from the pool. Raises IndexError if empty.
[ "Get", "rid", "of", "one", "worker", "from", "the", "pool", ".", "Raises", "IndexError", "if", "empty", "." ]
2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/pools.py#L72-L77
train
Get rid of one worker from the pool. Raises IndexError if empty.
shazow/workerpool
workerpool/pools.py
WorkerPool.map
def map(self, fn, *seq): "Perform a map operation distributed among the workers. Will " "block until done." results = Queue() args = zip(*seq) for seq in args: j = SimpleJob(results, fn, seq) self.put(j) # Aggregate results r = [] ...
python
def map(self, fn, *seq): "Perform a map operation distributed among the workers. Will " "block until done." results = Queue() args = zip(*seq) for seq in args: j = SimpleJob(results, fn, seq) self.put(j) # Aggregate results r = [] ...
[ "def", "map", "(", "self", ",", "fn", ",", "*", "seq", ")", ":", "\"block until done.\"", "results", "=", "Queue", "(", ")", "args", "=", "zip", "(", "*", "seq", ")", "for", "seq", "in", "args", ":", "j", "=", "SimpleJob", "(", "results", ",", "f...
Perform a map operation distributed among the workers. Will
[ "Perform", "a", "map", "operation", "distributed", "among", "the", "workers", ".", "Will" ]
2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/pools.py#L89-L103
train
Perform a map operation distributed among the workers. Will " "block until done.
nschloe/meshzoo
meshzoo/moebius.py
moebius
def moebius( num_twists=1, # How many twists are there in the 'paper'? nl=60, # Number of nodes along the length of the strip nw=11, # Number of nodes along the width of the strip (>= 2) mode="classical", ): """Creates a simplistic triangular mesh on a slightly Möbius strip. The Möbius strip ...
python
def moebius( num_twists=1, # How many twists are there in the 'paper'? nl=60, # Number of nodes along the length of the strip nw=11, # Number of nodes along the width of the strip (>= 2) mode="classical", ): """Creates a simplistic triangular mesh on a slightly Möbius strip. The Möbius strip ...
[ "def", "moebius", "(", "num_twists", "=", "1", ",", "# How many twists are there in the 'paper'?", "nl", "=", "60", ",", "# Number of nodes along the length of the strip", "nw", "=", "11", ",", "# Number of nodes along the width of the strip (>= 2)", "mode", "=", "\"classical...
Creates a simplistic triangular mesh on a slightly Möbius strip. The Möbius strip here deviates slightly from the ordinary geometry in that it is constructed in such a way that the two halves can be exchanged as to allow better comparison with the pseudo-Möbius geometry. The mode is either `'classical'...
[ "Creates", "a", "simplistic", "triangular", "mesh", "on", "a", "slightly", "Möbius", "strip", ".", "The", "Möbius", "strip", "here", "deviates", "slightly", "from", "the", "ordinary", "geometry", "in", "that", "it", "is", "constructed", "in", "such", "a", "w...
623b84c8b985dcc8e5ccc6250d1dbb989736dcef
https://github.com/nschloe/meshzoo/blob/623b84c8b985dcc8e5ccc6250d1dbb989736dcef/meshzoo/moebius.py#L7-L83
train
Returns a Möbius strip as a simplistic triangular mesh.
shazow/workerpool
workerpool/workers.py
Worker.run
def run(self): "Get jobs from the queue and perform them as they arrive." while 1: # Sleep until there is a job to perform. job = self.jobs.get() # Yawn. Time to get some work done. try: job.run() self.jobs.task_done() ...
python
def run(self): "Get jobs from the queue and perform them as they arrive." while 1: # Sleep until there is a job to perform. job = self.jobs.get() # Yawn. Time to get some work done. try: job.run() self.jobs.task_done() ...
[ "def", "run", "(", "self", ")", ":", "while", "1", ":", "# Sleep until there is a job to perform.", "job", "=", "self", ".", "jobs", ".", "get", "(", ")", "# Yawn. Time to get some work done.", "try", ":", "job", ".", "run", "(", ")", "self", ".", "jobs", ...
Get jobs from the queue and perform them as they arrive.
[ "Get", "jobs", "from", "the", "queue", "and", "perform", "them", "as", "they", "arrive", "." ]
2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5
https://github.com/shazow/workerpool/blob/2c5b29ec64ffbc94fc3623a4531eaf7c7c1a9ab5/workerpool/workers.py#L28-L40
train
Get jobs from the queue and perform them as they arrive.
jwass/geojsonio.py
geojsonio/geojsonio.py
display
def display(contents, domain=DEFAULT_DOMAIN, force_gist=False): """ Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the cont...
python
def display(contents, domain=DEFAULT_DOMAIN, force_gist=False): """ Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the cont...
[ "def", "display", "(", "contents", ",", "domain", "=", "DEFAULT_DOMAIN", ",", "force_gist", "=", "False", ")", ":", "url", "=", "make_url", "(", "contents", ",", "domain", ",", "force_gist", ")", "webbrowser", ".", "open", "(", "url", ")", "return", "url...
Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the content is small, this step is not needed as the data can be included in the...
[ "Open", "a", "web", "browser", "pointing", "to", "geojson", ".", "io", "with", "the", "specified", "content", "." ]
8229a48238f128837e6dce49f18310df84968825
https://github.com/jwass/geojsonio.py/blob/8229a48238f128837e6dce49f18310df84968825/geojsonio/geojsonio.py#L18-L38
train
Display a single object in a web browser pointing to geojson. io with the specified content.
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
Embed geojson. io in an iframe in Jupyter notebook.
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
Returns the URL to open given the domain and contents.
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
Returns a GeoJSON string from a variety of inputs.
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
Returns the URL for embedding the GeoJSON data in the URL hash
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
Create and return an anonymous gist with a single file and specified contents
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
Clenshaw s algorithm for evaluating the kth orthogonal polynomial defined by the recurrence coefficients alpha and beta.
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
Generalized Laguerre polynomials.
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
Return the recurrence coefficients for generalized Laguerre polynomials.
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
Generate the recurrence coefficients a_k b_k c_k for the Jacobi polynomials which are orthogonal on [ 1 - 1 ).
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
Plot function over a disk.
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
Evaluates the entire tree of orthogonal polynomials for the n - cube X.
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
Evaluate the orthogonal polynomial defined by its recurrence coefficients a b and c at the point s.
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
Plot function over a triangle.
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
Case - insensitive search for key within keys of lookup_dict.
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
Try to lookup a Language object by name e. g. English in internal language list.
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
Try to lookup a Language object by native name e. g. English in internal language list.
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
Returns a Language object for the language code code.
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
Write a function f defined in terms of spherical coordinates to a file.
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
Evaluate all spherical harmonics of degree at most n at angles polar and azimuthal.
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
Evaluates the entire tree of associated Legendre polynomials up to depth n.
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
Evaluates the entire tree of orthogonal polynomials on the unit disk.
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
Evaluates the entire tree of orthogonal triangle polynomials.
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
Check if the given filename actually exists and if it s a directory and if it s not a file
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
Handle the command line call keyword arguments return 0 if error or a string for the command line output
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
Returns the exif of a file
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
Return a json value of the exif
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
Returns a csv representation of the exif get a filename and returns a unicode string with a csv format
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
This function will output a message in a header
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
Checks if Exiftool is installed on your system and returns True if it is otherwise False
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
Render the message with the provided context.
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
Send the message to the related object.
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
This function is a convenience function for sending an email message to a list of recipients.
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
Compute the mean Silhouette Coefficient of all samples.
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
Compute the Silhouette Coefficient for each sample in X.
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
Compute the Calinski and Harabaz score.
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
Handles zeroes in a single scale.
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
Compute joint probabilities p_ij from distances.
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
Compute joint probabilities p_ij from distances using just nearest - neighbors.
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
t - SNE objective function for Kullback - Leibler divergence of p_ij and q_ij.
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
t - SNE objective function for the Kullback - Leibler divergence of p_ij and q_ij.
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
Batch gradient descent for a given parameter vector.
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
Returns the trustworthiness of the local structure.
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
Fit the model using X as training data.
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
Runs t - SNE.
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
Fit X into an embedded space and return that transformed .
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
Integrate and batch correct a list of data sets.
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
Integrate a list of data sets and correct a list of genes.
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
Batch correct a list of scanpy. api. AnnData.
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
Integrate a list of scanpy. api. AnnData objects.
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
Augment a knot vector with a new order.
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
Compute the running average of k successive elements of t. Return the averaged array.
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
Create an acceptable knot vector.
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
Count multiplicities of elements in a sorted list or rank - 1 array.
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
Return collocation matrix. spcol is the minimum emulation of MATLAB s pcol.
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
Order zero basis ( for internal use.
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
Recursive Cox - de Boor function.
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
Convenience function to compute first derivative of basis functions. Memoized for speed.
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
Convenience function that plots the basis functions over full range of knots. Convenience function. Requires matplotlib. pyplot.
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
Differentiate a B - spline once and return the resulting coefficients and Bspline objects.
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
Returns a function that evaluates the order - th derivative of a B - spline.
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
Compute collocation matrix for the given set of functions.
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
Build a dictionary of methods that are used by the method.
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
Returns a normalized request string as described in iN OAuth 2 MAC spec.
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
Returns the body hash of the given params.
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
Returns HMAC - SHA1 signature
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
open file and return contents.
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
This method computes the forward and backward steps for the internal state of the HMM.
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
Update the HMM model given the hidden state assignment and count matrices.
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
Computes the viterbi paths for the current trajectory and returns a numpy array of the paths.
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
Fits the maximum likelihood estimation of the HMM using Baum - Welch algorithm.
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
Generate random samples from a Gaussian distribution.
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
Perform the covariance M step for diagonal cases
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
Performing the covariance M step for spherical cases
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
Perform the covariance M step for full cases.
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
Returns the covariance parameters for each mixture component.
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
Provide values for covariance
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
Compute the log probability of each data point in X and return the posterior distribution of each mixture component of each element of X.
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
Compute the log probability under the model.
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
Predict label for data.
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
Generate random samples from the model.
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
This method calculates the model parameters with the expectation - minimization algorithm.
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
Perform the Mstep of the EM algorithm and return the class weihgts.
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
Return the number of free parameters in the model.