text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_a(values, n):
"""Extract the independent variables of the given values and return them as a matrix with n columns in a form suitable for the least square... |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_ma_coefs(self):
"""Determine the MA coefficients. The number of MA coefficients is subsequently increased until the required precision |ARMA.max_dev_c... |
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):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_next_ma_coef(self, ma_order, ma_model):
"""Determine the MA coefficients of the ARMA model based on its predetermined AR coefficients and the MA ordinat... |
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])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def response(self):
"""Return the response to a standard dt impulse.""" |
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 enum... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def moments(self):
"""The first two time delay weighted statistical moments of the ARMA response.""" |
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot(self, threshold=None, **kwargs):
"""Barplot of the ARMA response.""" |
try:
# Works under matplotlib 3.
pyplot.bar(x=self.ma.delays+.5, height=self.response,
width=1., fill=False, **kwargs)
except TypeError: # pragma: no cover
# Works under matplotlib 2.
pyplot.bar(left=self.ma.delays+.5, height=self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def method_header(method_name, nogil=False, idx_as_arg=False):
"""Returns the Cython method header for methods without arguments except `self`.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decorate_method(wrapped):
"""The decorated method will return a |Lines| object including a method header. However, the |Lines| object will be empty if the re... |
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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, indent, line):
"""Appends the given text line with prefixed spaces in accordance with the given number of indentation levels. """ |
if isinstance(line, str):
list.append(self, indent*4*' ' + line)
else:
for subline in line:
list.append(self, indent*4*' ' + subline) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pyname(self):
"""Name of the compiled module.""" |
if self.pymodule.endswith('__init__'):
return self.pymodule.split('.')[-2]
else:
return self.pymodule.split('.')[-1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pyxwriter(self):
"""Update the pyx file.""" |
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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pysourcefiles(self):
"""All source files of the actual models Python classes and their respective base classes.""" |
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)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def outdated(self):
"""True if at least one of the |Cythonizer.pysourcefiles| is newer than the compiled file under |Cythonizer.pyxfilepath|, otherwise False. ""... |
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 s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile_(self):
"""Translate cython code to C code and compile it.""" |
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.pyxfile... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_dll(self):
"""Try to find the resulting dll file and to move it into the `cythons` package. Things to be aware of: * The file extension either `pyd` (Wi... |
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)):
syst... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def constants(self):
"""Constants declaration lines.""" |
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)] +... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parameters(self):
"""Parameter declaration lines.""" |
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))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iosequence(seq):
"""Special declaration lines for the given |IOSequence| object. """ |
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]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_files(subseqs):
"""Open file statements.""" |
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(), '
'"r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close_files(subseqs):
"""Close file statements.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_data(subseqs):
"""Load data statements.""" |
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 se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_pointer(self, subseqs):
"""Set_pointer functions for link sequences.""" |
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))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_pointer0d(subseqs):
"""Set_pointer function for 0-dimensional link sequences.""" |
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_va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def alloc(subseqs):
"""Allocate memory for 1-dimensional link sequences.""" |
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 = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dealloc(subseqs):
"""Deallocate memory for 1-dimensional link sequences.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_pointer1d(subseqs):
"""Set_pointer function for 1-dimensional link sequences.""" |
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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def numericalparameters(self):
"""Numeric parameter declaration lines.""" |
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_incr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modeldeclarations(self):
"""Attribute declarations of the model class.""" |
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'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modelstandardfunctions(self):
"""Standard functions of the model class.""" |
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.updat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modelnumericfunctions(self):
"""Numerical functions of the model class.""" |
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_s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_single_terms(self):
"""Lines of model method with the same name.""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listofmodeluserfunctions(self):
"""User functions of the model class.""" |
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(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_linebreaks_within_equations(code):
r"""Remove line breaks within equations. This is not a exhaustive test, but shows how the method works: 'asdf = (a+... |
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.app... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_imath_operators(lines):
"""Remove mathematical expressions that require Pythons global interpreter locking mechanism. This is not a exhaustive test, b... |
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() f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pyxlines(self):
"""Cython code lines. Assumptions: * Function shall be a method * Method shall be inlined * Method returns nothing * Method arguments are of ... |
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)
line... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_smoothpar_logistic2(metapar):
"""Return the smoothing parameter corresponding to the given meta parameter when using |smooth_logistic2|. Calculate the s... |
if metapar <= 0.:
return 0.
return optimize.newton(_error_smoothpar_logistic2,
.3 * metapar**.84,
_smooth_logistic2_derivative,
args=(metapar,)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_cfunits(cls, units) -> 'Date': """Return a |Date| object representing the reference date of the given `units` string agreeing with the NetCDF-CF conventi... |
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 != '... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_cfunits(self, unit='hours', utcoffset=None):
"""Return a `units` string agreeing with the NetCDF-CF conventions. By default, |Date.to_cfunits| takes `hour... |
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}' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.')
k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wateryear(self):
"""The actual hydrological year according to the selected reference month. The reference mont reference |Date.refmonth| defaults to November... |
if self.month < self._firstmonth_wateryear:
return self.year
return self.year + 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fromseconds(cls, seconds):
"""Return a |Period| instance based on a given number of seconds.""" |
try:
seconds = int(seconds)
except TypeError:
seconds = int(seconds.flatten()[0])
return cls(datetime.timedelta(0, int(seconds))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _guessunit(self):
"""Guess the unit of the period as the largest one, which results in an integer duration. """ |
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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_array(cls, array):
"""Returns a |Timegrid| instance based on two date and one period information stored in the first 13 rows of a |numpy.ndarray| object... |
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'number... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_array(self):
"""Returns a 1-dimensional |numpy| |numpy.ndarray| with thirteen entries first defining the start date, secondly defining the end date and th... |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_timepoints(cls, timepoints, refdate, unit='hours'):
"""Return a |Timegrid| object representing the given starting `timepoints` in relation to the given ... |
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, step... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_timepoints(self, unit='hours', offset=None):
"""Return an |numpy.ndarray| representing the starting time points of the |Timegrid| object. The following ex... |
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.linspa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def array2series(self, array):
"""Prefix the information of the actual Timegrid object to the given array and return it. The Timegrid information is stored in th... |
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(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify(self):
"""Raise an |ValueError| if the dates or the step size of the time frame are inconsistent. """ |
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(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assignrepr(self, prefix, style=None, utcoffset=None):
"""Return a |repr| string with an prefixed assignement. Without option arguments given, printing the re... |
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)}')") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify(self):
"""Raise an |ValueError| it the different time grids are inconsistent.""" |
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 p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def seconds_passed(self):
"""Amount of time passed in seconds since the beginning of the year. In the first example, the year is only one minute and thirty secon... |
return int((Date(self).datetime -
self._STARTDATE.datetime).total_seconds()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def seconds_left(self):
"""Remaining part of the year in seconds. In the first example, only one minute and thirty seconds of the year remain: 90 The second exam... |
return int((self._ENDDATE.datetime -
Date(self).datetime).total_seconds()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def centred_timegrid(cls, simulationstep):
"""Return a |Timegrid| object defining the central time points of the year 2000 for the given simulation step. Timegri... |
simulationstep = Period(simulationstep)
return Timegrid(
cls._STARTDATE+simulationstep/2,
cls._ENDDATE+simulationstep/2,
simulationstep) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dir_(self):
"""The prefered way for HydPy objects to respond to |dir|. Note the depencence on the `pub.options.dirverbose`. If this option is set `True`, all... |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def classname(self):
"""Return the class name of the given instance object or class. float Options """ |
if inspect.isclass(self):
string = str(self)
else:
string = str(type(self))
try:
string = string.split("'")[1]
except IndexError:
pass
return string.split('.')[-1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def name(self):
"""Name of the class of the given instance in lower case letters. This function is thought to be implemented as a property. Otherwise it would vi... |
cls = type(self)
try:
return cls.__dict__['_name']
except KeyError:
setattr(cls, '_name', instancename(self))
return cls.__dict__['_name'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def valid_variable_identifier(string):
"""Raises an |ValueError| if the given name is not a valid Python identifier. Traceback (most recent call last):
ValueErr... |
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 contai... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def augment_excmessage(prefix=None, suffix=None) -> NoReturn: """Augment an exception message with additional information while keeping the original traceback. Yo... |
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 = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def excmessage_decorator(description) -> Callable: """Wrap a function with |augment_excmessage|. Function |excmessage_decorator| is a means to apply function |aug... |
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
"""Apply |augment_excmessage| when the wrapped function fails."""
# pylint: disable=unused-argument
try:
return wrapped(*args, **kwargs)
except BaseException:
info = kwargs.copy()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_values(values, width=70):
"""Print the given values in multiple lines with a certain maximum width. By default, each line contains at most 70 character... |
for line in textwrap.wrap(repr_values(values), width=width):
print(line) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assignrepr_values(values, prefix, width=None, _fakeend=0):
"""Return a prefixed, wrapped and properly aligned string representation of the given values using... |
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 widt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assignrepr_values2(values, prefix):
"""Return a prefixed and properly aligned string representation of the given 2-dimensional value matrix using function |r... |
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(lin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _assignrepr_bracketed2(assignrepr_bracketed1, values, prefix, width=None):
"""Return a prefixed, wrapped and properly aligned bracketed string representation... |
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(assignrep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def round_(values, decimals=None, width=0, lfill=None, rfill=None, **kwargs):
"""Prints values with a maximum number of digits in doctests. See the documentation... |
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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract(values, types, skip=False):
"""Return a generator that extracts certain objects from `values`. This function is thought for supporting the definition... |
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].s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enumeration(values, converter=str, default=''):
"""Return an enumeration string based on the given values. The following four examples show the standard outp... |
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])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trim(self, lower=None, upper=None):
"""Trim negative value whenever there is no internal lake within the respective subbasin. lz(-1.0) lz(0.0) lz(1.0) """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_data(self, idx):
"""Call method |InputSequences.load_data| of all handled |InputSequences| objects.""" |
for subseqs in self:
if isinstance(subseqs, abctools.InputSequencesABC):
subseqs.load_data(idx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_data(self, idx):
"""Call method `save_data|` of all handled |IOSequences| objects registered under |OutputSequencesABC|.""" |
for subseqs in self:
if isinstance(subseqs, abctools.OutputSequencesABC):
subseqs.save_data(idx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conditions(self) -> Dict[str, Dict[str, Union[float, numpy.ndarray]]]: """Nested dictionary containing the values of all condition sequences. See the document... |
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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dirpath_int(self):
"""Absolute path of the directory of the internal data file. Normally, each sequence queries its current "internal" directory path from th... |
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 manuall... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disk2ram(self):
"""Move internal data from disk to RAM.""" |
values = self.series
self.deactivate_disk()
self.ramflag = True
self.__set_array(values)
self.update_fastaccess() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ram2disk(self):
"""Move internal data from RAM to disk.""" |
values = self.series
self.deactivate_ram()
self.diskflag = True
self._save_int(values)
self.update_fastaccess() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def numericshape(self):
"""Shape of the array of temporary values required for the numerical solver actually being selected.""" |
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. '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def series(self) -> InfoArray: """Internal time series data within an |numpy.ndarray|.""" |
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 us... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_ext(self):
"""Read the internal data from an external data file.""" |
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.deviceph... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adjust_short_series(self, timegrid, values):
"""Adjust a short time series to a longer timegrid. Normally, time series data to be read from a external data f... |
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:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_completeness(self):
"""Raise a |RuntimeError| if the |IOSequence.series| contains at least one |numpy.nan| value, if option |Options.checkseries| is en... |
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 '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_ext(self):
"""Write the internal data into an external data file.""" |
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.devicephra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_int(self):
"""Load internal data from file and return it.""" |
values = numpy.fromfile(self.filepath_int)
if self.NDIM > 0:
values = values.reshape(self.seriesshape)
return values |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def average_series(self, *args, **kwargs) -> InfoArray: """Average the actual time series of the |Variable| object for all time points. Method |IOSequence.average... |
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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aggregate_series(self, *args, **kwargs) -> InfoArray: """Aggregates time series data based on the actual |FluxSequence.aggregation_ext| attribute of |IOSequen... |
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, obje... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_files(self, idx):
"""Open all files with an activated disk flag.""" |
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):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close_files(self):
"""Close all files with an activated disk flag.""" |
for name in self:
if getattr(self, '_%s_diskflag' % name):
file_ = getattr(self, '_%s_file' % name)
file_.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_data(self, idx):
"""Load the internal data of all sequences. Load from file if the corresponding disk flag is activated, otherwise load from RAM.""" |
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
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_data(self, idx):
"""Save the internal data of all sequences with an activated flag. Write to file if the corresponding disk flag is activated; store in ... |
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' % na... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |AbsFHRU| based on |FT| and |FHRU|. absfhru(20.0, 80.0) """ |
control = self.subpars.pars.control
self(control.ft*control.fhru) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |KInz| based on |HInz| and |LAI|. 0.2 0.4 """ |
con = self.subpars.pars.control
self(con.hinz*con.lai) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |WB| based on |RelWB| and |NFk|. wb(20.0, 40.0) """ |
con = self.subpars.pars.control
self(con.relwb*con.nfk) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |WZ| based on |RelWZ| and |NFk|. wz(80.0, 160.0) """ |
con = self.subpars.pars.control
self(con.relwz*con.nfk) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |KB| based on |EQB| and |TInd|. kb(100.0) """ |
con = self.subpars.pars.control
self(con.eqb*con.tind) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |KI1| based on |EQI1| and |TInd|. ki1(50.0) """ |
con = self.subpars.pars.control
self(con.eqi1*con.tind) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |KI2| based on |EQI2| and |TInd|. ki2(10.0) """ |
con = self.subpars.pars.control
self(con.eqi2*con.tind) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |KD1| based on |EQD1| and |TInd|. kd1(5.0) """ |
con = self.subpars.pars.control
self(con.eqd1*con.tind) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |KD2| based on |EQD2| and |TInd|. kd2(1.0) """ |
con = self.subpars.pars.control
self(con.eqd2*con.tind) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |QFactor| based on |FT| and the current simulation step size. qfactor(0.115741) """ |
con = self.subpars.pars.control
self(con.ft*1000./self.simulationstep.seconds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _router_numbers(self):
"""A tuple of the numbers of all "routing" basins.""" |
return tuple(up for up in self._up2down.keys()
if up in self._up2down.values()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def supplier_elements(self):
"""A |Elements| collection of all "supplying" basins. (All river basins are assumed to supply something to the downstream basin.) Th... |
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
elemen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def router_elements(self):
"""A |Elements| collection of all "routing" basins. (Only river basins with a upstream basin are assumed to route something to the dow... |
elements = devicetools.Elements()
for router in self._router_numbers:
element = self._get_routername(router)
inlet = self._get_nodename(router)
try:
outlet = self._get_nodename(self._up2down[router])
except TypeError:
outle... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nodes(self):
"""A |Nodes| collection of all required nodes. Note that the required outlet node is added: Nodes("node_1123", "node_1125", "node_11269", "node_... |
return (
devicetools.Nodes(
self.node_prefix+routers for routers in self._router_numbers) +
devicetools.Node(self.last_node)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.