idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
233,400 | def webui ( cmd , hostport = '127.0.0.1:8800' , skip_browser = False ) : dbpath = os . path . realpath ( os . path . expanduser ( config . dbserver . file ) ) if os . path . isfile ( dbpath ) and not os . access ( dbpath , os . W_OK ) : sys . exit ( 'This command must be run by the proper user: ' 'see the documentation... | start the webui server in foreground or perform other operation on the django application |
233,401 | def _get_basic_term ( self , C , rup , dists ) : if rup . mag > 5. : c4m = C [ 'c4' ] elif rup . mag > 4. : c4m = C [ 'c4' ] - ( C [ 'c4' ] - 1. ) * ( 5. - rup . mag ) else : c4m = 1. R = np . sqrt ( dists . rrup ** 2. + c4m ** 2. ) base_term = C [ 'a1' ] * np . ones_like ( dists . rrup ) + C [ 'a17' ] * dists . rrup i... | Compute and return basic form see page 1030 . |
233,402 | def _get_vs30star ( self , vs30 , imt ) : if imt . name == "SA" : t = imt . period if t <= 0.50 : v1 = 1500.0 elif t < 3.0 : v1 = np . exp ( - 0.35 * np . log ( t / 0.5 ) + np . log ( 1500. ) ) else : v1 = 800.0 elif imt . name == "PGA" : v1 = 1500.0 else : v1 = 1500.0 vs30_star = np . ones_like ( vs30 ) * vs30 vs30_st... | This computes equations 8 and 9 at page 1034 |
233,403 | def _get_site_response_term ( self , C , imt , vs30 , sa1180 ) : vs30_star = self . _get_vs30star ( vs30 , imt ) site_resp_term = np . zeros_like ( vs30 ) gt_vlin = vs30 >= C [ 'vlin' ] lw_vlin = vs30 < C [ 'vlin' ] vs30_rat = vs30_star / C [ 'vlin' ] site_resp_term [ gt_vlin ] = ( ( C [ 'a10' ] + C [ 'b' ] * self . CO... | Compute and return site response model term see page 1033 |
233,404 | def _get_hanging_wall_term ( self , C , dists , rup ) : if rup . dip == 90.0 : return np . zeros_like ( dists . rx ) else : Fhw = np . zeros_like ( dists . rx ) Fhw [ dists . rx > 0 ] = 1. T1 = np . ones_like ( dists . rx ) T1 *= 60. / 45. if rup . dip <= 30. else ( 90. - rup . dip ) / 45.0 T2 = np . zeros_like ( dists... | Compute and return hanging wall model term see page 1038 . |
233,405 | def _get_top_of_rupture_depth_term ( self , C , imt , rup ) : if rup . ztor >= 20.0 : return C [ 'a15' ] else : return C [ 'a15' ] * rup . ztor / 20.0 | Compute and return top of rupture depth term . See paragraph Depth - to - Top of Rupture Model page 1042 . |
233,406 | def _get_soil_depth_term ( self , C , z1pt0 , vs30 ) : z1ref = self . _get_z1pt0ref ( vs30 ) z10 = copy . deepcopy ( z1pt0 ) idx = z1pt0 < 0 z10 [ idx ] = z1ref [ idx ] factor = np . log ( ( z10 + 0.01 ) / ( z1ref + 0.01 ) ) f2 = interpolate . interp1d ( [ 0.0 , 150 , 250 , 400 , 700 , 1000 , 6000 ] , [ C [ 'a43' ] , C... | Compute and return soil depth term . See page 1042 . |
233,407 | def _get_stddevs ( self , C , imt , rup , sites , stddev_types , sa1180 , dists ) : std_intra = self . _get_intra_event_std ( C , rup . mag , sa1180 , sites . vs30 , sites . vs30measured , dists . rrup ) std_inter = self . _get_inter_event_std ( C , rup . mag , sa1180 , sites . vs30 ) stddevs = [ ] for stddev_type in s... | Return standard deviations as described in paragraph Equations for standard deviation page 1046 . |
233,408 | def _get_intra_event_std ( self , C , mag , sa1180 , vs30 , vs30measured , rrup ) : phi_al = self . _get_phi_al_regional ( C , mag , vs30measured , rrup ) derAmp = self . _get_derivative ( C , sa1180 , vs30 ) phi_amp = 0.4 idx = phi_al < phi_amp if np . any ( idx ) : phi_amp = 0.4 * np . ones_like ( phi_al ) phi_amp [ ... | Returns Phi as described at pages 1046 and 1047 |
233,409 | def _get_derivative ( self , C , sa1180 , vs30 ) : derAmp = np . zeros_like ( vs30 ) n = self . CONSTS [ 'n' ] c = C [ 'c' ] b = C [ 'b' ] idx = vs30 < C [ 'vlin' ] derAmp [ idx ] = ( b * sa1180 [ idx ] * ( - 1. / ( sa1180 [ idx ] + c ) + 1. / ( sa1180 [ idx ] + c * ( vs30 [ idx ] / C [ 'vlin' ] ) ** n ) ) ) return der... | Returns equation 30 page 1047 |
233,410 | def _get_regional_term ( self , C , imt , vs30 , rrup ) : f3 = interpolate . interp1d ( [ 150 , 250 , 350 , 450 , 600 , 850 , 1150 , 2000 ] , [ C [ 'a36' ] , C [ 'a37' ] , C [ 'a38' ] , C [ 'a39' ] , C [ 'a40' ] , C [ 'a41' ] , C [ 'a42' ] , C [ 'a42' ] ] , kind = 'linear' ) return f3 ( vs30 ) + C [ 'a29' ] * rrup | Compute regional term for Japan . See page 1043 |
233,411 | def gc ( coeff , mag ) : if mag > 6.5 : a1ca = coeff [ 'ua' ] a1cb = coeff [ 'ub' ] a1cc = coeff [ 'uc' ] a1cd = coeff [ 'ud' ] a1ce = coeff [ 'ue' ] a2ca = coeff [ 'ia' ] a2cb = coeff [ 'ib' ] a2cc = coeff [ 'ic' ] a2cd = coeff [ 'id' ] a2ce = coeff [ 'ie' ] else : a1ca = coeff [ 'a' ] a1cb = coeff [ 'b' ] a1cc = coef... | Returns the set of coefficients to be used for the calculation of GM as a function of earthquake magnitude |
233,412 | def rbf ( ra , coeff , mag ) : a1ca , a1cb , a1cc , a1cd , a1ce , a2ca , a2cb , a2cc , a2cd , a2ce = gc ( coeff , mag ) term1 = a1ca + a1cb * mag + a1cc * np . log ( ra + a1cd * np . exp ( a1ce * mag ) ) term2 = a2ca + a2cb * mag term3 = a2cd * np . exp ( a2ce * mag ) return np . exp ( ( term1 - term2 ) / a2cc ) - term... | Calculate the median ground motion for a given magnitude and distance |
233,413 | def fnc ( ra , * args ) : repi = args [ 0 ] theta = args [ 1 ] mag = args [ 2 ] coeff = args [ 3 ] rb = rbf ( ra , coeff , mag ) t1 = ra ** 2 * ( np . sin ( np . radians ( theta ) ) ) ** 2 t2 = rb ** 2 * ( np . cos ( np . radians ( theta ) ) ) ** 2 xx = ra * rb / ( t1 + t2 ) ** 0.5 return xx - repi | Function used in the minimisation problem . |
233,414 | def get_ras ( repi , theta , mag , coeff ) : rx = 100. ras = 200. dff = fnc ( ras , repi , theta , mag , coeff ) while abs ( dff ) > 1e-3 : if dff > 0. : ras = ras - rx else : ras = ras + rx dff = fnc ( ras , repi , theta , mag , coeff ) rx = rx / 2. if rx < 1e-3 : break return ras | Computes equivalent distance |
233,415 | def _get_stddevs ( self , C , stddev_types , rup , imt , num_sites ) : stddevs = [ ] for stddev_type in stddev_types : sigma_mean = self . _compute_standard_dev ( rup , imt , C ) sigma_tot = np . sqrt ( ( sigma_mean ** 2 ) + ( C [ 'SigmaReg' ] ** 2 ) ) sigma_tot = np . log10 ( np . exp ( sigma_tot ) ) stddevs . append ... | Return standard deviations as defined in eq . 4 and 5 page 744 based on table 8 page 744 . Eq . 5 yields std dev in natural log so convert to log10 |
233,416 | def _compute_standard_dev ( self , rup , imt , C ) : sigma_mean = 0. if imt . name in "SA PGA" : psi = - 6.898E-3 else : psi = - 3.054E-5 if rup . mag <= 6.5 : sigma_mean = ( C [ 'c12' ] * rup . mag ) + C [ 'c13' ] elif rup . mag > 6.5 : sigma_mean = ( psi * rup . mag ) + C [ 'c14' ] return sigma_mean | Compute the the standard deviation in terms of magnitude described on page 744 eq . 4 |
233,417 | def insert ( self , table , columns , rows ) : cursor = self . conn . cursor ( ) if len ( rows ) : templ , _args = match ( 'INSERT INTO ?s (?S) VALUES (?X)' , table , columns , rows [ 0 ] ) cursor . executemany ( templ , rows ) return cursor | Insert several rows with executemany . Return a cursor . |
233,418 | def _cluster ( param , tom , imtls , gsims , grp_ids , pmap ) : pmapclu = AccumDict ( { grp_id : ProbabilityMap ( len ( imtls . array ) , len ( gsims ) ) for grp_id in grp_ids } ) first = True for nocc in range ( 0 , 50 ) : ocr = tom . occurrence_rate prob_n_occ = tom . get_probability_n_occurrences ( ocr , nocc ) if f... | Computes the probability map in case of a cluster group |
233,419 | def _get_stddevs ( self , C , rup , shape , stddev_types ) : weight = self . _compute_weight_std ( C , rup . mag ) std_intra = weight * C [ "sd1" ] * np . ones ( shape ) std_inter = weight * C [ "sd2" ] * np . ones ( shape ) stddevs = [ ] for stddev_type in stddev_types : assert stddev_type in self . DEFINED_FOR_STANDA... | Return standard deviations as defined in p . 971 . |
233,420 | def _compute_weight_std ( self , C , mag ) : if mag < 6.0 : return C [ 'a1' ] elif mag >= 6.0 and mag < 6.5 : return C [ 'a1' ] + ( C [ 'a2' ] - C [ 'a1' ] ) * ( ( mag - 6.0 ) / 0.5 ) else : return C [ 'a2' ] | Common part of equations 8 and 9 page 971 . |
233,421 | def _compute_magnitude_scaling_term ( self , C , mag ) : c1 = self . CONSTS [ 'c1' ] if mag <= c1 : return C [ 'b1' ] + C [ 'b2' ] * ( mag - c1 ) + C [ 'b3' ] * ( 8.5 - mag ) ** 2 else : return C [ 'b1' ] + C [ 'b7' ] * ( mag - c1 ) + C [ 'b3' ] * ( 8.5 - mag ) ** 2 | Compute and return magnitude scaling term in equation 2 page 970 . |
233,422 | def _compute_geometric_decay_term ( self , C , mag , dists ) : c1 = self . CONSTS [ 'c1' ] return ( ( C [ 'b4' ] + C [ 'b5' ] * ( mag - c1 ) ) * np . log ( np . sqrt ( dists . rjb ** 2.0 + C [ 'b6' ] ** 2.0 ) ) ) | Compute and return geometric decay term in equation 3 page 970 . |
233,423 | def _compute_anelestic_attenuation_term ( self , C , dists ) : f_aat = np . zeros_like ( dists . rjb ) idx = dists . rjb > 80.0 f_aat [ idx ] = C [ "b10" ] * ( dists . rjb [ idx ] - 80.0 ) return f_aat | Compute and return anelastic attenuation term in equation 5 page 970 . |
233,424 | def _compute_non_linear_term ( self , C , pga_only , sites ) : Vref = self . CONSTS [ 'Vref' ] Vcon = self . CONSTS [ 'Vcon' ] c = self . CONSTS [ 'c' ] n = self . CONSTS [ 'n' ] lnS = np . zeros_like ( sites . vs30 ) idx = sites . vs30 < Vref lnS [ idx ] = ( C [ 'sb1' ] * np . log ( sites . vs30 [ idx ] / Vref ) + C [... | Compute non - linear term equation 6 page 970 . |
233,425 | def _compute_mean ( self , C , mag , dists , rake ) : mean = ( self . _compute_magnitude_scaling_term ( C , mag ) + self . _compute_geometric_decay_term ( C , mag , dists ) + self . _compute_faulting_style_term ( C , rake ) + self . _compute_anelestic_attenuation_term ( C , dists ) ) return mean | Compute and return mean value without site conditions that is equations 2 - 5 page 970 . |
233,426 | def get_bounding_box ( self , maxdist ) : return utils . get_bounding_box ( [ ps . location for ps in self ] , maxdist ) | Bounding box containing all the point sources enlarged by the maximum distance . |
233,427 | def _compute_standard_dev ( self , rup , imt , C ) : sigma_mean = 0. if rup . mag <= 7.0 : sigma_mean = ( C [ 'c12' ] * rup . mag ) + C [ 'c13' ] elif rup . mag > 7.0 : sigma_mean = ( - 0.00695 * rup . mag ) + C [ 'c14' ] return sigma_mean | Compute the the standard deviation in terms of magnitude described on p . 1866 eq . 6 |
233,428 | def get_rate_osr_normal_transform ( self , threshold_moment , id0 ) : e1h_ridge = np . zeros ( np . sum ( id0 ) , dtype = float ) e2h_ridge = self . strain . data [ 'e1h' ] [ id0 ] + self . strain . data [ 'e2h' ] [ id0 ] err_ridge = - ( e1h_ridge + e2h_ridge ) calculated_rate_ridge = self . continuum_seismicity ( thre... | Gets seismicity rate for special case of the ridge condition with spreading and transform component |
233,429 | def get_rate_osr_convergent_transform ( self , threshold_moment , id0 ) : e1h_ocb = self . strain . data [ 'e1h' ] [ id0 ] + self . strain . data [ 'e2h' ] [ id0 ] e2h_ocb = np . zeros ( np . sum ( id0 ) , dtype = float ) err_ocb = - ( e1h_ocb + e2h_ocb ) calculated_rate_ocb = self . continuum_seismicity ( threshold_mo... | Calculates seismicity rate for special case of the ridge condition with convergence and transform |
233,430 | def get_median_area ( self , mag , rake ) : if rake is None : return power ( 10.0 , ( mag - 4.185 ) ) elif ( - 45 <= rake <= 45 ) or ( rake >= 135 ) or ( rake <= - 135 ) : return power ( 10.0 , ( mag - 4.18 ) ) else : return power ( 10.0 , ( mag - 4.19 ) ) | Calculates median fault area from magnitude . |
233,431 | def _get_base_url ( request ) : if request . is_secure ( ) : base_url = 'https://%s' else : base_url = 'http://%s' base_url %= request . META [ 'HTTP_HOST' ] return base_url | Construct a base URL given a request object . |
233,432 | def _prepare_job ( request , candidates ) : temp_dir = tempfile . mkdtemp ( ) inifiles = [ ] arch = request . FILES . get ( 'archive' ) if arch is None : for each_file in request . FILES . values ( ) : new_path = os . path . join ( temp_dir , each_file . name ) shutil . move ( each_file . temporary_file_path ( ) , new_... | Creates a temporary directory move uploaded files there and select the job file by looking at the candidate names . |
233,433 | def ajax_login ( request ) : username = request . POST [ 'username' ] password = request . POST [ 'password' ] user = authenticate ( username = username , password = password ) if user is not None : if user . is_active : login ( request , user ) return HttpResponse ( content = 'Successful login' , content_type = 'text/... | Accept a POST request to login . |
233,434 | def get_available_gsims ( request ) : gsims = list ( gsim . get_available_gsims ( ) ) return HttpResponse ( content = json . dumps ( gsims ) , content_type = JSON ) | Return a list of strings with the available GSIMs |
233,435 | def validate_nrml ( request ) : xml_text = request . POST . get ( 'xml_text' ) if not xml_text : return HttpResponseBadRequest ( 'Please provide the "xml_text" parameter' ) xml_file = gettemp ( xml_text , suffix = '.xml' ) try : nrml . to_python ( xml_file ) except ExpatError as exc : return _make_response ( error_msg ... | Leverage oq - risklib to check if a given XML text is a valid NRML |
233,436 | def calc_list ( request , id = None ) : base_url = _get_base_url ( request ) calc_data = logs . dbcmd ( 'get_calcs' , request . GET , utils . get_valid_users ( request ) , utils . get_acl_on ( request ) , id ) response_data = [ ] username = psutil . Process ( os . getpid ( ) ) . username ( ) for ( hc_id , owner , statu... | Get a list of calculations and report their id status calculation_mode is_running description and a url where more detailed information can be accessed . This is called several times by the Javascript . |
233,437 | def calc_abort ( request , calc_id ) : job = logs . dbcmd ( 'get_job' , calc_id ) if job is None : message = { 'error' : 'Unknown job %s' % calc_id } return HttpResponse ( content = json . dumps ( message ) , content_type = JSON ) if job . status not in ( 'submitted' , 'executing' ) : message = { 'error' : 'Job %s is n... | Abort the given calculation it is it running |
233,438 | def calc_remove ( request , calc_id ) : user = utils . get_user ( request ) try : message = logs . dbcmd ( 'del_calc' , calc_id , user ) except dbapi . NotFound : return HttpResponseNotFound ( ) if 'success' in message : return HttpResponse ( content = json . dumps ( message ) , content_type = JSON , status = 200 ) eli... | Remove the calculation id |
233,439 | def log_to_json ( log ) : return [ log . timestamp . isoformat ( ) [ : 22 ] , log . level , log . process , log . message ] | Convert a log record into a list of strings |
233,440 | def calc_log_size ( request , calc_id ) : try : response_data = logs . dbcmd ( 'get_log_size' , calc_id ) except dbapi . NotFound : return HttpResponseNotFound ( ) return HttpResponse ( content = json . dumps ( response_data ) , content_type = JSON ) | Get the current number of lines in the log |
233,441 | def submit_job ( job_ini , username , hazard_job_id = None ) : job_id = logs . init ( 'job' ) oq = engine . job_from_file ( job_ini , job_id , username , hazard_calculation_id = hazard_job_id ) pik = pickle . dumps ( oq , protocol = 0 ) code = RUNCALC % dict ( job_id = job_id , hazard_job_id = hazard_job_id , pik = pik... | Create a job object from the given job . ini file in the job directory and run it in a new process . Returns the job ID and PID . |
233,442 | def calc_result ( request , result_id ) : try : job_id , job_status , job_user , datadir , ds_key = logs . dbcmd ( 'get_result' , result_id ) if not utils . user_has_permission ( request , job_user ) : return HttpResponseForbidden ( ) except dbapi . NotFound : return HttpResponseNotFound ( ) etype = request . GET . get... | Download a specific result by result_id . |
233,443 | def extract ( request , calc_id , what ) : job = logs . dbcmd ( 'get_job' , int ( calc_id ) ) if job is None : return HttpResponseNotFound ( ) if not utils . user_has_permission ( request , job . user_name ) : return HttpResponseForbidden ( ) try : with datastore . read ( job . ds_calc_dir + '.hdf5' ) as ds : fd , fnam... | Wrapper over the oq extract command . If setting . LOCKDOWN is true only calculations owned by the current user can be retrieved . |
233,444 | def calc_datastore ( request , job_id ) : job = logs . dbcmd ( 'get_job' , int ( job_id ) ) if job is None : return HttpResponseNotFound ( ) if not utils . user_has_permission ( request , job . user_name ) : return HttpResponseForbidden ( ) fname = job . ds_calc_dir + '.hdf5' response = FileResponse ( FileWrapper ( ope... | Download a full datastore file . |
233,445 | def calc_oqparam ( request , job_id ) : job = logs . dbcmd ( 'get_job' , int ( job_id ) ) if job is None : return HttpResponseNotFound ( ) if not utils . user_has_permission ( request , job . user_name ) : return HttpResponseForbidden ( ) with datastore . read ( job . ds_calc_dir + '.hdf5' ) as ds : oq = ds [ 'oqparam'... | Return the calculation parameters as a JSON |
233,446 | def on_same_fs ( request ) : filename = request . POST [ 'filename' ] checksum_in = request . POST [ 'checksum' ] checksum = 0 try : data = open ( filename , 'rb' ) . read ( 32 ) checksum = zlib . adler32 ( data , checksum ) & 0xffffffff if checksum == int ( checksum_in ) : return HttpResponse ( content = json . dumps ... | Accept a POST request to check access to a FS available by a client . |
233,447 | def classical_damage ( riskinputs , riskmodel , param , monitor ) : result = AccumDict ( accum = AccumDict ( ) ) for ri in riskinputs : for out in riskmodel . gen_outputs ( ri , monitor ) : for l , loss_type in enumerate ( riskmodel . loss_types ) : ordinals = ri . assets [ 'ordinal' ] result [ l , out . rlzi ] += dict... | Core function for a classical damage computation . |
233,448 | def cmp_mat ( a , b ) : c = 0 for x , y in zip ( a . flat , b . flat ) : c = cmp ( abs ( x ) , abs ( y ) ) if c != 0 : return c return c | Sorts two matrices returning a positive or zero value |
233,449 | def _get_centroid_time ( self , time_diff ) : source_time = datetime . datetime . combine ( self . date , self . time ) second_diff = floor ( fabs ( time_diff ) ) microsecond_diff = int ( 1000. * ( time_diff - second_diff ) ) if time_diff < 0. : source_time = source_time - datetime . timedelta ( seconds = int ( second_... | Calculates the time difference between the date - time classes |
233,450 | def _to_ned ( self ) : if self . ref_frame is 'USE' : return utils . use_to_ned ( self . tensor ) , utils . use_to_ned ( self . tensor_sigma ) elif self . ref_frame is 'NED' : return self . tensor , self . tensor_sigma else : raise ValueError ( 'Reference frame %s not recognised - cannot ' 'transform to NED!' % self . ... | Switches the reference frame to NED |
233,451 | def _to_use ( self ) : if self . ref_frame is 'NED' : return utils . ned_to_use ( self . tensor ) , utils . ned_to_use ( self . tensor_sigma ) elif self . ref_frame is 'USE' : return self . tensor , self . tensor_sigma else : raise ValueError ( 'Reference frame %s not recognised - cannot ' 'transform to USE!' % self . ... | Returns a tensor in the USE reference frame |
233,452 | def get_nodal_planes ( self ) : self . tensor , self . tensor_sigma = self . _to_ned ( ) self . ref_frame = 'NED' _ , evect = utils . eigendecompose ( self . tensor ) _ , rot_vec = utils . eigendecompose ( np . matrix ( [ [ 0. , 0. , - 1 ] , [ 0. , 0. , 0. ] , [ - 1. , 0. , 0. ] ] ) ) rotation_matrix = ( np . matrix ( ... | Returns the nodal planes by eigendecomposition of the moment tensor |
233,453 | def get_principal_axes ( self ) : _ = self . eigendecompose ( normalise = True ) principal_axes = GCMTPrincipalAxes ( ) principal_axes . p_axis = { 'eigenvalue' : self . eigenvalues [ 0 ] } principal_axes . b_axis = { 'eigenvalue' : self . eigenvalues [ 1 ] } principal_axes . t_axis = { 'eigenvalue' : self . eigenvalue... | Uses the eigendecomposition to extract the principal axes from the moment tensor - returning an instance of the GCMTPrincipalAxes class |
233,454 | def select_catalogue_events ( self , id0 ) : for key in self . data . keys ( ) : if isinstance ( self . data [ key ] , np . ndarray ) and len ( self . data [ key ] ) > 0 : self . data [ key ] = self . data [ key ] [ id0 ] elif isinstance ( self . data [ key ] , list ) and len ( self . data [ key ] ) > 0 : self . data [... | Orders the events in the catalogue according to an indexing vector |
233,455 | def _get_edge_set ( self , tol = 0.1 ) : edges = [ ] for surface in self . surfaces : if isinstance ( surface , GriddedSurface ) : return edges . append ( surface . mesh ) elif isinstance ( surface , PlanarSurface ) : edge = [ ] for pnt in [ surface . top_left , surface . top_right ] : edge . append ( [ pnt . longitude... | Retrieve set of top edges from all of the individual surfaces downsampling the upper edge based on the specified tolerance |
233,456 | def get_min_distance ( self , mesh ) : dists = [ surf . get_min_distance ( mesh ) for surf in self . surfaces ] return numpy . min ( dists , axis = 0 ) | For each point in mesh compute the minimum distance to each surface element and return the smallest value . |
233,457 | def get_closest_points ( self , mesh ) : dists = numpy . array ( [ surf . get_min_distance ( mesh ) . flatten ( ) for surf in self . surfaces ] ) idx = dists == numpy . min ( dists , axis = 0 ) lons = numpy . empty_like ( mesh . lons . flatten ( ) ) lats = numpy . empty_like ( mesh . lats . flatten ( ) ) depths = None ... | For each point in mesh find the closest surface element and return the corresponding closest point . |
233,458 | def get_bounding_box ( self ) : lons = [ ] lats = [ ] for surf in self . surfaces : west , east , north , south = surf . get_bounding_box ( ) lons . extend ( [ west , east ] ) lats . extend ( [ north , south ] ) return utils . get_spherical_bounding_box ( lons , lats ) | Compute bounding box for each surface element and then return the bounding box of all surface elements bounding boxes . |
233,459 | def _get_areas ( self ) : if self . areas is None : self . areas = [ ] for surf in self . surfaces : self . areas . append ( surf . get_area ( ) ) self . areas = numpy . array ( self . areas ) return self . areas | Return surface elements area values in a numpy array . |
233,460 | def _get_cartesian_edge_set ( self ) : edge_sets = numpy . vstack ( self . edge_set ) west , east , north , south = utils . get_spherical_bounding_box ( edge_sets [ : , 0 ] , edge_sets [ : , 1 ] ) self . proj = utils . OrthographicProjection ( west , east , north , south ) for edges in self . edge_set : px , py = self ... | For the GC2 calculations a set of cartesian representations of the fault edges are needed . In this present case we use a common cartesian framework for all edges as opposed to defining a separate orthographic projection per edge |
233,461 | def _get_gc2_coordinates_for_rupture ( self , edge_sets ) : rup_gc2t , rup_gc2u = self . get_generalised_coordinates ( edge_sets [ : , 0 ] , edge_sets [ : , 1 ] ) self . gc_length = numpy . max ( rup_gc2u ) | Calculates the GC2 coordinates for the nodes of the upper edge of the fault |
233,462 | def _get_ut_i ( self , seg , sx , sy ) : p0x , p0y , p1x , p1y = seg [ 0 , 0 ] , seg [ 0 , 1 ] , seg [ 1 , 0 ] , seg [ 1 , 1 ] t_i_vec = [ p1y - p0y , - ( p1x - p0x ) , 0.0 ] t_i_hat = t_i_vec / numpy . linalg . norm ( t_i_vec ) u_i_vec = [ p1x - p0x , p1y - p0y , 0.0 ] u_i_hat = u_i_vec / numpy . linalg . norm ( u_i_v... | Returns the U and T coordinate for a specific trace segment |
233,463 | def get_rx_distance ( self , mesh ) : if not self . tmp_mesh or ( self . tmp_mesh == mesh ) : self . gc2t , self . gc2u = self . get_generalised_coordinates ( mesh . lons , mesh . lats ) self . tmp_mesh = deepcopy ( mesh ) return self . gc2t | For each point determine the corresponding rx distance using the GC2 configuration . |
233,464 | def get_ry0_distance ( self , mesh ) : if not self . tmp_mesh or ( self . tmp_mesh == mesh ) : self . gc2t , self . gc2u = self . get_generalised_coordinates ( mesh . lons , mesh . lats ) self . tmp_mesh = deepcopy ( mesh ) ry0 = numpy . zeros_like ( self . gc2u , dtype = float ) neg_gc2u = self . gc2u < 0.0 ry0 [ neg_... | For each point determine the corresponding Ry0 distance using the GC2 configuration . |
233,465 | def from_model_files ( cls , limits , input_model , investigation_time = 1.0 , simple_mesh_spacing = 1.0 , complex_mesh_spacing = 5.0 , mfd_width = 0.1 , area_discretisation = 10.0 ) : converter = SourceConverter ( investigation_time , simple_mesh_spacing , complex_mesh_spacing , mfd_width , area_discretisation ) sourc... | Reads the hazard model from a file |
233,466 | def get_rates ( self , mmin , mmax = np . inf ) : nsrcs = self . number_sources ( ) for iloc , source in enumerate ( self . source_model ) : print ( "Source Number %s of %s, Name = %s, Typology = %s" % ( iloc + 1 , nsrcs , source . name , source . __class__ . __name__ ) ) if isinstance ( source , CharacteristicFaultSou... | Returns the cumulative rates greater than Mmin |
233,467 | def _get_point_location ( self , location ) : if ( location . longitude < self . xlim [ 0 ] ) or ( location . longitude > self . xlim [ - 1 ] ) : return None , None xloc = int ( ( ( location . longitude - self . xlim [ 0 ] ) / self . xspc ) + 1E-7 ) if ( location . latitude < self . ylim [ 0 ] ) or ( location . latitud... | Returns the location in the output grid corresponding to the cell in which the epicentre lays |
233,468 | def _get_area_rates ( self , source , mmin , mmax = np . inf ) : points = list ( source ) for point in points : self . _get_point_rates ( point , mmin , mmax ) | Adds the rates from the area source by discretising the source to a set of point sources |
233,469 | def _get_distance_scaling ( self , C , mag , rhypo ) : return ( C [ "a3" ] * np . log ( rhypo ) ) + ( C [ "a4" ] + C [ "a5" ] * mag ) * rhypo | Returns the distance scalig term |
233,470 | def _get_distance_scaling_term ( self , C , rjb , mag ) : rval = np . sqrt ( rjb ** 2.0 + C [ "c11" ] ** 2.0 ) f_0 , f_1 , f_2 = self . _get_distance_segment_coefficients ( rval ) return ( ( C [ "c4" ] + C [ "c5" ] * mag ) * f_0 + ( C [ "c6" ] + C [ "c7" ] * mag ) * f_1 + ( C [ "c8" ] + C [ "c9" ] * mag ) * f_2 + ( C [... | Returns the distance scaling component of the model Equation 10 Page 63 |
233,471 | def _get_distance_segment_coefficients ( self , rval ) : nsites = len ( rval ) f_0 = np . log10 ( self . CONSTS [ "r0" ] / rval ) f_0 [ rval > self . CONSTS [ "r0" ] ] = 0.0 f_1 = np . log10 ( rval ) f_1 [ rval > self . CONSTS [ "r1" ] ] = np . log10 ( self . CONSTS [ "r1" ] ) f_2 = np . log10 ( rval / self . CONSTS [ ... | Returns the coefficients describing the distance attenuation shape for three different distance bins equations 12a - 12c |
233,472 | def collect_files ( dirpath , cond = lambda fullname : True ) : files = [ ] for fname in os . listdir ( dirpath ) : fullname = os . path . join ( dirpath , fname ) if os . path . isdir ( fullname ) : files . extend ( collect_files ( fullname ) ) else : if cond ( fullname ) : files . append ( fullname ) return files | Recursively collect the files contained inside dirpath . |
233,473 | def extract_from_zip ( path , candidates ) : temp_dir = tempfile . mkdtemp ( ) with zipfile . ZipFile ( path ) as archive : archive . extractall ( temp_dir ) return [ f for f in collect_files ( temp_dir ) if os . path . basename ( f ) in candidates ] | Given a zip archive and a function to detect the presence of a given filename unzip the archive into a temporary directory and return the full path of the file . Raise an IOError if the file cannot be found within the archive . |
233,474 | def get_params ( job_inis , ** kw ) : input_zip = None if len ( job_inis ) == 1 and job_inis [ 0 ] . endswith ( '.zip' ) : input_zip = job_inis [ 0 ] job_inis = extract_from_zip ( job_inis [ 0 ] , [ 'job_hazard.ini' , 'job_haz.ini' , 'job.ini' , 'job_risk.ini' ] ) not_found = [ ini for ini in job_inis if not os . path ... | Parse one or more INI - style config files . |
233,475 | def get_oqparam ( job_ini , pkg = None , calculators = None , hc_id = None , validate = 1 , ** kw ) : from openquake . calculators import base OqParam . calculation_mode . validator . choices = tuple ( calculators or base . calculators ) if not isinstance ( job_ini , dict ) : basedir = os . path . dirname ( pkg . __fil... | Parse a dictionary of parameters from an INI - style config file . |
233,476 | def get_site_model ( oqparam ) : req_site_params = get_gsim_lt ( oqparam ) . req_site_params arrays = [ ] for fname in oqparam . inputs [ 'site_model' ] : if isinstance ( fname , str ) and fname . endswith ( '.csv' ) : sm = read_csv ( fname ) if 'site_id' in sm . dtype . names : raise InvalidFile ( '%s: you passed a si... | Convert the NRML file into an array of site parameters . |
233,477 | def get_site_collection ( oqparam ) : mesh = get_mesh ( oqparam ) req_site_params = get_gsim_lt ( oqparam ) . req_site_params if oqparam . inputs . get ( 'site_model' ) : sm = get_site_model ( oqparam ) try : depth = sm [ 'depth' ] except ValueError : depth = None sitecol = site . SiteCollection . from_points ( sm [ 'l... | Returns a SiteCollection instance by looking at the points and the site model defined by the configuration parameters . |
233,478 | def get_rupture ( oqparam ) : rup_model = oqparam . inputs [ 'rupture_model' ] [ rup_node ] = nrml . read ( rup_model ) conv = sourceconverter . RuptureConverter ( oqparam . rupture_mesh_spacing , oqparam . complex_fault_mesh_spacing ) rup = conv . convert_node ( rup_node ) rup . tectonic_region_type = '*' rup . serial... | Read the rupture_model file and by filter the site collection |
233,479 | def get_composite_source_model ( oqparam , monitor = None , in_memory = True , srcfilter = SourceFilter ( None , { } ) ) : ucerf = oqparam . calculation_mode . startswith ( 'ucerf' ) source_model_lt = get_source_model_lt ( oqparam , validate = not ucerf ) trts = source_model_lt . tectonic_region_types trts_lower = { tr... | Parse the XML and build a complete composite source model in memory . |
233,480 | def get_mesh_hcurves ( oqparam ) : imtls = oqparam . imtls lon_lats = set ( ) data = AccumDict ( ) ncols = len ( imtls ) + 1 csvfile = oqparam . inputs [ 'hazard_curves' ] for line , row in enumerate ( csv . reader ( csvfile ) , 1 ) : try : if len ( row ) != ncols : raise ValueError ( 'Expected %d columns, found %d' % ... | Read CSV data in the format lon lat v1 - vN w1 - wN ... . |
233,481 | def reduce_source_model ( smlt_file , source_ids , remove = True ) : found = 0 to_remove = [ ] for paths in logictree . collect_info ( smlt_file ) . smpaths . values ( ) : for path in paths : logging . info ( 'Reading %s' , path ) root = nrml . read ( path ) model = Node ( 'sourceModel' , root [ 0 ] . attrib ) origmode... | Extract sources from the composite source model |
233,482 | def get_checksum32 ( oqparam , hazard = False ) : checksum = 0 for fname in get_input_files ( oqparam , hazard ) : checksum = _checksum ( fname , checksum ) if hazard : hazard_params = [ ] for key , val in vars ( oqparam ) . items ( ) : if key in ( 'rupture_mesh_spacing' , 'complex_fault_mesh_spacing' , 'width_of_mfd_b... | Build an unsigned 32 bit integer from the input files of a calculation . |
233,483 | def smart_save ( dbpath , archive , calc_id ) : tmpdir = tempfile . mkdtemp ( ) newdb = os . path . join ( tmpdir , os . path . basename ( dbpath ) ) shutil . copy ( dbpath , newdb ) try : with sqlite3 . connect ( newdb ) as conn : conn . execute ( 'DELETE FROM job WHERE status != "complete"' ) if calc_id : conn . exec... | Make a copy of the db remove the incomplete jobs and add the copy to the archive |
233,484 | def dump ( archive , calc_id = 0 , user = None ) : t0 = time . time ( ) assert archive . endswith ( '.zip' ) , archive getfnames = 'select ds_calc_dir || ".hdf5" from job where ?A' param = dict ( status = 'complete' ) if calc_id : param [ 'id' ] = calc_id if user : param [ 'user_name' ] = user fnames = [ f for f , in d... | Dump the openquake database and all the complete calculations into a zip file . In a multiuser installation must be run as administrator . |
233,485 | def load_version ( ) : filename = os . path . abspath ( os . path . join ( os . path . dirname ( os . path . abspath ( __file__ ) ) , "cpt" , "__init__.py" ) ) with open ( filename , "rt" ) as version_file : conan_init = version_file . read ( ) version = re . search ( "__version__ = '([0-9a-z.-]+)'" , conan_init ) . gr... | Loads a file content |
233,486 | def builds ( self , confs ) : self . _named_builds = { } self . _builds = [ ] for values in confs : if len ( values ) == 2 : self . _builds . append ( BuildConf ( values [ 0 ] , values [ 1 ] , { } , { } , self . reference ) ) elif len ( values ) == 4 : self . _builds . append ( BuildConf ( values [ 0 ] , values [ 1 ] ,... | For retro compatibility directly assigning builds |
233,487 | def patch_default_base_profile ( conan_api , profile_abs_path ) : text = tools . load ( profile_abs_path ) if "include(default)" in text : if Version ( conan_version ) < Version ( "1.12.0" ) : cache = conan_api . _client_cache else : cache = conan_api . _cache default_profile_name = os . path . basename ( cache . defau... | If we have a profile including default but the users default in config is that the default is other we have to change the include |
233,488 | def get_user_if_exists ( strategy , details , user = None , * args , ** kwargs ) : if user : return { 'is_new' : False } try : username = details . get ( 'username' ) return { 'is_new' : False , 'user' : User . objects . get ( username = username ) } except User . DoesNotExist : pass return { } | Return a User with the given username iff the User exists . |
233,489 | def update_email ( strategy , details , user = None , * args , ** kwargs ) : if user : email = details . get ( 'email' ) if email and user . email != email : user . email = email strategy . storage . user . changed ( user ) | Update the user s email address using data from provider . |
233,490 | def get_user_claims ( self , access_token , claims = None , token_type = 'Bearer' ) : data = self . get_json ( self . USER_INFO_URL , headers = { 'Authorization' : '{token_type} {token}' . format ( token_type = token_type , token = access_token ) } ) if claims : claims_names = set ( claims ) data = { k : v for ( k , v ... | Returns a dictionary with the values for each claim requested . |
233,491 | def _setup_ipc ( self ) : log . debug ( 'Setting up the server IPC puller to receive from the listener' ) self . ctx = zmq . Context ( ) self . sub = self . ctx . socket ( zmq . PULL ) self . sub . bind ( LST_IPC_URL ) try : self . sub . setsockopt ( zmq . HWM , self . opts [ 'hwm' ] ) except AttributeError : self . su... | Setup the IPC pub and sub . Subscript to the listener IPC and publish to the device specific IPC . |
233,492 | def _cleanup_buffer ( self ) : if not self . _buffer : return while True : time . sleep ( 60 ) log . debug ( 'Cleaning up buffer' ) items = self . _buffer . items ( ) log . debug ( 'Collected items' ) log . debug ( list ( items ) ) | Periodically cleanup the buffer . |
233,493 | def _compile_prefixes ( self ) : self . compiled_prefixes = { } for dev_os , os_config in self . config . items ( ) : if not os_config : continue self . compiled_prefixes [ dev_os ] = [ ] for prefix in os_config . get ( 'prefixes' , [ ] ) : values = prefix . get ( 'values' , { } ) line = prefix . get ( 'line' , '' ) if... | Create a dict of all OS prefixes and their compiled regexs |
233,494 | def _identify_prefix ( self , msg , data ) : prefix_id = - 1 for prefix in data : msg_dict = { } prefix_id += 1 match = None if '__python_fun__' in prefix : log . debug ( 'Trying to match using the %s custom python profiler' , prefix [ '__python_mod__' ] ) try : match = prefix [ '__python_fun__' ] ( msg ) except Except... | Check the message again each OS prefix and if matched return the message dict |
233,495 | def _identify_os ( self , msg ) : ret = [ ] for dev_os , data in self . compiled_prefixes . items ( ) : log . debug ( 'Matching under %s' , dev_os ) msg_dict = self . _identify_prefix ( msg , data ) if msg_dict : log . debug ( 'Adding %s to list of matched OS' , dev_os ) ret . append ( ( dev_os , msg_dict ) ) else : lo... | Using the prefix of the syslog message we are able to identify the operating system and then continue parsing . |
233,496 | def _setup_ipc ( self ) : self . ctx = zmq . Context ( ) log . debug ( 'Creating the dealer IPC for %s' , self . _name ) self . sub = self . ctx . socket ( zmq . DEALER ) if six . PY2 : self . sub . setsockopt ( zmq . IDENTITY , self . _name ) elif six . PY3 : self . sub . setsockopt ( zmq . IDENTITY , bytes ( self . _... | Subscribe to the right topic in the device IPC and publish to the publisher proxy . |
233,497 | def _compile_messages ( self ) : self . compiled_messages = [ ] if not self . _config : return for message_dict in self . _config . get ( 'messages' , { } ) : error = message_dict [ 'error' ] tag = message_dict [ 'tag' ] model = message_dict [ 'model' ] match_on = message_dict . get ( 'match_on' , 'tag' ) if '__python_... | Create a list of all OS messages and their compiled regexs |
233,498 | def _parse ( self , msg_dict ) : error_present = False for message in self . compiled_messages : match_on = message [ 'match_on' ] if match_on not in msg_dict : continue if message [ 'tag' ] != msg_dict [ match_on ] : continue if '__python_fun__' in message : return { 'model' : message [ 'model' ] , 'error' : message [... | Parse a syslog message and check what OpenConfig object should be generated . |
233,499 | def _emit ( self , ** kwargs ) : oc_dict = { } for mapping , result_key in kwargs [ 'mapping' ] [ 'variables' ] . items ( ) : result = kwargs [ result_key ] oc_dict = napalm_logs . utils . setval ( mapping . format ( ** kwargs ) , result , oc_dict ) for mapping , result in kwargs [ 'mapping' ] [ 'static' ] . items ( ) ... | Emit an OpenConfig object given a certain combination of fields mappeed in the config to the corresponding hierarchy . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.