-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript_module.py
1720 lines (1444 loc) · 80.6 KB
/
script_module.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Name: script_module.py
Label: Set up longitudinal data, impute missing values, and apply valuation.
Summary: ThorNoe.GitHub.io/GreenGDP explains the overall approach and methodology.
Rqmts: ArcGIS Pro 3.2 or later must be installed on the system.
Usage: This module supports script.py and WaterbodiesScriptTool in gis.tbx.
See GitHub.com/ThorNoe/GreenGDP for instructions to run or update it all.
Functions: The class in this module contains 13 functions of which some are nested:
- get_data(), get_fc_from_WFS(), map_book(), and values_by_catchment_area() are standalone functions.
- observed_indicator() calls:
- longitudinal()
- impute_missing() calls:
- ecological_status(), which calls:
- indicator_to_status()
- missing_values_graph()
- decompose() calls:
- valuation(), which calls:
- BT()
Descriptions can be seen under each function.
License: MIT Copyright (c) 2025
Author: Thor Donsby Noe
"""
import os
import sys
import traceback
import urllib.request
import arcpy
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from cycler import cycler
from scipy import interpolate
from sklearn.experimental import enable_iterative_imputer # noqa
from sklearn.impute import IterativeImputer
class Water_Quality:
"""Class for all data processing and mapping functions"""
def __init__(
self,
yearFirst,
yearLast,
dataFilenames,
linkageFilenames,
WFS_ServiceURL,
WFS_featureClassNames,
WFS_fieldsInFeatureClass,
WFS_replaceFeatureClasses,
keepGeodatabase,
):
self.year_first = yearFirst
self.year_last = yearLast
self.years = list(range(yearFirst, yearLast + 1))
self.data = dataFilenames
self.linkage = linkageFilenames
self.wfs_service = WFS_ServiceURL
self.wfs_fc = WFS_featureClassNames
self.wfs_fields = WFS_fieldsInFeatureClass
self.wfs_replace = WFS_replaceFeatureClasses
self.keep_gdb = keepGeodatabase
self.path = os.getcwd()
self.arcPath = self.path + "\\gis.gdb"
# Color-blind-friendly color scheme by Paul Tol: https://personal.sron.nl/~pault
colors = {
"blue": "#4477AA",
"cyan": "#66CCEE",
"green": "#228833",
"yellow": "#CCBB44",
"red": "#EE6677",
"purple": "#AA3377",
"grey": "#BBBBBB",
}
# Set the default property-cycle and figure size for pyplots
color_cycler = cycler(color=list(colors.values())) # color cycler w. 7 colors
linestyle_cycler = cycler(linestyle=["-", "--", ":", "-", "--", ":", "-."]) # 7
plt.rc("axes", prop_cycle=(color_cycler + linestyle_cycler))
plt.rc("figure", figsize=[10, 6.18]) # golden ratio
# Set the default display format for floating-point numbers
pd.options.display.float_format = "{:.2f}".format
# pd.reset_option("display.float_format")
# Setup ArcPy
arcpy.env.workspace = self.arcPath # set the ArcPy workspace
arcpy.env.overwriteOutput = True # set overwrite option
# Check that folders for data, output, and linkage files exist or create them
self.get_data()
# Get feature class for coastal catchment areas from the WFS service
self.get_fc_from_WFS("catch")
def get_data(self):
"""Function to check that the folders and their files exist.
Otherwise creates the folders and downloads the files from GitHub."""
try:
# Dictionary for folders and their data and linkage files
allFiles = {
"data": [a for b in list(self.data.values()) for a in b],
"linkage": [a for b in list(self.linkage.values()) for a in b],
"output": [],
}
except:
# Report severe error messages
tb = sys.exc_info()[2] # get traceback object for Python errors
tbinfo = traceback.format_tb(tb)[0]
msg = "Could not set up dictionary with all files:\nTraceback info:\n{0}Error Info:\n{1}".format(
tbinfo, str(sys.exc_info()[1])
)
print(msg) # print error message in Python
arcpy.AddError(msg) # return error message in ArcGIS
sys.exit(1)
for key, filenames in allFiles.items():
try:
# Create the folder if it doesn't exist
newPath = self.path + "\\" + key
os.makedirs(newPath, exist_ok=True)
os.chdir(newPath)
for f in filenames:
# Download the files if they don't exist
if not os.path.exists(f):
try:
url = (
"https://github.com/thornoe/GreenGDP/raw/master/gis/"
+ key
+ "/"
+ f
)
urllib.request.urlretrieve(url, f)
except urllib.error.URLError as e:
## Report URL error messages
urlmsg = "URL error for {0}:\n{1}".format(f, e.reason)
print(urlmsg) # print URL error message in Python
arcpy.AddError(urlmsg) # return URL error message in ArcGIS
sys.exit(1)
except:
## Report other severe error messages
tb = sys.exc_info()[
2
] # get traceback object for Python errors
tbinfo = traceback.format_tb(tb)[0]
msg = "Could not download {0}:\nTraceback info:\n{1}Error Info:\n{2}".format(
f, tbinfo, str(sys.exc_info()[1])
)
print(msg) # print error message in Python
arcpy.AddError(msg) # return error message in ArcGIS
sys.exit(1)
except OSError:
# Report system errors
tb = sys.exc_info()[2] # get traceback object for Python errors
tbinfo = traceback.format_tb(tb)[0]
OSmsg = "System error for {0} folder:\nTraceback info:\n{1}Error Info:\n{2}".format(
key, tbinfo, str(sys.exc_info()[1])
)
print(OSmsg) # print system error message in Python
arcpy.AddError(OSmsg) # return system error message in ArcGIS
sys.exit(1)
finally:
# Change the directory back to the original working folder
os.chdir(self.path)
def get_fc_from_WFS(self, fc):
"""Create a feature class from a WFS service given the type of water body.
Also create a template with only the most necessary fields."""
try:
# Specify name of the feature class (fc) for the given type of water body
WFS_FeatureType = self.wfs_fc[fc]
# Specify names of the fields (columns) in fc that contain relevant variables
fields = self.wfs_fields[fc]
if self.wfs_replace != 0:
# Delete the fc template to create it anew
if arcpy.Exists(fc):
arcpy.Delete_management(fc)
if not arcpy.Exists(fc):
# Execute the WFSToFeatureClass tool to download the fc
arcpy.conversion.WFSToFeatureClass(
self.wfs_service,
WFS_FeatureType,
self.arcPath,
fc,
max_features=10000,
)
# Create a list of unnecessary fields
fieldsUnnecessary = []
fieldObjList = arcpy.ListFields(fc)
for field in fieldObjList:
if not field.required:
if field.name not in fields:
fieldsUnnecessary.append(field.name)
# Remove unnecessary fields (columns) to reduce the size of the feature class
arcpy.DeleteField_management(fc, fieldsUnnecessary)
except:
# Report severe error messages from Python or ArcPy
tb = sys.exc_info()[2] # get traceback object for Python errors
tbinfo = traceback.format_tb(tb)[0]
pymsg = "Python errors while using WFS for {0}:\nTraceback info:\n{1}Error Info:\n{2}".format(
fc, tbinfo, str(sys.exc_info()[1])
)
arcmsg = "ArcPy errors while using WFS for {0}:\n{1}".format(
fc, arcpy.GetMessages(severity=2)
)
print(pymsg) # print Python error message in Python
print(arcmsg) # print ArcPy error message in Python
arcpy.AddError(pymsg) # return Python error message in ArcGIS
arcpy.AddError(arcmsg) # return ArcPy error message in ArcGIS
sys.exit(1)
def observed_indicator(self, j, radius=15):
"""Set up a longitudinal DataFrame for all water bodies of category j by year t.
Assign monitoring stations to water bodies in water body plan via linkage table.
For monitoring stations not included in the linkage table: Assign a station to a waterbody if the station's coordinates are located within said waterbody. For streams, if the station is within a radius of 15 meters of a stream where the name of the stream matches the location name attached to the monitoring station).
Finally, construct the longitudinal DataFrame of observed biophysical indicator by year for all water bodies in the current water body plan. Separately, save the water body ID, typology, district ID, and shore length of each water body in VP3 using the feature classes collected via the get_fc_from_WFS() function.
"""
try:
if j == "streams":
# Create longitudinal df for stations in streams by monitoring version
kwargs = dict(
f=self.data[j][1],
d="Dato",
x="Xutm_Euref89_Zone32",
y="Yutm_Euref89_Zone32",
valueCol="Indeks",
parameterCol="Indekstype",
)
DVFI_F = self.longitudinal(j, parameter="Faunaklasse, felt", **kwargs)
DVFI_M = self.longitudinal(j, parameter="DVFI, MIB", **kwargs)
DVFI = self.longitudinal(j, parameter="DVFI", **kwargs)
# Observations after 2020 (publiced after ODA database update Jan 2024)
DVFI2 = self.longitudinal(
j,
f=self.data[j][0],
d="Dato",
x="X-UTM",
y="Y-UTM",
valueCol="Indeks",
)
# Group by station; keep last non-missing entry each year, DVFI>MIB>felt
long = (
pd.concat([DVFI_F, DVFI_M, DVFI, DVFI2]).groupby("station").last()
)
else: # lakes and coastal waters
# Create longitudinal df for stations
long = self.longitudinal(
j,
f=self.data[j][0],
d="Startdato",
x="X_UTM32",
y="Y_UTM32",
valueCol="Resultat",
)
if j == "lakes":
# Obtain the few missing coordinates
stations = pd.read_csv("linkage\\" + self.linkage[j][1]).astype(int)
stations.columns = ["station", "x", "y"]
stations.set_index("station", inplace=True)
long[["x", "y"]] = long[["x", "y"]].combine_first(stations)
# Read the linkage table
dfLinkage = pd.read_csv("linkage\\" + self.linkage[j][0])
# Convert station ID to integers
dfLinkage = dfLinkage.copy() # to avoid SettingWithCopyWarning
dfLinkage.loc[:, "station"] = (
dfLinkage["station_id"].str.slice(7).astype(int)
)
# Merge longitudinal DataFrame with linkage table for water bodies in VP3
df = long.merge(dfLinkage[["station", "ov_id"]], how="left", on="station")
# Stations covered by the linkage tabel for the third water body plan VP3
link = df.dropna(subset=["ov_id"])
# Convert water body ID (wb) to integers
link = link.copy() # to avoid SettingWithCopyWarning
if j == "lakes":
link.loc[:, "wb"] = link["ov_id"].str.slice(6).astype(int)
else:
link.loc[:, "wb"] = link["ov_id"].str.slice(7).astype(int)
# Stations not covered by the linkage table for VP3
noLink = df[df["ov_id"].isna()].drop(columns=["ov_id"])
# Create a spatial reference object with same geographical coordinate system
spatialRef = arcpy.SpatialReference("ETRS 1989 UTM Zone 32N")
# Specify name of feature class for stations (points)
fcStations = j + "_stations"
# Create new feature class shapefile (will overwrite if it already exists)
arcpy.CreateFeatureclass_management(
self.arcPath, fcStations, "POINT", spatial_reference=spatialRef
)
# Create field for 'station' and list fields
arcpy.AddField_management(fcStations, "station", "INTEGER")
fieldsStations = ["SHAPE@XY", "station"]
if j == "streams":
# Create field for 'location' and append to list of fields
arcpy.AddField_management(fcStations, "location", "TEXT")
fieldsStations.append("location")
# Create cursor to insert stations that were not in the linkage table
try:
with arcpy.da.InsertCursor(fcStations, fieldsStations) as cursor:
# Loop over each station-ID in df:
for index, row in noLink.iterrows():
try:
# Use cursor to insert new row in feature class
if j == "streams":
cursor.insertRow(
[
(row["x"], row["y"]),
row["station"],
row["location"],
]
)
else:
cursor.insertRow([(row["x"], row["y"]), row["station"]])
except:
# Report other severe error messages from Python or ArcPy
tb = sys.exc_info()[
2
] # get traceback object for Python errors
tbinfo = traceback.format_tb(tb)[0]
print(
"Python errors while inserting station {0} in {1}:\nTraceback info:{2}\nError Info:\n{3}\n".format(
str(row["station"]),
fcStations,
tbinfo,
str(sys.exc_info()[1]),
)
)
print(
"ArcPy errors while inserting station {0} in {1}:\n{2}".format(
str(row["station"]),
fcStations,
tbinfo,
)
)
sys.exit(1)
finally:
# Clean up for next iteration
del index, row
finally:
del cursor
# Specify name of feature class for streams in VP3 (polylines)
fc = j
# Specify name of joined feature class (polylines)
fcJoined = fcStations + "_joined"
# Spatial Join unmatched stations with streams within given radius
arcpy.SpatialJoin_analysis(
target_features=fc,
join_features=fcStations,
out_feature_class=fcJoined, # will overwrite if it already exists
join_operation="JOIN_ONE_TO_MANY",
join_type="KEEP_COMMON",
match_option="CLOSEST", # if more than one stream is within radius
search_radius=radius, # match to stream withing radius of station
distance_field_name="Distance",
)
# Specify fields of interest of fcJoined
if j == "streams":
fieldsJ = ["station", "ov_id", "ov_navn", "location", "Distance"]
else: # lakes and coastal waters
fieldsJ = ["station", "ov_id"]
# Create DataFrame from fcJoined and sort by distance (ascending)
stations = [row for row in arcpy.da.SearchCursor(fcJoined, fieldsJ)]
join = pd.DataFrame(stations, columns=fieldsJ)
# Convert water body ID (wb) to integers
join = join.copy() # to avoid SettingWithCopyWarning
if j == "lakes":
join.loc[:, "wb"] = join["ov_id"].str.slice(6).astype(int)
else:
join.loc[:, "wb"] = join["ov_id"].str.slice(7).astype(int)
if j == "streams":
# Capitalize water body names
join["ov_navn"] = join["ov_navn"].str.upper()
# Rename unnamed water bodies to distinguish from named water bodies
join["location"].mask(
join["location"] == "[IKKE NAVNGIVET]", "UDEN NAVN", inplace=True
)
# a Indicate that station and stream has the same water body name
join["match"] = np.select([join["location"] == join["ov_navn"]], [True])
# Subset to unique stations with their closest matching water body
jClosest = (
join[join["match"] == True]
.sort_values("Distance")
.groupby("station", as_index=False)
.first()
)
# Inner merge of noLink stations and jClosest water body with matching name
noLinkClosest = noLink.merge(jClosest[["station", "wb"]], on="station")
# df containing all stations that have been matched to a water body
allMatches = pd.concat([link, noLinkClosest]).drop(
columns=["station", "location", "x", "y", "ov_id"]
)
else: # for lakes and coastal waters
# df containing all stations that have been matched to a water body
allMatches = pd.concat([link, join]).drop(
columns=["station", "x", "y", "ov_id"]
)
# Group multiple stations in a water body: Take the median and round down
waterbodies = allMatches.groupby("wb").median().apply(np.floor)
# Specify the biophysical indicator for the current category
if j == "streams":
indicator = "til_oko_bb" # bottom fauna measured as DVFI index
else: # lakes and coastal waters
indicator = "til_oko_fy" # phytoplankton measured as chlorophyll
# Fields in fc that contain water body ID, typology, district, and length
fields = ["ov_id", "ov_typ", "distr_id", indicator]
fieldsTemp = ["ov_id", indicator]
if j != "coastal":
for f in (fields, fieldsTemp):
# Append field for shape length
f.append("Shape_Length") # lakes circumference; streams polyline
if j == "streams":
# Append field for natural/artificial/strongly modified streams
fields.append("na_kun_stm")
# Create df from fc with characteristics of all waterbodies in VP
dataVP = [row for row in arcpy.da.SearchCursor(fc, fields)]
dfVP = pd.DataFrame(dataVP, columns=fields)
if j == "coastal":
# Drop coastal waterbody without catchment area (Hesselø is uninhabited)
dfVP = dfVP[dfVP["ov_id"] != "DKCOAST205"]
# Convert water body ID (wb) to integers
dfVP = dfVP.copy() # to avoid SettingWithCopyWarning
if j == "lakes":
dfVP.loc[:, "wb"] = dfVP["ov_id"].str.slice(6).astype(int)
else:
dfVP.loc[:, "wb"] = dfVP["ov_id"].str.slice(7).astype(int)
# Sort by water body ID (wb, ascending)
dfVP = dfVP.set_index("wb").sort_index()
# Specify shore length for each category j
if j == "streams":
# Shore length is counted on both sides of the stream; convert to km
dfVP[["length"]] = dfVP[["Shape_Length"]] * 2 / 1000
elif j == "lakes":
# Shore length is the circumference, i.e. Shape_Length; convert to km
dfVP[["length"]] = dfVP[["Shape_Length"]] / 1000
else: # coastal waters
# Coastline by Zandersen et al.(2022) based on Corine Land Cover 2018
Geo = pd.read_excel("data\\" + self.data["shared"][2], index_col=0)
Geo.index.name = "wb"
# Merge with df for all water bodies in VP3
dfVP[["length"]] = Geo[["shore coastal"]]
# Convert ecological status as assessed in basis analysis for VP3
basis = dfVP[[indicator]].copy()
# Dictionary to map the Danish strings to ordinal scale of ecological status
status_dict = {
"Dårlig økologisk tilstand": 0,
"Ringe økologisk tilstand": 1,
"Moderat økologisk tilstand": 2,
"God økologisk tilstand": 3,
"Høj økologisk tilstand": 4,
"Dårligt økologisk potentiale": 0,
"Ringe økologisk potentiale": 1,
"Moderat økologisk potentiale": 2,
"Godt økologisk potentiale": 3,
"Maksimalt økologisk potentiale": 4,
"Ukendt": np.nan,
}
# Replace Danish strings in the df with the corresponding ordinal values
basis.replace(status_dict, inplace=True)
basis.columns = ["Basis"] # rename column for basis analysis
# Merge observed ecological status each year with basis analysis for VP3
dfVP = dfVP.merge(basis, on="wb")
# Subset columns to relevant water body characteristics
dfVP = dfVP.drop(columns=fieldsTemp)
# Save characteristics of water bodies to CSV for later work
dfVP.to_csv("output\\" + j + "_VP.csv")
# Merge index for all water bodies in VP3 with df for observed status
allVP = dfVP[[]].merge(waterbodies, how="left", on="wb")
# Save observations to CSV for later statistical work
allVP.to_csv("output\\" + j + "_ind_obs.csv")
# Report stations matched by linkage table and distance+name respectively
if j == "streams":
msg = "{0}:\n{1} out of {2} stations were linked to a water body by the official linkage table. Besides, {3} stations were located within {4} meters of a water body carrying the name of the station's location.".format(
str(j),
len(link),
len(df),
len(jClosest),
str(radius),
)
else:
msg = "{0}:\n{1} out of {2} stations were linked to a water body by the official linkage table for VP3. Besides, {3} stations were located inside the polygon shape of a water body present in VP3.".format(
str(j),
len(link),
len(df),
len(join),
)
print(msg) # print number of stations in Python
arcpy.AddMessage(msg) # return number of stations in ArcGIS
return allVP, dfVP
except:
# Report severe error messages
tb = sys.exc_info()[2] # get traceback object for Python errors
tbinfo = traceback.format_tb(tb)[0]
pymsg = "Python errors while assigning stations to water bodies:\nTraceback info:\n{0}Error Info:\n{1}".format(
tbinfo, str(sys.exc_info()[1])
)
arcmsg = (
"ArcPy errors while assigning stations to water bodies:\n{0}".format(
arcpy.GetMessages(severity=2)
)
)
print(pymsg) # print Python error message in Python
print(arcmsg) # print ArcPy error message in Python
arcpy.AddError(pymsg) # return Python error message in ArcGIS
arcpy.AddError(arcmsg) # return ArcPy error message in ArcGIS
sys.exit(1)
finally: # Clean up
for fc in [fcStations, fcJoined]: # Delete feature classes
if arcpy.Exists(fc):
arcpy.Delete_management(fc)
del fcStations, fcJoined
def longitudinal(self, j, f, d, x, y, valueCol, parameterCol=0, parameter=0):
"""Set up a longitudinal DataFrame for all stations in category j by year t.
Streams: For a given year, find the DVFI index value of bottom fauna for a station with multiple observations by taking the median and rounding down.
Lakes and coastal waters: For a given year, estimate the chlorophyll summer average for every station monitored at least four times during May-September by linear interpolating of daily data from May 1 to September 30 (or extrapolate by inserting the first/last observation from May/September if there exist no observations outside of said period that are no more than 6 weeks away from the first/last observation in May/September).
"""
try:
# Read the data for biophysical indicator (source: https://ODAforalle.au.dk)
df = pd.read_excel("data\\" + f)
# Rename the station ID column and make it the index of df
df = df.set_index("ObservationsStedNr").rename_axis("station")
# Create 'Year' column from the date column
df = df.copy() # to avoid SettingWithCopyWarning
df.loc[:, "year"] = df[d].astype(str).str.slice(0, 4).astype(int)
if parameterCol != 0:
# Subset the data to only contain the relevant parameter
df = df[df[parameterCol] == parameter]
# Drop missing values and sort by year
df = df.dropna(subset=valueCol).sort_values("year")
# Column names for the final longitudinal DataFrame besides the indicator
cols = ["x", "y"]
if j == "streams":
cols.append("location") # add location name for final DataFrame
df = df[[x, y, "Lokalitetsnavn", "year", valueCol]] # subset columns
df.columns = cols + ["year", "ind"] # shorten column names
df["location"] = df["location"].str.upper() # capitalize location names
df = df[df["ind"] != "U"] # drop obs with unknown indicator value "U"
df["ind"] = df["ind"].astype(int) # convert indicator to integer
else: # Lakes and coastal waters
# Convert date column to datetime format
df[d] = pd.to_datetime(df[d].astype(str), format="%Y%m%d") # convert
df = df[[x, y, d, "year", valueCol]] # subset to relevant columns
df.columns = cols + ["date", "year", "ind"] # shorten column names
df.set_index("date", append=True, inplace=True) # add 'date' to index
# Replace 0-values with missing in 'x' and 'y' columns
df[["x", "y"]] = df[["x", "y"]].replace(0, np.nan)
# Set up a longitudinal df with every station and its last non-null entry
long = df[cols].groupby(level="station").last()
# For each year t, add a column with observations for the indicator
for t in df["year"].unique():
# Subset to year t
dft = df[df["year"] == t]
# Subset to station and indicator columns only
dft = dft[["ind"]]
if j == "streams":
# Group multiple obs for a station: Take the median and round down
dfYear = dft.groupby("station").median().apply(np.floor).astype(int)
# Rename the indicator column to year t
dfYear.columns = [t]
else:
# Generate date range 6 weeks before and after May 1 and September 30
dates = pd.date_range(str(t) + "-03-20", str(t) + "-11-11")
summer = pd.date_range(str(t) + "-05-01", str(t) + "-09-30")
# Subset to dates in the date range
dft = dft.loc[
(dft.index.get_level_values("date") >= dates.min())
& (dft.index.get_level_values("date") <= dates.max())
]
# Take the mean of multiple obs for any station-date combination
dft = dft.groupby(level=["station", "date"]).mean()
# Pivot dft with dates as index and stations as columns
dft = dft.reset_index().pivot(
index="date", columns="station", values="ind"
)
# Subset dft to rows that are within the summer date range
dftSummer = dft.loc[dft.index.isin(summer), :]
# Drop columns (stations) with less than 4 values
dftSummer = dftSummer.dropna(axis=1, thresh=4)
# Create empty DataFrame with dates as index and stations as columns
dfd = pd.DataFrame(index=dates, columns=dftSummer.columns)
# Update the empty dfd with the chlorophyll observations in dft
dfd.update(dft)
# Convert to numeric, errors='coerce' will set non-numeric values to NaN
dfd = dfd.apply(pd.to_numeric, errors="coerce")
# Linear Interpolation of missing values with consecutive gap < 6 weeks
dfd = dfd.interpolate(limit=41, limit_direction="both")
# Linear Interpolation for May-September without limit
dfd = dfd.loc[dfd.index.isin(summer), :].interpolate(
limit_direction="both"
)
# Drop any column that might somehow still contain missing values
dfd = dfd.dropna(axis=1)
# Take the summer average of chlorophyll for each station in year t
dfYear = dfd.groupby(dfd.index.year).mean().T
# Merge into longitudinal df
long = long.merge(dfYear, how="left", on="station")
return long
except:
## Report severe error messages
tb = sys.exc_info()[2] # get traceback object for Python errors
tbinfo = traceback.format_tb(tb)[0]
msg = "Could not set up DataFrame for {0}:\nTraceback info:\n{1}Error Info:\n{2}".format(
j, tbinfo, str(sys.exc_info()[1])
)
print(msg) # print error message in Python
arcpy.AddError(msg) # return error message in ArcGIS
sys.exit(1)
def impute_missing(self, j, dfEcoObs, dfVP, index):
"""Impute ecological status for all water bodies from the observed indicator."""
try:
# Merge observed ecological status each year with basis analysis for VP3
dfEco = dfEcoObs.merge(dfVP[["Basis"]], on="wb")
if j == "streams":
# Create dummies for typology
typ = pd.get_dummies(dfVP["ov_typ"]).astype(int)
typ["Soft bottom"] = typ["RW4"] + typ["RW5"]
typ.columns = [
"Small",
"Medium",
"Large",
"Small w. soft bottom",
"Medium w. soft bottom",
"Soft bottom",
]
# Dummies for natural, artificial, and heavily modified water bodies
natural = pd.get_dummies(dfVP["na_kun_stm"]).astype(int)
natural.columns = ["Artificial", "Natural", "Heavily modified"]
# Merge DataFrames for typology and natural water bodies
typ = typ.merge(natural, on="wb")
# Dummies used for imputation chosen via Forward Stepwise Selection (CV)
cols = ["Soft bottom", "Natural", "Large"]
elif j == "lakes":
# Convert typology to integers
typ = dfVP[["ov_typ"]].copy()
typ.loc[:, "type"] = typ["ov_typ"].str.slice(6).astype(int)
# Create dummies for high alkalinity, brown, saline, and deep lakes
cond1 = [(typ["type"] >= 9) & (typ["type"] <= 16), typ["type"] == 17]
typ["Alkalinity"] = np.select(cond1, [1, np.nan], default=0)
cond2 = [
typ["type"].isin([5, 6, 7, 8, 13, 14, 15, 16]),
typ["type"] == 17,
]
typ["Brown"] = np.select(cond2, [1, np.nan], default=0)
cond3 = [
typ["type"].isin([2, 3, 7, 8, 11, 12, 15, 16]),
typ["type"] == 17,
]
typ["Saline"] = np.select(cond3, [1, np.nan], default=0)
cond4 = [typ["type"].isin(np.arange(2, 17, 2)), typ["type"] == 17]
typ["Deep"] = np.select(cond4, [1, np.nan], default=0)
# Dummies used for imputation chosen via Forward Stepwise Selection (CV)
cols = ["Saline", "Brown", "Alkalinity"]
else: # coastal waters
# Get typology
typ = dfVP[["ov_typ"]].copy()
# Define the dictionaries
dict1 = {
"No": "North Sea", # Nordsø
"K": "Kattegat", # Kattegat
"B": "Belt Sea", # Bælthav
"Ø": "Baltic Sea", # Østersøen
"Fj": "Fjord", # Fjord
"Vf": "North Sea fjord", # Vesterhavsfjord
}
dict2 = {
"Vu": "Water exchange", # vandudveksling
"F": "Freshwater inflow", # ferskvandspåvirkning
"D": "Deep", # vanddybde
"L": "Stratified", # lagdeling
"Se": "Sediment", # sediment
"Sa": "Saline", # salinitet
"T": "Tide", # tidevand
}
# Define a function to process each string
def process_string(s):
# Drop the hyphen and everything following it
s = s.split("-")[0]
# Create a en empty dictionary for relevant abbreviations as keys
dummies = {}
# Check for abbreviations from dict1 first
for abbr in dict1:
if abbr in s:
dummies[abbr] = 1
s = s.replace(
abbr, ""
) # Remove the matched abbreviation from the string
# Then check for abbreviations from dict2
for abbr in dict2:
if abbr in s:
dummies[abbr] = 1
return dummies
# Apply the function to typ["ov_typ"] to create a df with the dummies
typ = typ["ov_typ"].apply(process_string).apply(pd.Series)
# Replace NaN values with 0
typ = typ.fillna(0).astype(int)
# Rename the dummies from abbreviations to full names
dicts = {**dict1, **dict2} # combine the dictionaries
typ = typ.rename(columns=dicts) # rename columns to full names
# Dummies used for imputation chosen via Forward Stepwise Selection (CV)
cols = [
"North Sea",
"Kattegat",
"Belt Sea",
"Baltic Sea",
"Fjord",
"North Sea fjord",
"Water exchange",
"Sediment",
]
# Merge DataFrame for observed values with DataFrame for dummies
dfEcoSelected = dfEco.merge(typ[cols], on="wb") # selected predictors
# Multivariate imputer using BayesianRidge estimator w. increased tolerance
imputer = IterativeImputer(tol=1e-1, max_iter=100, random_state=0)
# Fit imputer, transform data iteratively, and limit to years of interest
dfImp = pd.DataFrame(
imputer.fit_transform(np.array(dfEcoSelected)),
index=dfEcoSelected.index,
columns=dfEcoSelected.columns,
)[dfEcoObs.columns]
# Calculate a 5-year moving average (MA) for each water body to reduce noise
dfImpMA = dfImp.T.rolling(window=5, min_periods=3, center=True).mean().T
# Stats if converting imputed status to categorical scale ∈ {0, 1, 2, 3, 4}
impStats = self.ecological_status(j, dfImp, dfVP, "imp", index)
# Stats if converting moving average to categorical scale ∈ {0, 1, 2, 3, 4}
impStatsMA = self.ecological_status(j, dfImpMA, dfVP, "imp_MA", index)
return dfImp[self.years], dfImpMA[self.years], impStats, impStatsMA
except:
## Report severe error messages
tb = sys.exc_info()[2] # get traceback object for Python errors
tbinfo = traceback.format_tb(tb)[0]
msg = "Could not impute biophysical indicator to ecological status for {0}:\nTraceback info:\n{1}Error Info:\n{2}".format(
j, tbinfo, str(sys.exc_info()[1])
)
print(msg) # print error message in Python
arcpy.AddError(msg) # return error message in ArcGIS
sys.exit(1)
def ecological_status(self, j, dfIndicator, dfVP, suffix="obs", index=None):
"""Call indicator_to_status() to convert the longitudinal DataFrame to the EU index of ecological status, i.e., from 0-4 for Bad, Poor, Moderate, Good, and High water quality based on the category and typology of each water body.
Also call missing_values_graph() to map missing observations by year.
Create a table of statistics and export it as an html table.
Print the shore length and share of water bodies observed at least once."""
try:
if suffix == "obs":
# Convert observed biophysical indicator to ecological status
dfEcoObs = self.indicator_to_status(j, dfIndicator, dfVP)
else:
# Imputed ecological status using a continuous scale
dfEcoObs = dfIndicator.copy()
# Save CSV of data on mean ecological status by water body and year
dfEcoObs.to_csv("output\\" + j + "_eco_" + suffix + ".csv")
# Merge observed ecological status each year with basis analysis for VP3
dfEco = dfEcoObs.merge(dfVP[["Basis"]], on="wb")
if suffix != "obs":
# Prepare for statistics and missing values graph
for t in dfEco.columns:
# Convert imp status to categorical scale w. equidistant thresholds
conditions = [
dfEco[t] < 0.5, # Bad
(dfEco[t] >= 0.5) & (dfEco[t] < 1.5), # Poor
(dfEco[t] >= 1.5) & (dfEco[t] < 2.5), # Moderate
(dfEco[t] >= 2.5) & (dfEco[t] < 3.5), # Good
dfEco[t] >= 3.5, # High
]
# Ecological status as a categorical index from Bad to High quality
dfEco[t] = np.select(conditions, [0, 1, 2, 3, 4], default=np.nan)
if suffix != "imp_MA":
# Create missing values graph (heatmap of missing observations by year)
indexSorted = self.missing_values_graph(j, dfEco, suffix, index)
# Merge df for observed ecological status with df for characteristics
dfEcoLength = dfEco.merge(dfVP[["length"]], on="wb")
# Calculate total length of all water bodies in current water body plan (VP2)
totalLength = dfEcoLength["length"].sum()
# Create an empty df for statistics
stats = pd.DataFrame(
index=self.years + ["Basis"],
columns=[
"high",
"good",
"moderate",
"poor",
"bad",
"not good",
"known",
],
)
# Calculate the above statistics for span of natural capital account & basis
for t in self.years + ["Basis"]:
y = dfEcoLength[[t, "length"]].reset_index(drop=True)
y["high"] = np.select([y[t] == 4], [y["length"]])
y["good"] = np.select([y[t] == 3], [y["length"]])
y["moderate"] = np.select([y[t] == 2], [y["length"]])
y["poor"] = np.select([y[t] == 1], [y["length"]])
y["bad"] = np.select([y[t] == 0], [y["length"]])
y["not good"] = np.select([y[t] < 3], [y["length"]])
y["known"] = np.select([y[t].notna()], [y["length"]])
# Add shares of total length to stats
knownLength = y["known"].sum()
stats.loc[t] = [
100 * y["high"].sum() / knownLength,
100 * y["good"].sum() / knownLength,
100 * y["moderate"].sum() / knownLength,
100 * y["poor"].sum() / knownLength,
100 * y["bad"].sum() / knownLength,
100 * y["not good"].sum() / knownLength,
100 * knownLength / totalLength,
]
# For imputed ecological status, convert to integers and drop 'known' column
if suffix != "obs":
stats = stats.drop(columns="known")
# Save statistics on mean ecological status by year weighted by shore length
stats.to_csv("output\\" + j + "_eco_" + suffix + "_stats.csv")
# Brief analysis of missing observations (not relevant for imputed data)
if suffix == "obs":
# Create df limited to water bodies that are observed at least one year
observed = dfEcoObs.dropna(how="all").merge(
dfVP[["length"]],
how="inner",
on="wb",
)
# Report length and share of water bodies observed at least one year
msg = "{0} km is the total shore length of {1} included in VP3, of which {2}% of {1} representing {3} km ({4}% of total shore length of {1}) have been assessed at least one year. On average, {5}% of {1} representing {6} km ({7}% of total shore length of {1}) are assessed each year.\n".format(
round(totalLength),
j,
round(100 * len(observed) / len(dfEco)),
round(observed["length"].sum()),
round(100 * observed["length"].sum() / totalLength),
round(100 * np.mean(dfEco[self.years].count() / len(dfEco))),
round(stats.drop("Basis")["known"].mean() / 100 * totalLength),
round(stats.drop("Basis")["known"].mean()),
)
print(msg) # print statistics in Python
arcpy.AddMessage(msg) # return statistics in ArcGIS
return dfEco[dfEcoObs.columns], stats["not good"], indexSorted
return stats["not good"]
except:
# Report severe error messages
tb = sys.exc_info()[2] # get traceback object for Python errors
tbinfo = traceback.format_tb(tb)[0]
msg = "Could not create df with {0} ecological status for {1}:\nTraceback info:\n{2}Error Info:\n{3}".format(
suffix, j, tbinfo, str(sys.exc_info()[1])
)
print(msg) # print error message in Python
arcpy.AddError(msg) # return error message in ArcGIS
sys.exit(1)
def indicator_to_status(self, j, dfIndicator, dfVP):
"""Convert biophysical indicators to ecological status."""
try:
# Column names for chlorophyll thresholds for lakes or coastal waters
cols = ["bad", "poor", "moderate", "good"]
if j == "streams":
# Copy DataFrame for the biophysical indicator
df = dfIndicator.copy()
# Convert DVFI fauna index for streams to index of ecological status
for t in df.columns:
# Set conditions given the official guidelines for conversion
conditions = [
df[t] < 1.5, # Bad
(df[t] >= 1.5) & (df[t] < 3.5), # Poor
(df[t] >= 3.5) & (df[t] < 4.5), # Moderate
(df[t] >= 4.5) & (df[t] < 6.5), # Good
df[t] >= 6.5, # High
]
# Ecological status as a categorical scale from Bad to High quality
df[t] = np.select(conditions, [0, 1, 2, 3, 4], default=np.nan)
return df
elif j == "lakes":
# Merge df for biophysical indicator with df for typology