idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
31,200
def GetSqlValuesTuple ( self , trip_id ) : result = [ ] for fn in self . _SQL_FIELD_NAMES : if fn == 'trip_id' : result . append ( trip_id ) else : result . append ( getattr ( self , fn ) ) return tuple ( result )
Return a tuple that outputs a row of _FIELD_NAMES to be written to a SQLite database .
31,201
def GetTimeSecs ( self ) : if self . arrival_secs != None : return self . arrival_secs elif self . departure_secs != None : return self . departure_secs else : return None
Return the first of arrival_secs and departure_secs that is not None . If both are None return None .
31,202
def create ( filename , spec ) : from . import _segyio if not structured ( spec ) : tracecount = spec . tracecount else : tracecount = len ( spec . ilines ) * len ( spec . xlines ) * len ( spec . offsets ) ext_headers = spec . ext_headers if hasattr ( spec , 'ext_headers' ) else 0 samples = numpy . asarray ( spec . sam...
Create a new segy file .
31,203
def open ( filename , mode = 'r' , iline = 189 , xline = 193 , strict = True , ignore_geometry = False , endian = 'big' ) : if 'w' in mode : problem = 'w in mode would truncate the file' solution = 'use r+ to open in read-write' raise ValueError ( ', ' . join ( ( problem , solution ) ) ) endians = { 'little' : 256 , 'l...
Open a seismic unix file .
31,204
def create_text_header ( lines ) : rows = [ ] for line_no in range ( 1 , 41 ) : line = "" if line_no in lines : line = lines [ line_no ] row = "C{0:>2} {1:76}" . format ( line_no , line ) rows . append ( row ) rows = '' . join ( rows ) return rows
Format textual header
31,205
def wrap ( s , width = 80 ) : return '\n' . join ( textwrap . wrap ( str ( s ) , width = width ) )
Formats the text input with newlines given the user specified width for each line .
31,206
def native ( data , format = segyio . SegySampleFormat . IBM_FLOAT_4_BYTE , copy = True ) : data = data . view ( dtype = np . single ) if copy : data = np . copy ( data ) format = int ( segyio . SegySampleFormat ( format ) ) return segyio . _segyio . native ( data , format )
Convert numpy array to native float
31,207
def cube ( f ) : if not isinstance ( f , segyio . SegyFile ) : with segyio . open ( f ) as fl : return cube ( fl ) ilsort = f . sorting == segyio . TraceSortingFormat . INLINE_SORTING fast = f . ilines if ilsort else f . xlines slow = f . xlines if ilsort else f . ilines fast , slow , offs = len ( fast ) , len ( slow )...
Read a full cube from a file
31,208
def rotation ( f , line = 'fast' ) : if f . unstructured : raise ValueError ( "Rotation requires a structured file" ) lines = { 'fast' : f . fast , 'slow' : f . slow , 'iline' : f . iline , 'xline' : f . xline , } if line not in lines : error = "Unknown line {}" . format ( line ) solution = "Must be any of: {}" . forma...
Find rotation of the survey
31,209
def metadata ( f ) : if not isinstance ( f , segyio . SegyFile ) : with segyio . open ( f ) as fl : return metadata ( fl ) spec = segyio . spec ( ) spec . iline = f . _il spec . xline = f . _xl spec . samples = f . samples spec . format = f . format spec . ilines = f . ilines spec . xlines = f . xlines spec . offsets =...
Get survey structural properties and metadata
31,210
def resample ( f , rate = None , delay = None , micro = False , trace = True , binary = True ) : if rate is not None : if not micro : rate *= 1000 if binary : f . bin [ segyio . su . hdt ] = rate if trace : f . header = { segyio . su . dt : rate } if delay is not None : f . header = { segyio . su . delrt : delay } t0 =...
Resample a file
31,211
def from_array3D ( filename , data , iline = 189 , xline = 193 , format = SegySampleFormat . IBM_FLOAT_4_BYTE , dt = 4000 , delrt = 0 ) : data = np . asarray ( data ) dimensions = len ( data . shape ) if dimensions != 3 : problem = "Expected 3 dimensions, {} was given" . format ( dimensions ) raise ValueError ( problem...
Create a new SEGY file from a 3D array Create an structured SEGY file with defaulted headers from a 3 - dimensional array . The file is inline - sorted . ilines xlines and samples are inferred from the array . Structure - defining fields in the binary header and in the traceheaders are set accordingly . Such fields inc...
31,212
def open ( filename , mode = "r" , iline = 189 , xline = 193 , strict = True , ignore_geometry = False , endian = 'big' ) : if 'w' in mode : problem = 'w in mode would truncate the file' solution = 'use r+ to open in read-write' raise ValueError ( ', ' . join ( ( problem , solution ) ) ) endians = { 'little' : 256 , 'l...
Open a segy file .
31,213
def fetch ( self , buf = None , traceno = None ) : if buf is None : buf = self . buf if traceno is None : traceno = self . traceno try : if self . kind == TraceField : if traceno is None : return buf return self . filehandle . getth ( traceno , buf ) else : return self . filehandle . getbin ( ) except IOError : if not ...
Fetch the header from disk
31,214
def reload ( self ) : self . buf = self . fetch ( buf = self . buf ) return self
This object will read header when it is constructed which means it might be out - of - date if the file is updated through some other handle .
31,215
def flush ( self ) : if self . kind == TraceField : self . filehandle . putth ( self . traceno , self . buf ) elif self . kind == BinField : self . filehandle . putbin ( self . buf ) else : msg = 'Object corrupted: kind {} not valid' raise RuntimeError ( msg . format ( self . kind ) )
Commit backing storage to disk
31,216
def raw ( self ) : return RawTrace ( self . filehandle , self . dtype , len ( self ) , self . shape , self . readonly , )
An eager version of Trace
31,217
def ref ( self ) : x = RefTrace ( self . filehandle , self . dtype , len ( self ) , self . shape , self . readonly , ) yield x x . flush ( )
A write - back version of Trace
31,218
def flush ( self ) : garbage = [ ] for i , ( x , signature ) in self . refs . items ( ) : if sys . getrefcount ( x ) == 3 : garbage . append ( i ) if fingerprint ( x ) == signature : continue self . filehandle . puttr ( i , x ) signature = fingerprint ( x ) for i in garbage : del self . refs [ i ]
Commit cached writes to the file handle . Does not flush libc buffers or notifies the kernel so these changes may not immediately be visible to other processes .
31,219
def iline ( self ) : if self . unstructured : raise ValueError ( self . _unstructured_errmsg ) if self . _iline is not None : return self . _iline self . _iline = Line ( self , self . ilines , self . _iline_length , self . _iline_stride , self . offsets , 'inline' , ) return self . _iline
Interact with segy in inline mode
31,220
def xline ( self ) : if self . unstructured : raise ValueError ( self . _unstructured_errmsg ) if self . _xline is not None : return self . _xline self . _xline = Line ( self , self . xlines , self . _xline_length , self . _xline_stride , self . offsets , 'crossline' , ) return self . _xline
Interact with segy in crossline mode
31,221
def fast ( self ) : if self . sorting == TraceSortingFormat . INLINE_SORTING : return self . iline elif self . sorting == TraceSortingFormat . CROSSLINE_SORTING : return self . xline else : raise RuntimeError ( "Unknown sorting." )
Access the fast dimension
31,222
def gather ( self ) : if self . unstructured : raise ValueError ( self . _unstructured_errmsg ) if self . _gather is not None : return self . _gather self . _gather = Gather ( self . trace , self . iline , self . xline , self . offsets ) return self . _gather
Interact with segy in gather mode
31,223
def pick_best_methods ( stochastic ) : max_competence = 0 best_candidates = set ( [ ] ) for method in StepMethodRegistry : try : competence = method . competence ( stochastic ) except : competence = 0 if competence > max_competence : best_candidates = set ( [ method ] ) max_competence = competence elif competence == ma...
Picks the StepMethods best suited to handle a stochastic variable .
31,224
def loglike ( self ) : sum = logp_of_set ( self . children ) if self . verbose > 2 : print_ ( '\t' + self . _id + ' Current log-likelihood ' , sum ) return sum
The summed log - probability of all stochastic variables that depend on self . stochastics with self . stochastics removed .
31,225
def logp_plus_loglike ( self ) : sum = logp_of_set ( self . markov_blanket ) if self . verbose > 2 : print_ ( '\t' + self . _id + ' Current log-likelihood plus current log-probability' , sum ) return sum
The summed log - probability of all stochastic variables that depend on self . stochastics and self . stochastics .
31,226
def current_state ( self ) : state = { } for s in self . _state : state [ s ] = getattr ( self , s ) return state
Return a dictionary with the current value of the variables defining the state of the step method .
31,227
def step ( self ) : if self . verbose > 2 : print_ ( ) print_ ( self . _id + ' getting initial logp.' ) if self . proposal_distribution == "prior" : logp = self . loglike else : logp = self . logp_plus_loglike if self . verbose > 2 : print_ ( self . _id + ' proposing.' ) self . propose ( ) try : if self . proposal_dist...
The default step method applies if the variable is floating - point valued and is not being proposed from its prior .
31,228
def competence ( s ) : if any ( [ isinstance ( s , cls ) for cls in [ distributions . Wishart , distributions . WishartCov ] ] ) : return 2 else : return 0
The competence function for MatrixMetropolis
31,229
def propose ( self ) : dims = self . stochastic . value . shape dev = rnormal ( 0 , self . adaptive_scale_factor * self . proposal_sd , size = dims ) symmetrize ( dev ) self . stochastic . value = dev + self . stochastic . value
Proposals for positive definite matrix using random walk deviations on the Cholesky factor of the current value .
31,230
def competence ( stochastic ) : if stochastic . dtype in bool_dtypes : return 2 elif isinstance ( stochastic , distributions . Bernoulli ) : return 2 elif ( isinstance ( stochastic , distributions . Categorical ) and ( len ( stochastic . parents [ 'p' ] ) == 2 ) ) : return 2 else : return 0
The competence function for Binary One - At - A - Time Metropolis
31,231
def cov_from_value ( self , scaling ) : rv = [ ] for s in self . stochastics : rv . extend ( np . ravel ( s . value ) . copy ( ) ) arv = np . array ( rv ) arv [ arv == 0 ] = 1. return np . eye ( self . dim ) * np . abs ( arv ) / scaling
Return a covariance matrix for the jump distribution using the actual value of the stochastic as a guess of their variance divided by the scaling argument .
31,232
def cov_from_scales ( self , scales ) : ord_sc = [ ] for stochastic in self . stochastics : ord_sc . append ( np . ravel ( scales [ stochastic ] ) ) ord_sc = np . concatenate ( ord_sc ) if np . squeeze ( ord_sc ) . shape [ 0 ] != self . dim : raise ValueError ( "Improper initial scales, dimension don't match" , ( np . ...
Return a covariance matrix built from a dictionary of scales .
31,233
def cov_from_trace ( self , trace = slice ( None ) ) : n = [ ] for s in self . stochastics : n . append ( s . trace . length ( ) ) n = set ( n ) if len ( n ) > 1 : raise ValueError ( 'Traces do not have the same length.' ) elif n == 0 : raise AttributeError ( 'Stochastic has no trace to compute covariance.' ) else : n ...
Define the jump distribution covariance matrix from the object s stored trace .
31,234
def check_type ( self ) : self . isdiscrete = { } for stochastic in self . stochastics : if stochastic . dtype in integer_dtypes : self . isdiscrete [ stochastic ] = True elif stochastic . dtype in bool_dtypes : raise ValueError ( 'Binary stochastics not supported by AdaptativeMetropolis.' ) else : self . isdiscrete [ ...
Make sure each stochastic has a correct type and identify discrete stochastics .
31,235
def dimension ( self ) : self . dim = 0 self . _slices = { } for stochastic in self . stochastics : if isinstance ( stochastic . value , np . matrix ) : p_len = len ( stochastic . value . A . ravel ( ) ) elif isinstance ( stochastic . value , np . ndarray ) : p_len = len ( stochastic . value . ravel ( ) ) else : p_len ...
Compute the dimension of the sampling space and identify the slices belonging to each stochastic .
31,236
def update_cov ( self ) : scaling = ( 2.4 ) ** 2 / self . dim epsilon = 1.0e-5 chain = np . asarray ( self . _trace ) self . C , self . chain_mean = self . recursive_cov ( self . C , self . _trace_count , self . chain_mean , chain , scaling = scaling , epsilon = epsilon ) acc_rate = self . accepted / ( self . accepted ...
Recursively compute the covariance matrix for the multivariate normal proposal distribution .
31,237
def recursive_cov ( self , cov , length , mean , chain , scaling = 1 , epsilon = 0 ) : r n = length + len ( chain ) k = length new_mean = self . recursive_mean ( mean , length , chain ) t0 = k * np . outer ( mean , mean ) t1 = np . dot ( chain . T , chain ) t2 = n * np . outer ( new_mean , new_mean ) t3 = epsilon * np ...
r Compute the covariance recursively .
31,238
def recursive_mean ( self , mean , length , chain ) : r n = length + len ( chain ) return length * mean / n + chain . sum ( 0 ) / n
r Compute the chain mean recursively .
31,239
def propose ( self ) : arrayjump = np . dot ( self . proposal_sd , np . random . normal ( size = self . proposal_sd . shape [ 0 ] ) ) if self . verbose > 2 : print_ ( 'Jump :' , arrayjump ) for stochastic in self . stochastics : jump = arrayjump [ self . _slices [ stochastic ] ] . squeeze ( ) if np . iterable ( stochas...
This method proposes values for stochastics based on the empirical covariance of the values sampled so far .
31,240
def step ( self ) : logp = self . logp_plus_loglike if self . verbose > 1 : print_ ( 'Current value: ' , self . stoch2array ( ) ) print_ ( 'Current likelihood: ' , logp ) self . propose ( ) accept = False try : logp_p = self . logp_plus_loglike if self . verbose > 2 : print_ ( 'Current value: ' , self . stoch2array ( )...
Perform a Metropolis step .
31,241
def internal_tally ( self ) : chain = [ ] for stochastic in self . stochastics : chain . append ( np . ravel ( stochastic . value ) ) self . _trace . append ( np . concatenate ( chain ) )
Store the trace of stochastics for the computation of the covariance . This trace is completely independent from the backend used by the sampler to store the samples .
31,242
def trace2array ( self , sl ) : chain = [ ] for stochastic in self . stochastics : tr = stochastic . trace . gettrace ( slicing = sl ) if tr is None : raise AttributeError chain . append ( tr ) return np . hstack ( chain )
Return an array with the trace of all stochastics sliced by sl .
31,243
def stoch2array ( self ) : a = np . empty ( self . dim ) for stochastic in self . stochastics : a [ self . _slices [ stochastic ] ] = stochastic . value return a
Return the stochastic objects as an array .
31,244
def walk ( self ) : if self . verbose > 1 : print_ ( '\t' + self . _id + ' Running Walk proposal kernel' ) phi = self . phi theta = self . walk_theta u = random ( len ( phi ) ) z = ( theta / ( 1 + theta ) ) * ( theta * u ** 2 + 2 * u - 1 ) if self . _prime : xp , x = self . values else : x , xp = self . values if self ...
Walk proposal kernel
31,245
def traverse ( self ) : if self . verbose > 1 : print_ ( '\t' + self . _id + ' Running Traverse proposal kernel' ) phi = self . phi theta = self . traverse_theta if ( random ( ) < ( theta - 1 ) / ( 2 * theta ) ) : beta = exp ( 1 / ( theta + 1 ) * log ( random ( ) ) ) else : beta = exp ( 1 / ( 1 - theta ) * log ( random...
Traverse proposal kernel
31,246
def blow ( self ) : if self . verbose > 1 : print_ ( '\t' + self . _id + ' Running Blow proposal kernel' ) phi = self . phi if self . _prime : xp , x = self . values else : x , xp = self . values if self . verbose > 1 : print_ ( '\t' + 'Current value ' + str ( x ) ) sigma = max ( phi * abs ( xp - x ) ) x = x + phi * si...
Blow proposal kernel
31,247
def _g ( self , h , xp , s ) : nphi = sum ( self . phi ) return ( nphi / 2.0 ) * log ( 2 * pi ) + nphi * log ( s ) + 0.5 * sum ( ( h - xp ) ** 2 ) / ( s ** 2 )
Density function for blow and hop moves
31,248
def reject ( self ) : self . stochastic . revert ( ) self . rejected [ self . current_kernel ] += 1 if self . verbose > 1 : print_ ( self . _id , "rejected, reverting to value =" , self . stochastic . value )
Sets current s value to the last accepted value
31,249
def step ( self ) : valid_proposal = False self . _prime = ( random ( ) < 0.5 ) if self . verbose > 1 : print_ ( "\n\nUsing x%s as pivot" % ( " prime" * self . _prime or "" ) ) if self . _prime : self . stochastic . value = self . values [ 1 ] if self . verbose > 1 : print_ ( self . _id , "setting value to auxiliary" ,...
Single iteration of t - walk algorithm
31,250
def step ( self ) : logy = self . loglike - rexponential ( 1 ) L = self . stochastic . value - runiform ( 0 , self . w ) R = L + self . w if self . doubling : K = self . m while ( K and ( logy < self . fll ( L ) or logy < self . fll ( R ) ) ) : if random ( ) < 0.5 : L -= R - L else : R += R - L K -= 1 else : J = np . f...
Slice step method
31,251
def fll ( self , value ) : self . stochastic . value = value try : ll = self . loglike except ZeroProbability : ll = - np . infty self . stochastic . revert ( ) return ll
Returns loglike of value
31,252
def tune ( self , verbose = None ) : if not self . _tune : return False else : self . w_tune . append ( abs ( self . stochastic . last_value - self . stochastic . value ) ) self . w = 2 * ( sum ( self . w_tune ) / len ( self . w_tune ) ) return True
Tuning initial slice width parameter
31,253
def tally ( self , chain ) : value = self . _getfunc ( ) try : self . _trace [ chain ] [ self . _index [ chain ] ] = value . copy ( ) except AttributeError : self . _trace [ chain ] [ self . _index [ chain ] ] = value self . _index [ chain ] += 1
Store the object s current value to a chain .
31,254
def truncate ( self , index , chain ) : self . _trace [ chain ] = self . _trace [ chain ] [ : index ]
Truncate the trace array to some index .
31,255
def gettrace ( self , burn = 0 , thin = 1 , chain = - 1 , slicing = None ) : if slicing is None : slicing = slice ( burn , None , thin ) if chain is not None : if chain < 0 : chain = range ( self . db . chains ) [ chain ] return self . _trace [ chain ] [ slicing ] else : return concatenate ( list ( self . _trace . valu...
Return the trace .
31,256
def load ( dbname , dbmode = 'a' ) : if dbmode == 'w' : raise AttributeError ( "dbmode='w' not allowed for load." ) db = Database ( dbname , dbmode = dbmode ) return db
Load an existing hdf5 database .
31,257
def load ( dirname ) : if not os . path . exists ( dirname ) : raise AttributeError ( 'No txt database named %s' % dirname ) db = Database ( dirname , dbmode = 'a' ) chain_folders = [ os . path . join ( dirname , c ) for c in db . get_chains ( ) ] db . chains = len ( chain_folders ) data = { } for chain , folder in enu...
Create a Database instance from the data stored in the directory .
31,258
def funname ( file ) : if isinstance ( file , str ) : files = [ file ] else : files = file bases = [ os . path . basename ( f ) for f in files ] names = [ os . path . splitext ( b ) [ 0 ] for b in bases ] if isinstance ( file , str ) : return names [ 0 ] else : return names
Return variable names from file names .
31,259
def _finalize ( self , chain ) : path = os . path . join ( self . db . _directory , self . db . get_chains ( ) [ chain ] , self . name + '.txt' ) arr = self . gettrace ( chain = chain ) if six . PY3 : mode = 'wb' else : mode = 'w' with open ( path , mode ) as f : f . write ( six . b ( '# Variable: %s\n' % self . name )...
Write the trace to an ASCII file .
31,260
def _initialize ( self , funs_to_tally , length ) : dir = os . path . join ( self . _directory , CHAIN_NAME % self . chains ) os . mkdir ( dir ) base . Database . _initialize ( self , funs_to_tally , length )
Create folder to store simulation results .
31,261
def savestate ( self , state ) : oldstate = np . get_printoptions ( ) np . set_printoptions ( threshold = 1e6 ) try : with open ( os . path . join ( self . _directory , 'state.txt' ) , 'w' ) as f : print_ ( state , file = f ) finally : np . set_printoptions ( ** oldstate )
Save the sampler s state in a state . txt file .
31,262
def rate ( s = switch , e = early_mean , l = late_mean ) : out = np . empty ( len ( disasters_array ) ) out [ : s ] = e out [ s : ] = l return out
Allocate appropriate mean to time series
31,263
def fast_matrix_copy ( f , t = None , n_threads = 1 ) : if not f . flags [ 'F_CONTIGUOUS' ] : raise RuntimeError ( 'This will not be fast unless input array f is Fortran-contiguous.' ) if t is None : t = asmatrix ( empty ( f . shape , order = 'F' ) ) elif not t . flags [ 'F_CONTIGUOUS' ] : raise RuntimeError ( 'This wi...
Not any faster than a serial copy so far .
31,264
def vecs_to_datmesh ( x , y ) : x , y = meshgrid ( x , y ) out = zeros ( x . shape + ( 2 , ) , dtype = float ) out [ : , : , 0 ] = x out [ : , : , 1 ] = y return out
Converts input arguments x and y to a 2d meshgrid suitable for calling Means Covariances and Realizations .
31,265
def batchsd ( trace , batches = 5 ) : if len ( np . shape ( trace ) ) > 1 : dims = np . shape ( trace ) ttrace = np . transpose ( [ t . ravel ( ) for t in trace ] ) return np . reshape ( [ batchsd ( t , batches ) for t in ttrace ] , dims [ 1 : ] ) else : if batches == 1 : return np . std ( trace ) / np . sqrt ( len ( t...
Calculates the simulation standard error accounting for non - independent samples . The trace is divided into batches and the standard deviation of the batch means is calculated .
31,266
def _initialize ( self , chain , length ) : if self . _getfunc is None : self . _getfunc = self . db . model . _funs_to_tally [ self . name ]
Prepare for tallying . Create a new chain .
31,267
def _initialize ( self , funs_to_tally , length = None ) : for name , fun in six . iteritems ( funs_to_tally ) : if name not in self . _traces : self . _traces [ name ] = self . __Trace__ ( name = name , getfunc = fun , db = self ) self . _traces [ name ] . _initialize ( self . chains , length ) self . trace_names . ap...
Initialize the tallyable objects .
31,268
def _finalize ( self , chain = - 1 ) : chain = range ( self . chains ) [ chain ] for name in self . trace_names [ chain ] : self . _traces [ name ] . _finalize ( chain ) self . commit ( )
Finalize the chain for all tallyable objects .
31,269
def truncate ( self , index , chain = - 1 ) : chain = range ( self . chains ) [ chain ] for name in self . trace_names [ chain ] : self . _traces [ name ] . truncate ( index , chain )
Tell the traces to truncate themselves at the given index .
31,270
def observe ( self , C , obs_mesh_new , obs_vals_new , mean_under = None ) : self . C = C self . obs_mesh = C . obs_mesh self . obs_len = C . obs_len self . Uo = C . Uo if mean_under is None : mean_under_new = C . _mean_under_new ( self , obs_mesh_new ) else : mean_under_new = mean_under if not self . observed : self ....
Synchronizes self s observation status with C s . Values of observation are given by obs_vals .
31,271
def _extract ( __func__ , kwds , keys , classname , probe = True ) : kwds [ 'doc' ] = __func__ . __doc__ if not 'name' in kwds : kwds [ 'name' ] = __func__ . __name__ parents = { } if probe : cur_status = check_special_methods ( ) disable_special_methods ( ) def probeFunc ( frame , event , arg ) : if event == 'return' ...
Used by decorators stochastic and deterministic to inspect declarations
31,272
def observed ( obj = None , ** kwds ) : if obj is not None : if isinstance ( obj , Stochastic ) : obj . _observed = True return obj else : p = stochastic ( __func__ = obj , observed = True , ** kwds ) return p kwds [ 'observed' ] = True def instantiate_observed ( func ) : return stochastic ( func , ** kwds ) return ins...
Decorator function to instantiate data objects . If given a Stochastic sets a the observed flag to True .
31,273
def robust_init ( stochclass , tries , * args , ** kwds ) : stochs = [ arg for arg in ( list ( args ) + list ( kwds . values ( ) ) ) if isinstance ( arg . __class__ , StochasticMeta ) ] parents = stochs for s in stochs : parents . extend ( s . extended_parents ) extended_parents = set ( parents ) random_parents = [ p f...
Robust initialization of a Stochastic .
31,274
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 ( se...
Plot posterior from simple nonstochetric regression .
31,275
def survival ( value = t , lam = lam , f = failure ) : return sum ( f * log ( lam ) - lam * value )
Exponential survival likelihood accounting for censoring
31,276
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 ) ) )
Coal mining disasters sampled from the posterior predictive distribution
31,277
def expected_values ( early_mean = early_mean , late_mean = late_mean , switchpoint = switchpoint ) : n = len ( disasters_array ) return concatenate ( ( ones ( switchpoint ) * early_mean , ones ( n - switchpoint ) * late_mean ) )
Discrepancy measure for GOF using the Freeman - Tukey statistic
31,278
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 ) s...
Load a pickled database .
31,279
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
Dump traces using cPickle .
31,280
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 ) ] if first + last >= 1 : raise ValueErr...
Return z - scores for convergence diagnostics .
31,281
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==========...
Return the number of iterations needed to achieve a given precision .
31,282
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...
Returns estimate of the effective sample size of a set of traces .
31,283
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 ) ] B_over_n = np . sum ...
Returns estimate of R for a set of traces .
31,284
def _find_max_lag ( x , rho_limit = 0.05 , maxmaxlag = 20000 , verbose = 0 ) : acv = autocov ( x ) rho = acv [ 0 , 1 ] / acv [ 0 , 0 ] lam = - 1. / np . log ( abs ( rho ) ) maxlag = int ( np . floor ( 3. * lam ) ) + 1 jump = int ( np . ceil ( 0.01 * lam ) ) + 1 T = len ( x ) while ( ( abs ( rho ) > rho_limit ) & ( maxl...
Automatically find an appropriate maximum lag to calculate IAT
31,285
def ppp_value ( simdata , trueval , round = 3 ) : if ndim ( trueval ) == 1 and ndim ( simdata == 2 ) : return [ post_pred_checks ( simdata [ : , i ] , trueval [ i ] ) for i in range ( len ( trueval ) ) ] return ( simdata > trueval ) . mean ( )
Calculates posterior predictive p - values on data simulated from the posterior predictive distribution returning the quantile of the observed data relative to simulated .
31,286
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__ )
Check that the names of the objects are all different .
31,287
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
Seed new initial values for the stochastics .
31,288
def get_node ( self , node_name ) : for node in self . nodes : if node . __name__ == node_name : return node
Retrieve node with passed name
31,289
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 ( ) self . db . connect_model ( self ) if length is None : length = iter self . db . _initialize ( self . _funs_to_tally , length ) for v in...
Draws iter samples from the posterior .
31,290
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 ( )
Reset the status and tell the database to finalize the traces .
31,291
def stats ( self , variables = None , alpha = 0.05 , start = 0 , batches = 100 , chain = None , quantiles = ( 2.5 , 25 , 50 , 75 , 97.5 ) ) : if variables is None : variables = self . _variables_to_tally else : variables = [ v for v in self . variables if v . __name__ in variables ] stat_dict = { } for variable in vari...
Statistical output for variables .
31,292
def write_csv ( self , filename , variables = None , alpha = 0.05 , start = 0 , batches = 100 , chain = None , quantiles = ( 2.5 , 25 , 50 , 75 , 97.5 ) ) : if filename . find ( '.' ) == - 1 : filename += '.csv' outfile = open ( filename , 'w' ) header = 'Parameter, Mean, SD, MC Error, Lower 95% HPD, Upper 95% HPD, ' h...
Save summary statistics to a csv table .
31,293
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 ] ) + ', ' iindex = [ key . split ...
Support function for write_csv
31,294
def summary ( self , variables = None , alpha = 0.05 , start = 0 , batches = 100 , chain = None , roundto = 3 ) : 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 ] for variable in variables...
Generate a pretty - printed summary of the model s variables .
31,295
def _assign_database_backend ( self , db ) : 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 : self . _funs_to_tally [ object ....
Assign Trace instance to stochastics and deterministics and Database instance to self .
31,296
def pause ( self ) : self . status = 'paused' if hasattr ( self , '_sampling_thread' ) and self . _sampling_thread . isAlive ( ) : print_ ( 'Waiting for current iteration to finish...' ) while self . _sampling_thread . isAlive ( ) : sleep ( .1 )
Pause the sampler . Sampling can be resumed by calling icontinue .
31,297
def halt ( self ) : self . status = 'halt' if hasattr ( self , '_sampling_thread' ) and self . _sampling_thread . isAlive ( ) : print_ ( 'Waiting for current iteration to finish...' ) while self . _sampling_thread . isAlive ( ) : sleep ( .1 )
Halt a sampling running in another thread .
31,298
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 ,...
Samples in interactive mode . Main thread of control stays in this function .
31,299
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_thr...
Restarts thread in interactive mode