id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
225,300 | pymc-devs/pymc | pymc/Model.py | Sampler.sample | def sample(self, iter, length=None, verbose=0):
"""
Draws iter samples from the posterior.
"""
self._cur_trace_index = 0
self.max_trace_length = iter
self._iter = iter
self.verbose = verbose or 0
self.seed()
# Assign Trace instances to tallyable objects.
self.db.connect_model(self)
# Initialize database -> initialize traces.
if length is None:
length = iter
self.db._initialize(self._funs_to_tally, length)
# Put traces on objects
for v in self._variables_to_tally:
v.trace = self.db._traces[v.__name__]
# Loop
self._current_iter = 0
self._loop()
self._finalize() | python | def sample(self, iter, length=None, verbose=0):
"""
Draws iter samples from the posterior.
"""
self._cur_trace_index = 0
self.max_trace_length = iter
self._iter = iter
self.verbose = verbose or 0
self.seed()
# Assign Trace instances to tallyable objects.
self.db.connect_model(self)
# Initialize database -> initialize traces.
if length is None:
length = iter
self.db._initialize(self._funs_to_tally, length)
# Put traces on objects
for v in self._variables_to_tally:
v.trace = self.db._traces[v.__name__]
# Loop
self._current_iter = 0
self._loop()
self._finalize() | [
"def",
"sample",
"(",
"self",
",",
"iter",
",",
"length",
"=",
"None",
",",
"verbose",
"=",
"0",
")",
":",
"self",
".",
"_cur_trace_index",
"=",
"0",
"self",
".",
"max_trace_length",
"=",
"iter",
"self",
".",
"_iter",
"=",
"iter",
"self",
".",
"verbo... | Draws iter samples from the posterior. | [
"Draws",
"iter",
"samples",
"from",
"the",
"posterior",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L221-L246 |
225,301 | pymc-devs/pymc | pymc/Model.py | Sampler._finalize | def _finalize(self):
"""Reset the status and tell the database to finalize the traces."""
if self.status in ['running', 'halt']:
if self.verbose > 0:
print_('\nSampling finished normally.')
self.status = 'ready'
self.save_state()
self.db._finalize() | python | def _finalize(self):
"""Reset the status and tell the database to finalize the traces."""
if self.status in ['running', 'halt']:
if self.verbose > 0:
print_('\nSampling finished normally.')
self.status = 'ready'
self.save_state()
self.db._finalize() | [
"def",
"_finalize",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"in",
"[",
"'running'",
",",
"'halt'",
"]",
":",
"if",
"self",
".",
"verbose",
">",
"0",
":",
"print_",
"(",
"'\\nSampling finished normally.'",
")",
"self",
".",
"status",
"=",
"'... | Reset the status and tell the database to finalize the traces. | [
"Reset",
"the",
"status",
"and",
"tell",
"the",
"database",
"to",
"finalize",
"the",
"traces",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L248-L256 |
225,302 | pymc-devs/pymc | pymc/Model.py | Sampler.stats | def stats(self, variables=None, alpha=0.05, start=0,
batches=100, chain=None, quantiles=(2.5, 25, 50, 75, 97.5)):
"""
Statistical output for variables.
:Parameters:
variables : iterable
List or array of variables for which statistics are to be
generated. If it is not specified, all the tallied variables
are summarized.
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
Batch size for calculating standard deviation for non-independent
samples. Defaults to 100.
chain : int
The index for which chain to summarize. Defaults to None (all
chains).
"""
# If no names provided, run them all
if variables is None:
variables = self._variables_to_tally
else:
variables = [v for v in self.variables if v.__name__ in variables]
stat_dict = {}
# Loop over nodes
for variable in variables:
# Plot object
stat_dict[variable.__name__] = self.trace(
variable.__name__).stats(alpha=alpha, start=start,
batches=batches, chain=chain, quantiles=quantiles)
return stat_dict | python | def stats(self, variables=None, alpha=0.05, start=0,
batches=100, chain=None, quantiles=(2.5, 25, 50, 75, 97.5)):
"""
Statistical output for variables.
:Parameters:
variables : iterable
List or array of variables for which statistics are to be
generated. If it is not specified, all the tallied variables
are summarized.
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
Batch size for calculating standard deviation for non-independent
samples. Defaults to 100.
chain : int
The index for which chain to summarize. Defaults to None (all
chains).
"""
# If no names provided, run them all
if variables is None:
variables = self._variables_to_tally
else:
variables = [v for v in self.variables if v.__name__ in variables]
stat_dict = {}
# Loop over nodes
for variable in variables:
# Plot object
stat_dict[variable.__name__] = self.trace(
variable.__name__).stats(alpha=alpha, start=start,
batches=batches, chain=chain, quantiles=quantiles)
return stat_dict | [
"def",
"stats",
"(",
"self",
",",
"variables",
"=",
"None",
",",
"alpha",
"=",
"0.05",
",",
"start",
"=",
"0",
",",
"batches",
"=",
"100",
",",
"chain",
"=",
"None",
",",
"quantiles",
"=",
"(",
"2.5",
",",
"25",
",",
"50",
",",
"75",
",",
"97.5... | Statistical output for variables.
:Parameters:
variables : iterable
List or array of variables for which statistics are to be
generated. If it is not specified, all the tallied variables
are summarized.
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
Batch size for calculating standard deviation for non-independent
samples. Defaults to 100.
chain : int
The index for which chain to summarize. Defaults to None (all
chains). | [
"Statistical",
"output",
"for",
"variables",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L304-L347 |
225,303 | pymc-devs/pymc | pymc/Model.py | Sampler.write_csv | def write_csv(
self, filename, variables=None, alpha=0.05, start=0, batches=100,
chain=None, quantiles=(2.5, 25, 50, 75, 97.5)):
"""
Save summary statistics to a csv table.
:Parameters:
filename : string
Filename to save output.
variables : iterable
List or array of variables for which statistics are to be
generated. If it is not specified, all the tallied variables
are summarized.
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
Batch size for calculating standard deviation for non-independent
samples. Defaults to 100.
chain : int
The index for which chain to summarize. Defaults to None (all
chains).
"""
# Append 'csv' suffix if there is no suffix on the filename
if filename.find('.') == -1:
filename += '.csv'
outfile = open(filename, 'w')
# Write header to file
header = 'Parameter, Mean, SD, MC Error, Lower 95% HPD, Upper 95% HPD, '
header += ', '.join(['q%s' % i for i in quantiles])
outfile.write(header + '\n')
stats = self.stats(
variables=variables,
alpha=alpha,
start=start,
batches=batches,
chain=chain,
quantiles=quantiles)
if variables is None:
variables = sorted(stats.keys())
buffer = str()
for param in variables:
values = stats[param]
try:
# Multivariate node
shape = values['mean'].shape
indices = list(itertools.product(*[range(i) for i in shape]))
for i in indices:
buffer += self._csv_str(param, values, quantiles, i)
except AttributeError:
# Scalar node
buffer += self._csv_str(param, values, quantiles)
outfile.write(buffer)
outfile.close() | python | def write_csv(
self, filename, variables=None, alpha=0.05, start=0, batches=100,
chain=None, quantiles=(2.5, 25, 50, 75, 97.5)):
"""
Save summary statistics to a csv table.
:Parameters:
filename : string
Filename to save output.
variables : iterable
List or array of variables for which statistics are to be
generated. If it is not specified, all the tallied variables
are summarized.
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
Batch size for calculating standard deviation for non-independent
samples. Defaults to 100.
chain : int
The index for which chain to summarize. Defaults to None (all
chains).
"""
# Append 'csv' suffix if there is no suffix on the filename
if filename.find('.') == -1:
filename += '.csv'
outfile = open(filename, 'w')
# Write header to file
header = 'Parameter, Mean, SD, MC Error, Lower 95% HPD, Upper 95% HPD, '
header += ', '.join(['q%s' % i for i in quantiles])
outfile.write(header + '\n')
stats = self.stats(
variables=variables,
alpha=alpha,
start=start,
batches=batches,
chain=chain,
quantiles=quantiles)
if variables is None:
variables = sorted(stats.keys())
buffer = str()
for param in variables:
values = stats[param]
try:
# Multivariate node
shape = values['mean'].shape
indices = list(itertools.product(*[range(i) for i in shape]))
for i in indices:
buffer += self._csv_str(param, values, quantiles, i)
except AttributeError:
# Scalar node
buffer += self._csv_str(param, values, quantiles)
outfile.write(buffer)
outfile.close() | [
"def",
"write_csv",
"(",
"self",
",",
"filename",
",",
"variables",
"=",
"None",
",",
"alpha",
"=",
"0.05",
",",
"start",
"=",
"0",
",",
"batches",
"=",
"100",
",",
"chain",
"=",
"None",
",",
"quantiles",
"=",
"(",
"2.5",
",",
"25",
",",
"50",
",... | Save summary statistics to a csv table.
:Parameters:
filename : string
Filename to save output.
variables : iterable
List or array of variables for which statistics are to be
generated. If it is not specified, all the tallied variables
are summarized.
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
Batch size for calculating standard deviation for non-independent
samples. Defaults to 100.
chain : int
The index for which chain to summarize. Defaults to None (all
chains). | [
"Save",
"summary",
"statistics",
"to",
"a",
"csv",
"table",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L349-L423 |
225,304 | pymc-devs/pymc | pymc/Model.py | Sampler._csv_str | def _csv_str(self, param, stats, quantiles, index=None):
"""Support function for write_csv"""
buffer = param
if not index:
buffer += ', '
else:
buffer += '_' + '_'.join([str(i) for i in index]) + ', '
for stat in ('mean', 'standard deviation', 'mc error'):
buffer += str(stats[stat][index]) + ', '
# Index to interval label
iindex = [key.split()[-1] for key in stats.keys()].index('interval')
interval = list(stats.keys())[iindex]
buffer += ', '.join(stats[interval].T[index].astype(str))
# Process quantiles
qvalues = stats['quantiles']
for q in quantiles:
buffer += ', ' + str(qvalues[q][index])
return buffer + '\n' | python | def _csv_str(self, param, stats, quantiles, index=None):
"""Support function for write_csv"""
buffer = param
if not index:
buffer += ', '
else:
buffer += '_' + '_'.join([str(i) for i in index]) + ', '
for stat in ('mean', 'standard deviation', 'mc error'):
buffer += str(stats[stat][index]) + ', '
# Index to interval label
iindex = [key.split()[-1] for key in stats.keys()].index('interval')
interval = list(stats.keys())[iindex]
buffer += ', '.join(stats[interval].T[index].astype(str))
# Process quantiles
qvalues = stats['quantiles']
for q in quantiles:
buffer += ', ' + str(qvalues[q][index])
return buffer + '\n' | [
"def",
"_csv_str",
"(",
"self",
",",
"param",
",",
"stats",
",",
"quantiles",
",",
"index",
"=",
"None",
")",
":",
"buffer",
"=",
"param",
"if",
"not",
"index",
":",
"buffer",
"+=",
"', '",
"else",
":",
"buffer",
"+=",
"'_'",
"+",
"'_'",
".",
"join... | Support function for write_csv | [
"Support",
"function",
"for",
"write_csv"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L425-L447 |
225,305 | pymc-devs/pymc | pymc/Model.py | Sampler.summary | def summary(self, variables=None, alpha=0.05, start=0, batches=100,
chain=None, roundto=3):
"""
Generate a pretty-printed summary of the model's variables.
:Parameters:
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
Batch size for calculating standard deviation for non-independent
samples. Defaults to 100.
chain : int
The index for which chain to summarize. Defaults to None (all
chains).
roundto : int
The number of digits to round posterior statistics.
quantiles : tuple or list
The desired quantiles to be calculated. Defaults to (2.5, 25, 50, 75, 97.5).
"""
# If no names provided, run them all
if variables is None:
variables = self._variables_to_tally
else:
variables = [
self.__dict__[
i] for i in variables if self.__dict__[
i] in self._variables_to_tally]
# Loop over nodes
for variable in variables:
variable.summary(
alpha=alpha, start=start, batches=batches, chain=chain,
roundto=roundto) | python | def summary(self, variables=None, alpha=0.05, start=0, batches=100,
chain=None, roundto=3):
"""
Generate a pretty-printed summary of the model's variables.
:Parameters:
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
Batch size for calculating standard deviation for non-independent
samples. Defaults to 100.
chain : int
The index for which chain to summarize. Defaults to None (all
chains).
roundto : int
The number of digits to round posterior statistics.
quantiles : tuple or list
The desired quantiles to be calculated. Defaults to (2.5, 25, 50, 75, 97.5).
"""
# If no names provided, run them all
if variables is None:
variables = self._variables_to_tally
else:
variables = [
self.__dict__[
i] for i in variables if self.__dict__[
i] in self._variables_to_tally]
# Loop over nodes
for variable in variables:
variable.summary(
alpha=alpha, start=start, batches=batches, chain=chain,
roundto=roundto) | [
"def",
"summary",
"(",
"self",
",",
"variables",
"=",
"None",
",",
"alpha",
"=",
"0.05",
",",
"start",
"=",
"0",
",",
"batches",
"=",
"100",
",",
"chain",
"=",
"None",
",",
"roundto",
"=",
"3",
")",
":",
"# If no names provided, run them all",
"if",
"v... | Generate a pretty-printed summary of the model's variables.
:Parameters:
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
Batch size for calculating standard deviation for non-independent
samples. Defaults to 100.
chain : int
The index for which chain to summarize. Defaults to None (all
chains).
roundto : int
The number of digits to round posterior statistics.
quantiles : tuple or list
The desired quantiles to be calculated. Defaults to (2.5, 25, 50, 75, 97.5). | [
"Generate",
"a",
"pretty",
"-",
"printed",
"summary",
"of",
"the",
"model",
"s",
"variables",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L449-L491 |
225,306 | pymc-devs/pymc | pymc/Model.py | Sampler._assign_database_backend | def _assign_database_backend(self, db):
"""Assign Trace instance to stochastics and deterministics and Database instance
to self.
:Parameters:
- `db` : string, Database instance
The name of the database module (see below), or a Database instance.
Available databases:
- `no_trace` : Traces are not stored at all.
- `ram` : Traces stored in memory.
- `txt` : Traces stored in memory and saved in txt files at end of
sampling.
- `sqlite` : Traces stored in sqlite database.
- `hdf5` : Traces stored in an HDF5 file.
"""
# Objects that are not to be tallied are assigned a no_trace.Trace
# Tallyable objects are listed in the _nodes_to_tally set.
no_trace = getattr(database, 'no_trace')
self._variables_to_tally = set()
for object in self.stochastics | self.deterministics:
if object.keep_trace:
self._variables_to_tally.add(object)
try:
if object.mask is None:
# Standard stochastic
self._funs_to_tally[object.__name__] = object.get_value
else:
# Has missing values, so only fetch stochastic elements
# using mask
self._funs_to_tally[
object.__name__] = object.get_stoch_value
except AttributeError:
# Not a stochastic object, so no mask
self._funs_to_tally[object.__name__] = object.get_value
else:
object.trace = no_trace.Trace(object.__name__)
check_valid_object_name(self._variables_to_tally)
# If not already done, load the trace backend from the database
# module, and assign a database instance to Model.
if isinstance(db, str):
if db in dir(database):
module = getattr(database, db)
# Assign a default name for the database output file.
if self._db_args.get('dbname') is None:
self._db_args['dbname'] = self.__name__ + '.' + db
self.db = module.Database(**self._db_args)
elif db in database.__modules__:
raise ImportError(
'Database backend `%s` is not properly installed. Please see the documentation for instructions.' % db)
else:
raise AttributeError(
'Database backend `%s` is not defined in pymc.database.' % db)
elif isinstance(db, database.base.Database):
self.db = db
self.restore_sampler_state()
else: # What is this for? DH.
self.db = db.Database(**self._db_args) | python | def _assign_database_backend(self, db):
"""Assign Trace instance to stochastics and deterministics and Database instance
to self.
:Parameters:
- `db` : string, Database instance
The name of the database module (see below), or a Database instance.
Available databases:
- `no_trace` : Traces are not stored at all.
- `ram` : Traces stored in memory.
- `txt` : Traces stored in memory and saved in txt files at end of
sampling.
- `sqlite` : Traces stored in sqlite database.
- `hdf5` : Traces stored in an HDF5 file.
"""
# Objects that are not to be tallied are assigned a no_trace.Trace
# Tallyable objects are listed in the _nodes_to_tally set.
no_trace = getattr(database, 'no_trace')
self._variables_to_tally = set()
for object in self.stochastics | self.deterministics:
if object.keep_trace:
self._variables_to_tally.add(object)
try:
if object.mask is None:
# Standard stochastic
self._funs_to_tally[object.__name__] = object.get_value
else:
# Has missing values, so only fetch stochastic elements
# using mask
self._funs_to_tally[
object.__name__] = object.get_stoch_value
except AttributeError:
# Not a stochastic object, so no mask
self._funs_to_tally[object.__name__] = object.get_value
else:
object.trace = no_trace.Trace(object.__name__)
check_valid_object_name(self._variables_to_tally)
# If not already done, load the trace backend from the database
# module, and assign a database instance to Model.
if isinstance(db, str):
if db in dir(database):
module = getattr(database, db)
# Assign a default name for the database output file.
if self._db_args.get('dbname') is None:
self._db_args['dbname'] = self.__name__ + '.' + db
self.db = module.Database(**self._db_args)
elif db in database.__modules__:
raise ImportError(
'Database backend `%s` is not properly installed. Please see the documentation for instructions.' % db)
else:
raise AttributeError(
'Database backend `%s` is not defined in pymc.database.' % db)
elif isinstance(db, database.base.Database):
self.db = db
self.restore_sampler_state()
else: # What is this for? DH.
self.db = db.Database(**self._db_args) | [
"def",
"_assign_database_backend",
"(",
"self",
",",
"db",
")",
":",
"# Objects that are not to be tallied are assigned a no_trace.Trace",
"# Tallyable objects are listed in the _nodes_to_tally set.",
"no_trace",
"=",
"getattr",
"(",
"database",
",",
"'no_trace'",
")",
"self",
... | Assign Trace instance to stochastics and deterministics and Database instance
to self.
:Parameters:
- `db` : string, Database instance
The name of the database module (see below), or a Database instance.
Available databases:
- `no_trace` : Traces are not stored at all.
- `ram` : Traces stored in memory.
- `txt` : Traces stored in memory and saved in txt files at end of
sampling.
- `sqlite` : Traces stored in sqlite database.
- `hdf5` : Traces stored in an HDF5 file. | [
"Assign",
"Trace",
"instance",
"to",
"stochastics",
"and",
"deterministics",
"and",
"Database",
"instance",
"to",
"self",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L516-L579 |
225,307 | pymc-devs/pymc | pymc/Model.py | Sampler.pause | def pause(self):
"""Pause the sampler. Sampling can be resumed by calling `icontinue`.
"""
self.status = 'paused'
# The _loop method will react to 'paused' status and stop looping.
if hasattr(
self, '_sampling_thread') and self._sampling_thread.isAlive():
print_('Waiting for current iteration to finish...')
while self._sampling_thread.isAlive():
sleep(.1) | python | def pause(self):
"""Pause the sampler. Sampling can be resumed by calling `icontinue`.
"""
self.status = 'paused'
# The _loop method will react to 'paused' status and stop looping.
if hasattr(
self, '_sampling_thread') and self._sampling_thread.isAlive():
print_('Waiting for current iteration to finish...')
while self._sampling_thread.isAlive():
sleep(.1) | [
"def",
"pause",
"(",
"self",
")",
":",
"self",
".",
"status",
"=",
"'paused'",
"# The _loop method will react to 'paused' status and stop looping.",
"if",
"hasattr",
"(",
"self",
",",
"'_sampling_thread'",
")",
"and",
"self",
".",
"_sampling_thread",
".",
"isAlive",
... | Pause the sampler. Sampling can be resumed by calling `icontinue`. | [
"Pause",
"the",
"sampler",
".",
"Sampling",
"can",
"be",
"resumed",
"by",
"calling",
"icontinue",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L581-L590 |
225,308 | pymc-devs/pymc | pymc/Model.py | Sampler.halt | def halt(self):
"""Halt a sampling running in another thread."""
self.status = 'halt'
# The _halt method is called by _loop.
if hasattr(
self, '_sampling_thread') and self._sampling_thread.isAlive():
print_('Waiting for current iteration to finish...')
while self._sampling_thread.isAlive():
sleep(.1) | python | def halt(self):
"""Halt a sampling running in another thread."""
self.status = 'halt'
# The _halt method is called by _loop.
if hasattr(
self, '_sampling_thread') and self._sampling_thread.isAlive():
print_('Waiting for current iteration to finish...')
while self._sampling_thread.isAlive():
sleep(.1) | [
"def",
"halt",
"(",
"self",
")",
":",
"self",
".",
"status",
"=",
"'halt'",
"# The _halt method is called by _loop.",
"if",
"hasattr",
"(",
"self",
",",
"'_sampling_thread'",
")",
"and",
"self",
".",
"_sampling_thread",
".",
"isAlive",
"(",
")",
":",
"print_",... | Halt a sampling running in another thread. | [
"Halt",
"a",
"sampling",
"running",
"in",
"another",
"thread",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L592-L600 |
225,309 | pymc-devs/pymc | pymc/Model.py | Sampler.isample | def isample(self, *args, **kwds):
"""
Samples in interactive mode. Main thread of control stays in this function.
"""
self._exc_info = None
out = kwds.pop('out', sys.stdout)
kwds['progress_bar'] = False
def samp_targ(*args, **kwds):
try:
self.sample(*args, **kwds)
except:
self._exc_info = sys.exc_info()
self._sampling_thread = Thread(
target=samp_targ,
args=args,
kwargs=kwds)
self.status = 'running'
self._sampling_thread.start()
self.iprompt(out=out) | python | def isample(self, *args, **kwds):
"""
Samples in interactive mode. Main thread of control stays in this function.
"""
self._exc_info = None
out = kwds.pop('out', sys.stdout)
kwds['progress_bar'] = False
def samp_targ(*args, **kwds):
try:
self.sample(*args, **kwds)
except:
self._exc_info = sys.exc_info()
self._sampling_thread = Thread(
target=samp_targ,
args=args,
kwargs=kwds)
self.status = 'running'
self._sampling_thread.start()
self.iprompt(out=out) | [
"def",
"isample",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"self",
".",
"_exc_info",
"=",
"None",
"out",
"=",
"kwds",
".",
"pop",
"(",
"'out'",
",",
"sys",
".",
"stdout",
")",
"kwds",
"[",
"'progress_bar'",
"]",
"=",
"False... | Samples in interactive mode. Main thread of control stays in this function. | [
"Samples",
"in",
"interactive",
"mode",
".",
"Main",
"thread",
"of",
"control",
"stays",
"in",
"this",
"function",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L632-L652 |
225,310 | pymc-devs/pymc | pymc/Model.py | Sampler.icontinue | def icontinue(self):
"""
Restarts thread in interactive mode
"""
if self.status != 'paused':
print_(
"No sampling to continue. Please initiate sampling with isample.")
return
def sample_and_finalize():
self._loop()
self._finalize()
self._sampling_thread = Thread(target=sample_and_finalize)
self.status = 'running'
self._sampling_thread.start()
self.iprompt() | python | def icontinue(self):
"""
Restarts thread in interactive mode
"""
if self.status != 'paused':
print_(
"No sampling to continue. Please initiate sampling with isample.")
return
def sample_and_finalize():
self._loop()
self._finalize()
self._sampling_thread = Thread(target=sample_and_finalize)
self.status = 'running'
self._sampling_thread.start()
self.iprompt() | [
"def",
"icontinue",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"!=",
"'paused'",
":",
"print_",
"(",
"\"No sampling to continue. Please initiate sampling with isample.\"",
")",
"return",
"def",
"sample_and_finalize",
"(",
")",
":",
"self",
".",
"_loop",
"... | Restarts thread in interactive mode | [
"Restarts",
"thread",
"in",
"interactive",
"mode"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L654-L670 |
225,311 | pymc-devs/pymc | pymc/Model.py | Sampler.get_state | def get_state(self):
"""
Return the sampler's current state in order to
restart sampling at a later time.
"""
state = dict(sampler={}, stochastics={})
# The state of the sampler itself.
for s in self._state:
state['sampler'][s] = getattr(self, s)
# The state of each stochastic parameter
for s in self.stochastics:
state['stochastics'][s.__name__] = s.value
return state | python | def get_state(self):
"""
Return the sampler's current state in order to
restart sampling at a later time.
"""
state = dict(sampler={}, stochastics={})
# The state of the sampler itself.
for s in self._state:
state['sampler'][s] = getattr(self, s)
# The state of each stochastic parameter
for s in self.stochastics:
state['stochastics'][s.__name__] = s.value
return state | [
"def",
"get_state",
"(",
"self",
")",
":",
"state",
"=",
"dict",
"(",
"sampler",
"=",
"{",
"}",
",",
"stochastics",
"=",
"{",
"}",
")",
"# The state of the sampler itself.",
"for",
"s",
"in",
"self",
".",
"_state",
":",
"state",
"[",
"'sampler'",
"]",
... | Return the sampler's current state in order to
restart sampling at a later time. | [
"Return",
"the",
"sampler",
"s",
"current",
"state",
"in",
"order",
"to",
"restart",
"sampling",
"at",
"a",
"later",
"time",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L751-L764 |
225,312 | pymc-devs/pymc | pymc/Model.py | Sampler.save_state | def save_state(self):
"""
Tell the database to save the current state of the sampler.
"""
try:
self.db.savestate(self.get_state())
except:
print_('Warning, unable to save state.')
print_('Error message:')
traceback.print_exc() | python | def save_state(self):
"""
Tell the database to save the current state of the sampler.
"""
try:
self.db.savestate(self.get_state())
except:
print_('Warning, unable to save state.')
print_('Error message:')
traceback.print_exc() | [
"def",
"save_state",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"db",
".",
"savestate",
"(",
"self",
".",
"get_state",
"(",
")",
")",
"except",
":",
"print_",
"(",
"'Warning, unable to save state.'",
")",
"print_",
"(",
"'Error message:'",
")",
"trace... | Tell the database to save the current state of the sampler. | [
"Tell",
"the",
"database",
"to",
"save",
"the",
"current",
"state",
"of",
"the",
"sampler",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L766-L775 |
225,313 | pymc-devs/pymc | pymc/Model.py | Sampler.restore_sampler_state | def restore_sampler_state(self):
"""
Restore the state of the sampler and to
the state stored in the database.
"""
state = self.db.getstate() or {}
# Restore sampler's state
sampler_state = state.get('sampler', {})
self.__dict__.update(sampler_state)
# Restore stochastic parameters state
stoch_state = state.get('stochastics', {})
for sm in self.stochastics:
try:
sm.value = stoch_state[sm.__name__]
except:
warnings.warn(
'Failed to restore state of stochastic %s from %s backend' %
(sm.__name__, self.db.__name__)) | python | def restore_sampler_state(self):
"""
Restore the state of the sampler and to
the state stored in the database.
"""
state = self.db.getstate() or {}
# Restore sampler's state
sampler_state = state.get('sampler', {})
self.__dict__.update(sampler_state)
# Restore stochastic parameters state
stoch_state = state.get('stochastics', {})
for sm in self.stochastics:
try:
sm.value = stoch_state[sm.__name__]
except:
warnings.warn(
'Failed to restore state of stochastic %s from %s backend' %
(sm.__name__, self.db.__name__)) | [
"def",
"restore_sampler_state",
"(",
"self",
")",
":",
"state",
"=",
"self",
".",
"db",
".",
"getstate",
"(",
")",
"or",
"{",
"}",
"# Restore sampler's state",
"sampler_state",
"=",
"state",
".",
"get",
"(",
"'sampler'",
",",
"{",
"}",
")",
"self",
".",
... | Restore the state of the sampler and to
the state stored in the database. | [
"Restore",
"the",
"state",
"of",
"the",
"sampler",
"and",
"to",
"the",
"state",
"stored",
"in",
"the",
"database",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L777-L797 |
225,314 | pymc-devs/pymc | pymc/utils.py | normcdf | def normcdf(x, log=False):
"""Normal cumulative density function."""
y = np.atleast_1d(x).copy()
flib.normcdf(y)
if log:
if (y>0).all():
return np.log(y)
return -np.inf
return y | python | def normcdf(x, log=False):
"""Normal cumulative density function."""
y = np.atleast_1d(x).copy()
flib.normcdf(y)
if log:
if (y>0).all():
return np.log(y)
return -np.inf
return y | [
"def",
"normcdf",
"(",
"x",
",",
"log",
"=",
"False",
")",
":",
"y",
"=",
"np",
".",
"atleast_1d",
"(",
"x",
")",
".",
"copy",
"(",
")",
"flib",
".",
"normcdf",
"(",
"y",
")",
"if",
"log",
":",
"if",
"(",
"y",
">",
"0",
")",
".",
"all",
"... | Normal cumulative density function. | [
"Normal",
"cumulative",
"density",
"function",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/utils.py#L453-L461 |
225,315 | pymc-devs/pymc | pymc/utils.py | lognormcdf | def lognormcdf(x, mu, tau):
"""Log-normal cumulative density function"""
x = np.atleast_1d(x)
return np.array(
[0.5 * (1 - flib.derf(-(np.sqrt(tau / 2)) * (np.log(y) - mu))) for y in x]) | python | def lognormcdf(x, mu, tau):
"""Log-normal cumulative density function"""
x = np.atleast_1d(x)
return np.array(
[0.5 * (1 - flib.derf(-(np.sqrt(tau / 2)) * (np.log(y) - mu))) for y in x]) | [
"def",
"lognormcdf",
"(",
"x",
",",
"mu",
",",
"tau",
")",
":",
"x",
"=",
"np",
".",
"atleast_1d",
"(",
"x",
")",
"return",
"np",
".",
"array",
"(",
"[",
"0.5",
"*",
"(",
"1",
"-",
"flib",
".",
"derf",
"(",
"-",
"(",
"np",
".",
"sqrt",
"(",... | Log-normal cumulative density function | [
"Log",
"-",
"normal",
"cumulative",
"density",
"function"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/utils.py#L464-L468 |
225,316 | pymc-devs/pymc | pymc/utils.py | invcdf | def invcdf(x):
"""Inverse of normal cumulative density function."""
x_flat = np.ravel(x)
x_trans = np.array([flib.ppnd16(y, 1) for y in x_flat])
return np.reshape(x_trans, np.shape(x)) | python | def invcdf(x):
"""Inverse of normal cumulative density function."""
x_flat = np.ravel(x)
x_trans = np.array([flib.ppnd16(y, 1) for y in x_flat])
return np.reshape(x_trans, np.shape(x)) | [
"def",
"invcdf",
"(",
"x",
")",
":",
"x_flat",
"=",
"np",
".",
"ravel",
"(",
"x",
")",
"x_trans",
"=",
"np",
".",
"array",
"(",
"[",
"flib",
".",
"ppnd16",
"(",
"y",
",",
"1",
")",
"for",
"y",
"in",
"x_flat",
"]",
")",
"return",
"np",
".",
... | Inverse of normal cumulative density function. | [
"Inverse",
"of",
"normal",
"cumulative",
"density",
"function",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/utils.py#L471-L475 |
225,317 | pymc-devs/pymc | pymc/utils.py | trace_generator | def trace_generator(trace, start=0, stop=None, step=1):
"""Return a generator returning values from the object's trace.
Ex:
T = trace_generator(theta.trace)
T.next()
for t in T:...
"""
i = start
stop = stop or np.inf
size = min(trace.length(), stop)
while i < size:
index = slice(i, i + 1)
yield trace.gettrace(slicing=index)[0]
i += step | python | def trace_generator(trace, start=0, stop=None, step=1):
"""Return a generator returning values from the object's trace.
Ex:
T = trace_generator(theta.trace)
T.next()
for t in T:...
"""
i = start
stop = stop or np.inf
size = min(trace.length(), stop)
while i < size:
index = slice(i, i + 1)
yield trace.gettrace(slicing=index)[0]
i += step | [
"def",
"trace_generator",
"(",
"trace",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"None",
",",
"step",
"=",
"1",
")",
":",
"i",
"=",
"start",
"stop",
"=",
"stop",
"or",
"np",
".",
"inf",
"size",
"=",
"min",
"(",
"trace",
".",
"length",
"(",
")"... | Return a generator returning values from the object's trace.
Ex:
T = trace_generator(theta.trace)
T.next()
for t in T:... | [
"Return",
"a",
"generator",
"returning",
"values",
"from",
"the",
"object",
"s",
"trace",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/utils.py#L557-L571 |
225,318 | pymc-devs/pymc | pymc/utils.py | draw_random | def draw_random(obj, **kwds):
"""Draw random variates from obj.random method.
If the object has parents whose value must be updated, use
parent_name=trace_generator_function.
Ex:
R = draw_random(theta, beta=pymc.utils.trace_generator(beta.trace))
R.next()
"""
while True:
for k, v in six.iteritems(kwds):
obj.parents[k] = v.next()
yield obj.random() | python | def draw_random(obj, **kwds):
"""Draw random variates from obj.random method.
If the object has parents whose value must be updated, use
parent_name=trace_generator_function.
Ex:
R = draw_random(theta, beta=pymc.utils.trace_generator(beta.trace))
R.next()
"""
while True:
for k, v in six.iteritems(kwds):
obj.parents[k] = v.next()
yield obj.random() | [
"def",
"draw_random",
"(",
"obj",
",",
"*",
"*",
"kwds",
")",
":",
"while",
"True",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"kwds",
")",
":",
"obj",
".",
"parents",
"[",
"k",
"]",
"=",
"v",
".",
"next",
"(",
")",
"yield... | Draw random variates from obj.random method.
If the object has parents whose value must be updated, use
parent_name=trace_generator_function.
Ex:
R = draw_random(theta, beta=pymc.utils.trace_generator(beta.trace))
R.next() | [
"Draw",
"random",
"variates",
"from",
"obj",
".",
"random",
"method",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/utils.py#L574-L587 |
225,319 | pymc-devs/pymc | pymc/utils.py | rec_setattr | def rec_setattr(obj, attr, value):
"""Set object's attribute. May use dot notation.
>>> class C(object): pass
>>> a = C()
>>> a.b = C()
>>> a.b.c = 4
>>> rec_setattr(a, 'b.c', 2)
>>> a.b.c
2
"""
attrs = attr.split('.')
setattr(reduce(getattr, attrs[:-1], obj), attrs[-1], value) | python | def rec_setattr(obj, attr, value):
"""Set object's attribute. May use dot notation.
>>> class C(object): pass
>>> a = C()
>>> a.b = C()
>>> a.b.c = 4
>>> rec_setattr(a, 'b.c', 2)
>>> a.b.c
2
"""
attrs = attr.split('.')
setattr(reduce(getattr, attrs[:-1], obj), attrs[-1], value) | [
"def",
"rec_setattr",
"(",
"obj",
",",
"attr",
",",
"value",
")",
":",
"attrs",
"=",
"attr",
".",
"split",
"(",
"'.'",
")",
"setattr",
"(",
"reduce",
"(",
"getattr",
",",
"attrs",
"[",
":",
"-",
"1",
"]",
",",
"obj",
")",
",",
"attrs",
"[",
"-"... | Set object's attribute. May use dot notation.
>>> class C(object): pass
>>> a = C()
>>> a.b = C()
>>> a.b.c = 4
>>> rec_setattr(a, 'b.c', 2)
>>> a.b.c
2 | [
"Set",
"object",
"s",
"attribute",
".",
"May",
"use",
"dot",
"notation",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/utils.py#L603-L615 |
225,320 | pymc-devs/pymc | pymc/utils.py | calc_min_interval | def calc_min_interval(x, alpha):
"""Internal method to determine the minimum interval of
a given width
Assumes that x is sorted numpy array.
"""
n = len(x)
cred_mass = 1.0 - alpha
interval_idx_inc = int(np.floor(cred_mass * n))
n_intervals = n - interval_idx_inc
interval_width = x[interval_idx_inc:] - x[:n_intervals]
if len(interval_width) == 0:
print_('Too few elements for interval calculation')
return [None, None]
min_idx = np.argmin(interval_width)
hdi_min = x[min_idx]
hdi_max = x[min_idx + interval_idx_inc]
return [hdi_min, hdi_max] | python | def calc_min_interval(x, alpha):
"""Internal method to determine the minimum interval of
a given width
Assumes that x is sorted numpy array.
"""
n = len(x)
cred_mass = 1.0 - alpha
interval_idx_inc = int(np.floor(cred_mass * n))
n_intervals = n - interval_idx_inc
interval_width = x[interval_idx_inc:] - x[:n_intervals]
if len(interval_width) == 0:
print_('Too few elements for interval calculation')
return [None, None]
min_idx = np.argmin(interval_width)
hdi_min = x[min_idx]
hdi_max = x[min_idx + interval_idx_inc]
return [hdi_min, hdi_max] | [
"def",
"calc_min_interval",
"(",
"x",
",",
"alpha",
")",
":",
"n",
"=",
"len",
"(",
"x",
")",
"cred_mass",
"=",
"1.0",
"-",
"alpha",
"interval_idx_inc",
"=",
"int",
"(",
"np",
".",
"floor",
"(",
"cred_mass",
"*",
"n",
")",
")",
"n_intervals",
"=",
... | Internal method to determine the minimum interval of
a given width
Assumes that x is sorted numpy array. | [
"Internal",
"method",
"to",
"determine",
"the",
"minimum",
"interval",
"of",
"a",
"given",
"width"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/utils.py#L694-L715 |
225,321 | pymc-devs/pymc | pymc/utils.py | quantiles | def quantiles(x, qlist=(2.5, 25, 50, 75, 97.5)):
"""Returns a dictionary of requested quantiles from array
:Arguments:
x : Numpy array
An array containing MCMC samples
qlist : tuple or list
A list of desired quantiles (defaults to (2.5, 25, 50, 75, 97.5))
"""
# Make a copy of trace
x = x.copy()
# For multivariate node
if x.ndim > 1:
# Transpose first, then sort, then transpose back
sx = sort(x.T).T
else:
# Sort univariate node
sx = sort(x)
try:
# Generate specified quantiles
quants = [sx[int(len(sx) * q / 100.0)] for q in qlist]
return dict(zip(qlist, quants))
except IndexError:
print_("Too few elements for quantile calculation") | python | def quantiles(x, qlist=(2.5, 25, 50, 75, 97.5)):
"""Returns a dictionary of requested quantiles from array
:Arguments:
x : Numpy array
An array containing MCMC samples
qlist : tuple or list
A list of desired quantiles (defaults to (2.5, 25, 50, 75, 97.5))
"""
# Make a copy of trace
x = x.copy()
# For multivariate node
if x.ndim > 1:
# Transpose first, then sort, then transpose back
sx = sort(x.T).T
else:
# Sort univariate node
sx = sort(x)
try:
# Generate specified quantiles
quants = [sx[int(len(sx) * q / 100.0)] for q in qlist]
return dict(zip(qlist, quants))
except IndexError:
print_("Too few elements for quantile calculation") | [
"def",
"quantiles",
"(",
"x",
",",
"qlist",
"=",
"(",
"2.5",
",",
"25",
",",
"50",
",",
"75",
",",
"97.5",
")",
")",
":",
"# Make a copy of trace",
"x",
"=",
"x",
".",
"copy",
"(",
")",
"# For multivariate node",
"if",
"x",
".",
"ndim",
">",
"1",
... | Returns a dictionary of requested quantiles from array
:Arguments:
x : Numpy array
An array containing MCMC samples
qlist : tuple or list
A list of desired quantiles (defaults to (2.5, 25, 50, 75, 97.5)) | [
"Returns",
"a",
"dictionary",
"of",
"requested",
"quantiles",
"from",
"array"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/utils.py#L718-L747 |
225,322 | pymc-devs/pymc | pymc/utils.py | coda_output | def coda_output(pymc_object, name=None, chain=-1):
"""Generate output files that are compatible with CODA
:Arguments:
pymc_object : Model or Node
A PyMC object containing MCMC output.
"""
print_()
print_("Generating CODA output")
print_('=' * 50)
if name is None:
name = pymc_object.__name__
# Open trace file
trace_file = open(name + '_coda.out', 'w')
# Open index file
index_file = open(name + '_coda.ind', 'w')
variables = [pymc_object]
if hasattr(pymc_object, 'stochastics'):
variables = pymc_object.stochastics
# Initialize index
index = 1
# Loop over all parameters
for v in variables:
vname = v.__name__
print_("Processing", vname)
try:
index = _process_trace(
trace_file,
index_file,
v.trace(chain=chain),
vname,
index)
except TypeError:
pass
# Close files
trace_file.close()
index_file.close() | python | def coda_output(pymc_object, name=None, chain=-1):
"""Generate output files that are compatible with CODA
:Arguments:
pymc_object : Model or Node
A PyMC object containing MCMC output.
"""
print_()
print_("Generating CODA output")
print_('=' * 50)
if name is None:
name = pymc_object.__name__
# Open trace file
trace_file = open(name + '_coda.out', 'w')
# Open index file
index_file = open(name + '_coda.ind', 'w')
variables = [pymc_object]
if hasattr(pymc_object, 'stochastics'):
variables = pymc_object.stochastics
# Initialize index
index = 1
# Loop over all parameters
for v in variables:
vname = v.__name__
print_("Processing", vname)
try:
index = _process_trace(
trace_file,
index_file,
v.trace(chain=chain),
vname,
index)
except TypeError:
pass
# Close files
trace_file.close()
index_file.close() | [
"def",
"coda_output",
"(",
"pymc_object",
",",
"name",
"=",
"None",
",",
"chain",
"=",
"-",
"1",
")",
":",
"print_",
"(",
")",
"print_",
"(",
"\"Generating CODA output\"",
")",
"print_",
"(",
"'='",
"*",
"50",
")",
"if",
"name",
"is",
"None",
":",
"n... | Generate output files that are compatible with CODA
:Arguments:
pymc_object : Model or Node
A PyMC object containing MCMC output. | [
"Generate",
"output",
"files",
"that",
"are",
"compatible",
"with",
"CODA"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/utils.py#L750-L796 |
225,323 | pymc-devs/pymc | pymc/utils.py | getInput | def getInput():
"""Read the input buffer without blocking the system."""
input = ''
if sys.platform == 'win32':
import msvcrt
if msvcrt.kbhit(): # Check for a keyboard hit.
input += msvcrt.getch()
print_(input)
else:
time.sleep(.1)
else: # Other platforms
# Posix will work with sys.stdin or sys.stdin.fileno()
# Mac needs the file descriptor.
# This solution does not work for windows since select
# expects a socket, and I have no idea how to create a
# socket from standard input.
sock = sys.stdin.fileno()
# select(rlist, wlist, xlist, timeout)
while len(select.select([sock], [], [], 0.1)[0]) > 0:
input += decode(os.read(sock, 4096))
return input | python | def getInput():
"""Read the input buffer without blocking the system."""
input = ''
if sys.platform == 'win32':
import msvcrt
if msvcrt.kbhit(): # Check for a keyboard hit.
input += msvcrt.getch()
print_(input)
else:
time.sleep(.1)
else: # Other platforms
# Posix will work with sys.stdin or sys.stdin.fileno()
# Mac needs the file descriptor.
# This solution does not work for windows since select
# expects a socket, and I have no idea how to create a
# socket from standard input.
sock = sys.stdin.fileno()
# select(rlist, wlist, xlist, timeout)
while len(select.select([sock], [], [], 0.1)[0]) > 0:
input += decode(os.read(sock, 4096))
return input | [
"def",
"getInput",
"(",
")",
":",
"input",
"=",
"''",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"import",
"msvcrt",
"if",
"msvcrt",
".",
"kbhit",
"(",
")",
":",
"# Check for a keyboard hit.",
"input",
"+=",
"msvcrt",
".",
"getch",
"(",
")",
"... | Read the input buffer without blocking the system. | [
"Read",
"the",
"input",
"buffer",
"without",
"blocking",
"the",
"system",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/utils.py#L834-L858 |
225,324 | pymc-devs/pymc | pymc/utils.py | find_generations | def find_generations(container, with_data=False):
"""
A generation is the set of stochastic variables that only has parents in
previous generations.
"""
generations = []
# Find root generation
generations.append(set())
all_children = set()
if with_data:
stochastics_to_iterate = container.stochastics | container.observed_stochastics
else:
stochastics_to_iterate = container.stochastics
for s in stochastics_to_iterate:
all_children.update(s.extended_children & stochastics_to_iterate)
generations[0] = stochastics_to_iterate - all_children
# Find subsequent _generations
children_remaining = True
gen_num = 0
while children_remaining:
gen_num += 1
# Find children of last generation
generations.append(set())
for s in generations[gen_num - 1]:
generations[gen_num].update(
s.extended_children & stochastics_to_iterate)
# Take away stochastics that have parents in the current generation.
thisgen_children = set()
for s in generations[gen_num]:
thisgen_children.update(
s.extended_children & stochastics_to_iterate)
generations[gen_num] -= thisgen_children
# Stop when no subsequent _generations remain
if len(thisgen_children) == 0:
children_remaining = False
return generations | python | def find_generations(container, with_data=False):
"""
A generation is the set of stochastic variables that only has parents in
previous generations.
"""
generations = []
# Find root generation
generations.append(set())
all_children = set()
if with_data:
stochastics_to_iterate = container.stochastics | container.observed_stochastics
else:
stochastics_to_iterate = container.stochastics
for s in stochastics_to_iterate:
all_children.update(s.extended_children & stochastics_to_iterate)
generations[0] = stochastics_to_iterate - all_children
# Find subsequent _generations
children_remaining = True
gen_num = 0
while children_remaining:
gen_num += 1
# Find children of last generation
generations.append(set())
for s in generations[gen_num - 1]:
generations[gen_num].update(
s.extended_children & stochastics_to_iterate)
# Take away stochastics that have parents in the current generation.
thisgen_children = set()
for s in generations[gen_num]:
thisgen_children.update(
s.extended_children & stochastics_to_iterate)
generations[gen_num] -= thisgen_children
# Stop when no subsequent _generations remain
if len(thisgen_children) == 0:
children_remaining = False
return generations | [
"def",
"find_generations",
"(",
"container",
",",
"with_data",
"=",
"False",
")",
":",
"generations",
"=",
"[",
"]",
"# Find root generation",
"generations",
".",
"append",
"(",
"set",
"(",
")",
")",
"all_children",
"=",
"set",
"(",
")",
"if",
"with_data",
... | A generation is the set of stochastic variables that only has parents in
previous generations. | [
"A",
"generation",
"is",
"the",
"set",
"of",
"stochastic",
"variables",
"that",
"only",
"has",
"parents",
"in",
"previous",
"generations",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/utils.py#L884-L925 |
225,325 | pymc-devs/pymc | pymc/utils.py | append | def append(nodelist, node, label=None, sep='_'):
"""
Append function to automate the naming of list elements in Containers.
:Arguments:
- `nodelist` : List containing nodes for Container.
- `node` : Node to be added to list.
- `label` : Label to be appended to list (If not passed,
defaults to element number).
- `sep` : Separator character for label (defaults to underscore).
:Return:
- `nodelist` : Passed list with node added.
"""
nname = node.__name__
# Determine label
label = label or len(nodelist)
# Look for separator at the end of name
ind = nname.rfind(sep)
# If there is no separator, we will remove last character and
# replace with label.
node.__name__ = nname[:ind] + sep + str(label)
nodelist.append(node)
return nodelist | python | def append(nodelist, node, label=None, sep='_'):
"""
Append function to automate the naming of list elements in Containers.
:Arguments:
- `nodelist` : List containing nodes for Container.
- `node` : Node to be added to list.
- `label` : Label to be appended to list (If not passed,
defaults to element number).
- `sep` : Separator character for label (defaults to underscore).
:Return:
- `nodelist` : Passed list with node added.
"""
nname = node.__name__
# Determine label
label = label or len(nodelist)
# Look for separator at the end of name
ind = nname.rfind(sep)
# If there is no separator, we will remove last character and
# replace with label.
node.__name__ = nname[:ind] + sep + str(label)
nodelist.append(node)
return nodelist | [
"def",
"append",
"(",
"nodelist",
",",
"node",
",",
"label",
"=",
"None",
",",
"sep",
"=",
"'_'",
")",
":",
"nname",
"=",
"node",
".",
"__name__",
"# Determine label",
"label",
"=",
"label",
"or",
"len",
"(",
"nodelist",
")",
"# Look for separator at the e... | Append function to automate the naming of list elements in Containers.
:Arguments:
- `nodelist` : List containing nodes for Container.
- `node` : Node to be added to list.
- `label` : Label to be appended to list (If not passed,
defaults to element number).
- `sep` : Separator character for label (defaults to underscore).
:Return:
- `nodelist` : Passed list with node added. | [
"Append",
"function",
"to",
"automate",
"the",
"naming",
"of",
"list",
"elements",
"in",
"Containers",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/utils.py#L928-L958 |
225,326 | pymc-devs/pymc | pymc/PyMCObjects.py | Deterministic.logp_partial_gradient | def logp_partial_gradient(self, variable, calculation_set=None):
"""
gets the logp gradient of this deterministic with respect to variable
"""
if self.verbose > 0:
print_('\t' + self.__name__ + ': logp_partial_gradient accessed.')
if not (datatypes.is_continuous(variable)
and datatypes.is_continuous(self)):
return zeros(shape(variable.value))
# loop through all the parameters and add up all the gradients of log p
# with respect to the approrpiate variable
gradient = builtins.sum(
[child.logp_partial_gradient(self,
calculation_set) for child in self.children])
totalGradient = 0
for parameter, value in six.iteritems(self.parents):
if value is variable:
totalGradient += self.apply_jacobian(
parameter, variable, gradient)
return np.reshape(totalGradient, shape(variable.value)) | python | def logp_partial_gradient(self, variable, calculation_set=None):
"""
gets the logp gradient of this deterministic with respect to variable
"""
if self.verbose > 0:
print_('\t' + self.__name__ + ': logp_partial_gradient accessed.')
if not (datatypes.is_continuous(variable)
and datatypes.is_continuous(self)):
return zeros(shape(variable.value))
# loop through all the parameters and add up all the gradients of log p
# with respect to the approrpiate variable
gradient = builtins.sum(
[child.logp_partial_gradient(self,
calculation_set) for child in self.children])
totalGradient = 0
for parameter, value in six.iteritems(self.parents):
if value is variable:
totalGradient += self.apply_jacobian(
parameter, variable, gradient)
return np.reshape(totalGradient, shape(variable.value)) | [
"def",
"logp_partial_gradient",
"(",
"self",
",",
"variable",
",",
"calculation_set",
"=",
"None",
")",
":",
"if",
"self",
".",
"verbose",
">",
"0",
":",
"print_",
"(",
"'\\t'",
"+",
"self",
".",
"__name__",
"+",
"': logp_partial_gradient accessed.'",
")",
"... | gets the logp gradient of this deterministic with respect to variable | [
"gets",
"the",
"logp",
"gradient",
"of",
"this",
"deterministic",
"with",
"respect",
"to",
"variable"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/PyMCObjects.py#L503-L527 |
225,327 | pymc-devs/pymc | pymc/PyMCObjects.py | Stochastic.gen_lazy_function | def gen_lazy_function(self):
"""
Will be called by Node at instantiation.
"""
# If value argument to __init__ was None, draw value from random
# method.
if self._value is None:
# Use random function if provided
if self._random is not None:
self.value = self._random(**self._parents.value)
# Otherwise leave initial value at None and warn.
else:
raise ValueError(
'Stochastic ' +
self.__name__ +
"'s value initialized to None; no initial value or random method provided.")
arguments = {}
arguments.update(self.parents)
arguments['value'] = self
arguments = DictContainer(arguments)
self._logp = LazyFunction(fun=self._logp_fun,
arguments=arguments,
ultimate_args=self.extended_parents | set(
[self]),
cache_depth=self._cache_depth)
self._logp.force_compute()
self._logp_partial_gradients = {}
for parameter, function in six.iteritems(self._logp_partial_gradient_functions):
lazy_logp_partial_gradient = LazyFunction(fun=function,
arguments=arguments,
ultimate_args=self.extended_parents | set(
[self]),
cache_depth=self._cache_depth)
# lazy_logp_partial_gradient.force_compute()
self._logp_partial_gradients[parameter] = lazy_logp_partial_gradient | python | def gen_lazy_function(self):
"""
Will be called by Node at instantiation.
"""
# If value argument to __init__ was None, draw value from random
# method.
if self._value is None:
# Use random function if provided
if self._random is not None:
self.value = self._random(**self._parents.value)
# Otherwise leave initial value at None and warn.
else:
raise ValueError(
'Stochastic ' +
self.__name__ +
"'s value initialized to None; no initial value or random method provided.")
arguments = {}
arguments.update(self.parents)
arguments['value'] = self
arguments = DictContainer(arguments)
self._logp = LazyFunction(fun=self._logp_fun,
arguments=arguments,
ultimate_args=self.extended_parents | set(
[self]),
cache_depth=self._cache_depth)
self._logp.force_compute()
self._logp_partial_gradients = {}
for parameter, function in six.iteritems(self._logp_partial_gradient_functions):
lazy_logp_partial_gradient = LazyFunction(fun=function,
arguments=arguments,
ultimate_args=self.extended_parents | set(
[self]),
cache_depth=self._cache_depth)
# lazy_logp_partial_gradient.force_compute()
self._logp_partial_gradients[parameter] = lazy_logp_partial_gradient | [
"def",
"gen_lazy_function",
"(",
"self",
")",
":",
"# If value argument to __init__ was None, draw value from random",
"# method.",
"if",
"self",
".",
"_value",
"is",
"None",
":",
"# Use random function if provided",
"if",
"self",
".",
"_random",
"is",
"not",
"None",
":... | Will be called by Node at instantiation. | [
"Will",
"be",
"called",
"by",
"Node",
"at",
"instantiation",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/PyMCObjects.py#L776-L817 |
225,328 | pymc-devs/pymc | pymc/PyMCObjects.py | Stochastic.logp_gradient_contribution | def logp_gradient_contribution(self, calculation_set=None):
"""
Calculates the gradient of the joint log posterior with respect to self.
Calculation of the log posterior is restricted to the variables in calculation_set.
"""
# NEED some sort of check to see if the log p calculation has recently
# failed, in which case not to continue
return self.logp_partial_gradient(self, calculation_set) + builtins.sum(
[child.logp_partial_gradient(self, calculation_set) for child in self.children]) | python | def logp_gradient_contribution(self, calculation_set=None):
"""
Calculates the gradient of the joint log posterior with respect to self.
Calculation of the log posterior is restricted to the variables in calculation_set.
"""
# NEED some sort of check to see if the log p calculation has recently
# failed, in which case not to continue
return self.logp_partial_gradient(self, calculation_set) + builtins.sum(
[child.logp_partial_gradient(self, calculation_set) for child in self.children]) | [
"def",
"logp_gradient_contribution",
"(",
"self",
",",
"calculation_set",
"=",
"None",
")",
":",
"# NEED some sort of check to see if the log p calculation has recently",
"# failed, in which case not to continue",
"return",
"self",
".",
"logp_partial_gradient",
"(",
"self",
",",
... | Calculates the gradient of the joint log posterior with respect to self.
Calculation of the log posterior is restricted to the variables in calculation_set. | [
"Calculates",
"the",
"gradient",
"of",
"the",
"joint",
"log",
"posterior",
"with",
"respect",
"to",
"self",
".",
"Calculation",
"of",
"the",
"log",
"posterior",
"is",
"restricted",
"to",
"the",
"variables",
"in",
"calculation_set",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/PyMCObjects.py#L940-L949 |
225,329 | pymc-devs/pymc | pymc/PyMCObjects.py | Stochastic.logp_partial_gradient | def logp_partial_gradient(self, variable, calculation_set=None):
"""
Calculates the partial gradient of the posterior of self with respect to variable.
Returns zero if self is not in calculation_set.
"""
if (calculation_set is None) or (self in calculation_set):
if not datatypes.is_continuous(variable):
return zeros(shape(variable.value))
if variable is self:
try:
gradient_func = self._logp_partial_gradients['value']
except KeyError:
raise NotImplementedError(
repr(
self) +
" has no gradient function for 'value'")
gradient = np.reshape(
gradient_func.get(
),
np.shape(
variable.value))
else:
gradient = builtins.sum(
[self._pgradient(variable,
parameter,
value) for parameter,
value in six.iteritems(self.parents)])
return gradient
else:
return 0 | python | def logp_partial_gradient(self, variable, calculation_set=None):
"""
Calculates the partial gradient of the posterior of self with respect to variable.
Returns zero if self is not in calculation_set.
"""
if (calculation_set is None) or (self in calculation_set):
if not datatypes.is_continuous(variable):
return zeros(shape(variable.value))
if variable is self:
try:
gradient_func = self._logp_partial_gradients['value']
except KeyError:
raise NotImplementedError(
repr(
self) +
" has no gradient function for 'value'")
gradient = np.reshape(
gradient_func.get(
),
np.shape(
variable.value))
else:
gradient = builtins.sum(
[self._pgradient(variable,
parameter,
value) for parameter,
value in six.iteritems(self.parents)])
return gradient
else:
return 0 | [
"def",
"logp_partial_gradient",
"(",
"self",
",",
"variable",
",",
"calculation_set",
"=",
"None",
")",
":",
"if",
"(",
"calculation_set",
"is",
"None",
")",
"or",
"(",
"self",
"in",
"calculation_set",
")",
":",
"if",
"not",
"datatypes",
".",
"is_continuous"... | Calculates the partial gradient of the posterior of self with respect to variable.
Returns zero if self is not in calculation_set. | [
"Calculates",
"the",
"partial",
"gradient",
"of",
"the",
"posterior",
"of",
"self",
"with",
"respect",
"to",
"variable",
".",
"Returns",
"zero",
"if",
"self",
"is",
"not",
"in",
"calculation_set",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/PyMCObjects.py#L951-L985 |
225,330 | pymc-devs/pymc | pymc/PyMCObjects.py | Stochastic.random | def random(self):
"""
Draws a new value for a stoch conditional on its parents
and returns it.
Raises an error if no 'random' argument was passed to __init__.
"""
if self._random:
# Get current values of parents for use as arguments for _random()
r = self._random(**self.parents.value)
else:
raise AttributeError(
'Stochastic ' +
self.__name__ +
' does not know how to draw its value, see documentation')
if self.shape:
r = np.reshape(r, self.shape)
# Set Stochastic's value to drawn value
if not self.observed:
self.value = r
return r | python | def random(self):
"""
Draws a new value for a stoch conditional on its parents
and returns it.
Raises an error if no 'random' argument was passed to __init__.
"""
if self._random:
# Get current values of parents for use as arguments for _random()
r = self._random(**self.parents.value)
else:
raise AttributeError(
'Stochastic ' +
self.__name__ +
' does not know how to draw its value, see documentation')
if self.shape:
r = np.reshape(r, self.shape)
# Set Stochastic's value to drawn value
if not self.observed:
self.value = r
return r | [
"def",
"random",
"(",
"self",
")",
":",
"if",
"self",
".",
"_random",
":",
"# Get current values of parents for use as arguments for _random()",
"r",
"=",
"self",
".",
"_random",
"(",
"*",
"*",
"self",
".",
"parents",
".",
"value",
")",
"else",
":",
"raise",
... | Draws a new value for a stoch conditional on its parents
and returns it.
Raises an error if no 'random' argument was passed to __init__. | [
"Draws",
"a",
"new",
"value",
"for",
"a",
"stoch",
"conditional",
"on",
"its",
"parents",
"and",
"returns",
"it",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/PyMCObjects.py#L1002-L1026 |
225,331 | pymc-devs/pymc | pymc/database/hdf5.py | save_sampler | def save_sampler(sampler):
"""
Dumps a sampler into its hdf5 database.
"""
db = sampler.db
fnode = tables.filenode.newnode(db._h5file, where='/', name='__sampler__')
import pickle
pickle.dump(sampler, fnode) | python | def save_sampler(sampler):
"""
Dumps a sampler into its hdf5 database.
"""
db = sampler.db
fnode = tables.filenode.newnode(db._h5file, where='/', name='__sampler__')
import pickle
pickle.dump(sampler, fnode) | [
"def",
"save_sampler",
"(",
"sampler",
")",
":",
"db",
"=",
"sampler",
".",
"db",
"fnode",
"=",
"tables",
".",
"filenode",
".",
"newnode",
"(",
"db",
".",
"_h5file",
",",
"where",
"=",
"'/'",
",",
"name",
"=",
"'__sampler__'",
")",
"import",
"pickle",
... | Dumps a sampler into its hdf5 database. | [
"Dumps",
"a",
"sampler",
"into",
"its",
"hdf5",
"database",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/hdf5.py#L605-L612 |
225,332 | pymc-devs/pymc | pymc/database/hdf5.py | restore_sampler | def restore_sampler(fname):
"""
Creates a new sampler from an hdf5 database.
"""
hf = tables.open_file(fname)
fnode = hf.root.__sampler__
import pickle
sampler = pickle.load(fnode)
return sampler | python | def restore_sampler(fname):
"""
Creates a new sampler from an hdf5 database.
"""
hf = tables.open_file(fname)
fnode = hf.root.__sampler__
import pickle
sampler = pickle.load(fnode)
return sampler | [
"def",
"restore_sampler",
"(",
"fname",
")",
":",
"hf",
"=",
"tables",
".",
"open_file",
"(",
"fname",
")",
"fnode",
"=",
"hf",
".",
"root",
".",
"__sampler__",
"import",
"pickle",
"sampler",
"=",
"pickle",
".",
"load",
"(",
"fnode",
")",
"return",
"sa... | Creates a new sampler from an hdf5 database. | [
"Creates",
"a",
"new",
"sampler",
"from",
"an",
"hdf5",
"database",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/hdf5.py#L615-L623 |
225,333 | pymc-devs/pymc | pymc/database/hdf5.py | Trace.tally | def tally(self, chain):
"""Adds current value to trace"""
self.db._rows[chain][self.name] = self._getfunc() | python | def tally(self, chain):
"""Adds current value to trace"""
self.db._rows[chain][self.name] = self._getfunc() | [
"def",
"tally",
"(",
"self",
",",
"chain",
")",
":",
"self",
".",
"db",
".",
"_rows",
"[",
"chain",
"]",
"[",
"self",
".",
"name",
"]",
"=",
"self",
".",
"_getfunc",
"(",
")"
] | Adds current value to trace | [
"Adds",
"current",
"value",
"to",
"trace"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/hdf5.py#L141-L143 |
225,334 | pymc-devs/pymc | pymc/database/hdf5.py | Trace.hdf5_col | def hdf5_col(self, chain=-1):
"""Return a pytables column object.
:Parameters:
chain : integer
The index of the chain.
.. note::
This method is specific to the ``hdf5`` backend.
"""
return self.db._tables[chain].colinstances[self.name] | python | def hdf5_col(self, chain=-1):
"""Return a pytables column object.
:Parameters:
chain : integer
The index of the chain.
.. note::
This method is specific to the ``hdf5`` backend.
"""
return self.db._tables[chain].colinstances[self.name] | [
"def",
"hdf5_col",
"(",
"self",
",",
"chain",
"=",
"-",
"1",
")",
":",
"return",
"self",
".",
"db",
".",
"_tables",
"[",
"chain",
"]",
".",
"colinstances",
"[",
"self",
".",
"name",
"]"
] | Return a pytables column object.
:Parameters:
chain : integer
The index of the chain.
.. note::
This method is specific to the ``hdf5`` backend. | [
"Return",
"a",
"pytables",
"column",
"object",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/hdf5.py#L195-L205 |
225,335 | pymc-devs/pymc | pymc/database/hdf5.py | Database.savestate | def savestate(self, state, chain=-1):
"""Store a dictionnary containing the state of the Model and its
StepMethods."""
cur_chain = self._chains[chain]
if hasattr(cur_chain, '_state_'):
cur_chain._state_[0] = state
else:
s = self._h5file.create_vlarray(
cur_chain,
'_state_',
tables.ObjectAtom(),
title='The saved state of the sampler',
filters=self.filter)
s.append(state)
self._h5file.flush() | python | def savestate(self, state, chain=-1):
"""Store a dictionnary containing the state of the Model and its
StepMethods."""
cur_chain = self._chains[chain]
if hasattr(cur_chain, '_state_'):
cur_chain._state_[0] = state
else:
s = self._h5file.create_vlarray(
cur_chain,
'_state_',
tables.ObjectAtom(),
title='The saved state of the sampler',
filters=self.filter)
s.append(state)
self._h5file.flush() | [
"def",
"savestate",
"(",
"self",
",",
"state",
",",
"chain",
"=",
"-",
"1",
")",
":",
"cur_chain",
"=",
"self",
".",
"_chains",
"[",
"chain",
"]",
"if",
"hasattr",
"(",
"cur_chain",
",",
"'_state_'",
")",
":",
"cur_chain",
".",
"_state_",
"[",
"0",
... | Store a dictionnary containing the state of the Model and its
StepMethods. | [
"Store",
"a",
"dictionnary",
"containing",
"the",
"state",
"of",
"the",
"Model",
"and",
"its",
"StepMethods",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/hdf5.py#L485-L499 |
225,336 | pymc-devs/pymc | pymc/database/hdf5.py | Database._model_trace_description | def _model_trace_description(self):
"""Return a description of the table and the ObjectAtoms to be created.
:Returns:
table_description : dict
A Description of the pyTables table.
ObjectAtomsn : dict
A
in terms of PyTables
columns, and a"""
D = {}
for name, fun in six.iteritems(self.model._funs_to_tally):
arr = asarray(fun())
D[name] = tables.Col.from_dtype(dtype((arr.dtype, arr.shape)))
return D, {} | python | def _model_trace_description(self):
"""Return a description of the table and the ObjectAtoms to be created.
:Returns:
table_description : dict
A Description of the pyTables table.
ObjectAtomsn : dict
A
in terms of PyTables
columns, and a"""
D = {}
for name, fun in six.iteritems(self.model._funs_to_tally):
arr = asarray(fun())
D[name] = tables.Col.from_dtype(dtype((arr.dtype, arr.shape)))
return D, {} | [
"def",
"_model_trace_description",
"(",
"self",
")",
":",
"D",
"=",
"{",
"}",
"for",
"name",
",",
"fun",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"model",
".",
"_funs_to_tally",
")",
":",
"arr",
"=",
"asarray",
"(",
"fun",
"(",
")",
")",
"D... | Return a description of the table and the ObjectAtoms to be created.
:Returns:
table_description : dict
A Description of the pyTables table.
ObjectAtomsn : dict
A
in terms of PyTables
columns, and a | [
"Return",
"a",
"description",
"of",
"the",
"table",
"and",
"the",
"ObjectAtoms",
"to",
"be",
"created",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/hdf5.py#L512-L526 |
225,337 | pymc-devs/pymc | pymc/database/hdf5.py | Database._check_compatibility | def _check_compatibility(self):
"""Make sure the next objects to be tallied are compatible with the
stored trace."""
stored_descr = self._file_trace_description()
try:
for k, v in self._model_trace_description():
assert(stored_descr[k][0] == v[0])
except:
raise ValueError(
"The objects to tally are incompatible with the objects stored in the file.") | python | def _check_compatibility(self):
"""Make sure the next objects to be tallied are compatible with the
stored trace."""
stored_descr = self._file_trace_description()
try:
for k, v in self._model_trace_description():
assert(stored_descr[k][0] == v[0])
except:
raise ValueError(
"The objects to tally are incompatible with the objects stored in the file.") | [
"def",
"_check_compatibility",
"(",
"self",
")",
":",
"stored_descr",
"=",
"self",
".",
"_file_trace_description",
"(",
")",
"try",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_model_trace_description",
"(",
")",
":",
"assert",
"(",
"stored_descr",
"[",
... | Make sure the next objects to be tallied are compatible with the
stored trace. | [
"Make",
"sure",
"the",
"next",
"objects",
"to",
"be",
"tallied",
"are",
"compatible",
"with",
"the",
"stored",
"trace",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/hdf5.py#L533-L542 |
225,338 | pymc-devs/pymc | pymc/database/hdf5.py | Database._gettables | def _gettables(self):
"""Return a list of hdf5 tables name PyMCsamples.
"""
groups = self._h5file.list_nodes("/")
if len(groups) == 0:
return []
else:
return [
gr.PyMCsamples for gr in groups if gr._v_name[:5] == 'chain'] | python | def _gettables(self):
"""Return a list of hdf5 tables name PyMCsamples.
"""
groups = self._h5file.list_nodes("/")
if len(groups) == 0:
return []
else:
return [
gr.PyMCsamples for gr in groups if gr._v_name[:5] == 'chain'] | [
"def",
"_gettables",
"(",
"self",
")",
":",
"groups",
"=",
"self",
".",
"_h5file",
".",
"list_nodes",
"(",
"\"/\"",
")",
"if",
"len",
"(",
"groups",
")",
"==",
"0",
":",
"return",
"[",
"]",
"else",
":",
"return",
"[",
"gr",
".",
"PyMCsamples",
"for... | Return a list of hdf5 tables name PyMCsamples. | [
"Return",
"a",
"list",
"of",
"hdf5",
"tables",
"name",
"PyMCsamples",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/hdf5.py#L544-L553 |
225,339 | pymc-devs/pymc | pymc/database/hdf5.py | Database.add_attr | def add_attr(self, name, object, description='', chain=-1, array=False):
"""Add an attribute to the chain.
description may not be supported for every date type.
if array is true, create an Array object.
"""
if not np.isscalar(chain):
raise TypeError("chain must be a scalar integer.")
table = self._tables[chain]
if array is False:
table.set_attr(name, object)
obj = getattr(table.attrs, name)
else:
# Create an array in the group
if description == '':
description = name
group = table._g_getparent()
self._h5file.create_array(group, name, object, description)
obj = getattr(group, name)
setattr(self, name, obj) | python | def add_attr(self, name, object, description='', chain=-1, array=False):
"""Add an attribute to the chain.
description may not be supported for every date type.
if array is true, create an Array object.
"""
if not np.isscalar(chain):
raise TypeError("chain must be a scalar integer.")
table = self._tables[chain]
if array is False:
table.set_attr(name, object)
obj = getattr(table.attrs, name)
else:
# Create an array in the group
if description == '':
description = name
group = table._g_getparent()
self._h5file.create_array(group, name, object, description)
obj = getattr(group, name)
setattr(self, name, obj) | [
"def",
"add_attr",
"(",
"self",
",",
"name",
",",
"object",
",",
"description",
"=",
"''",
",",
"chain",
"=",
"-",
"1",
",",
"array",
"=",
"False",
")",
":",
"if",
"not",
"np",
".",
"isscalar",
"(",
"chain",
")",
":",
"raise",
"TypeError",
"(",
"... | Add an attribute to the chain.
description may not be supported for every date type.
if array is true, create an Array object. | [
"Add",
"an",
"attribute",
"to",
"the",
"chain",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/hdf5.py#L558-L581 |
225,340 | pymc-devs/pymc | pymc/examples/disaster_model.py | rate | def rate(s=switchpoint, e=early_mean, l=late_mean):
''' Concatenate Poisson means '''
out = empty(len(disasters_array))
out[:s] = e
out[s:] = l
return out | python | def rate(s=switchpoint, e=early_mean, l=late_mean):
''' Concatenate Poisson means '''
out = empty(len(disasters_array))
out[:s] = e
out[s:] = l
return out | [
"def",
"rate",
"(",
"s",
"=",
"switchpoint",
",",
"e",
"=",
"early_mean",
",",
"l",
"=",
"late_mean",
")",
":",
"out",
"=",
"empty",
"(",
"len",
"(",
"disasters_array",
")",
")",
"out",
"[",
":",
"s",
"]",
"=",
"e",
"out",
"[",
"s",
":",
"]",
... | Concatenate Poisson means | [
"Concatenate",
"Poisson",
"means"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/examples/disaster_model.py#L43-L48 |
225,341 | pymc-devs/pymc | pymc/gp/cov_funs/cov_utils.py | regularize_array | def regularize_array(A):
"""
Takes an np.ndarray as an input.
- If the array is one-dimensional, it's assumed to be an array of input values.
- If the array is more than one-dimensional, its last index is assumed to curse
over spatial dimension.
Either way, the return value is at least two dimensional. A.shape[-1] gives the
number of spatial dimensions.
"""
if not isinstance(A,np.ndarray):
A = np.array(A, dtype=float)
else:
A = np.asarray(A, dtype=float)
if len(A.shape) <= 1:
return A.reshape(-1,1)
elif A.shape[-1]>1:
return A.reshape(-1, A.shape[-1])
else:
return A | python | def regularize_array(A):
"""
Takes an np.ndarray as an input.
- If the array is one-dimensional, it's assumed to be an array of input values.
- If the array is more than one-dimensional, its last index is assumed to curse
over spatial dimension.
Either way, the return value is at least two dimensional. A.shape[-1] gives the
number of spatial dimensions.
"""
if not isinstance(A,np.ndarray):
A = np.array(A, dtype=float)
else:
A = np.asarray(A, dtype=float)
if len(A.shape) <= 1:
return A.reshape(-1,1)
elif A.shape[-1]>1:
return A.reshape(-1, A.shape[-1])
else:
return A | [
"def",
"regularize_array",
"(",
"A",
")",
":",
"if",
"not",
"isinstance",
"(",
"A",
",",
"np",
".",
"ndarray",
")",
":",
"A",
"=",
"np",
".",
"array",
"(",
"A",
",",
"dtype",
"=",
"float",
")",
"else",
":",
"A",
"=",
"np",
".",
"asarray",
"(",
... | Takes an np.ndarray as an input.
- If the array is one-dimensional, it's assumed to be an array of input values.
- If the array is more than one-dimensional, its last index is assumed to curse
over spatial dimension.
Either way, the return value is at least two dimensional. A.shape[-1] gives the
number of spatial dimensions. | [
"Takes",
"an",
"np",
".",
"ndarray",
"as",
"an",
"input",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/gp/cov_funs/cov_utils.py#L23-L49 |
225,342 | pymc-devs/pymc | pymc/gp/cov_funs/cov_utils.py | import_item | def import_item(name):
"""
Useful for importing nested modules such as pymc.gp.cov_funs.isotropic_cov_funs.
Updated with code copied from IPython under a BSD license.
"""
package = '.'.join(name.split('.')[0:-1])
obj = name.split('.')[-1]
if package:
module = __import__(package,fromlist=[obj])
return module.__dict__[obj]
else:
return __import__(obj) | python | def import_item(name):
"""
Useful for importing nested modules such as pymc.gp.cov_funs.isotropic_cov_funs.
Updated with code copied from IPython under a BSD license.
"""
package = '.'.join(name.split('.')[0:-1])
obj = name.split('.')[-1]
if package:
module = __import__(package,fromlist=[obj])
return module.__dict__[obj]
else:
return __import__(obj) | [
"def",
"import_item",
"(",
"name",
")",
":",
"package",
"=",
"'.'",
".",
"join",
"(",
"name",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
":",
"-",
"1",
"]",
")",
"obj",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"if",
"pa... | Useful for importing nested modules such as pymc.gp.cov_funs.isotropic_cov_funs.
Updated with code copied from IPython under a BSD license. | [
"Useful",
"for",
"importing",
"nested",
"modules",
"such",
"as",
"pymc",
".",
"gp",
".",
"cov_funs",
".",
"isotropic_cov_funs",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/gp/cov_funs/cov_utils.py#L51-L64 |
225,343 | pymc-devs/pymc | pymc/gp/cov_funs/cov_utils.py | covariance_function_bundle.add_distance_metric | def add_distance_metric(self, distance_fun_name, distance_fun_module, with_x):
"""
Takes a function that computes a distance matrix for
points in some coordinate system and returns self's
covariance function wrapped to use that distance function.
Uses function apply_distance, which was used to produce
self.euclidean and self.geographic and their docstrings.
:Parameters:
- `distance_fun`: Creates a distance matrix from two
np.arrays of points, where the first index iterates
over separate points and the second over coordinates.
In addition to the arrays x and y, distance_fun should
take an argument called symm which indicates whether
x and y are the same array.
:SeeAlso:
- `apply_distance()`
"""
if self.ampsq_is_diag:
kls = covariance_wrapper_with_diag
else:
kls = covariance_wrapper
new_fun = kls(self.cov_fun_name, self.cov_fun_module, self.extra_cov_params, distance_fun_name, distance_fun_module, with_x=with_x)
self.wrappers.append(new_fun)
# try:
setattr(self, distance_fun_name, new_fun)
# except:
# pass
return new_fun | python | def add_distance_metric(self, distance_fun_name, distance_fun_module, with_x):
"""
Takes a function that computes a distance matrix for
points in some coordinate system and returns self's
covariance function wrapped to use that distance function.
Uses function apply_distance, which was used to produce
self.euclidean and self.geographic and their docstrings.
:Parameters:
- `distance_fun`: Creates a distance matrix from two
np.arrays of points, where the first index iterates
over separate points and the second over coordinates.
In addition to the arrays x and y, distance_fun should
take an argument called symm which indicates whether
x and y are the same array.
:SeeAlso:
- `apply_distance()`
"""
if self.ampsq_is_diag:
kls = covariance_wrapper_with_diag
else:
kls = covariance_wrapper
new_fun = kls(self.cov_fun_name, self.cov_fun_module, self.extra_cov_params, distance_fun_name, distance_fun_module, with_x=with_x)
self.wrappers.append(new_fun)
# try:
setattr(self, distance_fun_name, new_fun)
# except:
# pass
return new_fun | [
"def",
"add_distance_metric",
"(",
"self",
",",
"distance_fun_name",
",",
"distance_fun_module",
",",
"with_x",
")",
":",
"if",
"self",
".",
"ampsq_is_diag",
":",
"kls",
"=",
"covariance_wrapper_with_diag",
"else",
":",
"kls",
"=",
"covariance_wrapper",
"new_fun",
... | Takes a function that computes a distance matrix for
points in some coordinate system and returns self's
covariance function wrapped to use that distance function.
Uses function apply_distance, which was used to produce
self.euclidean and self.geographic and their docstrings.
:Parameters:
- `distance_fun`: Creates a distance matrix from two
np.arrays of points, where the first index iterates
over separate points and the second over coordinates.
In addition to the arrays x and y, distance_fun should
take an argument called symm which indicates whether
x and y are the same array.
:SeeAlso:
- `apply_distance()` | [
"Takes",
"a",
"function",
"that",
"computes",
"a",
"distance",
"matrix",
"for",
"points",
"in",
"some",
"coordinate",
"system",
"and",
"returns",
"self",
"s",
"covariance",
"function",
"wrapped",
"to",
"use",
"that",
"distance",
"function",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/gp/cov_funs/cov_utils.py#L271-L307 |
225,344 | pymc-devs/pymc | pymc/NormalApproximation.py | MAP.func | def func(self, p):
"""
The function that gets passed to the optimizers.
"""
self._set_stochastics(p)
try:
return -1. * self.logp
except ZeroProbability:
return Inf | python | def func(self, p):
"""
The function that gets passed to the optimizers.
"""
self._set_stochastics(p)
try:
return -1. * self.logp
except ZeroProbability:
return Inf | [
"def",
"func",
"(",
"self",
",",
"p",
")",
":",
"self",
".",
"_set_stochastics",
"(",
"p",
")",
"try",
":",
"return",
"-",
"1.",
"*",
"self",
".",
"logp",
"except",
"ZeroProbability",
":",
"return",
"Inf"
] | The function that gets passed to the optimizers. | [
"The",
"function",
"that",
"gets",
"passed",
"to",
"the",
"optimizers",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/NormalApproximation.py#L387-L395 |
225,345 | pymc-devs/pymc | pymc/NormalApproximation.py | MAP.gradfunc | def gradfunc(self, p):
"""
The gradient-computing function that gets passed to the optimizers,
if needed.
"""
self._set_stochastics(p)
for i in xrange(self.len):
self.grad[i] = self.diff(i)
return -1 * self.grad | python | def gradfunc(self, p):
"""
The gradient-computing function that gets passed to the optimizers,
if needed.
"""
self._set_stochastics(p)
for i in xrange(self.len):
self.grad[i] = self.diff(i)
return -1 * self.grad | [
"def",
"gradfunc",
"(",
"self",
",",
"p",
")",
":",
"self",
".",
"_set_stochastics",
"(",
"p",
")",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"len",
")",
":",
"self",
".",
"grad",
"[",
"i",
"]",
"=",
"self",
".",
"diff",
"(",
"i",
")",
"r... | The gradient-computing function that gets passed to the optimizers,
if needed. | [
"The",
"gradient",
"-",
"computing",
"function",
"that",
"gets",
"passed",
"to",
"the",
"optimizers",
"if",
"needed",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/NormalApproximation.py#L397-L406 |
225,346 | pymc-devs/pymc | pymc/NormalApproximation.py | MAP.i_logp | def i_logp(self, index):
"""
Evaluates the log-probability of the Markov blanket of
a stochastic owning a particular index.
"""
all_relevant_stochastics = set()
p, i = self.stochastic_indices[index]
try:
return p.logp + logp_of_set(p.extended_children)
except ZeroProbability:
return -Inf | python | def i_logp(self, index):
"""
Evaluates the log-probability of the Markov blanket of
a stochastic owning a particular index.
"""
all_relevant_stochastics = set()
p, i = self.stochastic_indices[index]
try:
return p.logp + logp_of_set(p.extended_children)
except ZeroProbability:
return -Inf | [
"def",
"i_logp",
"(",
"self",
",",
"index",
")",
":",
"all_relevant_stochastics",
"=",
"set",
"(",
")",
"p",
",",
"i",
"=",
"self",
".",
"stochastic_indices",
"[",
"index",
"]",
"try",
":",
"return",
"p",
".",
"logp",
"+",
"logp_of_set",
"(",
"p",
".... | Evaluates the log-probability of the Markov blanket of
a stochastic owning a particular index. | [
"Evaluates",
"the",
"log",
"-",
"probability",
"of",
"the",
"Markov",
"blanket",
"of",
"a",
"stochastic",
"owning",
"a",
"particular",
"index",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/NormalApproximation.py#L430-L440 |
225,347 | pymc-devs/pymc | pymc/NormalApproximation.py | MAP.grad_and_hess | def grad_and_hess(self):
"""
Computes self's gradient and Hessian. Used if the
optimization method for a NormApprox doesn't
use gradients and hessians, for instance fmin.
"""
for i in xrange(self.len):
di = self.diff(i)
self.grad[i] = di
self.hess[i, i] = self.diff(i, 2)
if i < self.len - 1:
for j in xrange(i + 1, self.len):
dij = self.diff2(i, j)
self.hess[i, j] = dij
self.hess[j, i] = dij | python | def grad_and_hess(self):
"""
Computes self's gradient and Hessian. Used if the
optimization method for a NormApprox doesn't
use gradients and hessians, for instance fmin.
"""
for i in xrange(self.len):
di = self.diff(i)
self.grad[i] = di
self.hess[i, i] = self.diff(i, 2)
if i < self.len - 1:
for j in xrange(i + 1, self.len):
dij = self.diff2(i, j)
self.hess[i, j] = dij
self.hess[j, i] = dij | [
"def",
"grad_and_hess",
"(",
"self",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"len",
")",
":",
"di",
"=",
"self",
".",
"diff",
"(",
"i",
")",
"self",
".",
"grad",
"[",
"i",
"]",
"=",
"di",
"self",
".",
"hess",
"[",
"i",
",",
... | Computes self's gradient and Hessian. Used if the
optimization method for a NormApprox doesn't
use gradients and hessians, for instance fmin. | [
"Computes",
"self",
"s",
"gradient",
"and",
"Hessian",
".",
"Used",
"if",
"the",
"optimization",
"method",
"for",
"a",
"NormApprox",
"doesn",
"t",
"use",
"gradients",
"and",
"hessians",
"for",
"instance",
"fmin",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/NormalApproximation.py#L487-L505 |
225,348 | pymc-devs/pymc | pymc/NormalApproximation.py | MAP.hessfunc | def hessfunc(self, p):
"""
The Hessian function that will be passed to the optimizer,
if needed.
"""
self._set_stochastics(p)
for i in xrange(self.len):
di = self.diff(i)
self.hess[i, i] = self.diff(i, 2)
if i < self.len - 1:
for j in xrange(i + 1, self.len):
dij = self.diff2(i, j)
self.hess[i, j] = dij
self.hess[j, i] = dij
return -1. * self.hess | python | def hessfunc(self, p):
"""
The Hessian function that will be passed to the optimizer,
if needed.
"""
self._set_stochastics(p)
for i in xrange(self.len):
di = self.diff(i)
self.hess[i, i] = self.diff(i, 2)
if i < self.len - 1:
for j in xrange(i + 1, self.len):
dij = self.diff2(i, j)
self.hess[i, j] = dij
self.hess[j, i] = dij
return -1. * self.hess | [
"def",
"hessfunc",
"(",
"self",
",",
"p",
")",
":",
"self",
".",
"_set_stochastics",
"(",
"p",
")",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"len",
")",
":",
"di",
"=",
"self",
".",
"diff",
"(",
"i",
")",
"self",
".",
"hess",
"[",
"i",
"... | The Hessian function that will be passed to the optimizer,
if needed. | [
"The",
"Hessian",
"function",
"that",
"will",
"be",
"passed",
"to",
"the",
"optimizer",
"if",
"needed",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/NormalApproximation.py#L507-L526 |
225,349 | pymc-devs/pymc | pymc/threadpool.py | makeRequests | def makeRequests(callable_, args_list, callback=None,
exc_callback=_handle_thread_exception):
"""Create several work requests for same callable with different arguments.
Convenience function for creating several work requests for the same
callable where each invocation of the callable receives different values
for its arguments.
``args_list`` contains the parameters for each invocation of callable.
Each item in ``args_list`` should be either a 2-item tuple of the list of
positional arguments and a dictionary of keyword arguments or a single,
non-tuple argument.
See docstring for ``WorkRequest`` for info on ``callback`` and
``exc_callback``.
"""
requests = []
for item in args_list:
if isinstance(item, tuple):
requests.append(
WorkRequest(callable_, item[0], item[1], callback=callback,
exc_callback=exc_callback)
)
else:
requests.append(
WorkRequest(callable_, [item], None, callback=callback,
exc_callback=exc_callback)
)
return requests | python | def makeRequests(callable_, args_list, callback=None,
exc_callback=_handle_thread_exception):
"""Create several work requests for same callable with different arguments.
Convenience function for creating several work requests for the same
callable where each invocation of the callable receives different values
for its arguments.
``args_list`` contains the parameters for each invocation of callable.
Each item in ``args_list`` should be either a 2-item tuple of the list of
positional arguments and a dictionary of keyword arguments or a single,
non-tuple argument.
See docstring for ``WorkRequest`` for info on ``callback`` and
``exc_callback``.
"""
requests = []
for item in args_list:
if isinstance(item, tuple):
requests.append(
WorkRequest(callable_, item[0], item[1], callback=callback,
exc_callback=exc_callback)
)
else:
requests.append(
WorkRequest(callable_, [item], None, callback=callback,
exc_callback=exc_callback)
)
return requests | [
"def",
"makeRequests",
"(",
"callable_",
",",
"args_list",
",",
"callback",
"=",
"None",
",",
"exc_callback",
"=",
"_handle_thread_exception",
")",
":",
"requests",
"=",
"[",
"]",
"for",
"item",
"in",
"args_list",
":",
"if",
"isinstance",
"(",
"item",
",",
... | Create several work requests for same callable with different arguments.
Convenience function for creating several work requests for the same
callable where each invocation of the callable receives different values
for its arguments.
``args_list`` contains the parameters for each invocation of callable.
Each item in ``args_list`` should be either a 2-item tuple of the list of
positional arguments and a dictionary of keyword arguments or a single,
non-tuple argument.
See docstring for ``WorkRequest`` for info on ``callback`` and
``exc_callback``. | [
"Create",
"several",
"work",
"requests",
"for",
"same",
"callable",
"with",
"different",
"arguments",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/threadpool.py#L95-L124 |
225,350 | pymc-devs/pymc | pymc/threadpool.py | thread_partition_array | def thread_partition_array(x):
"Partition work arrays for multithreaded addition and multiplication"
n_threads = get_threadpool_size()
if len(x.shape) > 1:
maxind = x.shape[1]
else:
maxind = x.shape[0]
bounds = np.array(np.linspace(0, maxind, n_threads + 1), dtype='int')
cmin = bounds[:-1]
cmax = bounds[1:]
return cmin, cmax | python | def thread_partition_array(x):
"Partition work arrays for multithreaded addition and multiplication"
n_threads = get_threadpool_size()
if len(x.shape) > 1:
maxind = x.shape[1]
else:
maxind = x.shape[0]
bounds = np.array(np.linspace(0, maxind, n_threads + 1), dtype='int')
cmin = bounds[:-1]
cmax = bounds[1:]
return cmin, cmax | [
"def",
"thread_partition_array",
"(",
"x",
")",
":",
"n_threads",
"=",
"get_threadpool_size",
"(",
")",
"if",
"len",
"(",
"x",
".",
"shape",
")",
">",
"1",
":",
"maxind",
"=",
"x",
".",
"shape",
"[",
"1",
"]",
"else",
":",
"maxind",
"=",
"x",
".",
... | Partition work arrays for multithreaded addition and multiplication | [
"Partition",
"work",
"arrays",
"for",
"multithreaded",
"addition",
"and",
"multiplication"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/threadpool.py#L402-L412 |
225,351 | pymc-devs/pymc | pymc/threadpool.py | WorkerThread.run | def run(self):
"""Repeatedly process the job queue until told to exit."""
while True:
if self._dismissed.isSet():
# we are dismissed, break out of loop
break
# get next work request.
request = self._requests_queue.get()
# print 'Worker thread %s running request %s' %(self, request)
if self._dismissed.isSet():
# we are dismissed, put back request in queue and exit loop
self._requests_queue.put(request)
break
try:
result = request.callable(*request.args, **request.kwds)
if request.callback:
request.callback(request, result)
del result
self._requests_queue.task_done()
except:
request.exception = True
if request.exc_callback:
request.exc_callback(request)
self._requests_queue.task_done()
finally:
request.self_destruct() | python | def run(self):
"""Repeatedly process the job queue until told to exit."""
while True:
if self._dismissed.isSet():
# we are dismissed, break out of loop
break
# get next work request.
request = self._requests_queue.get()
# print 'Worker thread %s running request %s' %(self, request)
if self._dismissed.isSet():
# we are dismissed, put back request in queue and exit loop
self._requests_queue.put(request)
break
try:
result = request.callable(*request.args, **request.kwds)
if request.callback:
request.callback(request, result)
del result
self._requests_queue.task_done()
except:
request.exception = True
if request.exc_callback:
request.exc_callback(request)
self._requests_queue.task_done()
finally:
request.self_destruct() | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"self",
".",
"_dismissed",
".",
"isSet",
"(",
")",
":",
"# we are dismissed, break out of loop",
"break",
"# get next work request.",
"request",
"=",
"self",
".",
"_requests_queue",
".",
"get",
"... | Repeatedly process the job queue until told to exit. | [
"Repeatedly",
"process",
"the",
"job",
"queue",
"until",
"told",
"to",
"exit",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/threadpool.py#L152-L179 |
225,352 | pymc-devs/pymc | pymc/threadpool.py | ThreadPool.createWorkers | def createWorkers(self, num_workers):
"""Add num_workers worker threads to the pool.
``poll_timout`` sets the interval in seconds (int or float) for how
ofte threads should check whether they are dismissed, while waiting for
requests.
"""
for i in range(num_workers):
self.workers.append(WorkerThread(self._requests_queue)) | python | def createWorkers(self, num_workers):
"""Add num_workers worker threads to the pool.
``poll_timout`` sets the interval in seconds (int or float) for how
ofte threads should check whether they are dismissed, while waiting for
requests.
"""
for i in range(num_workers):
self.workers.append(WorkerThread(self._requests_queue)) | [
"def",
"createWorkers",
"(",
"self",
",",
"num_workers",
")",
":",
"for",
"i",
"in",
"range",
"(",
"num_workers",
")",
":",
"self",
".",
"workers",
".",
"append",
"(",
"WorkerThread",
"(",
"self",
".",
"_requests_queue",
")",
")"
] | Add num_workers worker threads to the pool.
``poll_timout`` sets the interval in seconds (int or float) for how
ofte threads should check whether they are dismissed, while waiting for
requests. | [
"Add",
"num_workers",
"worker",
"threads",
"to",
"the",
"pool",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/threadpool.py#L287-L296 |
225,353 | pymc-devs/pymc | pymc/threadpool.py | ThreadPool.dismissWorkers | def dismissWorkers(self, num_workers):
"""Tell num_workers worker threads to quit after their current task."""
for i in range(min(num_workers, len(self.workers))):
worker = self.workers.pop()
worker.dismiss() | python | def dismissWorkers(self, num_workers):
"""Tell num_workers worker threads to quit after their current task."""
for i in range(min(num_workers, len(self.workers))):
worker = self.workers.pop()
worker.dismiss() | [
"def",
"dismissWorkers",
"(",
"self",
",",
"num_workers",
")",
":",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"num_workers",
",",
"len",
"(",
"self",
".",
"workers",
")",
")",
")",
":",
"worker",
"=",
"self",
".",
"workers",
".",
"pop",
"(",
")",... | Tell num_workers worker threads to quit after their current task. | [
"Tell",
"num_workers",
"worker",
"threads",
"to",
"quit",
"after",
"their",
"current",
"task",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/threadpool.py#L298-L302 |
225,354 | pymc-devs/pymc | pymc/threadpool.py | ThreadPool.setNumWorkers | def setNumWorkers(self, num_workers):
"""Set number of worker threads to num_workers"""
cur_num = len(self.workers)
if cur_num > num_workers:
self.dismissWorkers(cur_num - num_workers)
else:
self.createWorkers(num_workers - cur_num) | python | def setNumWorkers(self, num_workers):
"""Set number of worker threads to num_workers"""
cur_num = len(self.workers)
if cur_num > num_workers:
self.dismissWorkers(cur_num - num_workers)
else:
self.createWorkers(num_workers - cur_num) | [
"def",
"setNumWorkers",
"(",
"self",
",",
"num_workers",
")",
":",
"cur_num",
"=",
"len",
"(",
"self",
".",
"workers",
")",
"if",
"cur_num",
">",
"num_workers",
":",
"self",
".",
"dismissWorkers",
"(",
"cur_num",
"-",
"num_workers",
")",
"else",
":",
"se... | Set number of worker threads to num_workers | [
"Set",
"number",
"of",
"worker",
"threads",
"to",
"num_workers"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/threadpool.py#L304-L310 |
225,355 | pymc-devs/pymc | pymc/threadpool.py | ThreadPool.putRequest | def putRequest(self, request, block=True, timeout=0):
"""Put work request into work queue and save its id for later."""
# don't reuse old work requests
# print '\tthread pool putting work request %s'%request
self._requests_queue.put(request, block, timeout)
self.workRequests[request.requestID] = request | python | def putRequest(self, request, block=True, timeout=0):
"""Put work request into work queue and save its id for later."""
# don't reuse old work requests
# print '\tthread pool putting work request %s'%request
self._requests_queue.put(request, block, timeout)
self.workRequests[request.requestID] = request | [
"def",
"putRequest",
"(",
"self",
",",
"request",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"0",
")",
":",
"# don't reuse old work requests",
"# print '\\tthread pool putting work request %s'%request",
"self",
".",
"_requests_queue",
".",
"put",
"(",
"request",
... | Put work request into work queue and save its id for later. | [
"Put",
"work",
"request",
"into",
"work",
"queue",
"and",
"save",
"its",
"id",
"for",
"later",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/threadpool.py#L312-L317 |
225,356 | pymc-devs/pymc | pymc/examples/zip.py | zip | def zip(value=data, mu=mu, psi=psi):
""" Zero-inflated Poisson likelihood """
# Initialize likeihood
like = 0.0
# Loop over data
for x in value:
if not x:
# Zero values
like += np.log((1. - psi) + psi * np.exp(-mu))
else:
# Non-zero values
like += np.log(psi) + poisson_like(x, mu)
return like | python | def zip(value=data, mu=mu, psi=psi):
""" Zero-inflated Poisson likelihood """
# Initialize likeihood
like = 0.0
# Loop over data
for x in value:
if not x:
# Zero values
like += np.log((1. - psi) + psi * np.exp(-mu))
else:
# Non-zero values
like += np.log(psi) + poisson_like(x, mu)
return like | [
"def",
"zip",
"(",
"value",
"=",
"data",
",",
"mu",
"=",
"mu",
",",
"psi",
"=",
"psi",
")",
":",
"# Initialize likeihood",
"like",
"=",
"0.0",
"# Loop over data",
"for",
"x",
"in",
"value",
":",
"if",
"not",
"x",
":",
"# Zero values",
"like",
"+=",
"... | Zero-inflated Poisson likelihood | [
"Zero",
"-",
"inflated",
"Poisson",
"likelihood"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/examples/zip.py#L26-L43 |
225,357 | pymc-devs/pymc | pymc/Matplot.py | plot | def plot(
data, name, format='png', suffix='', path='./', common_scale=True, datarange=(None, None), fontmap=None, verbose=1,
new=True, last=True, rows=1, num=1):
"""
Generates summary plots for nodes of a given PyMC object.
:Arguments:
data: PyMC object, trace or array
A trace from an MCMC sample or a PyMC object with one or more traces.
name: string
The name of the object.
format (optional): string
Graphic output format (defaults to png).
suffix (optional): string
Filename suffix.
path (optional): string
Specifies location for saving plots (defaults to local directory).
common_scale (optional): bool
Specifies whether plots of multivariate nodes should be on the same scale
(defaults to True).
datarange (optional): tuple or list
Range of data to plot (defaults to empirical range of data)
fontmap (optional): dict
Dictionary containing the font map for the labels of the graphic.
verbose (optional): int
Verbosity level for output (defaults to 1).
"""
if fontmap is None:
fontmap = {1: 10, 2: 8, 3: 6, 4: 5, 5: 4}
# If there is only one data array, go ahead and plot it ...
if ndim(data) == 1:
if verbose > 0:
print_('Plotting', name)
# If new plot, generate new frame
if new:
figure(figsize=(10, 6))
# Call trace
trace(data, name, datarange=datarange, rows=rows * 2, columns=2,
num=num + 3 * (num - 1), last=last, fontmap=fontmap)
# Call autocorrelation
autocorrelation(data, name, rows=rows * 2, columns=2,
num=num+3*(num-1)+2, last=last, fontmap=fontmap)
# Call histogram
histogram(data, name, datarange=datarange, rows=rows, columns=2,
num=num*2, last=last, fontmap=fontmap)
if last:
if not os.path.exists(path):
os.mkdir(path)
if not path.endswith('/'):
path += '/'
savefig("%s%s%s.%s" % (path, name, suffix, format))
else:
# ... otherwise plot recursively
tdata = swapaxes(data, 0, 1)
datarange = (None, None)
# Determine common range for plots
if common_scale:
datarange = (nmin(tdata), nmax(tdata))
# How many rows?
_rows = min(4, len(tdata))
for i in range(len(tdata)):
# New plot or adding to existing?
_new = not i % _rows
# Current subplot number
_num = i % _rows + 1
# Final subplot of current figure?
_last = (_num == _rows) or (i == len(tdata) - 1)
plot(tdata[i], name + '_' + str(i), format=format, path=path,
common_scale=common_scale, datarange=datarange,
suffix=suffix, new=_new, last=_last, rows=_rows,
num=_num, fontmap=fontmap, verbose=verbose) | python | def plot(
data, name, format='png', suffix='', path='./', common_scale=True, datarange=(None, None), fontmap=None, verbose=1,
new=True, last=True, rows=1, num=1):
"""
Generates summary plots for nodes of a given PyMC object.
:Arguments:
data: PyMC object, trace or array
A trace from an MCMC sample or a PyMC object with one or more traces.
name: string
The name of the object.
format (optional): string
Graphic output format (defaults to png).
suffix (optional): string
Filename suffix.
path (optional): string
Specifies location for saving plots (defaults to local directory).
common_scale (optional): bool
Specifies whether plots of multivariate nodes should be on the same scale
(defaults to True).
datarange (optional): tuple or list
Range of data to plot (defaults to empirical range of data)
fontmap (optional): dict
Dictionary containing the font map for the labels of the graphic.
verbose (optional): int
Verbosity level for output (defaults to 1).
"""
if fontmap is None:
fontmap = {1: 10, 2: 8, 3: 6, 4: 5, 5: 4}
# If there is only one data array, go ahead and plot it ...
if ndim(data) == 1:
if verbose > 0:
print_('Plotting', name)
# If new plot, generate new frame
if new:
figure(figsize=(10, 6))
# Call trace
trace(data, name, datarange=datarange, rows=rows * 2, columns=2,
num=num + 3 * (num - 1), last=last, fontmap=fontmap)
# Call autocorrelation
autocorrelation(data, name, rows=rows * 2, columns=2,
num=num+3*(num-1)+2, last=last, fontmap=fontmap)
# Call histogram
histogram(data, name, datarange=datarange, rows=rows, columns=2,
num=num*2, last=last, fontmap=fontmap)
if last:
if not os.path.exists(path):
os.mkdir(path)
if not path.endswith('/'):
path += '/'
savefig("%s%s%s.%s" % (path, name, suffix, format))
else:
# ... otherwise plot recursively
tdata = swapaxes(data, 0, 1)
datarange = (None, None)
# Determine common range for plots
if common_scale:
datarange = (nmin(tdata), nmax(tdata))
# How many rows?
_rows = min(4, len(tdata))
for i in range(len(tdata)):
# New plot or adding to existing?
_new = not i % _rows
# Current subplot number
_num = i % _rows + 1
# Final subplot of current figure?
_last = (_num == _rows) or (i == len(tdata) - 1)
plot(tdata[i], name + '_' + str(i), format=format, path=path,
common_scale=common_scale, datarange=datarange,
suffix=suffix, new=_new, last=_last, rows=_rows,
num=_num, fontmap=fontmap, verbose=verbose) | [
"def",
"plot",
"(",
"data",
",",
"name",
",",
"format",
"=",
"'png'",
",",
"suffix",
"=",
"''",
",",
"path",
"=",
"'./'",
",",
"common_scale",
"=",
"True",
",",
"datarange",
"=",
"(",
"None",
",",
"None",
")",
",",
"fontmap",
"=",
"None",
",",
"v... | Generates summary plots for nodes of a given PyMC object.
:Arguments:
data: PyMC object, trace or array
A trace from an MCMC sample or a PyMC object with one or more traces.
name: string
The name of the object.
format (optional): string
Graphic output format (defaults to png).
suffix (optional): string
Filename suffix.
path (optional): string
Specifies location for saving plots (defaults to local directory).
common_scale (optional): bool
Specifies whether plots of multivariate nodes should be on the same scale
(defaults to True).
datarange (optional): tuple or list
Range of data to plot (defaults to empirical range of data)
fontmap (optional): dict
Dictionary containing the font map for the labels of the graphic.
verbose (optional): int
Verbosity level for output (defaults to 1). | [
"Generates",
"summary",
"plots",
"for",
"nodes",
"of",
"a",
"given",
"PyMC",
"object",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Matplot.py#L385-L475 |
225,358 | pymc-devs/pymc | pymc/Matplot.py | histogram | def histogram(
data, name, bins='sturges', datarange=(None, None), format='png', suffix='', path='./', rows=1,
columns=1, num=1, last=True, fontmap = None, verbose=1):
"""
Generates histogram from an array of data.
:Arguments:
data: array or list
Usually a trace from an MCMC sample.
name: string
The name of the histogram.
bins: int or string
The number of bins, or a preferred binning method. Available methods include
'doanes', 'sturges' and 'sqrt' (defaults to 'doanes').
datarange: tuple or list
Preferred range of histogram (defaults to (None,None)).
format (optional): string
Graphic output format (defaults to png).
suffix (optional): string
Filename suffix.
path (optional): string
Specifies location for saving plots (defaults to local directory).
fontmap (optional): dict
Font map for plot.
"""
# Internal histogram specification for handling nested arrays
try:
if fontmap is None:
fontmap = {1: 10, 2: 8, 3: 6, 4: 5, 5: 4}
# Stand-alone plot or subplot?
standalone = rows == 1 and columns == 1 and num == 1
if standalone:
if verbose > 0:
print_('Generating histogram of', name)
figure()
subplot(rows, columns, num)
# Specify number of bins
uniquevals = len(unique(data))
if isinstance(bins, int):
pass
if bins == 'sturges':
bins = uniquevals * (uniquevals <= 25) or _sturges(len(data))
elif bins == 'doanes':
bins = uniquevals * (uniquevals <= 25) or _doanes(data, len(data))
elif bins == 'sqrt':
bins = uniquevals * (uniquevals <= 25) or _sqrt_choice(len(data))
elif isinstance(bins, int):
bins = bins
else:
raise ValueError('Invalid bins argument in histogram')
if isnan(bins):
bins = uniquevals * (uniquevals <= 25) or int(
4 + 1.5 * log(len(data)))
print_(
'Bins could not be calculated using selected method. Setting bins to %i.' %
bins)
# Generate histogram
hist(data.tolist(), bins, histtype='stepfilled')
xlim(datarange)
# Plot options
title('\n\n %s hist' % name, x=0., y=1., ha='left', va='top',
fontsize='medium')
ylabel("Frequency", fontsize='x-small')
# Plot vertical lines for median and 95% HPD interval
quant = calc_quantiles(data)
axvline(x=quant[50], linewidth=2, color='black')
for q in calc_hpd(data, 0.05):
axvline(x=q, linewidth=2, color='grey', linestyle='dotted')
# Smaller tick labels
tlabels = gca().get_xticklabels()
setp(tlabels, 'fontsize', fontmap[rows])
tlabels = gca().get_yticklabels()
setp(tlabels, 'fontsize', fontmap[rows])
if standalone:
if not os.path.exists(path):
os.mkdir(path)
if not path.endswith('/'):
path += '/'
# Save to file
savefig("%s%s%s.%s" % (path, name, suffix, format))
# close()
except OverflowError:
print_('... cannot generate histogram') | python | def histogram(
data, name, bins='sturges', datarange=(None, None), format='png', suffix='', path='./', rows=1,
columns=1, num=1, last=True, fontmap = None, verbose=1):
"""
Generates histogram from an array of data.
:Arguments:
data: array or list
Usually a trace from an MCMC sample.
name: string
The name of the histogram.
bins: int or string
The number of bins, or a preferred binning method. Available methods include
'doanes', 'sturges' and 'sqrt' (defaults to 'doanes').
datarange: tuple or list
Preferred range of histogram (defaults to (None,None)).
format (optional): string
Graphic output format (defaults to png).
suffix (optional): string
Filename suffix.
path (optional): string
Specifies location for saving plots (defaults to local directory).
fontmap (optional): dict
Font map for plot.
"""
# Internal histogram specification for handling nested arrays
try:
if fontmap is None:
fontmap = {1: 10, 2: 8, 3: 6, 4: 5, 5: 4}
# Stand-alone plot or subplot?
standalone = rows == 1 and columns == 1 and num == 1
if standalone:
if verbose > 0:
print_('Generating histogram of', name)
figure()
subplot(rows, columns, num)
# Specify number of bins
uniquevals = len(unique(data))
if isinstance(bins, int):
pass
if bins == 'sturges':
bins = uniquevals * (uniquevals <= 25) or _sturges(len(data))
elif bins == 'doanes':
bins = uniquevals * (uniquevals <= 25) or _doanes(data, len(data))
elif bins == 'sqrt':
bins = uniquevals * (uniquevals <= 25) or _sqrt_choice(len(data))
elif isinstance(bins, int):
bins = bins
else:
raise ValueError('Invalid bins argument in histogram')
if isnan(bins):
bins = uniquevals * (uniquevals <= 25) or int(
4 + 1.5 * log(len(data)))
print_(
'Bins could not be calculated using selected method. Setting bins to %i.' %
bins)
# Generate histogram
hist(data.tolist(), bins, histtype='stepfilled')
xlim(datarange)
# Plot options
title('\n\n %s hist' % name, x=0., y=1., ha='left', va='top',
fontsize='medium')
ylabel("Frequency", fontsize='x-small')
# Plot vertical lines for median and 95% HPD interval
quant = calc_quantiles(data)
axvline(x=quant[50], linewidth=2, color='black')
for q in calc_hpd(data, 0.05):
axvline(x=q, linewidth=2, color='grey', linestyle='dotted')
# Smaller tick labels
tlabels = gca().get_xticklabels()
setp(tlabels, 'fontsize', fontmap[rows])
tlabels = gca().get_yticklabels()
setp(tlabels, 'fontsize', fontmap[rows])
if standalone:
if not os.path.exists(path):
os.mkdir(path)
if not path.endswith('/'):
path += '/'
# Save to file
savefig("%s%s%s.%s" % (path, name, suffix, format))
# close()
except OverflowError:
print_('... cannot generate histogram') | [
"def",
"histogram",
"(",
"data",
",",
"name",
",",
"bins",
"=",
"'sturges'",
",",
"datarange",
"=",
"(",
"None",
",",
"None",
")",
",",
"format",
"=",
"'png'",
",",
"suffix",
"=",
"''",
",",
"path",
"=",
"'./'",
",",
"rows",
"=",
"1",
",",
"colum... | Generates histogram from an array of data.
:Arguments:
data: array or list
Usually a trace from an MCMC sample.
name: string
The name of the histogram.
bins: int or string
The number of bins, or a preferred binning method. Available methods include
'doanes', 'sturges' and 'sqrt' (defaults to 'doanes').
datarange: tuple or list
Preferred range of histogram (defaults to (None,None)).
format (optional): string
Graphic output format (defaults to png).
suffix (optional): string
Filename suffix.
path (optional): string
Specifies location for saving plots (defaults to local directory).
fontmap (optional): dict
Font map for plot. | [
"Generates",
"histogram",
"from",
"an",
"array",
"of",
"data",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Matplot.py#L486-L589 |
225,359 | pymc-devs/pymc | pymc/Matplot.py | trace | def trace(
data, name, format='png', datarange=(None, None), suffix='', path='./', rows=1, columns=1,
num=1, last=True, fontmap = None, verbose=1):
"""
Generates trace plot from an array of data.
:Arguments:
data: array or list
Usually a trace from an MCMC sample.
name: string
The name of the trace.
datarange: tuple or list
Preferred y-range of trace (defaults to (None,None)).
format (optional): string
Graphic output format (defaults to png).
suffix (optional): string
Filename suffix.
path (optional): string
Specifies location for saving plots (defaults to local directory).
fontmap (optional): dict
Font map for plot.
"""
if fontmap is None:
fontmap = {1: 10, 2: 8, 3: 6, 4: 5, 5: 4}
# Stand-alone plot or subplot?
standalone = rows == 1 and columns == 1 and num == 1
if standalone:
if verbose > 0:
print_('Plotting', name)
figure()
subplot(rows, columns, num)
pyplot(data.tolist())
ylim(datarange)
# Plot options
title('\n\n %s trace' % name, x=0., y=1., ha='left', va='top',
fontsize='small')
# Smaller tick labels
tlabels = gca().get_xticklabels()
setp(tlabels, 'fontsize', fontmap[max(rows / 2, 1)])
tlabels = gca().get_yticklabels()
setp(tlabels, 'fontsize', fontmap[max(rows / 2, 1)])
if standalone:
if not os.path.exists(path):
os.mkdir(path)
if not path.endswith('/'):
path += '/'
# Save to file
savefig("%s%s%s.%s" % (path, name, suffix, format)) | python | def trace(
data, name, format='png', datarange=(None, None), suffix='', path='./', rows=1, columns=1,
num=1, last=True, fontmap = None, verbose=1):
"""
Generates trace plot from an array of data.
:Arguments:
data: array or list
Usually a trace from an MCMC sample.
name: string
The name of the trace.
datarange: tuple or list
Preferred y-range of trace (defaults to (None,None)).
format (optional): string
Graphic output format (defaults to png).
suffix (optional): string
Filename suffix.
path (optional): string
Specifies location for saving plots (defaults to local directory).
fontmap (optional): dict
Font map for plot.
"""
if fontmap is None:
fontmap = {1: 10, 2: 8, 3: 6, 4: 5, 5: 4}
# Stand-alone plot or subplot?
standalone = rows == 1 and columns == 1 and num == 1
if standalone:
if verbose > 0:
print_('Plotting', name)
figure()
subplot(rows, columns, num)
pyplot(data.tolist())
ylim(datarange)
# Plot options
title('\n\n %s trace' % name, x=0., y=1., ha='left', va='top',
fontsize='small')
# Smaller tick labels
tlabels = gca().get_xticklabels()
setp(tlabels, 'fontsize', fontmap[max(rows / 2, 1)])
tlabels = gca().get_yticklabels()
setp(tlabels, 'fontsize', fontmap[max(rows / 2, 1)])
if standalone:
if not os.path.exists(path):
os.mkdir(path)
if not path.endswith('/'):
path += '/'
# Save to file
savefig("%s%s%s.%s" % (path, name, suffix, format)) | [
"def",
"trace",
"(",
"data",
",",
"name",
",",
"format",
"=",
"'png'",
",",
"datarange",
"=",
"(",
"None",
",",
"None",
")",
",",
"suffix",
"=",
"''",
",",
"path",
"=",
"'./'",
",",
"rows",
"=",
"1",
",",
"columns",
"=",
"1",
",",
"num",
"=",
... | Generates trace plot from an array of data.
:Arguments:
data: array or list
Usually a trace from an MCMC sample.
name: string
The name of the trace.
datarange: tuple or list
Preferred y-range of trace (defaults to (None,None)).
format (optional): string
Graphic output format (defaults to png).
suffix (optional): string
Filename suffix.
path (optional): string
Specifies location for saving plots (defaults to local directory).
fontmap (optional): dict
Font map for plot. | [
"Generates",
"trace",
"plot",
"from",
"an",
"array",
"of",
"data",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Matplot.py#L593-L655 |
225,360 | pymc-devs/pymc | pymc/Matplot.py | gof_plot | def gof_plot(
simdata, trueval, name=None, bins=None, format='png', suffix='-gof', path='./',
fontmap=None, verbose=0):
"""
Plots histogram of replicated data, indicating the location of the observed data
:Arguments:
simdata: array or PyMC object
Trace of simulated data or the PyMC stochastic object containing trace.
trueval: numeric
True (observed) value of the data
bins: int or string
The number of bins, or a preferred binning method. Available methods include
'doanes', 'sturges' and 'sqrt' (defaults to 'doanes').
format (optional): string
Graphic output format (defaults to png).
suffix (optional): string
Filename suffix.
path (optional): string
Specifies location for saving plots (defaults to local directory).
fontmap (optional): dict
Font map for plot.
"""
if fontmap is None:
fontmap = {1: 10, 2: 8, 3: 6, 4: 5, 5: 4}
if not isinstance(simdata, ndarray):
## Can't just try and catch because ndarray objects also have
## `trace` method.
simdata = simdata.trace()
if ndim(trueval) == 1 and ndim(simdata == 2):
# Iterate over more than one set of data
for i in range(len(trueval)):
n = name or 'MCMC'
gof_plot(
simdata[
:,
i],
trueval[
i],
'%s[%i]' % (
n,
i),
bins=bins,
format=format,
suffix=suffix,
path=path,
fontmap=fontmap,
verbose=verbose)
return
if verbose > 0:
print_('Plotting', (name or 'MCMC') + suffix)
figure()
# Specify number of bins
if bins is None:
bins = 'sqrt'
uniquevals = len(unique(simdata))
if bins == 'sturges':
bins = uniquevals * (uniquevals <= 25) or _sturges(len(simdata))
elif bins == 'doanes':
bins = uniquevals * (
uniquevals <= 25) or _doanes(simdata,
len(simdata))
elif bins == 'sqrt':
bins = uniquevals * (uniquevals <= 25) or _sqrt_choice(len(simdata))
elif isinstance(bins, int):
bins = bins
else:
raise ValueError('Invalid bins argument in gof_plot')
# Generate histogram
hist(simdata, bins)
# Plot options
xlabel(name or 'Value', fontsize='x-small')
ylabel("Frequency", fontsize='x-small')
# Smaller tick labels
tlabels = gca().get_xticklabels()
setp(tlabels, 'fontsize', fontmap[1])
tlabels = gca().get_yticklabels()
setp(tlabels, 'fontsize', fontmap[1])
# Plot vertical line at location of true data value
axvline(x=trueval, linewidth=2, color='r', linestyle='dotted')
if not os.path.exists(path):
os.mkdir(path)
if not path.endswith('/'):
path += '/'
# Save to file
savefig("%s%s%s.%s" % (path, name or 'MCMC', suffix, format)) | python | def gof_plot(
simdata, trueval, name=None, bins=None, format='png', suffix='-gof', path='./',
fontmap=None, verbose=0):
"""
Plots histogram of replicated data, indicating the location of the observed data
:Arguments:
simdata: array or PyMC object
Trace of simulated data or the PyMC stochastic object containing trace.
trueval: numeric
True (observed) value of the data
bins: int or string
The number of bins, or a preferred binning method. Available methods include
'doanes', 'sturges' and 'sqrt' (defaults to 'doanes').
format (optional): string
Graphic output format (defaults to png).
suffix (optional): string
Filename suffix.
path (optional): string
Specifies location for saving plots (defaults to local directory).
fontmap (optional): dict
Font map for plot.
"""
if fontmap is None:
fontmap = {1: 10, 2: 8, 3: 6, 4: 5, 5: 4}
if not isinstance(simdata, ndarray):
## Can't just try and catch because ndarray objects also have
## `trace` method.
simdata = simdata.trace()
if ndim(trueval) == 1 and ndim(simdata == 2):
# Iterate over more than one set of data
for i in range(len(trueval)):
n = name or 'MCMC'
gof_plot(
simdata[
:,
i],
trueval[
i],
'%s[%i]' % (
n,
i),
bins=bins,
format=format,
suffix=suffix,
path=path,
fontmap=fontmap,
verbose=verbose)
return
if verbose > 0:
print_('Plotting', (name or 'MCMC') + suffix)
figure()
# Specify number of bins
if bins is None:
bins = 'sqrt'
uniquevals = len(unique(simdata))
if bins == 'sturges':
bins = uniquevals * (uniquevals <= 25) or _sturges(len(simdata))
elif bins == 'doanes':
bins = uniquevals * (
uniquevals <= 25) or _doanes(simdata,
len(simdata))
elif bins == 'sqrt':
bins = uniquevals * (uniquevals <= 25) or _sqrt_choice(len(simdata))
elif isinstance(bins, int):
bins = bins
else:
raise ValueError('Invalid bins argument in gof_plot')
# Generate histogram
hist(simdata, bins)
# Plot options
xlabel(name or 'Value', fontsize='x-small')
ylabel("Frequency", fontsize='x-small')
# Smaller tick labels
tlabels = gca().get_xticklabels()
setp(tlabels, 'fontsize', fontmap[1])
tlabels = gca().get_yticklabels()
setp(tlabels, 'fontsize', fontmap[1])
# Plot vertical line at location of true data value
axvline(x=trueval, linewidth=2, color='r', linestyle='dotted')
if not os.path.exists(path):
os.mkdir(path)
if not path.endswith('/'):
path += '/'
# Save to file
savefig("%s%s%s.%s" % (path, name or 'MCMC', suffix, format)) | [
"def",
"gof_plot",
"(",
"simdata",
",",
"trueval",
",",
"name",
"=",
"None",
",",
"bins",
"=",
"None",
",",
"format",
"=",
"'png'",
",",
"suffix",
"=",
"'-gof'",
",",
"path",
"=",
"'./'",
",",
"fontmap",
"=",
"None",
",",
"verbose",
"=",
"0",
")",
... | Plots histogram of replicated data, indicating the location of the observed data
:Arguments:
simdata: array or PyMC object
Trace of simulated data or the PyMC stochastic object containing trace.
trueval: numeric
True (observed) value of the data
bins: int or string
The number of bins, or a preferred binning method. Available methods include
'doanes', 'sturges' and 'sqrt' (defaults to 'doanes').
format (optional): string
Graphic output format (defaults to png).
suffix (optional): string
Filename suffix.
path (optional): string
Specifies location for saving plots (defaults to local directory).
fontmap (optional): dict
Font map for plot. | [
"Plots",
"histogram",
"of",
"replicated",
"data",
"indicating",
"the",
"location",
"of",
"the",
"observed",
"data"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Matplot.py#L790-L894 |
225,361 | pymc-devs/pymc | pymc/database/sqlite.py | load | def load(dbname):
"""Load an existing SQLite database.
Return a Database instance.
"""
db = Database(dbname)
# Get the name of the objects
tables = get_table_list(db.cur)
# Create a Trace instance for each object
chains = 0
for name in tables:
db._traces[name] = Trace(name=name, db=db)
db._traces[name]._shape = get_shape(db.cur, name)
setattr(db, name, db._traces[name])
db.cur.execute('SELECT MAX(trace) FROM [%s]' % name)
chains = max(chains, db.cur.fetchall()[0][0] + 1)
db.chains = chains
db.trace_names = chains * [tables, ]
db._state_ = {}
return db | python | def load(dbname):
"""Load an existing SQLite database.
Return a Database instance.
"""
db = Database(dbname)
# Get the name of the objects
tables = get_table_list(db.cur)
# Create a Trace instance for each object
chains = 0
for name in tables:
db._traces[name] = Trace(name=name, db=db)
db._traces[name]._shape = get_shape(db.cur, name)
setattr(db, name, db._traces[name])
db.cur.execute('SELECT MAX(trace) FROM [%s]' % name)
chains = max(chains, db.cur.fetchall()[0][0] + 1)
db.chains = chains
db.trace_names = chains * [tables, ]
db._state_ = {}
return db | [
"def",
"load",
"(",
"dbname",
")",
":",
"db",
"=",
"Database",
"(",
"dbname",
")",
"# Get the name of the objects",
"tables",
"=",
"get_table_list",
"(",
"db",
".",
"cur",
")",
"# Create a Trace instance for each object",
"chains",
"=",
"0",
"for",
"name",
"in",... | Load an existing SQLite database.
Return a Database instance. | [
"Load",
"an",
"existing",
"SQLite",
"database",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/sqlite.py#L233-L255 |
225,362 | pymc-devs/pymc | pymc/database/sqlite.py | get_shape | def get_shape(cursor, name):
"""Return the shape of the table ``name``."""
cursor.execute('select * from [%s]' % name)
inds = cursor.description[-1][0][1:].split('_')
return tuple([int(i) for i in inds]) | python | def get_shape(cursor, name):
"""Return the shape of the table ``name``."""
cursor.execute('select * from [%s]' % name)
inds = cursor.description[-1][0][1:].split('_')
return tuple([int(i) for i in inds]) | [
"def",
"get_shape",
"(",
"cursor",
",",
"name",
")",
":",
"cursor",
".",
"execute",
"(",
"'select * from [%s]'",
"%",
"name",
")",
"inds",
"=",
"cursor",
".",
"description",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"[",
"1",
":",
"]",
".",
"split",
"(",
... | Return the shape of the table ``name``. | [
"Return",
"the",
"shape",
"of",
"the",
"table",
"name",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/sqlite.py#L270-L274 |
225,363 | pymc-devs/pymc | pymc/database/sqlite.py | Database.close | def close(self, *args, **kwds):
"""Close database."""
self.cur.close()
self.commit()
self.DB.close() | python | def close(self, *args, **kwds):
"""Close database."""
self.cur.close()
self.commit()
self.DB.close() | [
"def",
"close",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"self",
".",
"cur",
".",
"close",
"(",
")",
"self",
".",
"commit",
"(",
")",
"self",
".",
"DB",
".",
"close",
"(",
")"
] | Close database. | [
"Close",
"database",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/sqlite.py#L204-L208 |
225,364 | pymc-devs/pymc | pymc/CommonDeterministics.py | create_nonimplemented_method | def create_nonimplemented_method(op_name, klass):
"""
Creates a new method that raises NotImplementedError.
"""
def new_method(self, *args):
raise NotImplementedError(
'Special method %s has not been implemented for PyMC variables.' %
op_name)
new_method.__name__ = '__' + op_name + '__'
setattr(
klass,
new_method.__name__,
UnboundMethodType(
new_method,
None,
klass)) | python | def create_nonimplemented_method(op_name, klass):
"""
Creates a new method that raises NotImplementedError.
"""
def new_method(self, *args):
raise NotImplementedError(
'Special method %s has not been implemented for PyMC variables.' %
op_name)
new_method.__name__ = '__' + op_name + '__'
setattr(
klass,
new_method.__name__,
UnboundMethodType(
new_method,
None,
klass)) | [
"def",
"create_nonimplemented_method",
"(",
"op_name",
",",
"klass",
")",
":",
"def",
"new_method",
"(",
"self",
",",
"*",
"args",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Special method %s has not been implemented for PyMC variables.'",
"%",
"op_name",
")",
"... | Creates a new method that raises NotImplementedError. | [
"Creates",
"a",
"new",
"method",
"that",
"raises",
"NotImplementedError",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/CommonDeterministics.py#L802-L818 |
225,365 | pymc-devs/pymc | pymc/MCMC.py | MCMC.remove_step_method | def remove_step_method(self, step_method):
"""
Removes a step method.
"""
try:
for s in step_method.stochastics:
self.step_method_dict[s].remove(step_method)
if hasattr(self, "step_methods"):
self.step_methods.discard(step_method)
self._sm_assigned = False
except AttributeError:
for sm in step_method:
self.remove_step_method(sm) | python | def remove_step_method(self, step_method):
"""
Removes a step method.
"""
try:
for s in step_method.stochastics:
self.step_method_dict[s].remove(step_method)
if hasattr(self, "step_methods"):
self.step_methods.discard(step_method)
self._sm_assigned = False
except AttributeError:
for sm in step_method:
self.remove_step_method(sm) | [
"def",
"remove_step_method",
"(",
"self",
",",
"step_method",
")",
":",
"try",
":",
"for",
"s",
"in",
"step_method",
".",
"stochastics",
":",
"self",
".",
"step_method_dict",
"[",
"s",
"]",
".",
"remove",
"(",
"step_method",
")",
"if",
"hasattr",
"(",
"s... | Removes a step method. | [
"Removes",
"a",
"step",
"method",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/MCMC.py#L129-L141 |
225,366 | pymc-devs/pymc | pymc/MCMC.py | MCMC.assign_step_methods | def assign_step_methods(self, verbose=-1, draw_from_prior_when_possible=True):
"""
Make sure every stochastic variable has a step method. If not,
assign a step method from the registry.
"""
if not self._sm_assigned:
if draw_from_prior_when_possible:
# Assign dataless stepper first
last_gen = set([])
for s in self.stochastics - self.observed_stochastics:
if s._random is not None:
if len(s.extended_children) == 0:
last_gen.add(s)
dataless, dataless_gens = crawl_dataless(
set(last_gen), [last_gen])
if len(dataless):
new_method = DrawFromPrior(
dataless,
dataless_gens[::-1],
verbose=verbose)
setattr(new_method, '_model', self)
for d in dataless:
if not d.observed:
self.step_method_dict[d].append(new_method)
if self.verbose > 1:
print_(
'Assigning step method %s to stochastic %s' %
(new_method.__class__.__name__, d.__name__))
for s in self.stochastics:
# If not handled by any step method, make it a new step method
# using the registry
if len(self.step_method_dict[s]) == 0:
new_method = assign_method(s, verbose=verbose)
setattr(new_method, '_model', self)
self.step_method_dict[s].append(new_method)
if self.verbose > 1:
print_(
'Assigning step method %s to stochastic %s' %
(new_method.__class__.__name__, s.__name__))
self.step_methods = set()
for s in self.stochastics:
self.step_methods |= set(self.step_method_dict[s])
for sm in self.step_methods:
if sm.tally:
for name in sm._tuning_info:
self._funs_to_tally[
sm._id + '_' + name] = lambda name=name, sm=sm: getattr(sm, name)
else:
# Change verbosity for step methods
for sm_key in self.step_method_dict:
for sm in self.step_method_dict[sm_key]:
sm.verbose = verbose
self.restore_sm_state()
self._sm_assigned = True | python | def assign_step_methods(self, verbose=-1, draw_from_prior_when_possible=True):
"""
Make sure every stochastic variable has a step method. If not,
assign a step method from the registry.
"""
if not self._sm_assigned:
if draw_from_prior_when_possible:
# Assign dataless stepper first
last_gen = set([])
for s in self.stochastics - self.observed_stochastics:
if s._random is not None:
if len(s.extended_children) == 0:
last_gen.add(s)
dataless, dataless_gens = crawl_dataless(
set(last_gen), [last_gen])
if len(dataless):
new_method = DrawFromPrior(
dataless,
dataless_gens[::-1],
verbose=verbose)
setattr(new_method, '_model', self)
for d in dataless:
if not d.observed:
self.step_method_dict[d].append(new_method)
if self.verbose > 1:
print_(
'Assigning step method %s to stochastic %s' %
(new_method.__class__.__name__, d.__name__))
for s in self.stochastics:
# If not handled by any step method, make it a new step method
# using the registry
if len(self.step_method_dict[s]) == 0:
new_method = assign_method(s, verbose=verbose)
setattr(new_method, '_model', self)
self.step_method_dict[s].append(new_method)
if self.verbose > 1:
print_(
'Assigning step method %s to stochastic %s' %
(new_method.__class__.__name__, s.__name__))
self.step_methods = set()
for s in self.stochastics:
self.step_methods |= set(self.step_method_dict[s])
for sm in self.step_methods:
if sm.tally:
for name in sm._tuning_info:
self._funs_to_tally[
sm._id + '_' + name] = lambda name=name, sm=sm: getattr(sm, name)
else:
# Change verbosity for step methods
for sm_key in self.step_method_dict:
for sm in self.step_method_dict[sm_key]:
sm.verbose = verbose
self.restore_sm_state()
self._sm_assigned = True | [
"def",
"assign_step_methods",
"(",
"self",
",",
"verbose",
"=",
"-",
"1",
",",
"draw_from_prior_when_possible",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"_sm_assigned",
":",
"if",
"draw_from_prior_when_possible",
":",
"# Assign dataless stepper first",
"last... | Make sure every stochastic variable has a step method. If not,
assign a step method from the registry. | [
"Make",
"sure",
"every",
"stochastic",
"variable",
"has",
"a",
"step",
"method",
".",
"If",
"not",
"assign",
"a",
"step",
"method",
"from",
"the",
"registry",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/MCMC.py#L143-L204 |
225,367 | pymc-devs/pymc | pymc/MCMC.py | MCMC.tune | def tune(self):
"""
Tell all step methods to tune themselves.
"""
if self.verbose > 0:
print_('\tTuning at iteration', self._current_iter)
# Initialize counter for number of tuning stochastics
tuning_count = 0
for step_method in self.step_methods:
verbose = self.verbose
if step_method.verbose > -1:
verbose = step_method.verbose
# Tune step methods
tuning_count += step_method.tune(verbose=self.verbose)
if verbose > 1:
print_(
'\t\tTuning step method %s, returned %i\n' % (
step_method._id, tuning_count
)
)
sys.stdout.flush()
if self._burn_till_tuned:
if not tuning_count:
# If no step methods needed tuning, increment count
self._tuned_count += 1
else:
# Otherwise re-initialize count
self._tuned_count = 0
# n consecutive clean intervals removed tuning
# n is equal to self._stop_tuning_after
if self._tuned_count == self._stop_tuning_after:
if self.verbose > 0:
print_('\nFinished tuning')
self._tuning = False | python | def tune(self):
"""
Tell all step methods to tune themselves.
"""
if self.verbose > 0:
print_('\tTuning at iteration', self._current_iter)
# Initialize counter for number of tuning stochastics
tuning_count = 0
for step_method in self.step_methods:
verbose = self.verbose
if step_method.verbose > -1:
verbose = step_method.verbose
# Tune step methods
tuning_count += step_method.tune(verbose=self.verbose)
if verbose > 1:
print_(
'\t\tTuning step method %s, returned %i\n' % (
step_method._id, tuning_count
)
)
sys.stdout.flush()
if self._burn_till_tuned:
if not tuning_count:
# If no step methods needed tuning, increment count
self._tuned_count += 1
else:
# Otherwise re-initialize count
self._tuned_count = 0
# n consecutive clean intervals removed tuning
# n is equal to self._stop_tuning_after
if self._tuned_count == self._stop_tuning_after:
if self.verbose > 0:
print_('\nFinished tuning')
self._tuning = False | [
"def",
"tune",
"(",
"self",
")",
":",
"if",
"self",
".",
"verbose",
">",
"0",
":",
"print_",
"(",
"'\\tTuning at iteration'",
",",
"self",
".",
"_current_iter",
")",
"# Initialize counter for number of tuning stochastics",
"tuning_count",
"=",
"0",
"for",
"step_me... | Tell all step methods to tune themselves. | [
"Tell",
"all",
"step",
"methods",
"to",
"tune",
"themselves",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/MCMC.py#L349-L387 |
225,368 | pymc-devs/pymc | pymc/MCMC.py | MCMC.get_state | def get_state(self):
"""
Return the sampler and step methods current state in order to
restart sampling at a later time.
"""
self.step_methods = set()
for s in self.stochastics:
self.step_methods |= set(self.step_method_dict[s])
state = Sampler.get_state(self)
state['step_methods'] = {}
# The state of each StepMethod.
for sm in self.step_methods:
state['step_methods'][sm._id] = sm.current_state().copy()
return state | python | def get_state(self):
"""
Return the sampler and step methods current state in order to
restart sampling at a later time.
"""
self.step_methods = set()
for s in self.stochastics:
self.step_methods |= set(self.step_method_dict[s])
state = Sampler.get_state(self)
state['step_methods'] = {}
# The state of each StepMethod.
for sm in self.step_methods:
state['step_methods'][sm._id] = sm.current_state().copy()
return state | [
"def",
"get_state",
"(",
"self",
")",
":",
"self",
".",
"step_methods",
"=",
"set",
"(",
")",
"for",
"s",
"in",
"self",
".",
"stochastics",
":",
"self",
".",
"step_methods",
"|=",
"set",
"(",
"self",
".",
"step_method_dict",
"[",
"s",
"]",
")",
"stat... | Return the sampler and step methods current state in order to
restart sampling at a later time. | [
"Return",
"the",
"sampler",
"and",
"step",
"methods",
"current",
"state",
"in",
"order",
"to",
"restart",
"sampling",
"at",
"a",
"later",
"time",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/MCMC.py#L389-L406 |
225,369 | pymc-devs/pymc | pymc/MCMC.py | MCMC._calc_dic | def _calc_dic(self):
"""Calculates deviance information Criterion"""
# Find mean deviance
mean_deviance = np.mean(self.db.trace('deviance')(), axis=0)
# Set values of all parameters to their mean
for stochastic in self.stochastics:
# Calculate mean of paramter
try:
mean_value = np.mean(
self.db.trace(
stochastic.__name__)(
),
axis=0)
# Set current value to mean
stochastic.value = mean_value
except KeyError:
print_(
"No trace available for %s. DIC value may not be valid." %
stochastic.__name__)
except TypeError:
print_(
"Not able to calculate DIC: invalid stochastic %s" %
stochastic.__name__)
return None
# Return twice deviance minus deviance at means
return 2 * mean_deviance - self.deviance | python | def _calc_dic(self):
"""Calculates deviance information Criterion"""
# Find mean deviance
mean_deviance = np.mean(self.db.trace('deviance')(), axis=0)
# Set values of all parameters to their mean
for stochastic in self.stochastics:
# Calculate mean of paramter
try:
mean_value = np.mean(
self.db.trace(
stochastic.__name__)(
),
axis=0)
# Set current value to mean
stochastic.value = mean_value
except KeyError:
print_(
"No trace available for %s. DIC value may not be valid." %
stochastic.__name__)
except TypeError:
print_(
"Not able to calculate DIC: invalid stochastic %s" %
stochastic.__name__)
return None
# Return twice deviance minus deviance at means
return 2 * mean_deviance - self.deviance | [
"def",
"_calc_dic",
"(",
"self",
")",
":",
"# Find mean deviance",
"mean_deviance",
"=",
"np",
".",
"mean",
"(",
"self",
".",
"db",
".",
"trace",
"(",
"'deviance'",
")",
"(",
")",
",",
"axis",
"=",
"0",
")",
"# Set values of all parameters to their mean",
"f... | Calculates deviance information Criterion | [
"Calculates",
"deviance",
"information",
"Criterion"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/MCMC.py#L419-L450 |
225,370 | pymc-devs/pymc | pymc/distributions.py | stochastic_from_data | def stochastic_from_data(name, data, lower=-np.inf, upper=np.inf,
value=None, observed=False, trace=True, verbose=-1, debug=False):
"""
Return a Stochastic subclass made from arbitrary data.
The histogram for the data is fitted with Kernel Density Estimation.
:Parameters:
- `data` : An array with samples (e.g. trace[:])
- `lower` : Lower bound on possible outcomes
- `upper` : Upper bound on possible outcomes
:Example:
>>> from pymc import stochastic_from_data
>>> pos = stochastic_from_data('posterior', posterior_samples)
>>> prior = pos # update the prior with arbitrary distributions
:Alias:
Histogram
"""
pdf = gaussian_kde(data) # automatic bandwidth selection
# account for tail contribution
lower_tail = upper_tail = 0.
if lower > -np.inf:
lower_tail = pdf.integrate_box(-np.inf, lower)
if upper < np.inf:
upper_tail = pdf.integrate_box(upper, np.inf)
factor = 1. / (1. - (lower_tail + upper_tail))
def logp(value):
prob = factor * pdf(value)
if value < lower or value > upper:
return -np.inf
elif prob <= 0.:
return -np.inf
else:
return np.log(prob)
def random():
res = pdf.resample(1)[0][0]
while res < lower or res > upper:
res = pdf.resample(1)[0][0]
return res
if value is None:
value = random()
return Stochastic(logp=logp,
doc='Non-parametric density with Gaussian Kernels.',
name=name,
parents={},
random=random,
trace=trace,
value=value,
dtype=float,
observed=observed,
verbose=verbose) | python | def stochastic_from_data(name, data, lower=-np.inf, upper=np.inf,
value=None, observed=False, trace=True, verbose=-1, debug=False):
"""
Return a Stochastic subclass made from arbitrary data.
The histogram for the data is fitted with Kernel Density Estimation.
:Parameters:
- `data` : An array with samples (e.g. trace[:])
- `lower` : Lower bound on possible outcomes
- `upper` : Upper bound on possible outcomes
:Example:
>>> from pymc import stochastic_from_data
>>> pos = stochastic_from_data('posterior', posterior_samples)
>>> prior = pos # update the prior with arbitrary distributions
:Alias:
Histogram
"""
pdf = gaussian_kde(data) # automatic bandwidth selection
# account for tail contribution
lower_tail = upper_tail = 0.
if lower > -np.inf:
lower_tail = pdf.integrate_box(-np.inf, lower)
if upper < np.inf:
upper_tail = pdf.integrate_box(upper, np.inf)
factor = 1. / (1. - (lower_tail + upper_tail))
def logp(value):
prob = factor * pdf(value)
if value < lower or value > upper:
return -np.inf
elif prob <= 0.:
return -np.inf
else:
return np.log(prob)
def random():
res = pdf.resample(1)[0][0]
while res < lower or res > upper:
res = pdf.resample(1)[0][0]
return res
if value is None:
value = random()
return Stochastic(logp=logp,
doc='Non-parametric density with Gaussian Kernels.',
name=name,
parents={},
random=random,
trace=trace,
value=value,
dtype=float,
observed=observed,
verbose=verbose) | [
"def",
"stochastic_from_data",
"(",
"name",
",",
"data",
",",
"lower",
"=",
"-",
"np",
".",
"inf",
",",
"upper",
"=",
"np",
".",
"inf",
",",
"value",
"=",
"None",
",",
"observed",
"=",
"False",
",",
"trace",
"=",
"True",
",",
"verbose",
"=",
"-",
... | Return a Stochastic subclass made from arbitrary data.
The histogram for the data is fitted with Kernel Density Estimation.
:Parameters:
- `data` : An array with samples (e.g. trace[:])
- `lower` : Lower bound on possible outcomes
- `upper` : Upper bound on possible outcomes
:Example:
>>> from pymc import stochastic_from_data
>>> pos = stochastic_from_data('posterior', posterior_samples)
>>> prior = pos # update the prior with arbitrary distributions
:Alias:
Histogram | [
"Return",
"a",
"Stochastic",
"subclass",
"made",
"from",
"arbitrary",
"data",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L401-L458 |
225,371 | pymc-devs/pymc | pymc/distributions.py | randomwrap | def randomwrap(func):
"""
Decorator for random value generators
Allows passing of sequence of parameters, as well as a size argument.
Convention:
- If size=1 and the parameters are all scalars, return a scalar.
- If size=1, the random variates are 1D.
- If the parameters are scalars and size > 1, the random variates are 1D.
- If size > 1 and the parameters are sequences, the random variates are
aligned as (size, max(length)), where length is the parameters size.
:Example:
>>> rbernoulli(.1)
0
>>> rbernoulli([.1,.9])
np.asarray([0, 1])
>>> rbernoulli(.9, size=2)
np.asarray([1, 1])
>>> rbernoulli([.1,.9], 2)
np.asarray([[0, 1],
[0, 1]])
"""
# Find the order of the arguments.
refargs, defaults = utils.get_signature(func)
# vfunc = np.vectorize(self.func)
npos = len(refargs) - len(defaults) # Number of pos. arg.
nkwds = len(defaults) # Number of kwds args.
mv = func.__name__[
1:] in mv_continuous_distributions + mv_discrete_distributions
# Use the NumPy random function directly if this is not a multivariate
# distribution
if not mv:
return func
def wrapper(*args, **kwds):
# First transform keyword arguments into positional arguments.
n = len(args)
if nkwds > 0:
args = list(args)
for i, k in enumerate(refargs[n:]):
if k in kwds.keys():
args.append(kwds[k])
else:
args.append(defaults[n - npos + i])
r = []
s = []
largs = []
nr = args[-1]
length = [np.atleast_1d(a).shape[0] for a in args]
dimension = [np.atleast_1d(a).ndim for a in args]
N = max(length)
if len(set(dimension)) > 2:
raise('Dimensions do not agree.')
# Make sure all elements are iterable and have consistent lengths, ie
# 1 or n, but not m and n.
for arg, s in zip(args, length):
t = type(arg)
arr = np.empty(N, type)
if s == 1:
arr.fill(arg)
elif s == N:
arr = np.asarray(arg)
else:
raise RuntimeError('Arguments size not allowed: %s.' % s)
largs.append(arr)
if mv and N > 1 and max(dimension) > 1 and nr > 1:
raise ValueError(
'Multivariate distributions cannot take s>1 and multiple values.')
if mv:
for i, arg in enumerate(largs[:-1]):
largs[0] = np.atleast_2d(arg)
for arg in zip(*largs):
r.append(func(*arg))
size = arg[-1]
vec_stochastics = len(r) > 1
if mv:
if nr == 1:
return r[0]
else:
return np.vstack(r)
else:
if size > 1 and vec_stochastics:
return np.atleast_2d(r).T
elif vec_stochastics or size > 1:
return np.concatenate(r)
else: # Scalar case
return r[0][0]
wrapper.__doc__ = func.__doc__
wrapper.__name__ = func.__name__
return wrapper | python | def randomwrap(func):
"""
Decorator for random value generators
Allows passing of sequence of parameters, as well as a size argument.
Convention:
- If size=1 and the parameters are all scalars, return a scalar.
- If size=1, the random variates are 1D.
- If the parameters are scalars and size > 1, the random variates are 1D.
- If size > 1 and the parameters are sequences, the random variates are
aligned as (size, max(length)), where length is the parameters size.
:Example:
>>> rbernoulli(.1)
0
>>> rbernoulli([.1,.9])
np.asarray([0, 1])
>>> rbernoulli(.9, size=2)
np.asarray([1, 1])
>>> rbernoulli([.1,.9], 2)
np.asarray([[0, 1],
[0, 1]])
"""
# Find the order of the arguments.
refargs, defaults = utils.get_signature(func)
# vfunc = np.vectorize(self.func)
npos = len(refargs) - len(defaults) # Number of pos. arg.
nkwds = len(defaults) # Number of kwds args.
mv = func.__name__[
1:] in mv_continuous_distributions + mv_discrete_distributions
# Use the NumPy random function directly if this is not a multivariate
# distribution
if not mv:
return func
def wrapper(*args, **kwds):
# First transform keyword arguments into positional arguments.
n = len(args)
if nkwds > 0:
args = list(args)
for i, k in enumerate(refargs[n:]):
if k in kwds.keys():
args.append(kwds[k])
else:
args.append(defaults[n - npos + i])
r = []
s = []
largs = []
nr = args[-1]
length = [np.atleast_1d(a).shape[0] for a in args]
dimension = [np.atleast_1d(a).ndim for a in args]
N = max(length)
if len(set(dimension)) > 2:
raise('Dimensions do not agree.')
# Make sure all elements are iterable and have consistent lengths, ie
# 1 or n, but not m and n.
for arg, s in zip(args, length):
t = type(arg)
arr = np.empty(N, type)
if s == 1:
arr.fill(arg)
elif s == N:
arr = np.asarray(arg)
else:
raise RuntimeError('Arguments size not allowed: %s.' % s)
largs.append(arr)
if mv and N > 1 and max(dimension) > 1 and nr > 1:
raise ValueError(
'Multivariate distributions cannot take s>1 and multiple values.')
if mv:
for i, arg in enumerate(largs[:-1]):
largs[0] = np.atleast_2d(arg)
for arg in zip(*largs):
r.append(func(*arg))
size = arg[-1]
vec_stochastics = len(r) > 1
if mv:
if nr == 1:
return r[0]
else:
return np.vstack(r)
else:
if size > 1 and vec_stochastics:
return np.atleast_2d(r).T
elif vec_stochastics or size > 1:
return np.concatenate(r)
else: # Scalar case
return r[0][0]
wrapper.__doc__ = func.__doc__
wrapper.__name__ = func.__name__
return wrapper | [
"def",
"randomwrap",
"(",
"func",
")",
":",
"# Find the order of the arguments.",
"refargs",
",",
"defaults",
"=",
"utils",
".",
"get_signature",
"(",
"func",
")",
"# vfunc = np.vectorize(self.func)",
"npos",
"=",
"len",
"(",
"refargs",
")",
"-",
"len",
"(",
"de... | Decorator for random value generators
Allows passing of sequence of parameters, as well as a size argument.
Convention:
- If size=1 and the parameters are all scalars, return a scalar.
- If size=1, the random variates are 1D.
- If the parameters are scalars and size > 1, the random variates are 1D.
- If size > 1 and the parameters are sequences, the random variates are
aligned as (size, max(length)), where length is the parameters size.
:Example:
>>> rbernoulli(.1)
0
>>> rbernoulli([.1,.9])
np.asarray([0, 1])
>>> rbernoulli(.9, size=2)
np.asarray([1, 1])
>>> rbernoulli([.1,.9], 2)
np.asarray([[0, 1],
[0, 1]]) | [
"Decorator",
"for",
"random",
"value",
"generators"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L469-L572 |
225,372 | pymc-devs/pymc | pymc/distributions.py | constrain | def constrain(value, lower=-np.Inf, upper=np.Inf, allow_equal=False):
"""
Apply interval constraint on stochastic value.
"""
ok = flib.constrain(value, lower, upper, allow_equal)
if ok == 0:
raise ZeroProbability | python | def constrain(value, lower=-np.Inf, upper=np.Inf, allow_equal=False):
"""
Apply interval constraint on stochastic value.
"""
ok = flib.constrain(value, lower, upper, allow_equal)
if ok == 0:
raise ZeroProbability | [
"def",
"constrain",
"(",
"value",
",",
"lower",
"=",
"-",
"np",
".",
"Inf",
",",
"upper",
"=",
"np",
".",
"Inf",
",",
"allow_equal",
"=",
"False",
")",
":",
"ok",
"=",
"flib",
".",
"constrain",
"(",
"value",
",",
"lower",
",",
"upper",
",",
"allo... | Apply interval constraint on stochastic value. | [
"Apply",
"interval",
"constraint",
"on",
"stochastic",
"value",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L599-L606 |
225,373 | pymc-devs/pymc | pymc/distributions.py | expand_triangular | def expand_triangular(X, k):
"""
Expand flattened triangular matrix.
"""
X = X.tolist()
# Unflatten matrix
Y = np.asarray(
[[0] * i + X[i * k - (i * (i - 1)) / 2: i * k + (k - i)] for i in range(k)])
# Loop over rows
for i in range(k):
# Loop over columns
for j in range(k):
Y[j, i] = Y[i, j]
return Y | python | def expand_triangular(X, k):
"""
Expand flattened triangular matrix.
"""
X = X.tolist()
# Unflatten matrix
Y = np.asarray(
[[0] * i + X[i * k - (i * (i - 1)) / 2: i * k + (k - i)] for i in range(k)])
# Loop over rows
for i in range(k):
# Loop over columns
for j in range(k):
Y[j, i] = Y[i, j]
return Y | [
"def",
"expand_triangular",
"(",
"X",
",",
"k",
")",
":",
"X",
"=",
"X",
".",
"tolist",
"(",
")",
"# Unflatten matrix",
"Y",
"=",
"np",
".",
"asarray",
"(",
"[",
"[",
"0",
"]",
"*",
"i",
"+",
"X",
"[",
"i",
"*",
"k",
"-",
"(",
"i",
"*",
"("... | Expand flattened triangular matrix. | [
"Expand",
"flattened",
"triangular",
"matrix",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L632-L646 |
225,374 | pymc-devs/pymc | pymc/distributions.py | rarlognormal | def rarlognormal(a, sigma, rho, size=1):
R"""
Autoregressive normal random variates.
If a is a scalar, generates one series of length size.
If a is a sequence, generates size series of the same length
as a.
"""
f = utils.ar1
if np.isscalar(a):
r = f(rho, 0, sigma, size)
else:
n = len(a)
r = [f(rho, 0, sigma, n) for i in range(size)]
if size == 1:
r = r[0]
return a * np.exp(r) | python | def rarlognormal(a, sigma, rho, size=1):
R"""
Autoregressive normal random variates.
If a is a scalar, generates one series of length size.
If a is a sequence, generates size series of the same length
as a.
"""
f = utils.ar1
if np.isscalar(a):
r = f(rho, 0, sigma, size)
else:
n = len(a)
r = [f(rho, 0, sigma, n) for i in range(size)]
if size == 1:
r = r[0]
return a * np.exp(r) | [
"def",
"rarlognormal",
"(",
"a",
",",
"sigma",
",",
"rho",
",",
"size",
"=",
"1",
")",
":",
"f",
"=",
"utils",
".",
"ar1",
"if",
"np",
".",
"isscalar",
"(",
"a",
")",
":",
"r",
"=",
"f",
"(",
"rho",
",",
"0",
",",
"sigma",
",",
"size",
")",... | R"""
Autoregressive normal random variates.
If a is a scalar, generates one series of length size.
If a is a sequence, generates size series of the same length
as a. | [
"R",
"Autoregressive",
"normal",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L722-L738 |
225,375 | pymc-devs/pymc | pymc/distributions.py | arlognormal_like | def arlognormal_like(x, a, sigma, rho):
R"""
Autoregressive lognormal log-likelihood.
.. math::
x_i & = a_i \exp(e_i) \\
e_i & = \rho e_{i-1} + \epsilon_i
where :math:`\epsilon_i \sim N(0,\sigma)`.
"""
return flib.arlognormal(x, np.log(a), sigma, rho, beta=1) | python | def arlognormal_like(x, a, sigma, rho):
R"""
Autoregressive lognormal log-likelihood.
.. math::
x_i & = a_i \exp(e_i) \\
e_i & = \rho e_{i-1} + \epsilon_i
where :math:`\epsilon_i \sim N(0,\sigma)`.
"""
return flib.arlognormal(x, np.log(a), sigma, rho, beta=1) | [
"def",
"arlognormal_like",
"(",
"x",
",",
"a",
",",
"sigma",
",",
"rho",
")",
":",
"return",
"flib",
".",
"arlognormal",
"(",
"x",
",",
"np",
".",
"log",
"(",
"a",
")",
",",
"sigma",
",",
"rho",
",",
"beta",
"=",
"1",
")"
] | R"""
Autoregressive lognormal log-likelihood.
.. math::
x_i & = a_i \exp(e_i) \\
e_i & = \rho e_{i-1} + \epsilon_i
where :math:`\epsilon_i \sim N(0,\sigma)`. | [
"R",
"Autoregressive",
"lognormal",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L741-L751 |
225,376 | pymc-devs/pymc | pymc/distributions.py | rbeta | def rbeta(alpha, beta, size=None):
"""
Random beta variates.
"""
from scipy.stats.distributions import beta as sbeta
return sbeta.ppf(np.random.random(size), alpha, beta) | python | def rbeta(alpha, beta, size=None):
"""
Random beta variates.
"""
from scipy.stats.distributions import beta as sbeta
return sbeta.ppf(np.random.random(size), alpha, beta) | [
"def",
"rbeta",
"(",
"alpha",
",",
"beta",
",",
"size",
"=",
"None",
")",
":",
"from",
"scipy",
".",
"stats",
".",
"distributions",
"import",
"beta",
"as",
"sbeta",
"return",
"sbeta",
".",
"ppf",
"(",
"np",
".",
"random",
".",
"random",
"(",
"size",
... | Random beta variates. | [
"Random",
"beta",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L803-L808 |
225,377 | pymc-devs/pymc | pymc/distributions.py | rbinomial | def rbinomial(n, p, size=None):
"""
Random binomial variates.
"""
if not size:
size = None
return np.random.binomial(np.ravel(n), np.ravel(p), size) | python | def rbinomial(n, p, size=None):
"""
Random binomial variates.
"""
if not size:
size = None
return np.random.binomial(np.ravel(n), np.ravel(p), size) | [
"def",
"rbinomial",
"(",
"n",
",",
"p",
",",
"size",
"=",
"None",
")",
":",
"if",
"not",
"size",
":",
"size",
"=",
"None",
"return",
"np",
".",
"random",
".",
"binomial",
"(",
"np",
".",
"ravel",
"(",
"n",
")",
",",
"np",
".",
"ravel",
"(",
"... | Random binomial variates. | [
"Random",
"binomial",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L858-L864 |
225,378 | pymc-devs/pymc | pymc/distributions.py | rbetabin | def rbetabin(alpha, beta, n, size=None):
"""
Random beta-binomial variates.
"""
phi = np.random.beta(alpha, beta, size)
return np.random.binomial(n, phi) | python | def rbetabin(alpha, beta, n, size=None):
"""
Random beta-binomial variates.
"""
phi = np.random.beta(alpha, beta, size)
return np.random.binomial(n, phi) | [
"def",
"rbetabin",
"(",
"alpha",
",",
"beta",
",",
"n",
",",
"size",
"=",
"None",
")",
":",
"phi",
"=",
"np",
".",
"random",
".",
"beta",
"(",
"alpha",
",",
"beta",
",",
"size",
")",
"return",
"np",
".",
"random",
".",
"binomial",
"(",
"n",
","... | Random beta-binomial variates. | [
"Random",
"beta",
"-",
"binomial",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L904-L910 |
225,379 | pymc-devs/pymc | pymc/distributions.py | rcategorical | def rcategorical(p, size=None):
"""
Categorical random variates.
"""
out = flib.rcat(p, np.random.random(size=size))
if sum(out.shape) == 1:
return out.squeeze()
else:
return out | python | def rcategorical(p, size=None):
"""
Categorical random variates.
"""
out = flib.rcat(p, np.random.random(size=size))
if sum(out.shape) == 1:
return out.squeeze()
else:
return out | [
"def",
"rcategorical",
"(",
"p",
",",
"size",
"=",
"None",
")",
":",
"out",
"=",
"flib",
".",
"rcat",
"(",
"p",
",",
"np",
".",
"random",
".",
"random",
"(",
"size",
"=",
"size",
")",
")",
"if",
"sum",
"(",
"out",
".",
"shape",
")",
"==",
"1"... | Categorical random variates. | [
"Categorical",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L957-L965 |
225,380 | pymc-devs/pymc | pymc/distributions.py | categorical_like | def categorical_like(x, p):
R"""
Categorical log-likelihood. The most general discrete distribution.
.. math:: f(x=i \mid p) = p_i
for :math:`i \in 0 \ldots k-1`.
:Parameters:
- `x` : [int] :math:`x \in 0\ldots k-1`
- `p` : [float] :math:`p > 0`, :math:`\sum p = 1`
"""
p = np.atleast_2d(p)
if np.any(abs(np.sum(p, 1) - 1) > 0.0001):
print_("Probabilities in categorical_like sum to", np.sum(p, 1))
return flib.categorical(np.array(x).astype(int), p) | python | def categorical_like(x, p):
R"""
Categorical log-likelihood. The most general discrete distribution.
.. math:: f(x=i \mid p) = p_i
for :math:`i \in 0 \ldots k-1`.
:Parameters:
- `x` : [int] :math:`x \in 0\ldots k-1`
- `p` : [float] :math:`p > 0`, :math:`\sum p = 1`
"""
p = np.atleast_2d(p)
if np.any(abs(np.sum(p, 1) - 1) > 0.0001):
print_("Probabilities in categorical_like sum to", np.sum(p, 1))
return flib.categorical(np.array(x).astype(int), p) | [
"def",
"categorical_like",
"(",
"x",
",",
"p",
")",
":",
"p",
"=",
"np",
".",
"atleast_2d",
"(",
"p",
")",
"if",
"np",
".",
"any",
"(",
"abs",
"(",
"np",
".",
"sum",
"(",
"p",
",",
"1",
")",
"-",
"1",
")",
">",
"0.0001",
")",
":",
"print_",... | R"""
Categorical log-likelihood. The most general discrete distribution.
.. math:: f(x=i \mid p) = p_i
for :math:`i \in 0 \ldots k-1`.
:Parameters:
- `x` : [int] :math:`x \in 0\ldots k-1`
- `p` : [float] :math:`p > 0`, :math:`\sum p = 1` | [
"R",
"Categorical",
"log",
"-",
"likelihood",
".",
"The",
"most",
"general",
"discrete",
"distribution",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L968-L985 |
225,381 | pymc-devs/pymc | pymc/distributions.py | rcauchy | def rcauchy(alpha, beta, size=None):
"""
Returns Cauchy random variates.
"""
return alpha + beta * np.tan(pi * random_number(size) - pi / 2.0) | python | def rcauchy(alpha, beta, size=None):
"""
Returns Cauchy random variates.
"""
return alpha + beta * np.tan(pi * random_number(size) - pi / 2.0) | [
"def",
"rcauchy",
"(",
"alpha",
",",
"beta",
",",
"size",
"=",
"None",
")",
":",
"return",
"alpha",
"+",
"beta",
"*",
"np",
".",
"tan",
"(",
"pi",
"*",
"random_number",
"(",
"size",
")",
"-",
"pi",
"/",
"2.0",
")"
] | Returns Cauchy random variates. | [
"Returns",
"Cauchy",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L990-L995 |
225,382 | pymc-devs/pymc | pymc/distributions.py | degenerate_like | def degenerate_like(x, k):
R"""
Degenerate log-likelihood.
.. math::
f(x \mid k) = \left\{ \begin{matrix} 1 \text{ if } x = k \\ 0 \text{ if } x \ne k\end{matrix} \right.
:Parameters:
- `x` : Input value.
- `k` : Degenerate value.
"""
x = np.atleast_1d(x)
return sum(np.log([i == k for i in x])) | python | def degenerate_like(x, k):
R"""
Degenerate log-likelihood.
.. math::
f(x \mid k) = \left\{ \begin{matrix} 1 \text{ if } x = k \\ 0 \text{ if } x \ne k\end{matrix} \right.
:Parameters:
- `x` : Input value.
- `k` : Degenerate value.
"""
x = np.atleast_1d(x)
return sum(np.log([i == k for i in x])) | [
"def",
"degenerate_like",
"(",
"x",
",",
"k",
")",
":",
"x",
"=",
"np",
".",
"atleast_1d",
"(",
"x",
")",
"return",
"sum",
"(",
"np",
".",
"log",
"(",
"[",
"i",
"==",
"k",
"for",
"i",
"in",
"x",
"]",
")",
")"
] | R"""
Degenerate log-likelihood.
.. math::
f(x \mid k) = \left\{ \begin{matrix} 1 \text{ if } x = k \\ 0 \text{ if } x \ne k\end{matrix} \right.
:Parameters:
- `x` : Input value.
- `k` : Degenerate value. | [
"R",
"Degenerate",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1094-L1107 |
225,383 | pymc-devs/pymc | pymc/distributions.py | rdirichlet | def rdirichlet(theta, size=1):
"""
Dirichlet random variates.
"""
gammas = np.vstack([rgamma(theta, 1) for i in xrange(size)])
if size > 1 and np.size(theta) > 1:
return (gammas.T / gammas.sum(1))[:-1].T
elif np.size(theta) > 1:
return (gammas[0] / gammas[0].sum())[:-1]
else:
return 1. | python | def rdirichlet(theta, size=1):
"""
Dirichlet random variates.
"""
gammas = np.vstack([rgamma(theta, 1) for i in xrange(size)])
if size > 1 and np.size(theta) > 1:
return (gammas.T / gammas.sum(1))[:-1].T
elif np.size(theta) > 1:
return (gammas[0] / gammas[0].sum())[:-1]
else:
return 1. | [
"def",
"rdirichlet",
"(",
"theta",
",",
"size",
"=",
"1",
")",
":",
"gammas",
"=",
"np",
".",
"vstack",
"(",
"[",
"rgamma",
"(",
"theta",
",",
"1",
")",
"for",
"i",
"in",
"xrange",
"(",
"size",
")",
"]",
")",
"if",
"size",
">",
"1",
"and",
"n... | Dirichlet random variates. | [
"Dirichlet",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1128-L1138 |
225,384 | pymc-devs/pymc | pymc/distributions.py | dirichlet_like | def dirichlet_like(x, theta):
R"""
Dirichlet log-likelihood.
This is a multivariate continuous distribution.
.. math::
f(\mathbf{x}) = \frac{\Gamma(\sum_{i=1}^k \theta_i)}{\prod \Gamma(\theta_i)}\prod_{i=1}^{k-1} x_i^{\theta_i - 1}
\cdot\left(1-\sum_{i=1}^{k-1}x_i\right)^\theta_k
:Parameters:
x : (n, k-1) array
Array of shape (n, k-1) where `n` is the number of samples
and `k` the dimension.
:math:`0 < x_i < 1`, :math:`\sum_{i=1}^{k-1} x_i < 1`
theta : array
An (n,k) or (1,k) array > 0.
.. note::
Only the first `k-1` elements of `x` are expected. Can be used
as a parent of Multinomial and Categorical nevertheless.
"""
x = np.atleast_2d(x)
theta = np.atleast_2d(theta)
if (np.shape(x)[-1] + 1) != np.shape(theta)[-1]:
raise ValueError('The dimension of x in dirichlet_like must be k-1.')
return flib.dirichlet(x, theta) | python | def dirichlet_like(x, theta):
R"""
Dirichlet log-likelihood.
This is a multivariate continuous distribution.
.. math::
f(\mathbf{x}) = \frac{\Gamma(\sum_{i=1}^k \theta_i)}{\prod \Gamma(\theta_i)}\prod_{i=1}^{k-1} x_i^{\theta_i - 1}
\cdot\left(1-\sum_{i=1}^{k-1}x_i\right)^\theta_k
:Parameters:
x : (n, k-1) array
Array of shape (n, k-1) where `n` is the number of samples
and `k` the dimension.
:math:`0 < x_i < 1`, :math:`\sum_{i=1}^{k-1} x_i < 1`
theta : array
An (n,k) or (1,k) array > 0.
.. note::
Only the first `k-1` elements of `x` are expected. Can be used
as a parent of Multinomial and Categorical nevertheless.
"""
x = np.atleast_2d(x)
theta = np.atleast_2d(theta)
if (np.shape(x)[-1] + 1) != np.shape(theta)[-1]:
raise ValueError('The dimension of x in dirichlet_like must be k-1.')
return flib.dirichlet(x, theta) | [
"def",
"dirichlet_like",
"(",
"x",
",",
"theta",
")",
":",
"x",
"=",
"np",
".",
"atleast_2d",
"(",
"x",
")",
"theta",
"=",
"np",
".",
"atleast_2d",
"(",
"theta",
")",
"if",
"(",
"np",
".",
"shape",
"(",
"x",
")",
"[",
"-",
"1",
"]",
"+",
"1",... | R"""
Dirichlet log-likelihood.
This is a multivariate continuous distribution.
.. math::
f(\mathbf{x}) = \frac{\Gamma(\sum_{i=1}^k \theta_i)}{\prod \Gamma(\theta_i)}\prod_{i=1}^{k-1} x_i^{\theta_i - 1}
\cdot\left(1-\sum_{i=1}^{k-1}x_i\right)^\theta_k
:Parameters:
x : (n, k-1) array
Array of shape (n, k-1) where `n` is the number of samples
and `k` the dimension.
:math:`0 < x_i < 1`, :math:`\sum_{i=1}^{k-1} x_i < 1`
theta : array
An (n,k) or (1,k) array > 0.
.. note::
Only the first `k-1` elements of `x` are expected. Can be used
as a parent of Multinomial and Categorical nevertheless. | [
"R",
"Dirichlet",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1148-L1175 |
225,385 | pymc-devs/pymc | pymc/distributions.py | rexponweib | def rexponweib(alpha, k, loc=0, scale=1, size=None):
"""
Random exponentiated Weibull variates.
"""
q = np.random.uniform(size=size)
r = flib.exponweib_ppf(q, alpha, k)
return loc + r * scale | python | def rexponweib(alpha, k, loc=0, scale=1, size=None):
"""
Random exponentiated Weibull variates.
"""
q = np.random.uniform(size=size)
r = flib.exponweib_ppf(q, alpha, k)
return loc + r * scale | [
"def",
"rexponweib",
"(",
"alpha",
",",
"k",
",",
"loc",
"=",
"0",
",",
"scale",
"=",
"1",
",",
"size",
"=",
"None",
")",
":",
"q",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"size",
")",
"r",
"=",
"flib",
".",
"exponweib_ppf",... | Random exponentiated Weibull variates. | [
"Random",
"exponentiated",
"Weibull",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1225-L1232 |
225,386 | pymc-devs/pymc | pymc/distributions.py | exponweib_like | def exponweib_like(x, alpha, k, loc=0, scale=1):
R"""
Exponentiated Weibull log-likelihood.
The exponentiated Weibull distribution is a generalization of the Weibull
family. Its value lies in being able to model monotone and non-monotone
failure rates.
.. math::
f(x \mid \alpha,k,loc,scale) & = \frac{\alpha k}{scale} (1-e^{-z^k})^{\alpha-1} e^{-z^k} z^{k-1} \\
z & = \frac{x-loc}{scale}
:Parameters:
- `x` : x > 0
- `alpha` : Shape parameter
- `k` : k > 0
- `loc` : Location parameter
- `scale` : Scale parameter (scale > 0).
"""
return flib.exponweib(x, alpha, k, loc, scale) | python | def exponweib_like(x, alpha, k, loc=0, scale=1):
R"""
Exponentiated Weibull log-likelihood.
The exponentiated Weibull distribution is a generalization of the Weibull
family. Its value lies in being able to model monotone and non-monotone
failure rates.
.. math::
f(x \mid \alpha,k,loc,scale) & = \frac{\alpha k}{scale} (1-e^{-z^k})^{\alpha-1} e^{-z^k} z^{k-1} \\
z & = \frac{x-loc}{scale}
:Parameters:
- `x` : x > 0
- `alpha` : Shape parameter
- `k` : k > 0
- `loc` : Location parameter
- `scale` : Scale parameter (scale > 0).
"""
return flib.exponweib(x, alpha, k, loc, scale) | [
"def",
"exponweib_like",
"(",
"x",
",",
"alpha",
",",
"k",
",",
"loc",
"=",
"0",
",",
"scale",
"=",
"1",
")",
":",
"return",
"flib",
".",
"exponweib",
"(",
"x",
",",
"alpha",
",",
"k",
",",
"loc",
",",
"scale",
")"
] | R"""
Exponentiated Weibull log-likelihood.
The exponentiated Weibull distribution is a generalization of the Weibull
family. Its value lies in being able to model monotone and non-monotone
failure rates.
.. math::
f(x \mid \alpha,k,loc,scale) & = \frac{\alpha k}{scale} (1-e^{-z^k})^{\alpha-1} e^{-z^k} z^{k-1} \\
z & = \frac{x-loc}{scale}
:Parameters:
- `x` : x > 0
- `alpha` : Shape parameter
- `k` : k > 0
- `loc` : Location parameter
- `scale` : Scale parameter (scale > 0). | [
"R",
"Exponentiated",
"Weibull",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1241-L1261 |
225,387 | pymc-devs/pymc | pymc/distributions.py | rgamma | def rgamma(alpha, beta, size=None):
"""
Random gamma variates.
"""
return np.random.gamma(shape=alpha, scale=1. / beta, size=size) | python | def rgamma(alpha, beta, size=None):
"""
Random gamma variates.
"""
return np.random.gamma(shape=alpha, scale=1. / beta, size=size) | [
"def",
"rgamma",
"(",
"alpha",
",",
"beta",
",",
"size",
"=",
"None",
")",
":",
"return",
"np",
".",
"random",
".",
"gamma",
"(",
"shape",
"=",
"alpha",
",",
"scale",
"=",
"1.",
"/",
"beta",
",",
"size",
"=",
"size",
")"
] | Random gamma variates. | [
"Random",
"gamma",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1275-L1280 |
225,388 | pymc-devs/pymc | pymc/distributions.py | gev_expval | def gev_expval(xi, mu=0, sigma=1):
"""
Expected value of generalized extreme value distribution.
"""
return mu - (sigma / xi) + (sigma / xi) * flib.gamfun(1 - xi) | python | def gev_expval(xi, mu=0, sigma=1):
"""
Expected value of generalized extreme value distribution.
"""
return mu - (sigma / xi) + (sigma / xi) * flib.gamfun(1 - xi) | [
"def",
"gev_expval",
"(",
"xi",
",",
"mu",
"=",
"0",
",",
"sigma",
"=",
"1",
")",
":",
"return",
"mu",
"-",
"(",
"sigma",
"/",
"xi",
")",
"+",
"(",
"sigma",
"/",
"xi",
")",
"*",
"flib",
".",
"gamfun",
"(",
"1",
"-",
"xi",
")"
] | Expected value of generalized extreme value distribution. | [
"Expected",
"value",
"of",
"generalized",
"extreme",
"value",
"distribution",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1333-L1337 |
225,389 | pymc-devs/pymc | pymc/distributions.py | gev_like | def gev_like(x, xi, mu=0, sigma=1):
R"""
Generalized Extreme Value log-likelihood
.. math::
pdf(x \mid \xi,\mu,\sigma) = \frac{1}{\sigma}(1 + \xi \left[\frac{x-\mu}{\sigma}\right])^{-1/\xi-1}\exp{-(1+\xi \left[\frac{x-\mu}{\sigma}\right])^{-1/\xi}}
.. math::
\sigma & > 0,\\
x & > \mu-\sigma/\xi \text{ if } \xi > 0,\\
x & < \mu-\sigma/\xi \text{ if } \xi < 0\\
x & \in [-\infty,\infty] \text{ if } \xi = 0
"""
return flib.gev(x, xi, mu, sigma) | python | def gev_like(x, xi, mu=0, sigma=1):
R"""
Generalized Extreme Value log-likelihood
.. math::
pdf(x \mid \xi,\mu,\sigma) = \frac{1}{\sigma}(1 + \xi \left[\frac{x-\mu}{\sigma}\right])^{-1/\xi-1}\exp{-(1+\xi \left[\frac{x-\mu}{\sigma}\right])^{-1/\xi}}
.. math::
\sigma & > 0,\\
x & > \mu-\sigma/\xi \text{ if } \xi > 0,\\
x & < \mu-\sigma/\xi \text{ if } \xi < 0\\
x & \in [-\infty,\infty] \text{ if } \xi = 0
"""
return flib.gev(x, xi, mu, sigma) | [
"def",
"gev_like",
"(",
"x",
",",
"xi",
",",
"mu",
"=",
"0",
",",
"sigma",
"=",
"1",
")",
":",
"return",
"flib",
".",
"gev",
"(",
"x",
",",
"xi",
",",
"mu",
",",
"sigma",
")"
] | R"""
Generalized Extreme Value log-likelihood
.. math::
pdf(x \mid \xi,\mu,\sigma) = \frac{1}{\sigma}(1 + \xi \left[\frac{x-\mu}{\sigma}\right])^{-1/\xi-1}\exp{-(1+\xi \left[\frac{x-\mu}{\sigma}\right])^{-1/\xi}}
.. math::
\sigma & > 0,\\
x & > \mu-\sigma/\xi \text{ if } \xi > 0,\\
x & < \mu-\sigma/\xi \text{ if } \xi < 0\\
x & \in [-\infty,\infty] \text{ if } \xi = 0 | [
"R",
"Generalized",
"Extreme",
"Value",
"log",
"-",
"likelihood"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1340-L1355 |
225,390 | pymc-devs/pymc | pymc/distributions.py | rhalf_cauchy | def rhalf_cauchy(alpha, beta, size=None):
"""
Returns half-Cauchy random variates.
"""
return abs(alpha + beta * np.tan(pi * random_number(size) - pi / 2.0)) | python | def rhalf_cauchy(alpha, beta, size=None):
"""
Returns half-Cauchy random variates.
"""
return abs(alpha + beta * np.tan(pi * random_number(size) - pi / 2.0)) | [
"def",
"rhalf_cauchy",
"(",
"alpha",
",",
"beta",
",",
"size",
"=",
"None",
")",
":",
"return",
"abs",
"(",
"alpha",
"+",
"beta",
"*",
"np",
".",
"tan",
"(",
"pi",
"*",
"random_number",
"(",
"size",
")",
"-",
"pi",
"/",
"2.0",
")",
")"
] | Returns half-Cauchy random variates. | [
"Returns",
"half",
"-",
"Cauchy",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1403-L1408 |
225,391 | pymc-devs/pymc | pymc/distributions.py | half_cauchy_like | def half_cauchy_like(x, alpha, beta):
R"""
Half-Cauchy log-likelihood. Simply the absolute value of Cauchy.
.. math::
f(x \mid \alpha, \beta) = \frac{2}{\pi \beta [1 + (\frac{x-\alpha}{\beta})^2]}
:Parameters:
- `alpha` : Location parameter.
- `beta` : Scale parameter (beta > 0).
.. note::
- x must be non-negative.
"""
x = np.atleast_1d(x)
if sum(x.ravel() < 0):
return -inf
return flib.cauchy(x, alpha, beta) + len(x) * np.log(2) | python | def half_cauchy_like(x, alpha, beta):
R"""
Half-Cauchy log-likelihood. Simply the absolute value of Cauchy.
.. math::
f(x \mid \alpha, \beta) = \frac{2}{\pi \beta [1 + (\frac{x-\alpha}{\beta})^2]}
:Parameters:
- `alpha` : Location parameter.
- `beta` : Scale parameter (beta > 0).
.. note::
- x must be non-negative.
"""
x = np.atleast_1d(x)
if sum(x.ravel() < 0):
return -inf
return flib.cauchy(x, alpha, beta) + len(x) * np.log(2) | [
"def",
"half_cauchy_like",
"(",
"x",
",",
"alpha",
",",
"beta",
")",
":",
"x",
"=",
"np",
".",
"atleast_1d",
"(",
"x",
")",
"if",
"sum",
"(",
"x",
".",
"ravel",
"(",
")",
"<",
"0",
")",
":",
"return",
"-",
"inf",
"return",
"flib",
".",
"cauchy"... | R"""
Half-Cauchy log-likelihood. Simply the absolute value of Cauchy.
.. math::
f(x \mid \alpha, \beta) = \frac{2}{\pi \beta [1 + (\frac{x-\alpha}{\beta})^2]}
:Parameters:
- `alpha` : Location parameter.
- `beta` : Scale parameter (beta > 0).
.. note::
- x must be non-negative. | [
"R",
"Half",
"-",
"Cauchy",
"log",
"-",
"likelihood",
".",
"Simply",
"the",
"absolute",
"value",
"of",
"Cauchy",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1421-L1439 |
225,392 | pymc-devs/pymc | pymc/distributions.py | rhalf_normal | def rhalf_normal(tau, size=None):
"""
Random half-normal variates.
"""
return abs(np.random.normal(0, np.sqrt(1 / tau), size)) | python | def rhalf_normal(tau, size=None):
"""
Random half-normal variates.
"""
return abs(np.random.normal(0, np.sqrt(1 / tau), size)) | [
"def",
"rhalf_normal",
"(",
"tau",
",",
"size",
"=",
"None",
")",
":",
"return",
"abs",
"(",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"np",
".",
"sqrt",
"(",
"1",
"/",
"tau",
")",
",",
"size",
")",
")"
] | Random half-normal variates. | [
"Random",
"half",
"-",
"normal",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1445-L1450 |
225,393 | pymc-devs/pymc | pymc/distributions.py | rhypergeometric | def rhypergeometric(n, m, N, size=None):
"""
Returns hypergeometric random variates.
"""
if n == 0:
return np.zeros(size, dtype=int)
elif n == N:
out = np.empty(size, dtype=int)
out.fill(m)
return out
return np.random.hypergeometric(n, N - n, m, size) | python | def rhypergeometric(n, m, N, size=None):
"""
Returns hypergeometric random variates.
"""
if n == 0:
return np.zeros(size, dtype=int)
elif n == N:
out = np.empty(size, dtype=int)
out.fill(m)
return out
return np.random.hypergeometric(n, N - n, m, size) | [
"def",
"rhypergeometric",
"(",
"n",
",",
"m",
",",
"N",
",",
"size",
"=",
"None",
")",
":",
"if",
"n",
"==",
"0",
":",
"return",
"np",
".",
"zeros",
"(",
"size",
",",
"dtype",
"=",
"int",
")",
"elif",
"n",
"==",
"N",
":",
"out",
"=",
"np",
... | Returns hypergeometric random variates. | [
"Returns",
"hypergeometric",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1483-L1493 |
225,394 | pymc-devs/pymc | pymc/distributions.py | hypergeometric_like | def hypergeometric_like(x, n, m, N):
R"""
Hypergeometric log-likelihood.
Discrete probability distribution that describes the number of successes in
a sequence of draws from a finite population without replacement.
.. math::
f(x \mid n, m, N) = \frac{\left({ \begin{array}{c} {m} \\ {x} \\
\end{array} }\right)\left({ \begin{array}{c} {N-m} \\ {n-x} \\
\end{array}}\right)}{\left({ \begin{array}{c} {N} \\ {n} \\
\end{array}}\right)}
:Parameters:
- `x` : [int] Number of successes in a sample drawn from a population.
- `n` : [int] Size of sample drawn from the population.
- `m` : [int] Number of successes in the population.
- `N` : [int] Total number of units in the population.
.. note::
:math:`E(X) = \frac{n n}{N}`
"""
return flib.hyperg(x, n, m, N) | python | def hypergeometric_like(x, n, m, N):
R"""
Hypergeometric log-likelihood.
Discrete probability distribution that describes the number of successes in
a sequence of draws from a finite population without replacement.
.. math::
f(x \mid n, m, N) = \frac{\left({ \begin{array}{c} {m} \\ {x} \\
\end{array} }\right)\left({ \begin{array}{c} {N-m} \\ {n-x} \\
\end{array}}\right)}{\left({ \begin{array}{c} {N} \\ {n} \\
\end{array}}\right)}
:Parameters:
- `x` : [int] Number of successes in a sample drawn from a population.
- `n` : [int] Size of sample drawn from the population.
- `m` : [int] Number of successes in the population.
- `N` : [int] Total number of units in the population.
.. note::
:math:`E(X) = \frac{n n}{N}`
"""
return flib.hyperg(x, n, m, N) | [
"def",
"hypergeometric_like",
"(",
"x",
",",
"n",
",",
"m",
",",
"N",
")",
":",
"return",
"flib",
".",
"hyperg",
"(",
"x",
",",
"n",
",",
"m",
",",
"N",
")"
] | R"""
Hypergeometric log-likelihood.
Discrete probability distribution that describes the number of successes in
a sequence of draws from a finite population without replacement.
.. math::
f(x \mid n, m, N) = \frac{\left({ \begin{array}{c} {m} \\ {x} \\
\end{array} }\right)\left({ \begin{array}{c} {N-m} \\ {n-x} \\
\end{array}}\right)}{\left({ \begin{array}{c} {N} \\ {n} \\
\end{array}}\right)}
:Parameters:
- `x` : [int] Number of successes in a sample drawn from a population.
- `n` : [int] Size of sample drawn from the population.
- `m` : [int] Number of successes in the population.
- `N` : [int] Total number of units in the population.
.. note::
:math:`E(X) = \frac{n n}{N}` | [
"R",
"Hypergeometric",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1503-L1529 |
225,395 | pymc-devs/pymc | pymc/distributions.py | rlogistic | def rlogistic(mu, tau, size=None):
"""
Logistic random variates.
"""
u = np.random.random(size)
return mu + np.log(u / (1 - u)) / tau | python | def rlogistic(mu, tau, size=None):
"""
Logistic random variates.
"""
u = np.random.random(size)
return mu + np.log(u / (1 - u)) / tau | [
"def",
"rlogistic",
"(",
"mu",
",",
"tau",
",",
"size",
"=",
"None",
")",
":",
"u",
"=",
"np",
".",
"random",
".",
"random",
"(",
"size",
")",
"return",
"mu",
"+",
"np",
".",
"log",
"(",
"u",
"/",
"(",
"1",
"-",
"u",
")",
")",
"/",
"tau"
] | Logistic random variates. | [
"Logistic",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1685-L1691 |
225,396 | pymc-devs/pymc | pymc/distributions.py | rlognormal | def rlognormal(mu, tau, size=None):
"""
Return random lognormal variates.
"""
return np.random.lognormal(mu, np.sqrt(1. / tau), size) | python | def rlognormal(mu, tau, size=None):
"""
Return random lognormal variates.
"""
return np.random.lognormal(mu, np.sqrt(1. / tau), size) | [
"def",
"rlognormal",
"(",
"mu",
",",
"tau",
",",
"size",
"=",
"None",
")",
":",
"return",
"np",
".",
"random",
".",
"lognormal",
"(",
"mu",
",",
"np",
".",
"sqrt",
"(",
"1.",
"/",
"tau",
")",
",",
"size",
")"
] | Return random lognormal variates. | [
"Return",
"random",
"lognormal",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1726-L1731 |
225,397 | pymc-devs/pymc | pymc/distributions.py | rmultinomial | def rmultinomial(n, p, size=None):
"""
Random multinomial variates.
"""
# Leaving size=None as the default means return value is 1d array
# if not specified-- nicer.
# Single value for p:
if len(np.shape(p)) == 1:
return np.random.multinomial(n, p, size)
# Multiple values for p:
if np.isscalar(n):
n = n * np.ones(np.shape(p)[0], dtype=np.int)
out = np.empty(np.shape(p))
for i in xrange(np.shape(p)[0]):
out[i, :] = np.random.multinomial(n[i], p[i,:], size)
return out | python | def rmultinomial(n, p, size=None):
"""
Random multinomial variates.
"""
# Leaving size=None as the default means return value is 1d array
# if not specified-- nicer.
# Single value for p:
if len(np.shape(p)) == 1:
return np.random.multinomial(n, p, size)
# Multiple values for p:
if np.isscalar(n):
n = n * np.ones(np.shape(p)[0], dtype=np.int)
out = np.empty(np.shape(p))
for i in xrange(np.shape(p)[0]):
out[i, :] = np.random.multinomial(n[i], p[i,:], size)
return out | [
"def",
"rmultinomial",
"(",
"n",
",",
"p",
",",
"size",
"=",
"None",
")",
":",
"# Leaving size=None as the default means return value is 1d array",
"# if not specified-- nicer.",
"# Single value for p:",
"if",
"len",
"(",
"np",
".",
"shape",
"(",
"p",
")",
")",
"=="... | Random multinomial variates. | [
"Random",
"multinomial",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1773-L1790 |
225,398 | pymc-devs/pymc | pymc/distributions.py | multinomial_like | def multinomial_like(x, n, p):
R"""
Multinomial log-likelihood.
Generalization of the binomial
distribution, but instead of each trial resulting in "success" or
"failure", each one results in exactly one of some fixed finite number k
of possible outcomes over n independent trials. 'x[i]' indicates the number
of times outcome number i was observed over the n trials.
.. math::
f(x \mid n, p) = \frac{n!}{\prod_{i=1}^k x_i!} \prod_{i=1}^k p_i^{x_i}
:Parameters:
x : (ns, k) int
Random variable indicating the number of time outcome i is
observed. :math:`\sum_{i=1}^k x_i=n`, :math:`x_i \ge 0`.
n : int
Number of trials.
p : (k,)
Probability of each one of the different outcomes.
:math:`\sum_{i=1}^k p_i = 1)`, :math:`p_i \ge 0`.
.. note::
- :math:`E(X_i)=n p_i`
- :math:`Var(X_i)=n p_i(1-p_i)`
- :math:`Cov(X_i,X_j) = -n p_i p_j`
- If :math:`\sum_i p_i < 0.999999` a log-likelihood value of -inf
will be returned.
"""
# flib expects 2d arguments. Do we still want to support multiple p
# values along realizations ?
x = np.atleast_2d(x)
p = np.atleast_2d(p)
return flib.multinomial(x, n, p) | python | def multinomial_like(x, n, p):
R"""
Multinomial log-likelihood.
Generalization of the binomial
distribution, but instead of each trial resulting in "success" or
"failure", each one results in exactly one of some fixed finite number k
of possible outcomes over n independent trials. 'x[i]' indicates the number
of times outcome number i was observed over the n trials.
.. math::
f(x \mid n, p) = \frac{n!}{\prod_{i=1}^k x_i!} \prod_{i=1}^k p_i^{x_i}
:Parameters:
x : (ns, k) int
Random variable indicating the number of time outcome i is
observed. :math:`\sum_{i=1}^k x_i=n`, :math:`x_i \ge 0`.
n : int
Number of trials.
p : (k,)
Probability of each one of the different outcomes.
:math:`\sum_{i=1}^k p_i = 1)`, :math:`p_i \ge 0`.
.. note::
- :math:`E(X_i)=n p_i`
- :math:`Var(X_i)=n p_i(1-p_i)`
- :math:`Cov(X_i,X_j) = -n p_i p_j`
- If :math:`\sum_i p_i < 0.999999` a log-likelihood value of -inf
will be returned.
"""
# flib expects 2d arguments. Do we still want to support multiple p
# values along realizations ?
x = np.atleast_2d(x)
p = np.atleast_2d(p)
return flib.multinomial(x, n, p) | [
"def",
"multinomial_like",
"(",
"x",
",",
"n",
",",
"p",
")",
":",
"# flib expects 2d arguments. Do we still want to support multiple p",
"# values along realizations ?",
"x",
"=",
"np",
".",
"atleast_2d",
"(",
"x",
")",
"p",
"=",
"np",
".",
"atleast_2d",
"(",
"p"... | R"""
Multinomial log-likelihood.
Generalization of the binomial
distribution, but instead of each trial resulting in "success" or
"failure", each one results in exactly one of some fixed finite number k
of possible outcomes over n independent trials. 'x[i]' indicates the number
of times outcome number i was observed over the n trials.
.. math::
f(x \mid n, p) = \frac{n!}{\prod_{i=1}^k x_i!} \prod_{i=1}^k p_i^{x_i}
:Parameters:
x : (ns, k) int
Random variable indicating the number of time outcome i is
observed. :math:`\sum_{i=1}^k x_i=n`, :math:`x_i \ge 0`.
n : int
Number of trials.
p : (k,)
Probability of each one of the different outcomes.
:math:`\sum_{i=1}^k p_i = 1)`, :math:`p_i \ge 0`.
.. note::
- :math:`E(X_i)=n p_i`
- :math:`Var(X_i)=n p_i(1-p_i)`
- :math:`Cov(X_i,X_j) = -n p_i p_j`
- If :math:`\sum_i p_i < 0.999999` a log-likelihood value of -inf
will be returned. | [
"R",
"Multinomial",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1800-L1836 |
225,399 | pymc-devs/pymc | pymc/distributions.py | rmultivariate_hypergeometric | def rmultivariate_hypergeometric(n, m, size=None):
"""
Random multivariate hypergeometric variates.
Parameters:
- `n` : Number of draws.
- `m` : Number of items in each categoy.
"""
N = len(m)
urn = np.repeat(np.arange(N), m)
if size:
draw = np.array([[urn[i] for i in np.random.permutation(len(urn))[:n]]
for j in range(size)])
r = [[np.sum(draw[j] == i) for i in range(len(m))]
for j in range(size)]
else:
draw = np.array([urn[i] for i in np.random.permutation(len(urn))[:n]])
r = [np.sum(draw == i) for i in range(len(m))]
return np.asarray(r) | python | def rmultivariate_hypergeometric(n, m, size=None):
"""
Random multivariate hypergeometric variates.
Parameters:
- `n` : Number of draws.
- `m` : Number of items in each categoy.
"""
N = len(m)
urn = np.repeat(np.arange(N), m)
if size:
draw = np.array([[urn[i] for i in np.random.permutation(len(urn))[:n]]
for j in range(size)])
r = [[np.sum(draw[j] == i) for i in range(len(m))]
for j in range(size)]
else:
draw = np.array([urn[i] for i in np.random.permutation(len(urn))[:n]])
r = [np.sum(draw == i) for i in range(len(m))]
return np.asarray(r) | [
"def",
"rmultivariate_hypergeometric",
"(",
"n",
",",
"m",
",",
"size",
"=",
"None",
")",
":",
"N",
"=",
"len",
"(",
"m",
")",
"urn",
"=",
"np",
".",
"repeat",
"(",
"np",
".",
"arange",
"(",
"N",
")",
",",
"m",
")",
"if",
"size",
":",
"draw",
... | Random multivariate hypergeometric variates.
Parameters:
- `n` : Number of draws.
- `m` : Number of items in each categoy. | [
"Random",
"multivariate",
"hypergeometric",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1841-L1863 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.