Skip to content

core

aquacrop.core

This file contains the AquacropModel class that runs the simulation.

AquaCropModel

This is the main class of the AquaCrop-OSPy model. It is in charge of executing all the operations.

Parameters:

sim_start_time (str): YYYY/MM/DD, Simulation start date

sim_end_time (str): date YYYY/MM/DD, Simulation end date

weather_df: daily weather data , created using prepare_weather

soil: Soil object contains paramaters and variables of the soil
        used in the simulation

crop: Crop object contains Paramaters and variables of the crop used
        in the simulation

initial_water_content: Defines water content at start of simulation

irrigation_management: Defines irrigation strategy

field_management: Defines field management options

fallow_field_management: Defines field management options during fallow period

groundwater: Stores information on water table parameters

co2_concentration: Defines CO2 concentrations

off_season: (True) simulate off-season or (False) skip ahead to start of 
            next growing season
Source code in aquacrop/core.py
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
class AquaCropModel:
    """
    This is the main class of the AquaCrop-OSPy model.
    It is in charge of executing all the operations.

    Parameters:

        sim_start_time (str): YYYY/MM/DD, Simulation start date

        sim_end_time (str): date YYYY/MM/DD, Simulation end date

        weather_df: daily weather data , created using prepare_weather

        soil: Soil object contains paramaters and variables of the soil
                used in the simulation

        crop: Crop object contains Paramaters and variables of the crop used
                in the simulation

        initial_water_content: Defines water content at start of simulation

        irrigation_management: Defines irrigation strategy

        field_management: Defines field management options

        fallow_field_management: Defines field management options during fallow period

        groundwater: Stores information on water table parameters

        co2_concentration: Defines CO2 concentrations

        off_season: (True) simulate off-season or (False) skip ahead to start of 
                    next growing season


    """

    # Model parameters
    __steps_are_finished: bool = False  # True if all steps of the simulation are done.
    __has_model_executed: bool = False  # Determines if the model has been run
    __has_model_finished: bool = False  # Determines if the model is finished
    __start_model_execution: float = 0.0  # Time when the execution start
    __end_model_execution: float = 0.0  # Time when the execution end
    # Attributes initialised later
    _clock_struct: "ClockStruct"
    _param_struct: "ParamStruct"
    _init_cond: "InitialCondition"
    _outputs: "Output"
    _weather: "DataFrame"

    def __init__(
        self,
        sim_start_time: str,
        sim_end_time: str,
        weather_df: "DataFrame",
        soil: "Soil",
        crop: "Crop",
        initial_water_content: "InitialWaterContent",
        irrigation_management: Optional["IrrigationManagement"] = None,
        field_management: Optional["FieldMngt"] = None,
        fallow_field_management: Optional["FieldMngt"] = None,
        groundwater: Optional["GroundWater"] = None,
        co2_concentration: Optional["CO2"] = None,
        off_season: bool=False,
    ) -> None:

        self.sim_start_time = sim_start_time
        self.sim_end_time = sim_end_time
        self.weather_df = weather_df
        self.soil = soil
        self.crop = crop
        self.initial_water_content = initial_water_content   
        self.co2_concentration = co2_concentration
        self.off_season = off_season

        self.irrigation_management = irrigation_management
        self.field_management = field_management
        self.fallow_field_management = fallow_field_management
        self.groundwater = groundwater

        if irrigation_management is None:
            self.irrigation_management = IrrigationManagement(irrigation_method=0)
        if field_management is None:
            self.field_management = FieldMngt()
        if fallow_field_management is None:
            self.fallow_field_management = FieldMngt()
        if groundwater is None:
            self.groundwater = GroundWater()
        if co2_concentration is None:
            self.co2_concentration = CO2()

    @property
    def sim_start_time(self) -> str:
        """
        Return sim start date
        """
        return self._sim_start_time

    @sim_start_time.setter
    def sim_start_time(self, value: str) -> None:
        """
        Check if sim start date is in a correct format.
        """

        if _sim_date_format_is_correct(value) is not False:
            self._sim_start_time = value
        else:
            raise ValueError("sim_start_time format must be 'YYYY/MM/DD'")

    @property
    def sim_end_time(self) -> str:
        """
        Return sim end date
        """
        return self._sim_end_time

    @sim_end_time.setter
    def sim_end_time(self, value: str) -> None:
        """
        Check if sim end date is in a correct format.
        """
        if _sim_date_format_is_correct(value) is not False:
            self._sim_end_time = value
        else:
            raise ValueError("sim_end_time format must be 'YYYY/MM/DD'")

    @property
    def weather_df(self) -> "DataFrame":
        """
        Return weather dataframe
        """
        return self._weather_df

    @weather_df.setter
    def weather_df(self, value: "DataFrame"):
        """
        Check if weather dataframe is in a correct format.
        """
        weather_df_columns = "Date MinTemp MaxTemp Precipitation ReferenceET".split(" ")
        if not all([column in value for column in weather_df_columns]):
            raise ValueError(
                "Error in weather_df format. Check if all the following columns exist "
                + "(Date MinTemp MaxTemp Precipitation ReferenceET)."
            )

        self._weather_df = value

    def _initialize(self) -> None:
        """
        Initialise all model variables
        """

        # Initialize ClockStruct object
        self._clock_struct = read_clock_parameters(
            self.sim_start_time, self.sim_end_time, self.off_season
        )

        # get _weather data
        self.weather_df = read_weather_inputs(self._clock_struct, self.weather_df)

        # read model params
        self._clock_struct, self._param_struct = read_model_parameters(
            self._clock_struct, self.soil, self.crop, self.weather_df
        )

        # read irrigation management
        self._param_struct = read_irrigation_management(
            self._param_struct, self.irrigation_management, self._clock_struct
        )

        # read field management
        self._param_struct = read_field_management(
            self._param_struct, self.field_management, self.fallow_field_management
        )

        # read groundwater table
        self._param_struct = read_groundwater_table(
            self._param_struct, self.groundwater, self._clock_struct
        )

        # Compute additional variables
        self._param_struct.CO2 = self.co2_concentration
        self._param_struct = compute_variables(
            self._param_struct, self.weather_df, self._clock_struct
        )

        # read, calculate inital conditions
        self._param_struct, self._init_cond = read_model_initial_conditions(
            self._param_struct, self._clock_struct, self.initial_water_content, self.crop
        )

        self._param_struct = create_soil_profile(self._param_struct)

        # Outputs results (water_flux, crop_growth, final_stats)
        self._outputs = Output(self._clock_struct.time_span, self._init_cond.th)

        # save model _weather to _init_cond
        self._weather = self.weather_df.values

    def run_model(
        self,
        num_steps: int = 1,
        till_termination: bool = False,
        initialize_model: bool = True,
        process_outputs: bool = False,
    ) -> bool:
        """
        This function is responsible for executing the model.

        Arguments:

            num_steps: Number of steps (Days) to be executed.

            till_termination: Run the simulation to completion

            initialize_model: Whether to initialize the model \
            (i.e., go back to beginning of season)

            process_outputs: process outputs into dataframe before \
                simulation is finished

        Returns:
            True if finished
        """

        if initialize_model:
            self._initialize()

        if till_termination:
            self.__start_model_execution = time.time()
            while self._clock_struct.model_is_finished is False:

                (
                    self._clock_struct,
                    self._init_cond,
                    self._param_struct,
                    self._outputs,
                ) = self._perform_timestep()
            self.__end_model_execution = time.time()
            self.__has_model_executed = True
            self.__has_model_finished = True
            return True
        else:
            if num_steps < 1:
                raise ValueError("num_steps must be equal to or greater than 1.")
            self.__start_model_execution = time.time()
            for i in range(num_steps):

                if (i == range(num_steps)[-1]) and (process_outputs is True):
                    self.__steps_are_finished = True

                (
                    self._clock_struct,
                    self._init_cond,
                    self._param_struct,
                    self._outputs,
                ) = self._perform_timestep()

                if self._clock_struct.model_is_finished:
                    self.__end_model_execution = time.time()
                    self.__has_model_executed = True
                    self.__has_model_finished = True
                    return True

            self.__end_model_execution = time.time()
            self.__has_model_executed = True
            self.__has_model_finished = False
            return True

    def _perform_timestep(
        self,
    ) -> Tuple["ClockStruct", "InitialCondition", "ParamStruct", "Output"]:

        """
        Function to run a single time-step (day) calculation of AquaCrop-OS
        """

        # extract _weather data for current timestep
        weather_step = _weather_data_current_timestep(
            self._weather, self._clock_struct.time_step_counter
        )

        # Get model solution_single_time_step
        new_cond, param_struct, outputs = solution_single_time_step(
            self._init_cond,
            self._param_struct,
            self._clock_struct,
            weather_step,
            self._outputs,
        )

        # Check model termination
        clock_struct = self._clock_struct
        clock_struct.model_is_finished = check_model_is_finished(
            self._clock_struct.step_end_time,
            self._clock_struct.simulation_end_date,
            self._clock_struct.model_is_finished,
            self._clock_struct.season_counter,
            self._clock_struct.n_seasons,
            new_cond.harvest_flag,
        )

        # Update time step
        clock_struct, _init_cond, param_struct = update_time(
            clock_struct, new_cond, param_struct, self._weather, self.crop
        )

        # Create  _outputsdataframes when model is finished
        final_water_flux_growth_outputs = outputs_when_model_is_finished(
            clock_struct.model_is_finished,
            outputs.water_flux,
            outputs.water_storage,
            outputs.crop_growth,
            self.__steps_are_finished,
        )

        if final_water_flux_growth_outputs is not False:
            (
                outputs.water_flux,
                outputs.water_storage,
                outputs.crop_growth,
            ) = final_water_flux_growth_outputs

        return clock_struct, _init_cond, param_struct, outputs

    def get_simulation_results(self):
        """
        Return all the simulation results
        """
        if self.__has_model_executed:
            if self.__has_model_finished:
                return self._outputs.final_stats
            else:
                return False  # If the model is not finished, the results are not generated.
        else:
            raise ValueError(
                "You cannot get results without running the model. "
                + "Please execute the run_model() method."
            )

    def get_water_storage(self):
        """
        Return water storage in soil results
        """
        if self.__has_model_executed:
            return self._outputs.water_storage
        else:
            raise ValueError(
                "You cannot get results without running the model. "
                + "Please execute the run_model() method."
            )

    def get_water_flux(self):
        """
        Return water flux results
        """
        if self.__has_model_executed:
            return self._outputs.water_flux
        else:
            raise ValueError(
                "You cannot get results without running the model. "
                + "Please execute the run_model() method."
            )

    def get_crop_growth(self):
        """
        Return crop growth results
        """
        if self.__has_model_executed:
            return self._outputs.crop_growth
        else:
            raise ValueError(
                "You cannot get results without running the model. "
                + "Please execute the run_model() method."
            )

    def get_additional_information(self) -> Dict[str, Union[bool, float]]:
        """
        Additional model information.

        Returns:
            dict: {has_model_finished,execution_time}

        """
        if self.__has_model_executed:
            return {
                "has_model_finished": self.__has_model_finished,
                "execution_time": self.__end_model_execution
                - self.__start_model_execution,
            }
        else:
            raise ValueError(
                "You cannot get results without running the model. "
                + "Please execute the run_model() method."
            )

sim_end_time: str property writable

Return sim end date

sim_start_time: str property writable

Return sim start date

weather_df: DataFrame property writable

Return weather dataframe

get_additional_information()

Additional model information.

Returns:

Name Type Description
dict Dict[str, Union[bool, float]]

{has_model_finished,execution_time}

Source code in aquacrop/core.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
def get_additional_information(self) -> Dict[str, Union[bool, float]]:
    """
    Additional model information.

    Returns:
        dict: {has_model_finished,execution_time}

    """
    if self.__has_model_executed:
        return {
            "has_model_finished": self.__has_model_finished,
            "execution_time": self.__end_model_execution
            - self.__start_model_execution,
        }
    else:
        raise ValueError(
            "You cannot get results without running the model. "
            + "Please execute the run_model() method."
        )

get_crop_growth()

Return crop growth results

Source code in aquacrop/core.py
417
418
419
420
421
422
423
424
425
426
427
def get_crop_growth(self):
    """
    Return crop growth results
    """
    if self.__has_model_executed:
        return self._outputs.crop_growth
    else:
        raise ValueError(
            "You cannot get results without running the model. "
            + "Please execute the run_model() method."
        )

get_simulation_results()

Return all the simulation results

Source code in aquacrop/core.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def get_simulation_results(self):
    """
    Return all the simulation results
    """
    if self.__has_model_executed:
        if self.__has_model_finished:
            return self._outputs.final_stats
        else:
            return False  # If the model is not finished, the results are not generated.
    else:
        raise ValueError(
            "You cannot get results without running the model. "
            + "Please execute the run_model() method."
        )

get_water_flux()

Return water flux results

Source code in aquacrop/core.py
405
406
407
408
409
410
411
412
413
414
415
def get_water_flux(self):
    """
    Return water flux results
    """
    if self.__has_model_executed:
        return self._outputs.water_flux
    else:
        raise ValueError(
            "You cannot get results without running the model. "
            + "Please execute the run_model() method."
        )

get_water_storage()

Return water storage in soil results

Source code in aquacrop/core.py
393
394
395
396
397
398
399
400
401
402
403
def get_water_storage(self):
    """
    Return water storage in soil results
    """
    if self.__has_model_executed:
        return self._outputs.water_storage
    else:
        raise ValueError(
            "You cannot get results without running the model. "
            + "Please execute the run_model() method."
        )

run_model(num_steps=1, till_termination=False, initialize_model=True, process_outputs=False)

This function is responsible for executing the model.

Arguments:

num_steps: Number of steps (Days) to be executed.

till_termination: Run the simulation to completion

initialize_model: Whether to initialize the model             (i.e., go back to beginning of season)

process_outputs: process outputs into dataframe before                 simulation is finished

Returns:

Type Description
bool

True if finished

Source code in aquacrop/core.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def run_model(
    self,
    num_steps: int = 1,
    till_termination: bool = False,
    initialize_model: bool = True,
    process_outputs: bool = False,
) -> bool:
    """
    This function is responsible for executing the model.

    Arguments:

        num_steps: Number of steps (Days) to be executed.

        till_termination: Run the simulation to completion

        initialize_model: Whether to initialize the model \
        (i.e., go back to beginning of season)

        process_outputs: process outputs into dataframe before \
            simulation is finished

    Returns:
        True if finished
    """

    if initialize_model:
        self._initialize()

    if till_termination:
        self.__start_model_execution = time.time()
        while self._clock_struct.model_is_finished is False:

            (
                self._clock_struct,
                self._init_cond,
                self._param_struct,
                self._outputs,
            ) = self._perform_timestep()
        self.__end_model_execution = time.time()
        self.__has_model_executed = True
        self.__has_model_finished = True
        return True
    else:
        if num_steps < 1:
            raise ValueError("num_steps must be equal to or greater than 1.")
        self.__start_model_execution = time.time()
        for i in range(num_steps):

            if (i == range(num_steps)[-1]) and (process_outputs is True):
                self.__steps_are_finished = True

            (
                self._clock_struct,
                self._init_cond,
                self._param_struct,
                self._outputs,
            ) = self._perform_timestep()

            if self._clock_struct.model_is_finished:
                self.__end_model_execution = time.time()
                self.__has_model_executed = True
                self.__has_model_finished = True
                return True

        self.__end_model_execution = time.time()
        self.__has_model_executed = True
        self.__has_model_finished = False
        return True

check_iwc_soil_match(iwc_layers, soil_layers)

This function checks if the number of soil layers is equivalent between the user-specified soil profile and initial water content.

Return

boolean: True if number of layers match

Source code in aquacrop/core.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
def check_iwc_soil_match(iwc_layers: int, soil_layers: int) -> bool:
    """
    This function checks if the number of soil layers is equivalent between the user-specified soil profile and initial water content.

    Arguments:
        iwc_layers
        soil_layers

    Return:
        boolean: True if number of layers match

    """
    if(iwc_layers == soil_layers):
        return True
    else:
        return False