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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
239,100
pymc-devs/pymc
pymc/InstantiationDecorators.py
robust_init
def robust_init(stochclass, tries, *args, **kwds): """Robust initialization of a Stochastic. If the evaluation of the log-probability returns a ZeroProbability error, due for example to a parent being outside of the support for this Stochastic, the values of parents are randomly sampled until a valid log-probability is obtained. If the log-probability is still not valid after `tries` attempts, the original ZeroProbability error is raised. :Parameters: stochclass : Stochastic, eg. Normal, Uniform, ... The Stochastic distribution to instantiate. tries : int Maximum number of times parents will be sampled. *args, **kwds Positional and keyword arguments to declare the Stochastic variable. :Example: >>> lower = pymc.Uniform('lower', 0., 2., value=1.5, rseed=True) >>> pymc.robust_init(pymc.Uniform, 100, 'data', lower=lower, upper=5, value=[1,2,3,4], observed=True) """ # Find the direct parents stochs = [arg for arg in (list(args) + list(kwds.values())) if isinstance(arg.__class__, StochasticMeta)] # Find the extended parents parents = stochs for s in stochs: parents.extend(s.extended_parents) extended_parents = set(parents) # Select the parents with a random method. random_parents = [ p for p in extended_parents if p.rseed is True and hasattr( p, 'random')] for i in range(tries): try: return stochclass(*args, **kwds) except ZeroProbability: exc = sys.exc_info() for parent in random_parents: try: parent.random() except: six.reraise(*exc) six.reraise(*exc)
python
def robust_init(stochclass, tries, *args, **kwds): # Find the direct parents stochs = [arg for arg in (list(args) + list(kwds.values())) if isinstance(arg.__class__, StochasticMeta)] # Find the extended parents parents = stochs for s in stochs: parents.extend(s.extended_parents) extended_parents = set(parents) # Select the parents with a random method. random_parents = [ p for p in extended_parents if p.rseed is True and hasattr( p, 'random')] for i in range(tries): try: return stochclass(*args, **kwds) except ZeroProbability: exc = sys.exc_info() for parent in random_parents: try: parent.random() except: six.reraise(*exc) six.reraise(*exc)
[ "def", "robust_init", "(", "stochclass", ",", "tries", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "# Find the direct parents", "stochs", "=", "[", "arg", "for", "arg", "in", "(", "list", "(", "args", ")", "+", "list", "(", "kwds", ".", "value...
Robust initialization of a Stochastic. If the evaluation of the log-probability returns a ZeroProbability error, due for example to a parent being outside of the support for this Stochastic, the values of parents are randomly sampled until a valid log-probability is obtained. If the log-probability is still not valid after `tries` attempts, the original ZeroProbability error is raised. :Parameters: stochclass : Stochastic, eg. Normal, Uniform, ... The Stochastic distribution to instantiate. tries : int Maximum number of times parents will be sampled. *args, **kwds Positional and keyword arguments to declare the Stochastic variable. :Example: >>> lower = pymc.Uniform('lower', 0., 2., value=1.5, rseed=True) >>> pymc.robust_init(pymc.Uniform, 100, 'data', lower=lower, upper=5, value=[1,2,3,4], observed=True)
[ "Robust", "initialization", "of", "a", "Stochastic", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/InstantiationDecorators.py#L300-L351
239,101
pymc-devs/pymc
pymc/examples/gp/more_examples/MKMsalmon/salmon.py
salmon.plot
def plot(self): """ Plot posterior from simple nonstochetric regression. """ figure() plot_envelope(self.M, self.C, self.xplot) for i in range(3): f = Realization(self.M, self.C) plot(self.xplot,f(self.xplot)) plot(self.abundance, self.frye, 'k.', markersize=4) xlabel('Female abundance') ylabel('Frye density') title(self.name) axis('tight')
python
def plot(self): figure() plot_envelope(self.M, self.C, self.xplot) for i in range(3): f = Realization(self.M, self.C) plot(self.xplot,f(self.xplot)) plot(self.abundance, self.frye, 'k.', markersize=4) xlabel('Female abundance') ylabel('Frye density') title(self.name) axis('tight')
[ "def", "plot", "(", "self", ")", ":", "figure", "(", ")", "plot_envelope", "(", "self", ".", "M", ",", "self", ".", "C", ",", "self", ".", "xplot", ")", "for", "i", "in", "range", "(", "3", ")", ":", "f", "=", "Realization", "(", "self", ".", ...
Plot posterior from simple nonstochetric regression.
[ "Plot", "posterior", "from", "simple", "nonstochetric", "regression", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/examples/gp/more_examples/MKMsalmon/salmon.py#L54-L68
239,102
pymc-devs/pymc
pymc/examples/melanoma.py
survival
def survival(value=t, lam=lam, f=failure): """Exponential survival likelihood, accounting for censoring""" return sum(f * log(lam) - lam * value)
python
def survival(value=t, lam=lam, f=failure): return sum(f * log(lam) - lam * value)
[ "def", "survival", "(", "value", "=", "t", ",", "lam", "=", "lam", ",", "f", "=", "failure", ")", ":", "return", "sum", "(", "f", "*", "log", "(", "lam", ")", "-", "lam", "*", "value", ")" ]
Exponential survival likelihood, accounting for censoring
[ "Exponential", "survival", "likelihood", "accounting", "for", "censoring" ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/examples/melanoma.py#L43-L45
239,103
pymc-devs/pymc
pymc/examples/disaster_model_gof.py
disasters_sim
def disasters_sim(early_mean=early_mean, late_mean=late_mean, switchpoint=switchpoint): """Coal mining disasters sampled from the posterior predictive distribution""" return concatenate((pm.rpoisson(early_mean, size=switchpoint), pm.rpoisson( late_mean, size=n - switchpoint)))
python
def disasters_sim(early_mean=early_mean, late_mean=late_mean, switchpoint=switchpoint): return concatenate((pm.rpoisson(early_mean, size=switchpoint), pm.rpoisson( late_mean, size=n - switchpoint)))
[ "def", "disasters_sim", "(", "early_mean", "=", "early_mean", ",", "late_mean", "=", "late_mean", ",", "switchpoint", "=", "switchpoint", ")", ":", "return", "concatenate", "(", "(", "pm", ".", "rpoisson", "(", "early_mean", ",", "size", "=", "switchpoint", ...
Coal mining disasters sampled from the posterior predictive distribution
[ "Coal", "mining", "disasters", "sampled", "from", "the", "posterior", "predictive", "distribution" ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/examples/disaster_model_gof.py#L50-L55
239,104
pymc-devs/pymc
pymc/examples/disaster_model_gof.py
expected_values
def expected_values(early_mean=early_mean, late_mean=late_mean, switchpoint=switchpoint): """Discrepancy measure for GOF using the Freeman-Tukey statistic""" # Sample size n = len(disasters_array) # Expected values return concatenate( (ones(switchpoint) * early_mean, ones(n - switchpoint) * late_mean))
python
def expected_values(early_mean=early_mean, late_mean=late_mean, switchpoint=switchpoint): # Sample size n = len(disasters_array) # Expected values return concatenate( (ones(switchpoint) * early_mean, ones(n - switchpoint) * late_mean))
[ "def", "expected_values", "(", "early_mean", "=", "early_mean", ",", "late_mean", "=", "late_mean", ",", "switchpoint", "=", "switchpoint", ")", ":", "# Sample size", "n", "=", "len", "(", "disasters_array", ")", "# Expected values", "return", "concatenate", "(", ...
Discrepancy measure for GOF using the Freeman-Tukey statistic
[ "Discrepancy", "measure", "for", "GOF", "using", "the", "Freeman", "-", "Tukey", "statistic" ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/examples/disaster_model_gof.py#L59-L68
239,105
pymc-devs/pymc
pymc/database/pickle.py
load
def load(filename): """Load a pickled database. Return a Database instance. """ file = open(filename, 'rb') container = std_pickle.load(file) file.close() db = Database(file.name) chains = 0 funs = set() for k, v in six.iteritems(container): if k == '_state_': db._state_ = v else: db._traces[k] = Trace(name=k, value=v, db=db) setattr(db, k, db._traces[k]) chains = max(chains, len(v)) funs.add(k) db.chains = chains db.trace_names = chains * [list(funs)] return db
python
def load(filename): file = open(filename, 'rb') container = std_pickle.load(file) file.close() db = Database(file.name) chains = 0 funs = set() for k, v in six.iteritems(container): if k == '_state_': db._state_ = v else: db._traces[k] = Trace(name=k, value=v, db=db) setattr(db, k, db._traces[k]) chains = max(chains, len(v)) funs.add(k) db.chains = chains db.trace_names = chains * [list(funs)] return db
[ "def", "load", "(", "filename", ")", ":", "file", "=", "open", "(", "filename", ",", "'rb'", ")", "container", "=", "std_pickle", ".", "load", "(", "file", ")", "file", ".", "close", "(", ")", "db", "=", "Database", "(", "file", ".", "name", ")", ...
Load a pickled database. Return a Database instance.
[ "Load", "a", "pickled", "database", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/pickle.py#L77-L100
239,106
pymc-devs/pymc
pymc/database/pickle.py
Database._finalize
def _finalize(self): """Dump traces using cPickle.""" container = {} try: for name in self._traces: container[name] = self._traces[name]._trace container['_state_'] = self._state_ file = open(self.filename, 'w+b') std_pickle.dump(container, file) file.close() except AttributeError: pass
python
def _finalize(self): container = {} try: for name in self._traces: container[name] = self._traces[name]._trace container['_state_'] = self._state_ file = open(self.filename, 'w+b') std_pickle.dump(container, file) file.close() except AttributeError: pass
[ "def", "_finalize", "(", "self", ")", ":", "container", "=", "{", "}", "try", ":", "for", "name", "in", "self", ".", "_traces", ":", "container", "[", "name", "]", "=", "self", ".", "_traces", "[", "name", "]", ".", "_trace", "container", "[", "'_s...
Dump traces using cPickle.
[ "Dump", "traces", "using", "cPickle", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/database/pickle.py#L62-L74
239,107
pymc-devs/pymc
pymc/diagnostics.py
geweke
def geweke(x, first=.1, last=.5, intervals=20, maxlag=20): """Return z-scores for convergence diagnostics. Compare the mean of the first % of series with the mean of the last % of series. x is divided into a number of segments for which this difference is computed. If the series is converged, this score should oscillate between -1 and 1. Parameters ---------- x : array-like The trace of some stochastic parameter. first : float The fraction of series at the beginning of the trace. last : float The fraction of series at the end to be compared with the section at the beginning. intervals : int The number of segments. maxlag : int Maximum autocorrelation lag for estimation of spectral variance Returns ------- scores : list [[]] Return a list of [i, score], where i is the starting index for each interval and score the Geweke score on the interval. Notes ----- The Geweke score on some series x is computed by: .. math:: \frac{E[x_s] - E[x_e]}{\sqrt{V[x_s] + V[x_e]}} where :math:`E` stands for the mean, :math:`V` the variance, :math:`x_s` a section at the start of the series and :math:`x_e` a section at the end of the series. References ---------- Geweke (1992) """ if not has_sm: print("statsmodels not available. Geweke diagnostic cannot be calculated.") return if np.ndim(x) > 1: return [geweke(y, first, last, intervals) for y in np.transpose(x)] # Filter out invalid intervals if first + last >= 1: raise ValueError( "Invalid intervals for Geweke convergence analysis", (first, last)) # Initialize list of z-scores zscores = [None] * intervals # Starting points for calculations starts = np.linspace(0, int(len(x)*(1.-last)), intervals).astype(int) # Loop over start indices for i,s in enumerate(starts): # Size of remaining array x_trunc = x[s:] n = len(x_trunc) # Calculate slices first_slice = x_trunc[:int(first * n)] last_slice = x_trunc[int(last * n):] z = (first_slice.mean() - last_slice.mean()) z /= np.sqrt(spec(first_slice)/len(first_slice) + spec(last_slice)/len(last_slice)) zscores[i] = len(x) - n, z return zscores
python
def geweke(x, first=.1, last=.5, intervals=20, maxlag=20): if not has_sm: print("statsmodels not available. Geweke diagnostic cannot be calculated.") return if np.ndim(x) > 1: return [geweke(y, first, last, intervals) for y in np.transpose(x)] # Filter out invalid intervals if first + last >= 1: raise ValueError( "Invalid intervals for Geweke convergence analysis", (first, last)) # Initialize list of z-scores zscores = [None] * intervals # Starting points for calculations starts = np.linspace(0, int(len(x)*(1.-last)), intervals).astype(int) # Loop over start indices for i,s in enumerate(starts): # Size of remaining array x_trunc = x[s:] n = len(x_trunc) # Calculate slices first_slice = x_trunc[:int(first * n)] last_slice = x_trunc[int(last * n):] z = (first_slice.mean() - last_slice.mean()) z /= np.sqrt(spec(first_slice)/len(first_slice) + spec(last_slice)/len(last_slice)) zscores[i] = len(x) - n, z return zscores
[ "def", "geweke", "(", "x", ",", "first", "=", ".1", ",", "last", "=", ".5", ",", "intervals", "=", "20", ",", "maxlag", "=", "20", ")", ":", "if", "not", "has_sm", ":", "print", "(", "\"statsmodels not available. Geweke diagnostic cannot be calculated.\"", "...
Return z-scores for convergence diagnostics. Compare the mean of the first % of series with the mean of the last % of series. x is divided into a number of segments for which this difference is computed. If the series is converged, this score should oscillate between -1 and 1. Parameters ---------- x : array-like The trace of some stochastic parameter. first : float The fraction of series at the beginning of the trace. last : float The fraction of series at the end to be compared with the section at the beginning. intervals : int The number of segments. maxlag : int Maximum autocorrelation lag for estimation of spectral variance Returns ------- scores : list [[]] Return a list of [i, score], where i is the starting index for each interval and score the Geweke score on the interval. Notes ----- The Geweke score on some series x is computed by: .. math:: \frac{E[x_s] - E[x_e]}{\sqrt{V[x_s] + V[x_e]}} where :math:`E` stands for the mean, :math:`V` the variance, :math:`x_s` a section at the start of the series and :math:`x_e` a section at the end of the series. References ---------- Geweke (1992)
[ "Return", "z", "-", "scores", "for", "convergence", "diagnostics", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L236-L315
239,108
pymc-devs/pymc
pymc/diagnostics.py
raftery_lewis
def raftery_lewis(x, q, r, s=.95, epsilon=.001, verbose=1): """ Return the number of iterations needed to achieve a given precision. :Parameters: x : sequence Sampled series. q : float Quantile. r : float Accuracy requested for quantile. s (optional) : float Probability of attaining the requested accuracy (defaults to 0.95). epsilon (optional) : float Half width of the tolerance interval required for the q-quantile (defaults to 0.001). verbose (optional) : int Verbosity level for output (defaults to 1). :Return: nmin : int Minimum number of independent iterates required to achieve the specified accuracy for the q-quantile. kthin : int Skip parameter sufficient to produce a first-order Markov chain. nburn : int Number of iterations to be discarded at the beginning of the simulation, i.e. the number of burn-in iterations. nprec : int Number of iterations not including the burn-in iterations which need to be obtained in order to attain the precision specified by the values of the q, r and s input parameters. kmind : int Minimum skip parameter sufficient to produce an independence chain. :Example: >>> raftery_lewis(x, q=.025, r=.005) :Reference: Raftery, A.E. and Lewis, S.M. (1995). The number of iterations, convergence diagnostics and generic Metropolis algorithms. In Practical Markov Chain Monte Carlo (W.R. Gilks, D.J. Spiegelhalter and S. Richardson, eds.). London, U.K.: Chapman and Hall. See the fortran source file `gibbsit.f` for more details and references. """ if np.ndim(x) > 1: return [raftery_lewis(y, q, r, s, epsilon, verbose) for y in np.transpose(x)] output = nmin, kthin, nburn, nprec, kmind = flib.gibbmain( x, q, r, s, epsilon) if verbose: print_("\n========================") print_("Raftery-Lewis Diagnostic") print_("========================") print_() print_( "%s iterations required (assuming independence) to achieve %s accuracy with %i percent probability." % (nmin, r, 100 * s)) print_() print_( "Thinning factor of %i required to produce a first-order Markov chain." % kthin) print_() print_( "%i iterations to be discarded at the beginning of the simulation (burn-in)." % nburn) print_() print_("%s subsequent iterations required." % nprec) print_() print_( "Thinning factor of %i required to produce an independence chain." % kmind) return output
python
def raftery_lewis(x, q, r, s=.95, epsilon=.001, verbose=1): if np.ndim(x) > 1: return [raftery_lewis(y, q, r, s, epsilon, verbose) for y in np.transpose(x)] output = nmin, kthin, nburn, nprec, kmind = flib.gibbmain( x, q, r, s, epsilon) if verbose: print_("\n========================") print_("Raftery-Lewis Diagnostic") print_("========================") print_() print_( "%s iterations required (assuming independence) to achieve %s accuracy with %i percent probability." % (nmin, r, 100 * s)) print_() print_( "Thinning factor of %i required to produce a first-order Markov chain." % kthin) print_() print_( "%i iterations to be discarded at the beginning of the simulation (burn-in)." % nburn) print_() print_("%s subsequent iterations required." % nprec) print_() print_( "Thinning factor of %i required to produce an independence chain." % kmind) return output
[ "def", "raftery_lewis", "(", "x", ",", "q", ",", "r", ",", "s", "=", ".95", ",", "epsilon", "=", ".001", ",", "verbose", "=", "1", ")", ":", "if", "np", ".", "ndim", "(", "x", ")", ">", "1", ":", "return", "[", "raftery_lewis", "(", "y", ",",...
Return the number of iterations needed to achieve a given precision. :Parameters: x : sequence Sampled series. q : float Quantile. r : float Accuracy requested for quantile. s (optional) : float Probability of attaining the requested accuracy (defaults to 0.95). epsilon (optional) : float Half width of the tolerance interval required for the q-quantile (defaults to 0.001). verbose (optional) : int Verbosity level for output (defaults to 1). :Return: nmin : int Minimum number of independent iterates required to achieve the specified accuracy for the q-quantile. kthin : int Skip parameter sufficient to produce a first-order Markov chain. nburn : int Number of iterations to be discarded at the beginning of the simulation, i.e. the number of burn-in iterations. nprec : int Number of iterations not including the burn-in iterations which need to be obtained in order to attain the precision specified by the values of the q, r and s input parameters. kmind : int Minimum skip parameter sufficient to produce an independence chain. :Example: >>> raftery_lewis(x, q=.025, r=.005) :Reference: Raftery, A.E. and Lewis, S.M. (1995). The number of iterations, convergence diagnostics and generic Metropolis algorithms. In Practical Markov Chain Monte Carlo (W.R. Gilks, D.J. Spiegelhalter and S. Richardson, eds.). London, U.K.: Chapman and Hall. See the fortran source file `gibbsit.f` for more details and references.
[ "Return", "the", "number", "of", "iterations", "needed", "to", "achieve", "a", "given", "precision", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L321-L400
239,109
pymc-devs/pymc
pymc/diagnostics.py
effective_n
def effective_n(x): """ Returns estimate of the effective sample size of a set of traces. Parameters ---------- x : array-like An array containing the 2 or more traces of a stochastic parameter. That is, an array of dimension m x n x k, where m is the number of traces, n the number of samples, and k the dimension of the stochastic. Returns ------- n_eff : float Return the effective sample size, :math:`\hat{n}_{eff}` Notes ----- The diagnostic is computed by: .. math:: \hat{n}_{eff} = \frac{mn}}{1 + 2 \sum_{t=1}^T \hat{\rho}_t} where :math:`\hat{\rho}_t` is the estimated autocorrelation at lag t, and T is the first odd positive integer for which the sum :math:`\hat{\rho}_{T+1} + \hat{\rho}_{T+1}` is negative. References ---------- Gelman et al. (2014)""" if np.shape(x) < (2,): raise ValueError( 'Calculation of effective sample size requires multiple chains of the same length.') try: m, n = np.shape(x) except ValueError: return [effective_n(np.transpose(y)) for y in np.transpose(x)] s2 = gelman_rubin(x, return_var=True) negative_autocorr = False t = 1 variogram = lambda t: (sum(sum((x[j][i] - x[j][i-t])**2 for i in range(t,n)) for j in range(m)) / (m*(n - t))) rho = np.ones(n) # Iterate until the sum of consecutive estimates of autocorrelation is negative while not negative_autocorr and (t < n): rho[t] = 1. - variogram(t)/(2.*s2) if not t % 2: negative_autocorr = sum(rho[t-1:t+1]) < 0 t += 1 return int(m*n / (1 + 2*rho[1:t].sum()))
python
def effective_n(x): if np.shape(x) < (2,): raise ValueError( 'Calculation of effective sample size requires multiple chains of the same length.') try: m, n = np.shape(x) except ValueError: return [effective_n(np.transpose(y)) for y in np.transpose(x)] s2 = gelman_rubin(x, return_var=True) negative_autocorr = False t = 1 variogram = lambda t: (sum(sum((x[j][i] - x[j][i-t])**2 for i in range(t,n)) for j in range(m)) / (m*(n - t))) rho = np.ones(n) # Iterate until the sum of consecutive estimates of autocorrelation is negative while not negative_autocorr and (t < n): rho[t] = 1. - variogram(t)/(2.*s2) if not t % 2: negative_autocorr = sum(rho[t-1:t+1]) < 0 t += 1 return int(m*n / (1 + 2*rho[1:t].sum()))
[ "def", "effective_n", "(", "x", ")", ":", "if", "np", ".", "shape", "(", "x", ")", "<", "(", "2", ",", ")", ":", "raise", "ValueError", "(", "'Calculation of effective sample size requires multiple chains of the same length.'", ")", "try", ":", "m", ",", "n", ...
Returns estimate of the effective sample size of a set of traces. Parameters ---------- x : array-like An array containing the 2 or more traces of a stochastic parameter. That is, an array of dimension m x n x k, where m is the number of traces, n the number of samples, and k the dimension of the stochastic. Returns ------- n_eff : float Return the effective sample size, :math:`\hat{n}_{eff}` Notes ----- The diagnostic is computed by: .. math:: \hat{n}_{eff} = \frac{mn}}{1 + 2 \sum_{t=1}^T \hat{\rho}_t} where :math:`\hat{\rho}_t` is the estimated autocorrelation at lag t, and T is the first odd positive integer for which the sum :math:`\hat{\rho}_{T+1} + \hat{\rho}_{T+1}` is negative. References ---------- Gelman et al. (2014)
[ "Returns", "estimate", "of", "the", "effective", "sample", "size", "of", "a", "set", "of", "traces", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L497-L552
239,110
pymc-devs/pymc
pymc/diagnostics.py
gelman_rubin
def gelman_rubin(x, return_var=False): """ Returns estimate of R for a set of traces. The Gelman-Rubin diagnostic tests for lack of convergence by comparing the variance between multiple chains to the variance within each chain. If convergence has been achieved, the between-chain and within-chain variances should be identical. To be most effective in detecting evidence for nonconvergence, each chain should have been initialized to starting values that are dispersed relative to the target distribution. Parameters ---------- x : array-like An array containing the 2 or more traces of a stochastic parameter. That is, an array of dimension m x n x k, where m is the number of traces, n the number of samples, and k the dimension of the stochastic. return_var : bool Flag for returning the marginal posterior variance instead of R-hat (defaults of False). Returns ------- Rhat : float Return the potential scale reduction factor, :math:`\hat{R}` Notes ----- The diagnostic is computed by: .. math:: \hat{R} = \sqrt{\frac{\hat{V}}{W}} where :math:`W` is the within-chain variance and :math:`\hat{V}` is the posterior variance estimate for the pooled traces. This is the potential scale reduction factor, which converges to unity when each of the traces is a sample from the target posterior. Values greater than one indicate that one or more chains have not yet converged. References ---------- Brooks and Gelman (1998) Gelman and Rubin (1992)""" if np.shape(x) < (2,): raise ValueError( 'Gelman-Rubin diagnostic requires multiple chains of the same length.') try: m, n = np.shape(x) except ValueError: return [gelman_rubin(np.transpose(y)) for y in np.transpose(x)] # Calculate between-chain variance B_over_n = np.sum((np.mean(x, 1) - np.mean(x)) ** 2) / (m - 1) # Calculate within-chain variances W = np.sum( [(x[i] - xbar) ** 2 for i, xbar in enumerate(np.mean(x, 1))]) / (m * (n - 1)) # (over) estimate of variance s2 = W * (n - 1) / n + B_over_n if return_var: return s2 # Pooled posterior variance estimate V = s2 + B_over_n / m # Calculate PSRF R = V / W return np.sqrt(R)
python
def gelman_rubin(x, return_var=False): if np.shape(x) < (2,): raise ValueError( 'Gelman-Rubin diagnostic requires multiple chains of the same length.') try: m, n = np.shape(x) except ValueError: return [gelman_rubin(np.transpose(y)) for y in np.transpose(x)] # Calculate between-chain variance B_over_n = np.sum((np.mean(x, 1) - np.mean(x)) ** 2) / (m - 1) # Calculate within-chain variances W = np.sum( [(x[i] - xbar) ** 2 for i, xbar in enumerate(np.mean(x, 1))]) / (m * (n - 1)) # (over) estimate of variance s2 = W * (n - 1) / n + B_over_n if return_var: return s2 # Pooled posterior variance estimate V = s2 + B_over_n / m # Calculate PSRF R = V / W return np.sqrt(R)
[ "def", "gelman_rubin", "(", "x", ",", "return_var", "=", "False", ")", ":", "if", "np", ".", "shape", "(", "x", ")", "<", "(", "2", ",", ")", ":", "raise", "ValueError", "(", "'Gelman-Rubin diagnostic requires multiple chains of the same length.'", ")", "try",...
Returns estimate of R for a set of traces. The Gelman-Rubin diagnostic tests for lack of convergence by comparing the variance between multiple chains to the variance within each chain. If convergence has been achieved, the between-chain and within-chain variances should be identical. To be most effective in detecting evidence for nonconvergence, each chain should have been initialized to starting values that are dispersed relative to the target distribution. Parameters ---------- x : array-like An array containing the 2 or more traces of a stochastic parameter. That is, an array of dimension m x n x k, where m is the number of traces, n the number of samples, and k the dimension of the stochastic. return_var : bool Flag for returning the marginal posterior variance instead of R-hat (defaults of False). Returns ------- Rhat : float Return the potential scale reduction factor, :math:`\hat{R}` Notes ----- The diagnostic is computed by: .. math:: \hat{R} = \sqrt{\frac{\hat{V}}{W}} where :math:`W` is the within-chain variance and :math:`\hat{V}` is the posterior variance estimate for the pooled traces. This is the potential scale reduction factor, which converges to unity when each of the traces is a sample from the target posterior. Values greater than one indicate that one or more chains have not yet converged. References ---------- Brooks and Gelman (1998) Gelman and Rubin (1992)
[ "Returns", "estimate", "of", "R", "for", "a", "set", "of", "traces", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L556-L627
239,111
pymc-devs/pymc
pymc/diagnostics.py
_find_max_lag
def _find_max_lag(x, rho_limit=0.05, maxmaxlag=20000, verbose=0): """Automatically find an appropriate maximum lag to calculate IAT""" # Fetch autocovariance matrix acv = autocov(x) # Calculate rho rho = acv[0, 1] / acv[0, 0] lam = -1. / np.log(abs(rho)) # Initial guess at 1.5 times lambda (i.e. 3 times mean life) maxlag = int(np.floor(3. * lam)) + 1 # Jump forward 1% of lambda to look for rholimit threshold jump = int(np.ceil(0.01 * lam)) + 1 T = len(x) while ((abs(rho) > rho_limit) & (maxlag < min(T / 2, maxmaxlag))): acv = autocov(x, maxlag) rho = acv[0, 1] / acv[0, 0] maxlag += jump # Add 30% for good measure maxlag = int(np.floor(1.3 * maxlag)) if maxlag >= min(T / 2, maxmaxlag): maxlag = min(min(T / 2, maxlag), maxmaxlag) "maxlag fixed to %d" % maxlag return maxlag if maxlag <= 1: print_("maxlag = %d, fixing value to 10" % maxlag) return 10 if verbose: print_("maxlag = %d" % maxlag) return maxlag
python
def _find_max_lag(x, rho_limit=0.05, maxmaxlag=20000, verbose=0): # Fetch autocovariance matrix acv = autocov(x) # Calculate rho rho = acv[0, 1] / acv[0, 0] lam = -1. / np.log(abs(rho)) # Initial guess at 1.5 times lambda (i.e. 3 times mean life) maxlag = int(np.floor(3. * lam)) + 1 # Jump forward 1% of lambda to look for rholimit threshold jump = int(np.ceil(0.01 * lam)) + 1 T = len(x) while ((abs(rho) > rho_limit) & (maxlag < min(T / 2, maxmaxlag))): acv = autocov(x, maxlag) rho = acv[0, 1] / acv[0, 0] maxlag += jump # Add 30% for good measure maxlag = int(np.floor(1.3 * maxlag)) if maxlag >= min(T / 2, maxmaxlag): maxlag = min(min(T / 2, maxlag), maxmaxlag) "maxlag fixed to %d" % maxlag return maxlag if maxlag <= 1: print_("maxlag = %d, fixing value to 10" % maxlag) return 10 if verbose: print_("maxlag = %d" % maxlag) return maxlag
[ "def", "_find_max_lag", "(", "x", ",", "rho_limit", "=", "0.05", ",", "maxmaxlag", "=", "20000", ",", "verbose", "=", "0", ")", ":", "# Fetch autocovariance matrix", "acv", "=", "autocov", "(", "x", ")", "# Calculate rho", "rho", "=", "acv", "[", "0", ",...
Automatically find an appropriate maximum lag to calculate IAT
[ "Automatically", "find", "an", "appropriate", "maximum", "lag", "to", "calculate", "IAT" ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L630-L668
239,112
pymc-devs/pymc
pymc/diagnostics.py
ppp_value
def ppp_value(simdata, trueval, round=3): """ Calculates posterior predictive p-values on data simulated from the posterior predictive distribution, returning the quantile of the observed data relative to simulated. The posterior predictive p-value is computed by: .. math:: Pr(T(y^{\text{sim}} > T(y) | y) where T is a test statistic of interest and :math:`y^{\text{sim}}` is the simulated 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 round: int Rounding of returned quantile (defaults to 3) """ if ndim(trueval) == 1 and ndim(simdata == 2): # Iterate over more than one set of data return [post_pred_checks(simdata[:, i], trueval[i]) for i in range(len(trueval))] return (simdata > trueval).mean()
python
def ppp_value(simdata, trueval, round=3): if ndim(trueval) == 1 and ndim(simdata == 2): # Iterate over more than one set of data return [post_pred_checks(simdata[:, i], trueval[i]) for i in range(len(trueval))] return (simdata > trueval).mean()
[ "def", "ppp_value", "(", "simdata", ",", "trueval", ",", "round", "=", "3", ")", ":", "if", "ndim", "(", "trueval", ")", "==", "1", "and", "ndim", "(", "simdata", "==", "2", ")", ":", "# Iterate over more than one set of data", "return", "[", "post_pred_ch...
Calculates posterior predictive p-values on data simulated from the posterior predictive distribution, returning the quantile of the observed data relative to simulated. The posterior predictive p-value is computed by: .. math:: Pr(T(y^{\text{sim}} > T(y) | y) where T is a test statistic of interest and :math:`y^{\text{sim}}` is the simulated 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 round: int Rounding of returned quantile (defaults to 3)
[ "Calculates", "posterior", "predictive", "p", "-", "values", "on", "data", "simulated", "from", "the", "posterior", "predictive", "distribution", "returning", "the", "quantile", "of", "the", "observed", "data", "relative", "to", "simulated", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/diagnostics.py#L705-L735
239,113
pymc-devs/pymc
pymc/Model.py
check_valid_object_name
def check_valid_object_name(sequence): """Check that the names of the objects are all different.""" names = [] for o in sequence: if o.__name__ in names: raise ValueError( 'A tallyable PyMC object called %s already exists. This will cause problems for some database backends.' % o.__name__) else: names.append(o.__name__)
python
def check_valid_object_name(sequence): names = [] for o in sequence: if o.__name__ in names: raise ValueError( 'A tallyable PyMC object called %s already exists. This will cause problems for some database backends.' % o.__name__) else: names.append(o.__name__)
[ "def", "check_valid_object_name", "(", "sequence", ")", ":", "names", "=", "[", "]", "for", "o", "in", "sequence", ":", "if", "o", ".", "__name__", "in", "names", ":", "raise", "ValueError", "(", "'A tallyable PyMC object called %s already exists. This will cause pr...
Check that the names of the objects are all different.
[ "Check", "that", "the", "names", "of", "the", "objects", "are", "all", "different", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L847-L856
239,114
pymc-devs/pymc
pymc/Model.py
Model.seed
def seed(self): """ Seed new initial values for the stochastics. """ for generation in self.generations: for s in generation: try: if s.rseed is not None: value = s.random(**s.parents.value) except: pass
python
def seed(self): for generation in self.generations: for s in generation: try: if s.rseed is not None: value = s.random(**s.parents.value) except: pass
[ "def", "seed", "(", "self", ")", ":", "for", "generation", "in", "self", ".", "generations", ":", "for", "s", "in", "generation", ":", "try", ":", "if", "s", ".", "rseed", "is", "not", "None", ":", "value", "=", "s", ".", "random", "(", "*", "*",...
Seed new initial values for the stochastics.
[ "Seed", "new", "initial", "values", "for", "the", "stochastics", "." ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L114-L125
239,115
pymc-devs/pymc
pymc/Model.py
Model.get_node
def get_node(self, node_name): """Retrieve node with passed name""" for node in self.nodes: if node.__name__ == node_name: return node
python
def get_node(self, node_name): for node in self.nodes: if node.__name__ == node_name: return node
[ "def", "get_node", "(", "self", ",", "node_name", ")", ":", "for", "node", "in", "self", ".", "nodes", ":", "if", "node", ".", "__name__", "==", "node_name", ":", "return", "node" ]
Retrieve node with passed name
[ "Retrieve", "node", "with", "passed", "name" ]
c6e530210bff4c0d7189b35b2c971bc53f93f7cd
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Model.py#L127-L131
239,116
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): 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
239,117
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): 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
239,118
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)): # 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
239,119
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)): # 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
239,120
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): 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
239,121
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): # 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
239,122
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): # 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
239,123
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): 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
239,124
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): 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
239,125
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): 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
239,126
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): 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
239,127
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): 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
239,128
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): 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
239,129
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): 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
239,130
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): 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
239,131
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): 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
239,132
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): 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
239,133
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): 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
239,134
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): 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
239,135
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): 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
239,136
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): 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
239,137
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)): # 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
239,138
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): 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
239,139
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(): 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
239,140
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): 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
239,141
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='_'): 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
239,142
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): 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
239,143
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): # 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
239,144
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): # 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
239,145
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): 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
239,146
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): 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
239,147
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): 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
239,148
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): 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
239,149
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): 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
239,150
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 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
239,151
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): 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
239,152
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): 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
239,153
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): 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
239,154
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): 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
239,155
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): 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
239,156
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
239,157
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): 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
239,158
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): 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
239,159
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): 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
239,160
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): 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
239,161
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): 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
239,162
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): 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
239,163
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): 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
239,164
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): 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
239,165
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): 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
239,166
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
239,167
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): 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
239,168
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): 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
239,169
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): 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
239,170
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): 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
239,171
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): # 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
239,172
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): # 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
239,173
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): 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
239,174
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): # 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
239,175
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): 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
239,176
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): 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
239,177
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): 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
239,178
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): 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
239,179
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): 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
239,180
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): 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
239,181
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): 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
239,182
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): 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
239,183
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): 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
239,184
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): 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
239,185
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): # 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
239,186
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): 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
239,187
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): # 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
239,188
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): 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
239,189
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): 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
239,190
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
239,191
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
239,192
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): 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
239,193
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): 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
239,194
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): 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
239,195
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): 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
239,196
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
239,197
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): 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
239,198
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
239,199
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): 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