idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
700
def sum_coefs ( self ) : return numpy . sum ( self . ar_coefs ) + numpy . sum ( self . ma_coefs )
The sum of all AR and MA coefficients
701
def calc_all_ar_coefs ( self , ar_order , ma_model ) : turning_idx , _ = ma_model . turningpoint values = ma_model . coefs [ turning_idx : ] self . ar_coefs , residuals = numpy . linalg . lstsq ( self . get_a ( values , ar_order ) , self . get_b ( values , ar_order ) , rcond = - 1 ) [ : 2 ] if len ( residuals ) == 1 : self . _rel_rmse = numpy . sqrt ( residuals [ 0 ] ) / numpy . sum ( values ) else : self . _rel_rmse = 0.
Determine the AR coeffcients based on a least squares approach .
702
def get_a ( values , n ) : m = len ( values ) - n a = numpy . empty ( ( m , n ) , dtype = float ) for i in range ( m ) : i0 = i - 1 if i > 0 else None i1 = i + n - 1 a [ i ] = values [ i1 : i0 : - 1 ] return numpy . array ( a )
Extract the independent variables of the given values and return them as a matrix with n columns in a form suitable for the least squares approach applied in method |ARMA . update_ar_coefs| .
703
def update_ma_coefs ( self ) : self . ma_coefs = [ ] for ma_order in range ( 1 , self . ma . order + 1 ) : self . calc_next_ma_coef ( ma_order , self . ma ) if self . dev_coefs < self . max_dev_coefs : self . norm_coefs ( ) break else : with hydpy . pub . options . reprdigits ( 12 ) : raise RuntimeError ( f'Method `update_ma_coefs` is not able to determine the ' f'MA coefficients of the ARMA model with the desired ' f'accuracy. You can set the tolerance value ' f'´max_dev_coefs` to a higher value. An accuracy of ' f'`{objecttools.repr_(self.dev_coefs)}` has been reached ' f'using `{self.ma.order}` MA coefficients.' ) if numpy . min ( self . response ) < 0. : warnings . warn ( 'Note that the smallest response to a standard impulse of the ' 'determined ARMA model is negative (`%s`).' % objecttools . repr_ ( numpy . min ( self . response ) ) )
Determine the MA coefficients .
704
def calc_next_ma_coef ( self , ma_order , ma_model ) : idx = ma_order - 1 coef = ma_model . coefs [ idx ] for jdx , ar_coef in enumerate ( self . ar_coefs ) : zdx = idx - jdx - 1 if zdx >= 0 : coef -= ar_coef * ma_model . coefs [ zdx ] self . ma_coefs = numpy . concatenate ( ( self . ma_coefs , [ coef ] ) )
Determine the MA coefficients of the ARMA model based on its predetermined AR coefficients and the MA ordinates of the given |MA| model .
705
def response ( self ) : values = [ ] sum_values = 0. ma_coefs = self . ma_coefs ar_coefs = self . ar_coefs ma_order = self . ma_order for idx in range ( len ( self . ma . delays ) ) : value = 0. if idx < ma_order : value += ma_coefs [ idx ] for jdx , ar_coef in enumerate ( ar_coefs ) : zdx = idx - jdx - 1 if zdx >= 0 : value += ar_coef * values [ zdx ] values . append ( value ) sum_values += value return numpy . array ( values )
Return the response to a standard dt impulse .
706
def moments ( self ) : timepoints = self . ma . delays response = self . response moment1 = statstools . calc_mean_time ( timepoints , response ) moment2 = statstools . calc_mean_time_deviation ( timepoints , response , moment1 ) return numpy . array ( [ moment1 , moment2 ] )
The first two time delay weighted statistical moments of the ARMA response .
707
def plot ( self , threshold = None , ** kwargs ) : try : pyplot . bar ( x = self . ma . delays + .5 , height = self . response , width = 1. , fill = False , ** kwargs ) except TypeError : pyplot . bar ( left = self . ma . delays + .5 , height = self . response , width = 1. , fill = False , ** kwargs ) pyplot . xlabel ( 'time' ) pyplot . ylabel ( 'response' ) if threshold is not None : cumsum = numpy . cumsum ( self . response ) idx = numpy . where ( cumsum > threshold * cumsum [ - 1 ] ) [ 0 ] [ 0 ] pyplot . xlim ( 0. , idx )
Barplot of the ARMA response .
708
def method_header ( method_name , nogil = False , idx_as_arg = False ) : if not config . FASTCYTHON : nogil = False header = 'cpdef inline void %s(self' % method_name header += ', int idx)' if idx_as_arg else ')' header += ' nogil:' if nogil else ':' return header
Returns the Cython method header for methods without arguments except self .
709
def decorate_method ( wrapped ) : def wrapper ( self ) : lines = Lines ( ) if hasattr ( self . model , wrapped . __name__ ) : print ( ' . %s' % wrapped . __name__ ) lines . add ( 1 , method_header ( wrapped . __name__ , nogil = True ) ) for line in wrapped ( self ) : lines . add ( 2 , line ) return lines functools . update_wrapper ( wrapper , wrapped ) wrapper . __doc__ = 'Lines of model method %s.' % wrapped . __name__ return property ( wrapper )
The decorated method will return a |Lines| object including a method header . However the |Lines| object will be empty if the respective model does not implement a method with the same name as the wrapped method .
710
def add ( self , indent , line ) : if isinstance ( line , str ) : list . append ( self , indent * 4 * ' ' + line ) else : for subline in line : list . append ( self , indent * 4 * ' ' + subline )
Appends the given text line with prefixed spaces in accordance with the given number of indentation levels .
711
def pyname ( self ) : if self . pymodule . endswith ( '__init__' ) : return self . pymodule . split ( '.' ) [ - 2 ] else : return self . pymodule . split ( '.' ) [ - 1 ]
Name of the compiled module .
712
def pyxwriter ( self ) : model = self . Model ( ) if hasattr ( self , 'Parameters' ) : model . parameters = self . Parameters ( vars ( self ) ) else : model . parameters = parametertools . Parameters ( vars ( self ) ) if hasattr ( self , 'Sequences' ) : model . sequences = self . Sequences ( model = model , ** vars ( self ) ) else : model . sequences = sequencetools . Sequences ( model = model , ** vars ( self ) ) return PyxWriter ( self , model , self . pyxfilepath )
Update the pyx file .
713
def pysourcefiles ( self ) : sourcefiles = set ( ) for ( name , child ) in vars ( self ) . items ( ) : try : parents = inspect . getmro ( child ) except AttributeError : continue for parent in parents : try : sourcefile = inspect . getfile ( parent ) except TypeError : break sourcefiles . add ( sourcefile ) return Lines ( * sourcefiles )
All source files of the actual models Python classes and their respective base classes .
714
def outdated ( self ) : if hydpy . pub . options . forcecompiling : return True if os . path . split ( hydpy . __path__ [ 0 ] ) [ - 2 ] . endswith ( '-packages' ) : return False if not os . path . exists ( self . dllfilepath ) : return True cydate = os . stat ( self . dllfilepath ) . st_mtime for pysourcefile in self . pysourcefiles : pydate = os . stat ( pysourcefile ) . st_mtime if pydate > cydate : return True return False
True if at least one of the |Cythonizer . pysourcefiles| is newer than the compiled file under |Cythonizer . pyxfilepath| otherwise False .
715
def compile_ ( self ) : from Cython import Build argv = copy . deepcopy ( sys . argv ) sys . argv = [ sys . argv [ 0 ] , 'build_ext' , '--build-lib=' + self . buildpath ] exc_modules = [ distutils . extension . Extension ( 'hydpy.cythons.autogen.' + self . cyname , [ self . pyxfilepath ] , extra_compile_args = [ '-O2' ] ) ] distutils . core . setup ( ext_modules = Build . cythonize ( exc_modules ) , include_dirs = [ numpy . get_include ( ) ] ) sys . argv = argv
Translate cython code to C code and compile it .
716
def move_dll ( self ) : dirinfos = os . walk ( self . buildpath ) next ( dirinfos ) system_dependent_filename = None for dirinfo in dirinfos : for filename in dirinfo [ 2 ] : if ( filename . startswith ( self . cyname ) and filename . endswith ( dllextension ) ) : system_dependent_filename = filename break if system_dependent_filename : try : shutil . move ( os . path . join ( dirinfo [ 0 ] , system_dependent_filename ) , os . path . join ( self . cydirpath , self . cyname + dllextension ) ) break except BaseException : prefix = ( 'After trying to cythonize module %s, when ' 'trying to move the final cython module %s ' 'from directory %s to directory %s' % ( self . pyname , system_dependent_filename , self . buildpath , self . cydirpath ) ) suffix = ( 'A likely error cause is that the cython module ' '%s does already exist in this directory and is ' 'currently blocked by another Python process. ' 'Maybe it helps to close all Python processes ' 'and restart the cyhonization afterwards.' % self . cyname + dllextension ) objecttools . augment_excmessage ( prefix , suffix ) else : raise IOError ( 'After trying to cythonize module %s, the resulting ' 'file %s could neither be found in directory %s nor ' 'its subdirectories. The distul report should tell ' 'whether the file has been stored somewhere else,' 'is named somehow else, or could not be build at ' 'all.' % self . buildpath )
Try to find the resulting dll file and to move it into the cythons package .
717
def constants ( self ) : lines = Lines ( ) for ( name , member ) in vars ( self . cythonizer ) . items ( ) : if ( name . isupper ( ) and ( not inspect . isclass ( member ) ) and ( type ( member ) in TYPE2STR ) ) : ndim = numpy . array ( member ) . ndim ctype = TYPE2STR [ type ( member ) ] + NDIM2STR [ ndim ] lines . add ( 0 , 'cdef public %s %s = %s' % ( ctype , name , member ) ) return lines
Constants declaration lines .
718
def parameters ( self ) : lines = Lines ( ) lines . add ( 0 , '@cython.final' ) lines . add ( 0 , 'cdef class Parameters(object):' ) for subpars in self . model . parameters : if subpars : lines . add ( 1 , 'cdef public %s %s' % ( objecttools . classname ( subpars ) , subpars . name ) ) for subpars in self . model . parameters : if subpars : print ( ' - %s' % subpars . name ) lines . add ( 0 , '@cython.final' ) lines . add ( 0 , 'cdef class %s(object):' % objecttools . classname ( subpars ) ) for par in subpars : try : ctype = TYPE2STR [ par . TYPE ] + NDIM2STR [ par . NDIM ] except KeyError : ctype = par . TYPE + NDIM2STR [ par . NDIM ] lines . add ( 1 , 'cdef public %s %s' % ( ctype , par . name ) ) return lines
Parameter declaration lines .
719
def iosequence ( seq ) : lines = Lines ( ) lines . add ( 1 , 'cdef public bint _%s_diskflag' % seq . name ) lines . add ( 1 , 'cdef public str _%s_path' % seq . name ) lines . add ( 1 , 'cdef FILE *_%s_file' % seq . name ) lines . add ( 1 , 'cdef public bint _%s_ramflag' % seq . name ) ctype = 'double' + NDIM2STR [ seq . NDIM + 1 ] lines . add ( 1 , 'cdef public %s _%s_array' % ( ctype , seq . name ) ) return lines
Special declaration lines for the given |IOSequence| object .
720
def open_files ( subseqs ) : print ( ' . open_files' ) lines = Lines ( ) lines . add ( 1 , 'cpdef open_files(self, int idx):' ) for seq in subseqs : lines . add ( 2 , 'if self._%s_diskflag:' % seq . name ) lines . add ( 3 , 'self._%s_file = fopen(str(self._%s_path).encode(), ' '"rb+")' % ( 2 * ( seq . name , ) ) ) if seq . NDIM == 0 : lines . add ( 3 , 'fseek(self._%s_file, idx*8, SEEK_SET)' % seq . name ) else : lines . add ( 3 , 'fseek(self._%s_file, idx*self._%s_length*8, ' 'SEEK_SET)' % ( 2 * ( seq . name , ) ) ) return lines
Open file statements .
721
def close_files ( subseqs ) : print ( ' . close_files' ) lines = Lines ( ) lines . add ( 1 , 'cpdef inline close_files(self):' ) for seq in subseqs : lines . add ( 2 , 'if self._%s_diskflag:' % seq . name ) lines . add ( 3 , 'fclose(self._%s_file)' % seq . name ) return lines
Close file statements .
722
def load_data ( subseqs ) : print ( ' . load_data' ) lines = Lines ( ) lines . add ( 1 , 'cpdef inline void load_data(self, int idx) %s:' % _nogil ) lines . add ( 2 , 'cdef int jdx0, jdx1, jdx2, jdx3, jdx4, jdx5' ) for seq in subseqs : lines . add ( 2 , 'if self._%s_diskflag:' % seq . name ) if seq . NDIM == 0 : lines . add ( 3 , 'fread(&self.%s, 8, 1, self._%s_file)' % ( 2 * ( seq . name , ) ) ) else : lines . add ( 3 , 'fread(&self.%s[0], 8, self._%s_length, ' 'self._%s_file)' % ( 3 * ( seq . name , ) ) ) lines . add ( 2 , 'elif self._%s_ramflag:' % seq . name ) if seq . NDIM == 0 : lines . add ( 3 , 'self.%s = self._%s_array[idx]' % ( 2 * ( seq . name , ) ) ) else : indexing = '' for idx in range ( seq . NDIM ) : lines . add ( 3 + idx , 'for jdx%d in range(self._%s_length_%d):' % ( idx , seq . name , idx ) ) indexing += 'jdx%d,' % idx indexing = indexing [ : - 1 ] lines . add ( 3 + seq . NDIM , 'self.%s[%s] = self._%s_array[idx,%s]' % ( 2 * ( seq . name , indexing ) ) ) return lines
Load data statements .
723
def set_pointer ( self , subseqs ) : lines = Lines ( ) for seq in subseqs : if seq . NDIM == 0 : lines . extend ( self . set_pointer0d ( subseqs ) ) break for seq in subseqs : if seq . NDIM == 1 : lines . extend ( self . alloc ( subseqs ) ) lines . extend ( self . dealloc ( subseqs ) ) lines . extend ( self . set_pointer1d ( subseqs ) ) break return lines
Set_pointer functions for link sequences .
724
def set_pointer0d ( subseqs ) : print ( ' . set_pointer0d' ) lines = Lines ( ) lines . add ( 1 , 'cpdef inline set_pointer0d' '(self, str name, pointerutils.PDouble value):' ) for seq in subseqs : lines . add ( 2 , 'if name == "%s":' % seq . name ) lines . add ( 3 , 'self.%s = value.p_value' % seq . name ) return lines
Set_pointer function for 0 - dimensional link sequences .
725
def alloc ( subseqs ) : print ( ' . setlength' ) lines = Lines ( ) lines . add ( 1 , 'cpdef inline alloc(self, name, int length):' ) for seq in subseqs : lines . add ( 2 , 'if name == "%s":' % seq . name ) lines . add ( 3 , 'self._%s_length_0 = length' % seq . name ) lines . add ( 3 , 'self.%s = <double**> ' 'PyMem_Malloc(length * sizeof(double*))' % seq . name ) return lines
Allocate memory for 1 - dimensional link sequences .
726
def dealloc ( subseqs ) : print ( ' . dealloc' ) lines = Lines ( ) lines . add ( 1 , 'cpdef inline dealloc(self):' ) for seq in subseqs : lines . add ( 2 , 'PyMem_Free(self.%s)' % seq . name ) return lines
Deallocate memory for 1 - dimensional link sequences .
727
def set_pointer1d ( subseqs ) : print ( ' . set_pointer1d' ) lines = Lines ( ) lines . add ( 1 , 'cpdef inline set_pointer1d' '(self, str name, pointerutils.PDouble value, int idx):' ) for seq in subseqs : lines . add ( 2 , 'if name == "%s":' % seq . name ) lines . add ( 3 , 'self.%s[idx] = value.p_value' % seq . name ) return lines
Set_pointer function for 1 - dimensional link sequences .
728
def numericalparameters ( self ) : lines = Lines ( ) if self . model . NUMERICAL : lines . add ( 0 , '@cython.final' ) lines . add ( 0 , 'cdef class NumConsts(object):' ) for name in ( 'nmb_methods' , 'nmb_stages' ) : lines . add ( 1 , 'cdef public %s %s' % ( TYPE2STR [ int ] , name ) ) for name in ( 'dt_increase' , 'dt_decrease' ) : lines . add ( 1 , 'cdef public %s %s' % ( TYPE2STR [ float ] , name ) ) lines . add ( 1 , 'cdef public configutils.Config pub' ) lines . add ( 1 , 'cdef public double[:, :, :] a_coefs' ) lines . add ( 0 , 'cdef class NumVars(object):' ) for name in ( 'nmb_calls' , 'idx_method' , 'idx_stage' ) : lines . add ( 1 , 'cdef public %s %s' % ( TYPE2STR [ int ] , name ) ) for name in ( 't0' , 't1' , 'dt' , 'dt_est' , 'error' , 'last_error' , 'extrapolated_error' ) : lines . add ( 1 , 'cdef public %s %s' % ( TYPE2STR [ float ] , name ) ) lines . add ( 1 , 'cdef public %s f0_ready' % TYPE2STR [ bool ] ) return lines
Numeric parameter declaration lines .
729
def modeldeclarations ( self ) : lines = Lines ( ) lines . add ( 0 , '@cython.final' ) lines . add ( 0 , 'cdef class Model(object):' ) lines . add ( 1 , 'cdef public int idx_sim' ) lines . add ( 1 , 'cdef public Parameters parameters' ) lines . add ( 1 , 'cdef public Sequences sequences' ) if hasattr ( self . model , 'numconsts' ) : lines . add ( 1 , 'cdef public NumConsts numconsts' ) if hasattr ( self . model , 'numvars' ) : lines . add ( 1 , 'cdef public NumVars numvars' ) return lines
Attribute declarations of the model class .
730
def modelstandardfunctions ( self ) : lines = Lines ( ) lines . extend ( self . doit ) lines . extend ( self . iofunctions ) lines . extend ( self . new2old ) lines . extend ( self . run ) lines . extend ( self . update_inlets ) lines . extend ( self . update_outlets ) lines . extend ( self . update_receivers ) lines . extend ( self . update_senders ) return lines
Standard functions of the model class .
731
def modelnumericfunctions ( self ) : lines = Lines ( ) lines . extend ( self . solve ) lines . extend ( self . calculate_single_terms ) lines . extend ( self . calculate_full_terms ) lines . extend ( self . get_point_states ) lines . extend ( self . set_point_states ) lines . extend ( self . set_result_states ) lines . extend ( self . get_sum_fluxes ) lines . extend ( self . set_point_fluxes ) lines . extend ( self . set_result_fluxes ) lines . extend ( self . integrate_fluxes ) lines . extend ( self . reset_sum_fluxes ) lines . extend ( self . addup_fluxes ) lines . extend ( self . calculate_error ) lines . extend ( self . extrapolate_error ) return lines
Numerical functions of the model class .
732
def calculate_single_terms ( self ) : lines = self . _call_methods ( 'calculate_single_terms' , self . model . PART_ODE_METHODS ) if lines : lines . insert ( 1 , ( ' self.numvars.nmb_calls =' 'self.numvars.nmb_calls+1' ) ) return lines
Lines of model method with the same name .
733
def listofmodeluserfunctions ( self ) : lines = [ ] for ( name , member ) in vars ( self . model . __class__ ) . items ( ) : if ( inspect . isfunction ( member ) and ( name not in ( 'run' , 'new2old' ) ) and ( 'fastaccess' in inspect . getsource ( member ) ) ) : lines . append ( ( name , member ) ) run = vars ( self . model . __class__ ) . get ( 'run' ) if run is not None : lines . append ( ( 'run' , run ) ) for ( name , member ) in vars ( self . model ) . items ( ) : if ( inspect . ismethod ( member ) and ( 'fastaccess' in inspect . getsource ( member ) ) ) : lines . append ( ( name , member ) ) return lines
User functions of the model class .
734
def remove_linebreaks_within_equations ( code ) : r code = code . replace ( '\\\n' , '' ) chars = [ ] counter = 0 for char in code : if char in ( '(' , '[' , '{' ) : counter += 1 elif char in ( ')' , ']' , '}' ) : counter -= 1 if not ( counter and ( char == '\n' ) ) : chars . append ( char ) return '' . join ( chars )
r Remove line breaks within equations .
735
def remove_imath_operators ( lines ) : for idx , line in enumerate ( lines ) : for operator in ( '+=' , '-=' , '**=' , '*=' , '//=' , '/=' , '%=' ) : sublines = line . split ( operator ) if len ( sublines ) > 1 : indent = line . count ( ' ' ) - line . lstrip ( ) . count ( ' ' ) sublines = [ sl . strip ( ) for sl in sublines ] line = ( '%s%s = %s %s (%s)' % ( indent * ' ' , sublines [ 0 ] , sublines [ 0 ] , operator [ : - 1 ] , sublines [ 1 ] ) ) lines [ idx ] = line
Remove mathematical expressions that require Pythons global interpreter locking mechanism .
736
def pyxlines ( self ) : lines = [ ' ' + line for line in self . cleanlines ] lines [ 0 ] = lines [ 0 ] . replace ( 'def ' , 'cpdef inline void ' ) lines [ 0 ] = lines [ 0 ] . replace ( '):' , ') %s:' % _nogil ) for name in self . untypedarguments : lines [ 0 ] = lines [ 0 ] . replace ( ', %s ' % name , ', int %s ' % name ) lines [ 0 ] = lines [ 0 ] . replace ( ', %s)' % name , ', int %s)' % name ) for name in self . untypedinternalvarnames : if name . startswith ( 'd_' ) : lines . insert ( 1 , ' cdef double ' + name ) else : lines . insert ( 1 , ' cdef int ' + name ) return Lines ( * lines )
Cython code lines .
737
def calc_smoothpar_logistic2 ( metapar ) : if metapar <= 0. : return 0. return optimize . newton ( _error_smoothpar_logistic2 , .3 * metapar ** .84 , _smooth_logistic2_derivative , args = ( metapar , ) )
Return the smoothing parameter corresponding to the given meta parameter when using |smooth_logistic2| .
738
def from_cfunits ( cls , units ) -> 'Date' : try : string = units [ units . find ( 'since' ) + 6 : ] idx = string . find ( '.' ) if idx != - 1 : jdx = None for jdx , char in enumerate ( string [ idx + 1 : ] ) : if not char . isnumeric ( ) : break if char != '0' : raise ValueError ( 'No other decimal fraction of a second ' 'than "0" allowed.' ) else : if jdx is None : jdx = idx + 1 else : jdx += 1 string = f'{string[:idx]}{string[idx+jdx+1:]}' return cls ( string ) except BaseException : objecttools . augment_excmessage ( f'While trying to parse the date of the NetCDF-CF "units" ' f'string `{units}`' )
Return a |Date| object representing the reference date of the given units string agreeing with the NetCDF - CF conventions .
739
def to_cfunits ( self , unit = 'hours' , utcoffset = None ) : if utcoffset is None : utcoffset = hydpy . pub . options . utcoffset string = self . to_string ( 'iso2' , utcoffset ) string = ' ' . join ( ( string [ : - 6 ] , string [ - 6 : ] ) ) return f'{unit} since {string}'
Return a units string agreeing with the NetCDF - CF conventions .
740
def _set_thing ( self , thing , value ) : try : value = int ( value ) except ( TypeError , ValueError ) : raise TypeError ( f'Changing the {thing} of a `Date` instance is only ' f'allowed via numbers, but the given value `{value}` ' f'is of type `{type(value)}` instead.' ) kwargs = { } for unit in ( 'year' , 'month' , 'day' , 'hour' , 'minute' , 'second' ) : kwargs [ unit ] = getattr ( self , unit ) kwargs [ thing ] = value self . datetime = datetime . datetime ( ** kwargs )
Convenience method for _set_year _set_month ...
741
def wateryear ( self ) : if self . month < self . _firstmonth_wateryear : return self . year return self . year + 1
The actual hydrological year according to the selected reference month .
742
def fromseconds ( cls , seconds ) : try : seconds = int ( seconds ) except TypeError : seconds = int ( seconds . flatten ( ) [ 0 ] ) return cls ( datetime . timedelta ( 0 , int ( seconds ) ) )
Return a |Period| instance based on a given number of seconds .
743
def _guessunit ( self ) : if not self . days % 1 : return 'd' elif not self . hours % 1 : return 'h' elif not self . minutes % 1 : return 'm' elif not self . seconds % 1 : return 's' else : raise ValueError ( 'The stepsize is not a multiple of one ' 'second, which is not allowed.' )
Guess the unit of the period as the largest one which results in an integer duration .
744
def from_array ( cls , array ) : try : return cls ( Date . from_array ( array [ : 6 ] ) , Date . from_array ( array [ 6 : 12 ] ) , Period . fromseconds ( array [ 12 ] ) ) except IndexError : raise IndexError ( f'To define a Timegrid instance via an array, 13 ' f'numbers are required. However, the given array ' f'consist of {len(array)} entries/rows only.' )
Returns a |Timegrid| instance based on two date and one period information stored in the first 13 rows of a |numpy . ndarray| object .
745
def to_array ( self ) : values = numpy . empty ( 13 , dtype = float ) values [ : 6 ] = self . firstdate . to_array ( ) values [ 6 : 12 ] = self . lastdate . to_array ( ) values [ 12 ] = self . stepsize . seconds return values
Returns a 1 - dimensional |numpy| |numpy . ndarray| with thirteen entries first defining the start date secondly defining the end date and thirdly the step size in seconds .
746
def from_timepoints ( cls , timepoints , refdate , unit = 'hours' ) : refdate = Date ( refdate ) unit = Period . from_cfunits ( unit ) delta = timepoints [ 1 ] - timepoints [ 0 ] firstdate = refdate + timepoints [ 0 ] * unit lastdate = refdate + ( timepoints [ - 1 ] + delta ) * unit stepsize = ( lastdate - firstdate ) / len ( timepoints ) return cls ( firstdate , lastdate , stepsize )
Return a |Timegrid| object representing the given starting timepoints in relation to the given refdate .
747
def to_timepoints ( self , unit = 'hours' , offset = None ) : unit = Period . from_cfunits ( unit ) if offset is None : offset = 0. else : try : offset = Period ( offset ) / unit except TypeError : offset = offset step = self . stepsize / unit nmb = len ( self ) variable = numpy . linspace ( offset , offset + step * ( nmb - 1 ) , nmb ) return variable
Return an |numpy . ndarray| representing the starting time points of the |Timegrid| object .
748
def array2series ( self , array ) : try : array = numpy . array ( array , dtype = float ) except BaseException : objecttools . augment_excmessage ( 'While trying to prefix timegrid information to the ' 'given array' ) if len ( array ) != len ( self ) : raise ValueError ( f'When converting an array to a sequence, the lengths of the ' f'timegrid and the given array must be equal, but the length ' f'of the timegrid object is `{len(self)}` and the length of ' f'the array object is `{len(array)}`.' ) shape = list ( array . shape ) shape [ 0 ] += 13 series = numpy . full ( shape , numpy . nan ) slices = [ slice ( 0 , 13 ) ] subshape = [ 13 ] for dummy in range ( 1 , series . ndim ) : slices . append ( slice ( 0 , 1 ) ) subshape . append ( 1 ) series [ tuple ( slices ) ] = self . to_array ( ) . reshape ( subshape ) series [ 13 : ] = array return series
Prefix the information of the actual Timegrid object to the given array and return it .
749
def verify ( self ) : if self . firstdate >= self . lastdate : raise ValueError ( f'Unplausible timegrid. The first given date ' f'{self.firstdate}, the second given date is {self.lastdate}.' ) if ( self . lastdate - self . firstdate ) % self . stepsize : raise ValueError ( f'Unplausible timegrid. The period span between the given ' f'dates {self.firstdate} and {self.lastdate} is not ' f'a multiple of the given step size {self.stepsize}.' )
Raise an |ValueError| if the dates or the step size of the time frame are inconsistent .
750
def assignrepr ( self , prefix , style = None , utcoffset = None ) : skip = len ( prefix ) + 9 blanks = ' ' * skip return ( f"{prefix}Timegrid('" f"{self.firstdate.to_string(style, utcoffset)}',\n" f"{blanks}'{self.lastdate.to_string(style, utcoffset)}',\n" f"{blanks}'{str(self.stepsize)}')" )
Return a |repr| string with an prefixed assignement .
751
def verify ( self ) : self . init . verify ( ) self . sim . verify ( ) if self . init . firstdate > self . sim . firstdate : raise ValueError ( f'The first date of the initialisation period ' f'({self.init.firstdate}) must not be later ' f'than the first date of the simulation period ' f'({self.sim.firstdate}).' ) elif self . init . lastdate < self . sim . lastdate : raise ValueError ( f'The last date of the initialisation period ' f'({self.init.lastdate}) must not be earlier ' f'than the last date of the simulation period ' f'({self.sim.lastdate}).' ) elif self . init . stepsize != self . sim . stepsize : raise ValueError ( f'The initialization stepsize ({self.init.stepsize}) ' f'must be identical with the simulation stepsize ' f'({self.sim.stepsize}).' ) else : try : self . init [ self . sim . firstdate ] except ValueError : raise ValueError ( 'The simulation time grid is not properly ' 'alligned on the initialization time grid.' )
Raise an |ValueError| it the different time grids are inconsistent .
752
def seconds_passed ( self ) : return int ( ( Date ( self ) . datetime - self . _STARTDATE . datetime ) . total_seconds ( ) )
Amount of time passed in seconds since the beginning of the year .
753
def seconds_left ( self ) : return int ( ( self . _ENDDATE . datetime - Date ( self ) . datetime ) . total_seconds ( ) )
Remaining part of the year in seconds .
754
def centred_timegrid ( cls , simulationstep ) : simulationstep = Period ( simulationstep ) return Timegrid ( cls . _STARTDATE + simulationstep / 2 , cls . _ENDDATE + simulationstep / 2 , simulationstep )
Return a |Timegrid| object defining the central time points of the year 2000 for the given simulation step .
755
def dir_ ( self ) : names = set ( ) for thing in list ( inspect . getmro ( type ( self ) ) ) + [ self ] : for key in vars ( thing ) . keys ( ) : if hydpy . pub . options . dirverbose or not key . startswith ( '_' ) : names . add ( key ) if names : names = list ( names ) else : names = [ ' ' ] return names
The prefered way for HydPy objects to respond to |dir| .
756
def classname ( self ) : if inspect . isclass ( self ) : string = str ( self ) else : string = str ( type ( self ) ) try : string = string . split ( "'" ) [ 1 ] except IndexError : pass return string . split ( '.' ) [ - 1 ]
Return the class name of the given instance object or class .
757
def name ( self ) : cls = type ( self ) try : return cls . __dict__ [ '_name' ] except KeyError : setattr ( cls , '_name' , instancename ( self ) ) return cls . __dict__ [ '_name' ]
Name of the class of the given instance in lower case letters .
758
def valid_variable_identifier ( string ) : string = str ( string ) try : exec ( '%s = None' % string ) if string in dir ( builtins ) : raise SyntaxError ( ) except SyntaxError : raise ValueError ( 'The given name string `%s` does not define a valid variable ' 'identifier. Valid identifiers do not contain characters like ' '`-` or empty spaces, do not start with numbers, cannot be ' 'mistaken with Python built-ins like `for`...)' % string )
Raises an |ValueError| if the given name is not a valid Python identifier .
759
def augment_excmessage ( prefix = None , suffix = None ) -> NoReturn : exc_old = sys . exc_info ( ) [ 1 ] message = str ( exc_old ) if prefix is not None : message = f'{prefix}, the following error occurred: {message}' if suffix is not None : message = f'{message} {suffix}' try : exc_new = type ( exc_old ) ( message ) except BaseException : exc_name = str ( type ( exc_old ) ) . split ( "'" ) [ 1 ] exc_type = type ( exc_name , ( BaseException , ) , { } ) exc_type . __module = exc_old . __module__ raise exc_type ( message ) from exc_old raise exc_new from exc_old
Augment an exception message with additional information while keeping the original traceback .
760
def excmessage_decorator ( description ) -> Callable : @ wrapt . decorator def wrapper ( wrapped , instance , args , kwargs ) : try : return wrapped ( * args , ** kwargs ) except BaseException : info = kwargs . copy ( ) info [ 'self' ] = instance argnames = inspect . getfullargspec ( wrapped ) . args if argnames [ 0 ] == 'self' : argnames = argnames [ 1 : ] for argname , arg in zip ( argnames , args ) : info [ argname ] = arg for argname in argnames : if argname not in info : info [ argname ] = '?' message = eval ( f"f'While trying to {description}'" , globals ( ) , info ) augment_excmessage ( message ) return wrapper
Wrap a function with |augment_excmessage| .
761
def print_values ( values , width = 70 ) : for line in textwrap . wrap ( repr_values ( values ) , width = width ) : print ( line )
Print the given values in multiple lines with a certain maximum width .
762
def assignrepr_values ( values , prefix , width = None , _fakeend = 0 ) : ellipsis_ = hydpy . pub . options . ellipsis if ( ellipsis_ > 0 ) and ( len ( values ) > 2 * ellipsis_ ) : string = ( repr_values ( values [ : ellipsis_ ] ) + ', ...,' + repr_values ( values [ - ellipsis_ : ] ) ) else : string = repr_values ( values ) blanks = ' ' * len ( prefix ) if width is None : wrapped = [ string ] _fakeend = 0 else : width -= len ( prefix ) wrapped = textwrap . wrap ( string + '_' * _fakeend , width ) if not wrapped : wrapped = [ '' ] lines = [ ] for ( idx , line ) in enumerate ( wrapped ) : if idx == 0 : lines . append ( '%s%s' % ( prefix , line ) ) else : lines . append ( '%s%s' % ( blanks , line ) ) string = '\n' . join ( lines ) return string [ : len ( string ) - _fakeend ]
Return a prefixed wrapped and properly aligned string representation of the given values using function |repr| .
763
def assignrepr_values2 ( values , prefix ) : lines = [ ] blanks = ' ' * len ( prefix ) for ( idx , subvalues ) in enumerate ( values ) : if idx == 0 : lines . append ( '%s%s,' % ( prefix , repr_values ( subvalues ) ) ) else : lines . append ( '%s%s,' % ( blanks , repr_values ( subvalues ) ) ) lines [ - 1 ] = lines [ - 1 ] [ : - 1 ] return '\n' . join ( lines )
Return a prefixed and properly aligned string representation of the given 2 - dimensional value matrix using function |repr| .
764
def _assignrepr_bracketed2 ( assignrepr_bracketed1 , values , prefix , width = None ) : brackets = getattr ( assignrepr_bracketed1 , '_brackets' ) prefix += brackets [ 0 ] lines = [ ] blanks = ' ' * len ( prefix ) for ( idx , subvalues ) in enumerate ( values ) : if idx == 0 : lines . append ( assignrepr_bracketed1 ( subvalues , prefix , width ) ) else : lines . append ( assignrepr_bracketed1 ( subvalues , blanks , width ) ) lines [ - 1 ] += ',' if ( len ( values ) > 1 ) or ( brackets != '()' ) : lines [ - 1 ] = lines [ - 1 ] [ : - 1 ] lines [ - 1 ] += brackets [ 1 ] return '\n' . join ( lines )
Return a prefixed wrapped and properly aligned bracketed string representation of the given 2 - dimensional value matrix using function |repr| .
765
def round_ ( values , decimals = None , width = 0 , lfill = None , rfill = None , ** kwargs ) : if decimals is None : decimals = hydpy . pub . options . reprdigits with hydpy . pub . options . reprdigits ( decimals ) : if isinstance ( values , abctools . IterableNonStringABC ) : string = repr_values ( values ) else : string = repr_ ( values ) if ( lfill is not None ) and ( rfill is not None ) : raise ValueError ( 'For function `round_` values are passed for both arguments ' '`lfill` and `rfill`. This is not allowed.' ) if ( lfill is not None ) or ( rfill is not None ) : width = max ( width , len ( string ) ) if lfill is not None : string = string . rjust ( width , lfill ) else : string = string . ljust ( width , rfill ) print ( string , ** kwargs )
Prints values with a maximum number of digits in doctests .
766
def extract ( values , types , skip = False ) : if isinstance ( values , types ) : yield values elif skip and ( values is None ) : return else : try : for value in values : for subvalue in extract ( value , types , skip ) : yield subvalue except TypeError as exc : if exc . args [ 0 ] . startswith ( 'The given value' ) : raise exc else : raise TypeError ( f'The given value `{repr(values)}` is neither iterable ' f'nor an instance of the following classes: ' f'{enumeration(types, converter=instancename)}.' )
Return a generator that extracts certain objects from values .
767
def enumeration ( values , converter = str , default = '' ) : values = tuple ( converter ( value ) for value in values ) if not values : return default if len ( values ) == 1 : return values [ 0 ] if len ( values ) == 2 : return ' and ' . join ( values ) return ', and ' . join ( ( ', ' . join ( values [ : - 1 ] ) , values [ - 1 ] ) )
Return an enumeration string based on the given values .
768
def trim ( self , lower = None , upper = None ) : if upper is None : control = self . subseqs . seqs . model . parameters . control if not any ( control . zonetype . values == ILAKE ) : lower = 0. sequencetools . StateSequence . trim ( self , lower , upper )
Trim negative value whenever there is no internal lake within the respective subbasin .
769
def load_data ( self , idx ) : for subseqs in self : if isinstance ( subseqs , abctools . InputSequencesABC ) : subseqs . load_data ( idx )
Call method |InputSequences . load_data| of all handled |InputSequences| objects .
770
def save_data ( self , idx ) : for subseqs in self : if isinstance ( subseqs , abctools . OutputSequencesABC ) : subseqs . save_data ( idx )
Call method save_data| of all handled |IOSequences| objects registered under |OutputSequencesABC| .
771
def conditions ( self ) -> Dict [ str , Dict [ str , Union [ float , numpy . ndarray ] ] ] : conditions = { } for subname in NAMES_CONDITIONSEQUENCES : subseqs = getattr ( self , subname , ( ) ) subconditions = { seq . name : copy . deepcopy ( seq . values ) for seq in subseqs } if subconditions : conditions [ subname ] = subconditions return conditions
Nested dictionary containing the values of all condition sequences .
772
def dirpath_int ( self ) : try : return hydpy . pub . sequencemanager . tempdirpath except RuntimeError : raise RuntimeError ( f'For sequence {objecttools.devicephrase(self)} ' f'the directory of the internal data file cannot ' f'be determined. Either set it manually or prepare ' f'`pub.sequencemanager` correctly.' )
Absolute path of the directory of the internal data file .
773
def disk2ram ( self ) : values = self . series self . deactivate_disk ( ) self . ramflag = True self . __set_array ( values ) self . update_fastaccess ( )
Move internal data from disk to RAM .
774
def ram2disk ( self ) : values = self . series self . deactivate_ram ( ) self . diskflag = True self . _save_int ( values ) self . update_fastaccess ( )
Move internal data from RAM to disk .
775
def numericshape ( self ) : try : numericshape = [ self . subseqs . seqs . model . numconsts . nmb_stages ] except AttributeError : objecttools . augment_excmessage ( 'The `numericshape` of a sequence like `%s` depends on the ' 'configuration of the actual integration algorithm. ' 'While trying to query the required configuration data ' '`nmb_stages` of the model associated with element `%s`' % ( self . name , objecttools . devicename ( self ) ) ) numericshape . extend ( self . shape ) return tuple ( numericshape )
Shape of the array of temporary values required for the numerical solver actually being selected .
776
def series ( self ) -> InfoArray : if self . diskflag : array = self . _load_int ( ) elif self . ramflag : array = self . __get_array ( ) else : raise AttributeError ( f'Sequence {objecttools.devicephrase(self)} is not requested ' f'to make any internal data available to the user.' ) return InfoArray ( array , info = { 'type' : 'unmodified' } )
Internal time series data within an |numpy . ndarray| .
777
def load_ext ( self ) : try : sequencemanager = hydpy . pub . sequencemanager except AttributeError : raise RuntimeError ( 'The time series of sequence %s cannot be loaded. Firstly, ' 'you have to prepare `pub.sequencemanager` correctly.' % objecttools . devicephrase ( self ) ) sequencemanager . load_file ( self )
Read the internal data from an external data file .
778
def adjust_short_series ( self , timegrid , values ) : idxs = [ timegrid [ hydpy . pub . timegrids . init . firstdate ] , timegrid [ hydpy . pub . timegrids . init . lastdate ] ] valcopy = values values = numpy . full ( self . seriesshape , self . initinfo [ 0 ] ) len_ = len ( valcopy ) jdxs = [ ] for idx in idxs : if idx < 0 : jdxs . append ( 0 ) elif idx <= len_ : jdxs . append ( idx ) else : jdxs . append ( len_ ) valcopy = valcopy [ jdxs [ 0 ] : jdxs [ 1 ] ] zdx1 = max ( - idxs [ 0 ] , 0 ) zdx2 = zdx1 + jdxs [ 1 ] - jdxs [ 0 ] values [ zdx1 : zdx2 ] = valcopy return values
Adjust a short time series to a longer timegrid .
779
def check_completeness ( self ) : if hydpy . pub . options . checkseries : isnan = numpy . isnan ( self . series ) if numpy . any ( isnan ) : nmb = numpy . sum ( isnan ) valuestring = 'value' if nmb == 1 else 'values' raise RuntimeError ( f'The series array of sequence ' f'{objecttools.devicephrase(self)} contains ' f'{nmb} nan {valuestring}.' )
Raise a |RuntimeError| if the |IOSequence . series| contains at least one |numpy . nan| value if option |Options . checkseries| is enabled .
780
def save_ext ( self ) : try : sequencemanager = hydpy . pub . sequencemanager except AttributeError : raise RuntimeError ( 'The time series of sequence %s cannot be saved. Firstly,' 'you have to prepare `pub.sequencemanager` correctly.' % objecttools . devicephrase ( self ) ) sequencemanager . save_file ( self )
Write the internal data into an external data file .
781
def _load_int ( self ) : values = numpy . fromfile ( self . filepath_int ) if self . NDIM > 0 : values = values . reshape ( self . seriesshape ) return values
Load internal data from file and return it .
782
def average_series ( self , * args , ** kwargs ) -> InfoArray : try : if not self . NDIM : array = self . series else : mask = self . get_submask ( * args , ** kwargs ) if numpy . any ( mask ) : weights = self . refweights [ mask ] weights /= numpy . sum ( weights ) series = self . series [ : , mask ] axes = tuple ( range ( 1 , self . NDIM + 1 ) ) array = numpy . sum ( weights * series , axis = axes ) else : return numpy . nan return InfoArray ( array , info = { 'type' : 'mean' } ) except BaseException : objecttools . augment_excmessage ( 'While trying to calculate the mean value of ' 'the internal time series of sequence %s' % objecttools . devicephrase ( self ) )
Average the actual time series of the |Variable| object for all time points .
783
def aggregate_series ( self , * args , ** kwargs ) -> InfoArray : mode = self . aggregation_ext if mode == 'none' : return self . series elif mode == 'mean' : return self . average_series ( * args , ** kwargs ) else : raise RuntimeError ( 'Unknown aggregation mode `%s` for sequence %s.' % ( mode , objecttools . devicephrase ( self ) ) )
Aggregates time series data based on the actual |FluxSequence . aggregation_ext| attribute of |IOSequence| subclasses .
784
def open_files ( self , idx ) : for name in self : if getattr ( self , '_%s_diskflag' % name ) : path = getattr ( self , '_%s_path' % name ) file_ = open ( path , 'rb+' ) ndim = getattr ( self , '_%s_ndim' % name ) position = 8 * idx for idim in range ( ndim ) : length = getattr ( self , '_%s_length_%d' % ( name , idim ) ) position *= length file_ . seek ( position ) setattr ( self , '_%s_file' % name , file_ )
Open all files with an activated disk flag .
785
def close_files ( self ) : for name in self : if getattr ( self , '_%s_diskflag' % name ) : file_ = getattr ( self , '_%s_file' % name ) file_ . close ( )
Close all files with an activated disk flag .
786
def load_data ( self , idx ) : for name in self : ndim = getattr ( self , '_%s_ndim' % name ) diskflag = getattr ( self , '_%s_diskflag' % name ) ramflag = getattr ( self , '_%s_ramflag' % name ) if diskflag : file_ = getattr ( self , '_%s_file' % name ) length_tot = 1 shape = [ ] for jdx in range ( ndim ) : length = getattr ( self , '_%s_length_%s' % ( name , jdx ) ) length_tot *= length shape . append ( length ) raw = file_ . read ( length_tot * 8 ) values = struct . unpack ( length_tot * 'd' , raw ) if ndim : values = numpy . array ( values ) . reshape ( shape ) else : values = values [ 0 ] elif ramflag : array = getattr ( self , '_%s_array' % name ) values = array [ idx ] if diskflag or ramflag : if ndim == 0 : setattr ( self , name , values ) else : getattr ( self , name ) [ : ] = values
Load the internal data of all sequences . Load from file if the corresponding disk flag is activated otherwise load from RAM .
787
def save_data ( self , idx ) : for name in self : actual = getattr ( self , name ) diskflag = getattr ( self , '_%s_diskflag' % name ) ramflag = getattr ( self , '_%s_ramflag' % name ) if diskflag : file_ = getattr ( self , '_%s_file' % name ) ndim = getattr ( self , '_%s_ndim' % name ) length_tot = 1 for jdx in range ( ndim ) : length = getattr ( self , '_%s_length_%s' % ( name , jdx ) ) length_tot *= length if ndim : raw = struct . pack ( length_tot * 'd' , * actual . flatten ( ) ) else : raw = struct . pack ( 'd' , actual ) file_ . write ( raw ) elif ramflag : array = getattr ( self , '_%s_array' % name ) array [ idx ] = actual
Save the internal data of all sequences with an activated flag . Write to file if the corresponding disk flag is activated ; store in working memory if the corresponding ram flag is activated .
788
def update ( self ) : control = self . subpars . pars . control self ( control . ft * control . fhru )
Update |AbsFHRU| based on |FT| and |FHRU| .
789
def update ( self ) : con = self . subpars . pars . control self ( con . hinz * con . lai )
Update |KInz| based on |HInz| and |LAI| .
790
def update ( self ) : con = self . subpars . pars . control self ( con . relwb * con . nfk )
Update |WB| based on |RelWB| and |NFk| .
791
def update ( self ) : con = self . subpars . pars . control self ( con . relwz * con . nfk )
Update |WZ| based on |RelWZ| and |NFk| .
792
def update ( self ) : con = self . subpars . pars . control self ( con . eqb * con . tind )
Update |KB| based on |EQB| and |TInd| .
793
def update ( self ) : con = self . subpars . pars . control self ( con . eqi1 * con . tind )
Update |KI1| based on |EQI1| and |TInd| .
794
def update ( self ) : con = self . subpars . pars . control self ( con . eqi2 * con . tind )
Update |KI2| based on |EQI2| and |TInd| .
795
def update ( self ) : con = self . subpars . pars . control self ( con . eqd1 * con . tind )
Update |KD1| based on |EQD1| and |TInd| .
796
def update ( self ) : con = self . subpars . pars . control self ( con . eqd2 * con . tind )
Update |KD2| based on |EQD2| and |TInd| .
797
def update ( self ) : con = self . subpars . pars . control self ( con . ft * 1000. / self . simulationstep . seconds )
Update |QFactor| based on |FT| and the current simulation step size .
798
def _router_numbers ( self ) : return tuple ( up for up in self . _up2down . keys ( ) if up in self . _up2down . values ( ) )
A tuple of the numbers of all routing basins .
799
def supplier_elements ( self ) : elements = devicetools . Elements ( ) for supplier in self . _supplier_numbers : element = self . _get_suppliername ( supplier ) try : outlet = self . _get_nodename ( self . _up2down [ supplier ] ) except TypeError : outlet = self . last_node elements += devicetools . Element ( element , outlets = outlet ) return elements
A |Elements| collection of all supplying basins .