Skip to content

API reference#

PyWheat classes#

crown_temperatures(snow_depth=0, Tmin=None, Tmax=None) #

Crown temperatures are simulated according to the original routines in CERES-Wheat and the correspond to air temperatures for non-freezing temperatures. The minimum and maximum crown temperatures (Tcmin and Tcmax) are calculated according to the maximum and minimun air temperatures (Tmax and Tmin), respectively.

Parameters:

Name Type Description Default
snow_depth int

Snow depth in centimeters (cm). Default value is set to zero.

0
Tmin float

Minimum Temperature (°C)

None
Tmax float

Maximum Temperature (°C)

None

Returns:

Name Type Description
Tcmin float

Minimum Crown Temperature (°C)

Tcmax float

Maximum Crown Temperature (°C)

Tcrown float

Optimum Crown Temperature (°C)

Source code in pywheat/pheno/__init__.py
def crown_temperatures(snow_depth=0, Tmin=None, Tmax=None):
    '''
        Crown temperatures are simulated according to the original routines in CERES-Wheat and the correspond 
        to air temperatures for non-freezing temperatures. The minimum and maximum crown temperatures (Tcmin and Tcmax) 
        are calculated according to the maximum and minimun air temperatures (Tmax and Tmin), respectively.

        Parameters:
            snow_depth (int): Snow depth in centimeters (cm). Default value is set to zero.
            Tmin (float): Minimum Temperature (°C)
            Tmax (float): Maximum Temperature (°C)

        Returns:
            Tcmin (float): Minimum Crown Temperature (°C)
            Tcmax (float): Maximum Crown Temperature (°C)
            Tcrown (float): Optimum Crown Temperature (°C)

    '''
    if (Tmin is None or Tmax is None):
        print("Please check out your inputs.")
        return

    Tcmax = None
    Tcmin = None

    def calc_CrownTemp(T, snow_depth=0):
        Tcrown = T
        snow_depth = min(snow_depth, 15)
        if (T < 0.0):
            Tcrown = 2.0 + T * (0.4 + 0.0018 * (snow_depth - 15)**2 )
        return Tcrown

    # Crown temperature for maximum development rate
    Tcmax = calc_CrownTemp(Tmax, snow_depth)
    # Crown temperature when snow is present and TMIN < 0.
    Tcmin = calc_CrownTemp(Tmin, snow_depth)

    Tcrown = (Tcmax + Tcmin) / 2 

    return Tcmax, Tcmin, Tcrown

day_length(DOY=1, lat=0.0, p=0.0) #

Length of the day for a specific site

Day length is calculated from day of year (DOY), latitude and the civil twilight using standard astronomical equations. Twilight is defined as the interval between sunrise or sunset and the time whan the true center of the sun is 6° below the horizon.

Parameters:

Name Type Description Default
DOY int

Day of year

1
lat float

Latitude of the site in celsius degrees

0.0
p float

Sun angle with the horizon. eg. p = 6.0 : civil twilight, p = 0.0 : day starts / ends when sun is even with the horizon. Default value p=0

0.0

Returns:

Name Type Description
daylength float

A daylength for the specific site

Source code in pywheat/pheno/__init__.py
def day_length(DOY=1, lat=0.0, p=0.0):
    '''
        Length of the day for a specific site

        Day length is calculated from day of year (DOY), latitude and the civil twilight using 
        standard astronomical equations. Twilight is defined as the interval between sunrise or 
        sunset and the time whan the true center of the sun is 6° below the horizon.

        Parameters:
            DOY (int): Day of year
            lat (float): Latitude of the site in celsius degrees
            p (float):  Sun angle with the horizon. eg. p = 6.0 : civil twilight,
                        p = 0.0 : day starts / ends when sun is even with the horizon.
                        Default value p=0

        Returns: 
            daylength (float): A daylength for the specific site

    '''
    S1 = math.sin(lat * 0.0174533) # np.sin(np.deg2rad(lat))
    C1 = math.cos(lat * 0.0174533) # np.cos(np.deg2rad(lat))
    DEC = 0.4093 * math.sin( 0.0172 * (DOY - 82.2) )
    DLV = ( ( -S1 * math.sin(DEC) - 0.1047 ) / ( C1 * math.cos(DEC) ) )
    DLV = max(DLV,-0.87)
    TWILEN = 7.639 * math.acos(DLV)

    # Another way to calculate
    #latInRad = np.deg2rad(lat)
    #revolutionAngle = 0.2163108 + 2*np.arctan(0.9671396*np.tan(0.00860 *(dayOfYear - 186)))
    #declinationAngle = np.arcsin(0.39795*np.cos(revolutionAngle))
    #value = (np.sin(np.deg2rad(p)) + (np.sin(latInRad)*np.sin(declinationAngle))) / (np.cos(latInRad)*np.cos(declinationAngle))
    #if value <= -1.0: 
    #    return  0.0
    #if value >= 1.0: 
    #    return 24.0
    #else: 
    #    return 24 - (24/np.pi)*np.arccos(value)


    return TWILEN

determine_anthesis_stage(initparams=None, verbose=False) #

Estimate Wheat phenological stages using an improved PyWheat model calibrated with IWIN datasets (ESWYT, IDYN, HTWYT and SAWYT nurseries)

Parameters:

Name Type Description Default
initparams dict

A dictionary with initial parameters

None
verbose bool

Display comments during the processes. Default is False

False

Attributes:

Name Type Description
weather object

A table or dataframe with weather data for the site

TT_TBASE float

Base temperature for estimate Thermal time. Default 0.0

TT_TEMPERATURE_OPTIMUM float

Thermal time optimum temperature. Default 26

TT_TEMPERATURE_MAXIMUM float

Thermal time maximum temperature. Default 34

CIVIL_TWILIGHT float

Sun angle with the horizon. eg. p = 6.0 : civil twilight. Default 0.0

HI float

Hardiness Index. Default 0.0

SNOW float

Snow fall. Default 0.0

SDEPTH float

Sowing depth in cm. Default 3.0 cm

GDDE float

Growing degree days per cm seed depth required for emergence, Default 6.2 GDD/cm.

DSGFT float

GDD from End Ear Growth to Start Grain Filling period. Default 200 degree-days

VREQ (float

Vernalization required for max.development rate (VDays). Default 505 degree-days

PHINT float

Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. Default 95.0 degree-days

P1V float

Development genetic coefficients, vernalization. 1 for spring type, 5 for winter type. Default 4.85

P1D float

Development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length). Default 3.675

P5 float

Grain filling degree days. Old value was divided by 10. Default 500 degree-days.

P6 float

Approximate the thermal time from physiological maturity to harvest. Default 250.

DAYS_GERMIMATION_LIMIT float

Threshold for days to germination. Default 40

TT_EMERGENCE_LIMIT int

Threshold for thermal time to emergence. Default 300 degree-days

TT_TDU_LIMIT float

Threshold for thermal development units (TDU). Default 400 degree-days

ADAH int

Number of days after heading. A threshold used for anthesis date after planting. Default is 6 days after heading.

Returns:

Name Type Description
growstages dict

A dictionary with all phenological stages and addtional useful information

Source code in pywheat/pheno/__init__.py
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
def determine_anthesis_stage(initparams=None, verbose=False):
    '''
        Estimate Wheat phenological stages using an improved PyWheat model calibrated 
        with IWIN datasets (ESWYT, IDYN, HTWYT and SAWYT nurseries)

        Parameters:
            initparams (dict): A dictionary with initial parameters
            verbose (bool): Display comments during the processes. Default is False

        Attributes:
            weather (object): A table or dataframe with weather data for the site
            TT_TBASE (float): Base temperature for estimate Thermal time. Default 0.0
            TT_TEMPERATURE_OPTIMUM (float): Thermal time optimum temperature. Default 26
            TT_TEMPERATURE_MAXIMUM (float): Thermal time maximum temperature. Default 34
            CIVIL_TWILIGHT (float): Sun angle with the horizon. eg. p = 6.0 : civil twilight. Default 0.0
            HI (float): Hardiness Index. Default 0.0 
            SNOW (float): Snow fall. Default 0.0
            SDEPTH (float): Sowing depth in cm. Default 3.0 cm
            GDDE (float): Growing degree days per cm seed depth required for emergence, Default 6.2 GDD/cm.
            DSGFT (float): GDD from End Ear Growth to Start Grain Filling period. Default 200 degree-days
            VREQ  (float): Vernalization required for max.development rate (VDays). Default 505 degree-days
            PHINT (float): Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. Default 95.0 degree-days
            P1V (float): Development genetic coefficients, vernalization. 1 for spring type, 5 for winter type. Default 4.85
            P1D (float): Development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length). Default 3.675
            P5 (float): Grain filling degree days. Old value was divided by 10. Default 500 degree-days.
            P6 (float): Approximate the thermal time from physiological maturity to harvest. Default 250.
            DAYS_GERMIMATION_LIMIT (float): Threshold for days to germination. Default 40
            TT_EMERGENCE_LIMIT (int): Threshold for thermal time to emergence. Default 300 degree-days
            TT_TDU_LIMIT (float): Threshold for thermal development units (TDU). Default 400  degree-days
            ADAH (int): Number of days after heading. A threshold used for anthesis date after planting. Default is 6 days after heading.

        Returns:
            growstages (dict): A dictionary with all phenological stages and addtional useful information

    '''
    if (initparams is None):
        print("Please check out the input parameters")
        return

    # Initialization of variables 
    params = dict(
        weather = None, # Weather data of the site
        sowing_date = "", # Sowing date in YYYY-MM-DD
        latitude = -90.0, # Latitude of the site
        longitude = -180.0, # Longitude of the site
        genotype = "", # Name of the grand parent in IWIN pedigrees database 
        TT_TBASE = 0.0, # Base Temperature, 2.0 to estimate HI
        TT_TEMPERATURE_OPTIMUM = 26, # Thermal time optimum temperature
        TT_TEMPERATURE_MAXIMUM = 34, # Thermal time maximum temperature
        CIVIL_TWILIGHT = 0.0, # Sun angle with the horizon. eg. p = 6.0 : civil twilight,
        HI = 0.0, # Hardiness Index
        SNOW = 0, # Snow fall
        SDEPTH = 3.0, # Sowing depth in cm
        GDDE = 6.2, # Growing degree days per cm seed depth required for emergence, GDD/cm
        DSGFT = 200, # GDD from End Ear Growth to Start Grain Filling period
        VREQ  = 505.0, # Vernalization required for max.development rate (VDays)
        PHINT = 95.0, # Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. 
        P1V = 1.0, # development genetic coefficients, vernalization. 1 for spring type, 5 for winter type
        P1D = 3.675, # development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length)
        P5 = 500, # grain filling degree days eg. 500 degree-days. Old value was divided by 10.
        P6 = 250, # approximate the thermal time from physiological maturity to harvest
        DAYS_GERMIMATION_LIMIT = 40, # threshold for days to germination
        TT_EMERGENCE_LIMIT = 300, # threshold for thermal time to emergence
        TT_TDU_LIMIT = 400, # threshold for thermal development units (TDU)
        ADAH = 6, # threshold for anthesis date after planting. This is a 6 days after heading.
    )
    if (initparams is not None):
        params = {**params, **initparams}

    # Validate
    if (params['sowing_date']=="" or params['sowing_date'] is None):
        print("Sowing date not defined")
        return
    if (params['latitude']==-90.0 or params['latitude'] is None):
        print("Problem with location of the site. Check the geographic coordinates.")
        return
    if (params['weather'] is None):
        print("Weather data is not available")
        return
    else:
        weather = params['weather']

    # ---------------------
    # GDD limits
    # ---------------------
    #P3 = params['PHINT'] * 2
    #P4 = params['DSGFT'] #200 # APSIM-Wheat = 120 # GDD from End Ear Growth to Start Grain Filling period

    growstages = {
            '7': {'istage_old': 'Sowing', 'istage': 'Fallow', 'desc': 'No crop present to Sowing', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '8': {'istage_old': 'Germinate', 'istage': 'Sowing', 'desc': 'Sowing to Germination', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '9': {'istage_old': 'Emergence', 'istage': 'Germinate', 'desc': 'Emergence to End of Juvenile', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '1': {'istage_old': 'Term Spklt', 'istage': 'Emergence', 'desc': 'Emergence to End of Juvenile', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '2': {'istage_old': 'End Veg', 'istage': 'End Juveni', 'desc': 'End of Juvenile to End of Vegetative growth', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '2.5': {'istage_old': 'Anthesis', 'istage': 'Anthesis', 'desc': 'Anthesis', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '3': {'istage_old': 'End Ear Gr', 'istage': 'End Veg', 'desc': 'End of Vegetative Growth to End of Ear Grow', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},

    }

    class StageFailed(Exception):
        def __init__(self, m, istage, err):
            self.message = m
            self.istage = istage
            self.err = err
        def __str__(self):
            return self.message + f" Stage ({self.istage}) - " + f"Error: {self.err}"

    # --------------------------------------------------------------------------
    # DETERMINE SOWING DATE
    # --------------------------------------------------------------------------
    ISTAGE = 7
    try:
        SOWING_DATE = pd.to_datetime(str(params['sowing_date']), format='%Y-%m-%d' )
        DOY = pd.to_datetime(SOWING_DATE).dayofyear

        growstages[f'{ISTAGE}']['date'] = str(SOWING_DATE).split(' ')[0]
        growstages[f'{ISTAGE}']['DOY'] = int(DOY)
        growstages[f'{ISTAGE}']['AGE'] = 0
        growstages[f'{ISTAGE}']['SUMDTT'] = 0
        growstages[f'{ISTAGE}']['DAP'] = 0
        #print("Sowing date:", SOWING_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem initializing the determination of phenological stage. Please check your input parameters such as sowing date or latitude of the site", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return


    # --------------------------------------------------------------------------
    # DETERMINE GERMINATION  DATE
    # --------------------------------------------------------------------------
    ISTAGE = 8
    try:
        SUMDTT = 0.0
        #VF = 0.0
        DAP = 0
        ndays = 1 # Seed germination is a rapid process and is assumed to occur in one day
        w = weather[(weather['DATE']==(SOWING_DATE + pd.DateOffset(days=ndays)) )].reset_index(drop=True)
        GERMINATION_DATE = ''
        Tmin = float(w.iloc[ndays-1]['TMIN'])
        Tmax = float(w.iloc[ndays-1]['TMAX'])
        # Thermal time
        DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                       Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                       Ttop=params['TT_TEMPERATURE_MAXIMUM'])
        SUMDTT = SUMDTT + DTT
        GERMINATION_DATE = w.iloc[ndays-1]['DATE']
        CROP_AGE = str(GERMINATION_DATE - SOWING_DATE).replace(' days 00:00:00','')
        DAP = DAP + int(CROP_AGE)
        growstages[f'{ISTAGE}']['date'] = str(GERMINATION_DATE).split(' ')[0]
        growstages[f'{ISTAGE}']['DOY'] = int(GERMINATION_DATE.dayofyear)
        growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
        growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
        growstages[f'{ISTAGE}']['DAP'] = DAP

        #print("Germination date:", GERMINATION_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining germination date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return


    # --------------------------------------------------------------------------
    # DETERMINE SEEDLING EMERGENCE DATE
    # --------------------------------------------------------------------------
    ISTAGE = 9
    P9 = 40 + params['GDDE'] * params['SDEPTH']
    try:
        SUMDTT = 0.0
        #print("Growing degree days from germination to emergence (P9): ",P9) 
        # The crop will die if germination has not occurred before a certain period (eg. 40 days)

        EMERGENCE_DATE = ''
        w = weather[weather['DATE']>=GERMINATION_DATE].reset_index(drop=True)
        for i in range(len(w)):
            Tmin = float(w.iloc[i]['TMIN'])
            Tmax = float(w.iloc[i]['TMAX'])
            DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                           Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                           Ttop=params['TT_TEMPERATURE_MAXIMUM'])
            SUMDTT = SUMDTT + DTT

            if (SUMDTT >= P9 or SUMDTT > params['TT_EMERGENCE_LIMIT']):
                EMERGENCE_DATE = w.iloc[i]['DATE']
                CROP_AGE = str(EMERGENCE_DATE - GERMINATION_DATE).replace(' days 00:00:00','')
                DAP = DAP + int(CROP_AGE)
                growstages[f'{ISTAGE}']['date'] = str(EMERGENCE_DATE).split(' ')[0]
                growstages[f'{ISTAGE}']['DOY'] = int(EMERGENCE_DATE.dayofyear)
                growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                growstages[f'{ISTAGE}']['DAP'] = DAP
                #print("Thermal time reached at DAP ", i+1, str(EMERGENCE_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                break

        #print("Emergence date: ", EMERGENCE_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining emergence date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # --------------------------------------------------------------------------------------
    # DETERMINE DURATION OF VEGETATIVE PHASE (END JUVENILE DATE - END OF VEGETATION GROWTH
    # --------------------------------------------------------------------------------------
    ISTAGE = 1
    try: 
        isVernalization = True
        SUMDTT = SUMDTT - P9 
        CUMVD = 0
        TDU = 0
        DF = 0.001

        w = weather[weather['DATE']>=EMERGENCE_DATE].reset_index(drop=True)
        END_JUVENILE_DATE = ''
        for i in range(len(w)):
            Tmin = float(w.iloc[i]['TMIN'])
            Tmax = float(w.iloc[i]['TMAX'])
            DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                           Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                           Ttop=params['TT_TEMPERATURE_MAXIMUM'])
            if (isVernalization is True):
                Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                CUMVD = vernalization(Tcrown, Tmin, Tmax, CUMVD)
                if (CUMVD < params['VREQ']):
                    VF = vernalization_factor(P1V=params['P1V'], dV=CUMVD, ISTAGE=ISTAGE)
                    if (VF < 0.3):
                        TDU = TDU + DTT * min(VF, DF)
                    else:
                        DOY = pd.to_datetime(w.iloc[i]['DATE']).dayofyear
                        TWILEN = day_length(DOY=DOY, lat=params['latitude'], p=params['CIVIL_TWILIGHT'])
                        DF = photoperiod_factor(P1D=params['P1D'], day_length=TWILEN)
                        TDU = TDU + DTT * min(VF, DF)
                    SUMDTT = TDU
                else:
                    isVernalization = False
            else:
                SUMDTT = SUMDTT + DTT

            if (SUMDTT > P9 ): #or SUMDTT > TT_emergence when reached the lower TT
                END_JUVENILE_DATE = w.iloc[i]['DATE']
                CROP_AGE = str(END_JUVENILE_DATE - EMERGENCE_DATE).replace(' days 00:00:00','')
                DAP = DAP + int(CROP_AGE)
                growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                growstages[f'{ISTAGE}']['date'] = str(END_JUVENILE_DATE).split(' ')[0]
                growstages[f'{ISTAGE}']['DOY'] = int(END_JUVENILE_DATE.dayofyear)
                growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                growstages[f'{ISTAGE}']['DAP'] = DAP
                #print("Thermal time reached at DAP ", i+1, str(END_JUVENILE_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                break
            #if (DTT > params['TT_EMERGENCE_LIMIT']): # TT_EMERGENCE_LIMIT = 300,
            #    # The crop will die if germination has not occurred before a certain period (eg. 40 days or 300oC d)
            #    print("The crop died because emergence has not occurred before {} degree-days".format(params['TT_EMERGENCE_LIMIT']))

        #print("End Juvenile date: ", END_JUVENILE_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of juvenile date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # --------------------------------------------------------------------------
    # DETERMINE END VEGETATION DATE - End of Juvenile to End of Vegetative growth
    # --------------------------------------------------------------------------
    ISTAGE = 1 # <- Note: this must continue with 1 as previous stage (Term Spklt = Emergence to End of Juvenile + End of Juvenile to End of Vegetative growth)
    try:
        isVernalization = True
        VF = 1.0
        w = weather[weather['DATE']>=END_JUVENILE_DATE].reset_index(drop=True)
        END_VEGETATION_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                if (isVernalization is True):
                    Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                    CUMVD = vernalization(Tcrown, Tmin, Tmax, CUMVD)
                    if (CUMVD < params['VREQ']):
                        VF = vernalization_factor(P1V=params['P1V'], dV=CUMVD, ISTAGE=ISTAGE)
                        if (VF < 0.3):
                            TDU = TDU + DTT * min(VF, DF)
                        else:
                            DOY = pd.to_datetime(w.iloc[i]['DATE']).dayofyear
                            TWILEN = day_length(DOY=DOY, lat=params['latitude'], p=params['CIVIL_TWILIGHT'])
                            DF = photoperiod_factor(P1D=params['P1D'], day_length=TWILEN)
                            TDU = TDU + DTT * min(VF, DF)
                        SUMDTT = TDU
                    else:
                        isVernalization = False
                else:
                    SUMDTT = SUMDTT + DTT

                # When this reduced thermal time accumulation (TDU) reaches 
                # 400 degree days, Stage 1 development ends
                if (SUMDTT > (params['TT_TDU_LIMIT'] * (params['PHINT'] / 95.0)) ):
                    END_VEGETATION_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_VEGETATION_DATE - END_JUVENILE_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    # Sum of the two phases
                    CROP_AGE_2 = str(END_VEGETATION_DATE - EMERGENCE_DATE).replace(' days 00:00:00','')
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE_2) # Sum of the last two phases
                    growstages[f'{ISTAGE}']['date'] = str(END_VEGETATION_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_VEGETATION_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    #if (verbose is True):
                    #    print("End of Juvenile: Thermal time reached at days duration ", i+1,
                    #          str(END_VEGETATION_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                    break
        else:
            print("Error reading weather data for vegetation phase")

        # print("End of Vegeation Growth ", END_VEGETATION_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of vegetation growth date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE END OF EAR GROWTH - End of Vegetative Growth to End of Ear Grow (End leaf growth)
    #-----------------------------------------------------------------------------------------------
    ISTAGE = 2 # Terminal spikelet initiation to the end of leaf growth - CERES Stage 2
    try:
        SUMDTT = 0.0
        P2 = params['PHINT'] * 3

        w = weather[weather['DATE']>=END_VEGETATION_DATE].reset_index(drop=True)
        END_OF_EAR_GROWTH_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT

                if (SUMDTT >= P2):
                    END_OF_EAR_GROWTH_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_OF_EAR_GROWTH_DATE - END_VEGETATION_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(END_OF_EAR_GROWTH_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_OF_EAR_GROWTH_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(END_OF_EAR_GROWTH_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("End of Ear growth",END_OF_EAR_GROWTH_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of ear growth date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return
    #
    # ----------------------------------------------------------------------------------------------
    # DETERMINE ANTHESIS
    # ----------------------------------------------------------------------------------------------
    # Anthesis date was estimated as occurring 7 d after heading. (based on McMaster and Smika, 1988; McMaster and Wilhelm, 2003; G. S. McMaster, unpubl. data)
    # Here we used 6 days according to IWIN reported anthesis
    ISTAGE = 2.5
    ADAH = params['ADAH']
    CROP_AGE = DAP + ADAH
    ANTHESIS_DATE = END_OF_EAR_GROWTH_DATE + pd.DateOffset(days=ADAH)
    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
    growstages[f'{ISTAGE}']['date'] = str(ANTHESIS_DATE).split(' ')[0]
    growstages[f'{ISTAGE}']['DOY'] = int(ANTHESIS_DATE.dayofyear)
    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1) # TODOs: Esto debe recalcularse
    growstages[f'{ISTAGE}']['DAP'] = DAP + ADAH

    #
    return growstages

determine_emergence_stage(initparams=None, verbose=False) #

Estimate Wheat phenological stages using CERES-Wheat model

Parameters:

Name Type Description Default
initparams dict

A dictionary with initial parameters

None
verbose bool

Display comments during the processes. Default is False

False

Attributes:

Name Type Description
weather object

A table or dataframe with weather data for the site

TT_TBASE float

Base temperature for estimate Thermal time. Default 0.0

TT_TEMPERATURE_OPTIMUM float

Thermal time optimum temperature. Default 26

TT_TEMPERATURE_MAXIMUM float

Thermal time maximum temperature. Default 34

CIVIL_TWILIGHT float

Sun angle with the horizon. eg. p = 6.0 : civil twilight. Default 0.0

HI float

Hardiness Index. Default 0.0

SNOW float

Snow fall. Default 0.0

SDEPTH float

Sowing depth in cm. Default 3.0 cm

GDDE float

Growing degree days per cm seed depth required for emergence, Default 6.2 GDD/cm.

DAYS_GERMIMATION_LIMIT float

Threshold for days to germination. Default 40

TT_EMERGENCE_LIMIT float

Threshold for thermal time to emergence. Default 300

Returns:

Name Type Description
growstages dict

A dictionary with all phenological stages and addtional useful information

Source code in pywheat/pheno/__init__.py
def determine_emergence_stage(initparams=None, verbose=False):
    '''
        Estimate Wheat phenological stages using CERES-Wheat model

        Parameters:
            initparams (dict): A dictionary with initial parameters
            verbose (bool): Display comments during the processes. Default is False

        Attributes:
            weather (object): A table or dataframe with weather data for the site
            TT_TBASE (float): Base temperature for estimate Thermal time. Default 0.0
            TT_TEMPERATURE_OPTIMUM (float): Thermal time optimum temperature. Default 26
            TT_TEMPERATURE_MAXIMUM (float): Thermal time maximum temperature. Default 34
            CIVIL_TWILIGHT (float): Sun angle with the horizon. eg. p = 6.0 : civil twilight. Default 0.0
            HI (float): Hardiness Index. Default 0.0 
            SNOW (float): Snow fall. Default 0.0
            SDEPTH (float): Sowing depth in cm. Default 3.0 cm
            GDDE (float): Growing degree days per cm seed depth required for emergence, Default 6.2 GDD/cm.
            DAYS_GERMIMATION_LIMIT (float): Threshold for days to germination. Default 40
            TT_EMERGENCE_LIMIT (float): Threshold for thermal time to emergence. Default 300

        Returns:
            growstages (dict): A dictionary with all phenological stages and addtional useful information

    '''
    if (initparams is None):
        print("Please check out the input parameters")
        return

    # Initialization of variables 
    params = dict(
        weather = None, # Weather data of the site
        sowing_date = "", # Sowing date in YYYY-MM-DD
        latitude = -99.0, # Latitude of the site
        TT_TBASE = 0.0, # Base Temperature, 2.0 to estimate HI
        TT_TEMPERATURE_OPTIMUM = 26, # Thermal time optimum temperature
        TT_TEMPERATURE_MAXIMUM = 34, # Thermal time maximum temperature
        CIVIL_TWILIGHT = 0.0, # Sun angle with the horizon. eg. p = 6.0 : civil twilight,
        HI = 0.0, # Hardiness Index
        SNOW = 0, # Snow fall
        SDEPTH = 3.0, # Sowing depth in cm
        GDDE = 6.2, # Growing degree days per cm seed depth required for emergence, GDD/cm
        DAYS_GERMIMATION_LIMIT = 40, # threshold for days to germination
        TT_EMERGENCE_LIMIT = 300, # threshold for thermal time to emergence
    )
    if (initparams is not None):
        params = {**params, **initparams}

    if (params['sowing_date'] is None or params['sowing_date']==""):
        print("Sowing date not valid")
        return
    if (params['latitude'] is None or params['latitude']==-99.0):
        print("Latitude of the site not valid")
        return
    if (params['weather'] is None):
        print("Weather data is not available")
        return
    else:
        weather = params['weather']


    growstages = {
            '7': {'istage_old': 'Sowing', 'istage': 'Fallow', 'desc': 'No crop present to Sowing', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '8': {'istage_old': 'Germinate', 'istage': 'Sowing', 'desc': 'Sowing to Germination', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '9': {'istage_old': 'Emergence', 'istage': 'Germinate', 'desc': 'Emergence to End of Juvenile', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''}
    }

    class StageFailed(Exception):
        def __init__(self, m, istage, err):
            self.message = m
            self.istage = istage
            self.err = err
        def __str__(self):
            return self.message + f" Stage ({self.istage}) - " + f"Error: {self.err}"

    # --------------------------------------------------------------------------
    # DETERMINE SOWING DATE
    # --------------------------------------------------------------------------
    ISTAGE = 7
    try:
        SOWING_DATE = pd.to_datetime(str(params['sowing_date']), format='%Y-%m-%d' )
        DOY = pd.to_datetime(SOWING_DATE).dayofyear

        growstages[f'{ISTAGE}']['date'] = str(SOWING_DATE).split(' ')[0]
        growstages[f'{ISTAGE}']['DOY'] = int(DOY)
        growstages[f'{ISTAGE}']['AGE'] = 0
        growstages[f'{ISTAGE}']['SUMDTT'] = 0
        growstages[f'{ISTAGE}']['DAP'] = 0
        #print("Sowing date:", SOWING_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem initializing the determination of phenological stage. Please check your input parameters such as sowing date or latitude of the site", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # --------------------------------------------------------------------------
    # DETERMINE GERMINATION  DATE
    # --------------------------------------------------------------------------
    ISTAGE = 8
    try:
        SUMDTT = 0.0
        #VF = 0.0
        DAP = 0
        ndays = 1 # Seed germination is a rapid process and is assumed to occur in one day
        w = weather[(weather['DATE']==(SOWING_DATE + pd.DateOffset(days=ndays)) )].reset_index(drop=True)
        GERMINATION_DATE = ''
        Tmin = float(w.iloc[ndays-1]['TMIN'])
        Tmax = float(w.iloc[ndays-1]['TMAX'])
        # Thermal time
        DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                       Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                       Ttop=params['TT_TEMPERATURE_MAXIMUM'])
        SUMDTT = SUMDTT + DTT
        GERMINATION_DATE = w.iloc[ndays-1]['DATE']
        CROP_AGE = str(GERMINATION_DATE - SOWING_DATE).replace(' days 00:00:00','')
        DAP = DAP + int(CROP_AGE)
        growstages[f'{ISTAGE}']['date'] = str(GERMINATION_DATE).split(' ')[0]
        growstages[f'{ISTAGE}']['DOY'] = int(GERMINATION_DATE.dayofyear)
        growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
        growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
        growstages[f'{ISTAGE}']['DAP'] = DAP

        #print("Germination date:", GERMINATION_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining germination date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return


    # --------------------------------------------------------------------------
    # DETERMINE SEEDLING EMERGENCE DATE
    # --------------------------------------------------------------------------
    ISTAGE = 9
    try:
        P9 = 40 + params['GDDE'] * params['SDEPTH'] #Default values
        SUMDTT = 0.0
        #print("Growing degree days from germination to emergence (P9): ",P9) 
        # The crop will die if germination has not occurred before a certain period (eg. 40 days)
        w = weather[weather['DATE']>=GERMINATION_DATE].reset_index(drop=True)
        EMERGENCE_DATE = ''
        for i in range(len(w)):
            Tmin = float(w.iloc[i]['TMIN'])
            Tmax = float(w.iloc[i]['TMAX'])
            DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                           Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                           Ttop=params['TT_TEMPERATURE_MAXIMUM'])
            SUMDTT = SUMDTT + DTT

            if (SUMDTT >= P9 or SUMDTT > params['TT_EMERGENCE_LIMIT']):
                EMERGENCE_DATE = w.iloc[i]['DATE']
                CROP_AGE = str(EMERGENCE_DATE - GERMINATION_DATE).replace(' days 00:00:00','')
                DAP = DAP + int(CROP_AGE)
                growstages[f'{ISTAGE}']['date'] = str(EMERGENCE_DATE).split(' ')[0]
                growstages[f'{ISTAGE}']['DOY'] = int(EMERGENCE_DATE.dayofyear)
                growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                growstages[f'{ISTAGE}']['DAP'] = DAP
                #print("Thermal time reached at DAP ", i+1, str(EMERGENCE_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                break

        #print("Emergence date: ", EMERGENCE_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining emergence date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return
    #
    return growstages

determine_heading_stage(initparams=None, verbose=False) #

Estimate Wheat phenological stages using an improved PyWheat model calibrated with IWIN datasets (ESWYT, IDYN, HTWYT and SAWYT nurseries)

Parameters:

Name Type Description Default
initparams dict

A dictionary with initial parameters

None
verbose bool

Display comments during the processes. Default is False

False

Attributes:

Name Type Description
weather object

A table or dataframe with weather data for the site

TT_TBASE float

Base temperature for estimate Thermal time. Default 0.0

TT_TEMPERATURE_OPTIMUM float

Thermal time optimum temperature. Default 26

TT_TEMPERATURE_MAXIMUM float

Thermal time maximum temperature. Default 34

CIVIL_TWILIGHT float

Sun angle with the horizon. eg. p = 6.0 : civil twilight. Default 0.0

HI float

Hardiness Index. Default 0.0

SNOW float

Snow fall. Default 0.0

SDEPTH float

Sowing depth in cm. Default 3.0 cm

GDDE float

Growing degree days per cm seed depth required for emergence, Default 6.2 GDD/cm.

DSGFT float

GDD from End Ear Growth to Start Grain Filling period. Default 200 degree-days

VREQ (float

Vernalization required for max.development rate (VDays). Default 505 degree-days

PHINT float

Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. Default 95.0 degree-days

P1V float

Development genetic coefficients, vernalization. 1 for spring type, 5 for winter type. Default 4.85

P1D float

Development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length). Default 3.675

P5 float

Grain filling degree days. Old value was divided by 10. Default 500 degree-days.

P6 float

Approximate the thermal time from physiological maturity to harvest. Default 250.

DAYS_GERMIMATION_LIMIT float

Threshold for days to germination. Default 40

TT_EMERGENCE_LIMIT int

Threshold for thermal time to emergence. Default 300 degree-days

TT_TDU_LIMIT float

Threshold for thermal development units (TDU). Default 400 degree-days

ADAH int

Number of days after heading. A threshold used for anthesis date after planting. Default is 6 days after heading.

Returns:

Name Type Description
growstages dict

A dictionary with all phenological stages and addtional useful information

Source code in pywheat/pheno/__init__.py
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
def determine_heading_stage(initparams=None, verbose=False):
    '''
        Estimate Wheat phenological stages using an improved PyWheat model calibrated 
        with IWIN datasets (ESWYT, IDYN, HTWYT and SAWYT nurseries)

        Parameters:
            initparams (dict): A dictionary with initial parameters
            verbose (bool): Display comments during the processes. Default is False

        Attributes:
            weather (object): A table or dataframe with weather data for the site
            TT_TBASE (float): Base temperature for estimate Thermal time. Default 0.0
            TT_TEMPERATURE_OPTIMUM (float): Thermal time optimum temperature. Default 26
            TT_TEMPERATURE_MAXIMUM (float): Thermal time maximum temperature. Default 34
            CIVIL_TWILIGHT (float): Sun angle with the horizon. eg. p = 6.0 : civil twilight. Default 0.0
            HI (float): Hardiness Index. Default 0.0 
            SNOW (float): Snow fall. Default 0.0
            SDEPTH (float): Sowing depth in cm. Default 3.0 cm
            GDDE (float): Growing degree days per cm seed depth required for emergence, Default 6.2 GDD/cm.
            DSGFT (float): GDD from End Ear Growth to Start Grain Filling period. Default 200 degree-days
            VREQ  (float): Vernalization required for max.development rate (VDays). Default 505 degree-days
            PHINT (float): Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. Default 95.0 degree-days
            P1V (float): Development genetic coefficients, vernalization. 1 for spring type, 5 for winter type. Default 4.85
            P1D (float): Development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length). Default 3.675
            P5 (float): Grain filling degree days. Old value was divided by 10. Default 500 degree-days.
            P6 (float): Approximate the thermal time from physiological maturity to harvest. Default 250.
            DAYS_GERMIMATION_LIMIT (float): Threshold for days to germination. Default 40
            TT_EMERGENCE_LIMIT (int): Threshold for thermal time to emergence. Default 300 degree-days
            TT_TDU_LIMIT (float): Threshold for thermal development units (TDU). Default 400  degree-days
            ADAH (int): Number of days after heading. A threshold used for anthesis date after planting. Default is 6 days after heading.

        Returns:
            growstages (dict): A dictionary with all phenological stages and addtional useful information

    '''
    if (initparams is None):
        print("Please check out the input parameters")
        return

    # Initialization of variables 
    params = dict(
        weather = None, # Weather data of the site
        sowing_date = "", # Sowing date in YYYY-MM-DD
        latitude = -90.0, # Latitude of the site
        longitude = -180.0, # Longitude of the site
        genotype = "", # Name of the grand parent in IWIN pedigrees database 
        TT_TBASE = 0.0, # Base Temperature, 2.0 to estimate HI
        TT_TEMPERATURE_OPTIMUM = 26, # Thermal time optimum temperature
        TT_TEMPERATURE_MAXIMUM = 34, # Thermal time maximum temperature
        CIVIL_TWILIGHT = 0.0, # Sun angle with the horizon. eg. p = 6.0 : civil twilight,
        HI = 0.0, # Hardiness Index
        SNOW = 0, # Snow fall
        SDEPTH = 3.0, # Sowing depth in cm
        GDDE = 6.2, # Growing degree days per cm seed depth required for emergence, GDD/cm
        DSGFT = 200, # GDD from End Ear Growth to Start Grain Filling period
        VREQ  = 505.0, # Vernalization required for max.development rate (VDays)
        PHINT = 95.0, # Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. 
        P1V = 1.0, # development genetic coefficients, vernalization. 1 for spring type, 5 for winter type
        P1D = 3.675, # development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length)
        P5 = 500, # grain filling degree days eg. 500 degree-days. Old value was divided by 10.
        P6 = 250, # approximate the thermal time from physiological maturity to harvest
        DAYS_GERMIMATION_LIMIT = 40, # threshold for days to germination
        TT_EMERGENCE_LIMIT = 300, # threshold for thermal time to emergence
        TT_TDU_LIMIT = 400, # threshold for thermal development units (TDU)
        ADAH = 6, # threshold for anthesis date after planting. This is a 6 days after heading.
    )
    if (initparams is not None):
        params = {**params, **initparams}

    # Validate
    if (params['sowing_date']=="" or params['sowing_date'] is None):
        print("Sowing date not defined")
        return
    if (params['latitude']==-90.0 or params['latitude'] is None):
        print("Problem with location of the site. Check the geographic coordinates.")
        return
    if (params['weather'] is None):
        print("Weather data is not available")
        return
    else:
        weather = params['weather']

    # ---------------------
    # GDD limits
    # ---------------------
    #P2 = params['PHINT'] * 3
    #P3 = params['PHINT'] * 2
    #P4 = params['DSGFT'] #200 # APSIM-Wheat = 120 # GDD from End Ear Growth to Start Grain Filling period
    #P5 = params['P5'] #430 + params['P5'] * 20
    #P6 = params['P5'] #250
    #P9 = 40 + params['GDDE'] * params['SDEPTH'] 

    growstages = {
            '7': {'istage_old': 'Sowing', 'istage': 'Fallow', 'desc': 'No crop present to Sowing', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '8': {'istage_old': 'Germinate', 'istage': 'Sowing', 'desc': 'Sowing to Germination', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '9': {'istage_old': 'Emergence', 'istage': 'Germinate', 'desc': 'Emergence to End of Juvenile', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '1': {'istage_old': 'Term Spklt', 'istage': 'Emergence', 'desc': 'Emergence to End of Juvenile', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '2': {'istage_old': 'End Veg', 'istage': 'End Juveni', 'desc': 'End of Juvenile to End of Vegetative growth', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''}
    }

    class StageFailed(Exception):
        def __init__(self, m, istage, err):
            self.message = m
            self.istage = istage
            self.err = err
        def __str__(self):
            return self.message + f" Stage ({self.istage}) - " + f"Error: {self.err}"

    # --------------------------------------------------------------------------
    # DETERMINE SOWING DATE
    # --------------------------------------------------------------------------
    ISTAGE = 7
    try:
        SOWING_DATE = pd.to_datetime(str(params['sowing_date']), format='%Y-%m-%d' )
        DOY = pd.to_datetime(SOWING_DATE).dayofyear

        growstages[f'{ISTAGE}']['date'] = str(SOWING_DATE).split(' ')[0]
        growstages[f'{ISTAGE}']['DOY'] = int(DOY)
        growstages[f'{ISTAGE}']['AGE'] = 0
        growstages[f'{ISTAGE}']['SUMDTT'] = 0
        growstages[f'{ISTAGE}']['DAP'] = 0
        #print("Sowing date:", SOWING_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem initializing the determination of phenological stage. Please check your input parameters such as sowing date or latitude of the site", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return


    # --------------------------------------------------------------------------
    # DETERMINE GERMINATION  DATE
    # --------------------------------------------------------------------------
    ISTAGE = 8
    try:
        SUMDTT = 0.0
        #VF = 0.0
        DAP = 0
        ndays = 1 # Seed germination is a rapid process and is assumed to occur in one day
        w = weather[(weather['DATE']==(SOWING_DATE + pd.DateOffset(days=ndays)) )].reset_index(drop=True)
        GERMINATION_DATE = ''
        Tmin = float(w.iloc[ndays-1]['TMIN'])
        Tmax = float(w.iloc[ndays-1]['TMAX'])
        # Thermal time
        DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                       Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                       Ttop=params['TT_TEMPERATURE_MAXIMUM'])
        SUMDTT = SUMDTT + DTT
        GERMINATION_DATE = w.iloc[ndays-1]['DATE']
        CROP_AGE = str(GERMINATION_DATE - SOWING_DATE).replace(' days 00:00:00','')
        DAP = DAP + int(CROP_AGE)
        growstages[f'{ISTAGE}']['date'] = str(GERMINATION_DATE).split(' ')[0]
        growstages[f'{ISTAGE}']['DOY'] = int(GERMINATION_DATE.dayofyear)
        growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
        growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
        growstages[f'{ISTAGE}']['DAP'] = DAP

        #print("Germination date:", GERMINATION_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining germination date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return


    # --------------------------------------------------------------------------
    # DETERMINE SEEDLING EMERGENCE DATE
    # --------------------------------------------------------------------------
    ISTAGE = 9
    P9 = 40 + params['GDDE'] * params['SDEPTH']
    try:
        SUMDTT = 0.0
        #print("Growing degree days from germination to emergence (P9): ",P9) 
        # The crop will die if germination has not occurred before a certain period (eg. 40 days)

        EMERGENCE_DATE = ''
        w = weather[weather['DATE']>=GERMINATION_DATE].reset_index(drop=True)
        for i in range(len(w)):
            Tmin = float(w.iloc[i]['TMIN'])
            Tmax = float(w.iloc[i]['TMAX'])
            DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                           Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                           Ttop=params['TT_TEMPERATURE_MAXIMUM'])
            SUMDTT = SUMDTT + DTT

            if (SUMDTT >= P9 or SUMDTT > params['TT_EMERGENCE_LIMIT']):
                EMERGENCE_DATE = w.iloc[i]['DATE']
                CROP_AGE = str(EMERGENCE_DATE - GERMINATION_DATE).replace(' days 00:00:00','')
                DAP = DAP + int(CROP_AGE)
                growstages[f'{ISTAGE}']['date'] = str(EMERGENCE_DATE).split(' ')[0]
                growstages[f'{ISTAGE}']['DOY'] = int(EMERGENCE_DATE.dayofyear)
                growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                growstages[f'{ISTAGE}']['DAP'] = DAP
                #print("Thermal time reached at DAP ", i+1, str(EMERGENCE_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                break

        #print("Emergence date: ", EMERGENCE_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining emergence date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # --------------------------------------------------------------------------------------
    # DETERMINE DURATION OF VEGETATIVE PHASE (END JUVENILE DATE - END OF VEGETATION GROWTH
    # --------------------------------------------------------------------------------------
    ISTAGE = 1
    try: 
        isVernalization = True
        SUMDTT = SUMDTT - P9 
        CUMVD = 0
        TDU = 0
        DF = 0.001

        w = weather[weather['DATE']>=EMERGENCE_DATE].reset_index(drop=True)
        END_JUVENILE_DATE = ''
        for i in range(len(w)):
            Tmin = float(w.iloc[i]['TMIN'])
            Tmax = float(w.iloc[i]['TMAX'])
            DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                           Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                           Ttop=params['TT_TEMPERATURE_MAXIMUM'])
            if (isVernalization is True):
                Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                CUMVD = vernalization(Tcrown, Tmin, Tmax, CUMVD)
                if (CUMVD < params['VREQ']):
                    VF = vernalization_factor(P1V=params['P1V'], dV=CUMVD, ISTAGE=ISTAGE)
                    if (VF < 0.3):
                        TDU = TDU + DTT * min(VF, DF)
                    else:
                        DOY = pd.to_datetime(w.iloc[i]['DATE']).dayofyear
                        TWILEN = day_length(DOY=DOY, lat=params['latitude'], p=params['CIVIL_TWILIGHT'])
                        DF = photoperiod_factor(P1D=params['P1D'], day_length=TWILEN)
                        TDU = TDU + DTT * min(VF, DF)
                    SUMDTT = TDU
                else:
                    isVernalization = False
            else:
                SUMDTT = SUMDTT + DTT

            if (SUMDTT > P9 ): #or SUMDTT > TT_emergence when reached the lower TT
                END_JUVENILE_DATE = w.iloc[i]['DATE']
                CROP_AGE = str(END_JUVENILE_DATE - EMERGENCE_DATE).replace(' days 00:00:00','')
                DAP = DAP + int(CROP_AGE)
                growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                growstages[f'{ISTAGE}']['date'] = str(END_JUVENILE_DATE).split(' ')[0]
                growstages[f'{ISTAGE}']['DOY'] = int(END_JUVENILE_DATE.dayofyear)
                growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                growstages[f'{ISTAGE}']['DAP'] = DAP
                #print("Thermal time reached at DAP ", i+1, str(END_JUVENILE_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                break
            #if (DTT > params['TT_EMERGENCE_LIMIT']): # TT_EMERGENCE_LIMIT = 300,
            #    # The crop will die if germination has not occurred before a certain period (eg. 40 days or 300oC d)
            #    print("The crop died because emergence has not occurred before {} degree-days".format(params['TT_EMERGENCE_LIMIT']))

        #print("End Juvenile date: ", END_JUVENILE_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of juvenile date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # --------------------------------------------------------------------------
    # DETERMINE END VEGETATION DATE - End of Juvenile to End of Vegetative growth
    # --------------------------------------------------------------------------
    ISTAGE = 1 # <- Note: this must continue with 1 as previous stage (Term Spklt = Emergence to End of Juvenile + End of Juvenile to End of Vegetative growth)
    try:
        isVernalization = True
        VF = 1.0
        w = weather[weather['DATE']>=END_JUVENILE_DATE].reset_index(drop=True)
        END_VEGETATION_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                if (isVernalization is True):
                    Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                    CUMVD = vernalization(Tcrown, Tmin, Tmax, CUMVD)
                    if (CUMVD < params['VREQ']):
                        VF = vernalization_factor(P1V=params['P1V'], dV=CUMVD, ISTAGE=ISTAGE)
                        if (VF < 0.3):
                            TDU = TDU + DTT * min(VF, DF)
                        else:
                            DOY = pd.to_datetime(w.iloc[i]['DATE']).dayofyear
                            TWILEN = day_length(DOY=DOY, lat=params['latitude'], p=params['CIVIL_TWILIGHT'])
                            DF = photoperiod_factor(P1D=params['P1D'], day_length=TWILEN)
                            TDU = TDU + DTT * min(VF, DF)
                        SUMDTT = TDU
                    else:
                        isVernalization = False
                else:
                    SUMDTT = SUMDTT + DTT

                # When this reduced thermal time accumulation (TDU) reaches 
                # 400 degree days, Stage 1 development ends
                if (SUMDTT > (params['TT_TDU_LIMIT'] * (params['PHINT'] / 95.0)) ):
                    END_VEGETATION_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_VEGETATION_DATE - END_JUVENILE_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    # Sum of the two phases
                    CROP_AGE_2 = str(END_VEGETATION_DATE - EMERGENCE_DATE).replace(' days 00:00:00','')
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE_2) # Sum of the last two phases
                    growstages[f'{ISTAGE}']['date'] = str(END_VEGETATION_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_VEGETATION_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    #if (verbose is True):
                    #    print("End of Juvenile: Thermal time reached at days duration ", i+1,
                    #          str(END_VEGETATION_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                    break
        else:
            print("Error reading weather data for vegetation phase")

        # print("End of Vegeation Growth ", END_VEGETATION_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of vegetation growth date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE END OF EAR GROWTH - End of Vegetative Growth to End of Ear Grow (End leaf growth)
    #-----------------------------------------------------------------------------------------------
    ISTAGE = 2 # Terminal spikelet initiation to the end of leaf growth - CERES Stage 2
    try:
        SUMDTT = 0.0
        P2 = params['PHINT'] * 3

        w = weather[weather['DATE']>=END_VEGETATION_DATE].reset_index(drop=True)
        END_OF_EAR_GROWTH_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT

                if (SUMDTT >= P2):
                    END_OF_EAR_GROWTH_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_OF_EAR_GROWTH_DATE - END_VEGETATION_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(END_OF_EAR_GROWTH_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_OF_EAR_GROWTH_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(END_OF_EAR_GROWTH_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("End of Ear growth",END_OF_EAR_GROWTH_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of ear growth date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return
    #
    return growstages

determine_maturity_stage(initparams=None, verbose=False) #

Estimate Wheat phenological stages using an improved PyWheat model calibrated with IWIN datasets (ESWYT, IDYN, HTWYT and SAWYT nurseries)

Parameters:

Name Type Description Default
initparams dict

A dictionary with initial parameters

None
verbose bool

Display comments during the processes. Default is False

False

Attributes:

Name Type Description
weather object

A table or dataframe with weather data for the site

TT_TBASE float

Base temperature for estimate Thermal time. Default 0.0

TT_TEMPERATURE_OPTIMUM float

Thermal time optimum temperature. Default 26

TT_TEMPERATURE_MAXIMUM float

Thermal time maximum temperature. Default 34

CIVIL_TWILIGHT float

Sun angle with the horizon. eg. p = 6.0 : civil twilight. Default 0.0

HI float

Hardiness Index. Default 0.0

SNOW float

Snow fall. Default 0.0

SDEPTH float

Sowing depth in cm. Default 3.0 cm

GDDE float

Growing degree days per cm seed depth required for emergence, Default 6.2 GDD/cm.

DSGFT float

GDD from End Ear Growth to Start Grain Filling period. Default 200 degree-days

VREQ (float

Vernalization required for max.development rate (VDays). Default 505 degree-days

PHINT float

Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. Default 95.0 degree-days

P1V float

Development genetic coefficients, vernalization. 1 for spring type, 5 for winter type. Default 4.85

P1D float

Development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length). Default 3.675

P5 float

Grain filling degree days. Old value was divided by 10. Default 500 degree-days.

P6 float

Approximate the thermal time from physiological maturity to harvest. Default 250.

DAYS_GERMIMATION_LIMIT float

Threshold for days to germination. Default 40

TT_EMERGENCE_LIMIT int

Threshold for thermal time to emergence. Default 300 degree-days

TT_TDU_LIMIT float

Threshold for thermal development units (TDU). Default 400 degree-days

ADAH int

Number of days after heading. A threshold used for anthesis date after planting. Default is 6 days after heading.

Returns:

Name Type Description
growstages dict

A dictionary with all phenological stages and addtional useful information

Source code in pywheat/pheno/__init__.py
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
def determine_maturity_stage(initparams=None, verbose=False):
    '''
        Estimate Wheat phenological stages using an improved PyWheat model calibrated 
        with IWIN datasets (ESWYT, IDYN, HTWYT and SAWYT nurseries)

        Parameters:
            initparams (dict): A dictionary with initial parameters
            verbose (bool): Display comments during the processes. Default is False

        Attributes:
            weather (object): A table or dataframe with weather data for the site
            TT_TBASE (float): Base temperature for estimate Thermal time. Default 0.0
            TT_TEMPERATURE_OPTIMUM (float): Thermal time optimum temperature. Default 26
            TT_TEMPERATURE_MAXIMUM (float): Thermal time maximum temperature. Default 34
            CIVIL_TWILIGHT (float): Sun angle with the horizon. eg. p = 6.0 : civil twilight. Default 0.0
            HI (float): Hardiness Index. Default 0.0 
            SNOW (float): Snow fall. Default 0.0
            SDEPTH (float): Sowing depth in cm. Default 3.0 cm
            GDDE (float): Growing degree days per cm seed depth required for emergence, Default 6.2 GDD/cm.
            DSGFT (float): GDD from End Ear Growth to Start Grain Filling period. Default 200 degree-days
            VREQ  (float): Vernalization required for max.development rate (VDays). Default 505 degree-days
            PHINT (float): Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. Default 95.0 degree-days
            P1V (float): Development genetic coefficients, vernalization. 1 for spring type, 5 for winter type. Default 4.85
            P1D (float): Development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length). Default 3.675
            P5 (float): Grain filling degree days. Old value was divided by 10. Default 500 degree-days.
            P6 (float): Approximate the thermal time from physiological maturity to harvest. Default 250.
            DAYS_GERMIMATION_LIMIT (float): Threshold for days to germination. Default 40
            TT_EMERGENCE_LIMIT (int): Threshold for thermal time to emergence. Default 300 degree-days
            TT_TDU_LIMIT (float): Threshold for thermal development units (TDU). Default 400  degree-days
            ADAH (int): Number of days after heading. A threshold used for anthesis date after planting. Default is 6 days after heading.

        Returns:
            growstages (dict): A dictionary with all phenological stages and addtional useful information

    '''
    if (initparams is None):
        print("Please check out the input parameters")
        return

    # Initialization of variables 
    params = dict(
        weather = None, # Weather data of the site
        sowing_date = "", # Sowing date in YYYY-MM-DD
        latitude = -90.0, # Latitude of the site
        longitude = -180.0, # Longitude of the site
        genotype = "", # Name of the grand parent in IWIN pedigrees database 
        TT_TBASE = 0.0, # Base Temperature, 2.0 to estimate HI
        TT_TEMPERATURE_OPTIMUM = 26, # Thermal time optimum temperature
        TT_TEMPERATURE_MAXIMUM = 34, # Thermal time maximum temperature
        CIVIL_TWILIGHT = 0.0, # Sun angle with the horizon. eg. p = 6.0 : civil twilight,
        HI = 0.0, # Hardiness Index
        SNOW = 0, # Snow fall
        SDEPTH = 3.0, # Sowing depth in cm
        GDDE = 6.2, # Growing degree days per cm seed depth required for emergence, GDD/cm
        DSGFT = 200, # GDD from End Ear Growth to Start Grain Filling period
        VREQ  = 505.0, # Vernalization required for max.development rate (VDays)
        PHINT = 95.0, # Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. 
        P1V = 1.0, # development genetic coefficients, vernalization. 1 for spring type, 5 for winter type
        P1D = 3.675, # development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length)
        P5 = 500, # grain filling degree days eg. 500 degree-days. Old value was divided by 10.
        P6 = 250, # approximate the thermal time from physiological maturity to harvest
        DAYS_GERMIMATION_LIMIT = 40, # threshold for days to germination
        TT_EMERGENCE_LIMIT = 300, # threshold for thermal time to emergence
        TT_TDU_LIMIT = 400, # threshold for thermal development units (TDU)
        ADAH = 6, # threshold for anthesis date after planting. This is a 6 days after heading.
    )
    if (initparams is not None):
        params = {**params, **initparams}

    # Validate
    if (params['sowing_date']=="" or params['sowing_date'] is None):
        print("Sowing date not defined")
        return
    if (params['latitude']==-90.0 or params['latitude'] is None):
        print("Problem with location of the site. Check the geographic coordinates.")
        return
    if (params['weather'] is None):
        print("Weather data is not available")
        return
    else:
        weather = params['weather']

    # ---------------------
    # GDD limits
    # ---------------------
    #P3 = params['PHINT'] * 2
    #P4 = params['DSGFT'] #200 # APSIM-Wheat = 120 # GDD from End Ear Growth to Start Grain Filling period

    growstages = {
            '7': {'istage_old': 'Sowing', 'istage': 'Fallow', 'desc': 'No crop present to Sowing', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '8': {'istage_old': 'Germinate', 'istage': 'Sowing', 'desc': 'Sowing to Germination', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '9': {'istage_old': 'Emergence', 'istage': 'Germinate', 'desc': 'Emergence to End of Juvenile', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '1': {'istage_old': 'Term Spklt', 'istage': 'Emergence', 'desc': 'Emergence to End of Juvenile', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '2': {'istage_old': 'End Veg', 'istage': 'End Juveni', 'desc': 'End of Juvenile to End of Vegetative growth', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '2.5': {'istage_old': 'Anthesis', 'istage': 'Anthesis', 'desc': 'Anthesis', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '3': {'istage_old': 'End Ear Gr', 'istage': 'End Veg', 'desc': 'End of Vegetative Growth to End of Ear Grow', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '4': {'istage_old': 'Beg Gr Fil', 'istage': 'End Ear Gr', 'desc': 'End of Ear Growth to Start of Grain Filling', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '5': {'istage_old': 'End Gr Fil', 'istage': 'Beg Gr Fil', 'desc': 'Start of Grain Filling to Maturity', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            #'6': {'istage_old': 'Harvest', 'istage': 'Maturity', 'desc': 'End Gr Fil', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''}
    }

    class StageFailed(Exception):
        def __init__(self, m, istage, err):
            self.message = m
            self.istage = istage
            self.err = err
        def __str__(self):
            return self.message + f" Stage ({self.istage}) - " + f"Error: {self.err}"

    # --------------------------------------------------------------------------
    # DETERMINE SOWING DATE
    # --------------------------------------------------------------------------
    ISTAGE = 7
    try:
        SOWING_DATE = pd.to_datetime(str(params['sowing_date']), format='%Y-%m-%d' )
        DOY = pd.to_datetime(SOWING_DATE).dayofyear

        growstages[f'{ISTAGE}']['date'] = str(SOWING_DATE).split(' ')[0]
        growstages[f'{ISTAGE}']['DOY'] = int(DOY)
        growstages[f'{ISTAGE}']['AGE'] = 0
        growstages[f'{ISTAGE}']['SUMDTT'] = 0
        growstages[f'{ISTAGE}']['DAP'] = 0
        #print("Sowing date:", SOWING_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem initializing the determination of phenological stage. Please check your input parameters such as sowing date or latitude of the site", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return


    # --------------------------------------------------------------------------
    # DETERMINE GERMINATION  DATE
    # --------------------------------------------------------------------------
    ISTAGE = 8
    try:
        SUMDTT = 0.0
        #VF = 0.0
        DAP = 0
        ndays = 1 # Seed germination is a rapid process and is assumed to occur in one day
        w = weather[(weather['DATE']==(SOWING_DATE + pd.DateOffset(days=ndays)) )].reset_index(drop=True)
        GERMINATION_DATE = ''
        Tmin = float(w.iloc[ndays-1]['TMIN'])
        Tmax = float(w.iloc[ndays-1]['TMAX'])
        # Thermal time
        DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                       Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                       Ttop=params['TT_TEMPERATURE_MAXIMUM'])
        SUMDTT = SUMDTT + DTT
        GERMINATION_DATE = w.iloc[ndays-1]['DATE']
        CROP_AGE = str(GERMINATION_DATE - SOWING_DATE).replace(' days 00:00:00','')
        DAP = DAP + int(CROP_AGE)
        growstages[f'{ISTAGE}']['date'] = str(GERMINATION_DATE).split(' ')[0]
        growstages[f'{ISTAGE}']['DOY'] = int(GERMINATION_DATE.dayofyear)
        growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
        growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
        growstages[f'{ISTAGE}']['DAP'] = DAP

        #print("Germination date:", GERMINATION_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining germination date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return


    # --------------------------------------------------------------------------
    # DETERMINE SEEDLING EMERGENCE DATE
    # --------------------------------------------------------------------------
    ISTAGE = 9
    P9 = 40 + params['GDDE'] * params['SDEPTH']
    try:
        SUMDTT = 0.0
        #print("Growing degree days from germination to emergence (P9): ",P9) 
        # The crop will die if germination has not occurred before a certain period (eg. 40 days)

        EMERGENCE_DATE = ''
        w = weather[weather['DATE']>=GERMINATION_DATE].reset_index(drop=True)
        for i in range(len(w)):
            Tmin = float(w.iloc[i]['TMIN'])
            Tmax = float(w.iloc[i]['TMAX'])
            DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                           Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                           Ttop=params['TT_TEMPERATURE_MAXIMUM'])
            SUMDTT = SUMDTT + DTT

            if (SUMDTT >= P9 or SUMDTT > params['TT_EMERGENCE_LIMIT']):
                EMERGENCE_DATE = w.iloc[i]['DATE']
                CROP_AGE = str(EMERGENCE_DATE - GERMINATION_DATE).replace(' days 00:00:00','')
                DAP = DAP + int(CROP_AGE)
                growstages[f'{ISTAGE}']['date'] = str(EMERGENCE_DATE).split(' ')[0]
                growstages[f'{ISTAGE}']['DOY'] = int(EMERGENCE_DATE.dayofyear)
                growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                growstages[f'{ISTAGE}']['DAP'] = DAP
                #print("Thermal time reached at DAP ", i+1, str(EMERGENCE_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                break

        #print("Emergence date: ", EMERGENCE_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining emergence date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # --------------------------------------------------------------------------------------
    # DETERMINE DURATION OF VEGETATIVE PHASE (END JUVENILE DATE - END OF VEGETATION GROWTH
    # --------------------------------------------------------------------------------------
    ISTAGE = 1
    try: 
        isVernalization = True
        SUMDTT = SUMDTT - P9 
        CUMVD = 0
        TDU = 0
        DF = 0.001

        w = weather[weather['DATE']>=EMERGENCE_DATE].reset_index(drop=True)
        END_JUVENILE_DATE = ''
        for i in range(len(w)):
            Tmin = float(w.iloc[i]['TMIN'])
            Tmax = float(w.iloc[i]['TMAX'])
            DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                           Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                           Ttop=params['TT_TEMPERATURE_MAXIMUM'])
            if (isVernalization is True):
                Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                CUMVD = vernalization(Tcrown, Tmin, Tmax, CUMVD)
                if (CUMVD < params['VREQ']):
                    VF = vernalization_factor(P1V=params['P1V'], dV=CUMVD, ISTAGE=ISTAGE)
                    if (VF < 0.3):
                        TDU = TDU + DTT * min(VF, DF)
                    else:
                        DOY = pd.to_datetime(w.iloc[i]['DATE']).dayofyear
                        TWILEN = day_length(DOY=DOY, lat=params['latitude'], p=params['CIVIL_TWILIGHT'])
                        DF = photoperiod_factor(P1D=params['P1D'], day_length=TWILEN)
                        TDU = TDU + DTT * min(VF, DF)
                    SUMDTT = TDU
                else:
                    isVernalization = False
            else:
                SUMDTT = SUMDTT + DTT

            if (SUMDTT > P9 ): #or SUMDTT > TT_emergence when reached the lower TT
                END_JUVENILE_DATE = w.iloc[i]['DATE']
                CROP_AGE = str(END_JUVENILE_DATE - EMERGENCE_DATE).replace(' days 00:00:00','')
                DAP = DAP + int(CROP_AGE)
                growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                growstages[f'{ISTAGE}']['date'] = str(END_JUVENILE_DATE).split(' ')[0]
                growstages[f'{ISTAGE}']['DOY'] = int(END_JUVENILE_DATE.dayofyear)
                growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                growstages[f'{ISTAGE}']['DAP'] = DAP
                #print("Thermal time reached at DAP ", i+1, str(END_JUVENILE_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                break
            #if (DTT > params['TT_EMERGENCE_LIMIT']): # TT_EMERGENCE_LIMIT = 300,
            #    # The crop will die if germination has not occurred before a certain period (eg. 40 days or 300oC d)
            #    print("The crop died because emergence has not occurred before {} degree-days".format(params['TT_EMERGENCE_LIMIT']))

        #print("End Juvenile date: ", END_JUVENILE_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of juvenile date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # --------------------------------------------------------------------------
    # DETERMINE END VEGETATION DATE - End of Juvenile to End of Vegetative growth
    # --------------------------------------------------------------------------
    ISTAGE = 1 # <- Note: this must continue with 1 as previous stage (Term Spklt = Emergence to End of Juvenile + End of Juvenile to End of Vegetative growth)
    try:
        isVernalization = True
        VF = 1.0
        w = weather[weather['DATE']>=END_JUVENILE_DATE].reset_index(drop=True)
        END_VEGETATION_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                if (isVernalization is True):
                    Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                    CUMVD = vernalization(Tcrown, Tmin, Tmax, CUMVD)
                    if (CUMVD < params['VREQ']):
                        VF = vernalization_factor(P1V=params['P1V'], dV=CUMVD, ISTAGE=ISTAGE)
                        if (VF < 0.3):
                            TDU = TDU + DTT * min(VF, DF)
                        else:
                            DOY = pd.to_datetime(w.iloc[i]['DATE']).dayofyear
                            TWILEN = day_length(DOY=DOY, lat=params['latitude'], p=params['CIVIL_TWILIGHT'])
                            DF = photoperiod_factor(P1D=params['P1D'], day_length=TWILEN)
                            TDU = TDU + DTT * min(VF, DF)
                        SUMDTT = TDU
                    else:
                        isVernalization = False
                else:
                    SUMDTT = SUMDTT + DTT

                # When this reduced thermal time accumulation (TDU) reaches 
                # 400 degree days, Stage 1 development ends
                if (SUMDTT > (params['TT_TDU_LIMIT'] * (params['PHINT'] / 95.0)) ):
                    END_VEGETATION_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_VEGETATION_DATE - END_JUVENILE_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    # Sum of the two phases
                    CROP_AGE_2 = str(END_VEGETATION_DATE - EMERGENCE_DATE).replace(' days 00:00:00','')
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE_2) # Sum of the last two phases
                    growstages[f'{ISTAGE}']['date'] = str(END_VEGETATION_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_VEGETATION_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    #if (verbose is True):
                    #    print("End of Juvenile: Thermal time reached at days duration ", i+1,
                    #          str(END_VEGETATION_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                    break
        else:
            print("Error reading weather data for vegetation phase")

        # print("End of Vegeation Growth ", END_VEGETATION_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of vegetation growth date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE END OF EAR GROWTH - End of Vegetative Growth to End of Ear Grow (End leaf growth)
    #-----------------------------------------------------------------------------------------------
    ISTAGE = 2 # Terminal spikelet initiation to the end of leaf growth - CERES Stage 2
    try:
        SUMDTT = 0.0
        P2 = params['PHINT'] * 3

        w = weather[weather['DATE']>=END_VEGETATION_DATE].reset_index(drop=True)
        END_OF_EAR_GROWTH_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT

                if (SUMDTT >= P2):
                    END_OF_EAR_GROWTH_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_OF_EAR_GROWTH_DATE - END_VEGETATION_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(END_OF_EAR_GROWTH_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_OF_EAR_GROWTH_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(END_OF_EAR_GROWTH_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("End of Ear growth",END_OF_EAR_GROWTH_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of ear growth date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return
    #
    # ----------------------------------------------------------------------------------------------
    # DETERMINE ANTHESIS
    # ----------------------------------------------------------------------------------------------
    # Anthesis date was estimated as occurring 7 d after heading. (based on McMaster and Smika, 1988; McMaster and Wilhelm, 2003; G. S. McMaster, unpubl. data)
    # Here we used 6 days according to IWIN reported anthesis
    ISTAGE = 2.5
    ADAH = params['ADAH']
    CROP_AGE = DAP + ADAH
    ANTHESIS_DATE = END_OF_EAR_GROWTH_DATE + pd.DateOffset(days=ADAH)
    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
    growstages[f'{ISTAGE}']['date'] = str(ANTHESIS_DATE).split(' ')[0]
    growstages[f'{ISTAGE}']['DOY'] = int(ANTHESIS_DATE.dayofyear)
    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1) # TODOs: Esto debe recalcularse
    growstages[f'{ISTAGE}']['DAP'] = DAP + ADAH
    #

    # ----------------------------------------------------------------------------------------------
    # DETERMINE END OF PANNICLE GROWTH - End pannicle growth - End of Ear Growth to Start of Grain Filling
    # ----------------------------------------------------------------------------------------------
    ISTAGE = 3 # Preanthesis ear growth - CERES Stage 3.
    try:
        SUMDTT = 0.0 #SUMDTT - P2
        P3 = params['PHINT'] * 2
        #TBASE=0.0

        w = weather[weather['DATE']>END_OF_EAR_GROWTH_DATE].reset_index(drop=True)
        END_OF_PANNICLE_GROWTH_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT

                if (SUMDTT >= P3):
                    END_OF_PANNICLE_GROWTH_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_OF_PANNICLE_GROWTH_DATE - END_OF_EAR_GROWTH_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(END_OF_PANNICLE_GROWTH_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_OF_PANNICLE_GROWTH_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    growstages[f'{ISTAGE}']['status'] = 1
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(END_OF_PANNICLE_GROWTH_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("End of Pre-Anthesis Ear growth",END_OF_PANNICLE_GROWTH_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of pre-anthesis earh growth date (end of pannicle growth date).", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE BEGIN GRAIN FILLING - Grain fill - Start of Grain Filling to Maturity
    # ----------------------------------------------------------------------------------------------
    ISTAGE = 4 # Preanthesis ear growth to the beginning of grain filling - CERES Stage 4.
    try: 
        P4 = params['DSGFT'] #200 GDD # APSIM-Wheat = 120
        SUMDTT = 0.0 #SUMDTT - P3

        w = weather[weather['DATE']>=END_OF_PANNICLE_GROWTH_DATE].reset_index(drop=True)
        BEGIN_GRAIN_FILLING_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT
                if (SUMDTT >= P4):
                    BEGIN_GRAIN_FILLING_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(BEGIN_GRAIN_FILLING_DATE - END_OF_PANNICLE_GROWTH_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(BEGIN_GRAIN_FILLING_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(BEGIN_GRAIN_FILLING_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    growstages[f'{ISTAGE}']['status'] = 1
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(BEGIN_GRAIN_FILLING_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("Begining of Grain fill",BEGIN_GRAIN_FILLING_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining begin of grain fill date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE END GRAIN FILLING - Maturity
    # ----------------------------------------------------------------------------------------------
    ISTAGE = 5
    try:
        SUMDTT = 0.0 #SUMDTT - P4
        #P5 = 430 + params['P5'] * 20 # P5 = (0.05 X TT_Maturity) - 21.5. ~500 degree-days
        P5 = params['P5'] # 400 + 5.0 * 20  

        w = weather[weather['DATE']>=BEGIN_GRAIN_FILLING_DATE].reset_index(drop=True)
        END_GRAIN_FILLING_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT
                if (SUMDTT >= P5):
                    END_GRAIN_FILLING_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_GRAIN_FILLING_DATE - BEGIN_GRAIN_FILLING_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(END_GRAIN_FILLING_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_GRAIN_FILLING_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    growstages[f'{ISTAGE}']['status'] = 1
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(END_GRAIN_FILLING_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("End of Grain filling",END_GRAIN_FILLING_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of grain fill date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return
    #
    return growstages

determine_phenology_stage(initparams=None, weather=None, dispDates=True, dispFigPhenology=False, verbose=False) #

Estimate Wheat phenological stages using CERES-Wheat model

Deprecated.

This function was depreciated on Oct 22, 2023. Please use an updated version named determine_phenology_stages

Parameters:

Name Type Description Default
initparams dict

A dictionary with initial parameters

None
weather object

A table or dataframe with weather data for the site

None
dispDates bool

Display results in text format. Default is True

True
dispFigPhenology bool

Display a figure with the phenological phases. Default is False

False
verbose bool

Display comments during the processes. Default is False

False

Attributes:

Name Type Description
TT_TBASE float

Base temperature for estimate Thermal time. Default 0.0

TT_TEMPERATURE_OPTIMUM float

Thermal time optimum temperature. Default 26

TT_TEMPERATURE_MAXIMUM float

Thermal time maximum temperature. Default 34

CIVIL_TWILIGHT float

Sun angle with the horizon. eg. p = 6.0 : civil twilight. Default 0.0

HI float

Hardiness Index. Default 0.0

SNOW float

Snow fall. Default 0.0

SDEPTH float

Sowing depth in cm. Default 3.0 cm

GDDE float

Growing degree days per cm seed depth required for emergence, Default 6.2 GDD/cm.

DSGFT float

GDD from End Ear Growth to Start Grain Filling period. Default 200 degree-days

VREQ (float

Vernalization required for max.development rate (VDays). Default 505 degree-days

PHINT float

Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. Default 95.0 degree-days

P1V float

Development genetic coefficients, vernalization. 1 for spring type, 5 for winter type. Default 4.85

P1D float

Development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length). Default 3.675

P5 float

Grain filling degree days. Old value was divided by 10. Default 500 degree-days.

P6 float

Approximate the thermal time from physiological maturity to harvest. Default 250.

DAYS_GERMIMATION_LIMIT float

Threshold for days to germination. Default 40

TT_EMERGENCE_LIMIT float

Threshold for thermal time to emergence. Default 300

TT_TDU_LIMIT float

Threshold for thermal development units (TDU). Default 400

Returns:

Name Type Description
growstages dict

A dictionary with all phenological stages and addtional useful information

Source code in pywheat/pheno/__init__.py
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
def determine_phenology_stage(initparams=None, weather=None, dispDates=True, dispFigPhenology=False, verbose=False):
    '''
        Estimate Wheat phenological stages using CERES-Wheat model

        Warning: Deprecated.
                This function was depreciated on Oct 22, 2023. 
                Please use an updated version named `determine_phenology_stages`

        Parameters:
            initparams (dict): A dictionary with initial parameters
            weather (object): A table or dataframe with weather data for the site
            dispDates (bool): Display results in text format. Default is True
            dispFigPhenology (bool): Display a figure with the phenological phases. Default is False
            verbose (bool): Display comments during the processes. Default is False

        Attributes:
            TT_TBASE (float): Base temperature for estimate Thermal time. Default 0.0
            TT_TEMPERATURE_OPTIMUM (float): Thermal time optimum temperature. Default 26
            TT_TEMPERATURE_MAXIMUM (float): Thermal time maximum temperature. Default 34
            CIVIL_TWILIGHT (float): Sun angle with the horizon. eg. p = 6.0 : civil twilight. Default 0.0
            HI (float): Hardiness Index. Default 0.0 
            SNOW (float): Snow fall. Default 0.0
            SDEPTH (float): Sowing depth in cm. Default 3.0 cm
            GDDE (float): Growing degree days per cm seed depth required for emergence, Default 6.2 GDD/cm.
            DSGFT (float): GDD from End Ear Growth to Start Grain Filling period. Default 200 degree-days
            VREQ  (float): Vernalization required for max.development rate (VDays). Default 505 degree-days
            PHINT (float): Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. Default 95.0 degree-days
            P1V (float): Development genetic coefficients, vernalization. 1 for spring type, 5 for winter type. Default 4.85
            P1D (float): Development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length). Default 3.675
            P5 (float): Grain filling degree days. Old value was divided by 10. Default 500 degree-days.
            P6 (float): Approximate the thermal time from physiological maturity to harvest. Default 250.
            DAYS_GERMIMATION_LIMIT (float): Threshold for days to germination. Default 40
            TT_EMERGENCE_LIMIT (float): Threshold for thermal time to emergence. Default 300
            TT_TDU_LIMIT (float): Threshold for thermal development units (TDU). Default 400 

        Returns:
            growstages (dict): A dictionary with all phenological stages and addtional useful information

    '''
    if (initparams is None):
        print("Please check out the input parameters")
        return
    if (weather is None):
        print("Weather data is not available")
        return

    # Initialization of variables 
    params = dict(
        sowing_date = "", # Sowing date in YYYY-MM-DD
        latitude = -99.0, # Latitude of the site
        TT_TBASE = 0.0, # Base Temperature, 2.0 to estimate HI
        TT_TEMPERATURE_OPTIMUM = 26, # Thermal time optimum temperature
        TT_TEMPERATURE_MAXIMUM = 34, # Thermal time maximum temperature
        CIVIL_TWILIGHT = 0.0, # Sun angle with the horizon. eg. p = 6.0 : civil twilight,
        HI = 0.0, # Hardiness Index
        SNOW = 0, # Snow fall
        SDEPTH = 3.0, # Sowing depth in cm
        GDDE = 6.2, # Growing degree days per cm seed depth required for emergence, GDD/cm
        DSGFT = 200, # GDD from End Ear Growth to Start Grain Filling period
        VREQ  = 505.0, # Vernalization required for max.development rate (VDays)
        PHINT = 95.0, # Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. 
        P1V = 1.0, # development genetic coefficients, vernalization. 1 for spring type, 5 for winter type
        P1D = 3.675, # development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length)
        P5 = 500, # grain filling degree days eg. 500 degree-days. Old value was divided by 10.
        P6 = 250, # approximate the thermal time from physiological maturity to harvest
        DAYS_GERMIMATION_LIMIT = 40, # threshold for days to germination
        TT_EMERGENCE_LIMIT = 300, # threshold for thermal time to emergence
        TT_TDU_LIMIT = 400, # threshold for thermal development units (TDU)

    )
    if (initparams is not None):
        params = {**params, **initparams}

    # ---------------------
    # GDD limits
    # ---------------------
    P2 = params['PHINT'] * 3
    P3 = params['PHINT'] * 2
    P4 = params['DSGFT'] #200 # APSIM-Wheat = 120 # GDD from End Ear Growth to Start Grain Filling period
    P5 = params['P5'] #430 + params['P5'] * 20
    P6 = params['P5'] #250
    #P9 = 40 + params['GDDE'] * params['SDEPTH'] 

    growstages = {
            '7': {'istage_old': 'Sowing', 'istage': 'Fallow', 'desc': 'No crop present to Sowing', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '8': {'istage_old': 'Germinate', 'istage': 'Sowing', 'desc': 'Sowing to Germination', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '9': {'istage_old': 'Emergence', 'istage': 'Germinate', 'desc': 'Emergence to End of Juvenile', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '1': {'istage_old': 'Term Spklt', 'istage': 'Emergence', 'desc': 'Emergence to End of Juvenile', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '2': {'istage_old': 'End Veg', 'istage': 'End Juveni', 'desc': 'End of Juvenile to End of Vegetative growth', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '3': {'istage_old': 'End Ear Gr', 'istage': 'End Veg', 'desc': 'End of Vegetative Growth to End of Ear Grow', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '4': {'istage_old': 'Beg Gr Fil', 'istage': 'End Ear Gr', 'desc': 'End of Ear Growth to Start of Grain Filling', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '5': {'istage_old': 'End Gr Fil', 'istage': 'Beg Gr Fil', 'desc': 'Start of Grain Filling to Maturity', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''},
            '6': {'istage_old': 'Harvest', 'istage': 'Maturity', 'desc': 'End Gr Fil', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':''}
    }

    class StageFailed(Exception):
        def __init__(self, m, istage, err):
            self.message = m
            self.istage = istage
            self.err = err
        def __str__(self):
            return self.message + f" Stage ({self.istage}) - " + f"Error: {self.err}"

    # --------------------------------------------------------------------------
    # DETERMINE SOWING DATE
    # --------------------------------------------------------------------------
    ISTAGE = 7
    try:
        SOWING_DATE = pd.to_datetime(str(params['sowing_date']), format='%Y-%m-%d' )
        DOY = pd.to_datetime(SOWING_DATE).dayofyear

        growstages[f'{ISTAGE}']['date'] = str(SOWING_DATE).split(' ')[0]
        growstages[f'{ISTAGE}']['DOY'] = int(DOY)
        growstages[f'{ISTAGE}']['AGE'] = 0
        growstages[f'{ISTAGE}']['SUMDTT'] = 0
        growstages[f'{ISTAGE}']['DAP'] = 0
        #print("Sowing date:", SOWING_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem initializing the determination of phenological stage. Please check your input parameters such as sowing date or latitude of the site", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return


    # --------------------------------------------------------------------------
    # DETERMINE GERMINATION  DATE
    # --------------------------------------------------------------------------
    ISTAGE = 8
    try:
        SUMDTT = 0.0
        #VF = 0.0
        DAP = 0
        ndays = 1 # Seed germination is a rapid process and is assumed to occur in one day
        w = weather[(weather['DATE']==(SOWING_DATE + pd.DateOffset(days=ndays)) )].reset_index(drop=True)
        GERMINATION_DATE = ''
        Tmin = float(w.iloc[ndays-1]['TMIN'])
        Tmax = float(w.iloc[ndays-1]['TMAX'])
        # Thermal time
        DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                       Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                       Ttop=params['TT_TEMPERATURE_MAXIMUM'])
        SUMDTT = SUMDTT + DTT
        GERMINATION_DATE = w.iloc[ndays-1]['DATE']
        CROP_AGE = str(GERMINATION_DATE - SOWING_DATE).replace(' days 00:00:00','')
        DAP = DAP + int(CROP_AGE)
        growstages[f'{ISTAGE}']['date'] = str(GERMINATION_DATE).split(' ')[0]
        growstages[f'{ISTAGE}']['DOY'] = int(GERMINATION_DATE.dayofyear)
        growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
        growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
        growstages[f'{ISTAGE}']['DAP'] = DAP

        #print("Germination date:", GERMINATION_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining germination date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return


    # --------------------------------------------------------------------------
    # DETERMINE SEEDLING EMERGENCE DATE
    # --------------------------------------------------------------------------
    ISTAGE = 9
    try:
        P9 = 40 + params['GDDE'] * params['SDEPTH'] #Default values
        SUMDTT = 0.0
        #print("Growing degree days from germination to emergence (P9): ",P9) 
        # The crop will die if germination has not occurred before a certain period (eg. 40 days)
        w = weather[weather['DATE']>=GERMINATION_DATE].reset_index(drop=True)
        EMERGENCE_DATE = ''
        for i in range(len(w)):
            Tmin = float(w.iloc[i]['TMIN'])
            Tmax = float(w.iloc[i]['TMAX'])
            DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                           Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                           Ttop=params['TT_TEMPERATURE_MAXIMUM'])
            SUMDTT = SUMDTT + DTT

            if (SUMDTT >= P9 or SUMDTT > params['TT_EMERGENCE_LIMIT']):
                EMERGENCE_DATE = w.iloc[i]['DATE']
                CROP_AGE = str(EMERGENCE_DATE - GERMINATION_DATE).replace(' days 00:00:00','')
                DAP = DAP + int(CROP_AGE)
                growstages[f'{ISTAGE}']['date'] = str(EMERGENCE_DATE).split(' ')[0]
                growstages[f'{ISTAGE}']['DOY'] = int(EMERGENCE_DATE.dayofyear)
                growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                growstages[f'{ISTAGE}']['DAP'] = DAP
                #print("Thermal time reached at DAP ", i+1, str(EMERGENCE_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                break

        #print("Emergence date: ", EMERGENCE_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining emergence date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # --------------------------------------------------------------------------------------
    # DETERMINE DURATION OF VEGETATIVE PAHSE (END JUVENILE DATE - END OF VEGETATION GROWTH
    # --------------------------------------------------------------------------------------
    ISTAGE = 1
    try: 
        isVernalization = True
        SUMDTT = SUMDTT - P9 
        CUMVD = 0
        TDU = 0
        DF = 0.001
        shoot_lag = 40 # Assumed to be around 40 °C d
        shoot_rate = 1.5 # 1.5 °C d per mm. dDerived from studies where thermal time to emergence was measured and where sowing depth was known
        sowing_depth = params['SDEPTH'] * 10.0 # mm or 3cm as CERES

        T_emer = shoot_lag + shoot_rate * sowing_depth
        #print("Thermal time to emergence date: {} °C d".format( T_emer))
        #print("Thermal time to emergence date in CERES (P9): {} °C d".format(P9))
        TT_emergence = min(T_emer, P9)

        w = weather[weather['DATE']>=EMERGENCE_DATE].reset_index(drop=True)
        END_JUVENILE_DATE = ''
        for i in range(len(w)):
            Tmin = float(w.iloc[i]['TMIN'])
            Tmax = float(w.iloc[i]['TMAX'])
            DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                           Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                           Ttop=params['TT_TEMPERATURE_MAXIMUM'])
            if (isVernalization is True):
                Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                CUMVD = vernalization(Tcrown, Tmin, Tmax, CUMVD)
                if (CUMVD < params['VREQ']):
                    VF = vernalization_factor(P1V=params['P1V'], dV=CUMVD, ISTAGE=ISTAGE)
                    if (VF < 0.3):
                        TDU = TDU + DTT * min(VF, DF)
                    else:
                        DOY = pd.to_datetime(w.iloc[i]['DATE']).dayofyear
                        TWILEN = day_length(DOY=DOY, lat=params['latitude'], p=params['CIVIL_TWILIGHT'])
                        DF = photoperiod_factor(P1D=params['P1D'], day_length=TWILEN)
                        TDU = TDU + DTT * min(VF, DF)
                    SUMDTT = TDU
                else:
                    isVernalization = False
            else:
                SUMDTT = SUMDTT + DTT

            if (SUMDTT > P9 or SUMDTT > TT_emergence): # when reached the lower TT
                END_JUVENILE_DATE = w.iloc[i]['DATE']
                CROP_AGE = str(END_JUVENILE_DATE - EMERGENCE_DATE).replace(' days 00:00:00','')
                DAP = DAP + int(CROP_AGE)
                growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                growstages[f'{ISTAGE}']['date'] = str(END_JUVENILE_DATE).split(' ')[0]
                growstages[f'{ISTAGE}']['DOY'] = int(END_JUVENILE_DATE.dayofyear)
                growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                growstages[f'{ISTAGE}']['DAP'] = DAP
                #print("Thermal time reached at DAP ", i+1, str(END_JUVENILE_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                break
            if (DTT > params['TT_EMERGENCE_LIMIT']): # TT_EMERGENCE_LIMIT = 300,
                # The crop will die if germination has not occurred before a certain period (eg. 40 days or 300oC d)
                print("The crop died because emergence has not occurred before {} degree-days".format(params['TT_EMERGENCE_LIMIT']))

        #print("End Juvenile date: ", END_JUVENILE_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of juvenile date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # --------------------------------------------------------------------------
    # DETERMINE END VEGETATION DATE - End of Juvenile to End of Vegetative growth
    # --------------------------------------------------------------------------
    ISTAGE = 1 # <- Note: this must continue with 1 as previous stage (Term Spklt = Emergence to End of Juvenile + End of Juvenile to End of Vegetative growth)
    try:
        isVernalization = True
        VF = 1.0
        w = weather[weather['DATE']>=END_JUVENILE_DATE].reset_index(drop=True)
        END_VEGETATION_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                if (isVernalization is True):
                    Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                    CUMVD = vernalization(Tcrown, Tmin, Tmax, CUMVD)
                    if (CUMVD < params['VREQ']):
                        VF = vernalization_factor(P1V=params['P1V'], dV=CUMVD, ISTAGE=ISTAGE)
                        if (VF < 0.3):
                            TDU = TDU + DTT * min(VF, DF)
                        else:
                            DOY = pd.to_datetime(w.iloc[i]['DATE']).dayofyear
                            TWILEN = day_length(DOY=DOY, lat=params['latitude'], p=params['CIVIL_TWILIGHT'])
                            DF = photoperiod_factor(P1D=params['P1D'], day_length=TWILEN)
                            TDU = TDU + DTT * min(VF, DF)
                        SUMDTT = TDU
                    else:
                        isVernalization = False
                else:
                    SUMDTT = SUMDTT + DTT

                # When this reduced thermal time accumulation (TDU) reaches 
                # 400 degree days, Stage 1 development ends
                if (SUMDTT > (params['TT_TDU_LIMIT'] * (params['PHINT'] / 95.0)) ):
                    END_VEGETATION_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_VEGETATION_DATE - END_JUVENILE_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    # Sum of the two phases
                    CROP_AGE_2 = str(END_VEGETATION_DATE - EMERGENCE_DATE).replace(' days 00:00:00','')
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE_2) # Sum of the last two phases
                    growstages[f'{ISTAGE}']['date'] = str(END_VEGETATION_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_VEGETATION_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    #if (verbose is True):
                    #    print("End of Juvenile: Thermal time reached at days duration ", i+1,
                    #          str(END_VEGETATION_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                    break
        else:
            print("Error reading weather data for vegetation phase")

        # print("End of Vegeation Growth ", END_VEGETATION_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of vegetation growth date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE END OF EAR GROWTH - End of Vegetative Growth to End of Ear Grow (End leaf growth)
    #-----------------------------------------------------------------------------------------------
    ISTAGE = 2 # Terminal spikelet initiation to the end of leaf growth - CERES Stage 2
    try:
        SUMDTT = 0.0
        P2 = params['PHINT'] * 3

        w = weather[weather['DATE']>=END_VEGETATION_DATE].reset_index(drop=True)
        END_OF_EAR_GROWTH_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT

                if (SUMDTT >= P2):
                    END_OF_EAR_GROWTH_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_OF_EAR_GROWTH_DATE - END_VEGETATION_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(END_OF_EAR_GROWTH_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_OF_EAR_GROWTH_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(END_OF_EAR_GROWTH_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("End of Ear growth",END_OF_EAR_GROWTH_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of ear growth date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE END OF PANNICLE GROWTH - End pannicle growth - End of Ear Growth to Start of Grain Filling
    # ----------------------------------------------------------------------------------------------
    ISTAGE = 3 # Preanthesis ear growth - CERES Stage 3.
    try:
        SUMDTT = 0.0 #SUMDTT - P2
        P3 = params['PHINT'] * 2
        #TBASE=0.0

        w = weather[weather['DATE']>END_OF_EAR_GROWTH_DATE].reset_index(drop=True)
        END_OF_PANNICLE_GROWTH_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT

                if (SUMDTT >= P3):
                    END_OF_PANNICLE_GROWTH_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_OF_PANNICLE_GROWTH_DATE - END_OF_EAR_GROWTH_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(END_OF_PANNICLE_GROWTH_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_OF_PANNICLE_GROWTH_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(END_OF_PANNICLE_GROWTH_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("End of Pre-Anthesis Ear growth",END_OF_PANNICLE_GROWTH_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of pre-anthesis earh growth date (end of pannicle growth date).", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE BEGIN GRAIN FILLING - Grain fill - Start of Grain Filling to Maturity
    # ----------------------------------------------------------------------------------------------
    ISTAGE = 4 # Preanthesis ear growth to the beginning of grain filling - CERES Stage 4.
    try: 
        P4 = params['DSGFT'] #200 GDD # APSIM-Wheat = 120
        SUMDTT = 0.0 #SUMDTT - P3

        w = weather[weather['DATE']>=END_OF_PANNICLE_GROWTH_DATE].reset_index(drop=True)
        BEGIN_GRAIN_FILLING_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT
                if (SUMDTT >= P4):
                    BEGIN_GRAIN_FILLING_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(BEGIN_GRAIN_FILLING_DATE - END_OF_PANNICLE_GROWTH_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(BEGIN_GRAIN_FILLING_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(BEGIN_GRAIN_FILLING_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(BEGIN_GRAIN_FILLING_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("Begining of Grain fill",BEGIN_GRAIN_FILLING_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining begin of grain fill date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE END GRAIN FILLING - Maturity
    # ----------------------------------------------------------------------------------------------
    ISTAGE = 5
    try:
        SUMDTT = 0.0 #SUMDTT - P4
        #P5 = 430 + params['P5'] * 20 # P5 = (0.05 X TT_Maturity) - 21.5. ~500 degree-days
        P5 = params['P5'] # 400 + 5.0 * 20  

        w = weather[weather['DATE']>=BEGIN_GRAIN_FILLING_DATE].reset_index(drop=True)
        END_GRAIN_FILLING_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT
                if (SUMDTT >= P5):
                    END_GRAIN_FILLING_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_GRAIN_FILLING_DATE - BEGIN_GRAIN_FILLING_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(END_GRAIN_FILLING_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_GRAIN_FILLING_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(END_GRAIN_FILLING_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("End of Grain filling",END_GRAIN_FILLING_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of grain fill date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE HARVEST - Harvest - End of Grain Filling or Maturity
    # ----------------------------------------------------------------------------------------------
    ISTAGE = 6  # Physiological maturity to harvest - CERES Stage 6.
    try: 
        SUMDTT = 0.0
        estimateHarvest = True
        P6 = params['P6']

        if (estimateHarvest is False):
            HARVEST = END_GRAIN_FILLING_DATE
            growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
            growstages[f'{ISTAGE}']['date'] = str(HARVEST).split(' ')[0]
            growstages[f'{ISTAGE}']['DOY'] = int(HARVEST.dayofyear)
            growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
            growstages[f'{ISTAGE}']['DAP'] = DAP
        else:
            # A value of 250 degree-days can be used to approximate the thermal time from physiological maturity to harvest
            w = weather[weather['DATE']>=END_GRAIN_FILLING_DATE].reset_index(drop=True)
            HARVEST = ''
            if (len(w)>0):
                for i in range(len(w)):
                    Tmin = float(w.iloc[i]['TMIN'])
                    Tmax = float(w.iloc[i]['TMAX'])
                    # Thermal time
                    DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                                   Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                                   Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                    SUMDTT = SUMDTT + DTT
                    if (SUMDTT >= P6):
                        HARVEST = w.iloc[i]['DATE']
                        CROP_AGE = str(HARVEST - END_GRAIN_FILLING_DATE).replace(' days 00:00:00','')
                        DAP = DAP + int(CROP_AGE)
                        growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                        growstages[f'{ISTAGE}']['date'] = str(HARVEST).split(' ')[0]
                        growstages[f'{ISTAGE}']['DOY'] = int(HARVEST.dayofyear)
                        growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                        growstages[f'{ISTAGE}']['DAP'] = DAP
                        #if (verbose is True):
                        #    print("Thermal time reached at days duration ", i+1, str(HARVEST), 
                        #          CROP_AGE, DAP, round(SUMDTT, 1))
                        break
    except Exception as err:
        try:
            raise StageFailed("Problem determining physiological maturity to harvest date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ---------------------
    if (dispDates is True):
        try:
            print("RSTG   GROWTH STAGE      DAP  DOY   CROP AGE   SUMDTT   DATE ")
            for k in growstages.keys():
                print("{:4}   {:10} {:>10} {:>4} {:>6} {:>12} {:>12}".format(k, growstages[k]['istage_old'], 
                                                                             growstages[k]['DAP'],
                                                                             growstages[k]['DOY'], growstages[k]['AGE'],
                                                                             growstages[k]['SUMDTT'], 
                                                                             growstages[k]['date']))
        except Exception as err:
            try:
                raise StageFailed("Problem displaying results.", -99, err)
            except StageFailed as x:
                print(x)
                return

    if (dispFigPhenology is True):
        try:
            drawPhenology(gs=growstages, title='Phenological growth phases of Wheat', dpi=150,
                         dispPlants=True, topDAPLabel=True, timeSpanLabel=True, topNameStageLabel=True,
                         topNameStageLabelOpt=True, copyrightLabel=True, 
                         saveFig=False, showFig=True, path_to_save_results='./', 
                         fname='Fig_1_Phenological_Phases_Wheat', fmt='jpg')
        except Exception as err:
            try:
                raise StageFailed("Problem displaying figure of phenological stages.", -99, err)
            except StageFailed as x:
                print(x)
                return
    # ---------------------
    return growstages

determine_phenology_stages(config=None, initparams=None, useDefault=True, dispDates=True, dispFigPhenology=False, verbose=False) #

Estimate Wheat phenological stages using an improved PyWheat model calibrated with IWIN datasets (ESWYT, IDYN, HTWYT and SAWYT nurseries)

Parameters:

Name Type Description Default
config dict

A dictionary with configuration parameters

None
initparams dict

A dictionary with initial parameters

None
dispDates bool

Display results in text format. Default is True

True
dispFigPhenology bool

Display a figure with the phenological phases. Default is False

False
verbose bool

Display comments during the processes. Default is False

False

Attributes:

Name Type Description
weather object

A table or dataframe with weather data for the site

TT_TBASE float

Base temperature for estimate Thermal time. Default 0.0

TT_TEMPERATURE_OPTIMUM float

Thermal time optimum temperature. Default 26

TT_TEMPERATURE_MAXIMUM float

Thermal time maximum temperature. Default 34

CIVIL_TWILIGHT float

Sun angle with the horizon. eg. p = 6.0 : civil twilight. Default 0.0

HI float

Hardiness Index. Default 0.0

SNOW float

Snow fall. Default 0.0

SDEPTH float

Sowing depth in cm. Default 3.0 cm

GDDE float

Growing degree days per cm seed depth required for emergence, Default 6.2 GDD/cm.

DSGFT float

GDD from End Ear Growth to Start Grain Filling period. Default 200 degree-days

VREQ (float

Vernalization required for max.development rate (VDays). Default 505 degree-days

PHINT float

Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. Default 95.0 degree-days

P1V float

Days,optimum vernalizing temperature,required for vernalization. Development genetic coefficients, vernalization. 1 for spring type, 5 for winter type. Default 1.00

P1D float

Photoperiod response (% reduction in rate/10 h drop in pp). Development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length). Default 3.675 #75 DSSAT

P5 float

Grain filling degree days. Old value was divided by 10. Default 500 degree-days.

P6 float

Approximate the thermal time from physiological maturity to harvest. Default 250.

DAYS_GERMIMATION_LIMIT float

Threshold for days to germination. Default 40

TT_EMERGENCE_LIMIT int

Threshold for thermal time to emergence. Default 400 degree-days

TT_TDU_LIMIT float

Threshold for thermal development units (TDU). Default 400 degree-days

ADAH int

Number of days after heading. A threshold used for anthesis date after planting. Default is 6 days after heading.

p5_steps float

Step to increase or reduce the P5 parameters. Default 1.0

maxP5 float

Threshold for the maximum value of P5 to reach maturity date. Default 1000

Returns:

Name Type Description
growstages dict

A dictionary with all phenological stages and addtional useful information

Source code in pywheat/pheno/__init__.py
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
def determine_phenology_stages(config=None, initparams=None, useDefault=True, 
                               dispDates=True, dispFigPhenology=False, verbose=False):
    '''
        Estimate Wheat phenological stages using an improved PyWheat model calibrated 
        with IWIN datasets (ESWYT, IDYN, HTWYT and SAWYT nurseries)

        Parameters:
            config (dict): A dictionary with configuration parameters
            initparams (dict): A dictionary with initial parameters
            dispDates (bool): Display results in text format. Default is True
            dispFigPhenology (bool): Display a figure with the phenological phases. Default is False
            verbose (bool): Display comments during the processes. Default is False

        Attributes:
            weather (object): A table or dataframe with weather data for the site
            TT_TBASE (float): Base temperature for estimate Thermal time. Default 0.0
            TT_TEMPERATURE_OPTIMUM (float): Thermal time optimum temperature. Default 26
            TT_TEMPERATURE_MAXIMUM (float): Thermal time maximum temperature. Default 34
            CIVIL_TWILIGHT (float): Sun angle with the horizon. eg. p = 6.0 : civil twilight. Default 0.0
            HI (float): Hardiness Index. Default 0.0 
            SNOW (float): Snow fall. Default 0.0
            SDEPTH (float): Sowing depth in cm. Default 3.0 cm
            GDDE (float): Growing degree days per cm seed depth required for emergence, Default 6.2 GDD/cm.
            DSGFT (float): GDD from End Ear Growth to Start Grain Filling period. Default 200 degree-days
            VREQ  (float): Vernalization required for max.development rate (VDays). Default 505 degree-days
            PHINT (float): Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. Default 95.0 degree-days
            P1V (float): Days,optimum vernalizing temperature,required for vernalization. Development genetic coefficients, vernalization. 1 for spring type, 5 for winter type. Default 1.00
            P1D (float): Photoperiod response (% reduction in rate/10 h drop in pp). Development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length). Default 3.675  #75 DSSAT
            P5 (float): Grain filling degree days. Old value was divided by 10. Default 500 degree-days.
            P6 (float): Approximate the thermal time from physiological maturity to harvest. Default 250.
            DAYS_GERMIMATION_LIMIT (float): Threshold for days to germination. Default 40
            TT_EMERGENCE_LIMIT (int): Threshold for thermal time to emergence. Default 400 degree-days
            TT_TDU_LIMIT (float): Threshold for thermal development units (TDU). Default 400  degree-days
            ADAH (int): Number of days after heading. A threshold used for anthesis date after planting. Default is 6 days after heading.
            p5_steps (float): Step to increase or reduce the P5 parameters. Default 1.0
            maxP5 (float): Threshold for the maximum value of P5 to reach maturity date. Default 1000

        Returns:
            growstages (dict): A dictionary with all phenological stages and addtional useful information

    '''
    if (config is None):
        config = load_configfiles()
    if (initparams is None):
        print("Please check out the input parameters")
        return

    # Initialization of variables 
    params = dict(
        weather = None, # Weather data of the site
        sowing_date = "", # Sowing date in YYYY-MM-DD
        latitude = -90.0, # Latitude of the site
        longitude = -180.0, # Longitude of the site
        genotype = "", # Name of the grand parent in IWIN pedigrees database 
        TT_TBASE = 0.0, # Base Temperature, 2.0 to estimate HI
        TT_TEMPERATURE_OPTIMUM = 26, # Thermal time optimum temperature
        TT_TEMPERATURE_MAXIMUM = 34, # Thermal time maximum temperature
        CIVIL_TWILIGHT = 0.0, # Sun angle with the horizon. eg. p = 6.0 : civil twilight,
        HI = 0.0, # Hardiness Index
        SNOW = 0, # Snow fall
        SDEPTH = 3.0, # Sowing depth in cm
        GDDE = 6.2, # Growing degree days per cm seed depth required for emergence, GDD/cm
        DSGFT = 200, # GDD from End Ear Growth to Start Grain Filling period
        VREQ  = 505.0, # Vernalization required for max.development rate (VDays)
        PHINT = 95.0, # Phyllochron. A good estimate for PHINT is 95 degree days. This value for PHINT is appropriate except for spring sown wheat in latitudes greater than 30 degrees north and 30 degrees south, in which cases a value for PHINT of 75 degree days is suggested. 
        P1V = 1.0, # development genetic coefficients, vernalization. 1 for spring type, 5 for winter type
        P1D = 3.675, # development genetic coefficients, Photoperiod (1 - 6, low- high sensitive to day length)
        P5 = 500, # grain filling degree days eg. 500 degree-days. Old value was divided by 10.
        P6 = 250, # approximate the thermal time from physiological maturity to harvest
        DAYS_GERMIMATION_LIMIT = 40, # threshold for days to germination
        TT_EMERGENCE_LIMIT = 500, # threshold for thermal time to emergence
        TT_TDU_LIMIT = 1000, # threshold for thermal development units (TDU)
        ADAH = 6, # threshold for anthesis date after planting. This is a 6 days after heading.
        bruteforce = False,
        brute_params = {
            "obsEmergenceDAP": None, # Observed days after planting to emergence.
            "obsHeadingDAP": None, # Observed days after planting to heading.
            "obsAnthesisDAP": None, # Observed days after planting to Anthesis.
            "obsMaturityDAP": None, # Observed days after planting to Maturity.
            "max_tries": 300, # Number of maximum tries to find the best value
            "error_lim": 0.5, # Threshold to classify the observation as a good or bad
            "gdde_steps": 1.0, # Step to increase or reduce the GDDE parameters. Default 1.0
            "maxGDDE": 50, #Threshold for the maximum value of GDDE to reach emergence date
            "phint_steps": 1.0, # Step to increase or reduce the PHINT parameters. Default 1.0
            "maxPHINT": 150, #Threshold for the maximum value of PHINT to reach heading date
            "adap_steps": 1, #Step to increase or reduce the ADAH parameters. Default 1
            "maxADAP": 10, #Threshold for the maximum value of ADAH to reach anthesis date.
            "p5_steps": 1, #Step to increase or reduce the P5 parameters. Default 1.0
            "maxP5": 2000 #Threshold for the maximum value of P5 to reach anthesis date.
        }

    )
    if (initparams is not None):
        params = {**params, **initparams}

    # Validate
    if (params['sowing_date']=="" or params['sowing_date'] is None):
        print("Sowing date not defined")
        return
    if (params['latitude']==-90.0 or params['latitude'] is None):
        print("Problem with location of the site. Check the geographic coordinates.")
        return
    if (params['weather'] is None):
        print("Weather data is not available")
        return
    else:
        weather = params['weather']
    if ((params['bruteforce'] is True )
        and (params['brute_params']["obsEmergenceDAP"] is None and params['brute_params']["obsHeadingDAP"] is None 
             and params['brute_params']["obsAnthesisDAP"] is None and params['brute_params']["obsMaturityDAP"] is None
            )):
        print("Parameters to run brute force algorithm are not defined yet.")
        return

    # ---------------------
    # GDD limits
    # ---------------------
    P2 = params['PHINT'] * 3
    P3 = params['PHINT'] * 2
    P4 = params['DSGFT'] #200 # APSIM-Wheat = 120 # GDD from End Ear Growth to Start Grain Filling period
    P5 = params['P5'] #430 + params['P5'] * 20 # DSSAT v4.8
    #P6 = params['P5'] #250
    #P9 = 40 + params['GDDE'] * params['SDEPTH'] 

    growstages = {
            '7': {'istage_old': 'Sowing', 'istage': 'Fallow', 'desc': 'No crop present to Sowing', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':'', 'status':''},
            '8': {'istage_old': 'Germinate', 'istage': 'Sowing', 'desc': 'Sowing to Germination', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':'', 'status':''},
            '9': {'istage_old': 'Emergence', 'istage': 'Germinate', 'desc': 'Emergence to End of Juvenile', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':'', 'status':''},
            '1': {'istage_old': 'Term Spklt', 'istage': 'Emergence', 'desc': 'Emergence to End of Juvenile', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':'', 'status':''},
            '2': {'istage_old': 'End Veg', 'istage': 'End Juveni', 'desc': 'End of Juvenile to End of Vegetative growth', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':'', 'status':''},
            '2.5': {'istage_old': 'Anthesis', 'istage': 'Anthesis', 'desc': 'Anthesis', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':'', 'status':''},
            '3': {'istage_old': 'End Ear Gr', 'istage': 'End Veg', 'desc': 'End of Vegetative Growth to End of Ear Grow', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':'', 'status':''},
            '4': {'istage_old': 'Beg Gr Fil', 'istage': 'End Ear Gr', 'desc': 'End of Ear Growth to Start of Grain Filling', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':'', 'status':''},
            '5': {'istage_old': 'End Gr Fil', 'istage': 'Beg Gr Fil', 'desc': 'Start of Grain Filling to Maturity', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':'', 'status':''},
            '6': {'istage_old': 'Harvest', 'istage': 'Maturity', 'desc': 'End Gr Fil', 'date':'', 'DOY':'', 'AGE':'', 'DAP':'', 'SUMDTT':'', 'status':''}
    }

    class StageFailed(Exception):
        def __init__(self, m, istage, err):
            self.message = m
            self.istage = istage
            self.err = err
        def __str__(self):
            return self.message + f" Stage ({self.istage}) - " + f"Error: {self.err}"

    # --------------------------------------------------------------------------
    # DETERMINE SOWING DATE
    # --------------------------------------------------------------------------
    ISTAGE = 7
    try:
        SOWING_DATE = pd.to_datetime(str(params['sowing_date']), format='%Y-%m-%d' )
        DOY = pd.to_datetime(SOWING_DATE).dayofyear

        growstages[f'{ISTAGE}']['date'] = str(SOWING_DATE).split(' ')[0]
        growstages[f'{ISTAGE}']['DOY'] = int(DOY)
        growstages[f'{ISTAGE}']['AGE'] = 0
        growstages[f'{ISTAGE}']['SUMDTT'] = 0
        growstages[f'{ISTAGE}']['DAP'] = 0
        growstages[f'{ISTAGE}']['status'] = 1
        #print("Sowing date:", SOWING_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem initializing the determination of phenological stage. Please check your input parameters such as sowing date or latitude of the site", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # --------------------------------------------------------------------------
    # DETERMINE GERMINATION  DATE
    # --------------------------------------------------------------------------
    ISTAGE = 8
    try:
        SUMDTT = 0.0
        #VF = 0.0
        DAP = 0
        ndays = 1 # Seed germination is a rapid process and is assumed to occur in one day
        w = weather[(weather['DATE']==(SOWING_DATE + pd.DateOffset(days=ndays)) )].reset_index(drop=True)
        GERMINATION_DATE = ''
        Tmin = float(w.iloc[ndays-1]['TMIN'])
        Tmax = float(w.iloc[ndays-1]['TMAX'])
        # Thermal time
        DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                       Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                       Ttop=params['TT_TEMPERATURE_MAXIMUM'])
        SUMDTT = SUMDTT + DTT
        GERMINATION_DATE = w.iloc[ndays-1]['DATE']
        CROP_AGE = str(GERMINATION_DATE - SOWING_DATE).replace(' days 00:00:00','')
        DAP = DAP + int(CROP_AGE)
        growstages[f'{ISTAGE}']['date'] = str(GERMINATION_DATE).split(' ')[0]
        growstages[f'{ISTAGE}']['DOY'] = int(GERMINATION_DATE.dayofyear)
        growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
        growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
        growstages[f'{ISTAGE}']['DAP'] = DAP
        growstages[f'{ISTAGE}']['status'] = 1

        #print("Germination date:", GERMINATION_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining germination date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return


    # --------------------------------------------------------------------------
    # DETERMINE SEEDLING EMERGENCE DATE
    # --------------------------------------------------------------------------
    ISTAGE = 9
    P9 = 40 + params['GDDE'] * params['SDEPTH'] #Default values defined by user or by CERES-Wheat
    try:
        # Get GDDE and SDEPTH parameters
        e_status = 1
        if (params['bruteforce']==True and params['brute_params']!={} and 
            params['brute_params']["obsEmergenceDAP"] is not None):
            # using brute force algorithms
            e_growstages, params, e_status = estimate_emergence_by_bruteforce(params)
            #params = { **params, **e_params}
        elif ( useDefault is True and params['longitude']!=-180.0 and params['longitude']!='' 
              and params['longitude'] is not None):
            ## using geographic coordinates and month to extract values by linear regression
            params = estimate_emergence_by_default(config, params, GERMINATION_DATE)
        elif (params['longitude']!=-180.0 and params['longitude']!='' and params['longitude'] is not None):
            ## using geographic coordinates
            params = estimate_emergence_by_coords(config, params)
        elif (params['genotype']!="" and params['genotype'] is not None):
            # using cultivar or genotype name
            params = estimate_emergence_by_cultivar(config, params, GERMINATION_DATE)

        #
        P9 = 40 + params['GDDE'] * params['SDEPTH']
        SUMDTT = 0.0
        #print("Growing degree days from germination to emergence (P9): ",P9) 
        # The crop will die if germination has not occurred before a certain period (eg. 40 days)

        EMERGENCE_DATE = ''
        w = weather[weather['DATE']>=GERMINATION_DATE].reset_index(drop=True)
        for i in range(len(w)):
            Tmin = float(w.iloc[i]['TMIN'])
            Tmax = float(w.iloc[i]['TMAX'])
            DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                           Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                           Ttop=params['TT_TEMPERATURE_MAXIMUM'])
            SUMDTT = SUMDTT + DTT

            if (SUMDTT >= P9 or SUMDTT > params['TT_EMERGENCE_LIMIT']):
                EMERGENCE_DATE = w.iloc[i]['DATE']
                CROP_AGE = str(EMERGENCE_DATE - GERMINATION_DATE).replace(' days 00:00:00','')
                DAP = DAP + int(CROP_AGE)
                growstages[f'{ISTAGE}']['date'] = str(EMERGENCE_DATE).split(' ')[0]
                growstages[f'{ISTAGE}']['DOY'] = int(EMERGENCE_DATE.dayofyear)
                growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                growstages[f'{ISTAGE}']['DAP'] = DAP
                growstages[f'{ISTAGE}']['status'] = e_status
                #print("Thermal time reached at DAP ", i+1, str(EMERGENCE_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                break

        #print("Emergence date: ", EMERGENCE_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining emergence date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # --------------------------------------------------------------------------------------
    # DETERMINE DURATION OF VEGETATIVE PAHSE (END JUVENILE DATE - END OF VEGETATION GROWTH
    # --------------------------------------------------------------------------------------
    ISTAGE = 1
    # Get SNOW, VREQ, P1V, P1D,  parameters using geographic coordinates
    h_status = 1
    if (params['bruteforce']==True and params['brute_params']!={} and 
        params['brute_params']["obsHeadingDAP"] is not None):
        # using brute force algorithms
        h_growstages, params, h_status = estimate_heading_by_bruteforce(params)
        #params = { **params, **h_params}
    elif ( useDefault is True and params['longitude']!=-180.0 and params['longitude']!='' 
          and params['longitude'] is not None):
        ## using geographic coordinates and month to extract values by linear regression
        params = estimate_heading_by_default(config, params, EMERGENCE_DATE)
    elif (params['longitude']!=-180.0 and params['longitude']!='' and params['longitude'] is not None):
        ## using geographic coordinates
        params = estimate_heading_by_coords(config, params)
    elif (params['genotype']!="" and params['genotype'] is not None):
        # using cultivar or genotype name
        params = estimate_heading_by_cultivar(config, params, EMERGENCE_DATE)

    try: 
        isVernalization = True
        SUMDTT = SUMDTT - P9 
        CUMVD = 0
        TDU = 0
        DF = 0.001
        shoot_lag = 40 # Assumed to be around 40 °C d
        shoot_rate = 1.5 # 1.5 °C d per mm. dDerived from studies where thermal time to emergence was measured and where sowing depth was known
        sowing_depth = params['SDEPTH'] * 10.0 # mm or 3cm as CERES

        T_emer = shoot_lag + shoot_rate * sowing_depth
        #print("Thermal time to emergence date: {} °C d".format( T_emer))
        #print("Thermal time to emergence date in CERES (P9): {} °C d".format(P9))
        TT_emergence = min(T_emer, P9)

        w = weather[weather['DATE']>=EMERGENCE_DATE].reset_index(drop=True)
        END_JUVENILE_DATE = ''
        for i in range(len(w)):
            Tmin = float(w.iloc[i]['TMIN'])
            Tmax = float(w.iloc[i]['TMAX'])
            DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                           Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                           Ttop=params['TT_TEMPERATURE_MAXIMUM'])
            if (isVernalization is True):
                Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                CUMVD = vernalization(Tcrown, Tmin, Tmax, CUMVD)
                if (CUMVD < params['VREQ']):
                    VF = vernalization_factor(P1V=params['P1V'], dV=CUMVD, ISTAGE=ISTAGE)
                    if (VF < 0.3):
                        TDU = TDU + DTT * min(VF, DF)
                    else:
                        DOY = pd.to_datetime(w.iloc[i]['DATE']).dayofyear
                        TWILEN = day_length(DOY=DOY, lat=params['latitude'], p=params['CIVIL_TWILIGHT'])
                        DF = photoperiod_factor(P1D=params['P1D'], day_length=TWILEN)
                        TDU = TDU + DTT * min(VF, DF)
                    SUMDTT = TDU
                else:
                    isVernalization = False
            else:
                SUMDTT = SUMDTT + DTT

            if (SUMDTT > P9 or SUMDTT > TT_emergence): # when reached the lower TT
                END_JUVENILE_DATE = w.iloc[i]['DATE']
                CROP_AGE = str(END_JUVENILE_DATE - EMERGENCE_DATE).replace(' days 00:00:00','')
                DAP = DAP + int(CROP_AGE)
                growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                growstages[f'{ISTAGE}']['date'] = str(END_JUVENILE_DATE).split(' ')[0]
                growstages[f'{ISTAGE}']['DOY'] = int(END_JUVENILE_DATE.dayofyear)
                growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                growstages[f'{ISTAGE}']['DAP'] = DAP
                growstages[f'{ISTAGE}']['status'] = h_status
                #print("Thermal time reached at DAP ", i+1, str(END_JUVENILE_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                break
            if (DTT > params['TT_EMERGENCE_LIMIT']): # TT_EMERGENCE_LIMIT = 300,
                # The crop will die if germination has not occurred before a certain period (eg. 40 days or 300oC d)
                print("The crop died because emergence has not occurred before {} degree-days".format(params['TT_EMERGENCE_LIMIT']))

        #print("End Juvenile date: ", END_JUVENILE_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of juvenile date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # --------------------------------------------------------------------------
    # DETERMINE END VEGETATION DATE - End of Juvenile to End of Vegetative growth
    # --------------------------------------------------------------------------
    ISTAGE = 1 # <- Note: this must continue with 1 as previous stage (Term Spklt = Emergence to End of Juvenile + End of Juvenile to End of Vegetative growth)
    try:
        isVernalization = True
        VF = 1.0
        w = weather[weather['DATE']>=END_JUVENILE_DATE].reset_index(drop=True)
        END_VEGETATION_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                if (isVernalization is True):
                    Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax)
                    CUMVD = vernalization(Tcrown, Tmin, Tmax, CUMVD)
                    if (CUMVD < params['VREQ']):
                        VF = vernalization_factor(P1V=params['P1V'], dV=CUMVD, ISTAGE=ISTAGE)
                        if (VF < 0.3):
                            TDU = TDU + DTT * min(VF, DF)
                        else:
                            DOY = pd.to_datetime(w.iloc[i]['DATE']).dayofyear
                            TWILEN = day_length(DOY=DOY, lat=params['latitude'], p=params['CIVIL_TWILIGHT'])
                            DF = photoperiod_factor(P1D=params['P1D'], day_length=TWILEN)
                            TDU = TDU + DTT * min(VF, DF)
                        SUMDTT = TDU
                    else:
                        isVernalization = False
                else:
                    SUMDTT = SUMDTT + DTT

                # When this reduced thermal time accumulation (TDU) reaches 
                # 400 degree days, Stage 1 development ends
                if (SUMDTT > (params['TT_TDU_LIMIT'] * (params['PHINT'] / 95.0)) ):
                    END_VEGETATION_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_VEGETATION_DATE - END_JUVENILE_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    # Sum of the two phases
                    CROP_AGE_2 = str(END_VEGETATION_DATE - EMERGENCE_DATE).replace(' days 00:00:00','')
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE_2) # Sum of the last two phases
                    growstages[f'{ISTAGE}']['date'] = str(END_VEGETATION_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_VEGETATION_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    growstages[f'{ISTAGE}']['status'] = h_status
                    #if (verbose is True):
                    #    print("End of Juvenile: Thermal time reached at days duration ", i+1,
                    #          str(END_VEGETATION_DATE), CROP_AGE, DAP, round(SUMDTT, 1))
                    break
        else:
            print("Error reading weather data for vegetation phase")

        # print("End of Vegeation Growth ", END_VEGETATION_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of vegetation growth date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE END OF EAR GROWTH - End of Vegetative Growth to End of Ear Grow (End leaf growth)
    #-----------------------------------------------------------------------------------------------
    ISTAGE = 2 # Terminal spikelet initiation to the end of leaf growth - CERES Stage 2
    try:
        SUMDTT = 0.0
        P2 = params['PHINT'] * 3

        w = weather[weather['DATE']>=END_VEGETATION_DATE].reset_index(drop=True)
        END_OF_EAR_GROWTH_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT

                if (SUMDTT >= P2):
                    END_OF_EAR_GROWTH_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_OF_EAR_GROWTH_DATE - END_VEGETATION_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(END_OF_EAR_GROWTH_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_OF_EAR_GROWTH_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    growstages[f'{ISTAGE}']['status'] = h_status
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(END_OF_EAR_GROWTH_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("End of Ear growth",END_OF_EAR_GROWTH_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of ear growth date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return
    #
    #
    # ----------------------------------------------------------------------------------------------
    # DETERMINE ANTHESIS
    # ----------------------------------------------------------------------------------------------
    # Anthesis date was estimated as occurring 7 d after heading. (based on McMaster and Smika, 1988; 
    # McMaster and Wilhelm, 2003; G. S. McMaster, unpubl. data). 
    # Here we used 6 days according to IWIN reported anthesis
    ISTAGE = 2.5
    ADAH = params['ADAH'] # Anthesis days after heading

    # Get ADAH parameter
    a_status = 1
    if (params['bruteforce']==True and params['brute_params']!={} and 
        params['brute_params']["obsAnthesisDAP"] is not None):
        # using brute force algorithms
        a_growstages, params, a_status = estimate_anthesis_by_bruteforce(params)
        #params = { **params, **e_params}
    elif ( useDefault is True and params['longitude']!=-180.0 and params['longitude']!='' 
          and params['longitude'] is not None):
        ## using geographic coordinates and month to extract values by linear regression
        params = estimate_anthesis_by_default(config, params, END_OF_EAR_GROWTH_DATE)
    elif (params['longitude']!=-180.0 and params['longitude']!='' and params['longitude'] is not None):
        ## using geographic coordinates
        params = estimate_anthesis_by_coords(config, params)
    elif (params['genotype']!="" and params['genotype'] is not None):
        # using cultivar or genotype name
        params = estimate_anthesis_by_cultivar(config, params, END_OF_EAR_GROWTH_DATE)

    CROP_AGE = DAP + ADAH
    ANTHESIS_DATE = END_OF_EAR_GROWTH_DATE + pd.DateOffset(days=ADAH)
    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
    growstages[f'{ISTAGE}']['date'] = str(ANTHESIS_DATE).split(' ')[0]
    growstages[f'{ISTAGE}']['DOY'] = int(ANTHESIS_DATE.dayofyear)
    growstages[f'{ISTAGE}']['SUMDTT'] = -99.0 #round(SUMDTT-100, 1) # TODOs: SUMDTT debe recalcularse
    growstages[f'{ISTAGE}']['DAP'] = int(DAP + ADAH)
    growstages[f'{ISTAGE}']['status'] = a_status

    # ----------------------------------------------------------------------------------------------
    # DETERMINE END OF PANNICLE GROWTH - End pannicle growth - End of Ear Growth to Start of Grain Filling
    # ----------------------------------------------------------------------------------------------
    ISTAGE = 3 # Preanthesis ear growth - CERES Stage 3.
    try:
        SUMDTT = 0.0 #SUMDTT - P2
        P3 = params['PHINT'] * 2
        #TBASE=0.0

        w = weather[weather['DATE']>END_OF_EAR_GROWTH_DATE].reset_index(drop=True)
        END_OF_PANNICLE_GROWTH_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT

                if (SUMDTT >= P3):
                    END_OF_PANNICLE_GROWTH_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_OF_PANNICLE_GROWTH_DATE - END_OF_EAR_GROWTH_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(END_OF_PANNICLE_GROWTH_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_OF_PANNICLE_GROWTH_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    growstages[f'{ISTAGE}']['status'] = 1
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(END_OF_PANNICLE_GROWTH_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("End of Pre-Anthesis Ear growth",END_OF_PANNICLE_GROWTH_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of pre-anthesis earh growth date (end of pannicle growth date).", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE BEGIN GRAIN FILLING - Grain fill - Start of Grain Filling to Maturity
    # ----------------------------------------------------------------------------------------------
    ISTAGE = 4 # Preanthesis ear growth to the beginning of grain filling - CERES Stage 4.
    try: 
        P4 = params['DSGFT'] #200 GDD # APSIM-Wheat = 120
        SUMDTT = 0.0 #SUMDTT - P3

        w = weather[weather['DATE']>=END_OF_PANNICLE_GROWTH_DATE].reset_index(drop=True)
        BEGIN_GRAIN_FILLING_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT
                if (SUMDTT >= P4):
                    BEGIN_GRAIN_FILLING_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(BEGIN_GRAIN_FILLING_DATE - END_OF_PANNICLE_GROWTH_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(BEGIN_GRAIN_FILLING_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(BEGIN_GRAIN_FILLING_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    growstages[f'{ISTAGE}']['status'] = 1
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(BEGIN_GRAIN_FILLING_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("Begining of Grain fill",BEGIN_GRAIN_FILLING_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining begin of grain fill date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE END GRAIN FILLING - Maturity
    # ----------------------------------------------------------------------------------------------
    ISTAGE = 5
    # Get SNOW, VREQ, P1V, P1D,  parameters using geographic coordinates
    m_status = 1
    if (params['bruteforce']==True and params['brute_params']!={} and 
        params['brute_params']["obsMaturityDAP"] is not None):
        # using brute force algorithms
        m_growstages, params, m_status = estimate_maturity_by_bruteforce(params)
    elif ( useDefault is True and params['longitude']!=-180.0 and params['longitude']!='' 
          and params['longitude'] is not None):
        ## using geographic coordinates and month to extract values by linear regression
        params = estimate_maturity_by_default(config, params, BEGIN_GRAIN_FILLING_DATE)
    elif (params['longitude']!=-180.0 and params['longitude']!='' and params['longitude'] is not None):
        ## using geographic coordinates
        params = estimate_maturity_by_coords(config, params)
    elif (params['genotype']!="" and params['genotype'] is not None):
        # using cultivar or genotype name
        params = estimate_maturity_by_cultivar(config, params, BEGIN_GRAIN_FILLING_DATE)

    try:
        SUMDTT = 0.0 #SUMDTT - P4
        #P5 = 430 + params['P5'] * 20 # P5 = (0.05 X TT_Maturity) - 21.5. ~500 degree-days
        P5 = params['P5'] # 400 + 5.0 * 20  

        w = weather[weather['DATE']>=BEGIN_GRAIN_FILLING_DATE].reset_index(drop=True)
        END_GRAIN_FILLING_DATE = ''
        if (len(w)>0):
            for i in range(len(w)):
                Tmin = float(w.iloc[i]['TMIN'])
                Tmax = float(w.iloc[i]['TMAX'])
                # Thermal time
                DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                               Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                               Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                SUMDTT = SUMDTT + DTT
                if (SUMDTT >= P5):
                    END_GRAIN_FILLING_DATE = w.iloc[i]['DATE']
                    CROP_AGE = str(END_GRAIN_FILLING_DATE - BEGIN_GRAIN_FILLING_DATE).replace(' days 00:00:00','')
                    DAP = DAP + int(CROP_AGE)
                    growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                    growstages[f'{ISTAGE}']['date'] = str(END_GRAIN_FILLING_DATE).split(' ')[0]
                    growstages[f'{ISTAGE}']['DOY'] = int(END_GRAIN_FILLING_DATE.dayofyear)
                    growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                    growstages[f'{ISTAGE}']['DAP'] = DAP
                    growstages[f'{ISTAGE}']['status'] = m_status
                    #if (verbose is True):
                    #    print("Thermal time reached at days duration ", i+1, str(END_GRAIN_FILLING_DATE), 
                    #          CROP_AGE, DAP, round(SUMDTT, 1))
                    break

        #if (verbose is True):
        #    print("End of Grain filling",END_GRAIN_FILLING_DATE)
    except Exception as err:
        try:
            raise StageFailed("Problem determining end of grain fill date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ----------------------------------------------------------------------------------------------
    # DETERMINE HARVEST - Harvest - End of Grain Filling or Maturity
    # ----------------------------------------------------------------------------------------------
    ISTAGE = 6  # Physiological maturity to harvest - CERES Stage 6.
    try: 
        SUMDTT = 0.0
        estimateHarvest = True
        P6 = params['P6']

        if (estimateHarvest is False):
            HARVEST = END_GRAIN_FILLING_DATE
            growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
            growstages[f'{ISTAGE}']['date'] = str(HARVEST).split(' ')[0]
            growstages[f'{ISTAGE}']['DOY'] = int(HARVEST.dayofyear)
            growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
            growstages[f'{ISTAGE}']['DAP'] = DAP
        else:
            # A value of 250 degree-days can be used to approximate the thermal time from physiological maturity to harvest
            w = weather[weather['DATE']>=END_GRAIN_FILLING_DATE].reset_index(drop=True)
            HARVEST = ''
            if (len(w)>0):
                for i in range(len(w)):
                    Tmin = float(w.iloc[i]['TMIN'])
                    Tmax = float(w.iloc[i]['TMAX'])
                    # Thermal time
                    DTT = thermal_time_calculation( snow_depth=params['SNOW'], Tmin=Tmin, Tmax=Tmax, 
                                                   Tbase=params['TT_TBASE'], Topt=params['TT_TEMPERATURE_OPTIMUM'], 
                                                   Ttop=params['TT_TEMPERATURE_MAXIMUM'])
                    SUMDTT = SUMDTT + DTT
                    if (SUMDTT >= P6):
                        HARVEST = w.iloc[i]['DATE']
                        CROP_AGE = str(HARVEST - END_GRAIN_FILLING_DATE).replace(' days 00:00:00','')
                        DAP = DAP + int(CROP_AGE)
                        growstages[f'{ISTAGE}']['AGE'] = int(CROP_AGE)
                        growstages[f'{ISTAGE}']['date'] = str(HARVEST).split(' ')[0]
                        growstages[f'{ISTAGE}']['DOY'] = int(HARVEST.dayofyear)
                        growstages[f'{ISTAGE}']['SUMDTT'] = round(SUMDTT, 1)
                        growstages[f'{ISTAGE}']['DAP'] = DAP
                        growstages[f'{ISTAGE}']['status'] = 1
                        #if (verbose is True):
                        #    print("Thermal time reached at days duration ", i+1, str(HARVEST), 
                        #          CROP_AGE, DAP, round(SUMDTT, 1))
                        break
    except Exception as err:
        try:
            raise StageFailed("Problem determining physiological maturity to harvest date.", ISTAGE, err)
        except StageFailed as x:
            print(x)
            return

    # ---------------------
    if (dispDates is True):
        try:
            if (params['bruteforce']==True):
                print("RSTG   GROWTH STAGE      DAP  DOY   CROP AGE   SUMDTT   DATE       STATUS")
                for i, k in enumerate(growstages.keys()):
                    print("{:4}   {:10} {:>10} {:>4} {:>6} {:>12} {:>12} {:>12}".format(i, growstages[k]['istage_old'], 
                                                                                 growstages[k]['DAP'],
                                                                                 growstages[k]['DOY'], 
                                                                                 growstages[k]['AGE'],
                                                                                 growstages[k]['SUMDTT'], 
                                                                                 growstages[k]['date'],
                                                                                 growstages[k]['status']
                                                                                       ))
            else:
                print("RSTG   GROWTH STAGE      DAP  DOY   CROP AGE   SUMDTT   DATE ")
                for i, k in enumerate(growstages.keys()):
                    print("{:4}   {:10} {:>10} {:>4} {:>6} {:>12} {:>12}".format(i, growstages[k]['istage_old'], 
                                                                             growstages[k]['DAP'],
                                                                             growstages[k]['DOY'], growstages[k]['AGE'],
                                                                             growstages[k]['SUMDTT'], 
                                                                             growstages[k]['date']))
        except Exception as err:
            try:
                raise StageFailed("Problem displaying results.", -99, err)
            except StageFailed as x:
                print(x)
                return

    if (dispFigPhenology is True):
        try:
            # remove anthesis to display correctly
            if ('2.5' in growstages):
                del growstages['2.5']
            drawPhenology(gs=growstages, title='Phenological growth phases of Wheat', dpi=150,
                         dispPlants=True, topDAPLabel=True, timeSpanLabel=True, topNameStageLabel=True,
                         topNameStageLabelOpt=True, copyrightLabel=True, 
                         saveFig=False, showFig=True, path_to_save_results='./', 
                         fname='Fig_1_Phenological_Phases_Wheat', fmt='jpg')
        except Exception as err:
            try:
                raise StageFailed("Problem displaying figure of phenological stages.", -99, err)
            except StageFailed as x:
                print(x)
                return
    # ---------------------
    return growstages, params

estimate_anthesis_by_bruteforce(params=None) #

Getting Anthesis date by brute force algorithm

Parameters:

Name Type Description Default
params dict

A dictionary with attributes

None

Attributes obsAnthesisDAP (int): Observed days after planting to Anthesis. sowingdate (str): Sowing date in YYYY-MM-DD format. latitude (float): Latitude of the site in celsius degrees weather (object): A table or dataframe with weather data for the site max_tries (int): Number of maximum tries to find the best value error_lim (float): Threshold to classify the observation as a good or bad adap_steps (int): Step to increase or reduce the ADAH parameters. Default 1 maxADAP (float): Threshold for the maximum value of ADAH to reach anthesis date. ADAH (int): Number of days after heading. A threshold used for anthesis date after planting. Default is 6 days after heading.

Returns:

Name Type Description
params dict

Update params dictionary with with ADAH value for Anthesis date

Source code in pywheat/pheno/__init__.py
def estimate_anthesis_by_bruteforce(params=None):
    '''Getting Anthesis date by brute force algorithm

        Parameters:
            params (dict): A dictionary with attributes

        Attributes
            obsAnthesisDAP (int): Observed days after planting to Anthesis.
            sowingdate (str): Sowing date in YYYY-MM-DD format.
            latitude (float): Latitude of the site in celsius degrees
            weather (object): A table or dataframe with weather data for the site
            max_tries (int): Number of maximum tries to find the best value
            error_lim (float): Threshold to classify the observation as a good or bad
            adap_steps (int): Step to increase or reduce the ADAH parameters. Default 1
            maxADAP (float): Threshold for the maximum value of ADAH to reach anthesis date.
            ADAH (int): Number of days after heading. A threshold used for anthesis date after planting. Default is 6 days after heading.

        Returns:
            params (dict): Update params dictionary with with ADAH value for Anthesis date

    '''
    if (params is None):
        print("Parameters not valid")
        return
    if (params['brute_params']['obsAnthesisDAP'] is None):
        print("Observed anthesis days after planting not defined")
        return
    if (params['sowing_date'] is None):
        print("Sowing date not valid")
        return
    if (params['latitude'] is None):
        print("Latitude of the site not valid")
        return
    if (params['weather'] is None):
        print("Weather data not defined")
        return
    try:
        # Setup initial parameters
        sowingdate = params['sowing_date']
        latitude = params['latitude']
        weather = params['weather']
        obsDAP = params['brute_params']['obsAnthesisDAP']
        max_tries = params['brute_params']['max_tries']
        error_lim = params['brute_params']['error_lim']
        adap_steps = params['brute_params']['adap_steps']
        maxADAP = params['brute_params']['maxADAP']
        ADAH = params['ADAH']

        growstages = determine_anthesis_stage(initparams=params)

        # loop until converge
        status = 0
        t = 0
        simDAP = int(growstages['2.5']['DAP']) 
        while True:
            if (simDAP < obsDAP):
                ADAH = ADAH + adap_steps
                #ADAH = min(maxADAP, ADAH)
            else:
                ADAH = ADAH - adap_steps
                ADAH = max(ADAH, 0.0)
            #
            new_params = dict( 
                ADAH=ADAH
            )
            params = {**params, **new_params}
            # Run simulation
            growstages = determine_anthesis_stage(initparams=params)
            #
            try:
                simDAP = int(growstages['2.5']['DAP']) # Problem with DAP = '' # not found
            except:
                status = -3
                break
            if (simDAP == obsDAP):
                status = 3
                break
            elif (ADAH > maxADAP or ADAH <= 0):
                status = -3
                break
            elif (t > max_tries):
                status = -3
                break
            t += 1

        # end while

    except Exception as err:
        print(f"Problem getting anthesis",err)

    return growstages, params, status

estimate_emergence_by_bruteforce(params=None) #

Getting Emergence date by brute force algorithm

Parameters:

Name Type Description Default
params dict

A dictionary with attributes

None

Attributes:

Name Type Description
obsEmergenceDAP int

Observed days after planting to emergence.

sowingdate str

Sowing date in YYYY-MM-DD format.

latitude float

Latitude of the site in celsius degrees

weather object

A table or dataframe with weather data for the site

max_tries int

Number of maximum tries to find the best value

error_lim float

Threshold to classify the observation as a good or bad

gdde_steps float

Step to increase or reduce the GDDE parameters. Default 1.0

maxGDDE float

Threshold for the maximum value of GDDE to reach emergence date

TT_EMERGENCE_LIMIT int

threshold for thermal time to emergence. Default is 300 degree-days#

Returns:

Name Type Description
params dict

Update params dictionary with GDDE and SDEPTH values for Emergence date using P9

Source code in pywheat/pheno/__init__.py
def estimate_emergence_by_bruteforce(params=None):
    '''Getting Emergence date by brute force algorithm

        Parameters:
            params (dict): A dictionary with attributes

        Attributes:
            obsEmergenceDAP (int): Observed days after planting to emergence.
            sowingdate (str): Sowing date in YYYY-MM-DD format.
            latitude (float): Latitude of the site in celsius degrees
            weather (object): A table or dataframe with weather data for the site
            max_tries (int): Number of maximum tries to find the best value
            error_lim (float): Threshold to classify the observation as a good or bad
            gdde_steps (float): Step to increase or reduce the GDDE parameters. Default 1.0
            maxGDDE (float): Threshold for the maximum value of GDDE to reach emergence date
            TT_EMERGENCE_LIMIT (int): # threshold for thermal time to emergence. Default is 300 degree-days

        Returns:
            params (dict): Update params dictionary with GDDE and SDEPTH values for Emergence date using P9

    '''
    if (params is None):
        print("Parameters not valid")
        return
    if (params['brute_params']['obsEmergenceDAP'] is None):
        print("Observed emergence days after planting not defined")
        return
    if (params['sowing_date'] is None):
        print("Sowing date not valid")
        return
    if (params['latitude'] is None):
        print("Latitude of the site not valid")
        return
    if (params['weather'] is None):
        print("Weather data not defined")
        return
    try:

        # Setup initial parameters
        sowingdate = params['sowing_date']
        latitude = params['latitude']
        weather = params['weather']
        obsDAP = params['brute_params']["obsEmergenceDAP"]
        max_tries = params['brute_params']['max_tries']
        error_lim = params['brute_params']['error_lim']
        gdde_steps = params['brute_params']['gdde_steps']
        maxGDDE = params['brute_params']['maxGDDE']
        TT_EMERGENCE_LIMIT = params['TT_EMERGENCE_LIMIT']
        SDEPTH = params['SDEPTH']
        GDDE = params['GDDE']
        # Run initial simulation
        growstages = determine_emergence_stage(initparams=params)
        # loop until converge
        status = 0
        t = 0
        simDAP = int(growstages['9']['DAP']) 
        while True:
            if (simDAP < obsDAP):
                GDDE = GDDE + gdde_steps
                if GDDE > 20:
                    SDEPTH = 5.0
                if GDDE > 30:
                    SDEPTH = 10.0
                if GDDE > 40:
                    SDEPTH = 15.0
                if GDDE > 50:
                    SDEPTH = 20.0
                #    SDEPTH = min(SDEPTH, 20.0)
            else:
                GDDE = GDDE - gdde_steps
                GDDE = max(GDDE, 0.0)

            new_params = dict( SDEPTH=SDEPTH, GDDE=GDDE ) # Updated parameters
            params = {**params, **new_params}
            growstages = determine_emergence_stage(initparams=params)

            try:
                simDAP = int(growstages['9']['DAP']) # Problem with DAP = '' # not found
            except:
                status = -1
                break
            if (simDAP == obsDAP):
                status = 1
                break
            elif (int(growstages['9']['SUMDTT']) > TT_EMERGENCE_LIMIT):
                status = -1
                break
            elif GDDE > maxGDDE or GDDE <= 0:
                status = -1
                break
            elif (t > max_tries):
                status = -1
                break
            t += 1

        # end while

    except Exception as err:
        print(f"Problem getting emergence by brute force",err)

    return growstages, params, status

estimate_heading_by_bruteforce(params=None) #

Getting Heading date by brute force algorithm.

This tool allows users to run the model for several parameter values to test, and then identifies which combination of parameter values results in simulated values that show the least deviations from observed values of a specified trait using root-mean-square error (RMSE) as the main criterion.

Parameters:
    params (dict): A dictionary with attributes

Attributes
    obsHeadingDAP (int): Observed days after planting to Heading.
    sowingdate (str): Sowing date in YYYY-MM-DD format.
    latitude (float): Latitude of the site in celsius degrees
    weather (object): A table or dataframe with weather data for the site
    max_tries (int): Number of maximum tries to find the best value
    error_lim (float): Threshold to classify the observation as a good or bad
    phint_steps (float): Step to increase or reduce the PHINT parameters. Default 1.0
    maxPHINT (float): Threshold for the maximum value of PHINT to reach heading date. Default value taken from DSSAT WHCER048.CUL
    TT_TDU_LIMIT (float): Threshold for thermal development units (TDU). Default 400  degree-days

Returns:
    params (dict): Update params dictionary with with SNOW, VREQ, P1V, P1D and PHINT values for Heading date
Source code in pywheat/pheno/__init__.py
def estimate_heading_by_bruteforce(params=None):
    '''Getting Heading date by brute force algorithm.

    This tool allows users to run the model for several parameter values to test, 
    and then identifies which combination of parameter values results in simulated values that show 
    the least deviations from observed values of a specified trait using root-mean-square error (RMSE) as 
    the main criterion.

        Parameters:
            params (dict): A dictionary with attributes

        Attributes
            obsHeadingDAP (int): Observed days after planting to Heading.
            sowingdate (str): Sowing date in YYYY-MM-DD format.
            latitude (float): Latitude of the site in celsius degrees
            weather (object): A table or dataframe with weather data for the site
            max_tries (int): Number of maximum tries to find the best value
            error_lim (float): Threshold to classify the observation as a good or bad
            phint_steps (float): Step to increase or reduce the PHINT parameters. Default 1.0
            maxPHINT (float): Threshold for the maximum value of PHINT to reach heading date. Default value taken from DSSAT WHCER048.CUL
            TT_TDU_LIMIT (float): Threshold for thermal development units (TDU). Default 400  degree-days

        Returns:
            params (dict): Update params dictionary with with SNOW, VREQ, P1V, P1D and PHINT values for Heading date

    '''
    if (params is None):
        print("Parameters not valid")
        return
    if (params['brute_params']['obsHeadingDAP'] is None):
        print("Observed heading days after planting not defined")
        return
    if (params['sowing_date'] is None):
        print("Sowing date not valid")
        return
    if (params['latitude'] is None):
        print("Latitude of the site not valid")
        return
    if (params['weather'] is None):
        print("Weather data not defined")
        return
    try:
        # Setup initial parameters
        sowingdate = params['sowing_date']
        latitude = params['latitude']
        weather = params['weather']
        obsDAP = params['brute_params']['obsHeadingDAP']
        max_tries = params['brute_params']['max_tries']
        error_lim = params['brute_params']['error_lim']
        phint_steps = params['brute_params']['phint_steps']
        maxPHINT = params['brute_params']['maxPHINT']
        TT_TDU_LIMIT = params['TT_TDU_LIMIT']
        SDEPTH = params['SDEPTH']
        GDDE = params['GDDE']
        SNOW = params['SNOW'] #0 
        VREQ = params['VREQ'] #505.0 
        PHINT = params['PHINT'] #95.0
        P1V = params['P1V'] #1.0 # Spring wheat
        P1D = params['P1D'] #3.675

        growstages = determine_heading_stage(initparams=params)

        # loop until converge
        status = 0
        t = 0
        simDAP = int(growstages['2']['DAP']) 
        while True:
            if (simDAP < obsDAP):
                PHINT = PHINT + phint_steps
                if PHINT > 120.0:
                    P1V = P1V + 0.25
                    P1V = min(P1V, 5.0)
            else:
                PHINT = PHINT - phint_steps
                PHINT = max(PHINT, 0.0)
            #
            new_params = dict( 
                PHINT=PHINT, P1V=P1V, P1D=P1D, VREQ=VREQ, SNOW=SNOW, #TT_TDU_LIMIT = TT_TDU_LIMIT
            )
            params = {**params, **new_params}
            # Run simulation
            growstages = determine_heading_stage(initparams=params)
            #
            try:
                simDAP = int(growstages['2']['DAP']) # Problem with DAP = '' # not found
            except:
                status = -2
                break
            if (simDAP == obsDAP):
                status = 2
                break
            elif (PHINT > maxPHINT or PHINT <= 0):
                status = -2
                break
            elif (t > max_tries):
                status = -2
                break
            t += 1

        # end while

    except Exception as err:
        print(f"Problem getting heading by brute force",err)

    return growstages, params, status

estimate_maturity_by_bruteforce(params=None) #

Getting maturity date by brute force algorithm

Parameters:

Name Type Description Default
params dict

A dictionary with attributes

None

Attributes obsMaturityDAP (int): Observed days after planting to maturity. sowingdate (str): Sowing date in YYYY-MM-DD format. latitude (float): Latitude of the site in celsius degrees weather (object): A table or dataframe with weather data for the site max_tries (int): Number of maximum tries to find the best value error_lim (float): Threshold to classify the observation as a good or bad p5_steps (float): Step to increase or reduce the P5 parameters. Default 1.0 maxP5 (float): Threshold for the maximum value of P5 to reach maturity date.

Returns:

Name Type Description
params dict

Update params dictionary with with P5 value for maturity date

Source code in pywheat/pheno/__init__.py
def estimate_maturity_by_bruteforce(params=None):
    '''Getting maturity date by brute force algorithm

        Parameters:
            params (dict): A dictionary with attributes

        Attributes
            obsMaturityDAP (int): Observed days after planting to maturity.
            sowingdate (str): Sowing date in YYYY-MM-DD format.
            latitude (float): Latitude of the site in celsius degrees
            weather (object): A table or dataframe with weather data for the site
            max_tries (int): Number of maximum tries to find the best value
            error_lim (float): Threshold to classify the observation as a good or bad
            p5_steps (float): Step to increase or reduce the P5 parameters. Default 1.0
            maxP5 (float): Threshold for the maximum value of P5 to reach maturity date.

        Returns:
            params (dict): Update params dictionary with with P5 value for maturity date

    '''
    if (params is None):
        print("Parameters not valid")
        return
    if (params['brute_params']['obsMaturityDAP'] is None):
        print("Observed maturity days after planting not defined")
        return
    if (params['sowing_date'] is None):
        print("Sowing date not valid")
        return
    if (params['latitude'] is None):
        print("Latitude of the site not valid")
        return
    if (params['weather'] is None):
        print("Weather data not defined")
        return
    try:
        # Setup initial parameters
        sowingdate = params['sowing_date']
        latitude = params['latitude']
        weather = params['weather']
        obsDAP = params['brute_params']['obsMaturityDAP']
        max_tries = params['brute_params']['max_tries']
        error_lim = params['brute_params']['error_lim']
        p5_steps = params['brute_params']['p5_steps']
        maxP5 = params['brute_params']['maxP5']
        P4 = params['DSGFT'] #200 GDD # APSIM-Wheat = 120
        P5 = params['P5'] # P5 = (0.05 X TT_Maturity) - 21.5. ~500 degree-days 

        growstages = determine_maturity_stage(initparams=params)

        # loop until converge
        status = 0
        t = 0
        simDAP = int(growstages['5']['DAP'])
        while True:
            if (simDAP < obsDAP):
                P5 = P5 + p5_steps
                #P5 = min(maxP5, P5)
            else:
                P5 = P5 - p5_steps
                P5 = max(P5, 0.0)
            #
            new_params = dict( 
                P5=P5
            )
            params = {**params, **new_params}
            # Run simulation
            growstages = determine_maturity_stage(initparams=params)
            #
            try:
                simDAP = int(growstages['5']['DAP']) # Problem with DAP = '' # not found
            except:
                status = -4
                break
            if (simDAP == obsDAP):
                status = 4
                break
            elif (P5 > maxP5 or P5 <= 0):
                status = -4
                break
            elif (t > max_tries):
                status = -4
                break
            t += 1

        # end while

    except Exception as err:
        print(f"Problem getting maturity",err)

    return growstages, params, status

photoperiod_factor(P1D=3.675, day_length=20) #

Photoperiod factor

Phenology is affected by photoperiod between emergence and floral initiation, and thermal time is affected by a photoperiod factor.

Parameters:

Name Type Description Default
P1D float

The sensitive to photoperiod (P1D) which is cultivar-specific. (1 - 6, low- high sensitive to day length)

3.675
day_length float

Day length in hours

20

Returns:

Name Type Description
DF float

A photoperiod factor

Source code in pywheat/pheno/__init__.py
def photoperiod_factor(P1D=3.675, day_length=20):
    '''
        Photoperiod factor 

        Phenology is affected by photoperiod between emergence and floral initiation, and 
        thermal time is affected by a photoperiod factor.

        Parameters:
            P1D (float): The sensitive to photoperiod (P1D) which is cultivar-specific. (1 - 6, low- high sensitive to day length)
            day_length (float): Day length in hours

        Returns:
            DF (float): A photoperiod factor

    '''
    DF = 1 - (0.002 * P1D) * (20 - day_length)**2
    return DF

snow_fall(Tmax, Rain) #

Cold weather handling routine (extracted from watbal subroutine)

Parameters:

Name Type Description Default
Rain float

Precipitation depth for current day (mm)

required
Tmax float

Maximum daily temperature (°C)

required

Returns:

Name Type Description
snow_melt float

Daily Snowmelt (mm/d)

snow float

Snow accumulation (mm)

water_available float

Water available for infiltration or runoff (rainfall plus irrigation) (mm/d)

Source code in pywheat/pheno/__init__.py
def snow_fall(Tmax, Rain):
    '''
        Cold weather handling routine (extracted from watbal subroutine)

        Parameters:
            Rain (float): Precipitation depth for current day (mm)
            Tmax (float): Maximum daily temperature (°C)

        Returns:
            snow_melt (float): Daily Snowmelt (mm/d)
            snow (float): Snow accumulation (mm)
            water_available (float): Water available for infiltration or runoff (rainfall plus irrigation) (mm/d)

    '''
    snow = 0.0
    snow_melt = 0.0
    water_available = 0.0
    if (Tmax > 1.0):
        snow_melt = Tmax + Rain * 0.4
        if (snow_melt > snow):
            snow_melt = snow
        snow = snow - snow_melt
        water_available = Rain + snow_melt
    else:
        snow = snow + Rain
    #
    return snow, snow_melt, water_available

thermal_time_calculation(m='CERES', snow_depth=0, Tmin=None, Tmax=None, Tbase=0, Topt=26, Ttop=34) #

The daily thermal time (daily_TT) or Growing degree days calculation

It's calculated from the daily average of maximum and minimum crown temperatures, and is adjusted by genetic and environments factors.

Parameters:

Name Type Description Default
m str

Name of the model. Default is 'CERES'. Options: CERES, NWHEAT, WHAPS

'CERES'
snow_depth int

Snow depth in centimeters (cm). Default value is set to zero.

0
Tmin float

Minimum Temperature (°C)

None
Tmax float

Maximum Temperature (°C)

None
Tbase float

Base temperature for development from ecotype database. Default 0°C

0
Topt float

Optimum temperature for development from species database. Default 26°C

26
Ttop float

Maximum temperature for development from species database. Default 34°C

34

Returns:

Name Type Description
dTT float

Thermal time or Growing degree days

Source code in pywheat/pheno/__init__.py
def thermal_time_calculation(m='CERES', snow_depth=0, Tmin=None, Tmax=None, Tbase=0, Topt=26, Ttop=34):
    '''
        The daily thermal time (daily_TT) or Growing degree days calculation

        It's calculated from the daily average of maximum and minimum crown temperatures, 
        and is adjusted by genetic and environments factors.

        Parameters:
            m (str): Name of the model. Default is 'CERES'. Options: CERES, NWHEAT, WHAPS
            snow_depth (int): Snow depth in centimeters (cm). Default value is set to zero.
            Tmin (float): Minimum Temperature (°C)
            Tmax (float): Maximum Temperature (°C)
            Tbase (float): Base temperature for development from ecotype database. Default 0°C
            Topt (float): Optimum temperature for development from species database. Default 26°C
            Ttop (float): Maximum temperature for development from species database. Default 34°C

        Returns:
            dTT (float): Thermal time or Growing degree days

    '''
    if (Tmin is None or Tmax is None):
        print("Check input parameters")
        return
    # Calculate Crown Temperatures
    Tcmax, Tcmin, Tcrown = crown_temperatures(snow_depth=snow_depth, Tmin=Tmin, Tmax=Tmax)
    tcdif = Tcmax - Tcmin
    dTT = Tcrown - Tbase
    if (m=='CERES'):
        if (tcdif == 0): tcdif = 1.0
        if (Tcmax < Tbase):
            dTT = 0.0
        elif(Tcmax < Topt):
            if (Tcmin < Tbase):
                tcor = (Tcmax - Tbase) / tcdif
                dTT = (Tcmax - Tbase) / 2 * tcor
            else:
                dTT = Tcrown - Tbase
        elif(Tcmax < Ttop):
            if (Tcmin < Topt):
                tcor = (Tcmax - Topt) / tcdif
                # dTT = 13. * (1 + tcor) + Tcmin/2 * (1 - tcor)
                dTT = (Topt - Tbase) / 2 * (1 + tcor) + Tcmin/2 * (1 - tcor)
            else:
                dTT = Topt - Tbase
        else:
            if (Tcmin < Topt):
                tcor = (Tcmax - Ttop) / tcdif
                # dTT = (60 - Tcmax) * tcor + Topt * (1 - tcor)
                dTT = (Topt + Ttop - Tcmax) * tcor + Topt * (1 - tcor)
                tcor =  (Topt - Tcmin) / tcdif
                dTT = dTT * (1 - tcor) + (Tcmin + Topt) / 2 * tcor
            else:
                tcor = (Tcmax - Ttop) / tcdif
                dTT = (Topt + Ttop - Tcmax) * tcor + Topt * (1 - tcor)
        #
    #elif(m=='NWHEAT'):
    #    if ((Tcrown > 0) and (Tcrown <= 26)):
    #        dTT = Tcrown
    #    elif((Tcrown > 26) and (Tcrown <= 34)):
    #        dTT = (26/8) * (34 - Tcrown)
    #    elif((Tcrown <= 0) or (Tcrown > 34)):
    #        dTT = 0

    return round(dTT, 2)

vernalization(Tcrown, Tmin, Tmax, cumvd=0) #

Calculate damage to crop due to cold weather.

Vernalization is a response to relatively cold temperatures in some species that must occur before reproductive growth will begin. For wheat, temperature above zero to about 8°C seem to be the most effective for vernalization (Ahrens & Loomis, 1963; Chujo, 1966).

Vernalization affects phenology between emergence and floral initiation. Spring-type winter cereals have little sensitivity to vernalization, which is the principal difference between them and the winter types.

In the model, if the number of vernalization days (cumvd) is less than 10 and the maximum temperature exceeds 30°C, then the number of vernalization days decreases by 0.5 days per degree above 30°C. If cumvd is greater than 10, no devernalization is calculated.

Vernalization is simulated from daily average crown temperature (Tcrown), daily maximum (Tmax) and minimum (Tmin) temperatures using the original CEREES approach.

Parameters:

Name Type Description Default
Tcrown float

daily average crown temperature (°C)

required
Tmin float

daily average minimum temperature (°C)

required
Tmax float

daily average maximum temperature (°C)

required
cumvd float

the number of vernalization days of total vernalization

0

Returns:

Name Type Description
dV float

Vernalization

Source code in pywheat/pheno/__init__.py
def vernalization(Tcrown, Tmin, Tmax, cumvd=0):
    '''
        Calculate damage to crop due to cold weather. 

        Vernalization is a response to relatively cold temperatures 
        in some species that must occur before reproductive growth will begin. 
        For wheat, temperature above zero to about 8°C seem to be the most effective 
        for vernalization (Ahrens & Loomis, 1963; Chujo, 1966).

        Vernalization affects phenology between emergence and floral initiation.
        Spring-type winter cereals have little sensitivity to vernalization, which is 
        the principal difference between them and the winter types.

        In the model, if the number of vernalization days (cumvd) is less than 10 and 
        the maximum temperature exceeds 30°C, then the number of vernalization days decreases 
        by 0.5 days per degree above 30°C. If cumvd is greater than 10, no devernalization is calculated. 

        Vernalization is simulated from daily average crown temperature (Tcrown), daily maximum (Tmax) and
        minimum (Tmin) temperatures using the original CEREES approach.

        Parameters:
            Tcrown (float): daily average crown temperature (°C)
            Tmin (float): daily average minimum temperature (°C)
            Tmax (float): daily average maximum temperature (°C)
            cumvd (float): the number of vernalization days of total vernalization

        Returns:
            dV (float): Vernalization
    '''
    # TODOs: Add threshold values as a global variables for VERN_TMIN, VERN_TMAX and CUMVD
    # Vernalization
    if( (Tmin < 15) and (Tmax > 0.0) ): #and Tmax <= 30 ISTAGE == 1 || ISTAGE == 9
        vd1 =  1.4 - 0.0778 * Tcrown
        # vd2 =  0.5 + 13.44 * ( Tcrown / ((Tmax - Tmin + 3)**2)) # wrong extract by APSIM-Wheat documentation
        vd2 =  0.5 + 13.44 / (Tmax - Tmin + 3)**2 * Tcrown # Extract by CERES Wheat 2.0 fortran code
        vd =  min(1.0, vd1, vd2)
        vd =  max(vd, 0.0)
        cumvd = cumvd + vd
    # Devernalization
    elif(Tmax > 30 and cumvd < 10): 
        cumvd = cumvd - 0.5 * (Tmax - 30)
        cumvd = max(cumvd, 0.0) 
        #cumvd = max(min(0.5 * (Tmax - 30), cumvd), 0.0)
    # ---------------------
    # VF = vernalization_factor(P1V=1.5, dV=20, ISTAGE=ISTAGE)
    #if (ISTAGE != 9):
    #    VF = 1.0 - P1V * (VREQ - cumvd) 
    #    if (VF <= 0.0):
    #        VF = 0.0
    #elif (VF > 1.0):
    #    VF = 1.0
    # ---------------------

    return cumvd

vernalization_factor(P1V=1.0, dV=50, ISTAGE=1) #

Calculation of vernalization factor.

Phenology is affected by vernalization between emergence and floral initiation, and thermal time is affected by a vernalization factor.

Parameters:

Name Type Description Default
P1V float

The sensitive to vernalization (P1V) which is cultivar-specific. 1 for spring type, 5 for winter type

1.0
dV float

The total vernalization.

50

Returns:

Name Type Description
VF float

A vernalization factor

Source code in pywheat/pheno/__init__.py
def vernalization_factor(P1V=1.00, dV=50, ISTAGE=1):
    '''
        Calculation of vernalization factor.

        Phenology is affected by vernalization between emergence and floral initiation, and 
        thermal time is affected by a vernalization factor.

        Parameters:
            P1V (float): The sensitive to vernalization (P1V) which is cultivar-specific. 1 for spring type, 5 for winter type
            dV (float): The total vernalization. 

        Returns:
            VF (float): A vernalization factor

    '''
    # Set genetic coefficients to appropriate units
    #VSEN = params['P1V'] * 0.0054545 + 0.0003 
    # VF = 1 - VSEN * (50 - CUMVD)
    if (ISTAGE==1): #or ISTAGE==2
        VF = 1 - (0.0054545 * P1V  + 0.0003) * ( 50 - dV )
        VF = max(min(VF, 1.0), 0.0)
    else:
        VF = 1.0
    return VF