Search is not available for this dataset
text
stringlengths
75
104k
def trim(self, lower=None, upper=None): """Trim upper values in accordance with :math:`EQI2 \\leq EQI1 \\leq EQB`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqb.value = 3.0 >>> eqi2.value = 1.0 >>> eqi1(0.0) >>> eqi1 eqi1(1....
def time_choices(): """Return digital time choices every half hour from 00:00 to 23:30.""" hours = list(range(0, 24)) times = [] for h in hours: hour = str(h).zfill(2) times.append(hour+':00') times.append(hour+':30') return list(zip(times, times))
def _add_lines(specification, module): """Return autodoc commands for a basemodels docstring. Note that `collection classes` (e.g. `Model`, `ControlParameters`, `InputSequences` are placed on top of the respective section and the `contained classes` (e.g. model methods, `ControlParameter` instances, ...
def autodoc_basemodel(module): """Add an exhaustive docstring to the given module of a basemodel. Works onlye when all modules of the basemodel are named in the standard way, e.g. `lland_model`, `lland_control`, `lland_inputs`. """ autodoc_tuple2doc(module) namespace = module.__dict__ doc =...
def autodoc_applicationmodel(module): """Improves the docstrings of application models when called at the bottom of the respective module. |autodoc_applicationmodel| requires, similar to |autodoc_basemodel|, that both the application model and its base model are defined in the conventional way. ...
def prepare_mainsubstituter(): """Prepare and return a |Substituter| object for the main `__init__` file of *HydPy*.""" substituter = Substituter() for module in (builtins, numpy, datetime, unittest, doctest, inspect, io, os, sys, time, collections, itertools, subprocess, scipy, ...
def _number_of_line(member_tuple): """Try to return the number of the first line of the definition of a member of a module.""" member = member_tuple[1] try: return member.__code__.co_firstlineno except AttributeError: pass try: return inspect.findsource(member)[1] exc...
def autodoc_module(module): """Add a short summary of all implemented members to a modules docstring. """ doc = getattr(module, '__doc__') if doc is None: doc = '' members = [] for name, member in inspect.getmembers(module): if ((not name.startswith('_')) and (ins...
def autodoc_tuple2doc(module): """Include tuples as `CLASSES` of `ControlParameters` and `RUN_METHODS` of `Models` into the respective docstring.""" modulename = module.__name__ for membername, member in inspect.getmembers(module): for tuplename, descr in _name2descr.items(): tuple_ ...
def consider_member(name_member, member, module, class_=None): """Return |True| if the given member should be added to the substitutions. If not return |False|. Some examples based on the site-package |numpy|: >>> from hydpy.core.autodoctools import Substituter >>> import numpy...
def get_role(member, cython=False): """Return the reStructuredText role `func`, `class`, or `const` best describing the given member. Some examples based on the site-package |numpy|. |numpy.clip| is a function: >>> from hydpy.core.autodoctools import Substituter >>> im...
def add_substitution(self, short, medium, long, module): """Add the given substitutions both as a `short2long` and a `medium2long` mapping. Assume `variable1` is defined in the hydpy module `module1` and the short and medium descriptions are `var1` and `mod1.var1`: >>> import t...
def add_module(self, module, cython=False): """Add the given module, its members, and their submembers. The first examples are based on the site-package |numpy|: which is passed to method |Substituter.add_module|: >>> from hydpy.core.autodoctools import Substituter >>> substitu...
def add_modules(self, package): """Add the modules of the given package without their members.""" for name in os.listdir(package.__path__[0]): if name.startswith('_'): continue name = name.split('.')[0] short = '|%s|' % name long = ':mod:`~...
def update_masters(self): """Update all `master` |Substituter| objects. If a |Substituter| object is passed to the constructor of another |Substituter| object, they become `master` and `slave`: >>> from hydpy.core.autodoctools import Substituter >>> sub1 = Substituter() ...
def update_slaves(self): """Update all `slave` |Substituter| objects. See method |Substituter.update_masters| for further information. """ for slave in self.slaves: slave._medium2long.update(self._medium2long) slave.update_slaves()
def get_commands(self, source=None): """Return a string containing multiple `reStructuredText` replacements with the substitutions currently defined. Some examples based on the subpackage |optiontools|: >>> from hydpy.core.autodoctools import Substituter >>> substituter = Subst...
def find(self, text): """Print all substitutions that include the given text string.""" for key, value in self: if (text in key) or (text in value): print(key, value)
def print_progress(wrapped, _=None, args=None, kwargs=None): """Add print commands time to the given function informing about execution time. To show how the |print_progress| decorator works, we need to modify the functions used by |print_progress| to gain system time information available in modu...
def progressbar(iterable, length=23): """Print a simple progress bar while processing the given iterable. Function |progressbar| does print the progress bar when option `printprogress` is activted: >>> from hydpy import pub >>> pub.options.printprogress = True You can pass an iterable object....
def start_server(socket, projectname, xmlfilename: str) -> None: """Start the *HydPy* server using the given socket. The folder with the given `projectname` must be available within the current working directory. The XML configuration file must be placed within the project folder unless `xmlfilename` ...
def await_server(port, seconds): """Block the current process until either the *HydPy* server is responding on the given `port` or the given number of `seconds` elapsed. >>> from hydpy import run_subprocess, TestIO >>> with TestIO(): # doctest: +ELLIPSIS ... run_subprocess('hyd.py await_serv...
def initialise(self, projectname: str, xmlfile: str) -> None: """Initialise a *HydPy* project based on the given XML configuration file agreeing with `HydPyConfigMultipleRuns.xsd`. We use the `LahnH` project and its rather complex XML configuration file `multiple_runs.xml` as an example...
def POST_evaluate(self) -> None: """Evaluate any valid Python expression with the *HydPy* server process and get its result. Method |HydPyServer.POST_evaluate| serves to test and debug, primarily. The main documentation on module |servertools| explains its usage. """ for...
def GET_close_server(self) -> None: """Stop and close the *HydPy* server.""" def _close_server(): self.server.shutdown() self.server.server_close() shutter = threading.Thread(target=_close_server) shutter.deamon = True shutter.start()
def GET_parameteritemtypes(self) -> None: """Get the types of all current exchange items supposed to change the values of |Parameter| objects.""" for item in state.parameteritems: self._outputs[item.name] = self._get_itemtype(item)
def GET_conditionitemtypes(self) -> None: """Get the types of all current exchange items supposed to change the values of |StateSequence| or |LogSequence| objects.""" for item in state.conditionitems: self._outputs[item.name] = self._get_itemtype(item)
def GET_getitemtypes(self) -> None: """Get the types of all current exchange items supposed to return the values of |Parameter| or |Sequence| objects or the time series of |IOSequence| objects.""" for item in state.getitems: type_ = self._get_itemtype(item) for na...
def POST_timegrid(self) -> None: """Change the current simulation |Timegrid|.""" init = hydpy.pub.timegrids.init sim = hydpy.pub.timegrids.sim sim.firstdate = self._inputs['firstdate'] sim.lastdate = self._inputs['lastdate'] state.idx1 = init[sim.firstdate] state....
def GET_parameteritemvalues(self) -> None: """Get the values of all |ChangeItem| objects handling |Parameter| objects.""" for item in state.parameteritems: self._outputs[item.name] = item.value
def GET_conditionitemvalues(self) -> None: """Get the values of all |ChangeItem| objects handling |StateSequence| or |LogSequence| objects.""" for item in state.conditionitems: self._outputs[item.name] = item.value
def GET_getitemvalues(self) -> None: """Get the values of all |Variable| objects observed by the current |GetItem| objects. For |GetItem| objects observing time series, |HydPyServer.GET_getitemvalues| returns only the values within the current simulation period. """ ...
def GET_load_conditionvalues(self) -> None: """Assign the |StateSequence| or |LogSequence| object values available for the current simulation start point to the current |HydPy| instance. When the simulation start point is identical with the initialisation time point and you did not save...
def GET_save_conditionvalues(self) -> None: """Save the |StateSequence| and |LogSequence| object values of the current |HydPy| instance for the current simulation endpoint.""" state.conditions[self._id] = state.conditions.get(self._id, {}) state.conditions[self._id][state.idx2] = state.h...
def GET_save_parameteritemvalues(self) -> None: """Save the values of those |ChangeItem| objects which are handling |Parameter| objects.""" for item in state.parameteritems: state.parameteritemvalues[self._id][item.name] = item.value.copy()
def GET_savedparameteritemvalues(self) -> None: """Get the previously saved values of those |ChangeItem| objects which are handling |Parameter| objects.""" dict_ = state.parameteritemvalues.get(self._id) if dict_ is None: self.GET_parameteritemvalues() else: ...
def GET_save_modifiedconditionitemvalues(self) -> None: """ToDo: extend functionality and add tests""" for item in state.conditionitems: state.modifiedconditionitemvalues[self._id][item.name] = \ list(item.device2target.values())[0].value
def GET_savedmodifiedconditionitemvalues(self) -> None: """ToDo: extend functionality and add tests""" dict_ = state.modifiedconditionitemvalues.get(self._id) if dict_ is None: self.GET_conditionitemvalues() else: for name, value in dict_.items(): ...
def GET_save_getitemvalues(self) -> None: """Save the values of all current |GetItem| objects.""" for item in state.getitems: for name, value in item.yield_name2value(state.idx1, state.idx2): state.getitemvalues[self._id][name] = value
def GET_savedgetitemvalues(self) -> None: """Get the previously saved values of all |GetItem| objects.""" dict_ = state.getitemvalues.get(self._id) if dict_ is None: self.GET_getitemvalues() else: for name, value in dict_.items(): self._outputs[nam...
def GET_save_timegrid(self) -> None: """Save the current simulation period.""" state.timegrids[self._id] = copy.deepcopy(hydpy.pub.timegrids.sim)
def GET_savedtimegrid(self) -> None: """Get the previously saved simulation period.""" try: self._write_timegrid(state.timegrids[self._id]) except KeyError: self._write_timegrid(hydpy.pub.timegrids.init)
def trim(self: 'Variable', lower=None, upper=None) -> None: """Trim the value(s) of a |Variable| instance. Usually, users do not need to apply function |trim| directly. Instead, some |Variable| subclasses implement their own `trim` methods relying on function |trim|. Model developers should implem...
def _get_tolerance(values): """Return some "numerical accuracy" to be expected for the given floating point value(s) (see method |trim|).""" tolerance = numpy.abs(values*1e-15) if hasattr(tolerance, '__setitem__'): tolerance[numpy.isinf(tolerance)] = 0. elif numpy.isinf(tolerance): t...
def _compare_variables_function_generator( method_string, aggregation_func): """Return a function usable as a comparison method for class |Variable|. Pass the specific method (e.g. `__eq__`) and the corresponding operator (e.g. `==`) as strings. Also pass either |numpy.all| or |numpy.any| for...
def to_repr(self: Variable, values, brackets1d: Optional[bool] = False) \ -> str: """Return a valid string representation for the given |Variable| object. Function |to_repr| it thought for internal purposes only, more specifically for defining string representations of subclasses of class |...
def verify(self) -> None: """Raises a |RuntimeError| if at least one of the required values of a |Variable| object is |None| or |numpy.nan|. The descriptor `mask` defines, which values are considered to be necessary. Example on a 0-dimensional |Variable|: >>> from hydpy.core.va...
def average_values(self, *args, **kwargs) -> float: """Average the actual values of the |Variable| object. For 0-dimensional |Variable| objects, the result of method |Variable.average_values| equals |Variable.value|. The following example shows this for the sloppily defined class ...
def get_submask(self, *args, **kwargs) -> masktools.CustomMask: """Get a sub-mask of the mask handled by the actual |Variable| object based on the given arguments. See the documentation on method |Variable.average_values| for further information. """ if args or kwargs: ...
def commentrepr(self) -> List[str]: """A list with comments for making string representations more informative. With option |Options.reprcomments| being disabled, |Variable.commentrepr| is empty. """ if hydpy.pub.options.reprcomments: return [f'# {line}' for ...
def AddTable(p_workSheet = None, p_headerDict = None, p_startColumn = 1, p_startRow = 1, p_headerHeight = None, p_data = None, p_mainTable = False, p_conditionalFormatting = None, p_tableStyleInfo = None, p_withFilters = True): """Insert a table in a given worksheet. Args: p_workSheet (openpyxl...
def get_controlfileheader( model: Union[str, 'modeltools.Model'], parameterstep: timetools.PeriodConstrArg = None, simulationstep: timetools.PeriodConstrArg = None) -> str: """Return the header of a regular or auxiliary parameter control file. The header contains the default coding info...
def _prepare_docstrings(self, frame): """Assign docstrings to the constants handled by |Constants| to make them available in the interactive mode of Python.""" if config.USEAUTODOC: filename = inspect.getsourcefile(frame) with open(filename) as file_: sour...
def update(self) -> None: """Call method |Parameter.update| of all "secondary" parameters. Directly after initialisation, neither the primary (`control`) parameters nor the secondary (`derived`) parameters of application model |hstream_v1| are ready for usage: >>> from hydpy.m...
def save_controls(self, filepath: Optional[str] = None, parameterstep: timetools.PeriodConstrArg = None, simulationstep: timetools.PeriodConstrArg = None, auxfiler: 'auxfiletools.Auxfiler' = None): """Write the control parameters to file. ...
def _get_values_from_auxiliaryfile(self, auxfile): """Try to return the parameter values from the auxiliary control file with the given name. Things are a little complicated here. To understand this method, you should first take a look at the |parameterstep| function. """ ...
def initinfo(self) -> Tuple[Union[float, int, bool], bool]: """The actual initial value of the given parameter. Some |Parameter| subclasses define another value for class attribute `INIT` than |None| to provide a default value. Let's define a parameter test class and prepare a function...
def get_timefactor(cls) -> float: """Factor to adjust a new value of a time-dependent parameter. For a time-dependent parameter, its effective value depends on the simulation step size. Method |Parameter.get_timefactor| returns the fraction between the current simulation step size and ...
def apply_timefactor(cls, values): """Change and return the given value(s) in accordance with |Parameter.get_timefactor| and the type of time-dependence of the actual parameter subclass. .. testsetup:: >>> from hydpy import pub >>> del pub.timegrids For...
def revert_timefactor(cls, values): """The inverse version of method |Parameter.apply_timefactor|. See the explanations on method Parameter.apply_timefactor| to understand the following examples: .. testsetup:: >>> from hydpy import pub >>> del pub.timegrids ...
def compress_repr(self) -> Optional[str]: """Try to find a compressed parameter value representation and return it. |Parameter.compress_repr| raises a |NotImplementedError| when failing to find a compressed representation. .. testsetup:: >>> from hydpy import pub ...
def compress_repr(self) -> str: """Works as |Parameter.compress_repr|, but returns a string with constant names instead of constant values. See the main documentation on class |NameParameter| for further information. """ string = super().compress_repr() if string...
def compress_repr(self) -> Optional[str]: """Works as |Parameter.compress_repr|, but alternatively tries to compress by following an external classification. See the main documentation on class |ZipParameter| for further information. """ string = super().compress_repr() ...
def refresh(self) -> None: """Update the actual simulation values based on the toy-value pairs. Usually, one does not need to call refresh explicitly. The "magic" methods __call__, __setattr__, and __delattr__ invoke it automatically, when required. Instantiate a 1-dimensional...
def interp(self, date: timetools.Date) -> float: """Perform a linear value interpolation for the given `date` and return the result. Instantiate a 1-dimensional |SeasonalParameter| object: >>> from hydpy.core.parametertools import SeasonalParameter >>> class Par(SeasonalParamet...
def update(self) -> None: """Update subclass of |RelSubweightsMixin| based on `refweights`.""" mask = self.mask weights = self.refweights[mask] self[~mask] = numpy.nan self[mask] = weights/numpy.sum(weights)
def alternative_initvalue(self) -> Union[bool, int, float]: """A user-defined value to be used instead of the value of class constant `INIT`. See the main documentation on class |SolverParameter| for more information. """ if self._alternative_initvalue is None: ...
def update(self) -> None: """Reference the actual |Indexer.timeofyear| array of the |Indexer| object available in module |pub|. >>> from hydpy import pub >>> pub.timegrids = '27.02.2004', '3.03.2004', '1d' >>> from hydpy.core.parametertools import TOYParameter >>> toypar...
def get_premises_model(): """ Support for custom company premises model with developer friendly validation. """ try: app_label, model_name = PREMISES_MODEL.split('.') except ValueError: raise ImproperlyConfigured("OPENINGHOURS_PREMISES_MODEL must be of the" ...
def get_now(): """ Allows to access global request and read a timestamp from query. """ if not get_current_request: return datetime.datetime.now() request = get_current_request() if request: openinghours_now = request.GET.get('openinghours-now') if openinghours_now: ...
def get_closing_rule_for_now(location): """ Returns QuerySet of ClosingRules that are currently valid """ now = get_now() if location: return ClosingRules.objects.filter(company=location, start__lte=now, end__gte=now) return Company.objects.fi...
def is_open(location, now=None): """ Is the company currently open? Pass "now" to test with a specific timestamp. Can be used stand-alone or as a helper. """ if now is None: now = get_now() if has_closing_rule_for_now(location): return False now_time = datetime.time(now.hou...
def next_time_open(location): """ Returns the next possible opening hours object, or (False, None) if location is currently open or there is no such object I.e. when is the company open for the next time? """ if not is_open(location): now = get_now() now_time = datetime.time(now....
def refweights(self): """A |numpy| |numpy.ndarray| with equal weights for all segment junctions.. >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> states.qjoints.shape = 5 >>> states.qjoints.refweights array([ 0.2, 0.2, 0.2, 0.2, 0.2]) ...
def add(self, directory, path=None) -> None: """Add a directory and optionally its path.""" objecttools.valid_variable_identifier(directory) if path is None: path = directory setattr(self, directory, path)
def basepath(self) -> str: """Absolute path pointing to the available working directories. >>> from hydpy.core.filetools import FileManager >>> filemanager = FileManager() >>> filemanager.BASEDIR = 'basename' >>> filemanager.projectdir = 'projectname' >>> from hydpy impo...
def availabledirs(self) -> Folder2Path: """Names and paths of the available working directories. Available working directories are those beeing stored in the base directory of the respective |FileManager| subclass. Folders with names starting with an underscore are ignored (use ...
def currentdir(self) -> str: """Name of the current working directory containing the relevant files. To show most of the functionality of |property| |FileManager.currentdir| (unpacking zip files on the fly is explained in the documentation on function (|FileManager.zip_currentdi...
def currentpath(self) -> str: """Absolute path of the current working directory. >>> from hydpy.core.filetools import FileManager >>> filemanager = FileManager() >>> filemanager.BASEDIR = 'basename' >>> filemanager.projectdir = 'projectname' >>> from hydpy import repr_, ...
def filenames(self) -> List[str]: """Names of the files contained in the the current working directory. Files names starting with underscores are ignored: >>> from hydpy.core.filetools import FileManager >>> filemanager = FileManager() >>> filemanager.BASEDIR = 'basename' ...
def filepaths(self) -> List[str]: """Absolute path names of the files contained in the current working directory. Files names starting with underscores are ignored: >>> from hydpy.core.filetools import FileManager >>> filemanager = FileManager() >>> filemanager.BASEDIR ...
def zip_currentdir(self) -> None: """Pack the current working directory in a `zip` file. |FileManager| subclasses allow for manual packing and automatic unpacking of working directories. The only supported format is `zip`. To avoid possible inconsistencies, origin directories and zip ...
def load_files(self) -> selectiontools.Selections: """Read all network files of the current working directory, structure their contents in a |selectiontools.Selections| object, and return it. """ devicetools.Node.clear_all() devicetools.Element.clear_all() selections = se...
def save_files(self, selections) -> None: """Save the |Selection| objects contained in the given |Selections| instance to separate network files.""" try: currentpath = self.currentpath selections = selectiontools.Selections(selections) for selection in selecti...
def delete_files(self, selections) -> None: """Delete the network files corresponding to the given selections (e.g. a |list| of |str| objects or a |Selections| object).""" try: currentpath = self.currentpath for selection in selections: name = str(selectio...
def load_file(self, element=None, filename=None, clear_registry=True): """Return the namespace of the given file (and eventually of its corresponding auxiliary subfiles) as a |dict|. By default, the internal registry is cleared when a control file and all its corresponding auxiliary fil...
def read2dict(cls, filename, info): """Read the control parameters from the given path (and its auxiliary paths, where appropriate) and store them in the given |dict| object `info`. Note that the |dict| `info` can be used to feed information into the execution of control files. ...
def save_file(self, filename, text): """Save the given text under the given control filename and the current path.""" if not filename.endswith('.py'): filename += '.py' path = os.path.join(self.currentpath, filename) with open(path, 'w', encoding="utf-8") as file_: ...
def load_file(self, filename): """Read and return the content of the given file. If the current directory is not defined explicitly, the directory name is constructed with the actual simulation start date. If such an directory does not exist, it is created immediately. """ ...
def save_file(self, filename, text): """Save the given text under the given condition filename and the current path. If the current directory is not defined explicitly, the directory name is constructed with the actual simulation end date. If such an directory does not exist, i...
def load_file(self, sequence): """Load data from an "external" data file an pass it to the given |IOSequence|.""" try: if sequence.filetype_ext == 'npy': sequence.series = sequence.adjust_series( *self._load_npy(sequence)) elif sequence...
def save_file(self, sequence, array=None): """Write the date stored in |IOSequence.series| of the given |IOSequence| into an "external" data file. """ if array is None: array = sequence.aggregate_series() try: if sequence.filetype_ext == 'nc': self...
def open_netcdf_reader(self, flatten=False, isolate=False, timeaxis=1): """Prepare a new |NetCDFInterface| object for reading data.""" self._netcdf_reader = netcdftools.NetCDFInterface( flatten=bool(flatten), isolate=bool(isolate), timeaxis=int(timeaxis))
def open_netcdf_writer(self, flatten=False, isolate=False, timeaxis=1): """Prepare a new |NetCDFInterface| object for writing data.""" self._netcdf_writer = netcdftools.NetCDFInterface( flatten=bool(flatten), isolate=bool(isolate), timeaxis=int(timeaxis))
def calc_nkor_v1(self): """Adjust the given precipitation values. Required control parameters: |NHRU| |KG| Required input sequence: |Nied| Calculated flux sequence: |NKor| Basic equation: :math:`NKor = KG \\cdot Nied` Example: >>> from hydpy.models.lla...
def calc_tkor_v1(self): """Adjust the given air temperature values. Required control parameters: |NHRU| |KT| Required input sequence: |TemL| Calculated flux sequence: |TKor| Basic equation: :math:`TKor = KT + TemL` Example: >>> from hydpy.models.lland ...
def calc_et0_v1(self): """Calculate reference evapotranspiration after Turc-Wendling. Required control parameters: |NHRU| |KE| |KF| |HNN| Required input sequence: |Glob| Required flux sequence: |TKor| Calculated flux sequence: |ET0| Basic equation: ...
def calc_et0_wet0_v1(self): """Correct the given reference evapotranspiration and update the corresponding log sequence. Required control parameters: |NHRU| |KE| |WfET0| Required input sequence: |PET| Calculated flux sequence: |ET0| Updated log sequence: |...
def calc_evpo_v1(self): """Calculate land use and month specific values of potential evapotranspiration. Required control parameters: |NHRU| |Lnk| |FLn| Required derived parameter: |MOY| Required flux sequence: |ET0| Calculated flux sequence: |EvPo| A...
def calc_nbes_inzp_v1(self): """Calculate stand precipitation and update the interception storage accordingly. Required control parameters: |NHRU| |Lnk| Required derived parameter: |KInz| Required flux sequence: |NKor| Calculated flux sequence: |NBes| Updat...