Exemple #1
0
class spot_setup(object):
    """
    A 3 dimensional implementation of the Rosenbrock function

    Result at (1,1,1) is 0.
    """
    x = Uniform(-10, 10, 1.5, 3.0, -10, 10, doc='x value of Rosenbrock function')
    y = Uniform(-10, 10, 1.5, 3.0, -10, 10, doc='y value of Rosenbrock function')
    z = Uniform(-10, 10, 1.5, 3.0, -10, 10, doc='z value of Rosenbrock function')
    def __init__(self,used_algorithm='default'):
        self.used_algorithm =used_algorithm
    def simulation(self, vector):
        x=np.array(vector)
        simulations= [sum(100.0 * (x[1:] - x[:-1] ** 2.0) ** 2.0 + (1 - x[:-1]) ** 2.0)]
        return simulations
        
    def evaluation(self):
        observations = [0]
        return observations
    
    def objectivefunction(self, simulation, evaluation):
        if self.used_algorithm == 'sceua' or self.used_algorithm == 'abc' or self.used_algorithm == 'fscabc':
            objectivefunction = rmse(evaluation=evaluation, simulation=simulation)
        elif self.used_algorithm == 'dream' or self.used_algorithm == 'demcz' or self.used_algorithm == 'mcmc':
            objectivefunction = log_p(evaluation=evaluation, simulation=simulation)
        else:
            objectivefunction = - rmse(evaluation=evaluation, simulation=simulation)
        return objectivefunction
 def parameters(self):
     if self.params is None:
         self.params = [
             Uniform("0",
                     -10,
                     10,
                     1.5,
                     3.0,
                     -10,
                     10,
                     doc='x value of Rosenbrock function'),
             Uniform("1",
                     -10,
                     10,
                     1.5,
                     3.0,
                     -10,
                     10,
                     doc='y value of Rosenbrock function'),
             Uniform("z",
                     -10,
                     10,
                     1.5,
                     3.0,
                     -10,
                     10,
                     doc='z value of Rosenbrock function')
         ]
     return spotpy.parameter.generate(self.params)
Exemple #3
0
class spot_setup(object):
    cmax = Uniform(low=1.0, high=500, optguess=412.33)
    bexp = Uniform(low=0.1, high=2.0, optguess=0.1725)
    alpha = Uniform(low=0.1, high=0.99, optguess=0.8127)
    Ks = Uniform(low=0.001, high=0.10, optguess=0.0404)
    Kq = Uniform(low=0.1, high=0.99, optguess=0.5592)

    #fake1 =spotpy.parameter.Uniform(low=0.1 , high=10, optguess=0.5592)
    #fake2 =spotpy.parameter.Uniform(low=0.1 , high=10, optguess=0.5592)

    def __init__(self, obj_func=None):
        #Just a way to keep this example flexible and applicable to various examples
        self.obj_func = obj_func
        #Transform [mm/day] into [l s-1], where 1.783 is the catchment area
        self.Factor = 1.783 * 1000 * 1000 / (60 * 60 * 24)
        #Load Observation data from file
        self.PET, self.Precip = [], []
        self.date, self.trueObs = [], []
        #Find Path to Hymod on users system
        self.owd = os.path.dirname(os.path.realpath(__file__))
        self.hymod_path = self.owd + os.sep + 'hymod_python'
        climatefile = open(self.hymod_path + os.sep + 'hymod_input.csv', 'r')
        headerline = climatefile.readline()[:-1]

        #Read model forcing in working storage (this is done only ones)
        if ';' in headerline:
            self.delimiter = ';'
        else:
            self.delimiter = ','
        self.header = headerline.split(self.delimiter)
        for line in climatefile:
            values = line.strip().split(self.delimiter)
            self.date.append(str(values[0]))
            self.Precip.append(float(values[1]))
            self.PET.append(float(values[2]))
            self.trueObs.append(float(values[3]))
        climatefile.close()

    def simulation(self, x):
        #Here the model is actualy startet with one paramter combination
        data = hymod(self.Precip, self.PET, x[0], x[1], x[2], x[3], x[4])
        sim = []
        for val in data:
            sim.append(val * self.Factor)
        #The first year of simulation data is ignored (warm-up)
        return sim[366:]

    def evaluation(self):
        return self.trueObs[366:]

    def objectivefunction(self, simulation, evaluation, params=None):
        #SPOTPY expects to get one or multiple values back,
        #that define the performance of the model run
        if not self.obj_func:
            # This is used if not overwritten by user
            like = rmse(evaluation, simulation)
        else:
            #Way to ensure flexible spot setup class
            like = self.obj_func(evaluation, simulation)
        return like
class spot_setup(object):
    """
    A 3 dimensional implementation of the Rosenbrock function

    Result at (1,1,1) is 0.
    """
    x = Uniform(-10,
                10,
                1.5,
                3.0,
                -10,
                10,
                doc='x value of Rosenbrock function')
    y = Uniform(-10,
                10,
                1.5,
                3.0,
                -10,
                10,
                doc='y value of Rosenbrock function')
    z = Uniform(-10,
                10,
                1.5,
                3.0,
                -10,
                10,
                doc='z value of Rosenbrock function')

    def __init__(self, obj_func=None):
        self.obj_func = obj_func

    def simulation(self, vector):
        x = np.array(vector)
        simulations = [
            sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
        ]
        return simulations

    def evaluation(self):
        observations = [0]
        return observations

    def objectivefunction(self, simulation, evaluation, params=None):

        #SPOTPY expects to get one or multiple values back,
        #that define the performence of the model run
        if not self.obj_func:
            # This is used if not overwritten by user
            like = rmse(evaluation, simulation)
        else:
            #Way to ensure on flexible spot setup class
            like = self.obj_func(evaluation, simulation)
        return like
class SpotSetup(object):
    """
    Just a fun setup using non ASCIÎ letters to chällenge describe in Python 2
    """
    a = Uniform(-1, 1, doc='α parameter')
    beta = Uniform(-1, 1, doc='β parameter')

    @staticmethod
    def simulation(par):
        return [par.a + par.beta]

    @staticmethod
    def evaluation():
        return [0]

    @staticmethod
    def objectivefunction(simulation, evaluation):
        return abs(simulation[0] - evaluation[0])
class spot_setup(object):
    """
    A 3 dimensional implementation of the Rosenbrock function

    Result at (1,1,1) is 0.
    """
    x = Uniform(-10,
                10,
                1.5,
                3.0,
                -10,
                10,
                doc='x value of Rosenbrock function')
    y = Uniform(-10,
                10,
                1.5,
                3.0,
                -10,
                10,
                doc='y value of Rosenbrock function')
    z = Uniform(-10,
                10,
                1.5,
                3.0,
                -10,
                10,
                doc='z value of Rosenbrock function')

    def simulation(self, vector):
        x = np.array(vector)
        simulations = [
            sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
        ]
        return simulations

    def evaluation(self):
        observations = [0]
        return observations

    def objectivefunction(self, simulation, evaluation):
        objectivefunction = rmse(evaluation=evaluation, simulation=simulation)
        return objectivefunction
Exemple #7
0
class spot_setup(object):
    x1 = Uniform(low=1, high=1500, optguess=500)
    x2 = Uniform(low=-10, high=5, optguess=1)
    x3 = Uniform(low=1, high=500, optguess=250)
    x4 = Uniform(low=0.4, high=4, optguess=0.5)

    def __init__(self, bacia_nome, bacia_area, obj_func):
        # Definir funcao objetivo
        self.obj_func = obj_func
        # Definir bacia
        self.area = bacia_area
        # Carrega o arquivo PEQ (deve estar na mesma pasta do arquivo de exec)
        self.ETP, self.PME = [], []
        self.data, self.Q_obs = [], []

        path = os.path.dirname(os.path.realpath(__file__))
        PEQ = pd.read_csv('{}.csv'.format(bacia_nome),
                          index_col='data',
                          parse_dates=True)
        self.data = PEQ.index
        self.pme = PEQ.pme.to_numpy()
        self.etp = PEQ.etp.to_numpy()
        self.qin = PEQ.qin.to_numpy()
        self.qobs = PEQ.qobs.to_numpy()

    def simulation(self, x):
        # Executa a simulacao com o modelo hidrologico retornando a vazao em mm
        Qsim = gr4j.sim(self.pme, self.etp, self.area, x[0], x[1], x[2], x[3])
        return Qsim

    def evaluation(self):
        Qobs = self.qobs
        return Qobs

    def objectivefunction(self, simulation, evaluation, params=None):
        if params is None:
            params = {}
        wup = Estados.get('wup', 0)  # warm-up period

        NSE = (simulation - evaluation)**2 / (evaluation -
                                              np.mean(evaluation))**2
        return f
Exemple #8
0
def u(vmin, vmax, default=None, doc=None):
    """
    Creates a uniform distributed parameter
    :param vmin: Minimum value
    :param vmax: Maximum value
    :param default: Default value
    :param doc: Documentation of the parameter (use reStructuredText)
    :return: The parameter object
    """
    if default is None:
        default = 0.5 * (vmin + vmax)
    return Uniform(vmin, vmax, optguess=default, doc=doc)
 def __init__(self, default=True):
     self.params = []
     if default:
         for i in range(30):
             self.params.append(spotpy.parameter.Uniform(str(i+1), 0, 1, 0, 0, 0, 1,doc="param no " + str(i+1)))
     else:
         self.params = [Uniform(.5, 5., optguess=1.5, doc='saturated depth at beginning'),
                        Uniform(.001, .8, optguess=.1, doc='porosity of matrix [m3 Pores / m3 Soil]'),
                        Uniform(1., 240., optguess=10.,
                                doc='ssaturated conductivity of macropores [m/day]'),
                        Uniform(.0001, .5, optguess=.05, doc='macropore fraction [m3/m3]'),
                        Uniform(.005, 1., optguess=.05,
                                doc='mean distance between the macropores [m]'),
                        Uniform(0., 1., optguess=0.,
                                doc='water content when matric potential pointing towards -infinity'),
                        Uniform(.5, 1., optguess=.99,
                                doc='wetness above which the parabolic extrapolation is used instead of VGM'),
                        Uniform(0., 50, optguess=.1,
                                doc='exchange rate [1/day] for macropore-matrix-exchange')]
         for i in range(8,30):
             self.params.append(Uniform(str(i+1), 0, 1, 0, 0, 0, 1,doc="param no " + str(i+1)))
Exemple #10
0
class setup_hymod(object):

    cmax = Uniform(low=1.0, high=500)
    bexp = Uniform(low=0.1, high=2.0)
    alpha = Uniform(low=0.1, high=0.99)
    Ks = Uniform(low=0.001, high=0.10)
    Kq = Uniform(low=0.1, high=0.99)
    k = Uniform(low=0.5, high=7)
    x = Uniform(low=0.01, high=0.5)

    def __init__(self, area, PME, ETP, Qjus, Qmon=None, h_aq=0, fobj='KGE'):
        self.area = area
        self.PME = PME
        self.ETP = ETP
        self.Qjus = Qjus
        self.Qmon = Qmon
        self.h_aq = h_aq
        self.fobj = fobj

    def simulation(self, x):
        Qsim = hymod_nash(self.area,
                          self.PME,
                          self.ETP,
                          x[0],
                          x[1],
                          x[2],
                          x[3],
                          x[4],
                          x[5],
                          x[6],
                          Qmon=self.Qmon)
        return Qsim

    def evaluation(self):
        Qobs = self.Qjus
        return Qobs

    def objectivefunction(self, simulation, evaluation):
        criterio = getattr(funcoes_objetivo, self.fobj)(simulation, evaluation,
                                                        self.h_aq)
        fmin = 1 - criterio
        return fmin
Exemple #11
0
class ScalingTester:
    """
    A class to determine how CMF handles different amounts of cells. To test
    this the same model structure is run as a 1, 2, 4 and 8 cell layout. Each
    cell has the same structure and parameters.
    """
    # Catchment area km²
    area = 562.41

    # General storage parameter
    V0_L1 = Uniform(10, 300)
    V0_L2 = Uniform(10, 300)

    # ET parameter
    fETV1 = Uniform(0.01,
                    1,
                    doc='if V<fETV1*V0, water uptake stress for '
                    'plants starts [%]')
    fETV0 = Uniform(0,
                    0.9,
                    doc='if V<fETV0*fETV1*V0, plants die of drought '
                    '[%]')

    # Outflow parameters
    tr_L1_out = Uniform(0.1,
                        200,
                        doc='Residence time of water in storage '
                        'when '
                        'V=V0 [days]')
    tr_L1_L2 = Uniform(0.1, 200)
    tr_L2_out = Uniform(0.1, 200)

    beta_L1_out = Uniform(0.5, 4, doc="Exponent for scaling the outflow[]")
    beta_L1_L2 = Uniform(0.5, 4)
    beta_L2_out = Uniform(0.4, 4)

    # Snow parameters
    snow_meltrate = Uniform(3, 10, doc="Meltrate of the snow [(mm*degC)/day]")
    snow_melt_temp = Uniform(0,
                             3.5,
                             doc="Temperature at which the snow [degC]"
                             "melts")

    # Canopy Parameters
    LAI = Uniform(1, 12, doc="Leaf Area Index")
    CanopyClosure = Uniform(0.1, 0.9, doc="Closure of the Canopy [%]")

    def __init__(self, begin=None, end=None, num_cells=None):
        """
        Initializes the model.

        :param begin: Start year for the calibration
        :param end: Stop year
        :param num_cells: Number of cells used for this layout
        :return: None
        """
        self.dbname = "scaling_tester_num_cells_" + str(num_cells)

        # load driver data
        self.data = DataProvider("fulda_kaemmerzell_climate_79_89.csv")
        # Create cells and project
        self.project, self.outlet = self.create_project()
        self.num_cells = num_cells
        self.cells = self.create_cells()

        # Add the data and set the parameters with random value, so the
        # complete structure can be described.
        self.data.add_stations(self.project)
        self.begin = begin or self.data.begin
        self.end = end or self.data.end
        self.setparameters()

    def create_project(self):
        """
        Creates and CMF project with an outlet and other basic stuff and
        returns it.
        :return: cmf project and cmf outlet
        """
        # Use only a single thread, that is better for a calibration run and
        # for small models
        cmf.set_parallel_threads(1)

        # make the project
        p = cmf.project()

        # make the outlet
        outlet = p.NewOutlet("outlet", 10, 0, 0)
        return p, outlet

    def create_cells(self):
        """
        Creates a 'num_cells' amount of cells for the project
        :return:
        """
        # Adjust the cellsize to the amount of cells
        area = self.area / self.num_cells
        # Create all the cells!
        cells = []
        for num in range(self.num_cells):
            cells.append(CellTemplate(self.project, self.outlet, area, num))
        return cells

    def setparameters(self, par=None):
        """
        Sets the parameters for all cells seperately
        :return:
        """
        # Create tje parameters
        par = par or spotpy.parameter.create_set(self)
        # Call all cells
        for cell in self.cells:
            cell.set_parameters(par)

    def runmodel(self):
        """
        Runs the models and saves the results.

        :return: Simulated discharge
        """
        solver = cmf.CVodeIntegrator(self.project, 1e-9)

        # Result timeseries
        res_q = cmf.timeseries(self.begin, cmf.day)

        try:
            # Start solver and calculate in daily steps
            for t in solver.run(self.data.begin, self.end, cmf.day):
                res_q.add(self.outlet.waterbalance(t))
        except RuntimeError:
            return np.array(self.data.Q[self.data.begin:self.data.end +
                                        datetime.timedelta(days=1)]) * np.nan

        return res_q

    def simulation(self, vector=None):
        """
        Sets the parameters of the model and starts a run
        :return: np.array with runoff in mm/day
        """
        self.setparameters(vector)
        result_q = self.runmodel()
        result_q /= 86400
        return np.array(result_q[self.begin:self.end])

    def evaluation(self):
        """Returns the evaluation data"""
        return np.array(self.data.Q[self.begin:self.end])

    def objectivefunction(self, simulation, evaluation):
        """Calculates the objective function"""
        return spotpy.objectivefunctions.nashsutcliffe(evaluation, simulation)
    def _objfunc_switcher(self, name):
        """
        Set new parameter and objective function while setup is instanced in a test case
        :param name: function name which overwrites initial objective function
        :return:
        """

        if name == "ackley":
            self.objfunc = ackley10
            self.params = [
                Uniform(str(j),
                        -2,
                        2,
                        1.5,
                        3.0,
                        -2,
                        2,
                        doc=str(j) + ' value of Rosenbrock function')
                for j in range(10)
            ]
        elif name == "griewank":
            self.objfunc = griewank10
            self.params = [
                Uniform('d' + str(j),
                        -500,
                        700,
                        1.5,
                        3.0,
                        -500,
                        700,
                        doc=str(j) + 'distinc parameter within a boundary',
                        as_int=True) for j in range(2)
            ] + [
                Uniform('c' + str(j),
                        -500,
                        700,
                        1.5,
                        3.0,
                        -500,
                        700,
                        doc=str(j) + 'continuous parameter within a boundary')
                for j in range(8)
            ]
        elif name == "cmf_style":
            self.objfunc = ackley10
            self.params = [
                Uniform(.5,
                        5.,
                        optguess=1.5,
                        doc='saturated depth at beginning'),
                Uniform(.001,
                        .8,
                        optguess=.1,
                        doc='porosity of matrix [m3 Pores / m3 Soil]'),
                Uniform(1.,
                        240.,
                        optguess=10.,
                        doc='ssaturated conductivity of macropores [m/day]'),
                Uniform(.0001,
                        .5,
                        optguess=.05,
                        doc='macropore fraction [m3/m3]'),
                Uniform(.005,
                        1.,
                        optguess=.05,
                        doc='mean distance between the macropores [m]'),
                Uniform(
                    0.,
                    1.,
                    optguess=0.,
                    doc=
                    'water content when matric potential pointing towards -infinity'
                ),
                Uniform(
                    .5,
                    1.,
                    optguess=.99,
                    doc=
                    'wetness above which the parabolic extrapolation is used instead of VGM'
                ),
                Uniform(
                    0.,
                    50,
                    optguess=.1,
                    doc='exchange rate [1/day] for macropore-matrix-exchange')
            ]
Exemple #13
0
class SingleStorage(object):
    """
    A simple hydrological single storage model.
    No snow, interception  or routing.
    """
    # Catchment area
    area = 2976.41e6  # sq m
    # General storage parameter
    V0 = Uniform(10, 10000, optguess=1000)

    # ET parameters
    fETV1 = Uniform(0.01, 1, optguess=0.2, doc='if V<fETV1*V0, water uptake stress for plants starts')
    fETV0 = Uniform(0, 0.9, optguess=0.2, doc='if V<fETV0*fETV1*V0, plants die of drought')

    # Outflow parameters
    tr = Uniform(0.1, 1000, optguess=10, doc='Residence time of water in storage when V=V0')
    Vr = Uniform(0, 1, optguess=0.0, doc='Residual water in storage in terms of V0')
    beta = Uniform(0.3, 5, optguess=1, doc='Exponent in kinematic wave function')

    max_run_minutes = 5

    def __init__(self, begin=None, end=None):
        """
        Initializes the model

        :param begin: Start year for calibration
        :param end: stop year

        """

        self.dbname = 'cmf_singlestorage'

        # Loads driver data
        self.data = DataProvider()
        self.project, self.outlet = self.create_project()
        self.data.add_stations(self.project)
        self.setparameters()

        self.begin = begin or self.data.begin
        self.end = end or self.data.end

    def __str__(self):
        return type(self).__name__

    def create_project(self):
        """
        Creates the cmf project with its basic elements
        """
        # Use only a single thread, that is better for a calibration run and for small models
        cmf.set_parallel_threads(1)

        # make the project
        p = cmf.project()

        # make a new cell
        c = p.NewCell(0, 0, 0, 1000)

        # Add a storage
        layer = c.add_layer(1.0)
        # ET
        cmf.HargreaveET(layer, c.transpiration)
        # Outlet
        outlet = p.NewOutlet('outlet', 10, 0, 0)
        return p, outlet

    def setparameters(self, par=None):
        """
        Sets the parameters of the model by creating the connections
        """
        par = par or spotpy.parameter.create_set(self, valuetype='optguess')

        # Some shortcuts to gain visibility
        c = self.project[0]
        o = self.outlet

        # Set uptake stress
        ETV1 = par.fETV1 * par.V0
        ETV0 = par.fETV0 * ETV1
        c.set_uptakestress(cmf.VolumeStress(ETV1, ETV0))

        # Connect layer with outlet
        cmf.PowerLawConnection(c.layers[0], o,
                               Q0=par.V0 / par.tr, beta=par.beta,
                               residual=par.Vr * par.V0, V0=par.V0)

    def runmodel(self, verbose=False):
        """
        Runs the model and saves the results
        """
        solver = cmf.CVodeIntegrator(self.project, 1e-9)
        c = self.project[0]

        # result timeseries
        res_q = cmf.timeseries(self.begin, cmf.day)

        tstart = datetime.datetime.now()
        # start solver and calculate in daily steps
        for t in solver.run(self.data.begin, self.end, cmf.day):
            if t > self.begin:
                # append results, when spin up time is over
                res_q.add(self.outlet.waterbalance(t))
            # Give the status the screen to let us know what is going on
            if verbose:
                print(t, 'P={:5.3f}'.format(c.get_rainfall(t)))
            if datetime.datetime.now() - tstart > datetime.timedelta(minutes=self.max_run_minutes):
                print('Cancelled, since it took more than {} minutes'.format(self.max_run_minutes))
                for t in cmf.timerange(solver.t, self.end, cmf.day):
                    res_q.add(np.nan)

        return res_q

    def simulation(self, vector=None, verbose=False):
        """
        Sets the parameters of the model and starts a run
        :return: np.array with runoff in mm/day
        """
        self.setparameters(vector)
        result_q = self.runmodel(verbose)

        return np.array(result_q[self.begin:self.end])

    @staticmethod
    def objectivefunction(simulation, evaluation):
        """
        Calculates the goodness of the simulation
        """
        return [
            spotpy.objectivefunctions.nashsutcliffe(evaluation, simulation),
            spotpy.objectivefunctions.pbias(evaluation, simulation)
        ]

    def evaluation(self):
        """
        Returns the evaluation data
        """
        runoff_mm = self.data.runoff_mm(self.area)
        return np.array(runoff_mm[self.begin:self.end])
class spot_setup:
    # defining all parameters and the distribution
    param = lr_T, lr_RRR, lr_RH, RRR_factor, alb_ice, alb_snow, alb_firn,\
            albedo_aging, albedo_depth = [
        Uniform(low=-0.007, high=-0.005),  # lr_temp
        Uniform(low=0, high=0.00017),  # lr_prec
        Uniform(low=0, high=0.1), #lr RH2 -> in percent so from 0 to 1 % no prior knowledge for this factor
        Uniform(low=0.6, high=0.7,  step=0.01), #1.235, high=1.265
        Uniform(low=0.18, high=0.4, step=0.01),  # alb ice
        Uniform(low=0.65, high=0.9, step=0.01),  # alb snow
        Uniform(low=0.4, high=0.65, step=0.01), #alb_firn
        Uniform(low=5, high=23, step=1), #effect of age on snow albedo (days)
        Uniform(low=3, high=8, step=1) #effect of snow depth on albedo (cm) 
        ]

    # Number of needed parameter iterations for parametrization and sensitivity analysis
    M = 4  # inference factor (default = 4)
    d = 2  # frequency step (default = 2)
    k = len(param)  # number of parameters

    par_iter = (1 + 4 * M**2 * (1 + (k - 2) * d)) * k

    def __init__(self, obs, count="", obj_func=None):
        self.obj_func = obj_func
        self.obs = obs
        self.count = count
        print("Initialised.")

    def simulation(self, x):
        if isinstance(self.count, int):
            self.count += 1
        print("Count", self.count)
        sim = main(lr_T=x.lr_T,
                   lr_RRR=x.lr_RRR,
                   lr_RH=x.lr_RH,
                   RRR_factor=x.RRR_factor,
                   alb_ice=x.alb_ice,
                   alb_snow=x.alb_snow,
                   alb_firn=x.alb_firn,
                   albedo_aging=x.albedo_aging,
                   albedo_depth=x.albedo_depth,
                   count=self.count)
        sim = sim[sim['time'].isin(obs.index)]
        return sim.Med_TSL.values

    def evaluation(self):
        tsl_obs = self.obs.copy()
        return tsl_obs

    def objectivefunction(self, simulation, evaluation, params=None):
        # SPOTPY expects to get one or multiple values back,
        # that define the performance of the model run
        if not self.obj_func:
            eval = np.delete(evaluation.SC_median.values,
                             np.argwhere(np.isnan(simulation)))
            sim = simulation[~np.isnan(simulation)]
            like = -rmse(
                eval, sim
            )  #set minus before rmse if trying to maximize, depends on algorithm
            print("RMSE is: ", like)
        else:
            # Way to ensure flexible spot setup class
            like = self.obj_func(evaluation.SC_median.values,
                                 simulation.Med_TSL.values)
        return like
    def __init__(self,
                 p_and_e,
                 qobs,
                 warmup_length=30,
                 model="xaj",
                 obj_func=None):
        """
        Set up for Spotpy

        Parameters
        ----------
        p_and_e
            inputs of model
        qobs
            observation data
        warmup_length
            GR4J model need warmup period
        model
            we support "gr4j", "hymod", and "xaj"
        obj_func
            objective function, typically RMSE
        """
        if model == "xaj":
            self.parameter_names = [
                # Allen, R.G., L. Pereira, D. Raes, and M. Smith, 1998.
                # Crop Evapotranspiration, Food and Agriculture Organization of the United Nations,
                # Rome, Italy. FAO publication 56. ISBN 92-5-104219-5. 290p.
                "K",  # ratio of potential evapotranspiration to reference crop evaporation generally from Allen, 1998
                "B",  # The exponent of the tension water capacity curve
                "IM",  # The ratio of the impervious to the total area of the basin
                "UM",  # Tension water capacity in the upper layer
                "LM",  # Tension water capacity in the lower layer
                "DM",  # Tension water capacity in the deepest layer
                "C",  # The coefficient of deep evapotranspiration
                "SM",  # The areal mean of the free water capacity of surface soil layer
                "EX",  # The exponent of the free water capacity curve
                "KI",  # Outflow coefficients of interflow
                "KG",  # Outflow coefficients of groundwater
                "CS",  # The recession constant of channel system
                "L",  # Lag time
                "CI",  # The recession constant of the lower interflow
                "CG",  # The recession constant of groundwater storage
            ]
        elif model == "xaj_mz":
            # use mizuRoute for xaj's surface routing module
            self.parameter_names = [
                # Allen, R.G., L. Pereira, D. Raes, and M. Smith, 1998.
                # Crop Evapotranspiration, Food and Agriculture Organization of the United Nations,
                # Rome, Italy. FAO publication 56. ISBN 92-5-104219-5. 290p.
                "K",  # ratio of potential evapotranspiration to reference crop evaporation generally from Allen, 1998
                "B",  # The exponent of the tension water capacity curve
                "IM",  # The ratio of the impervious to the total area of the basin
                "UM",  # Tension water capacity in the upper layer
                "LM",  # Tension water capacity in the lower layer
                "DM",  # Tension water capacity in the deepest layer
                "C",  # The coefficient of deep evapotranspiration
                "SM",  # The areal mean of the free water capacity of surface soil layer
                "EX",  # The exponent of the free water capacity curve
                "KI",  # Outflow coefficients of interflow
                "KG",  # Outflow coefficients of groundwater
                "A",  # parameter of mizuRoute
                "THETA",  # parameter of mizuRoute
                "CI",  # The recession constant of the lower interflow
                "CG",  # The recession constant of groundwater storage
            ]
        elif model == "gr4j":
            self.parameter_names = ["x1", "x2", "x3", "x4"]
        elif model == "hymod":
            self.parameter_names = ["cmax", "bexp", "alpha", "ks", "kq"]
        else:
            raise NotImplementedError("We don't provide this model now")
        self.model = model
        self.params = []
        for par_name in self.parameter_names:
            # All parameters' range are [0,1], we will transform them to normal range in the model
            self.params.append(Uniform(par_name, low=0.0, high=1.0))
        # Just a way to keep this example flexible and applicable to various examples
        self.obj_func = obj_func
        # Load Observation data from file
        self.p_and_e = p_and_e
        # chose observation data after warmup period
        self.true_obs = qobs[warmup_length:, :, :]
        self.warmup_length = warmup_length
Exemple #16
0
class spot_setup(object):

    UZTWM  = Uniform(low=10, high=150)
    UZFWM  = Uniform(low=10, high=75)
    LZTWM  = Uniform(low=75, high=400)
    LZFSM  = Uniform(low=10, high=300)
    LZFPM  = Uniform(low=50, high=1000)
    UZK    = Uniform(low=0.2, high=0.4)
    LZSK   = Uniform(low=0.020, high=0.250)
    LZPK   = Uniform(low=0.001, high=0.020)
    PFREE  = Uniform(low=0, high=0.6)
    ZPERC  = Uniform(low=5, high=250)
    REXP   = Uniform(low=1.1, high=4)
    PCTIM  = Uniform(low=0, high=0.1)
    ADIMP  = Uniform(low=0, high=0.2)
    k_HU   = Uniform(low=0.5, high=10)
    C1     = Uniform(low=0.01, high=0.35)
    C2     = Uniform(low=0.01, high=0.35)
    k_musk = Uniform(low=0.5, high=10)
    x      = Uniform(low=0.01, high=0.5)

    def __init__(self, area, PME, ETP, Qjus, Qmon=None, h_aq=0, fobj='KGE'):
        self.area = area
        self.PME  = PME
        self.ETP  = ETP
        self.Qjus = Qjus
        self.Qmon = Qmon
        self.h_aq = h_aq
        self.fobj = fobj

    def simulation(self, x):
        Qsim = sacramento(self.area, self.PME, self.ETP,  \
                            x[0], x[1], x[2], x[3], x[4], \
                            x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], \
                            x[13], x[14], x[15], x[16], x[17], Qmon=self.Qmon)
        return Qsim

    def evaluation(self):
        Qobs = self.Qjus
        return Qobs

    def objectivefunction(self, simulation, evaluation):
        criterio = getattr(funcoes_objetivo, self.fobj)(simulation, evaluation, self.h_aq)
        fmin = 1 - criterio
        return fmin