idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
500
def prepare_obsseries ( self , ramflag : bool = True ) -> None : for node in printtools . progressbar ( self ) : node . prepare_obsseries ( ramflag )
Call method |Node . prepare_obsseries| of all handled |Node| objects .
501
def init_models ( self ) -> None : try : for element in printtools . progressbar ( self ) : element . init_model ( clear_registry = False ) finally : hydpy . pub . controlmanager . clear_registry ( )
Call method |Element . init_model| of all handle |Element| objects .
502
def save_controls ( self , parameterstep : 'timetools.PeriodConstrArg' = None , simulationstep : 'timetools.PeriodConstrArg' = None , auxfiler : 'Optional[auxfiletools.Auxfiler]' = None ) : if auxfiler : auxfiler . save ( parameterstep , simulationstep ) for element in printtools . progressbar ( self ) : element . model . parameters . save_controls ( parameterstep = parameterstep , simulationstep = simulationstep , auxfiler = auxfiler )
Save the control parameters of the |Model| object handled by each |Element| object and eventually the ones handled by the given |Auxfiler| object .
503
def load_conditions ( self ) -> None : for element in printtools . progressbar ( self ) : element . model . sequences . load_conditions ( )
Save the initial conditions of the |Model| object handled by each |Element| object .
504
def save_conditions ( self ) -> None : for element in printtools . progressbar ( self ) : element . model . sequences . save_conditions ( )
Save the calculated conditions of the |Model| object handled by each |Element| object .
505
def conditions ( self ) -> Dict [ str , Dict [ str , Dict [ str , Union [ float , numpy . ndarray ] ] ] ] : return { element . name : element . model . sequences . conditions for element in self }
A nested dictionary containing the values of all |ConditionSequence| objects of all currently handled models .
506
def prepare_allseries ( self , ramflag : bool = True ) -> None : for element in printtools . progressbar ( self ) : element . prepare_allseries ( ramflag )
Call method |Element . prepare_allseries| of all handled |Element| objects .
507
def prepare_inputseries ( self , ramflag : bool = True ) -> None : for element in printtools . progressbar ( self ) : element . prepare_inputseries ( ramflag )
Call method |Element . prepare_inputseries| of all handled |Element| objects .
508
def prepare_fluxseries ( self , ramflag : bool = True ) -> None : for element in printtools . progressbar ( self ) : element . prepare_fluxseries ( ramflag )
Call method |Element . prepare_fluxseries| of all handled |Element| objects .
509
def prepare_stateseries ( self , ramflag : bool = True ) -> None : for element in printtools . progressbar ( self ) : element . prepare_stateseries ( ramflag )
Call method |Element . prepare_stateseries| of all handled |Element| objects .
510
def extract_new ( cls ) -> DevicesTypeUnbound : devices = cls . get_handlerclass ( ) ( * _selection [ cls ] ) _selection [ cls ] . clear ( ) return devices
Gather all new |Node| or |Element| objects .
511
def get_double ( self , group : str ) -> pointerutils . Double : if group in ( 'inlets' , 'receivers' ) : if self . deploymode != 'obs' : return self . sequences . fastaccess . sim return self . sequences . fastaccess . obs if group in ( 'outlets' , 'senders' ) : if self . deploymode != 'oldsim' : return self . sequences . fastaccess . sim return self . __blackhole raise ValueError ( f'Function `get_double` of class `Node` does not ' f'support the given group name `{group}`.' )
Return the |Double| object appropriate for the given |Element| input or output group and the actual |Node . deploymode| .
512
def plot_simseries ( self , ** kwargs : Any ) -> None : self . __plot_series ( [ self . sequences . sim ] , kwargs )
Plot the |IOSequence . series| of the |Sim| sequence object .
513
def plot_obsseries ( self , ** kwargs : Any ) -> None : self . __plot_series ( [ self . sequences . obs ] , kwargs )
Plot the |IOSequence . series| of the |Obs| sequence object .
514
def model ( self ) -> 'modeltools.Model' : model = vars ( self ) . get ( 'model' ) if model : return model raise AttributeError ( f'The model object of element `{self.name}` has ' f'been requested but not been prepared so far.' )
The |Model| object handled by the actual |Element| object .
515
def variables ( self ) -> Set [ str ] : variables : Set [ str ] = set ( ) for connection in self . __connections : variables . update ( connection . variables ) return variables
A set of all different |Node . variable| values of the |Node| objects directly connected to the actual |Element| object .
516
def prepare_allseries ( self , ramflag : bool = True ) -> None : self . prepare_inputseries ( ramflag ) self . prepare_fluxseries ( ramflag ) self . prepare_stateseries ( ramflag )
Prepare the |IOSequence . series| objects of all input flux and state sequences of the model handled by this element .
517
def plot_fluxseries ( self , names : Optional [ Iterable [ str ] ] = None , average : bool = False , ** kwargs : Any ) -> None : self . __plot ( self . model . sequences . fluxes , names , average , kwargs )
Plot the flux series of the handled model .
518
def plot_stateseries ( self , names : Optional [ Iterable [ str ] ] = None , average : bool = False , ** kwargs : Any ) -> None : self . __plot ( self . model . sequences . states , names , average , kwargs )
Plot the state series of the handled model .
519
def _init_methods ( self ) : for name_group in self . _METHOD_GROUPS : functions = getattr ( self , name_group , ( ) ) uniques = { } for func in functions : name_func = func . __name__ method = types . MethodType ( func , self ) setattr ( self , name_func , method ) shortname = '_' . join ( name_func . split ( '_' ) [ : - 1 ] ) if shortname in uniques : uniques [ shortname ] = None else : uniques [ shortname ] = method for ( shortname , method ) in uniques . items ( ) : if method is not None : setattr ( self , shortname , method )
Convert all pure Python calculation functions of the model class to methods and assign them to the model instance .
520
def name ( self ) : name = self . __name if name : return name subs = self . __module__ . split ( '.' ) if len ( subs ) == 2 : type ( self ) . __name = subs [ 1 ] else : type ( self ) . __name = subs [ 2 ] return self . __name
Name of the model type .
521
def connect ( self ) : try : for group in ( 'inlets' , 'receivers' , 'outlets' , 'senders' ) : self . _connect_subgroup ( group ) except BaseException : objecttools . augment_excmessage ( 'While trying to build the node connection of the `%s` ' 'sequences of the model handled by element `%s`' % ( group [ : - 1 ] , objecttools . devicename ( self ) ) )
Connect the link sequences of the actual model .
522
def calculate_single_terms ( self ) : self . numvars . nmb_calls = self . numvars . nmb_calls + 1 for method in self . PART_ODE_METHODS : method ( self )
Apply all methods stored in the hidden attribute PART_ODE_METHODS .
523
def get_sum_fluxes ( self ) : fluxes = self . sequences . fluxes for flux in fluxes . numerics : flux ( getattr ( fluxes . fastaccess , '_%s_sum' % flux . name ) )
Get the sum of the fluxes calculated so far .
524
def integrate_fluxes ( self ) : fluxes = self . sequences . fluxes for flux in fluxes . numerics : points = getattr ( fluxes . fastaccess , '_%s_points' % flux . name ) coefs = self . numconsts . a_coefs [ self . numvars . idx_method - 1 , self . numvars . idx_stage , : self . numvars . idx_method ] flux ( self . numvars . dt * numpy . dot ( coefs , points [ : self . numvars . idx_method ] ) )
Perform a dot multiplication between the fluxes and the A coefficients associated with the different stages of the actual method .
525
def reset_sum_fluxes ( self ) : fluxes = self . sequences . fluxes for flux in fluxes . numerics : if flux . NDIM == 0 : setattr ( fluxes . fastaccess , '_%s_sum' % flux . name , 0. ) else : getattr ( fluxes . fastaccess , '_%s_sum' % flux . name ) [ : ] = 0.
Set the sum of the fluxes calculated so far to zero .
526
def addup_fluxes ( self ) : fluxes = self . sequences . fluxes for flux in fluxes . numerics : sum_ = getattr ( fluxes . fastaccess , '_%s_sum' % flux . name ) sum_ += flux if flux . NDIM == 0 : setattr ( fluxes . fastaccess , '_%s_sum' % flux . name , sum_ )
Add up the sum of the fluxes calculated so far .
527
def calculate_error ( self ) : self . numvars . error = 0. fluxes = self . sequences . fluxes for flux in fluxes . numerics : results = getattr ( fluxes . fastaccess , '_%s_results' % flux . name ) diff = ( results [ self . numvars . idx_method ] - results [ self . numvars . idx_method - 1 ] ) self . numvars . error = max ( self . numvars . error , numpy . max ( numpy . abs ( diff ) ) )
Estimate the numerical error based on the fluxes calculated by the current and the last method .
528
def extrapolate_error ( self ) : if self . numvars . idx_method > 2 : self . numvars . extrapolated_error = modelutils . exp ( modelutils . log ( self . numvars . error ) + ( modelutils . log ( self . numvars . error ) - modelutils . log ( self . numvars . last_error ) ) * ( self . numconsts . nmb_methods - self . numvars . idx_method ) ) else : self . numvars . extrapolated_error = - 999.9
Estimate the numerical error to be expected when applying all methods available based on the results of the current and the last method .
529
def run_simulation ( projectname : str , xmlfile : str ) : write = commandtools . print_textandtime hydpy . pub . options . printprogress = False write ( f'Start HydPy project `{projectname}`' ) hp = hydpytools . HydPy ( projectname ) write ( f'Read configuration file `{xmlfile}`' ) interface = XMLInterface ( xmlfile ) write ( 'Interpret the defined options' ) interface . update_options ( ) hydpy . pub . options . printprogress = False write ( 'Interpret the defined period' ) interface . update_timegrids ( ) write ( 'Read all network files' ) hp . prepare_network ( ) write ( 'Activate the selected network' ) hp . update_devices ( interface . fullselection ) write ( 'Read the required control files' ) hp . init_models ( ) write ( 'Read the required condition files' ) interface . conditions_io . load_conditions ( ) write ( 'Read the required time series files' ) interface . series_io . prepare_series ( ) interface . series_io . load_series ( ) write ( 'Perform the simulation run' ) hp . doit ( ) write ( 'Write the desired condition files' ) interface . conditions_io . save_conditions ( ) write ( 'Write the desired time series files' ) interface . series_io . save_series ( )
Perform a HydPy workflow in agreement with the given XML configuration file available in the directory of the given project . ToDo
530
def validate_xml ( self ) -> None : try : filenames = ( 'HydPyConfigSingleRun.xsd' , 'HydPyConfigMultipleRuns.xsd' ) for name in filenames : if name in self . root . tag : schemafile = name break else : raise RuntimeError ( f'Configuration file `{os.path.split(self.filepath)[-1]}` ' f'does not correctly refer to one of the available XML ' f'schema files ({objecttools.enumeration(filenames)}).' ) schemapath = os . path . join ( conf . __path__ [ 0 ] , schemafile ) schema = xmlschema . XMLSchema ( schemapath ) schema . validate ( self . filepath ) except BaseException : objecttools . augment_excmessage ( f'While trying to validate XML file `{self.filepath}`' )
Raise an error if the actual XML does not agree with one of the available schema files .
531
def update_options ( self ) -> None : options = hydpy . pub . options for option in self . find ( 'options' ) : value = option . text if value in ( 'true' , 'false' ) : value = value == 'true' setattr ( options , strip ( option . tag ) , value ) options . printprogress = False options . printincolor = False
Update the |Options| object available in module |pub| with the values defined in the options XML element .
532
def update_timegrids ( self ) -> None : timegrid_xml = self . find ( 'timegrid' ) try : timegrid = timetools . Timegrid ( * ( timegrid_xml [ idx ] . text for idx in range ( 3 ) ) ) hydpy . pub . timegrids = timetools . Timegrids ( timegrid ) except IndexError : seriesfile = find ( timegrid_xml , 'seriesfile' ) . text with netcdf4 . Dataset ( seriesfile ) as ncfile : hydpy . pub . timegrids = timetools . Timegrids ( netcdftools . query_timegrid ( ncfile ) )
Update the |Timegrids| object available in module |pub| with the values defined in the timegrid XML element .
533
def elements ( self ) -> Iterator [ devicetools . Element ] : selections = copy . copy ( self . selections ) selections += self . devices elements = set ( ) for selection in selections : for element in selection . elements : if element not in elements : elements . add ( element ) yield element
Yield all |Element| objects returned by |XMLInterface . selections| and |XMLInterface . devices| without duplicates .
534
def fullselection ( self ) -> selectiontools . Selection : fullselection = selectiontools . Selection ( 'fullselection' ) for selection in self . selections : fullselection += selection fullselection += self . devices return fullselection
A |Selection| object containing all |Element| and |Node| objects defined by |XMLInterface . selections| and |XMLInterface . devices| .
535
def prepare_series ( self ) -> None : memory = set ( ) for output in itertools . chain ( self . readers , self . writers ) : output . prepare_series ( memory )
Call |XMLSubseries . prepare_series| of all |XMLSubseries| objects with the same memory |set| object .
536
def selections ( self ) -> selectiontools . Selections : selections = self . find ( 'selections' ) master = self while selections is None : master = master . master selections = master . find ( 'selections' ) return _query_selections ( selections )
The |Selections| object defined for the respective reader or writer element of the actual XML file . ToDo
537
def devices ( self ) -> selectiontools . Selection : devices = self . find ( 'devices' ) master = self while devices is None : master = master . master devices = master . find ( 'devices' ) return _query_devices ( devices )
The additional devices defined for the respective reader or writer element contained within a |Selection| object . ToDo
538
def prepare_sequencemanager ( self ) -> None : for config , convert in ( ( 'filetype' , lambda x : x ) , ( 'aggregation' , lambda x : x ) , ( 'overwrite' , lambda x : x . lower ( ) == 'true' ) , ( 'dirpath' , lambda x : x ) ) : xml_special = self . find ( config ) xml_general = self . master . find ( config ) for name_manager , name_xml in zip ( ( 'input' , 'flux' , 'state' , 'node' ) , ( 'inputs' , 'fluxes' , 'states' , 'nodes' ) ) : value = None for xml , attr_xml in zip ( ( xml_special , xml_special , xml_general , xml_general ) , ( name_xml , 'general' , name_xml , 'general' ) ) : try : value = find ( xml , attr_xml ) . text except AttributeError : continue break setattr ( hydpy . pub . sequencemanager , f'{name_manager}{config}' , convert ( value ) )
Configure the |SequenceManager| object available in module |pub| following the definitions of the actual XML reader or writer element when available ; if not use those of the XML series_io element .
539
def model2subs2seqs ( self ) -> Dict [ str , Dict [ str , List [ str ] ] ] : model2subs2seqs = collections . defaultdict ( lambda : collections . defaultdict ( list ) ) for model in self . find ( 'sequences' ) : model_name = strip ( model . tag ) if model_name == 'node' : continue for group in model : group_name = strip ( group . tag ) for sequence in group : seq_name = strip ( sequence . tag ) model2subs2seqs [ model_name ] [ group_name ] . append ( seq_name ) return model2subs2seqs
A nested |collections . defaultdict| containing the model specific information provided by the XML sequences element .
540
def subs2seqs ( self ) -> Dict [ str , List [ str ] ] : subs2seqs = collections . defaultdict ( list ) nodes = find ( self . find ( 'sequences' ) , 'node' ) if nodes is not None : for seq in nodes : subs2seqs [ 'node' ] . append ( strip ( seq . tag ) ) return subs2seqs
A |collections . defaultdict| containing the node - specific information provided by XML sequences element .
541
def prepare_series ( self , memory : set ) -> None : for sequence in self . _iterate_sequences ( ) : if sequence not in memory : memory . add ( sequence ) sequence . activate_ram ( )
Call |IOSequence . activate_ram| of all sequences selected by the given output element of the actual XML file .
542
def load_series ( self ) -> None : kwargs = { } for keyword in ( 'flattennetcdf' , 'isolatenetcdf' , 'timeaxisnetcdf' ) : argument = getattr ( hydpy . pub . options , keyword , None ) if argument is not None : kwargs [ keyword [ : - 6 ] ] = argument hydpy . pub . sequencemanager . open_netcdf_reader ( ** kwargs ) self . prepare_sequencemanager ( ) for sequence in self . _iterate_sequences ( ) : sequence . load_ext ( ) hydpy . pub . sequencemanager . close_netcdf_reader ( )
Load time series data as defined by the actual XML reader element .
543
def save_series ( self ) -> None : hydpy . pub . sequencemanager . open_netcdf_writer ( flatten = hydpy . pub . options . flattennetcdf , isolate = hydpy . pub . options . isolatenetcdf ) self . prepare_sequencemanager ( ) for sequence in self . _iterate_sequences ( ) : sequence . save_ext ( ) hydpy . pub . sequencemanager . close_netcdf_writer ( )
Save time series data as defined by the actual XML writer element .
544
def write_xsd ( cls ) -> None : with open ( cls . filepath_source ) as file_ : template = file_ . read ( ) template = template . replace ( '<!--include model sequence groups , cls . get_insertion ( ) ) template = template . replace ( '<!--include exchange items , cls . get_exchangeinsertion ( ) ) with open ( cls . filepath_target , 'w' ) as file_ : file_ . write ( template )
Write the complete base schema file HydPyConfigBase . xsd based on the template file HydPyConfigBase . xsdt .
545
def get_modelnames ( ) -> List [ str ] : return sorted ( str ( fn . split ( '.' ) [ 0 ] ) for fn in os . listdir ( models . __path__ [ 0 ] ) if ( fn . endswith ( '.py' ) and ( fn != '__init__.py' ) ) )
Return a sorted |list| containing all application model names .
546
def get_insertion ( cls ) -> str : indent = 1 blanks = ' ' * ( indent + 4 ) subs = [ ] for name in cls . get_modelnames ( ) : subs . extend ( [ f'{blanks}<element name="{name}"' , f'{blanks} substitutionGroup="hpcb:sequenceGroup"' , f'{blanks} type="hpcb:{name}Type"/>' , f'' , f'{blanks}<complexType name="{name}Type">' , f'{blanks} <complexContent>' , f'{blanks} <extension base="hpcb:sequenceGroupType">' , f'{blanks} <sequence>' ] ) model = importtools . prepare_model ( name ) subs . append ( cls . get_modelinsertion ( model , indent + 4 ) ) subs . extend ( [ f'{blanks} </sequence>' , f'{blanks} </extension>' , f'{blanks} </complexContent>' , f'{blanks}</complexType>' , f'' ] ) return '\n' . join ( subs )
Return the complete string to be inserted into the string of the template file .
547
def get_modelinsertion ( cls , model , indent ) -> str : texts = [ ] for name in ( 'inputs' , 'fluxes' , 'states' ) : subsequences = getattr ( model . sequences , name , None ) if subsequences : texts . append ( cls . get_subsequencesinsertion ( subsequences , indent ) ) return '\n' . join ( texts )
Return the insertion string required for the given application model .
548
def get_subsequencesinsertion ( cls , subsequences , indent ) -> str : blanks = ' ' * ( indent * 4 ) lines = [ f'{blanks}<element name="{subsequences.name}"' , f'{blanks} minOccurs="0">' , f'{blanks} <complexType>' , f'{blanks} <sequence>' ] for sequence in subsequences : lines . append ( cls . get_sequenceinsertion ( sequence , indent + 3 ) ) lines . extend ( [ f'{blanks} </sequence>' , f'{blanks} </complexType>' , f'{blanks}</element>' ] ) return '\n' . join ( lines )
Return the insertion string required for the given group of sequences .
549
def get_exchangeinsertion ( cls ) : indent = 1 subs = [ cls . get_mathitemsinsertion ( indent ) ] for groupname in ( 'setitems' , 'additems' , 'getitems' ) : subs . append ( cls . get_itemsinsertion ( groupname , indent ) ) subs . append ( cls . get_itemtypesinsertion ( groupname , indent ) ) return '\n' . join ( subs )
Return the complete string related to the definition of exchange items to be inserted into the string of the template file .
550
def get_mathitemsinsertion ( cls , indent ) -> str : blanks = ' ' * ( indent * 4 ) subs = [ ] for modelname in cls . get_modelnames ( ) : model = importtools . prepare_model ( modelname ) subs . extend ( [ f'{blanks}<complexType name="{modelname}_mathitemType">' , f'{blanks} <complexContent>' , f'{blanks} <extension base="hpcb:setitemType">' , f'{blanks} <choice>' ] ) for subvars in cls . _get_subvars ( model ) : for var in subvars : subs . append ( f'{blanks} ' f'<element name="{subvars.name}.{var.name}"/>' ) subs . extend ( [ f'{blanks} </choice>' , f'{blanks} </extension>' , f'{blanks} </complexContent>' , f'{blanks}</complexType>' , f'' ] ) return '\n' . join ( subs )
Return a string defining a model specific XML type extending ItemType .
551
def get_itemsinsertion ( cls , itemgroup , indent ) -> str : blanks = ' ' * ( indent * 4 ) subs = [ ] subs . extend ( [ f'{blanks}<element name="{itemgroup}">' , f'{blanks} <complexType>' , f'{blanks} <sequence>' , f'{blanks} <element ref="hpcb:selections"' , f'{blanks} minOccurs="0"/>' , f'{blanks} <element ref="hpcb:devices"' , f'{blanks} minOccurs="0"/>' ] ) for modelname in cls . get_modelnames ( ) : type_ = cls . _get_itemstype ( modelname , itemgroup ) subs . append ( f'{blanks} <element name="{modelname}"' ) subs . append ( f'{blanks} type="hpcb:{type_}"' ) subs . append ( f'{blanks} minOccurs="0"' ) subs . append ( f'{blanks} maxOccurs="unbounded"/>' ) if itemgroup in ( 'setitems' , 'getitems' ) : type_ = f'nodes_{itemgroup}Type' subs . append ( f'{blanks} <element name="nodes"' ) subs . append ( f'{blanks} type="hpcb:{type_}"' ) subs . append ( f'{blanks} minOccurs="0"' ) subs . append ( f'{blanks} maxOccurs="unbounded"/>' ) subs . extend ( [ f'{blanks} </sequence>' , f'{blanks} <attribute name="info" type="string"/>' , f'{blanks} </complexType>' , f'{blanks}</element>' , f'' ] ) return '\n' . join ( subs )
Return a string defining the XML element for the given exchange item group .
552
def get_itemtypesinsertion ( cls , itemgroup , indent ) -> str : subs = [ ] for modelname in cls . get_modelnames ( ) : subs . append ( cls . get_itemtypeinsertion ( itemgroup , modelname , indent ) ) subs . append ( cls . get_nodesitemtypeinsertion ( itemgroup , indent ) ) return '\n' . join ( subs )
Return a string defining the required types for the given exchange item group .
553
def get_nodesitemtypeinsertion ( cls , itemgroup , indent ) -> str : blanks = ' ' * ( indent * 4 ) subs = [ f'{blanks}<complexType name="nodes_{itemgroup}Type">' , f'{blanks} <sequence>' , f'{blanks} <element ref="hpcb:selections"' , f'{blanks} minOccurs="0"/>' , f'{blanks} <element ref="hpcb:devices"' , f'{blanks} minOccurs="0"/>' ] type_ = 'getitemType' if itemgroup == 'getitems' else 'setitemType' for name in ( 'sim' , 'obs' , 'sim.series' , 'obs.series' ) : subs . extend ( [ f'{blanks} <element name="{name}"' , f'{blanks} type="hpcb:{type_}"' , f'{blanks} minOccurs="0"' , f'{blanks} maxOccurs="unbounded"/>' ] ) subs . extend ( [ f'{blanks} </sequence>' , f'{blanks}</complexType>' , f'' ] ) return '\n' . join ( subs )
Return a string defining the required types for the given combination of an exchange item group and |Node| objects .
554
def get_subgroupiteminsertion ( cls , itemgroup , model , subgroup , indent ) -> str : blanks1 = ' ' * ( indent * 4 ) blanks2 = ' ' * ( ( indent + 5 ) * 4 + 1 ) subs = [ f'{blanks1}<element name="{subgroup.name}"' , f'{blanks1} minOccurs="0"' , f'{blanks1} maxOccurs="unbounded">' , f'{blanks1} <complexType>' , f'{blanks1} <sequence>' , f'{blanks1} <element ref="hpcb:selections"' , f'{blanks1} minOccurs="0"/>' , f'{blanks1} <element ref="hpcb:devices"' , f'{blanks1} minOccurs="0"/>' ] seriesflags = ( False , ) if subgroup . name == 'control' else ( False , True ) for variable in subgroup : for series in seriesflags : name = f'{variable.name}.series' if series else variable . name subs . append ( f'{blanks1} <element name="{name}"' ) if itemgroup == 'setitems' : subs . append ( f'{blanks2}type="hpcb:setitemType"' ) elif itemgroup == 'getitems' : subs . append ( f'{blanks2}type="hpcb:getitemType"' ) else : subs . append ( f'{blanks2}type="hpcb:{model.name}_mathitemType"' ) subs . append ( f'{blanks2}minOccurs="0"' ) subs . append ( f'{blanks2}maxOccurs="unbounded"/>' ) subs . extend ( [ f'{blanks1} </sequence>' , f'{blanks1} </complexType>' , f'{blanks1}</element>' ] ) return '\n' . join ( subs )
Return a string defining the required types for the given combination of an exchange item group and a specific variable subgroup of an application model or class |Node| .
555
def array2mask ( cls , array = None , ** kwargs ) : kwargs [ 'dtype' ] = bool if array is None : return numpy . ndarray . __new__ ( cls , 0 , ** kwargs ) return numpy . asarray ( array , ** kwargs ) . view ( cls )
Create a new mask object based on the given |numpy . ndarray| and return it .
556
def new ( cls , variable , ** kwargs ) : return cls . array2mask ( numpy . full ( variable . shape , True ) )
Return a new |DefaultMask| object associated with the given |Variable| object .
557
def new ( cls , variable , ** kwargs ) : indices = cls . get_refindices ( variable ) if numpy . min ( getattr ( indices , 'values' , 0 ) ) < 1 : raise RuntimeError ( f'The mask of parameter {objecttools.elementphrase(variable)} ' f'cannot be determined, as long as parameter `{indices.name}` ' f'is not prepared properly.' ) mask = numpy . full ( indices . shape , False , dtype = bool ) refvalues = indices . values for relvalue in cls . RELEVANT_VALUES : mask [ refvalues == relvalue ] = True return cls . array2mask ( mask , ** kwargs )
Return a new |IndexMask| object of the same shape as the parameter referenced by |property| |IndexMask . refindices| . Entries are only |True| if the integer values of the respective entries of the referenced parameter are contained in the |IndexMask| class attribute tuple RELEVANT_VALUES .
558
def calc_qref_v1 ( self ) : new = self . sequences . states . fastaccess_new old = self . sequences . states . fastaccess_old flu = self . sequences . fluxes . fastaccess flu . qref = ( new . qz + old . qz + old . qa ) / 3.
Determine the reference discharge within the given space - time interval .
559
def calc_am_um_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess if flu . h <= 0. : flu . am = 0. flu . um = 0. elif flu . h < con . hm : flu . am = flu . h * ( con . bm + flu . h * con . bnm ) flu . um = con . bm + 2. * flu . h * ( 1. + con . bnm ** 2 ) ** .5 else : flu . am = ( con . hm * ( con . bm + con . hm * con . bnm ) + ( ( flu . h - con . hm ) * ( con . bm + 2. * con . hm * con . bnm ) ) ) flu . um = con . bm + ( 2. * con . hm * ( 1. + con . bnm ** 2 ) ** .5 ) + ( 2 * ( flu . h - con . hm ) )
Calculate the flown through area and the wetted perimeter of the main channel .
560
def calc_qm_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess if ( flu . am > 0. ) and ( flu . um > 0. ) : flu . qm = con . ekm * con . skm * flu . am ** ( 5. / 3. ) / flu . um ** ( 2. / 3. ) * con . gef ** .5 else : flu . qm = 0.
Calculate the discharge of the main channel after Manning - Strickler .
561
def calc_av_uv_v1 ( self ) : con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess for i in range ( 2 ) : if flu . h <= con . hm : flu . av [ i ] = 0. flu . uv [ i ] = 0. elif flu . h <= ( con . hm + der . hv [ i ] ) : flu . av [ i ] = ( flu . h - con . hm ) * ( con . bv [ i ] + ( flu . h - con . hm ) * con . bnv [ i ] / 2. ) flu . uv [ i ] = con . bv [ i ] + ( flu . h - con . hm ) * ( 1. + con . bnv [ i ] ** 2 ) ** .5 else : flu . av [ i ] = ( der . hv [ i ] * ( con . bv [ i ] + der . hv [ i ] * con . bnv [ i ] / 2. ) + ( ( flu . h - ( con . hm + der . hv [ i ] ) ) * ( con . bv [ i ] + der . hv [ i ] * con . bnv [ i ] ) ) ) flu . uv [ i ] = ( ( con . bv [ i ] ) + ( der . hv [ i ] * ( 1. + con . bnv [ i ] ** 2 ) ** .5 ) + ( flu . h - ( con . hm + der . hv [ i ] ) ) )
Calculate the flown through area and the wetted perimeter of both forelands .
562
def calc_qv_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess for i in range ( 2 ) : if ( flu . av [ i ] > 0. ) and ( flu . uv [ i ] > 0. ) : flu . qv [ i ] = ( con . ekv [ i ] * con . skv [ i ] * flu . av [ i ] ** ( 5. / 3. ) / flu . uv [ i ] ** ( 2. / 3. ) * con . gef ** .5 ) else : flu . qv [ i ] = 0.
Calculate the discharge of both forelands after Manning - Strickler .
563
def calc_avr_uvr_v1 ( self ) : con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess for i in range ( 2 ) : if flu . h <= ( con . hm + der . hv [ i ] ) : flu . avr [ i ] = 0. flu . uvr [ i ] = 0. else : flu . avr [ i ] = ( flu . h - ( con . hm + der . hv [ i ] ) ) ** 2 * con . bnvr [ i ] / 2. flu . uvr [ i ] = ( flu . h - ( con . hm + der . hv [ i ] ) ) * ( 1. + con . bnvr [ i ] ** 2 ) ** .5
Calculate the flown through area and the wetted perimeter of both outer embankments .
564
def calc_qvr_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess for i in range ( 2 ) : if ( flu . avr [ i ] > 0. ) and ( flu . uvr [ i ] > 0. ) : flu . qvr [ i ] = ( con . ekv [ i ] * con . skv [ i ] * flu . avr [ i ] ** ( 5. / 3. ) / flu . uvr [ i ] ** ( 2. / 3. ) * con . gef ** .5 ) else : flu . qvr [ i ] = 0.
Calculate the discharge of both outer embankments after Manning - Strickler .
565
def calc_ag_v1 ( self ) : flu = self . sequences . fluxes . fastaccess flu . ag = flu . am + flu . av [ 0 ] + flu . av [ 1 ] + flu . avr [ 0 ] + flu . avr [ 1 ]
Sum the through flown area of the total cross section .
566
def calc_qg_v1 ( self ) : flu = self . sequences . fluxes . fastaccess self . calc_am_um ( ) self . calc_qm ( ) self . calc_av_uv ( ) self . calc_qv ( ) self . calc_avr_uvr ( ) self . calc_qvr ( ) flu . qg = flu . qm + flu . qv [ 0 ] + flu . qv [ 1 ] + flu . qvr [ 0 ] + flu . qvr [ 1 ]
Calculate the discharge of the total cross section .
567
def calc_hmin_qmin_hmax_qmax_v1 ( self ) : con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess aid = self . sequences . aides . fastaccess if flu . qref <= der . qm : aid . hmin = 0. aid . qmin = 0. aid . hmax = con . hm aid . qmax = der . qm elif flu . qref <= min ( der . qv [ 0 ] , der . qv [ 1 ] ) : aid . hmin = con . hm aid . qmin = der . qm aid . hmax = con . hm + min ( der . hv [ 0 ] , der . hv [ 1 ] ) aid . qmax = min ( der . qv [ 0 ] , der . qv [ 1 ] ) elif flu . qref < max ( der . qv [ 0 ] , der . qv [ 1 ] ) : aid . hmin = con . hm + min ( der . hv [ 0 ] , der . hv [ 1 ] ) aid . qmin = min ( der . qv [ 0 ] , der . qv [ 1 ] ) aid . hmax = con . hm + max ( der . hv [ 0 ] , der . hv [ 1 ] ) aid . qmax = max ( der . qv [ 0 ] , der . qv [ 1 ] ) else : flu . h = con . hm + max ( der . hv [ 0 ] , der . hv [ 1 ] ) aid . hmin = flu . h aid . qmin = flu . qg while True : flu . h *= 2. self . calc_qg ( ) if flu . qg < flu . qref : aid . hmin = flu . h aid . qmin = flu . qg else : aid . hmax = flu . h aid . qmax = flu . qg break
Determine an starting interval for iteration methods as the one implemented in method |calc_h_v1| .
568
def calc_h_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess aid = self . sequences . aides . fastaccess aid . qmin -= flu . qref aid . qmax -= flu . qref if modelutils . fabs ( aid . qmin ) < con . qtol : flu . h = aid . hmin self . calc_qg ( ) elif modelutils . fabs ( aid . qmax ) < con . qtol : flu . h = aid . hmax self . calc_qg ( ) elif modelutils . fabs ( aid . hmax - aid . hmin ) < con . htol : flu . h = ( aid . hmin + aid . hmax ) / 2. self . calc_qg ( ) else : while True : flu . h = aid . hmin - aid . qmin * ( aid . hmax - aid . hmin ) / ( aid . qmax - aid . qmin ) self . calc_qg ( ) aid . qtest = flu . qg - flu . qref if modelutils . fabs ( aid . qtest ) < con . qtol : return if ( ( ( aid . qmax < 0. ) and ( aid . qtest < 0. ) ) or ( ( aid . qmax > 0. ) and ( aid . qtest > 0. ) ) ) : aid . qmin *= aid . qmax / ( aid . qmax + aid . qtest ) else : aid . hmin = aid . hmax aid . qmin = aid . qmax aid . hmax = flu . h aid . qmax = aid . qtest if modelutils . fabs ( aid . hmax - aid . hmin ) < con . htol : return
Approximate the water stage resulting in a certain reference discarge with the Pegasus iteration method .
569
def calc_qa_v1 ( self ) : flu = self . sequences . fluxes . fastaccess old = self . sequences . states . fastaccess_old new = self . sequences . states . fastaccess_new aid = self . sequences . aides . fastaccess if flu . rk <= 0. : new . qa = new . qz elif flu . rk > 1e200 : new . qa = old . qa + new . qz - old . qz else : aid . temp = ( 1. - modelutils . exp ( - 1. / flu . rk ) ) new . qa = ( old . qa + ( old . qz - old . qa ) * aid . temp + ( new . qz - old . qz ) * ( 1. - flu . rk * aid . temp ) )
Calculate outflow .
570
def pass_q_v1 ( self ) : sta = self . sequences . states . fastaccess out = self . sequences . outlets . fastaccess out . q [ 0 ] += sta . qa
Update outflow .
571
def calc_tc_v1 ( self ) : con = self . parameters . control . fastaccess inp = self . sequences . inputs . fastaccess flu = self . sequences . fluxes . fastaccess for k in range ( con . nmbzones ) : flu . tc [ k ] = inp . t - con . tcalt [ k ] * ( con . zonez [ k ] - con . zrelt )
Adjust the measured air temperature to the altitude of the individual zones .
572
def calc_tmean_v1 ( self ) : con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess flu . tmean = 0. for k in range ( con . nmbzones ) : flu . tmean += der . relzonearea [ k ] * flu . tc [ k ]
Calculate the areal mean temperature of the subbasin .
573
def calc_pc_v1 ( self ) : con = self . parameters . control . fastaccess inp = self . sequences . inputs . fastaccess flu = self . sequences . fluxes . fastaccess for k in range ( con . nmbzones ) : flu . pc [ k ] = inp . p * ( 1. + con . pcalt [ k ] * ( con . zonez [ k ] - con . zrelp ) ) if flu . pc [ k ] <= 0. : flu . pc [ k ] = 0. else : flu . pc [ k ] *= con . pcorr [ k ] * ( flu . rfc [ k ] + flu . sfc [ k ] )
Apply the precipitation correction factors and adjust precipitation to the altitude of the individual zones .
574
def calc_ep_v1 ( self ) : con = self . parameters . control . fastaccess inp = self . sequences . inputs . fastaccess flu = self . sequences . fluxes . fastaccess for k in range ( con . nmbzones ) : flu . ep [ k ] = inp . epn * ( 1. + con . etf [ k ] * ( flu . tmean - inp . tn ) ) flu . ep [ k ] = min ( max ( flu . ep [ k ] , 0. ) , 2. * inp . epn )
Adjust potential norm evaporation to the actual temperature .
575
def calc_epc_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess for k in range ( con . nmbzones ) : flu . epc [ k ] = ( flu . ep [ k ] * con . ecorr [ k ] * ( 1. - con . ecalt [ k ] * ( con . zonez [ k ] - con . zrele ) ) ) if flu . epc [ k ] <= 0. : flu . epc [ k ] = 0. else : flu . epc [ k ] *= modelutils . exp ( - con . epf [ k ] * flu . pc [ k ] )
Apply the evaporation correction factors and adjust evaporation to the altitude of the individual zones .
576
def calc_tf_ic_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess for k in range ( con . nmbzones ) : if con . zonetype [ k ] in ( FIELD , FOREST ) : flu . tf [ k ] = max ( flu . pc [ k ] - ( con . icmax [ k ] - sta . ic [ k ] ) , 0. ) sta . ic [ k ] += flu . pc [ k ] - flu . tf [ k ] else : flu . tf [ k ] = flu . pc [ k ] sta . ic [ k ] = 0.
Calculate throughfall and update the interception storage accordingly .
577
def calc_sp_wc_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess for k in range ( con . nmbzones ) : if con . zonetype [ k ] != ILAKE : if ( flu . rfc [ k ] + flu . sfc [ k ] ) > 0. : sta . wc [ k ] += flu . tf [ k ] * flu . rfc [ k ] / ( flu . rfc [ k ] + flu . sfc [ k ] ) sta . sp [ k ] += flu . tf [ k ] * flu . sfc [ k ] / ( flu . rfc [ k ] + flu . sfc [ k ] ) else : sta . wc [ k ] = 0. sta . sp [ k ] = 0.
Add throughfall to the snow layer .
578
def calc_refr_sp_wc_v1 ( self ) : con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess for k in range ( con . nmbzones ) : if con . zonetype [ k ] != ILAKE : if flu . tc [ k ] < der . ttm [ k ] : flu . refr [ k ] = min ( con . cfr [ k ] * con . cfmax [ k ] * ( der . ttm [ k ] - flu . tc [ k ] ) , sta . wc [ k ] ) sta . sp [ k ] += flu . refr [ k ] sta . wc [ k ] -= flu . refr [ k ] else : flu . refr [ k ] = 0. else : flu . refr [ k ] = 0. sta . wc [ k ] = 0. sta . sp [ k ] = 0.
Calculate refreezing of the water content within the snow layer and update both the snow layers ice and the water content .
579
def calc_glmelt_in_v1 ( self ) : con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess for k in range ( con . nmbzones ) : if ( ( con . zonetype [ k ] == GLACIER ) and ( sta . sp [ k ] <= 0. ) and ( flu . tc [ k ] > der . ttm [ k ] ) ) : flu . glmelt [ k ] = con . gmelt [ k ] * ( flu . tc [ k ] - der . ttm [ k ] ) flu . in_ [ k ] += flu . glmelt [ k ] else : flu . glmelt [ k ] = 0.
Calculate melting from glaciers which are actually not covered by a snow layer and add it to the water release of the snow module .
580
def calc_r_sm_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess for k in range ( con . nmbzones ) : if con . zonetype [ k ] in ( FIELD , FOREST ) : if con . fc [ k ] > 0. : flu . r [ k ] = flu . in_ [ k ] * ( sta . sm [ k ] / con . fc [ k ] ) ** con . beta [ k ] flu . r [ k ] = max ( flu . r [ k ] , sta . sm [ k ] + flu . in_ [ k ] - con . fc [ k ] ) else : flu . r [ k ] = flu . in_ [ k ] sta . sm [ k ] += flu . in_ [ k ] - flu . r [ k ] else : flu . r [ k ] = flu . in_ [ k ] sta . sm [ k ] = 0.
Calculate effective precipitation and update soil moisture .
581
def calc_cf_sm_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess for k in range ( con . nmbzones ) : if con . zonetype [ k ] in ( FIELD , FOREST ) : if con . fc [ k ] > 0. : flu . cf [ k ] = con . cflux [ k ] * ( 1. - sta . sm [ k ] / con . fc [ k ] ) flu . cf [ k ] = min ( flu . cf [ k ] , sta . uz + flu . r [ k ] ) flu . cf [ k ] = min ( flu . cf [ k ] , con . fc [ k ] - sta . sm [ k ] ) else : flu . cf [ k ] = 0. sta . sm [ k ] += flu . cf [ k ] else : flu . cf [ k ] = 0. sta . sm [ k ] = 0.
Calculate capillary flow and update soil moisture .
582
def calc_ea_sm_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess for k in range ( con . nmbzones ) : if con . zonetype [ k ] in ( FIELD , FOREST ) : if sta . sp [ k ] <= 0. : if ( con . lp [ k ] * con . fc [ k ] ) > 0. : flu . ea [ k ] = flu . epc [ k ] * sta . sm [ k ] / ( con . lp [ k ] * con . fc [ k ] ) flu . ea [ k ] = min ( flu . ea [ k ] , flu . epc [ k ] ) else : flu . ea [ k ] = flu . epc [ k ] flu . ea [ k ] -= max ( con . ered [ k ] * ( flu . ea [ k ] + flu . ei [ k ] - flu . epc [ k ] ) , 0. ) flu . ea [ k ] = min ( flu . ea [ k ] , sta . sm [ k ] ) else : flu . ea [ k ] = 0. sta . sm [ k ] -= flu . ea [ k ] else : flu . ea [ k ] = 0. sta . sm [ k ] = 0.
Calculate soil evaporation and update soil moisture .
583
def calc_inuz_v1 ( self ) : con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess flu . inuz = 0. for k in range ( con . nmbzones ) : if con . zonetype [ k ] != ILAKE : flu . inuz += der . rellandzonearea [ k ] * ( flu . r [ k ] - flu . cf [ k ] )
Accumulate the total inflow into the upper zone layer .
584
def calc_contriarea_v1 ( self ) : con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess if con . resparea and ( der . relsoilarea > 0. ) : flu . contriarea = 0. for k in range ( con . nmbzones ) : if con . zonetype [ k ] in ( FIELD , FOREST ) : if con . fc [ k ] > 0. : flu . contriarea += ( der . relsoilzonearea [ k ] * ( sta . sm [ k ] / con . fc [ k ] ) ** con . beta [ k ] ) else : flu . contriarea += der . relsoilzonearea [ k ] else : flu . contriarea = 1.
Determine the relative size of the contributing area of the whole subbasin .
585
def calc_q0_perc_uz_v1 ( self ) : con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess flu . perc = 0. flu . q0 = 0. for dummy in range ( con . recstep ) : sta . uz += der . dt * flu . inuz d_perc = min ( der . dt * con . percmax * flu . contriarea , sta . uz ) sta . uz -= d_perc flu . perc += d_perc if sta . uz > 0. : if flu . contriarea > 0. : d_q0 = ( der . dt * con . k * ( sta . uz / flu . contriarea ) ** ( 1. + con . alpha ) ) d_q0 = min ( d_q0 , sta . uz ) else : d_q0 = sta . uz sta . uz -= d_q0 flu . q0 += d_q0 else : d_q0 = 0.
Perform the upper zone layer routine which determines percolation to the lower zone layer and the fast response of the hland model . Note that the system behaviour of this method depends strongly on the specifications of the options |RespArea| and |RecStep| .
586
def calc_el_lz_v1 ( self ) : con = self . parameters . control . fastaccess der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess for k in range ( con . nmbzones ) : if ( con . zonetype [ k ] == ILAKE ) and ( flu . tc [ k ] > con . ttice [ k ] ) : flu . el [ k ] = flu . epc [ k ] sta . lz -= der . relzonearea [ k ] * flu . el [ k ] else : flu . el [ k ] = 0.
Calculate lake evaporation .
587
def calc_q1_lz_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess sta = self . sequences . states . fastaccess if sta . lz > 0. : flu . q1 = con . k4 * sta . lz ** ( 1. + con . gamma ) else : flu . q1 = 0. sta . lz -= flu . q1
Calculate the slow response of the lower zone layer .
588
def calc_inuh_v1 ( self ) : der = self . parameters . derived . fastaccess flu = self . sequences . fluxes . fastaccess flu . inuh = der . rellandarea * flu . q0 + flu . q1
Calculate the unit hydrograph input .
589
def calc_qt_v1 ( self ) : con = self . parameters . control . fastaccess flu = self . sequences . fluxes . fastaccess flu . qt = max ( flu . outuh - con . abstr , 0. )
Calculate the total discharge after possible abstractions .
590
def save ( self , parameterstep = None , simulationstep = None ) : par = parametertools . Parameter for ( modelname , var2aux ) in self : for filename in var2aux . filenames : with par . parameterstep ( parameterstep ) , par . simulationstep ( simulationstep ) : lines = [ parametertools . get_controlfileheader ( modelname , parameterstep , simulationstep ) ] for par in getattr ( var2aux , filename ) : lines . append ( repr ( par ) + '\n' ) hydpy . pub . controlmanager . save_file ( filename , '' . join ( lines ) )
Save all defined auxiliary control files .
591
def remove ( self , * values ) : for value in objecttools . extract ( values , ( str , variabletools . Variable ) ) : try : deleted_something = False for fn2var in list ( self . _type2filename2variable . values ( ) ) : for fn_ , var in list ( fn2var . items ( ) ) : if value in ( fn_ , var ) : del fn2var [ fn_ ] deleted_something = True if not deleted_something : raise ValueError ( f'`{repr(value)}` is neither a registered ' f'filename nor a registered variable.' ) except BaseException : objecttools . augment_excmessage ( f'While trying to remove the given object `{value}` ' f'of type `{objecttools.classname(value)}` from the ' f'actual Variable2AuxFile object' )
Remove the defined variables .
592
def filenames ( self ) : fns = set ( ) for fn2var in self . _type2filename2variable . values ( ) : fns . update ( fn2var . keys ( ) ) return sorted ( fns )
A list of all handled auxiliary file names .
593
def get_filename ( self , variable ) : fn2var = self . _type2filename2variable . get ( type ( variable ) , { } ) for ( fn_ , var ) in fn2var . items ( ) : if var == variable : return fn_ return None
Return the auxiliary file name the given variable is allocated to or |None| if the given variable is not allocated to any auxiliary file name .
594
def update ( self ) : metapar = self . subpars . pars . control . remotedischargesafety self . shape = metapar . shape self ( tuple ( smoothtools . calc_smoothpar_logistic1 ( mp ) for mp in metapar . values ) )
Calculate the smoothing parameter values .
595
def run_subprocess ( command : str , verbose : bool = True , blocking : bool = True ) -> Optional [ subprocess . Popen ] : if blocking : result1 = subprocess . run ( command , stdout = subprocess . PIPE , stderr = subprocess . PIPE , encoding = 'utf-8' , shell = True ) if verbose : for output in ( result1 . stdout , result1 . stderr ) : output = output . strip ( ) if output : print ( output ) return None stdouterr = None if verbose else subprocess . DEVNULL result2 = subprocess . Popen ( command , stdout = stdouterr , stderr = stdouterr , encoding = 'utf-8' , shell = True ) return result2
Execute the given command in a new process .
596
def exec_commands ( commands : str , ** parameters : Any ) -> None : cmdlist = commands . split ( ';' ) print ( f'Start to execute the commands {cmdlist} for testing purposes.' ) for par , value in parameters . items ( ) : exec ( f'{par} = {value}' ) for command in cmdlist : command = command . replace ( '__' , 'temptemptemp' ) command = command . replace ( '_' , ' ' ) command = command . replace ( 'temptemptemp' , '_' ) exec ( command )
Execute the given Python commands .
597
def prepare_logfile ( filename : str ) -> str : if filename == 'stdout' : return filename if filename == 'default' : filename = datetime . datetime . now ( ) . strftime ( 'hydpy_%Y-%m-%d_%H-%M-%S.log' ) with open ( filename , 'w' ) : pass return os . path . abspath ( filename )
Prepare an empty log file eventually and return its absolute path .
598
def execute_scriptfunction ( ) -> None : try : args_given = [ ] kwargs_given = { } for arg in sys . argv [ 1 : ] : if len ( arg ) < 3 : args_given . append ( arg ) else : try : key , value = parse_argument ( arg ) kwargs_given [ key ] = value except ValueError : args_given . append ( arg ) logfilepath = prepare_logfile ( kwargs_given . pop ( 'logfile' , 'stdout' ) ) logstyle = kwargs_given . pop ( 'logstyle' , 'plain' ) try : funcname = str ( args_given . pop ( 0 ) ) except IndexError : raise ValueError ( 'The first positional argument defining the function ' 'to be called is missing.' ) try : func = hydpy . pub . scriptfunctions [ funcname ] except KeyError : available_funcs = objecttools . enumeration ( sorted ( hydpy . pub . scriptfunctions . keys ( ) ) ) raise ValueError ( f'There is no `{funcname}` function callable by `hyd.py`. ' f'Choose one of the following instead: {available_funcs}.' ) args_required = inspect . getfullargspec ( func ) . args nmb_args_required = len ( args_required ) nmb_args_given = len ( args_given ) if nmb_args_given != nmb_args_required : enum_args_given = '' if nmb_args_given : enum_args_given = ( f' ({objecttools.enumeration(args_given)})' ) enum_args_required = '' if nmb_args_required : enum_args_required = ( f' ({objecttools.enumeration(args_required)})' ) raise ValueError ( f'Function `{funcname}` requires `{nmb_args_required:d}` ' f'positional arguments{enum_args_required}, but ' f'`{nmb_args_given:d}` are given{enum_args_given}.' ) with _activate_logfile ( logfilepath , logstyle , 'info' , 'warning' ) : func ( * args_given , ** kwargs_given ) except BaseException as exc : if logstyle not in LogFileInterface . style2infotype2string : logstyle = 'plain' with _activate_logfile ( logfilepath , logstyle , 'exception' , 'exception' ) : arguments = ', ' . join ( sys . argv ) print ( f'Invoking hyd.py with arguments `{arguments}` ' f'resulted in the following error:\n{str(exc)}\n\n' f'See the following stack traceback for debugging:\n' , file = sys . stderr ) traceback . print_tb ( sys . exc_info ( ) [ 2 ] )
Execute a HydPy script function .
599
def parse_argument ( string : str ) -> Union [ str , Tuple [ str , str ] ] : idx_equal = string . find ( '=' ) if idx_equal == - 1 : return string idx_quote = idx_equal + 1 for quote in ( '"' , "'" ) : idx = string . find ( quote ) if - 1 < idx < idx_quote : idx_quote = idx if idx_equal < idx_quote : return string [ : idx_equal ] , string [ idx_equal + 1 : ] return string
Return a single value for a string understood as a positional argument or a |tuple| containing a keyword and its value for a string understood as a keyword argument .