idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
33,700 | def grayify_cmap ( cmap ) : cmap = plt . cm . get_cmap ( cmap ) colors = cmap ( np . arange ( cmap . N ) ) RGB_weight = [ 0.299 , 0.587 , 0.114 ] luminance = np . sqrt ( np . dot ( colors [ : , : 3 ] ** 2 , RGB_weight ) ) colors [ : , : 3 ] = luminance [ : , np . newaxis ] return mplcolors . LinearSegmentedColormap . f... | Return a grayscale version of the colormap . |
33,701 | def get_color_cycle ( n , cmap = "rainbow" , rotations = 3 ) : cmap = colormaps [ cmap ] if np . mod ( n , rotations ) == 0 : per = np . floor_divide ( n , rotations ) else : per = np . floor_divide ( n , rotations ) + 1 vals = list ( np . linspace ( 0 , 1 , per ) ) vals = vals * rotations vals = vals [ : n ] out = cma... | Get a list of RGBA colors following a colormap . |
33,702 | def label_sectors ( * , labels = [ "I" , "II" , "IV" , "VI" , "V" , "III" ] , ax = None , lw = 2 , lc = "k" , cs = None , c_zlevel = 2 , c_alpha = 0.5 , fontsize = 40 ) : if ax is None : ax = plt . gca ( ) factors = [ [ 0.25 , 0.75 ] , [ 2 / 3 , 5 / 6 ] , [ 5 / 6 , 2 / 3 ] , [ 0.75 , 0.25 ] , [ 1 / 3 , 1 / 6 ] , [ 1 / ... | Label the six time - orderings in a three - pulse experiment . |
33,703 | def fluence ( power_mW , color , beam_radius , reprate_Hz , pulse_width , color_units = "wn" , beam_radius_units = "mm" , pulse_width_units = "fs_t" , area_type = "even" , ) -> tuple : if area_type == "even" : radius_cm = wt_units . converter ( beam_radius , beam_radius_units , "cm" ) area_cm2 = np . pi * radius_cm ** ... | Calculate the fluence of a beam . |
33,704 | def mono_resolution ( grooves_per_mm , slit_width , focal_length , output_color , output_units = "wn" ) -> float : d_lambda = 1e6 * slit_width / ( grooves_per_mm * focal_length ) upper = output_color + d_lambda / 2 lower = output_color - d_lambda / 2 return abs ( wt_units . converter ( upper , "nm" , output_units ) - w... | Calculate the resolution of a monochromator . |
33,705 | def nm_width ( center , width , units = "wn" ) -> float : red = wt_units . converter ( center - width / 2. , units , "nm" ) blue = wt_units . converter ( center + width / 2. , units , "nm" ) return red - blue | Given a center and width in energy units get back a width in nm . |
33,706 | def add_arrow ( self , index , between , kind , label = "" , head_length = 0.1 , head_aspect = 2 , font_size = 14 , color = "k" , ) : if hasattr ( index , "index" ) : x_pos = list ( index ) else : x_pos = [ index ] * 2 x_pos = [ np . linspace ( 0 , 1 , self . interactions ) [ i ] for i in x_pos ] arrow_length = self . ... | Add an arrow to the WMEL diagram . |
33,707 | def label_rows ( self , labels , font_size = 15 , text_buffer = 1.5 ) : for i in range ( len ( self . subplots ) ) : plot = self . subplots [ i ] [ - 1 ] plot . text ( text_buffer , 0.5 , labels [ i ] , fontsize = font_size , verticalalignment = "center" , horizontalalignment = "center" , ) | Label rows . |
33,708 | def clear_diagram ( self , diagram ) : plot = self . subplots [ diagram [ 1 ] ] [ diagram [ 0 ] ] plot . cla ( ) | Clear diagram . |
33,709 | def add_arrow ( self , diagram , number , between , kind , label = "" , head_length = 0.075 , font_size = 7 , color = "k" ) : column , row = diagram x_pos = self . x_pos [ number ] arrow_length = self . energies [ between [ 1 ] ] - self . energies [ between [ 0 ] ] arrow_end = self . energies [ between [ 1 ] ] if arrow... | Add arrow . |
33,710 | def plot ( self , save_path = None , close = False , bbox_inches = "tight" , pad_inches = 1 ) : for plot in self . subplots . flatten ( ) : plot . set_xlim ( - 0.1 , 1.1 ) plot . set_ylim ( - 0.1 , 1.1 ) plot . axis ( "off" ) if save_path : plt . savefig ( save_path , transparent = True , dpi = 300 , bbox_inches = bbox... | Plot figure . |
33,711 | def create_collection ( self , name = "collection" , position = None , ** kwargs ) : if name in self . item_names : wt_exceptions . ObjectExistsWarning . warn ( name ) return self [ name ] collection = Collection ( filepath = self . filepath , parent = self . name , name = name , edit_local = True , ** kwargs ) if posi... | Create a new child colleciton . |
33,712 | def create_data ( self , name = "data" , position = None , ** kwargs ) : if name in self . item_names : wt_exceptions . ObjectExistsWarning . warn ( name ) return self [ name ] if name == "" : data = None natural_name = "" . encode ( ) else : data = wt_data . Data ( filepath = self . filepath , parent = self . name , n... | Create a new child data . |
33,713 | def flush ( self ) : for name in self . item_names : item = self [ name ] item . flush ( ) self . file . flush ( ) | Ensure contents are written to file . |
33,714 | def closest_pair ( arr , give = "indicies" ) : idxs = [ idx for idx in np . ndindex ( arr . shape ) ] outs = [ ] min_dist = arr . max ( ) - arr . min ( ) for idxa in idxs : for idxb in idxs : if idxa == idxb : continue dist = abs ( arr [ idxa ] - arr [ idxb ] ) if dist == min_dist : if not [ idxb , idxa ] in outs : out... | Find the pair of indices corresponding to the closest elements in an array . |
33,715 | def diff ( xi , yi , order = 1 ) -> np . ndarray : yi = np . array ( yi ) . copy ( ) flip = False if xi [ - 1 ] < xi [ 0 ] : xi = np . flipud ( xi . copy ( ) ) yi = np . flipud ( yi ) flip = True midpoints = ( xi [ 1 : ] + xi [ : - 1 ] ) / 2 for _ in range ( order ) : d = np . diff ( yi ) d /= np . diff ( xi ) yi = np ... | Take the numerical derivative of a 1D array . |
33,716 | def fft ( xi , yi , axis = 0 ) -> tuple : if xi . ndim != 1 : raise wt_exceptions . DimensionalityError ( 1 , xi . ndim ) spacing = np . diff ( xi ) if not np . allclose ( spacing , spacing . mean ( ) ) : raise RuntimeError ( "WrightTools.kit.fft: argument xi must be evenly spaced" ) yi = np . fft . fft ( yi , axis = a... | Take the 1D FFT of an N - dimensional array and return sensible properly shifted arrays . |
33,717 | def joint_shape ( * args ) -> tuple : if len ( args ) == 0 : return ( ) shape = [ ] shapes = [ a . shape for a in args ] ndim = args [ 0 ] . ndim for i in range ( ndim ) : shape . append ( max ( [ s [ i ] for s in shapes ] ) ) return tuple ( shape ) | Given a set of arrays return the joint shape . |
33,718 | def orthogonal ( * args ) -> bool : for i , arg in enumerate ( args ) : if hasattr ( arg , "shape" ) : args [ i ] = arg . shape for s in zip ( * args ) : if np . product ( s ) != max ( s ) : return False return True | Determine if a set of arrays are orthogonal . |
33,719 | def remove_nans_1D ( * args ) -> tuple : vals = np . isnan ( args [ 0 ] ) for a in args : vals |= np . isnan ( a ) return tuple ( np . array ( a ) [ ~ vals ] for a in args ) | Remove nans in a set of 1D arrays . |
33,720 | def share_nans ( * arrs ) -> tuple : nans = np . zeros ( joint_shape ( * arrs ) ) for arr in arrs : nans *= arr return tuple ( [ a + nans for a in arrs ] ) | Take a list of nD arrays and return a new list of nD arrays . |
33,721 | def smooth_1D ( arr , n = 10 , smooth_type = "flat" ) -> np . ndarray : if arr . ndim != 1 : raise wt_exceptions . DimensionalityError ( 1 , arr . ndim ) if arr . size < n : message = "Input array size must be larger than window size." raise wt_exceptions . ValueError ( message ) if n < 3 : return arr if smooth_type ==... | Smooth 1D data using a window function . Edge effects will be present . |
33,722 | def svd ( a , i = None ) -> tuple : u , s , v = np . linalg . svd ( a , full_matrices = False , compute_uv = True ) u = u . T if i is None : return u , v , s else : return u [ i ] , v [ i ] , s [ i ] | Singular Value Decomposition . |
33,723 | def unique ( arr , tolerance = 1e-6 ) -> np . ndarray : arr = sorted ( arr . flatten ( ) ) unique = [ ] while len ( arr ) > 0 : current = arr [ 0 ] lis = [ xi for xi in arr if np . abs ( current - xi ) < tolerance ] arr = [ xi for xi in arr if not np . abs ( lis [ 0 ] - xi ) < tolerance ] xi_lis_average = sum ( lis ) /... | Return unique elements in 1D array within tolerance . |
33,724 | def valid_index ( index , shape ) -> tuple : index = list ( index ) while len ( index ) < len ( shape ) : index . append ( slice ( None ) ) out = [ ] for i , s in zip ( index [ : : - 1 ] , shape [ : : - 1 ] ) : if s == 1 : if isinstance ( i , slice ) : out . append ( slice ( None ) ) else : out . append ( 0 ) else : ou... | Get a valid index for a broadcastable shape . |
33,725 | def mask_reduce ( mask ) : mask = mask . copy ( ) for i in range ( len ( mask . shape ) ) : a = mask . copy ( ) j = list ( range ( len ( mask . shape ) ) ) j . remove ( i ) j = tuple ( j ) a = a . max ( axis = j , keepdims = True ) idx = [ slice ( None ) ] * len ( mask . shape ) a = a . flatten ( ) idx [ i ] = [ k for ... | Reduce a boolean mask removing all false slices in any dimension . |
33,726 | def enforce_mask_shape ( mask , shape ) : red = tuple ( [ i for i in range ( len ( shape ) ) if shape [ i ] == 1 ] ) return mask . max ( axis = red , keepdims = True ) | Reduce a boolean mask to fit a given shape . |
33,727 | def _from_directory ( self , dirname , prefix = "" ) : ps = [ os . path . join ( here , dirname , p ) for p in os . listdir ( os . path . join ( here , dirname ) ) ] n = prefix + wt_kit . string2identifier ( os . path . basename ( dirname ) ) setattr ( self , n , ps ) | Add dataset from files in a directory . |
33,728 | def string2identifier ( s ) : if len ( s ) == 0 : return "_" if s [ 0 ] not in string . ascii_letters : s = "_" + s valids = string . ascii_letters + string . digits + "_" out = "" for i , char in enumerate ( s ) : if char in valids : out += char else : out += "_" return out | Turn a string into a valid python identifier . |
33,729 | def converter ( val , current_unit , destination_unit ) : x = val for dic in dicts . values ( ) : if current_unit in dic . keys ( ) and destination_unit in dic . keys ( ) : try : native = eval ( dic [ current_unit ] [ 0 ] ) except ZeroDivisionError : native = np . inf x = native try : out = eval ( dic [ destination_uni... | Convert from one unit to another . |
33,730 | def get_symbol ( units ) -> str : if kind ( units ) == "energy" : d = { } d [ "nm" ] = r"\lambda" d [ "wn" ] = r"\bar\nu" d [ "eV" ] = r"\hslash\omega" d [ "Hz" ] = r"f" d [ "THz" ] = r"f" d [ "GHz" ] = r"f" return d . get ( units , "E" ) elif kind ( units ) == "delay" : return r"\tau" elif kind ( units ) == "fluence" ... | Get default symbol type . |
33,731 | def kind ( units ) : for k , v in dicts . items ( ) : if units in v . keys ( ) : return k | Find the kind of given units . |
33,732 | def latex_defs_to_katex_macros ( defs ) : r defs = defs . strip ( ) tmp = [ ] for line in defs . splitlines ( ) : line = line . strip ( ) line = re . sub ( r'^\\def[ ]?' , '' , line ) line = re . sub ( r'(#[0-9])+' , '' , line , 1 ) line = re . sub ( r'( {)|(}$)' , '"' , line ) line = re . sub ( r'(^\\[A-Za-z]+)' , r'"... | r Converts LaTeX \ def statements to KaTeX macros . |
33,733 | def katex_rendering_delimiters ( app ) : if 'delimiters' in app . config . katex_options : return '' katex_inline = [ d . replace ( '\\' , '\\\\' ) for d in app . config . katex_inline ] katex_display = [ d . replace ( '\\' , '\\\\' ) for d in app . config . katex_display ] katex_delimiters = { 'inline' : katex_inline ... | Delimiters for rendering KaTeX math . |
33,734 | def label ( self ) -> str : label = self . expression . replace ( "_" , "\\;" ) if self . units_kind : symbol = wt_units . get_symbol ( self . units ) for v in self . variables : vl = "%s_{%s}" % ( symbol , v . label ) vl = vl . replace ( "_{}" , "" ) label = label . replace ( v . natural_name , vl ) units_dictionary =... | A latex formatted label representing axis expression . |
33,735 | def natural_name ( self ) -> str : name = self . expression . strip ( ) for op in operators : name = name . replace ( op , operator_to_identifier [ op ] ) return wt_kit . string2identifier ( name ) | Valid python identifier representation of the expession . |
33,736 | def masked ( self ) -> np . ndarray : arr = self [ : ] arr . shape = self . shape arr = wt_kit . share_nans ( arr , * self . parent . channels ) [ 0 ] return np . nanmean ( arr , keepdims = True , axis = tuple ( i for i in range ( self . ndim ) if self . shape [ i ] == 1 ) ) | Axis expression evaluated and masked with NaN shared from data channels . |
33,737 | def convert ( self , destination_units , * , convert_variables = False ) : if self . units is None and ( destination_units is None or destination_units == "None" ) : return if not wt_units . is_valid_conversion ( self . units , destination_units ) : valid = wt_units . get_valid_conversions ( self . units ) raise wt_exc... | Convert axis to destination_units . |
33,738 | def add_section ( self , section ) : self . config . read ( self . filepath ) self . config . add_section ( section ) with open ( self . filepath , "w" ) as f : self . config . write ( f ) | Add section . |
33,739 | def dictionary ( self ) -> dict : self . config . read ( self . filepath ) return self . config . _sections | Get a python dictionary of contents . |
33,740 | def has_option ( self , section , option ) -> bool : self . config . read ( self . filepath ) return self . config . has_option ( section , option ) | Test if file has option . |
33,741 | def has_section ( self , section ) -> bool : self . config . read ( self . filepath ) return self . config . has_section ( section ) | Test if file has section . |
33,742 | def read ( self , section , option ) : self . config . read ( self . filepath ) raw = self . config . get ( section , option ) out = tidy_headers . _parse_item . string2item ( raw , sep = ", " ) return out | Read from file . |
33,743 | def sections ( self ) -> list : self . config . read ( self . filepath ) return self . config . sections ( ) | List of sections . |
33,744 | def write ( self , section , option , value ) : self . config . read ( self . filepath ) string = tidy_headers . _parse_item . item2string ( value , sep = ", " ) self . config . set ( section , option , string ) with open ( self . filepath , "w" ) as f : self . config . write ( f ) | Write to file . |
33,745 | def timestamp_from_RFC3339 ( RFC3339 ) : dt = dateutil . parser . parse ( RFC3339 ) if hasattr ( dt . tzinfo , "_offset" ) : timezone = dt . tzinfo . _offset . total_seconds ( ) else : timezone = "utc" timestamp = TimeStamp ( at = dt . timestamp ( ) , timezone = timezone ) return timestamp | Generate a Timestamp object from a RFC3339 formatted string . |
33,746 | def human ( self ) : delta_sec = time . timezone m , s = divmod ( delta_sec , 60 ) h , m = divmod ( m , 60 ) format_string = "%Y-%m-%d %H:%M:%S" out = self . datetime . strftime ( format_string ) return out | Human - readable timestamp . |
33,747 | def path ( self ) : out = self . datetime . strftime ( "%Y-%m-%d" ) out += " " ssm = ( self . datetime - self . datetime . replace ( hour = 0 , minute = 0 , second = 0 , microsecond = 0 ) ) . total_seconds ( ) out += str ( int ( ssm ) ) . zfill ( 5 ) return out | Timestamp for placing into filepaths . |
33,748 | def zoom2D ( xi , yi , zi , xi_zoom = 3. , yi_zoom = 3. , order = 3 , mode = "nearest" , cval = 0. ) : xi = ndimage . interpolation . zoom ( xi , xi_zoom , order = order , mode = "nearest" ) yi = ndimage . interpolation . zoom ( yi , yi_zoom , order = order , mode = "nearest" ) zi = ndimage . interpolation . zoom ( zi ... | Zoom a 2D array with axes . |
33,749 | def apply_rcparams ( kind = "fast" ) : if kind == "default" : matplotlib . rcdefaults ( ) elif kind == "fast" : matplotlib . rcParams [ "text.usetex" ] = False matplotlib . rcParams [ "mathtext.fontset" ] = "cm" matplotlib . rcParams [ "font.family" ] = "sans-serif" matplotlib . rcParams [ "font.size" ] = 14 matplotlib... | Quickly apply rcparams for given purposes . |
33,750 | def _apply_labels ( self , autolabel = "none" , xlabel = None , ylabel = None , data = None , channel_index = 0 ) : if autolabel in [ "xy" , "both" , "x" ] and not xlabel : xlabel = data . axes [ 0 ] . label if autolabel in [ "xy" , "both" , "y" ] and not ylabel : if data . ndim == 1 : ylabel = data . channels [ channe... | Apply x and y labels to axes . |
33,751 | def add_sideplot ( self , along , pad = 0 , height = 0.75 , ymin = 0 , ymax = 1.1 ) : if hasattr ( self , "divider" ) : divider = self . divider else : divider = make_axes_locatable ( self ) setattr ( self , "divider" , divider ) if along == "x" : ax = self . sidex = divider . append_axes ( "top" , height , pad = pad ,... | Add a side axis . |
33,752 | def legend ( self , * args , ** kwargs ) : if "fancybox" not in kwargs . keys ( ) : kwargs [ "fancybox" ] = False if "framealpha" not in kwargs . keys ( ) : kwargs [ "framealpha" ] = 1. return super ( ) . legend ( * args , ** kwargs ) | Add a legend . |
33,753 | def add_subplot ( self , * args , ** kwargs ) : kwargs . setdefault ( "projection" , "wright" ) return super ( ) . add_subplot ( * args , ** kwargs ) | Add a subplot to the figure . |
33,754 | def warn ( filepath , expected ) : filepath = pathlib . Path ( filepath ) message = "file {0} has type {1} (expected {2})" . format ( filepath , filepath . suffix , expected ) warnings . warn ( message , WrongFileTypeWarning ) | Raise warning . |
33,755 | def channel_names ( self ) -> tuple : if "channel_names" not in self . attrs . keys ( ) : self . attrs [ "channel_names" ] = np . array ( [ ] , dtype = "S" ) return tuple ( s . decode ( ) for s in self . attrs [ "channel_names" ] ) | Channel names . |
33,756 | def ndim ( self ) -> int : try : assert self . _ndim is not None except ( AssertionError , AttributeError ) : if len ( self . variables ) == 0 : self . _ndim = 0 else : self . _ndim = self . variables [ 0 ] . ndim finally : return self . _ndim | Get number of dimensions . |
33,757 | def _on_axes_updated ( self ) : self . attrs [ "axes" ] = [ a . identity . encode ( ) for a in self . _axes ] while len ( self . _current_axis_identities_in_natural_namespace ) > 0 : key = self . _current_axis_identities_in_natural_namespace . pop ( 0 ) try : delattr ( self , key ) except AttributeError : pass for a in... | Method to run when axes are changed in any way . |
33,758 | def _on_constants_updated ( self ) : self . attrs [ "constants" ] = [ a . identity . encode ( ) for a in self . _constants ] | Method to run when constants are changed in any way . |
33,759 | def bring_to_front ( self , channel ) : channel_index = wt_kit . get_index ( self . channel_names , channel ) new = list ( self . channel_names ) new . insert ( 0 , new . pop ( channel_index ) ) self . channel_names = new | Bring a specific channel to the zero - indexed position in channels . |
33,760 | def gradient ( self , axis , * , channel = 0 ) : if isinstance ( axis , int ) : axis_index = axis elif isinstance ( axis , str ) : index = self . axis_names . index ( axis ) axes = [ i for i in range ( self . ndim ) if self . axes [ index ] . shape [ i ] > 1 ] if len ( axes ) > 1 : raise wt_exceptions . Multidimensiona... | Compute the gradient along one axis . |
33,761 | def convert ( self , destination_units , * , convert_variables = False , verbose = True ) : units_kind = wt_units . kind ( destination_units ) for axis in self . axes : if axis . units_kind == units_kind : orig = axis . units axis . convert ( destination_units , convert_variables = convert_variables ) if verbose : prin... | Convert all compatable axes and constants to given units . |
33,762 | def create_channel ( self , name , values = None , * , shape = None , units = None , dtype = None , ** kwargs ) -> Channel : if name in self . channel_names : warnings . warn ( name , wt_exceptions . ObjectExistsWarning ) return self [ name ] elif name in self . variable_names : raise wt_exceptions . NameNotUniqueError... | Append a new channel . |
33,763 | def create_variable ( self , name , values = None , * , shape = None , units = None , dtype = None , ** kwargs ) -> Variable : if name in self . variable_names : warnings . warn ( name , wt_exceptions . ObjectExistsWarning ) return self [ name ] elif name in self . channel_names : raise wt_exceptions . NameNotUniqueErr... | Add new child variable . |
33,764 | def get_nadir ( self , channel = 0 ) -> tuple : if isinstance ( channel , int ) : channel_index = channel elif isinstance ( channel , str ) : channel_index = self . channel_names . index ( channel ) else : raise TypeError ( "channel: expected {int, str}, got %s" % type ( channel ) ) channel = self . channels [ channel_... | Get the coordinates in units of the minimum in a channel . |
33,765 | def get_zenith ( self , channel = 0 ) -> tuple : if isinstance ( channel , int ) : channel_index = channel elif isinstance ( channel , str ) : channel_index = self . channel_names . index ( channel ) else : raise TypeError ( "channel: expected {int, str}, got %s" % type ( channel ) ) channel = self . channels [ channel... | Get the coordinates in units of the maximum in a channel . |
33,766 | def heal ( self , channel = 0 , method = "linear" , fill_value = np . nan , verbose = True ) : warnings . warn ( "heal" , category = wt_exceptions . EntireDatasetInMemoryWarning ) timer = wt_kit . Timer ( verbose = False ) with timer : if isinstance ( channel , int ) : channel_index = channel elif isinstance ( channel ... | Remove nans from channel using interpolation . |
33,767 | def level ( self , channel , axis , npts , * , verbose = True ) : warnings . warn ( "level" , category = wt_exceptions . EntireDatasetInMemoryWarning ) channel_index = wt_kit . get_index ( self . channel_names , channel ) channel = self . channels [ channel_index ] npts = int ( npts ) if npts == 0 : raise wt_exceptions... | Subtract the average value of npts at the edge of a given axis . |
33,768 | def print_tree ( self , * , verbose = True ) : print ( "{0} ({1})" . format ( self . natural_name , self . filepath ) ) self . _print_branch ( "" , depth = 0 , verbose = verbose ) | Print a ascii - formatted tree representation of the data contents . |
33,769 | def remove_channel ( self , channel , * , verbose = True ) : channel_index = wt_kit . get_index ( self . channel_names , channel ) new = list ( self . channel_names ) name = new . pop ( channel_index ) del self [ name ] self . channel_names = new if verbose : print ( "channel {0} removed" . format ( name ) ) | Remove channel from data . |
33,770 | def remove_variable ( self , variable , * , implied = True , verbose = True ) : if isinstance ( variable , int ) : variable = self . variable_names [ variable ] removed = [ ] if implied : for n in self . variable_names : if n . startswith ( variable ) : removed . append ( n ) else : removed = [ variable ] for n in remo... | Remove variable from data . |
33,771 | def rename_channels ( self , * , verbose = True , ** kwargs ) : changed = kwargs . keys ( ) for k , v in kwargs . items ( ) : if v not in changed and v in self . keys ( ) : raise wt_exceptions . NameNotUniqueError ( v ) new = { } for k , v in kwargs . items ( ) : obj = self [ k ] index = self . channel_names . index ( ... | Rename a set of channels . |
33,772 | def rename_variables ( self , * , implied = True , verbose = True , ** kwargs ) : kwargs = collections . OrderedDict ( kwargs ) if implied : new = collections . OrderedDict ( ) for k , v in kwargs . items ( ) : for n in self . variable_names : if n . startswith ( k ) : new [ n ] = n . replace ( k , v , 1 ) kwargs = new... | Rename a set of variables . |
33,773 | def share_nans ( self ) : def f ( _ , s , channels ) : outs = wt_kit . share_nans ( * [ c [ s ] for c in channels ] ) for c , o in zip ( channels , outs ) : c [ s ] = o self . channels [ 0 ] . chunkwise ( f , self . channels ) | Share not - a - numbers between all channels . |
33,774 | def smooth ( self , factors , channel = None , verbose = True ) -> "Data" : warnings . warn ( "smooth" , category = wt_exceptions . EntireDatasetInMemoryWarning ) if isinstance ( factors , list ) : pass else : dummy = np . zeros ( len ( self . _axes ) ) dummy [ : : ] = factors factors = list ( dummy ) if channel is Non... | Smooth a channel using an n - dimenional kaiser window . |
33,775 | def transform ( self , * axes , verbose = True ) : new = [ ] newt = "newt" in self . axis_expressions current = { a . expression : a for a in self . _axes } for expression in axes : axis = current . get ( expression , Axis ( self , expression ) ) new . append ( axis ) self . _axes = new for a in self . _axes : if a . u... | Transform the data . |
33,776 | def set_constants ( self , * constants , verbose = True ) : new = [ ] current = { c . expression : c for c in self . _constants } for expression in constants : constant = current . get ( expression , Constant ( self , expression ) ) new . append ( constant ) self . _constants = new for c in self . _constants : if c . u... | Set the constants associated with the data . |
33,777 | def create_constant ( self , expression , * , verbose = True ) : if expression in self . constant_expressions : wt_exceptions . ObjectExistsWarning . warn ( expression ) return self . constants [ self . constant_expressions . index ( expression ) ] constant = Constant ( self , expression ) if constant . units is None :... | Append a constant to the stored list . |
33,778 | def remove_constant ( self , constant , * , verbose = True ) : if isinstance ( constant , ( str , int ) ) : constant_index = wt_kit . get_index ( self . constant_expressions , constant ) elif isinstance ( constant , Constant ) : constant_index = wt_kit . get_index ( self . constants , constant ) constant = self . _cons... | Remove a constant from the stored list . |
33,779 | def zoom ( self , factor , order = 1 , verbose = True ) : raise NotImplementedError import scipy . ndimage for axis in self . _axes : axis [ : ] = scipy . ndimage . interpolation . zoom ( axis [ : ] , factor , order = order ) for channel in self . channels : channel [ : ] = scipy . ndimage . interpolation . zoom ( chan... | Zoom the data array using spline interpolation of the requested order . |
33,780 | def get_path_matching ( name ) : p = os . path . join ( os . path . expanduser ( "~" ) , name ) if not os . path . isdir ( p ) : p = None drive , folders = os . path . splitdrive ( os . getcwd ( ) ) folders = folders . split ( os . sep ) folders . insert ( 0 , os . sep ) if name in folders : p = os . path . join ( driv... | Get path matching a name . |
33,781 | def glob_handler ( extension , folder = None , identifier = None ) : filepaths = [ ] if folder : folder = folder . replace ( "[" , "?" ) folder = folder . replace ( "]" , "*" ) folder = folder . replace ( "?" , "[[]" ) folder = folder . replace ( "*" , "[]]" ) glob_str = os . path . join ( folder , "*" + extension ) el... | Return a list of all files matching specified inputs . |
33,782 | def major_extent ( self ) -> complex : return max ( ( self . max ( ) - self . null , self . null - self . min ( ) ) ) | Maximum deviation from null . |
33,783 | def minor_extent ( self ) -> complex : return min ( ( self . max ( ) - self . null , self . null - self . min ( ) ) ) | Minimum deviation from null . |
33,784 | def normalize ( self , mag = 1. ) : def f ( dataset , s , null , mag ) : dataset [ s ] -= null dataset [ s ] /= mag if self . signed : mag = self . mag ( ) / mag else : mag = self . max ( ) / mag self . chunkwise ( f , null = self . null , mag = mag ) self . _null = 0 | Normalize a Channel set null to 0 and the mag to given value . |
33,785 | def trim ( self , neighborhood , method = "ztest" , factor = 3 , replace = "nan" , verbose = True ) : warnings . warn ( "trim" , category = wt_exceptions . EntireDatasetInMemoryWarning ) outliers = [ ] means = [ ] ex_means = [ ] for idx in np . ndindex ( self . shape ) : slices = [ ] for i , di , size in zip ( idx , ne... | Remove outliers from the dataset . |
33,786 | def units ( self , value ) : if value is None : if "units" in self . attrs . keys ( ) : self . attrs . pop ( "units" ) else : try : self . attrs [ "units" ] = value except AttributeError : self . attrs [ "units" ] = value | Set units . |
33,787 | def argmax ( self ) : if "argmax" not in self . attrs . keys ( ) : def f ( dataset , s ) : arr = dataset [ s ] try : amin = np . nanargmax ( arr ) except ValueError : amin = 0 idx = np . unravel_index ( amin , arr . shape ) val = arr [ idx ] return ( tuple ( i + ( ss . start if ss . start else 0 ) for i , ss in zip ( i... | Index of the maximum ignorning nans . |
33,788 | def chunkwise ( self , func , * args , ** kwargs ) : out = collections . OrderedDict ( ) for s in self . slices ( ) : key = tuple ( sss . start for sss in s ) out [ key ] = func ( self , s , * args , ** kwargs ) self . _clear_array_attributes_cache ( ) return out | Execute a function for each chunk in the dataset . |
33,789 | def clip ( self , min = None , max = None , replace = np . nan ) : if max is None : max = self . max ( ) if min is None : min = self . min ( ) def f ( dataset , s , min , max , replace ) : if hasattr ( min , "shape" ) : min = min [ wt_kit . valid_index ( s , min . shape ) ] if hasattr ( max , "shape" ) : max = max [ wt... | Clip values outside of a defined range . |
33,790 | def convert ( self , destination_units ) : if not wt_units . is_valid_conversion ( self . units , destination_units ) : kind = wt_units . kind ( self . units ) valid = list ( wt_units . dicts [ kind ] . keys ( ) ) raise wt_exceptions . UnitsError ( valid , destination_units ) if self . units is None : return def f ( da... | Convert units . |
33,791 | def log ( self , base = np . e , floor = None ) : def f ( dataset , s , base , floor ) : arr = dataset [ s ] arr = np . log ( arr ) if base != np . e : arr /= np . log ( base ) if floor is not None : arr [ arr < floor ] = floor dataset [ s ] = arr self . chunkwise ( f , base = base , floor = floor ) | Take the log of the entire dataset . |
33,792 | def log10 ( self , floor = None ) : def f ( dataset , s , floor ) : arr = dataset [ s ] arr = np . log10 ( arr ) if floor is not None : arr [ arr < floor ] = floor dataset [ s ] = arr self . chunkwise ( f , floor = floor ) | Take the log base 10 of the entire dataset . |
33,793 | def max ( self ) : if "max" not in self . attrs . keys ( ) : def f ( dataset , s ) : return np . nanmax ( dataset [ s ] ) self . attrs [ "max" ] = np . nanmax ( list ( self . chunkwise ( f ) . values ( ) ) ) return self . attrs [ "max" ] | Maximum ignorning nans . |
33,794 | def min ( self ) : if "min" not in self . attrs . keys ( ) : def f ( dataset , s ) : return np . nanmin ( dataset [ s ] ) self . attrs [ "min" ] = np . nanmin ( list ( self . chunkwise ( f ) . values ( ) ) ) return self . attrs [ "min" ] | Minimum ignoring nans . |
33,795 | def slices ( self ) : if self . chunks is None : yield tuple ( slice ( None , s ) for s in self . shape ) else : ceilings = tuple ( - ( - s // c ) for s , c in zip ( self . shape , self . chunks ) ) for idx in np . ndindex ( ceilings ) : out = [ ] for i , c , s in zip ( idx , self . chunks , self . shape ) : start = i ... | Returns a generator yielding tuple of slice objects . |
33,796 | def label ( self ) -> str : label = self . expression . replace ( "_" , "\\;" ) if self . units_kind : symbol = wt_units . get_symbol ( self . units ) for v in self . variables : vl = "%s_{%s}" % ( symbol , v . label ) vl = vl . replace ( "_{}" , "" ) label = label . replace ( v . natural_name , vl ) val = ( round ( se... | A latex formatted label representing constant expression and united value . |
33,797 | def from_directory ( filepath , from_methods , * , name = None , parent = None , verbose = True ) : filepath = pathlib . Path ( filepath ) . resolve ( ) if name is None : name = filepath . name if verbose : print ( "Creating Collection:" , name ) root = Collection ( name = name , parent = parent ) q = queue . Queue ( )... | Create a WrightTools Collection from a directory of source files . |
33,798 | def is_valid_combination ( values , names ) : dictionary = dict ( zip ( names , values ) ) rules = [ lambda d : "98" == d [ "os" ] and "Brand Y" == d [ "brand" ] , lambda d : "XP" == d [ "os" ] and "Brand X" == d [ "brand" ] , lambda d : "Contr." == d [ "employee" ] and d [ "increment" ] < 30 , ] for rule in rules : tr... | Should return True if combination is valid and False otherwise . |
33,799 | def is_valid_combination ( row ) : n = len ( row ) if n > 1 : if "98" == row [ 1 ] and "Brand Y" == row [ 0 ] : return False if "XP" == row [ 1 ] and "Brand X" == row [ 0 ] : return False if n > 4 : if "Contr." == row [ 3 ] and row [ 4 ] < 30 : return False return True | This is a filtering function . Filtering functions should return True if combination is valid and False otherwise . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.