CanopyAnalysis.py 22.5 KB
Newer Older
1
2

import pandas as pd
luroth's avatar
luroth committed
3
from datetime import datetime, timedelta
4
5
6
7
8
9
10
11
import numpy as np
from pathlib import Path
import imageio
from scipy import ndimage as ndi
from skimage.feature import peak_local_max
from scipy.ndimage.measurements import center_of_mass, label
from skimage.morphology import watershed
from scipy.sparse import csr_matrix
12
import math
luroth's avatar
cleanup    
luroth committed
13

luroth's avatar
luroth committed
14
from matplotlib import pyplot as plt
luroth's avatar
luroth committed
15
16
from skimage.morphology import disk
from skimage.filters import rank
17

luroth's avatar
luroth committed
18
from sklearn import svm
luroth's avatar
luroth committed
19
from sklearn.preprocessing import StandardScaler
luroth's avatar
luroth committed
20

luroth's avatar
luroth committed
21
# Helper functions
22

luroth's avatar
luroth committed
23
def tiller_prediction(LA, GDD_BBCH30):
luroth's avatar
luroth committed
24
25
26
27
28
29
30
31
32
33
    """
    Predicts tiller count pased on multi-view leaf area
    :param LA: Multi-view leaf area, scaled to plot size of 125 * 50 * 3 mm
    :param GDD: Growing degree days since sowing
    :return: Estimation of tiller count
    """

    #Asym: Model was fit to plot size of 125 * 50 * 3 (mm)
    Asym = 125 * 50 * 3

luroth's avatar
luroth committed
34
35
36
    # xmid and scal: Dependend on GDD_BBCH30, empirical estimation with 2018/2019 data
    xmid = 3.39 + GDD_BBCH30 * -0.00417
    scal = 0.877 + GDD_BBCH30 * 0.00302
luroth's avatar
luroth committed
37

luroth's avatar
luroth committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    # Dependence leaf area to tiller count:
    # LA ~ SSlogis(log(tiller_count+1), 125 * 50 * 3, xmid, scal)

    # Solving for tiller_count:

    # LA ~ Asym / (1 + exp((xmid - log(x+1) )/scal))
    # y ~  a    / (1 + exp((m -    log(x+1) )/s))
    # Wolframalpha tells me:
    # solve(y =  a    / (1 + exp((m -    log(x+1) )/s)), x)
    # x = (a/y - 1)^(-s) (e^m - (a/y - 1)^s)
    # Therefore:
    tiller_count = (Asym / LA - 1)**(-scal) * (math.exp(xmid) - (Asym / LA - 1) ** scal)

    return(tiller_count)


luroth's avatar
luroth committed
54
def plant_prediction(image, delta_to_BBCH30, GSD):
luroth's avatar
luroth committed
55
56
57
58
59
60
    """
    Extracts plant regions (number and size) using local maxima and watershed
    :param image: Multi-view leaf area image from plot in BBCH31 / ~ GDD 470-490 stage
    :return: Total plant count, individual sizes of regions
    """

luroth's avatar
luroth committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    if delta_to_BBCH30 == 15:
        w_intercept = 1.4
        w_slope = 0.000855
        gc_intercept = 4.2
        gc_slope = 0.000547


    elif delta_to_BBCH30 == 10:
        w_intercept = 0.99
        w_slope = 0.000755
        gc_intercept = 3.8
        gc_slope = 0.000473

    elif delta_to_BBCH30 == 5:
        w_intercept = 0.18
        w_slope = 0.000471
        gc_intercept = 2
        gc_slope = 0.000352
    else:
        print("Delta to BBCH30", delta_to_BBCH30, " not implemented, must be in [5, 10, 15]")


luroth's avatar
luroth committed
83
    # Minimal distance between two adjacent local maxima
luroth's avatar
luroth committed
84
    min_distance_local_peaks = 15
luroth's avatar
luroth committed
85
    # Minimum intensity of pixel to become considered as local maxima
luroth's avatar
luroth committed
86
    min_intensity_local_peaks = 0.1
luroth's avatar
luroth committed
87
    # Minimum intensity of pixel to count as part of watershed area
luroth's avatar
luroth committed
88
    min_intensity_watershed_area = 0.50
luroth's avatar
luroth committed
89
90
91
92
93
94
95
96

    # Smooth with mean
    selem = disk(min_distance_local_peaks)
    image_smoothed = rank.mean(image, selem=selem)

    # Calc local maxima
    local_maxima = peak_local_max(image_smoothed, min_distance=min_distance_local_peaks, indices=False,
                                  threshold_abs=int(min_intensity_local_peaks*255), exclude_border=int(min_distance_local_peaks))
97
98

    local_maxima_labels, n_max = label(local_maxima)
luroth's avatar
luroth committed
99
100
    # Merge adjacent local maxima
    local_maxima_merged = np.round(center_of_mass( local_maxima, local_maxima_labels, range(1, n_max+1) ))
101

luroth's avatar
luroth committed
102
    if len(local_maxima_merged)>0:
103

luroth's avatar
luroth committed
104
105
106
        # Extract watershed regions
        # Create numbered labels for local maxima
        local_maxima_labels = csr_matrix((np.arange(local_maxima_merged.shape[0])+1, (local_maxima_merged[:, 0], local_maxima_merged[:, 1])),
107
108
                                         shape=image.shape).toarray()

luroth's avatar
luroth committed
109
110
        # Do watershed with min intensity limit
        watershed_labels = watershed(-image_smoothed, local_maxima_labels, mask=image>min_intensity_watershed_area*255)
111

luroth's avatar
luroth committed
112
113
        # Summarize area per watershed label
        area_watershed_labels, area_watershed_label_counts = np.unique(watershed_labels, return_counts=True)
114

luroth's avatar
luroth committed
115
116
        # Remove size of zone "0" (ground)
        area_watershed_label_counts = area_watershed_label_counts[1:]
117
118

    else:
luroth's avatar
luroth committed
119
120
121
        area_watershed_label_counts = []

    a_area_watershed_label_counts = np.array(area_watershed_label_counts)
122

luroth's avatar
luroth committed
123
124
125
126
127
128
129
130
    w_plant_counts = np.round(a_area_watershed_label_counts * w_slope + w_intercept)
    w_plant_count_total = np.sum(w_plant_counts)

    # Extract ground coverage > 50, normalize to 3 microplots (divide by sampling area, multiply by 3-microplot-area)
    a_area_gc50 = ( np.sum(image>255 * 0.5) ) / (image.shape[0] * image.shape[1] * (GSD*1000)**2) * (150 * 150)
    # Calculate plant counts
    gc_plant_counts_total = a_area_gc50 * gc_slope + gc_intercept
    gc_plant_counts_total = gc_plant_counts_total / (150 * 150) * (image.shape[0] * image.shape[1] * (GSD*1000)**2)
131

luroth's avatar
luroth committed
132
    return(w_plant_count_total, gc_plant_counts_total)
133
134


luroth's avatar
luroth committed
135
def process_plant_count(path_campaign, delta_to_BBCH30,
luroth's avatar
luroth committed
136
                        GSD):
luroth's avatar
luroth committed
137
138
139
140
141
142
    """
    Process folder to perform plant count estimation
    :param path_campaign: path of campaigns
    :param campaign_date: Date of campaign
    """

luroth's avatar
luroth committed
143
    print("Process campaign ", path_campaign)
luroth's avatar
luroth committed
144

luroth's avatar
luroth committed
145
146
147
    # Container for results
    plant_counts = {}

luroth's avatar
luroth committed
148
    campaign_date = path_campaign.parts[-2]
luroth's avatar
luroth committed
149

luroth's avatar
luroth committed
150
    path_GC_AC_folder = path_campaign / 'GC_AC'
luroth's avatar
luroth committed
151

luroth's avatar
luroth committed
152
    LA_images = sorted(path_GC_AC_folder.glob('*_?????????*.tif'))
luroth's avatar
luroth committed
153

luroth's avatar
luroth committed
154
155
    for LA_image in LA_images:
        parts = LA_image.name.split("_")
luroth's avatar
luroth committed
156
157
158
159
        if (len(parts) == 2):
            design_label = parts[0]
            plot_label = parts[1][:-4]
        elif (len(parts) == 3):
luroth's avatar
luroth committed
160
161
162
163
164
165
            design_label = parts[0] + "_" + parts[1]
            plot_label = parts[2][:-4]
        elif (len(parts) == 4):
            design_label = parts[0] + "_" + parts[1]
            plot_label = parts[2] + "_" + parts[3][:-4]
        else:
luroth's avatar
luroth committed
166
            raise Exception("Do not know how to parse name " + LA_image.name + " with n parts: " + str(len(parts)))
luroth's avatar
luroth committed
167

luroth's avatar
luroth committed
168
        print("Process LA image for plot", plot_label)
169

luroth's avatar
luroth committed
170
        LA_img = imageio.imread(LA_image)
171

luroth's avatar
luroth committed
172
        w_counts, gc_counts = plant_prediction(LA_img, delta_to_BBCH30, GSD)
173

luroth's avatar
luroth committed
174
175
176
        # plant count estimation is absolut number, divide by sampling area size in mm^2
        w_counts_scaled = round(w_counts  / (LA_img.shape[0] * LA_img.shape[1] * (GSD)**2))
        gc_counts_scaled = round(gc_counts / (LA_img.shape[0] * LA_img.shape[1] * (GSD) ** 2))
177

luroth's avatar
luroth committed
178
        print("Plants: w:", w_counts_scaled, "gc: ", gc_counts_scaled, "per m²")
luroth's avatar
luroth committed
179

luroth's avatar
luroth committed
180
181
182
183
184
185
186
187
        plant_counts_ = {}
        plant_counts_['plot_label'] = plot_label
        plant_counts_['campaign_date'] = campaign_date
        plant_counts_['watershed_plant_count_estimation'] = w_counts_scaled
        plant_counts_['watershed_plant_count_estimation_abs'] = w_counts
        plant_counts_['groundcoverage_plant_count_estimation'] = gc_counts_scaled
        plant_counts_['groundcoverage_plant_count_estimation_abs'] = gc_counts
        plant_counts_['delta'] = delta_to_BBCH30
luroth's avatar
luroth committed
188

luroth's avatar
luroth committed
189
190
        if design_label not in plant_counts:
            plant_counts[design_label] = []
luroth's avatar
luroth committed
191

luroth's avatar
luroth committed
192
        plant_counts[design_label].append(plant_counts_)
luroth's avatar
luroth committed
193

luroth's avatar
luroth committed
194
    path_trait_csvs = path_campaign / 'trait_csvs'
luroth's avatar
SE    
luroth committed
195
    path_trait_csvs.mkdir(exist_ok=True)
196

luroth's avatar
luroth committed
197
198
199
    for design_label, plant_region_data_ in plant_counts.items():
        print("Write plant region trait csv for", design_label)

luroth's avatar
luroth committed
200
201
        df_regions_w = pd.DataFrame(plant_region_data_)
        df_regions_gc = pd.DataFrame(plant_region_data_)
luroth's avatar
luroth committed
202

luroth's avatar
luroth committed
203
204
205
        # watershed data
        df_regions_w['trait'] = "PntDen"
        df_regions_w['trait_id'] = 1
luroth's avatar
SE    
luroth committed
206
        df_regions_w['value'] = df_regions_w['watershed_plant_count_estimation']
luroth's avatar
luroth committed
207

luroth's avatar
SE    
luroth committed
208
        df_regions_w['timestamp'] = pd.to_datetime(df_regions_w['campaign_date'], format="%Y%m%d")
luroth's avatar
luroth committed
209

luroth's avatar
luroth committed
210
211
212
213
214
        df_regions_w.to_csv(path_trait_csvs / (design_label + "_watershed_plants.csv"), index=False)

        # GC data
        df_regions_gc['trait'] = "PntDen"
        df_regions_gc['trait_id'] = 1
luroth's avatar
SE    
luroth committed
215
        df_regions_gc['value'] = df_regions_gc['groundcoverage_plant_count_estimation']
luroth's avatar
luroth committed
216

luroth's avatar
SE    
luroth committed
217
        df_regions_gc['timestamp'] = pd.to_datetime(df_regions_gc['campaign_date'], format="%Y%m%d")
luroth's avatar
luroth committed
218
219

        df_regions_gc.to_csv(path_trait_csvs / (design_label + "_gc_plants.csv"), index=False)
luroth's avatar
luroth committed
220

luroth's avatar
luroth committed
221

luroth's avatar
luroth committed
222
223

def process_tiller_count(path_campaign, GSD, path_BBCH30_estimation = None,
luroth's avatar
luroth committed
224
225
226
                         paths_BBCH30_measured = None):

    print("Process campaigns ", path_campaign)
luroth's avatar
luroth committed
227

luroth's avatar
luroth committed
228
    campaign_date = path_campaign.parts[-2]
luroth's avatar
luroth committed
229

luroth's avatar
luroth committed
230
    campaign_date_long = campaign_date[0:4] + "-" + campaign_date[4:6] + "-" + campaign_date[6:8]
luroth's avatar
luroth committed
231

luroth's avatar
luroth committed
232
    # Read GDD
233
234
235
236
    path_GDD_csv = path_campaign.parent.parent / 'covariates' / 'GDD.csv'
    df_GDDs = pd.read_csv(path_GDD_csv)
    GDD = df_GDDs.loc[df_GDDs.campaign_date == campaign_date_long, 'GDD'].values[0]

luroth's avatar
luroth committed
237
238
239
    # Read BBCH30 estimation
    if path_BBCH30_estimation is not None:
        BBCH30_estimation_files = sorted(path_BBCH30_estimation.glob('*_BBCH30.csv'))
240

luroth's avatar
luroth committed
241
242
243
244
245
246
        BBCH30_estimations = {}
        for BBCH30_estimation_file in BBCH30_estimation_files:
            df_BBCH30_estimation = pd.read_csv(BBCH30_estimation_file)
            # Join with GDD to get delta to BBCH30 in GDD
            df_BBCH30 = df_BBCH30_estimation[df_BBCH30_estimation.value == 30]
            df_BBCH30 = df_BBCH30.sort_values(by=['timestamp']).groupby("plot_label").first()
luroth's avatar
luroth committed
247
            # TODO: Something is very buggy with the label here...
luroth's avatar
luroth committed
248
249
            df_GGD_at_BBCH30 = pd.merge(df_BBCH30, df_GDDs, left_on="timestamp", right_on="campaign_date")
            df_GGD_at_BBCH30['GDD_BBCH30'] = GDD - df_GGD_at_BBCH30.GDD
250

luroth's avatar
luroth committed
251
            design_label = BBCH30_estimation_file.name[:-11]
252

luroth's avatar
luroth committed
253
254
            if design_label not in BBCH30_estimations:
                BBCH30_estimations[design_label] = []
255

luroth's avatar
luroth committed
256
            BBCH30_estimations[design_label].append(df_GGD_at_BBCH30.to_dict('records'))
luroth's avatar
luroth committed
257
258
    
    df_BBCH30_estimations = pd.DataFrame.from_records(BBCH30_estimations)
259

luroth's avatar
luroth committed
260
261
    # Read BBCH30 measurement
    if paths_BBCH30_measured is not None:
262

luroth's avatar
luroth committed
263
264
265
        BBCH30_measurements = []
        for path_BBCH30_measured in paths_BBCH30_measured:
            df_BBCH30_measured = pd.read_csv(path_BBCH30_measured)
266

luroth's avatar
luroth committed
267
268
269
            # Join with GDD to get delta to BBCH30 in GDD
            df_BBCH30 = df_BBCH30_measured[df_BBCH30_measured.value== 30]
            df_BBCH30 = df_BBCH30.sort_values(by=['timestamp']).groupby("plot_label").first()
270

luroth's avatar
luroth committed
271
272
            df_GGD_at_BBCH30 = pd.merge(df_BBCH30, df_GDDs, left_on="timestamp", right_on="campaign_date")
            df_GGD_at_BBCH30['GDD_BBCH30'] = GDD - df_GGD_at_BBCH30.GDD
273

luroth's avatar
luroth committed
274
            BBCH30_measurements.append(df_GGD_at_BBCH30.to_dict('records'))
luroth's avatar
luroth committed
275
276
            
    df_BBCH30_measurements = pd.concat(BBCH30_measurements)
277

luroth's avatar
luroth committed
278
    # Read LA and calc tiller estimation
luroth's avatar
luroth committed
279
    path_trait_csvs = path_campaign / 'trait_csvs'
luroth's avatar
luroth committed
280
281
    LA_files = path_trait_csvs.glob("*_LA.csv")
    df_LA.to_csv(path_trait_csvs / (design_label + "_LA.csv"), index=False)
luroth's avatar
luroth committed
282

luroth's avatar
luroth committed
283
284
285
    for design_label, LA in LA_data.items():
        print("Write tiller trait csv for", design_label)
        df_ = pd.DataFrame(LA)
luroth's avatar
luroth committed
286

luroth's avatar
luroth committed
287
288
289
        df_['trait'] = "PltTilDen"
        df_['trait_id'] = 34
        df_['value'] = df_['tiller_estimation']
290

luroth's avatar
luroth committed
291
        df_['timestamp'] = datetime.strptime(campaign_date, "%Y%m%d")
292

luroth's avatar
luroth committed
293
        df_.to_csv(path_trait_csvs / (design_label + "_tillers.csv"), index=False)
294

luroth's avatar
luroth committed
295

296

luroth's avatar
luroth committed
297
def process_NadirCC_LCCC_LA_BBCH30(path_campaign, GSD):
luroth's avatar
luroth committed
298

luroth's avatar
luroth committed
299
    campaign_date = path_campaign.parts[-2]
luroth's avatar
luroth committed
300

luroth's avatar
luroth committed
301
302
303
    # Trains SVM
    df_training = pd.read_csv('./GroundAerialCoverage/svm_SE_training.csv')
    features_col = [col for col in df_training if col.startswith('gt_bin')]
luroth's avatar
luroth committed
304
305
306

    sc_x = StandardScaler()

luroth's avatar
luroth committed
307
    X = df_training[features_col]
luroth's avatar
luroth committed
308
309
310
    sc_x.fit(X)
    X = sc_x.transform(X)

luroth's avatar
luroth committed
311
312
    # Log delta to weight close-to-zero values higher
    y = np.log(np.abs(df_training['delta_to_BBCH']) + 1) * np.sign(df_training['delta_to_BBCH'])
luroth's avatar
luroth committed
313

luroth's avatar
luroth committed
314
    svm_predictor = svm.SVR(C=32, kernel='rbf', gamma = 0.125, epsilon = 0.1)
luroth's avatar
luroth committed
315
316
    svm_predictor.fit(X, y)

luroth's avatar
luroth committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
    print("Process campaign ", path_campaign)

    # Read / calc traits

    path_GC_AC_folder = path_campaign / 'GC_AC'
    path_trait_csvs = path_campaign / 'trait_csvs'

    ## CC based on nadir image
    CC_files = sorted(path_GC_AC_folder.glob('*_canopy_coverages.csv'))
    for CC_file in CC_files:
        design_label = CC_file.name[:-21]
        print("Process CC nadir file for design", design_label)

        df_CC = pd.read_csv(CC_file)
        df_CC_soil = df_CC.loc[df_CC.type == 'soil']
luroth's avatar
luroth committed
332
        # Select max zenith angle (in radian) -> most nadir view
luroth's avatar
luroth committed
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
        df_CC_nadir = df_CC_soil.loc[df_CC_soil.groupby('plot_label').zenith_angle.idxmax()]

        df_CC_nadir['value_json'] = df_CC_nadir.apply(lambda row: row.iloc[1:].to_json(), axis=1)

        df_CC_nadir['trait'] = "CnpCov"
        df_CC_nadir['trait_id'] = 38
        df_CC_nadir['value'] = df_CC_nadir['canopy_coverage']

        df_CC_nadir['timestamp'] =  datetime.strptime(campaign_date, "%Y%m%d")

        df_CC_nadir.to_csv(path_trait_csvs / (design_label + "_CC_nadir.csv"), index=False)

    # CC based on LC/CC model
    CC_LC_files = sorted(path_GC_AC_folder.glob('*_CC_LC.csv'))

    for CC_LC_file in CC_LC_files:
        design_label = CC_LC_file.name[:-10]
        print("Process CC LC file for design", design_label)

luroth's avatar
luroth committed
352
        # Read file in LC_CC folder and convert to trait file
luroth's avatar
luroth committed
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
        df_CC_LC = pd.read_csv(CC_LC_file)
        df_CC_LC['value_json'] = df_CC_LC.apply(lambda row: row.iloc[1:].to_json(), axis=1)

        df_CC_LC['trait'] = "CnpCov"
        df_CC_LC['trait_id'] = 38
        df_CC_LC['value'] = df_CC_LC['CC']

        df_CC_LC['timestamp'] = datetime.strptime(campaign_date, "%Y%m%d")

        df_CC_LC.to_csv(path_trait_csvs / (design_label + "_CC_LC.csv"), index=False)

    # LA
    # Container for results
    LA_data = {}
    plant_region_data = {}

    LA_images = sorted(path_GC_AC_folder.glob('*_?????????*.tif'))

    for LA_image in LA_images:
        parts = LA_image.name.split("_")
        if(len(parts)==3):
luroth's avatar
cleanup    
luroth committed
374
375
376
            if parts[1] == "lp01":
                print(LA_image, " is lp01 overview image, skip")
                continue
luroth's avatar
luroth committed
377
378
379
380
381
382
383
384
385
386
387
            design_label = parts[0] + "_" + parts[1]
            plot_label = parts[2][:-4]
        elif(len(parts)==2):
            design_label = parts[0]
            plot_label = parts[1][:-4]
        elif (len(parts) == 4):
            design_label = parts[0] + "_" + parts[1]
            plot_label = parts[2] + "_" + parts[3][:-4]
        else:
            raise Exception("Do not know how to parse name " + LA_image.name)

luroth's avatar
cleanup    
luroth committed
388

luroth's avatar
luroth committed
389
390
391
392
393
394
395
396
        print("Process LA image for plot", plot_label)

        LA_img = imageio.imread(LA_image)

        # Convert to fraction
        LA_img = LA_img / 255.0
        # Square
        LA_img_powered = np.power(LA_img, 2)
luroth's avatar
luroth committed
397
398

        gt_bins = {}
luroth's avatar
luroth committed
399
        for gt_bin in np.arange(start=0, stop=100, step=1):
luroth's avatar
luroth committed
400
            gt_bins[gt_bin] = np.sum(LA_img > gt_bin/100) / (LA_img.shape[0] * LA_img.shape[1])
luroth's avatar
luroth committed
401

luroth's avatar
luroth committed
402
403
404
405
406
407
408
409
410
411
412
        # normalize
        gt_bins_norm = {}
        for gt_bin in np.arange(start=0, stop=100, step=10):
            sum_a = np.sum([val for val in gt_bins.values()])
            if sum_a != 0:
                gt_bins_norm[gt_bin] = gt_bins[gt_bin] / sum_a
            else:
                gt_bins_norm[gt_bin] = 0
        # check normalization:
        #np.sum([val for val in gt_bins_norm.values()])

luroth's avatar
luroth committed
413
414
415
416
417
418
419
420
421
        # Calc LA and aerial index
        LA = np.sum(LA_img_powered)

        LA_data_ = {}
        LA_data_['plot_label'] = plot_label
        LA_data_['campaign_date'] = campaign_date

        # LA is absolut, divide by sampling area size in mm^2
        LA_data_['LA'] = LA / (LA_img.shape[0] * LA_img.shape[1] * (GSD*1000)**2)
luroth's avatar
luroth committed
422
        LA_data_['gt_bins'] = gt_bins
luroth's avatar
luroth committed
423
        LA_data_['gt_bins_norm'] = gt_bins_norm
luroth's avatar
luroth committed
424
425
426
427
428
429

        if design_label not in LA_data:
            LA_data[design_label] = []

        LA_data[design_label].append(LA_data_)

luroth's avatar
luroth committed
430
    # Write trait files
luroth's avatar
luroth committed
431
432
433
    for design_label, LA in LA_data.items():
        print("Write LA trait csv for", design_label)
        df_LA = pd.DataFrame(LA)
luroth's avatar
luroth committed
434
        df_LA['value_json'] = ""
luroth's avatar
luroth committed
435
436
437
438
439
440
441
442
443
444

        df_LA['trait'] = "PltLA"
        df_LA['trait_id'] = 39
        df_LA['value'] = df_LA['LA']

        df_LA['timestamp'] = datetime.strptime(campaign_date, "%Y%m%d")

        df_LA.to_csv(path_trait_csvs / (design_label + "_LA.csv"), index=False)

    for design_label, LA in LA_data.items():
luroth's avatar
luroth committed
445
        print("Write bbch30 trait csv for", design_label)
luroth's avatar
luroth committed
446
        df_LA = pd.DataFrame(LA)
luroth's avatar
luroth committed
447
        df_LA['value_json'] = ""
luroth's avatar
luroth committed
448

luroth's avatar
luroth committed
449
        df_LA['trait'] = "PltSE"
luroth's avatar
luroth committed
450
        df_LA['trait_id'] = 41
luroth's avatar
luroth committed
451

luroth's avatar
luroth committed
452
        X = [list(d.values()) for d in df_LA['gt_bins_norm']]
luroth's avatar
luroth committed
453

luroth's avatar
luroth committed
454
        value = -svm_predictor.predict(sc_x.transform(X))
luroth's avatar
luroth committed
455
        value = (np.exp(value) + 1) * np.sign(value)
luroth's avatar
luroth committed
456
457

        df_LA['value'] = value
luroth's avatar
luroth committed
458
459
460
461
462
463

        df_LA['timestamp'] = datetime.strptime(campaign_date, "%Y%m%d")

        df_LA.to_csv(path_trait_csvs / (design_label + "_AI.csv"), index=False)


luroth's avatar
luroth committed
464
### TODO: Dynamic traits, should be based on spatial corrected values from DB
luroth's avatar
luroth committed
465

luroth's avatar
luroth committed
466

luroth's avatar
luroth committed
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
def process_plant_count_dynamics(path_campaign_date_5,
                                 path_campaign_date_10,
                                 path_campaign_date_15,
                                 GSD):
    """
    Process folder to perform plant count estimation
    :param path_campaign: path of campaigns
    :param campaign_date: Date of campaign
    """

    print("Process campaigns ", path_campaign_date_5, path_campaign_date_10)

    paths = {5: path_campaign_date_5,
             10: path_campaign_date_10,
             15: path_campaign_date_15}

    # Container for results
    plant_counts = {}

    for delta, path_campaign in paths.items():

        campaign_date = path_campaign.parts[-2]

        path_trait_csvs = path_campaign / 'trait_csvs'

        plant_count_trait_files = sorted(path_GC_AC_folder.glob('*_?????????*.tif'))

        for LA_image in LA_images:
            parts = LA_image.name.split("_")
            if (len(parts) == 3):
                design_label = parts[0] + "_" + parts[1]
                plot_label = parts[2][:-4]
            elif (len(parts) == 4):
                design_label = parts[0] + "_" + parts[1]
                plot_label = parts[2] + "_" + parts[3][:-4]
            else:
                Exception("Do not know how to parse name " + LA_image.name)

            print("Process LA image for plot", plot_label)

            LA_img = imageio.imread(LA_image)

            w_counts, gc_counts = plant_prediction(LA_img, delta, GSD)

            # plant count estimation is absolut number, divide by sampling area size in mm^2
            w_counts_scaled = round(w_counts / (LA_img.shape[0] * LA_img.shape[1] * (GSD) ** 2))
            gc_counts_scaled = round(gc_counts / (LA_img.shape[0] * LA_img.shape[1] * (GSD) ** 2))

            print("Plants: w:", w_counts_scaled, "gc: ", gc_counts_scaled, "per m²")

            plant_counts_ = {}
            plant_counts_['plot_label'] = plot_label
            plant_counts_['campaign_date'] = campaign_date
            plant_counts_['watershed_plant_count_estimation'] = w_counts_scaled
            plant_counts_['watershed_plant_count_estimation_abs'] = w_counts
            plant_counts_['groundcoverage_plant_count_estimation'] = gc_counts_scaled
            plant_counts_['groundcoverage_plant_count_estimation_abs'] = gc_counts
            plant_counts_['delta'] = delta

            if design_label not in plant_counts:
                plant_counts[design_label] = []

            plant_counts[design_label].append(plant_counts_)

    path_trait_csvs = path_campaign_date_10.parent.parent / 'trait_csvs'
    path_trait_csvs.mkdir(exist_ok=True)

    for design_label, plant_region_data_ in plant_counts.items():
        print("Write plant region trait csv for", design_label)

        df_regions = pd.DataFrame(plant_region_data_)

        idx_w = df_regions.groupby(['plot_label'])['watershed_plant_count_estimation_abs'].transform(np.median) == \
                df_regions['watershed_plant_count_estimation_abs']
        df_regions_w = df_regions[idx_w].copy()

        idx_gc = df_regions.groupby(['plot_label'])['groundcoverage_plant_count_estimation'].transform(np.median) == \
                 df_regions['groundcoverage_plant_count_estimation']
        df_regions_gc = df_regions[idx_gc].copy()

        # watershed data
        df_regions_w['trait'] = "PntDen"
        df_regions_w['trait_id'] = 1
        df_regions_w['value'] = df_regions_w['watershed_plant_count_estimation']

        df_regions_w['timestamp'] = pd.to_datetime(df_regions_w['campaign_date'], format="%Y%m%d")

        df_regions_w.to_csv(path_trait_csvs / (design_label + "_watershed_plants.csv"), index=False)

        # GC data
        df_regions_gc['trait'] = "PntDen"
        df_regions_gc['trait_id'] = 1
        df_regions_gc['value'] = df_regions_gc['groundcoverage_plant_count_estimation']

        df_regions_gc['timestamp'] = pd.to_datetime(df_regions_gc['campaign_date'], format="%Y%m%d")

        df_regions_gc.to_csv(path_trait_csvs / (design_label + "_gc_plants.csv"), index=False)


def process_tiller_dynamics():
    if GDD >= 400 and GDD <= 600:
        for design_label, LA in LA_data.items():
            print("Write tiller rate trait csv for", design_label)

            df_ = pd.DataFrame(LA)

            # get plant counts
            df_plant_counts_ = pd.DataFrame(plant_counts[design_label][0])
            df_plant_counts_ = df_plant_counts_[['plot_label', 'value']].copy()
            df_plant_counts_.columns = ['plot_label', 'plant_count_estimate']

            df_  = pd.merge(df_, df_plant_counts_, on="plot_label")

            df_['trait'] = "PntShtDen"
            df_['trait_id'] = 40
            df_['value'] = df_['tiller_estimation'] / df_['plant_count_estimate']

            df_['timestamp'] = datetime.strptime(campaign_date, "%Y%m%d")

            df_.to_csv(path_trait_csvs / (design_label + "_tiller_rates.csv"), index=False)
            

    # Read plant counts for later calculation of tiller rate per plant
    plant_count_files = sorted(path_plant_count_estimation.glob('*_plants.csv'))

    plant_counts = {}
    for plant_count_file in plant_count_files:
        df_plant_counts = pd.read_csv(plant_count_file)
        design_label = plant_count_file.name[:-11]

        if design_label not in plant_counts:
            plant_counts[design_label] = []

        plant_counts[design_label].append(df_plant_counts.to_dict('records'))

luroth's avatar
luroth committed
602
603


luroth's avatar
luroth committed
604
605
606
def clean_trait_folder(path_campaign, patterns):
    path_trait_csvs = path_campaign / 'trait_csvs'

luroth's avatar
luroth committed
607
608
609
610
611
612
613
614
615
616
617
    files = []
    for pattern in patterns:
        files.extend(path_trait_csvs.glob(pattern))

    for file in files:
        print("deleting", file)
        file.unlink()

def clean_main_folder(path_campaign, patterns):
    path_trait_csvs = path_campaign

luroth's avatar
luroth committed
618
619
    files = []
    for pattern in patterns:
luroth's avatar
luroth committed
620
        files.extend(path_trait_csvs.glob(pattern))
luroth's avatar
luroth committed
621

luroth's avatar
luroth committed
622
623
624
    for file in files:
        print("deleting", file)
        file.unlink()