idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
239,500 | def get_hypothesis ( hypotheses , current_file ) : uri = current_file [ 'uri' ] if uri in hypotheses : return hypotheses [ uri ] # if the exact 'uri' is not available in hypothesis, # look for matching substring tmp_uri = [ u for u in hypotheses if u in uri ] # no matching speech turns. return empty annotation if len ( tmp_uri ) == 0 : msg = f'Could not find hypothesis for file "{uri}"; assuming empty file.' warnings . warn ( msg ) return Annotation ( uri = uri , modality = 'speaker' ) # exactly one matching file. return it if len ( tmp_uri ) == 1 : hypothesis = hypotheses [ tmp_uri [ 0 ] ] hypothesis . uri = uri return hypothesis # more that one matching file. error. msg = f'Found too many hypotheses matching file "{uri}" ({uris}).' raise ValueError ( msg . format ( uri = uri , uris = tmp_uri ) ) | Get hypothesis for given file | 221 | 5 |
239,501 | def reindex ( report ) : index = list ( report . index ) i = index . index ( 'TOTAL' ) return report . reindex ( index [ : i ] + index [ i + 1 : ] + [ 'TOTAL' ] ) | Reindex report so that TOTAL is the last row | 53 | 10 |
239,502 | def precision_recall_curve ( y_true , scores , distances = False ) : if distances : scores = - scores precision , recall , thresholds = sklearn . metrics . precision_recall_curve ( y_true , scores , pos_label = True ) if distances : thresholds = - thresholds auc = sklearn . metrics . auc ( precision , recall , reorder = True ) return precision , recall , thresholds , auc | Precision - recall curve | 94 | 5 |
239,503 | def difference ( self , reference , hypothesis , uem = None , uemified = False ) : R , H , common_timeline = self . uemify ( reference , hypothesis , uem = uem , collar = self . collar , skip_overlap = self . skip_overlap , returns_timeline = True ) errors = Annotation ( uri = reference . uri , modality = reference . modality ) # loop on all segments for segment in common_timeline : # list of labels in reference segment rlabels = R . get_labels ( segment , unique = False ) # list of labels in hypothesis segment hlabels = H . get_labels ( segment , unique = False ) _ , details = self . matcher ( rlabels , hlabels ) for r , h in details [ MATCH_CORRECT ] : track = errors . new_track ( segment , prefix = MATCH_CORRECT ) errors [ segment , track ] = ( MATCH_CORRECT , r , h ) for r , h in details [ MATCH_CONFUSION ] : track = errors . new_track ( segment , prefix = MATCH_CONFUSION ) errors [ segment , track ] = ( MATCH_CONFUSION , r , h ) for r in details [ MATCH_MISSED_DETECTION ] : track = errors . new_track ( segment , prefix = MATCH_MISSED_DETECTION ) errors [ segment , track ] = ( MATCH_MISSED_DETECTION , r , None ) for h in details [ MATCH_FALSE_ALARM ] : track = errors . new_track ( segment , prefix = MATCH_FALSE_ALARM ) errors [ segment , track ] = ( MATCH_FALSE_ALARM , None , h ) if uemified : return reference , hypothesis , errors else : return errors | Get error analysis as Annotation | 411 | 6 |
239,504 | def reset ( self ) : if self . parallel : from pyannote . metrics import manager_ self . accumulated_ = manager_ . dict ( ) self . results_ = manager_ . list ( ) self . uris_ = manager_ . dict ( ) else : self . accumulated_ = dict ( ) self . results_ = list ( ) self . uris_ = dict ( ) for value in self . components_ : self . accumulated_ [ value ] = 0. | Reset accumulated components and metric values | 99 | 7 |
239,505 | def confidence_interval ( self , alpha = 0.9 ) : m , _ , _ = scipy . stats . bayes_mvs ( [ r [ self . metric_name_ ] for _ , r in self . results_ ] , alpha = alpha ) return m | Compute confidence interval on accumulated metric values | 60 | 8 |
239,506 | def compute_metric ( self , components ) : numerator = components [ PRECISION_RELEVANT_RETRIEVED ] denominator = components [ PRECISION_RETRIEVED ] if denominator == 0. : if numerator == 0 : return 1. else : raise ValueError ( '' ) else : return numerator / denominator | Compute precision from components | 78 | 5 |
239,507 | def compute_metric ( self , components ) : numerator = components [ RECALL_RELEVANT_RETRIEVED ] denominator = components [ RECALL_RELEVANT ] if denominator == 0. : if numerator == 0 : return 1. else : raise ValueError ( '' ) else : return numerator / denominator | Compute recall from components | 75 | 5 |
239,508 | def optimal_mapping ( self , reference , hypothesis , uem = None ) : # NOTE that this 'uemification' will not be called when # 'optimal_mapping' is called from 'compute_components' as it # has already been done in 'compute_components' if uem : reference , hypothesis = self . uemify ( reference , hypothesis , uem = uem ) # call hungarian mapper mapping = self . mapper_ ( hypothesis , reference ) return mapping | Optimal label mapping | 109 | 4 |
239,509 | def greedy_mapping ( self , reference , hypothesis , uem = None ) : if uem : reference , hypothesis = self . uemify ( reference , hypothesis , uem = uem ) return self . mapper_ ( hypothesis , reference ) | Greedy label mapping | 53 | 4 |
239,510 | def default_absorbers ( Tatm , ozone_file = 'apeozone_cam3_5_54.nc' , verbose = True , ) : absorber_vmr = { } absorber_vmr [ 'CO2' ] = 348. / 1E6 absorber_vmr [ 'CH4' ] = 1650. / 1E9 absorber_vmr [ 'N2O' ] = 306. / 1E9 absorber_vmr [ 'O2' ] = 0.21 absorber_vmr [ 'CFC11' ] = 0. absorber_vmr [ 'CFC12' ] = 0. absorber_vmr [ 'CFC22' ] = 0. absorber_vmr [ 'CCL4' ] = 0. # Ozone: start with all zeros, interpolate to data if we can xTatm = Tatm . to_xarray ( ) O3 = 0. * xTatm if ozone_file is not None : ozonefilepath = os . path . join ( os . path . dirname ( __file__ ) , 'data' , 'ozone' , ozone_file ) remotepath_http = 'http://thredds.atmos.albany.edu:8080/thredds/fileServer/CLIMLAB/ozone/' + ozone_file remotepath_opendap = 'http://thredds.atmos.albany.edu:8080/thredds/dodsC/CLIMLAB/ozone/' + ozone_file ozonedata , path = load_data_source ( local_path = ozonefilepath , remote_source_list = [ remotepath_http , remotepath_opendap ] , open_method = xr . open_dataset , remote_kwargs = { 'engine' : 'pydap' } , verbose = verbose , ) ## zonal and time average ozone_zon = ozonedata . OZONE . mean ( dim = ( 'time' , 'lon' ) ) . transpose ( 'lat' , 'lev' ) if ( 'lat' in xTatm . dims ) : O3source = ozone_zon else : weight = np . cos ( np . deg2rad ( ozonedata . lat ) ) ozone_global = ( ozone_zon * weight ) . mean ( dim = 'lat' ) / weight . mean ( dim = 'lat' ) O3source = ozone_global try : O3 = O3source . interp_like ( xTatm ) # There will be NaNs for gridpoints outside the ozone file domain assert not np . any ( np . isnan ( O3 ) ) except : warnings . warn ( 'Some grid points are beyond the bounds of the ozone file. Ozone values will be extrapolated.' ) try : # passing fill_value=None to the underlying scipy interpolator # will result in extrapolation instead of NaNs O3 = O3source . interp_like ( xTatm , kwargs = { 'fill_value' : None } ) assert not np . any ( np . isnan ( O3 ) ) except : warnings . warn ( 'Interpolation of ozone data failed. Setting O3 to zero instead.' ) O3 = 0. * xTatm absorber_vmr [ 'O3' ] = O3 . values return absorber_vmr | Initialize a dictionary of well - mixed radiatively active gases All values are volumetric mixing ratios . | 761 | 21 |
239,511 | def init_interface ( field ) : interface_shape = np . array ( field . shape ) interface_shape [ - 1 ] += 1 interfaces = np . tile ( False , len ( interface_shape ) ) interfaces [ - 1 ] = True interface_zero = Field ( np . zeros ( interface_shape ) , domain = field . domain , interfaces = interfaces ) return interface_zero | Return a Field object defined at the vertical interfaces of the input Field object . | 81 | 15 |
239,512 | def convective_adjustment_direct ( p , T , c , lapserate = 6.5 ) : # largely follows notation and algorithm in Akmaev (1991) MWR alpha = const . Rd / const . g * lapserate / 1.E3 # same dimensions as lapserate L = p . size ### now handles variable lapse rate pextended = np . insert ( p , 0 , const . ps ) # prepend const.ps = 1000 hPa as ref pressure to compute potential temperature Pi = np . cumprod ( ( p / pextended [ : - 1 ] ) ** alpha ) # Akmaev's equation 14 recurrence formula beta = 1. / Pi theta = T * beta q = Pi * c n_k = np . zeros ( L , dtype = np . int8 ) theta_k = np . zeros_like ( p ) s_k = np . zeros_like ( p ) t_k = np . zeros_like ( p ) thetaadj = Akmaev_adjustment_multidim ( theta , q , beta , n_k , theta_k , s_k , t_k ) T = thetaadj * Pi return T | Convective Adjustment to a specified lapse rate . | 262 | 11 |
239,513 | def Akmaev_adjustment ( theta , q , beta , n_k , theta_k , s_k , t_k ) : L = q . size # number of vertical levels # Akmaev step 1 k = 1 n_k [ k - 1 ] = 1 theta_k [ k - 1 ] = theta [ k - 1 ] l = 2 while True : # Akmaev step 2 n = 1 thistheta = theta [ l - 1 ] while True : # Akmaev step 3 if theta_k [ k - 1 ] <= thistheta : # Akmaev step 6 k += 1 break # to step 7 else : if n <= 1 : s = q [ l - 1 ] t = s * thistheta # Akmaev step 4 if n_k [ k - 1 ] <= 1 : # lower adjacent level is not an earlier-formed neutral layer s_k [ k - 1 ] = q [ l - n - 1 ] t_k [ k - 1 ] = s_k [ k - 1 ] * theta_k [ k - 1 ] # Akmaev step 5 # join current and underlying layers n += n_k [ k - 1 ] s += s_k [ k - 1 ] t += t_k [ k - 1 ] s_k [ k - 1 ] = s t_k [ k - 1 ] = t thistheta = t / s if k == 1 : # joint neutral layer is the first one break # to step 7 k -= 1 # back to step 3 # Akmaev step 7 if l == L : # the scan is over break # to step 8 l += 1 n_k [ k - 1 ] = n theta_k [ k - 1 ] = thistheta # back to step 2 # update the potential temperatures while True : while True : # Akmaev step 8 if n == 1 : # current model level was not included in any neutral layer break # to step 11 while True : # Akmaev step 9 theta [ l - 1 ] = thistheta if n == 1 : break # Akmaev step 10 l -= 1 n -= 1 # back to step 9 # Akmaev step 11 if k == 1 : break k -= 1 l -= 1 n = n_k [ k - 1 ] thistheta = theta_k [ k - 1 ] # back to step 8 return theta | Single column only . | 523 | 4 |
239,514 | def do_diagnostics ( self ) : self . OLR = self . subprocess [ 'LW' ] . flux_to_space self . LW_down_sfc = self . subprocess [ 'LW' ] . flux_to_sfc self . LW_up_sfc = self . subprocess [ 'LW' ] . flux_from_sfc self . LW_absorbed_sfc = self . LW_down_sfc - self . LW_up_sfc self . LW_absorbed_atm = self . subprocess [ 'LW' ] . absorbed self . LW_emission = self . subprocess [ 'LW' ] . emission # contributions to OLR from surface and atm. levels #self.diagnostics['OLR_sfc'] = self.flux['sfc2space'] #self.diagnostics['OLR_atm'] = self.flux['atm2space'] self . ASR = ( self . subprocess [ 'SW' ] . flux_from_space - self . subprocess [ 'SW' ] . flux_to_space ) #self.SW_absorbed_sfc = (self.subprocess['surface'].SW_from_atm - # self.subprocess['surface'].SW_to_atm) self . SW_absorbed_atm = self . subprocess [ 'SW' ] . absorbed self . SW_down_sfc = self . subprocess [ 'SW' ] . flux_to_sfc self . SW_up_sfc = self . subprocess [ 'SW' ] . flux_from_sfc self . SW_absorbed_sfc = self . SW_down_sfc - self . SW_up_sfc self . SW_up_TOA = self . subprocess [ 'SW' ] . flux_to_space self . SW_down_TOA = self . subprocess [ 'SW' ] . flux_from_space self . planetary_albedo = ( self . subprocess [ 'SW' ] . flux_to_space / self . subprocess [ 'SW' ] . flux_from_space ) | Set all the diagnostics from long and shortwave radiation . | 476 | 12 |
239,515 | def clausius_clapeyron ( T ) : Tcel = T - tempCtoK es = 6.112 * exp ( 17.67 * Tcel / ( Tcel + 243.5 ) ) return es | Compute saturation vapor pressure as function of temperature T . | 48 | 11 |
239,516 | def qsat ( T , p ) : es = clausius_clapeyron ( T ) q = eps * es / ( p - ( 1 - eps ) * es ) return q | Compute saturation specific humidity as function of temperature and pressure . | 43 | 12 |
239,517 | def pseudoadiabat ( T , p ) : esoverp = clausius_clapeyron ( T ) / p Tcel = T - tempCtoK L = ( 2.501 - 0.00237 * Tcel ) * 1.E6 # Accurate form of latent heat of vaporization in J/kg ratio = L / T / Rv dTdp = ( T / p * kappa * ( 1 + esoverp * ratio ) / ( 1 + kappa * ( cpv / Rv + ( ratio - 1 ) * ratio ) * esoverp ) ) return dTdp | Compute the local slope of the pseudoadiabat at given temperature and pressure | 133 | 17 |
239,518 | def _solve_implicit_banded ( current , banded_matrix ) : # can improve performance by storing the banded form once and not # recalculating it... # but whatever J = banded_matrix . shape [ 0 ] diag = np . zeros ( ( 3 , J ) ) diag [ 1 , : ] = np . diag ( banded_matrix , k = 0 ) diag [ 0 , 1 : ] = np . diag ( banded_matrix , k = 1 ) diag [ 2 , : - 1 ] = np . diag ( banded_matrix , k = - 1 ) return solve_banded ( ( 1 , 1 ) , diag , current ) | Uses a banded solver for matrix inversion of a tridiagonal matrix . | 158 | 18 |
239,519 | def _guess_diffusion_axis ( process_or_domain ) : axes = get_axes ( process_or_domain ) diff_ax = { } for axname , ax in axes . items ( ) : if ax . num_points > 1 : diff_ax . update ( { axname : ax } ) if len ( list ( diff_ax . keys ( ) ) ) == 1 : return list ( diff_ax . keys ( ) ) [ 0 ] else : raise ValueError ( 'More than one possible diffusion axis.' ) | Scans given process domain or dictionary of domains for a diffusion axis and returns appropriate name . | 116 | 18 |
239,520 | def _implicit_solver ( self ) : #if self.update_diffusivity: # Time-stepping the diffusion is just inverting this matrix problem: newstate = { } for varname , value in self . state . items ( ) : if self . use_banded_solver : newvar = _solve_implicit_banded ( value , self . _diffTriDiag ) else : newvar = np . linalg . solve ( self . _diffTriDiag , value ) newstate [ varname ] = newvar return newstate | Invertes and solves the matrix problem for diffusion matrix and temperature T . | 124 | 15 |
239,521 | def _compute_fixed ( self ) : try : lon , lat = np . meshgrid ( self . lon , self . lat ) except : lat = self . lat phi = np . deg2rad ( lat ) try : albedo = self . a0 + self . a2 * P2 ( np . sin ( phi ) ) except : albedo = np . zeros_like ( phi ) # make sure that the diagnostic has the correct field dimensions. #dom = self.domains['default'] # this is a more robust way to get the single value from dictionary: dom = next ( iter ( self . domains . values ( ) ) ) self . albedo = Field ( albedo , domain = dom ) | Recompute any fixed quantities after a change in parameters | 160 | 11 |
239,522 | def find_icelines ( self ) : Tf = self . param [ 'Tf' ] Ts = self . state [ 'Ts' ] lat_bounds = self . domains [ 'Ts' ] . axes [ 'lat' ] . bounds self . noice = np . where ( Ts >= Tf , True , False ) self . ice = np . where ( Ts < Tf , True , False ) # Ice cover in fractional area self . ice_area = global_mean ( self . ice * np . ones_like ( self . Ts ) ) # Express ice cover in terms of ice edge latitudes if self . ice . all ( ) : # 100% ice cover self . icelat = np . array ( [ - 0. , 0. ] ) elif self . noice . all ( ) : # zero ice cover self . icelat = np . array ( [ - 90. , 90. ] ) else : # there is some ice edge # Taking np.diff of a boolean array gives True at the boundaries between True and False boundary_indices = np . where ( np . diff ( self . ice . squeeze ( ) ) ) [ 0 ] + 1 # check for asymmetry case: [-90,x] or [x,90] # -> boundary_indices hold only one value for icelat if boundary_indices . size == 1 : if self . ice [ 0 ] == True : # case: [x,90] # extend indice array by missing value for northpole boundary_indices = np . append ( boundary_indices , self . ice . size ) elif self . ice [ - 1 ] == True : # case: [-90,x] # extend indice array by missing value for northpole boundary_indices = np . insert ( boundary_indices , 0 , 0 ) # check for asymmetry case: [-90,x] or [x,90] # -> boundary_indices hold only one value for icelat if boundary_indices . size == 1 : if self . ice [ 0 ] == True : # case: [x,90] # extend indice array by missing value for northpole boundary_indices = np . append ( boundary_indices , self . ice . size ) elif self . ice [ - 1 ] == True : # case: [-90,x] # extend indice array by missing value for northpole boundary_indices = np . insert ( boundary_indices , 0 , 0 ) self . icelat = lat_bounds [ boundary_indices ] | Finds iceline according to the surface temperature . | 547 | 10 |
239,523 | def _get_current_albedo ( self ) : ice = self . subprocess [ 'iceline' ] . ice # noice = self.subprocess['iceline'].diagnostics['noice'] cold_albedo = self . subprocess [ 'cold_albedo' ] . albedo warm_albedo = self . subprocess [ 'warm_albedo' ] . albedo albedo = Field ( np . where ( ice , cold_albedo , warm_albedo ) , domain = self . domains [ 'Ts' ] ) return albedo | Simple step - function albedo based on ice line at temperature Tf . | 132 | 16 |
239,524 | def process_like ( proc ) : newproc = copy . deepcopy ( proc ) newproc . creation_date = time . strftime ( "%a, %d %b %Y %H:%M:%S %z" , time . localtime ( ) ) return newproc | Make an exact clone of a process including state and all subprocesses . | 61 | 15 |
239,525 | def get_axes ( process_or_domain ) : if isinstance ( process_or_domain , Process ) : dom = process_or_domain . domains else : dom = process_or_domain if isinstance ( dom , _Domain ) : return dom . axes elif isinstance ( dom , dict ) : axes = { } for thisdom in list ( dom . values ( ) ) : assert isinstance ( thisdom , _Domain ) axes . update ( thisdom . axes ) return axes else : raise TypeError ( 'dom must be a domain or dictionary of domains.' ) | Returns a dictionary of all Axis in a domain or dictionary of domains . | 124 | 14 |
239,526 | def add_subprocesses ( self , procdict ) : if isinstance ( procdict , Process ) : try : name = procdict . name except : name = 'default' self . add_subprocess ( name , procdict ) else : for name , proc in procdict . items ( ) : self . add_subprocess ( name , proc ) | Adds a dictionary of subproceses to this process . | 80 | 12 |
239,527 | def add_subprocess ( self , name , proc ) : if isinstance ( proc , Process ) : self . subprocess . update ( { name : proc } ) self . has_process_type_list = False # Add subprocess diagnostics to parent # (if there are no name conflicts) for diagname , value in proc . diagnostics . items ( ) : #if not (diagname in self.diagnostics or hasattr(self, diagname)): # self.add_diagnostic(diagname, value) self . add_diagnostic ( diagname , value ) else : raise ValueError ( 'subprocess must be Process object' ) | Adds a single subprocess to this process . | 144 | 9 |
239,528 | def remove_subprocess ( self , name , verbose = True ) : try : self . subprocess . pop ( name ) except KeyError : if verbose : print ( 'WARNING: {} not found in subprocess dictionary.' . format ( name ) ) self . has_process_type_list = False | Removes a single subprocess from this process . | 65 | 10 |
239,529 | def set_state ( self , name , value ) : if isinstance ( value , Field ) : # populate domains dictionary with domains from state variables self . domains . update ( { name : value . domain } ) else : try : thisdom = self . state [ name ] . domain domshape = thisdom . shape except : raise ValueError ( 'State variable needs a domain.' ) value = np . atleast_1d ( value ) if value . shape == domshape : value = Field ( value , domain = thisdom ) else : raise ValueError ( 'Shape mismatch between existing domain and new state variable.' ) # set the state dictionary self . state [ name ] = value for name , value in self . state . items ( ) : #convert int dtype to float if np . issubdtype ( self . state [ name ] . dtype , np . dtype ( 'int' ) . type ) : value = self . state [ name ] . astype ( float ) self . state [ name ] = value self . __setattr__ ( name , value ) | Sets the variable name to a new state value . | 228 | 11 |
239,530 | def _add_field ( self , field_type , name , value ) : try : self . __getattribute__ ( field_type ) . update ( { name : value } ) except : raise ValueError ( 'Problem with field_type %s' % field_type ) # Note that if process has attribute name, this will trigger The # setter method for that attribute self . __setattr__ ( name , value ) | Adds a new field to a specified dictionary . The field is also added as a process attribute . field_type can be input diagnostics | 90 | 27 |
239,531 | def add_diagnostic ( self , name , value = None ) : self . _diag_vars . append ( name ) self . __setattr__ ( name , value ) | Create a new diagnostic variable called name for this process and initialize it with the given value . | 39 | 18 |
239,532 | def add_input ( self , name , value = None ) : self . _input_vars . append ( name ) self . __setattr__ ( name , value ) | Create a new input variable called name for this process and initialize it with the given value . | 37 | 18 |
239,533 | def remove_diagnostic ( self , name ) : #_ = self.diagnostics.pop(name) #delattr(type(self), name) try : delattr ( self , name ) self . _diag_vars . remove ( name ) except : print ( 'No diagnostic named {} was found.' . format ( name ) ) | Removes a diagnostic from the process . diagnostic dictionary and also delete the associated process attribute . | 73 | 18 |
239,534 | def to_xarray ( self , diagnostics = False ) : if diagnostics : dic = self . state . copy ( ) dic . update ( self . diagnostics ) return state_to_xarray ( dic ) else : return state_to_xarray ( self . state ) | Convert process variables to xarray . Dataset format . | 63 | 13 |
239,535 | def diagnostics ( self ) : diag_dict = { } for key in self . _diag_vars : try : #diag_dict[key] = getattr(self,key) # using self.__dict__ doesn't count diagnostics defined as properties diag_dict [ key ] = self . __dict__ [ key ] except : pass return diag_dict | Dictionary access to all diagnostic variables | 83 | 7 |
239,536 | def input ( self ) : input_dict = { } for key in self . _input_vars : try : input_dict [ key ] = getattr ( self , key ) except : pass return input_dict | Dictionary access to all input variables | 46 | 7 |
239,537 | def _get_Berger_data ( verbose = True ) : # The first column of the data file is used as the row index, and represents kyr from present orbit91_pd , path = load_data_source ( local_path = local_path , remote_source_list = [ threddspath , NCDCpath ] , open_method = pd . read_csv , open_method_kwargs = { 'delim_whitespace' : True , 'skiprows' : 1 } , verbose = verbose , ) # As xarray structure with the dimension named 'kyear' orbit = xr . Dataset ( orbit91_pd ) . rename ( { 'dim_0' : 'kyear' } ) # Now change names orbit = orbit . rename ( { 'ECC' : 'ecc' , 'OMEGA' : 'long_peri' , 'OBL' : 'obliquity' , 'PREC' : 'precession' } ) # add 180 degrees to long_peri (see lambda definition, Berger 1978 Appendix) orbit [ 'long_peri' ] += 180. orbit [ 'precession' ] *= - 1. orbit . attrs [ 'Description' ] = 'The Berger and Loutre (1991) orbital data table' orbit . attrs [ 'Citation' ] = 'https://doi.org/10.1016/0277-3791(91)90033-Q' orbit . attrs [ 'Source' ] = path orbit . attrs [ 'Note' ] = 'Longitude of perihelion is defined to be 0 degrees at Northern Vernal Equinox. This differs by 180 degrees from orbit91 source file.' return orbit | Read in the Berger and Loutre orbital table as a pandas dataframe convert to xarray | 374 | 20 |
239,538 | def load_data_source ( local_path , remote_source_list , open_method , open_method_kwargs = dict ( ) , remote_kwargs = dict ( ) , verbose = True ) : try : path = local_path data = open_method ( path , * * open_method_kwargs ) if verbose : print ( 'Opened data from {}' . format ( path ) ) #except FileNotFoundError: # this is a more specific exception in Python 3 except IOError : # works for Py2.7 and Py3.x # First try to load from remote sources and cache the file locally for source in remote_source_list : try : response = _download_and_cache ( source , local_path ) data = open_method ( local_path , * * open_method_kwargs ) if verbose : print ( 'Data retrieved from {} and saved locally.' . format ( source ) ) break except Exception : continue else : # as a final resort, try opening the source remotely for source in remote_source_list : path = source try : # This works fine for Python >= 3.5 #data = open_method(path, **open_method_kwargs, **remote_kwargs) data = open_method ( path , * * merge_two_dicts ( open_method_kwargs , remote_kwargs ) ) if verbose : print ( 'Opened data remotely from {}' . format ( source ) ) break except Exception : continue else : raise Exception ( 'All data access methods have failed.' ) return data , path | Flexible data retreiver to download and cache the data files locally . | 340 | 16 |
239,539 | def tril ( array , k = 0 ) : try : tril_array = np . tril ( array , k = k ) except : # have to loop tril_array = np . zeros_like ( array ) shape = array . shape otherdims = shape [ : - 2 ] for index in np . ndindex ( otherdims ) : tril_array [ index ] = np . tril ( array [ index ] , k = k ) return tril_array | Lower triangle of an array . Return a copy of an array with elements above the k - th diagonal zeroed . Need a multi - dimensional version here because numpy . tril does not broadcast for numpy verison < 1 . 9 . | 105 | 49 |
239,540 | def flux_up ( self , fluxUpBottom , emission = None ) : if emission is None : emission = np . zeros_like ( self . absorptivity ) E = np . concatenate ( ( emission , np . atleast_1d ( fluxUpBottom ) ) , axis = - 1 ) # dot product (matrix multiplication) along last axes return np . squeeze ( matrix_multiply ( self . Tup , E [ ... , np . newaxis ] ) ) | Compute downwelling radiative flux at interfaces between layers . | 104 | 13 |
239,541 | def flux_down ( self , fluxDownTop , emission = None ) : if emission is None : emission = np . zeros_like ( self . absorptivity ) E = np . concatenate ( ( np . atleast_1d ( fluxDownTop ) , emission ) , axis = - 1 ) # dot product (matrix multiplication) along last axes return np . squeeze ( matrix_multiply ( self . Tdown , E [ ... , np . newaxis ] ) ) | Compute upwelling radiative flux at interfaces between layers . | 105 | 13 |
239,542 | def interface_temperature ( Ts , Tatm , * * kwargs ) : # Actually it's not clear to me how the RRTM code uses these values lev = Tatm . domain . axes [ 'lev' ] . points lev_bounds = Tatm . domain . axes [ 'lev' ] . bounds # Interpolate to layer interfaces f = interp1d ( lev , Tatm , axis = - 1 ) # interpolation function Tinterp = f ( lev_bounds [ 1 : - 1 ] ) # add TOA value, Assume surface temperature at bottom boundary Ttoa = Tatm [ ... , 0 ] Tinterp = np . concatenate ( ( Ttoa [ ... , np . newaxis ] , Tinterp , Ts ) , axis = - 1 ) return Tinterp | Compute temperature at model layer interfaces . | 176 | 8 |
239,543 | def moist_amplification_factor ( Tkelvin , relative_humidity = 0.8 ) : deltaT = 0.01 # slope of saturation specific humidity at 1000 hPa dqsdTs = ( qsat ( Tkelvin + deltaT / 2 , 1000. ) - qsat ( Tkelvin - deltaT / 2 , 1000. ) ) / deltaT return const . Lhvap / const . cp * relative_humidity * dqsdTs | Compute the moisture amplification factor for the moist diffusivity given relative humidity and reference temperature profile . | 104 | 20 |
239,544 | def daily_insolation ( lat , day , orb = const . orb_present , S0 = const . S0 , day_type = 1 ) : # Inputs can be scalar, numpy vector, or xarray.DataArray. # If numpy, convert to xarray so that it will broadcast correctly lat_is_xarray = True day_is_xarray = True if type ( lat ) is np . ndarray : lat_is_xarray = False lat = xr . DataArray ( lat , coords = [ lat ] , dims = [ 'lat' ] ) if type ( day ) is np . ndarray : day_is_xarray = False day = xr . DataArray ( day , coords = [ day ] , dims = [ 'day' ] ) ecc = orb [ 'ecc' ] long_peri = orb [ 'long_peri' ] obliquity = orb [ 'obliquity' ] # Convert precession angle and latitude to radians phi = deg2rad ( lat ) # lambda_long (solar longitude) is the angular distance along Earth's orbit measured from spring equinox (21 March) if day_type == 1 : # calendar days lambda_long = solar_longitude ( day , orb ) elif day_type == 2 : #solar longitude (1-360) is specified in input, no need to convert days to longitude lambda_long = deg2rad ( day ) else : raise ValueError ( 'Invalid day_type.' ) # Compute declination angle of the sun delta = arcsin ( sin ( deg2rad ( obliquity ) ) * sin ( lambda_long ) ) # suppress warning message generated by arccos here! oldsettings = np . seterr ( invalid = 'ignore' ) # Compute Ho, the hour angle at sunrise / sunset # Check for no sunrise or no sunset: Berger 1978 eqn (8),(9) Ho = xr . where ( abs ( delta ) - pi / 2 + abs ( phi ) < 0. , # there is sunset/sunrise arccos ( - tan ( phi ) * tan ( delta ) ) , # otherwise figure out if it's all night or all day xr . where ( phi * delta > 0. , pi , 0. ) ) # this is not really the daily average cosine of the zenith angle... # it's the integral from sunrise to sunset of that quantity... coszen = Ho * sin ( phi ) * sin ( delta ) + cos ( phi ) * cos ( delta ) * sin ( Ho ) # Compute insolation: Berger 1978 eq (10) Fsw = S0 / pi * ( ( 1 + ecc * cos ( lambda_long - deg2rad ( long_peri ) ) ) ** 2 / ( 1 - ecc ** 2 ) ** 2 * coszen ) if not ( lat_is_xarray or day_is_xarray ) : # Dimensional ordering consistent with previous numpy code return Fsw . transpose ( ) . values else : return Fsw | Compute daily average insolation given latitude time of year and orbital parameters . | 668 | 15 |
239,545 | def solar_longitude ( day , orb = const . orb_present , days_per_year = None ) : if days_per_year is None : days_per_year = const . days_per_year ecc = orb [ 'ecc' ] long_peri_rad = deg2rad ( orb [ 'long_peri' ] ) delta_lambda = ( day - 80. ) * 2 * pi / days_per_year beta = sqrt ( 1 - ecc ** 2 ) lambda_long_m = - 2 * ( ( ecc / 2 + ( ecc ** 3 ) / 8 ) * ( 1 + beta ) * sin ( - long_peri_rad ) - ( ecc ** 2 ) / 4 * ( 1 / 2 + beta ) * sin ( - 2 * long_peri_rad ) + ( ecc ** 3 ) / 8 * ( 1 / 3 + beta ) * sin ( - 3 * long_peri_rad ) ) + delta_lambda lambda_long = ( lambda_long_m + ( 2 * ecc - ( ecc ** 3 ) / 4 ) * sin ( lambda_long_m - long_peri_rad ) + ( 5 / 4 ) * ( ecc ** 2 ) * sin ( 2 * ( lambda_long_m - long_peri_rad ) ) + ( 13 / 12 ) * ( ecc ** 3 ) * sin ( 3 * ( lambda_long_m - long_peri_rad ) ) ) return lambda_long | Estimates solar longitude from calendar day . | 320 | 9 |
239,546 | def single_column ( num_lev = 30 , water_depth = 1. , lev = None , * * kwargs ) : if lev is None : levax = Axis ( axis_type = 'lev' , num_points = num_lev ) elif isinstance ( lev , Axis ) : levax = lev else : try : levax = Axis ( axis_type = 'lev' , points = lev ) except : raise ValueError ( 'lev must be Axis object or pressure array' ) depthax = Axis ( axis_type = 'depth' , bounds = [ water_depth , 0. ] ) slab = SlabOcean ( axes = depthax , * * kwargs ) atm = Atmosphere ( axes = levax , * * kwargs ) return slab , atm | Creates domains for a single column of atmosphere overlying a slab of water . | 170 | 16 |
239,547 | def zonal_mean_surface ( num_lat = 90 , water_depth = 10. , lat = None , * * kwargs ) : if lat is None : latax = Axis ( axis_type = 'lat' , num_points = num_lat ) elif isinstance ( lat , Axis ) : latax = lat else : try : latax = Axis ( axis_type = 'lat' , points = lat ) except : raise ValueError ( 'lat must be Axis object or latitude array' ) depthax = Axis ( axis_type = 'depth' , bounds = [ water_depth , 0. ] ) axes = { 'depth' : depthax , 'lat' : latax } slab = SlabOcean ( axes = axes , * * kwargs ) return slab | Creates a 1D slab ocean Domain in latitude with uniform water depth . | 169 | 15 |
239,548 | def surface_2D ( num_lat = 90 , num_lon = 180 , water_depth = 10. , lon = None , lat = None , * * kwargs ) : if lat is None : latax = Axis ( axis_type = 'lat' , num_points = num_lat ) elif isinstance ( lat , Axis ) : latax = lat else : try : latax = Axis ( axis_type = 'lat' , points = lat ) except : raise ValueError ( 'lat must be Axis object or latitude array' ) if lon is None : lonax = Axis ( axis_type = 'lon' , num_points = num_lon ) elif isinstance ( lon , Axis ) : lonax = lon else : try : lonax = Axis ( axis_type = 'lon' , points = lon ) except : raise ValueError ( 'lon must be Axis object or longitude array' ) depthax = Axis ( axis_type = 'depth' , bounds = [ water_depth , 0. ] ) axes = { 'lat' : latax , 'lon' : lonax , 'depth' : depthax } slab = SlabOcean ( axes = axes , * * kwargs ) return slab | Creates a 2D slab ocean Domain in latitude and longitude with uniform water depth . | 272 | 18 |
239,549 | def _make_axes_dict ( self , axes ) : if type ( axes ) is dict : axdict = axes elif type ( axes ) is Axis : ax = axes axdict = { ax . axis_type : ax } elif axes is None : axdict = { 'empty' : None } else : raise ValueError ( 'axes needs to be Axis object or dictionary of Axis object' ) return axdict | Makes an axes dictionary . | 90 | 6 |
239,550 | def _compute ( self ) : newstate = self . _implicit_solver ( ) adjustment = { } tendencies = { } for name , var in self . state . items ( ) : adjustment [ name ] = newstate [ name ] - var tendencies [ name ] = adjustment [ name ] / self . timestep # express the adjustment (already accounting for the finite time step) # as a tendency per unit time, so that it can be applied along with explicit self . adjustment = adjustment self . _update_diagnostics ( newstate ) return tendencies | Computes the state variable tendencies in time for implicit processes . | 118 | 12 |
239,551 | def walk_processes ( top , topname = 'top' , topdown = True , ignoreFlag = False ) : if not ignoreFlag : flag = topdown else : flag = True proc = top level = 0 if flag : yield topname , proc , level if len ( proc . subprocess ) > 0 : # there are sub-processes level += 1 for name , subproc in proc . subprocess . items ( ) : for name2 , subproc2 , level2 in walk_processes ( subproc , topname = name , topdown = subproc . topdown , ignoreFlag = ignoreFlag ) : yield name2 , subproc2 , level + level2 if not flag : yield topname , proc , level | Generator for recursive tree of climlab processes | 155 | 9 |
239,552 | def process_tree ( top , name = 'top' ) : str1 = '' for name , proc , level in walk_processes ( top , name , ignoreFlag = True ) : indent = ' ' * 3 * ( level ) str1 += ( '{}{}: {}\n' . format ( indent , name , type ( proc ) ) ) return str1 | Creates a string representation of the process tree for process top . | 78 | 13 |
239,553 | def _compute_fluxes ( self ) : self . emission = self . _compute_emission ( ) self . emission_sfc = self . _compute_emission_sfc ( ) fromspace = self . _from_space ( ) self . flux_down = self . trans . flux_down ( fromspace , self . emission ) self . flux_reflected_up = self . trans . flux_reflected_up ( self . flux_down , self . albedo_sfc ) # this ensure same dimensions as other fields self . flux_to_sfc = self . flux_down [ ... , - 1 , np . newaxis ] self . flux_from_sfc = ( self . emission_sfc + self . flux_reflected_up [ ... , - 1 , np . newaxis ] ) self . flux_up = self . trans . flux_up ( self . flux_from_sfc , self . emission + self . flux_reflected_up [ ... , 0 : - 1 ] ) self . flux_net = self . flux_up - self . flux_down # absorbed radiation (flux convergence) in W / m**2 (per band) self . absorbed = np . diff ( self . flux_net , axis = - 1 ) self . absorbed_total = np . sum ( self . absorbed , axis = - 1 ) self . flux_to_space = self . _compute_flux_top ( ) | All fluxes are band by band | 320 | 7 |
239,554 | def flux_components_top ( self ) : N = self . lev . size flux_up_bottom = self . flux_from_sfc emission = np . zeros_like ( self . emission ) this_flux_up = ( np . ones_like ( self . Ts ) * self . trans . flux_up ( flux_up_bottom , emission ) ) sfcComponent = this_flux_up [ ... , - 1 ] atmComponents = np . zeros_like ( self . Tatm ) flux_up_bottom = np . zeros_like ( self . Ts ) # I'm sure there's a way to write this as a vectorized operation # but the speed doesn't really matter if it's just for diagnostic # and we are not calling it every timestep for n in range ( N ) : emission = np . zeros_like ( self . emission ) emission [ ... , n ] = self . emission [ ... , n ] this_flux_up = self . trans . flux_up ( flux_up_bottom , emission ) atmComponents [ ... , n ] = this_flux_up [ ... , - 1 ] return sfcComponent , atmComponents | Compute the contributions to the outgoing flux to space due to emissions from each level and the surface . | 262 | 20 |
239,555 | def flux_components_bottom ( self ) : N = self . lev . size atmComponents = np . zeros_like ( self . Tatm ) flux_down_top = np . zeros_like ( self . Ts ) # same comment as above... would be nice to vectorize for n in range ( N ) : emission = np . zeros_like ( self . emission ) emission [ ... , n ] = self . emission [ ... , n ] this_flux_down = self . trans . flux_down ( flux_down_top , emission ) atmComponents [ ... , n ] = this_flux_down [ ... , 0 ] return atmComponents | Compute the contributions to the downwelling flux to surface due to emissions from each level . | 149 | 19 |
239,556 | def _compute ( self ) : tendencies = self . _temperature_tendencies ( ) if 'q' in self . state : # in a model with active water vapor, this flux should affect # water vapor tendency, NOT air temperature tendency! tendencies [ 'Tatm' ] *= 0. Pa_per_hPa = 100. air_mass_per_area = self . Tatm . domain . lev . delta [ ... , - 1 ] * Pa_per_hPa / const . g specific_humidity_tendency = 0. * self . q specific_humidity_tendency [ ... , - 1 , np . newaxis ] = self . LHF / const . Lhvap / air_mass_per_area tendencies [ 'q' ] = specific_humidity_tendency return tendencies | Overides the _compute method of EnergyBudget | 180 | 11 |
239,557 | def Pn ( x ) : Pn = { } Pn [ '0' ] = P0 ( x ) Pn [ '1' ] = P1 ( x ) Pn [ '2' ] = P2 ( x ) Pn [ '3' ] = P3 ( x ) Pn [ '4' ] = P4 ( x ) Pn [ '5' ] = P5 ( x ) Pn [ '6' ] = P6 ( x ) Pn [ '8' ] = P8 ( x ) Pn [ '10' ] = P10 ( x ) Pn [ '12' ] = P12 ( x ) Pn [ '14' ] = P14 ( x ) Pn [ '16' ] = P16 ( x ) Pn [ '18' ] = P18 ( x ) Pn [ '20' ] = P20 ( x ) Pn [ '22' ] = P22 ( x ) Pn [ '24' ] = P24 ( x ) Pn [ '26' ] = P26 ( x ) Pn [ '28' ] = P28 ( x ) return Pn | Calculate Legendre polyomials P0 to P28 and returns them in a dictionary Pn . | 249 | 22 |
239,558 | def Pnprime ( x ) : Pnprime = { } Pnprime [ '0' ] = 0 Pnprime [ '1' ] = P1prime ( x ) Pnprime [ '2' ] = P2prime ( x ) Pnprime [ '3' ] = P3prime ( x ) Pnprime [ '4' ] = P4prime ( x ) Pnprime [ '6' ] = P6prime ( x ) Pnprime [ '8' ] = P8prime ( x ) Pnprime [ '10' ] = P10prime ( x ) Pnprime [ '12' ] = P12prime ( x ) Pnprime [ '14' ] = P14prime ( x ) return Pnprime | Calculates first derivatives of Legendre polynomials and returns them in a dictionary Pnprime . | 163 | 22 |
239,559 | def inferred_heat_transport ( self ) : phi = np . deg2rad ( self . lat ) energy_in = np . squeeze ( self . net_radiation ) return ( 1E-15 * 2 * np . math . pi * const . a ** 2 * integrate . cumtrapz ( np . cos ( phi ) * energy_in , x = phi , initial = 0. ) ) | Calculates the inferred heat transport by integrating the TOA energy imbalance from pole to pole . | 89 | 19 |
239,560 | def rrtmg_lw_gen_source ( ext , build_dir ) : thispath = config . local_path module_src = [ ] for item in modules : fullname = join ( thispath , 'rrtmg_lw_v4.85' , 'gcm_model' , 'modules' , item ) module_src . append ( fullname ) for item in src : if item in mod_src : fullname = join ( thispath , 'sourcemods' , item ) else : fullname = join ( thispath , 'rrtmg_lw_v4.85' , 'gcm_model' , 'src' , item ) module_src . append ( fullname ) sourcelist = [ join ( thispath , '_rrtmg_lw.pyf' ) , join ( thispath , 'Driver.f90' ) ] try : config . have_f90c ( ) return module_src + sourcelist except : print ( 'No Fortran 90 compiler found, not building RRTMG_LW extension!' ) return None | Add RRTMG_LW fortran source if Fortran 90 compiler available if no compiler is found do not try to build the extension . | 234 | 30 |
239,561 | def compute ( self ) : # First reset tendencies to zero -- recomputing them is the point of this method for varname in self . tendencies : self . tendencies [ varname ] *= 0. if not self . has_process_type_list : self . _build_process_type_list ( ) tendencies = { } ignored = self . _compute_type ( 'diagnostic' ) tendencies [ 'explicit' ] = self . _compute_type ( 'explicit' ) # Tendencies due to implicit and adjustment processes need to be # calculated from a state that is already adjusted after explicit stuff # So apply the tendencies temporarily and then remove them again for name , var in self . state . items ( ) : var += tendencies [ 'explicit' ] [ name ] * self . timestep # Now compute all implicit processes -- matrix inversions tendencies [ 'implicit' ] = self . _compute_type ( 'implicit' ) # Same deal ... temporarily apply tendencies from implicit step for name , var in self . state . items ( ) : var += tendencies [ 'implicit' ] [ name ] * self . timestep # Finally compute all instantaneous adjustments -- expressed as explicit forward step tendencies [ 'adjustment' ] = self . _compute_type ( 'adjustment' ) # Now remove the changes from the model state for name , var in self . state . items ( ) : var -= ( ( tendencies [ 'implicit' ] [ name ] + tendencies [ 'explicit' ] [ name ] ) * self . timestep ) # Sum up all subprocess tendencies for proctype in [ 'explicit' , 'implicit' , 'adjustment' ] : for varname , tend in tendencies [ proctype ] . items ( ) : self . tendencies [ varname ] += tend # Finally compute my own tendencies, if any self_tend = self . _compute ( ) # Adjustment processes _compute method returns absolute adjustment # Needs to be converted to rate of change if self . time_type is 'adjustment' : for varname , adj in self_tend . items ( ) : self_tend [ varname ] /= self . timestep for varname , tend in self_tend . items ( ) : self . tendencies [ varname ] += tend return self . tendencies | Computes the tendencies for all state variables given current state and specified input . | 498 | 15 |
239,562 | def _compute_type ( self , proctype ) : tendencies = { } for varname in self . state : tendencies [ varname ] = 0. * self . state [ varname ] for proc in self . process_types [ proctype ] : # Asynchronous coupling # if subprocess has longer timestep than parent # We compute subprocess tendencies once # and apply the same tendency at each substep step_ratio = int ( proc . timestep / self . timestep ) # Does the number of parent steps divide evenly by the ratio? # If so, it's time to do a subprocess step. if self . time [ 'steps' ] % step_ratio == 0 : proc . time [ 'active_now' ] = True tenddict = proc . compute ( ) else : # proc.tendencies is unchanged from last subprocess timestep if we didn't recompute it above proc . time [ 'active_now' ] = False tenddict = proc . tendencies for name , tend in tenddict . items ( ) : tendencies [ name ] += tend for diagname , value in proc . diagnostics . items ( ) : self . __setattr__ ( diagname , value ) return tendencies | Computes tendencies due to all subprocesses of given type proctype . Also pass all diagnostics up to parent process . | 263 | 26 |
239,563 | def _compute ( self ) : tendencies = { } for name , value in self . state . items ( ) : tendencies [ name ] = value * 0. return tendencies | Where the tendencies are actually computed ... | 36 | 7 |
239,564 | def _build_process_type_list ( self ) : self . process_types = { 'diagnostic' : [ ] , 'explicit' : [ ] , 'implicit' : [ ] , 'adjustment' : [ ] } #for name, proc, level in walk.walk_processes(self, topdown=self.topdown): # self.process_types[proc.time_type].append(proc) for name , proc in self . subprocess . items ( ) : self . process_types [ proc . time_type ] . append ( proc ) self . has_process_type_list = True | Generates lists of processes organized by process type . | 136 | 10 |
239,565 | def step_forward ( self ) : tenddict = self . compute ( ) # Total tendency is applied as an explicit forward timestep # (already accounting properly for order of operations in compute() ) for varname , tend in tenddict . items ( ) : self . state [ varname ] += tend * self . timestep # Update all time counters for this and all subprocesses in the tree # Also pass diagnostics up the process tree for name , proc , level in walk . walk_processes ( self , ignoreFlag = True ) : if proc . time [ 'active_now' ] : proc . _update_time ( ) | Updates state variables with computed tendencies . | 136 | 8 |
239,566 | def _update_time ( self ) : self . time [ 'steps' ] += 1 # time in days since beginning self . time [ 'days_elapsed' ] += self . time [ 'timestep' ] / const . seconds_per_day if self . time [ 'day_of_year_index' ] >= self . time [ 'num_steps_per_year' ] - 1 : self . _do_new_calendar_year ( ) else : self . time [ 'day_of_year_index' ] += 1 | Increments the timestep counter by one . | 119 | 10 |
239,567 | def integrate_years ( self , years = 1.0 , verbose = True ) : days = years * const . days_per_year numsteps = int ( self . time [ 'num_steps_per_year' ] * years ) if verbose : print ( "Integrating for " + str ( numsteps ) + " steps, " + str ( days ) + " days, or " + str ( years ) + " years." ) # begin time loop for count in range ( numsteps ) : # Compute the timestep self . step_forward ( ) if count == 0 : # on first step only... # This implements a generic time-averaging feature # using the list of model state variables self . timeave = self . state . copy ( ) # add any new diagnostics to the timeave dictionary self . timeave . update ( self . diagnostics ) # reset all values to zero for varname , value in self . timeave . items ( ) : # moves on to the next varname if value is None # this preserves NoneType diagnostics if value is None : continue self . timeave [ varname ] = 0 * value # adding up all values for each timestep for varname in list ( self . timeave . keys ( ) ) : try : self . timeave [ varname ] += self . state [ varname ] except : try : self . timeave [ varname ] += self . diagnostics [ varname ] except : pass # calculating mean values through dividing the sum by number of steps for varname , value in self . timeave . items ( ) : if value is None : continue self . timeave [ varname ] /= numsteps if verbose : print ( "Total elapsed time is %s years." % str ( self . time [ 'days_elapsed' ] / const . days_per_year ) ) | Integrates the model by a given number of years . | 396 | 11 |
239,568 | def integrate_days ( self , days = 1.0 , verbose = True ) : years = days / const . days_per_year self . integrate_years ( years = years , verbose = verbose ) | Integrates the model forward for a specified number of days . | 46 | 12 |
239,569 | def integrate_converge ( self , crit = 1e-4 , verbose = True ) : # implemented by m-kreuzer for varname , value in self . state . items ( ) : value_old = copy . deepcopy ( value ) self . integrate_years ( 1 , verbose = False ) while np . max ( np . abs ( value_old - value ) ) > crit : value_old = copy . deepcopy ( value ) self . integrate_years ( 1 , verbose = False ) if verbose == True : print ( "Total elapsed time is %s years." % str ( self . time [ 'days_elapsed' ] / const . days_per_year ) ) | Integrates the model until model states are converging . | 153 | 11 |
239,570 | def cam3_gen_source ( ext , build_dir ) : # Fortran 90 sources in order of compilation fort90source = [ 'pmgrid.F90' , 'prescribed_aerosols.F90' , 'shr_kind_mod.F90' , 'quicksort.F90' , 'abortutils.F90' , 'absems.F90' , 'wv_saturation.F90' , 'aer_optics.F90' , 'cmparray_mod.F90' , 'shr_const_mod.F90' , 'physconst.F90' , 'pkg_cldoptics.F90' , 'gffgch.F90' , 'chem_surfvals.F90' , 'volcrad.F90' , 'radae.F90' , 'radlw.F90' , 'radsw.F90' , 'crm.F90' , ] #thispath = abspath(config.local_path) thispath = config . local_path sourcelist = [ ] sourcelist . append ( join ( thispath , '_cam3.pyf' ) ) for item in fort90source : sourcelist . append ( join ( thispath , 'src' , item ) ) sourcelist . append ( join ( thispath , 'Driver.f90' ) ) try : config . have_f90c ( ) return sourcelist except : print ( 'No Fortran 90 compiler found, not building CAM3 extension!' ) return None | Add CAM3 fortran source if Fortran 90 compiler available if no compiler is found do not try to build the extension . | 337 | 26 |
239,571 | def global_mean ( field ) : try : lat = field . domain . lat . points except : raise ValueError ( 'No latitude axis in input field.' ) try : # Field is 2D latitude / longitude lon = field . domain . lon . points return _global_mean_latlon ( field . squeeze ( ) ) except : # Field is 1D latitude only (zonal average) lat_radians = np . deg2rad ( lat ) return _global_mean ( field . squeeze ( ) , lat_radians ) | Calculates the latitude weighted global mean of a field with latitude dependence . | 115 | 15 |
239,572 | def to_latlon ( array , domain , axis = 'lon' ) : # if array is latitude dependent (has the same shape as lat) axis , array , depth = np . meshgrid ( domain . axes [ axis ] . points , array , domain . axes [ 'depth' ] . points ) if axis == 'lat' : # if array is longitude dependent (has the same shape as lon) np . swapaxes ( array , 1 , 0 ) return Field ( array , domain = domain ) | Broadcasts a 1D axis dependent array across another axis . | 108 | 12 |
239,573 | def Field_to_xarray ( field ) : dom = field . domain dims = [ ] dimlist = [ ] coords = { } for axname in dom . axes : dimlist . append ( axname ) try : assert field . interfaces [ dom . axis_index [ axname ] ] bounds_name = axname + '_bounds' dims . append ( bounds_name ) coords [ bounds_name ] = dom . axes [ axname ] . bounds except : dims . append ( axname ) coords [ axname ] = dom . axes [ axname ] . points # Might need to reorder the data da = DataArray ( field . transpose ( [ dom . axis_index [ name ] for name in dimlist ] ) , dims = dims , coords = coords ) for name in dims : try : da [ name ] . attrs [ 'units' ] = dom . axes [ name ] . units except : pass return da | Convert a climlab . Field object to xarray . DataArray | 209 | 14 |
239,574 | def state_to_xarray ( state ) : from climlab . domain . field import Field ds = Dataset ( ) for name , field in state . items ( ) : if isinstance ( field , Field ) : ds [ name ] = Field_to_xarray ( field ) dom = field . domain for axname , ax in dom . axes . items ( ) : bounds_name = axname + '_bounds' ds . coords [ bounds_name ] = DataArray ( ax . bounds , dims = [ bounds_name ] , coords = { bounds_name : ax . bounds } ) try : ds [ bounds_name ] . attrs [ 'units' ] = ax . units except : pass else : warnings . warn ( '{} excluded from Dataset because it is not a Field variable.' . format ( name ) ) return ds | Convert a dictionary of climlab . Field objects to xarray . Dataset | 189 | 17 |
239,575 | def to_xarray ( input ) : from climlab . domain . field import Field if isinstance ( input , Field ) : return Field_to_xarray ( input ) elif isinstance ( input , dict ) : return state_to_xarray ( input ) else : raise TypeError ( 'input must be Field object or dictionary of Field objects' ) | Convert climlab input to xarray format . | 76 | 10 |
239,576 | def generate ( data , dimOrder , maxWindowSize , overlapPercent , transforms = [ ] ) : # Determine the dimensions of the input data width = data . shape [ dimOrder . index ( 'w' ) ] height = data . shape [ dimOrder . index ( 'h' ) ] # Generate the windows return generateForSize ( width , height , dimOrder , maxWindowSize , overlapPercent , transforms ) | Generates a set of sliding windows for the specified dataset . | 88 | 12 |
239,577 | def generateForSize ( width , height , dimOrder , maxWindowSize , overlapPercent , transforms = [ ] ) : # If the input data is smaller than the specified window size, # clip the window size to the input size on both dimensions windowSizeX = min ( maxWindowSize , width ) windowSizeY = min ( maxWindowSize , height ) # Compute the window overlap and step size windowOverlapX = int ( math . floor ( windowSizeX * overlapPercent ) ) windowOverlapY = int ( math . floor ( windowSizeY * overlapPercent ) ) stepSizeX = windowSizeX - windowOverlapX stepSizeY = windowSizeY - windowOverlapY # Determine how many windows we will need in order to cover the input data lastX = width - windowSizeX lastY = height - windowSizeY xOffsets = list ( range ( 0 , lastX + 1 , stepSizeX ) ) yOffsets = list ( range ( 0 , lastY + 1 , stepSizeY ) ) # Unless the input data dimensions are exact multiples of the step size, # we will need one additional row and column of windows to get 100% coverage if len ( xOffsets ) == 0 or xOffsets [ - 1 ] != lastX : xOffsets . append ( lastX ) if len ( yOffsets ) == 0 or yOffsets [ - 1 ] != lastY : yOffsets . append ( lastY ) # Generate the list of windows windows = [ ] for xOffset in xOffsets : for yOffset in yOffsets : for transform in [ None ] + transforms : windows . append ( SlidingWindow ( x = xOffset , y = yOffset , w = windowSizeX , h = windowSizeY , dimOrder = dimOrder , transform = transform ) ) return windows | Generates a set of sliding windows for a dataset with the specified dimensions and order . | 387 | 17 |
239,578 | def apply ( self , matrix ) : view = matrix [ self . indices ( ) ] return self . transform ( view ) if self . transform != None else view | Slices the supplied matrix and applies any transform bound to this window | 33 | 14 |
239,579 | def indices ( self , includeChannel = True ) : if self . dimOrder == DimOrder . HeightWidthChannel : # Equivalent to [self.y:self.y+self.h+1, self.x:self.x+self.w+1] return ( slice ( self . y , self . y + self . h ) , slice ( self . x , self . x + self . w ) ) elif self . dimOrder == DimOrder . ChannelHeightWidth : if includeChannel is True : # Equivalent to [:, self.y:self.y+self.h+1, self.x:self.x+self.w+1] return ( slice ( None , None ) , slice ( self . y , self . y + self . h ) , slice ( self . x , self . x + self . w ) ) else : # Equivalent to [self.y:self.y+self.h+1, self.x:self.x+self.w+1] return ( slice ( self . y , self . y + self . h ) , slice ( self . x , self . x + self . w ) ) else : raise Error ( 'Unsupported order of dimensions: ' + str ( self . dimOrder ) ) | Retrieves the indices for this window as a tuple of slices | 271 | 13 |
239,580 | def batchWindows ( windows , batchSize ) : return np . array_split ( np . array ( windows ) , len ( windows ) // batchSize ) | Splits a list of windows into a series of batches . | 32 | 12 |
239,581 | def generateDistanceMatrix ( width , height ) : # Determine the coordinates of the exact centre of the window originX = width / 2 originY = height / 2 # Generate the distance matrix distances = zerosFactory ( ( height , width ) , dtype = np . float ) for index , val in np . ndenumerate ( distances ) : y , x = index distances [ ( y , x ) ] = math . sqrt ( math . pow ( x - originX , 2 ) + math . pow ( y - originY , 2 ) ) return distances | Generates a matrix specifying the distance of each point in a window to its centre . | 119 | 17 |
239,582 | def _requiredSize ( shape , dtype ) : return math . floor ( np . prod ( np . asarray ( shape , dtype = np . uint64 ) ) * np . dtype ( dtype ) . itemsize ) | Determines the number of bytes required to store a NumPy array with the specified shape and datatype . | 49 | 23 |
239,583 | def arrayFactory ( shape , dtype = float ) : # Determine the number of bytes required to store the array requiredBytes = _requiredSize ( shape , dtype ) # Determine if there is sufficient available memory vmem = psutil . virtual_memory ( ) if vmem . available > requiredBytes : return np . ndarray ( shape = shape , dtype = dtype ) else : return TempfileBackedArray ( shape = shape , dtype = dtype ) | Creates a new ndarray of the specified shape and datatype storing it in memory if there is sufficient available space or else using a memory - mapped temporary file to provide the underlying buffer . | 101 | 40 |
239,584 | def arrayCast ( source , dtype ) : # Determine the number of bytes required to store the array requiredBytes = _requiredSize ( source . shape , dtype ) # Determine if there is sufficient available memory vmem = psutil . virtual_memory ( ) if vmem . available > requiredBytes : return source . astype ( dtype , subok = False ) else : dest = arrayFactory ( source . shape , dtype ) np . copyto ( dest , source , casting = 'unsafe' ) return dest | Casts a NumPy array to the specified datatype storing the copy in memory if there is sufficient available space or else using a memory - mapped temporary file to provide the underlying buffer . | 111 | 38 |
239,585 | def determineMaxWindowSize ( dtype , limit = None ) : vmem = psutil . virtual_memory ( ) maxSize = math . floor ( math . sqrt ( vmem . available / np . dtype ( dtype ) . itemsize ) ) if limit is None or limit >= maxSize : return maxSize else : return limit | Determines the largest square window size that can be used based on the specified datatype and amount of currently available system memory . If limit is specified then this value will be returned in the event that it is smaller than the maximum computed size . | 72 | 50 |
239,586 | def set_state ( self , state ) : for k , v in state . items ( ) : setattr ( self , k , v ) | Set the view state . | 30 | 5 |
239,587 | def _fullname ( o ) : return o . __module__ + "." + o . __name__ if o . __module__ else o . __name__ | Return the fully - qualified name of a function . | 35 | 10 |
239,588 | def _get_axis_label ( self , dim ) : if u ( dim [ : - 1 ] ) . isdecimal ( ) : n = len ( self . channel_ids ) return str ( self . channel_ids [ int ( dim [ : - 1 ] ) % n ] ) + dim [ - 1 ] else : return dim | Return the channel id from a dimension if applicable . | 72 | 10 |
239,589 | def _get_axis_data ( self , bunch , dim , cluster_id = None , load_all = None ) : if dim in self . attributes : return self . attributes [ dim ] ( cluster_id , load_all = load_all ) masks = bunch . get ( 'masks' , None ) assert dim not in self . attributes # This is called only on PC data. s = 'ABCDEFGHIJ' # Channel relative index. c_rel = int ( dim [ : - 1 ] ) # Get the channel_id from the currently-selected channels. channel_id = self . channel_ids [ c_rel % len ( self . channel_ids ) ] # Skup the plot if the channel id is not displayed. if channel_id not in bunch . channel_ids : # pragma: no cover return None # Get the column index of the current channel in data. c = list ( bunch . channel_ids ) . index ( channel_id ) # Principal component: A=0, B=1, etc. d = s . index ( dim [ - 1 ] ) if masks is not None : masks = masks [ : , c ] return Bunch ( data = bunch . data [ : , c , d ] , masks = masks , ) | Extract the points from the data on a given dimension . | 269 | 12 |
239,590 | def _plot_labels ( self ) : # iterate simultaneously over kth row in left column and # kth column in bottom row: br = self . n_cols - 1 # bottom row for k in range ( 0 , self . n_cols ) : dim_x , _ = self . grid_dim [ 0 ] [ k ] . split ( ',' ) _ , dim_y = self . grid_dim [ k ] [ br ] . split ( ',' ) # Get the channel ids corresponding to the relative channel indices # specified in the dimensions. Channel 0 corresponds to the first # best channel for the selected cluster, and so on. dim_x = self . _get_axis_label ( dim_x ) dim_y = self . _get_axis_label ( dim_y ) # Left edge of left column of subplots. self [ k , 0 ] . text ( pos = [ - 1. , 0. ] , text = dim_y , anchor = [ - 1.03 , 0. ] , data_bounds = None , ) # Bottom edge of bottom row of subplots. self [ br , k ] . text ( pos = [ 0. , - 1. ] , text = dim_x , anchor = [ 0. , - 1.04 ] , data_bounds = None , ) | Plot feature labels along left and bottom edge of subplots | 288 | 12 |
239,591 | def on_channel_click ( self , channel_id = None , key = None , button = None ) : channels = self . channel_ids if channels is None : return if len ( channels ) == 1 : self . on_select ( ) return assert len ( channels ) >= 2 # Get the axis from the pressed button (1, 2, etc.) # axis = 'x' if button == 1 else 'y' d = 0 if button == 1 else 1 # Change the first or second best channel. old = channels [ d ] # Avoid updating the view if the channel doesn't change. if channel_id == old : return channels [ d ] = channel_id # Ensure that the first two channels are different. if channels [ 1 - d ] == channel_id : channels [ 1 - d ] = old assert channels [ 0 ] != channels [ 1 ] # Remove duplicate channels. self . channel_ids = _uniq ( channels ) logger . debug ( "Choose channels %d and %d in feature view." , * channels [ : 2 ] ) # Fix the channels temporarily. self . on_select ( fixed_channels = True ) | Respond to the click on a channel . | 241 | 9 |
239,592 | def on_request_split ( self ) : if ( self . lasso . count < 3 or not len ( self . cluster_ids ) ) : # pragma: no cover return np . array ( [ ] , dtype = np . int64 ) assert len ( self . channel_ids ) # Get the dimensions of the lassoed subplot. i , j = self . lasso . box dim = self . grid_dim [ i ] [ j ] dim_x , dim_y = dim . split ( ',' ) # Get all points from all clusters. pos = [ ] spike_ids = [ ] for cluster_id in self . cluster_ids : # Load all spikes. bunch = self . features ( cluster_id , channel_ids = self . channel_ids , load_all = True ) px = self . _get_axis_data ( bunch , dim_x , cluster_id = cluster_id , load_all = True ) py = self . _get_axis_data ( bunch , dim_y , cluster_id = cluster_id , load_all = True ) points = np . c_ [ px . data , py . data ] # Normalize the points. xmin , xmax = self . _get_axis_bounds ( dim_x , px ) ymin , ymax = self . _get_axis_bounds ( dim_y , py ) r = Range ( ( xmin , ymin , xmax , ymax ) ) points = r . apply ( points ) pos . append ( points ) spike_ids . append ( bunch . spike_ids ) pos = np . vstack ( pos ) spike_ids = np . concatenate ( spike_ids ) # Find lassoed spikes. ind = self . lasso . in_polygon ( pos ) self . lasso . clear ( ) return np . unique ( spike_ids [ ind ] ) | Return the spikes enclosed by the lasso . | 411 | 9 |
239,593 | def get_closest_box ( self , pos ) : pos = np . atleast_2d ( pos ) d = np . sum ( ( np . array ( self . box_pos ) - pos ) ** 2 , axis = 1 ) idx = np . argmin ( d ) return idx | Get the box closest to some position . | 67 | 8 |
239,594 | def update_boxes ( self , box_pos , box_size ) : assert box_pos . shape == ( self . n_boxes , 2 ) assert len ( box_size ) == 2 self . box_bounds = _get_boxes ( box_pos , size = box_size , keep_aspect_ratio = self . keep_aspect_ratio , ) | Set the box bounds from specified box positions and sizes . | 82 | 11 |
239,595 | def require_qt ( func ) : @ wraps ( func ) def wrapped ( * args , * * kwargs ) : if not QApplication . instance ( ) : # pragma: no cover raise RuntimeError ( "A Qt application must be created." ) return func ( * args , * * kwargs ) return wrapped | Specify that a function requires a Qt application . | 68 | 10 |
239,596 | def create_app ( ) : global QT_APP QT_APP = QApplication . instance ( ) if QT_APP is None : # pragma: no cover QT_APP = QApplication ( sys . argv ) return QT_APP | Create a Qt application . | 55 | 5 |
239,597 | def set ( self , f ) : self . stop ( ) self . _create_timer ( f ) self . start ( ) | Call a function after a delay unless another function is set in the meantime . | 27 | 15 |
239,598 | def stop ( self ) : if self . _timer : self . _timer . stop ( ) self . _timer . deleteLater ( ) | Stop the current timer if there is one and cancel the async call . | 29 | 14 |
239,599 | def _wrap_callback_args ( f , docstring = None ) : # pragma: no cover def wrapped ( checked , * args ) : if args : return f ( * args ) if isinstance ( f , partial ) : argspec = inspect . getargspec ( f . func ) else : argspec = inspect . getargspec ( f ) f_args = argspec . args if 'self' in f_args : f_args . remove ( 'self' ) # Remove arguments with defaults from the list. if len ( argspec . defaults or ( ) ) : f_args = f_args [ : - len ( argspec . defaults ) ] # Remove arguments supplied in a partial. if isinstance ( f , partial ) : f_args = f_args [ len ( f . args ) : ] f_args = [ arg for arg in f_args if arg not in f . keywords ] # If there are no remaining args, we can just run the fu nction. if not f_args : return f ( ) # There are args, need to display the dialog. # Extract Example: `...` in the docstring to put a predefined text # in the input dialog. r = re . search ( 'Example: `([^`]+)`' , docstring ) docstring_ = docstring [ : r . start ( ) ] . strip ( ) if r else docstring text = r . group ( 1 ) if r else None s , ok = _input_dialog ( getattr ( f , '__name__' , 'action' ) , docstring_ , text ) if not ok or not s : return # Parse user-supplied arguments and call the function. args = _parse_snippet ( s ) return f ( * args ) return wrapped | Display a Qt dialog when a function has arguments . | 383 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.