idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
232,800 | def connection_args ( * lst , ** mapping ) : pd = ArgDict ( * lst , ** mapping ) pd . setdefault ( 'after' , String ) pd . setdefault ( 'before' , String ) pd . setdefault ( 'first' , Int ) pd . setdefault ( 'last' , Int ) return pd | Returns the default parameters for connection . |
232,801 | def msjd ( theta ) : s = 0. for p in theta . dtype . names : s += np . sum ( np . diff ( theta [ p ] , axis = 0 ) ** 2 ) return s | Mean squared jumping distance . |
232,802 | def loglik ( self , theta , t = None ) : if t is None : t = self . T - 1 l = np . zeros ( shape = theta . shape [ 0 ] ) for s in range ( t + 1 ) : l += self . logpyt ( theta , s ) return l | log - likelihood at given parameter values . |
232,803 | def logpost ( self , theta , t = None ) : return self . prior . logpdf ( theta ) + self . loglik ( theta , t ) | Posterior log - density at given parameter values . |
232,804 | def copyto ( self , src , where = None ) : for n , _ in enumerate ( self . l ) : if where [ n ] : self . l [ n ] = src . l [ n ] | Same syntax and functionality as numpy . copyto |
232,805 | def copy ( self ) : attrs = { k : self . __dict__ [ k ] . copy ( ) for k in self . containers } attrs . update ( { k : cp . deepcopy ( self . __dict__ [ k ] ) for k in self . shared } ) return self . __class__ ( ** attrs ) | Returns a copy of the object . |
232,806 | def copyto ( self , src , where = None ) : for k in self . containers : v = self . __dict__ [ k ] if isinstance ( v , np . ndarray ) : np . copyto ( v , src . __dict__ [ k ] , where = where ) else : v . copyto ( src . __dict__ [ k ] , where = where ) | Emulates function copyto in NumPy . |
232,807 | def copyto_at ( self , n , src , m ) : for k in self . containers : self . __dict__ [ k ] [ n ] = src . __dict__ [ k ] [ m ] | Copy to at a given location . |
232,808 | def Metropolis ( self , compute_target , mh_options ) : opts = mh_options . copy ( ) nsteps = opts . pop ( 'nsteps' , 0 ) delta_dist = opts . pop ( 'delta_dist' , 0.1 ) proposal = self . choose_proposal ( ** opts ) xout = self . copy ( ) xp = self . __class__ ( theta = np . empty_like ( self . theta ) ) step_ars = [ ] ... | Performs a certain number of Metropolis steps . |
232,809 | def backward ( self ) : if not self . filt : self . forward ( ) self . smth = [ self . filt [ - 1 ] ] log_trans = np . log ( self . hmm . trans_mat ) ctg = np . zeros ( self . hmm . dim ) for filt , next_ft in reversed ( list ( zip ( self . filt [ : - 1 ] , self . logft [ 1 : ] ) ) ) : new_ctg = np . empty ( self . hmm... | Backward recursion . |
232,810 | def predict_step ( F , covX , filt ) : pred_mean = np . matmul ( filt . mean , F . T ) pred_cov = dotdot ( F , filt . cov , F . T ) + covX return MeanAndCov ( mean = pred_mean , cov = pred_cov ) | Predictive step of Kalman filter . |
232,811 | def filter_step ( G , covY , pred , yt ) : data_pred_mean = np . matmul ( pred . mean , G . T ) data_pred_cov = dotdot ( G , pred . cov , G . T ) + covY if covY . shape [ 0 ] == 1 : logpyt = dists . Normal ( loc = data_pred_mean , scale = np . sqrt ( data_pred_cov ) ) . logpdf ( yt ) else : logpyt = dists . MvNormal ( ... | Filtering step of Kalman filter . |
232,812 | def check_shapes ( self ) : assert self . covX . shape == ( self . dx , self . dx ) , error_msg assert self . covY . shape == ( self . dy , self . dy ) , error_msg assert self . F . shape == ( self . dx , self . dx ) , error_msg assert self . G . shape == ( self . dy , self . dx ) , error_msg assert self . mu0 . shape ... | Check all dimensions are correct . |
232,813 | def sobol ( N , dim , scrambled = 1 ) : while ( True ) : seed = np . random . randint ( 2 ** 32 ) out = lowdiscrepancy . sobol ( N , dim , scrambled , seed , 1 , 0 ) if ( scrambled == 0 ) or ( ( out < 1. ) . all ( ) and ( out > 0. ) . all ( ) ) : return out | Sobol sequence . |
232,814 | def smoothing_worker ( method = None , N = 100 , seed = None , fk = None , fk_info = None , add_func = None , log_gamma = None ) : T = fk . T if fk_info is None : fk_info = fk . __class__ ( ssm = fk . ssm , data = fk . data [ : : - 1 ] ) if seed : random . seed ( seed ) est = np . zeros ( T - 1 ) if method == 'FFBS_QMC... | Generic worker for off - line smoothing algorithms . |
232,815 | def save ( self , X = None , w = None , A = None ) : self . X . append ( X ) self . wgt . append ( w ) self . A . append ( A ) | Save one page of history at a given time . |
232,816 | def extract_one_trajectory ( self ) : traj = [ ] for t in reversed ( range ( self . T ) ) : if t == self . T - 1 : n = rs . multinomial_once ( self . wgt [ - 1 ] . W ) else : n = self . A [ t + 1 ] [ n ] traj . append ( self . X [ t ] [ n ] ) return traj [ : : - 1 ] | Extract a single trajectory from the particle history . |
232,817 | def compute_trajectories ( self ) : self . B = np . empty ( ( self . T , self . N ) , 'int' ) self . B [ - 1 , : ] = self . A [ - 1 ] for t in reversed ( range ( self . T - 1 ) ) : self . B [ t , : ] = self . A [ t + 1 ] [ self . B [ t + 1 ] ] | Compute the N trajectories that constitute the current genealogy . |
232,818 | def twofilter_smoothing ( self , t , info , phi , loggamma , linear_cost = False , return_ess = False , modif_forward = None , modif_info = None ) : ti = self . T - 2 - t if t < 0 or t >= self . T - 1 : raise ValueError ( 'two-filter smoothing: t must be in range 0,...,T-2' ) lwinfo = info . hist . wgt [ ti ] . lw - lo... | Two - filter smoothing . |
232,819 | def multiSMC ( nruns = 10 , nprocs = 0 , out_func = None , ** args ) : def f ( ** args ) : pf = SMC ( ** args ) pf . run ( ) return out_func ( pf ) if out_func is None : out_func = lambda x : x return utils . multiplexer ( f = f , nruns = nruns , nprocs = nprocs , seeding = True , ** args ) | Run SMC algorithms in parallel for different combinations of parameters . |
232,820 | def reset_weights ( self ) : if self . fk . isAPF : lw = ( rs . log_mean_exp ( self . logetat , W = self . W ) - self . logetat [ self . A ] ) self . wgts = rs . Weights ( lw = lw ) else : self . wgts = rs . Weights ( ) | Reset weights after a resampling step . |
232,821 | def log_sum_exp ( v ) : m = v . max ( ) return m + np . log ( np . sum ( np . exp ( v - m ) ) ) | Log of the sum of the exp of the arguments . |
232,822 | def log_sum_exp_ab ( a , b ) : if a > b : return a + np . log ( 1. + np . exp ( b - a ) ) else : return b + np . log ( 1. + np . exp ( a - b ) ) | log_sum_exp for two scalars . |
232,823 | def wmean_and_var ( W , x ) : m = np . average ( x , weights = W , axis = 0 ) m2 = np . average ( x ** 2 , weights = W , axis = 0 ) v = m2 - m ** 2 return { 'mean' : m , 'var' : v } | Component - wise weighted mean and variance . |
232,824 | def wmean_and_var_str_array ( W , x ) : m = np . empty ( shape = x . shape [ 1 : ] , dtype = x . dtype ) v = np . empty_like ( m ) for p in x . dtype . names : m [ p ] , v [ p ] = wmean_and_var ( W , x [ p ] ) . values ( ) return { 'mean' : m , 'var' : v } | Weighted mean and variance of each component of a structured array . |
232,825 | def wquantiles ( W , x , alphas = ( 0.25 , 0.50 , 0.75 ) ) : if len ( x . shape ) == 1 : return _wquantiles ( W , x , alphas = alphas ) elif len ( x . shape ) == 2 : return np . array ( [ _wquantiles ( W , x [ : , i ] , alphas = alphas ) for i in range ( x . shape [ 1 ] ) ] ) | Quantiles for weighted data . |
232,826 | def wquantiles_str_array ( W , x , alphas = ( 0.25 , 0.50 , 0 , 75 ) ) : return { p : wquantiles ( W , x [ p ] , alphas ) for p in x . dtype . names } | quantiles for weighted data stored in a structured array . |
232,827 | def resampling_scheme ( func ) : @ functools . wraps ( func ) def modif_func ( W , M = None ) : M = W . shape [ 0 ] if M is None else M return func ( W , M ) rs_funcs [ func . __name__ ] = modif_func modif_func . __doc__ = rs_doc % func . __name__ . capitalize ( ) return modif_func | Decorator for resampling schemes . |
232,828 | def inverse_cdf ( su , W ) : j = 0 s = W [ 0 ] M = su . shape [ 0 ] A = np . empty ( M , 'int' ) for n in range ( M ) : while su [ n ] > s : j += 1 s += W [ j ] A [ n ] = j return A | Inverse CDF algorithm for a finite distribution . |
232,829 | def hilbert_array ( xint ) : N , d = xint . shape h = np . zeros ( N , int64 ) for n in range ( N ) : h [ n ] = Hilbert_to_int ( xint [ n , : ] ) return h | Compute Hilbert indices . |
232,830 | def mean_sq_jump_dist ( self , discard_frac = 0.1 ) : discard = int ( self . niter * discard_frac ) return msjd ( self . chain . theta [ discard : ] ) | Mean squared jumping distance estimated from chain . |
232,831 | def update ( self , v ) : self . t += 1 g = self . gamma ( ) self . mu = ( 1. - g ) * self . mu + g * v mv = v - self . mu self . Sigma = ( ( 1. - g ) * self . Sigma + g * np . dot ( mv [ : , np . newaxis ] , mv [ np . newaxis , : ] ) ) try : self . L = cholesky ( self . Sigma , lower = True ) except LinAlgError : self... | Adds point v |
232,832 | def cartesian_lists ( d ) : return [ { k : v for k , v in zip ( d . keys ( ) , args ) } for args in itertools . product ( * d . values ( ) ) ] | turns a dict of lists into a list of dicts that represents the cartesian product of the initial lists |
232,833 | def cartesian_args ( args , listargs , dictargs ) : ils = { k : [ v , ] for k , v in args . items ( ) } ils . update ( listargs ) ils . update ( { k : v . values ( ) for k , v in dictargs . items ( ) } ) ols = listargs . copy ( ) ols . update ( { k : v . keys ( ) for k , v in dictargs . items ( ) } ) return cartesian_l... | Compute a list of inputs and outputs for a function with kw arguments . |
232,834 | def worker ( qin , qout , f ) : while not qin . empty ( ) : i , args = qin . get ( ) qout . put ( ( i , f ( ** args ) ) ) | Worker for muliprocessing . A worker repeatedly picks a dict of arguments in the queue and computes f for this set of arguments until the input queue is empty . |
232,835 | def distinct_seeds ( k ) : seeds = [ ] for _ in range ( k ) : while True : s = random . randint ( 2 ** 32 - 1 ) if s not in seeds : break seeds . append ( s ) return seeds | returns k distinct seeds for random number generation |
232,836 | def multiplexer ( f = None , nruns = 1 , nprocs = 1 , seeding = None , ** args ) : if not callable ( f ) : raise ValueError ( 'multiplexer: function f missing, or not callable' ) if seeding is None : seeding = ( nruns > 1 ) fixedargs , listargs , dictargs = { } , { } , { } listargs [ 'run' ] = list ( range ( nruns ) ) ... | Evaluate a function for different parameters optionally in parallel . |
232,837 | def simulate ( self , T ) : x = [ ] for t in range ( T ) : law_x = self . PX0 ( ) if t == 0 else self . PX ( t , x [ - 1 ] ) x . append ( law_x . rvs ( size = 1 ) ) y = self . simulate_given_x ( x ) return x , y | Simulate state and observation processes . |
232,838 | def interpoled_resampling ( W , x ) : N = W . shape [ 0 ] idx = np . argsort ( x ) xs = x [ idx ] ws = W [ idx ] cs = np . cumsum ( avg_n_nplusone ( ws ) ) u = random . rand ( N ) xrs = np . empty ( N ) where = np . searchsorted ( cs , u ) for n in range ( N ) : m = where [ n ] if m == 0 : xrs [ n ] = xs [ 0 ] elif m =... | Resampling based on an interpolated CDF as described in Malik and Pitt . |
232,839 | def sort_items ( self , items , args = False ) : if self . settings [ 'sort' ] . lower ( ) == 'src' : return def alpha ( i ) : return i . name def permission ( i ) : if args : if i . intent == 'in' : return 'b' if i . intent == 'inout' : return 'c' if i . intent == 'out' : return 'd' if i . intent == '' : return 'e' pe... | Sort the self s contents as contained in the list items as specified in self s meta - data . |
232,840 | def contents_size ( self ) : count = 0 if hasattr ( self , 'variables' ) : count += 1 if hasattr ( self , 'types' ) : count += 1 if hasattr ( self , 'modules' ) : count += 1 if hasattr ( self , 'submodules' ) : count += 1 if hasattr ( self , 'subroutines' ) : count += 1 if hasattr ( self , 'modprocedures' ) : count += ... | Returns the number of different categories to be shown in the contents side - bar in the HTML documentation . |
232,841 | def sort ( self ) : if hasattr ( self , 'variables' ) : sort_items ( self , self . variables ) if hasattr ( self , 'modules' ) : sort_items ( self , self . modules ) if hasattr ( self , 'submodules' ) : sort_items ( self , self . submodules ) if hasattr ( self , 'common' ) : sort_items ( self , self . common ) if hasat... | Sorts components of the object . |
232,842 | def make_links ( self , project ) : self . doc = ford . utils . sub_links ( self . doc , project ) if 'summary' in self . meta : self . meta [ 'summary' ] = ford . utils . sub_links ( self . meta [ 'summary' ] , project ) for item in self . iterator ( 'variables' , 'types' , 'enums' , 'modules' , 'submodules' , 'subrou... | Process intra - site links to documentation of other parts of the program . |
232,843 | def iterator ( self , * argv ) : for arg in argv : if hasattr ( self , arg ) : for item in getattr ( self , arg ) : yield item | Iterator returning any list of elements via attribute lookup in self |
232,844 | def get_used_entities ( self , use_specs ) : if len ( use_specs . strip ( ) ) == 0 : return ( self . pub_procs , self . pub_absints , self . pub_types , self . pub_vars ) only = bool ( self . ONLY_RE . match ( use_specs ) ) use_specs = self . ONLY_RE . sub ( '' , use_specs ) ulist = self . SPLIT_RE . split ( use_specs ... | Returns the entities which are imported by a use statement . These are contained in dicts . |
232,845 | def get_name ( self , item ) : if not isinstance ( item , ford . sourceform . FortranBase ) : raise Exception ( '{} is not of a type derived from FortranBase' . format ( str ( item ) ) ) if item in self . _items : return self . _items [ item ] else : if item . get_dir ( ) not in self . _counts : self . _counts [ item .... | Return the name for this item registered with this NameSelector . If no name has previously been registered then generate a new one . |
232,846 | def main ( proj_data , proj_docs , md ) : if proj_data [ 'relative' ] : proj_data [ 'project_url' ] = '.' project = ford . fortran_project . Project ( proj_data ) if len ( project . files ) < 1 : print ( "Error: No source files with appropriate extension found in specified directory." ) sys . exit ( 1 ) if proj_data [ ... | Main driver of FORD . |
232,847 | def convertToFree ( stream , length_limit = True ) : linestack = [ ] for line in stream : convline = FortranLine ( line , length_limit ) if convline . is_regular : if convline . isContinuation and linestack : linestack [ 0 ] . continueLine ( ) for l in linestack : yield str ( l ) linestack = [ ] linestack . append ( co... | Convert stream from fixed source form to free source form . |
232,848 | def continueLine ( self ) : if not ( self . isLong and self . is_regular ) : self . line_conv = self . line_conv . rstrip ( ) + " &\n" else : temp = self . line_conv [ : 72 ] . rstrip ( ) + " &" self . line_conv = temp . ljust ( 72 ) + self . excess_line | Insert line continuation symbol at end of line . |
232,849 | def id_mods ( obj , modlist , intrinsic_mods = { } , submodlist = [ ] ) : for i in range ( len ( obj . uses ) ) : for candidate in modlist : if obj . uses [ i ] [ 0 ] . lower ( ) == candidate . name . lower ( ) : obj . uses [ i ] = [ candidate , obj . uses [ i ] [ 1 ] ] break else : if obj . uses [ i ] [ 0 ] . lower ( ... | Match USE statements up with the right modules |
232,850 | def allfiles ( self ) : for f in self . files : yield f for f in self . extra_files : yield f | Instead of duplicating files it is much more efficient to create the itterator on the fly |
232,851 | def make_links ( self , base_url = '..' ) : ford . sourceform . set_base_url ( base_url ) for src in self . allfiles : src . make_links ( self ) | Substitute intrasite links to documentation for other parts of the program . |
232,852 | def sub_notes ( docs ) : def substitute ( match ) : ret = "</p><div class=\"alert alert-{}\" role=\"alert\"><h4>{}</h4>" "<p>{}</p></div>" . format ( NOTE_TYPE [ match . group ( 1 ) . lower ( ) ] , match . group ( 1 ) . capitalize ( ) , match . group ( 2 ) ) if len ( match . groups ( ) ) >= 4 and not match . group ( 4 ... | Substitutes the special controls for notes warnings todos and bugs with the corresponding div . |
232,853 | def paren_split ( sep , string ) : if len ( sep ) != 1 : raise Exception ( "Separation string must be one character long" ) retlist = [ ] level = 0 blevel = 0 left = 0 for i in range ( len ( string ) ) : if string [ i ] == "(" : level += 1 elif string [ i ] == ")" : level -= 1 elif string [ i ] == "[" : blevel += 1 eli... | Splits the string into pieces divided by sep when sep is outside of parentheses . |
232,854 | def quote_split ( sep , string ) : if len ( sep ) != 1 : raise Exception ( "Separation string must be one character long" ) retlist = [ ] squote = False dquote = False left = 0 i = 0 while i < len ( string ) : if string [ i ] == '"' and not dquote : if not squote : squote = True elif ( i + 1 ) < len ( string ) and stri... | Splits the strings into pieces divided by sep when sep in not inside quotes . |
232,855 | def split_path ( path ) : def recurse_path ( path , retlist ) : if len ( retlist ) > 100 : fullpath = os . path . join ( * ( [ path , ] + retlist ) ) print ( "Directory '{}' contains too many levels" . format ( fullpath ) ) exit ( 1 ) head , tail = os . path . split ( path ) if len ( tail ) > 0 : retlist . insert ( 0 ,... | Splits the argument into its constituent directories and returns them as a list . |
232,856 | def sub_macros ( string , base_url ) : macros = { '|url|' : base_url , '|media|' : os . path . join ( base_url , 'media' ) , '|page|' : os . path . join ( base_url , 'page' ) } for key , val in macros . items ( ) : string = string . replace ( key , val ) return string | Replaces macros in documentation with their appropriate values . These macros are used for things like providing URLs . |
232,857 | def copytree ( src , dst ) : def touch ( path ) : now = time . time ( ) try : os . utime ( path , ( now , now ) ) except os . error : os . makedirs ( os . path . dirname ( path ) ) open ( path , "w" ) . close ( ) os . utime ( path , ( now , now ) ) for root , dirs , files in os . walk ( src ) : relsrcdir = os . path . ... | Replaces shutil . copytree to avoid problems on certain file systems . |
232,858 | def export_hmaps_csv ( key , dest , sitemesh , array , comment ) : curves = util . compose_arrays ( sitemesh , array ) writers . write_csv ( dest , curves , comment = comment ) return [ dest ] | Export the hazard maps of the given realization into CSV . |
232,859 | def export_hcurves_by_imt_csv ( key , kind , rlzs_assoc , fname , sitecol , array , oq , checksum ) : nsites = len ( sitecol ) fnames = [ ] for imt , imls in oq . imtls . items ( ) : slc = oq . imtls ( imt ) dest = add_imt ( fname , imt ) lst = [ ( 'lon' , F32 ) , ( 'lat' , F32 ) , ( 'depth' , F32 ) ] for iml in imls :... | Export the curves of the given realization into CSV . |
232,860 | def export_hcurves_csv ( ekey , dstore ) : oq = dstore [ 'oqparam' ] info = get_info ( dstore ) rlzs_assoc = dstore [ 'csm_info' ] . get_rlzs_assoc ( ) R = len ( rlzs_assoc . realizations ) sitecol = dstore [ 'sitecol' ] sitemesh = get_mesh ( sitecol ) key , kind , fmt = get_kkf ( ekey ) fnames = [ ] checksum = dstore ... | Exports the hazard curves into several . csv files |
232,861 | def save_disagg_to_csv ( metadata , matrices ) : skip_keys = ( 'Mag' , 'Dist' , 'Lon' , 'Lat' , 'Eps' , 'TRT' ) base_header = ',' . join ( '%s=%s' % ( key , value ) for key , value in metadata . items ( ) if value is not None and key not in skip_keys ) for disag_tup , ( poe , iml , matrix , fname ) in matrices . items ... | Save disaggregation matrices to multiple . csv files . |
232,862 | def _interp_function ( self , y_ip1 , y_i , t_ip1 , t_i , imt_per ) : return y_i + ( y_ip1 - y_i ) / ( t_ip1 - t_i ) * ( imt_per - t_i ) | Generic interpolation function used in equation 19 of 2013 report . |
232,863 | def _get_SRF_tau ( self , imt_per ) : if imt_per < 1 : srf = 0.87 elif 1 <= imt_per < 5 : srf = self . _interp_function ( 0.58 , 0.87 , 5 , 1 , imt_per ) elif 5 <= imt_per <= 10 : srf = 0.58 else : srf = 1 return srf | Table 6 and equation 19 of 2013 report . |
232,864 | def _get_SRF_phi ( self , imt_per ) : if imt_per < 0.6 : srf = 0.8 elif 0.6 <= imt_per < 1 : srf = self . _interp_function ( 0.7 , 0.8 , 1 , 0.6 , imt_per ) elif 1 <= imt_per <= 10 : srf = self . _interp_function ( 0.6 , 0.7 , 10 , 1 , imt_per ) else : srf = 1 return srf | Table 7 and equation 19 of 2013 report . NB change in notation 2013 report calls this term sigma but it is referred to here as phi . |
232,865 | def _get_SRF_sigma ( self , imt_per ) : if imt_per < 0.6 : srf = 0.8 elif 0.6 <= imt_per < 1 : srf = self . _interp_function ( 0.7 , 0.8 , 1 , 0.6 , imt_per ) elif 1 <= imt_per <= 10 : srf = self . _interp_function ( 0.6 , 0.7 , 10 , 1 , imt_per ) else : srf = 1 return srf | Table 8 and equation 19 of 2013 report . NB change in notation 2013 report calls this term sigma_t but it is referred to here as sigma . Note that Table 8 is identical to Table 7 in the 2013 report . |
232,866 | def _get_dL2L ( self , imt_per ) : if imt_per < 0.18 : dL2L = - 0.06 elif 0.18 <= imt_per < 0.35 : dL2L = self . _interp_function ( 0.12 , - 0.06 , 0.35 , 0.18 , imt_per ) elif 0.35 <= imt_per <= 10 : dL2L = self . _interp_function ( 0.65 , 0.12 , 10 , 0.35 , imt_per ) else : dL2L = 0 return dL2L | Table 3 and equation 19 of 2013 report . |
232,867 | def _get_dS2S ( self , imt_per ) : if imt_per == 0 : dS2S = 0.05 elif 0 < imt_per < 0.15 : dS2S = self . _interp_function ( - 0.15 , 0.05 , 0.15 , 0 , imt_per ) elif 0.15 <= imt_per < 0.45 : dS2S = self . _interp_function ( 0.4 , - 0.15 , 0.45 , 0.15 , imt_per ) elif 0.45 <= imt_per < 3.2 : dS2S = 0.4 elif 3.2 <= imt_p... | Table 4 of 2013 report |
232,868 | def context ( src ) : try : yield except Exception : etype , err , tb = sys . exc_info ( ) msg = 'An error occurred with source id=%s. Error: %s' msg %= ( src . source_id , err ) raise_ ( etype , msg , tb ) | Used to add the source_id to the error message . To be used as |
232,869 | def get_bounding_box ( self , lon , lat , trt = None , mag = None ) : if trt is None : maxdist = max ( self ( trt , mag ) for trt in self . dic ) else : maxdist = self ( trt , mag ) a1 = min ( maxdist * KM_TO_DEGREES , 90 ) a2 = min ( angular_distance ( maxdist , lat ) , 180 ) return lon - a2 , lat - a1 , lon + a2 , la... | Build a bounding box around the given lon lat by computing the maximum_distance at the given tectonic region type and magnitude . |
232,870 | def get_affected_box ( self , src ) : mag = src . get_min_max_mag ( ) [ 1 ] maxdist = self ( src . tectonic_region_type , mag ) bbox = get_bounding_box ( src , maxdist ) return ( fix_lon ( bbox [ 0 ] ) , bbox [ 1 ] , fix_lon ( bbox [ 2 ] ) , bbox [ 3 ] ) | Get the enlarged bounding box of a source . |
232,871 | def sitecol ( self ) : if 'sitecol' in vars ( self ) : return self . __dict__ [ 'sitecol' ] if self . filename is None or not os . path . exists ( self . filename ) : return with hdf5 . File ( self . filename , 'r' ) as h5 : self . __dict__ [ 'sitecol' ] = sc = h5 . get ( 'sitecol' ) return sc | Read the site collection from . filename and cache it |
232,872 | def hypocentre_patch_index ( cls , hypocentre , rupture_top_edge , upper_seismogenic_depth , lower_seismogenic_depth , dip ) : totaln_patch = len ( rupture_top_edge ) indexlist = [ ] dist_list = [ ] for i , index in enumerate ( range ( 1 , totaln_patch ) ) : p0 , p1 , p2 , p3 = cls . get_fault_patch_vertices ( rupture_... | This methods finds the index of the fault patch including the hypocentre . |
232,873 | def get_surface_vertexes ( cls , fault_trace , upper_seismogenic_depth , lower_seismogenic_depth , dip ) : dip_tan = math . tan ( math . radians ( dip ) ) hdist_top = upper_seismogenic_depth / dip_tan hdist_bottom = lower_seismogenic_depth / dip_tan strike = fault_trace [ 0 ] . azimuth ( fault_trace [ - 1 ] ) azimuth =... | Get surface main vertexes . |
232,874 | def surface_projection_from_fault_data ( cls , fault_trace , upper_seismogenic_depth , lower_seismogenic_depth , dip ) : lons , lats = cls . get_surface_vertexes ( fault_trace , upper_seismogenic_depth , lower_seismogenic_depth , dip ) return Mesh ( lons , lats , depths = None ) . get_convex_hull ( ) | Get a surface projection of the simple fault surface . |
232,875 | def _compute_distance_term ( self , C , mag , rrup ) : term1 = C [ 'b' ] * rrup term2 = - np . log ( rrup + C [ 'c' ] * np . exp ( C [ 'd' ] * mag ) ) return term1 + term2 | Compute second and third terms in equation 1 p . 901 . |
232,876 | def _compute_focal_depth_term ( self , C , hypo_depth ) : focal_depth = hypo_depth if focal_depth > 125.0 : focal_depth = 125.0 hc = 15.0 return float ( focal_depth >= hc ) * C [ 'e' ] * ( focal_depth - hc ) | Compute fourth term in equation 1 p . 901 . |
232,877 | def _compute_site_class_term ( self , C , vs30 ) : site_term = np . zeros ( len ( vs30 ) ) site_term [ vs30 > 1100.0 ] = C [ 'CH' ] site_term [ ( vs30 > 600 ) & ( vs30 <= 1100 ) ] = C [ 'C1' ] site_term [ ( vs30 > 300 ) & ( vs30 <= 600 ) ] = C [ 'C2' ] site_term [ ( vs30 > 200 ) & ( vs30 <= 300 ) ] = C [ 'C3' ] site_te... | Compute nine - th term in equation 1 p . 901 . |
232,878 | def _compute_magnitude_squared_term ( self , P , M , Q , W , mag ) : return P * ( mag - M ) + Q * ( mag - M ) ** 2 + W | Compute magnitude squared term equation 5 p . 909 . |
232,879 | def _compute_slab_correction_term ( self , C , rrup ) : slab_term = C [ 'SSL' ] * np . log ( rrup ) return slab_term | Compute path modification term for slab events that is the 8 - th term in equation 1 p . 901 . |
232,880 | def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) : dists_mod = copy . deepcopy ( dists ) dists_mod . rrup [ dists . rrup <= 5. ] = 5. return super ( ) . get_mean_and_stddevs ( sites , rup , dists_mod , imt , stddev_types ) | Using a minimum distance of 5km for the calculation . |
232,881 | def confirm ( prompt ) : while True : try : answer = input ( prompt ) except KeyboardInterrupt : return False answer = answer . strip ( ) . lower ( ) if answer not in ( 'y' , 'n' ) : print ( 'Please enter y or n' ) continue return answer == 'y' | Ask for confirmation given a prompt and return a boolean value . |
232,882 | def _csv_header ( self ) : fields = [ 'id' , 'number' , 'taxonomy' , 'lon' , 'lat' ] for name in self . cost_types [ 'name' ] : fields . append ( name ) if 'per_area' in self . cost_types [ 'type' ] : fields . append ( 'area' ) if self . occupancy_periods : fields . extend ( self . occupancy_periods . split ( ) ) field... | Extract the expected CSV header from the exposure metadata |
232,883 | def build_vf_node ( vf ) : nodes = [ Node ( 'imls' , { 'imt' : vf . imt } , vf . imls ) , Node ( 'meanLRs' , { } , vf . mean_loss_ratios ) , Node ( 'covLRs' , { } , vf . covs ) ] return Node ( 'vulnerabilityFunction' , { 'id' : vf . id , 'dist' : vf . distribution_name } , nodes = nodes ) | Convert a VulnerabilityFunction object into a Node suitable for XML conversion . |
232,884 | def get_riskmodel ( taxonomy , oqparam , ** extra ) : riskmodel_class = registry [ oqparam . calculation_mode ] argnames = inspect . getfullargspec ( riskmodel_class . __init__ ) . args [ 3 : ] known_args = set ( name for name , value in inspect . getmembers ( oqparam . __class__ ) if isinstance ( value , valid . Param... | Return an instance of the correct riskmodel class depending on the attribute calculation_mode of the object oqparam . |
232,885 | def Beachball ( fm , linewidth = 2 , facecolor = 'b' , bgcolor = 'w' , edgecolor = 'k' , alpha = 1.0 , xy = ( 0 , 0 ) , width = 200 , size = 100 , nofill = False , zorder = 100 , outfile = None , format = None , fig = None ) : plot_width = width * 0.95 if not fig : fig = plt . figure ( figsize = ( 3 , 3 ) , dpi = 100 )... | Draws a beach ball diagram of an earthquake focal mechanism . |
232,886 | def StrikeDip ( n , e , u ) : r2d = 180 / np . pi if u < 0 : n = - n e = - e u = - u strike = np . arctan2 ( e , n ) * r2d strike = strike - 90 while strike >= 360 : strike = strike - 360 while strike < 0 : strike = strike + 360 x = np . sqrt ( np . power ( n , 2 ) + np . power ( e , 2 ) ) dip = np . arctan2 ( x , u ) ... | Finds strike and dip of plane given normal vector having components n e and u . |
232,887 | def AuxPlane ( s1 , d1 , r1 ) : r2d = 180 / np . pi z = ( s1 + 90 ) / r2d z2 = d1 / r2d z3 = r1 / r2d sl1 = - np . cos ( z3 ) * np . cos ( z ) - np . sin ( z3 ) * np . sin ( z ) * np . cos ( z2 ) sl2 = np . cos ( z3 ) * np . sin ( z ) - np . sin ( z3 ) * np . cos ( z ) * np . cos ( z2 ) sl3 = np . sin ( z3 ) * np . sin... | Get Strike and dip of second plane . |
232,888 | def MT2Plane ( mt ) : ( d , v ) = np . linalg . eig ( mt . mt ) D = np . array ( [ d [ 1 ] , d [ 0 ] , d [ 2 ] ] ) V = np . array ( [ [ v [ 1 , 1 ] , - v [ 1 , 0 ] , - v [ 1 , 2 ] ] , [ v [ 2 , 1 ] , - v [ 2 , 0 ] , - v [ 2 , 2 ] ] , [ - v [ 0 , 1 ] , v [ 0 , 0 ] , v [ 0 , 2 ] ] ] ) IMAX = D . argmax ( ) IMIN = D . arg... | Calculates a nodal plane of a given moment tensor . |
232,889 | def TDL ( AN , BN ) : XN = AN [ 0 ] YN = AN [ 1 ] ZN = AN [ 2 ] XE = BN [ 0 ] YE = BN [ 1 ] ZE = BN [ 2 ] AAA = 1.0 / ( 1000000 ) CON = 57.2957795 if np . fabs ( ZN ) < AAA : FD = 90. AXN = np . fabs ( XN ) if AXN > 1.0 : AXN = 1.0 FT = np . arcsin ( AXN ) * CON ST = - XN CT = YN if ST >= 0. and CT < 0 : FT = 180. - FT... | Helper function for MT2Plane . |
232,890 | def MT2Axes ( mt ) : ( D , V ) = np . linalg . eigh ( mt . mt ) pl = np . arcsin ( - V [ 0 ] ) az = np . arctan2 ( V [ 2 ] , - V [ 1 ] ) for i in range ( 0 , 3 ) : if pl [ i ] <= 0 : pl [ i ] = - pl [ i ] az [ i ] += np . pi if az [ i ] < 0 : az [ i ] += 2 * np . pi if az [ i ] > 2 * np . pi : az [ i ] -= 2 * np . pi p... | Calculates the principal axes of a given moment tensor . |
232,891 | def tapered_gutenberg_richter_cdf ( moment , moment_threshold , beta , corner_moment ) : cdf = np . exp ( ( moment_threshold - moment ) / corner_moment ) return ( ( moment / moment_threshold ) ** ( - beta ) ) * cdf | Tapered Gutenberg Richter Cumulative Density Function |
232,892 | def tapered_gutenberg_richter_pdf ( moment , moment_threshold , beta , corner_moment ) : return ( ( beta / moment + 1. / corner_moment ) * tapered_gutenberg_richter_cdf ( moment , moment_threshold , beta , corner_moment ) ) | Tapered Gutenberg - Richter Probability Density Function |
232,893 | def makedirs ( path ) : if os . path . exists ( path ) : if not os . path . isdir ( path ) : raise RuntimeError ( '%s already exists and is not a directory.' % path ) else : os . makedirs ( path ) | Make all of the directories in the path using os . makedirs . |
232,894 | def _get_observed_mmax ( catalogue , config ) : if config [ 'input_mmax' ] : obsmax = config [ 'input_mmax' ] if config [ 'input_mmax_uncertainty' ] : return config [ 'input_mmax' ] , config [ 'input_mmax_uncertainty' ] else : raise ValueError ( 'Input mmax uncertainty must be specified!' ) max_location = np . argmax (... | Check see if observed mmax values are input if not then take from the catalogue |
232,895 | def _get_magnitude_vector_properties ( catalogue , config ) : mmin = config . get ( 'input_mmin' , np . min ( catalogue [ 'magnitude' ] ) ) neq = np . float ( np . sum ( catalogue [ 'magnitude' ] >= mmin - 1.E-7 ) ) return neq , mmin | If an input minimum magnitude is given then consider catalogue only above the minimum magnitude - returns corresponding properties |
232,896 | def get_dip ( self ) : if self . dip is None : mesh = self . mesh self . dip , self . strike = mesh . get_mean_inclination_and_azimuth ( ) return self . dip | Return the fault dip as the average dip over the mesh . |
232,897 | def check_surface_validity ( cls , edges ) : full_boundary = [ ] left_boundary = [ ] right_boundary = [ ] for i in range ( 1 , len ( edges ) - 1 ) : left_boundary . append ( edges [ i ] . points [ 0 ] ) right_boundary . append ( edges [ i ] . points [ - 1 ] ) full_boundary . extend ( edges [ 0 ] . points ) full_boundar... | Check validity of the surface . |
232,898 | def surface_projection_from_fault_data ( cls , edges ) : lons = [ ] lats = [ ] for edge in edges : for point in edge : lons . append ( point . longitude ) lats . append ( point . latitude ) lons = numpy . array ( lons , dtype = float ) lats = numpy . array ( lats , dtype = float ) return Mesh ( lons , lats , depths = N... | Get a surface projection of the complex fault surface . |
232,899 | def check_time_event ( oqparam , occupancy_periods ) : time_event = oqparam . time_event if time_event and time_event not in occupancy_periods : raise ValueError ( 'time_event is %s in %s, but the exposure contains %s' % ( time_event , oqparam . inputs [ 'job_ini' ] , ', ' . join ( occupancy_periods ) ) ) | Check the time_event parameter in the datastore by comparing with the periods found in the exposure . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.