idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
240,500
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 , _...
Returns a dictionary of all Axis in a domain or dictionary of domains .
240,501
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 .
240,502
def add_subprocess ( self , name , proc ) : if isinstance ( proc , Process ) : self . subprocess . update ( { name : proc } ) self . has_process_type_list = False for diagname , value in proc . diagnostics . items ( ) : self . add_diagnostic ( diagname , value ) else : raise ValueError ( 'subprocess must be Process obj...
Adds a single subprocess to this process .
240,503
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 .
240,504
def set_state ( self , name , value ) : if isinstance ( value , Field ) : 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 . sha...
Sets the variable name to a new state value .
240,505
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 ) 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
240,506
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 .
240,507
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 .
240,508
def remove_diagnostic ( 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 .
240,509
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 .
240,510
def diagnostics ( self ) : diag_dict = { } for key in self . _diag_vars : try : diag_dict [ key ] = self . __dict__ [ key ] except : pass return diag_dict
Dictionary access to all diagnostic variables
240,511
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
240,512
def _get_Berger_data ( verbose = True ) : 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 , ) orbit = xr . Dataset ( orbit91_pd ) . ren...
Read in the Berger and Loutre orbital table as a pandas dataframe convert to xarray
240,513
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 IOError : for source in r...
Flexible data retreiver to download and cache the data files locally .
240,514
def tril ( array , k = 0 ) : try : tril_array = np . tril ( array , k = k ) except : 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 .
240,515
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 ) return np . squeeze ( matrix_multiply ( self . Tup , E [ ... , np . newaxis ] ) )
Compute downwelling radiative flux at interfaces between layers .
240,516
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 ) return np . squeeze ( matrix_multiply ( self . Tdown , E [ ... , np . newaxis ] ) )
Compute upwelling radiative flux at interfaces between layers .
240,517
def _compute_heating_rates ( self ) : ( ncol , nlay , icld , permuteseed , irng , idrv , cp , play , plev , tlay , tlev , tsfc , h2ovmr , o3vmr , co2vmr , ch4vmr , n2ovmr , o2vmr , cfc11vmr , cfc12vmr , cfc22vmr , ccl4vmr , emis , inflglw , iceflglw , liqflglw , cldfrac , ciwp , clwp , reic , relq , tauc , tauaer , ) =...
Prepare arguments and call the RRTGM_LW driver to calculate radiative fluxes and heating rates
240,518
def _prepare_general_arguments ( RRTMGobject ) : tlay = _climlab_to_rrtm ( RRTMGobject . Tatm ) tlev = _climlab_to_rrtm ( interface_temperature ( ** RRTMGobject . state ) ) play = _climlab_to_rrtm ( RRTMGobject . lev * np . ones_like ( tlay ) ) plev = _climlab_to_rrtm ( RRTMGobject . lev_bounds * np . ones_like ( tlev ...
Prepare arguments needed for both RRTMG_SW and RRTMG_LW with correct dimensions .
240,519
def interface_temperature ( Ts , Tatm , ** kwargs ) : lev = Tatm . domain . axes [ 'lev' ] . points lev_bounds = Tatm . domain . axes [ 'lev' ] . bounds f = interp1d ( lev , Tatm , axis = - 1 ) Tinterp = f ( lev_bounds [ 1 : - 1 ] ) Ttoa = Tatm [ ... , 0 ] Tinterp = np . concatenate ( ( Ttoa [ ... , np . newaxis ] , Ti...
Compute temperature at model layer interfaces .
240,520
def moist_amplification_factor ( Tkelvin , relative_humidity = 0.8 ) : deltaT = 0.01 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 .
240,521
def daily_insolation ( lat , day , orb = const . orb_present , S0 = const . S0 , day_type = 1 ) : 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 d...
Compute daily average insolation given latitude time of year and orbital parameters .
240,522
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 * (...
Estimates solar longitude from calendar day .
240,523
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 ...
Creates domains for a single column of atmosphere overlying a slab of water .
240,524
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 obje...
Creates a 1D slab ocean Domain in latitude with uniform water depth .
240,525
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 ( '...
Creates a 2D slab ocean Domain in latitude and longitude with uniform water depth .
240,526
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 .
240,527
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 self . adjustment = adjustment self . _update_diagnostics ( newstate ) r...
Computes the state variable tendencies in time for implicit processes .
240,528
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 : level += 1 for name , subproc in proc . subprocess . items ( ) : for name2 , subproc2 ...
Generator for recursive tree of climlab processes
240,529
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 .
240,530
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_do...
All fluxes are band by band
240,531
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 (...
Compute the contributions to the outgoing flux to space due to emissions from each level and the surface .
240,532
def flux_components_bottom ( self ) : N = self . lev . size atmComponents = np . zeros_like ( self . Tatm ) flux_down_top = np . zeros_like ( self . Ts ) for n in range ( N ) : emission = np . zeros_like ( self . emission ) emission [ ... , n ] = self . emission [ ... , n ] this_flux_down = self . trans . flux_down ( f...
Compute the contributions to the downwelling flux to surface due to emissions from each level .
240,533
def _compute ( self ) : tendencies = self . _temperature_tendencies ( ) if 'q' in self . state : 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 ,...
Overides the _compute method of EnergyBudget
240,534
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 ) ...
Calculate Legendre polyomials P0 to P28 and returns them in a dictionary Pn .
240,535
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 ) Pnprim...
Calculates first derivatives of Legendre polynomials and returns them in a dictionary Pnprime .
240,536
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 .
240,537
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 ) ...
Add RRTMG_LW fortran source if Fortran 90 compiler available if no compiler is found do not try to build the extension .
240,538
def compute ( self ) : 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' ) for name , var in self ...
Computes the tendencies for all state variables given current state and specified input .
240,539
def _compute_type ( self , proctype ) : tendencies = { } for varname in self . state : tendencies [ varname ] = 0. * self . state [ varname ] for proc in self . process_types [ proctype ] : step_ratio = int ( proc . timestep / self . timestep ) if self . time [ 'steps' ] % step_ratio == 0 : proc . time [ 'active_now' ]...
Computes tendencies due to all subprocesses of given type proctype . Also pass all diagnostics up to parent process .
240,540
def _compute ( self ) : tendencies = { } for name , value in self . state . items ( ) : tendencies [ name ] = value * 0. return tendencies
Where the tendencies are actually computed ...
240,541
def _build_process_type_list ( self ) : self . process_types = { 'diagnostic' : [ ] , 'explicit' : [ ] , 'implicit' : [ ] , 'adjustment' : [ ] } 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 .
240,542
def step_forward ( self ) : tenddict = self . compute ( ) for varname , tend in tenddict . items ( ) : self . state [ varname ] += tend * self . timestep 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 .
240,543
def _update_time ( self ) : self . time [ 'steps' ] += 1 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 .
240,544
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." ) for count in range ( nums...
Integrates the model by a given number of years .
240,545
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 .
240,546
def integrate_converge ( self , crit = 1e-4 , verbose = True ) : 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 ...
Integrates the model until model states are converging .
240,547
def cam3_gen_source ( ext , build_dir ) : 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_...
Add CAM3 fortran source if Fortran 90 compiler available if no compiler is found do not try to build the extension .
240,548
def global_mean ( field ) : try : lat = field . domain . lat . points except : raise ValueError ( 'No latitude axis in input field.' ) try : lon = field . domain . lon . points return _global_mean_latlon ( field . squeeze ( ) ) except : lat_radians = np . deg2rad ( lat ) return _global_mean ( field . squeeze ( ) , lat_...
Calculates the latitude weighted global mean of a field with latitude dependence .
240,549
def to_latlon ( array , domain , axis = 'lon' ) : axis , array , depth = np . meshgrid ( domain . axes [ axis ] . points , array , domain . axes [ 'depth' ] . points ) if axis == 'lat' : np . swapaxes ( array , 1 , 0 ) return Field ( array , domain = domain )
Broadcasts a 1D axis dependent array across another axis .
240,550
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 ] ...
Convert a climlab . Field object to xarray . DataArray
240,551
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 [ bo...
Convert a dictionary of climlab . Field objects to xarray . Dataset
240,552
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 .
240,553
def generate ( data , dimOrder , maxWindowSize , overlapPercent , transforms = [ ] ) : width = data . shape [ dimOrder . index ( 'w' ) ] height = data . shape [ dimOrder . index ( 'h' ) ] return generateForSize ( width , height , dimOrder , maxWindowSize , overlapPercent , transforms )
Generates a set of sliding windows for the specified dataset .
240,554
def generateForSize ( width , height , dimOrder , maxWindowSize , overlapPercent , transforms = [ ] ) : windowSizeX = min ( maxWindowSize , width ) windowSizeY = min ( maxWindowSize , height ) windowOverlapX = int ( math . floor ( windowSizeX * overlapPercent ) ) windowOverlapY = int ( math . floor ( windowSizeY * over...
Generates a set of sliding windows for a dataset with the specified dimensions and order .
240,555
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
240,556
def indices ( self , includeChannel = True ) : if self . dimOrder == DimOrder . HeightWidthChannel : return ( slice ( self . y , self . y + self . h ) , slice ( self . x , self . x + self . w ) ) elif self . dimOrder == DimOrder . ChannelHeightWidth : if includeChannel is True : return ( slice ( None , None ) , slice (...
Retrieves the indices for this window as a tuple of slices
240,557
def batchWindows ( windows , batchSize ) : return np . array_split ( np . array ( windows ) , len ( windows ) // batchSize )
Splits a list of windows into a series of batches .
240,558
def generateDistanceMatrix ( width , height ) : originX = width / 2 originY = height / 2 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 - origin...
Generates a matrix specifying the distance of each point in a window to its centre .
240,559
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 .
240,560
def arrayFactory ( shape , dtype = float ) : requiredBytes = _requiredSize ( shape , dtype ) 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 .
240,561
def arrayCast ( source , dtype ) : requiredBytes = _requiredSize ( source . shape , dtype ) 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' ) r...
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 .
240,562
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 .
240,563
def set_state ( self , state ) : for k , v in state . items ( ) : setattr ( self , k , v )
Set the view state .
240,564
def _fullname ( o ) : return o . __module__ + "." + o . __name__ if o . __module__ else o . __name__
Return the fully - qualified name of a function .
240,565
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 .
240,566
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 s = 'ABCDEFGHIJ' c_rel = int ( dim [ : - 1 ] ) channel_id = sel...
Extract the points from the data on a given dimension .
240,567
def _plot_labels ( self ) : br = self . n_cols - 1 for k in range ( 0 , self . n_cols ) : dim_x , _ = self . grid_dim [ 0 ] [ k ] . split ( ',' ) _ , dim_y = self . grid_dim [ k ] [ br ] . split ( ',' ) dim_x = self . _get_axis_label ( dim_x ) dim_y = self . _get_axis_label ( dim_y ) self [ k , 0 ] . text ( pos = [ - 1...
Plot feature labels along left and bottom edge of subplots
240,568
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 d = 0 if button == 1 else 1 old = channels [ d ] if channel_id == old : return channels [ d ] = ...
Respond to the click on a channel .
240,569
def on_request_split ( self ) : if ( self . lasso . count < 3 or not len ( self . cluster_ids ) ) : return np . array ( [ ] , dtype = np . int64 ) assert len ( self . channel_ids ) i , j = self . lasso . box dim = self . grid_dim [ i ] [ j ] dim_x , dim_y = dim . split ( ',' ) pos = [ ] spike_ids = [ ] for cluster_id i...
Return the spikes enclosed by the lasso .
240,570
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 .
240,571
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 .
240,572
def require_qt ( func ) : @ wraps ( func ) def wrapped ( * args , ** kwargs ) : if not QApplication . instance ( ) : raise RuntimeError ( "A Qt application must be created." ) return func ( * args , ** kwargs ) return wrapped
Specify that a function requires a Qt application .
240,573
def create_app ( ) : global QT_APP QT_APP = QApplication . instance ( ) if QT_APP is None : QT_APP = QApplication ( sys . argv ) return QT_APP
Create a Qt application .
240,574
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 .
240,575
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 .
240,576
def _wrap_callback_args ( f , docstring = None ) : 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' ) if len ( ar...
Display a Qt dialog when a function has arguments .
240,577
def _get_shortcut_string ( shortcut ) : if shortcut is None : return '' if isinstance ( shortcut , ( tuple , list ) ) : return ', ' . join ( [ _get_shortcut_string ( s ) for s in shortcut ] ) if isinstance ( shortcut , string_types ) : if hasattr ( QKeySequence , shortcut ) : shortcut = QKeySequence ( getattr ( QKeySeq...
Return a string representation of a shortcut .
240,578
def _get_qkeysequence ( shortcut ) : if shortcut is None : return [ ] if isinstance ( shortcut , ( tuple , list ) ) : return [ _get_qkeysequence ( s ) for s in shortcut ] assert isinstance ( shortcut , string_types ) if hasattr ( QKeySequence , shortcut ) : return QKeySequence ( getattr ( QKeySequence , shortcut ) ) se...
Return a QKeySequence or list of QKeySequence from a shortcut string .
240,579
def _show_shortcuts ( shortcuts , name = None ) : name = name or '' print ( '' ) if name : name = ' for ' + name print ( 'Keyboard shortcuts' + name ) for name in sorted ( shortcuts ) : shortcut = _get_shortcut_string ( shortcuts [ name ] ) if not name . startswith ( '_' ) : print ( '- {0:<40}: {1:s}' . format ( name ,...
Display shortcuts .
240,580
def add ( self , callback = None , name = None , shortcut = None , alias = None , docstring = None , menu = None , verbose = True ) : if callback is None : return partial ( self . add , name = name , shortcut = shortcut , alias = alias , menu = menu ) assert callback name = name or callback . __name__ alias = alias or ...
Add an action with a keyboard shortcut .
240,581
def separator ( self , menu = None ) : self . gui . get_menu ( menu or self . menu ) . addSeparator ( )
Add a separator
240,582
def disable ( self , name = None ) : if name is None : for name in self . _actions_dict : self . disable ( name ) return self . _actions_dict [ name ] . qaction . setEnabled ( False )
Disable one or all actions .
240,583
def enable ( self , name = None ) : if name is None : for name in self . _actions_dict : self . enable ( name ) return self . _actions_dict [ name ] . qaction . setEnabled ( True )
Enable one or all actions .
240,584
def run ( self , name , * args ) : assert isinstance ( name , string_types ) name = self . _aliases . get ( name , name ) action = self . _actions_dict . get ( name , None ) if not action : raise ValueError ( "Action `{}` doesn't exist." . format ( name ) ) if not name . startswith ( '_' ) : logger . debug ( "Execute a...
Run an action as specified by its name .
240,585
def remove ( self , name ) : self . gui . removeAction ( self . _actions_dict [ name ] . qaction ) del self . _actions_dict [ name ] delattr ( self , name )
Remove an action .
240,586
def remove_all ( self ) : names = sorted ( self . _actions_dict . keys ( ) ) for name in names : self . remove ( name )
Remove all actions .
240,587
def shortcuts ( self ) : return { name : action . shortcut for name , action in self . _actions_dict . items ( ) }
A dictionary of action shortcuts .
240,588
def show_shortcuts ( self ) : gui_name = self . gui . name actions_name = self . name name = ( '{} - {}' . format ( gui_name , actions_name ) if actions_name else gui_name ) _show_shortcuts ( self . shortcuts , name )
Print all shortcuts .
240,589
def command ( self ) : msg = self . gui . status_message n = len ( msg ) n_cur = len ( self . cursor ) return msg [ : n - n_cur ]
This is used to write a snippet message in the status bar .
240,590
def _backspace ( self ) : if self . command == ':' : return logger . log ( 5 , "Snippet keystroke `Backspace`." ) self . command = self . command [ : - 1 ]
Erase the last character in the snippet command .
240,591
def _enter ( self ) : command = self . command logger . log ( 5 , "Snippet keystroke `Enter`." ) self . mode_off ( ) self . run ( command )
Disable the snippet mode and execute the command .
240,592
def _create_snippet_actions ( self ) : for i , char in enumerate ( self . _snippet_chars ) : def _make_func ( char ) : def callback ( ) : logger . log ( 5 , "Snippet keystroke `%s`." , char ) self . command += char return callback self . actions . add ( name = '_snippet_{}' . format ( i ) , shortcut = char , callback =...
Add mock Qt actions for snippet keystrokes .
240,593
def run ( self , snippet ) : assert snippet [ 0 ] == ':' snippet = snippet [ 1 : ] snippet_args = _parse_snippet ( snippet ) name = snippet_args [ 0 ] logger . info ( "Processing snippet `%s`." , snippet ) try : for actions in self . gui . actions : try : actions . run ( name , * snippet_args [ 1 : ] ) return except Va...
Executes a snippet command .
240,594
def _before_after ( n_samples ) : if not isinstance ( n_samples , ( tuple , list ) ) : before = n_samples // 2 after = n_samples - before else : assert len ( n_samples ) == 2 before , after = n_samples n_samples = before + after assert before >= 0 assert after >= 0 assert before + after == n_samples return before , aft...
Get the number of samples before and after .
240,595
def _slice ( index , n_samples , margin = None ) : if margin is None : margin = ( 0 , 0 ) assert isinstance ( n_samples , ( tuple , list ) ) assert len ( n_samples ) == 2 before , after = n_samples assert isinstance ( margin , ( tuple , list ) ) assert len ( margin ) == 2 margin_before , margin_after = margin before +=...
Return a waveform slice .
240,596
def _load_at ( self , time , channels = None ) : if channels is None : channels = slice ( None , None , None ) time = int ( time ) time_o = time ns = self . n_samples_trace if not ( 0 <= time_o < ns ) : raise ValueError ( "Invalid time {0:d}/{1:d}." . format ( time_o , ns ) ) slice_extract = _slice ( time_o , self . n_...
Load a waveform at a given time .
240,597
def get ( self , spike_ids , channels = None ) : if isinstance ( spike_ids , slice ) : spike_ids = _range_from_slice ( spike_ids , start = 0 , stop = self . n_spikes , ) if not hasattr ( spike_ids , '__len__' ) : spike_ids = [ spike_ids ] if channels is None : channels = slice ( None , None , None ) nc = self . n_chann...
Load the waveforms of the specified spikes .
240,598
def get_waveform_amplitude ( mean_masks , mean_waveforms ) : assert mean_waveforms . ndim == 2 n_samples , n_channels = mean_waveforms . shape assert mean_masks . ndim == 1 assert mean_masks . shape == ( n_channels , ) mean_waveforms = mean_waveforms * mean_masks assert mean_waveforms . shape == ( n_samples , n_channel...
Return the amplitude of the waveforms on all channels .
240,599
def get_mean_masked_features_distance ( mean_features_0 , mean_features_1 , mean_masks_0 , mean_masks_1 , n_features_per_channel = None , ) : assert n_features_per_channel > 0 mu_0 = mean_features_0 . ravel ( ) mu_1 = mean_features_1 . ravel ( ) omeg_0 = mean_masks_0 omeg_1 = mean_masks_1 omeg_0 = np . repeat ( omeg_0 ...
Compute the distance between the mean masked features .