Skip to content
Snippets Groups Projects
Commit cb991da6 authored by Jeremy Auclair's avatar Jeremy Auclair
Browse files

Modified input calculations. Reprojection of weather dataset needs to be...

Modified input calculations. Reprojection of weather dataset needs to be handled differently for bigger images (with OTB for example). Modified the parameter class. Begining to work on samir time loop, inputs and parameters are done. Added env file. New method for calculating ET0 with xarray might have been found.
parent 9a5d72d5
No related branches found
No related tags found
No related merge requests found
......@@ -10,24 +10,112 @@ Usage of the SAMIR model in the Modspa framework.
import os # for path exploration
import csv # open csv files
from fnmatch import fnmatch # for character string comparison
from typing import List, Union # to declare variables
from typing import List, Tuple # to declare variables
import xarray as xr # to manage dataset
import pandas as pd # to manage dataframes
import numpy as np # for math and array operations
import rasterio as rio # to open geotiff files
import geopandas as gpd # to manage shapefile crs projections
from code.params_samir_class import samir_parameters
from parameters.params_samir_class import samir_parameters
def rasterize_samir_parameters(csv_param_file: str, empty_dataset: xr.Dataset):
def rasterize_samir_parameters(csv_param_file: str, parameter_dataset: xr.Dataset, land_cover_raster: str) -> xr.Dataset:
"""
Creates a raster `xarray` dataset from the csv parameter file, the land cover raster and an empty dataset
that contains the right structure (emptied ndvi dataset for example). For each parameter, the function loops
on land cover classes to fill the raster.
## Arguments
1. csv_param_file: `str`
path to csv paramter file
2. parameter_dataset: `xr.Dataset`
empty dataset that contains the right structure (emptied ndvi dataset for example)
3. land_cover_raster: `str`
path to land cover netcdf raster
## Returns
1. parameter_dataset: `xr.Dataset`
the dataset containing all the rasterized Parameters
"""
# Load samir params into an object
table_param = samir_parameters(csv_param_file)
return None
# Set general variables
class_count = table_param.table.shape[1] - 2 # remove dtype and default columns
# Open land cover raster
land_cover = xr.open_dataarray(land_cover_raster)
# Loop on samir parameters and create
for parameter in table_param.table.index[1:]:
# Create new variable and set attributes
parameter_dataset[parameter] = land_cover.astype('i2')
parameter_dataset[parameter].attrs['name'] = parameter
parameter_dataset[parameter].attrs['description'] = 'cf SAMIR Doc for detail'
# Loop on classes to set parameter values for each class
for class_val, class_name in zip(range(1, class_count + 1), table_param.table.columns[2:]):
# Parameter values are multiplied by the scale factor in order to store all values as int16 types
# These values are then rounded to make sure there isn't any decimal point issues when casting the values to int16
parameter_dataset[parameter].values = np.where(parameter_dataset[parameter].values == class_val, round(table_param.table.loc[table_param.table.index == parameter][class_name].values[0]*table_param.table.loc[table_param.table.index == parameter]['scale_factor'].values[0]), parameter_dataset[parameter].values).astype('i2')
# Return dataset converted to 'int16' data type to reduce memory usage
# Scale factor for calculation is stored in the samir_parameters object
return parameter_dataset
def setup_time_loop(calculation_variables: List[str], calculation_constant_values: List[str], empty_dataset: xr.Dataset) -> Tuple[xr.Dataset, xr.Dataset, xr.Dataset]:
"""
Creates three temporary `xarray Datasets` that will be used in the SAMIR time loop.
`variables_t1` corresponds to the variables for the previous day and `variables_t2`
corresponds to the variables for the current day. After each loop, `variables_t1`
takes the value of `variables_t2`. `constant_values` corresponds to model values
that are not time dependant, and therefore stay constant during the SAMIR time loop.
def setup_time_loop():
## Arguments
1. calculation_variables: `List[str]`
list of strings containing the variable names
2. calculation_constant_values: `List[str]`
list of strings containing the constant value names
3. empty_dataset: `xr.Dataset`
empty dataset that contains the right structure
## Returns
1. variables_t1: `xr.Dataset`
output dataset for previous day
2. variables_t2: `xr.Dataset`
output dataset for current day
3. constant_values: `xr.Dataset`
output dataset for constant values
"""
return None
# Create new dataset
variables_t1 = empty_dataset.copy(deep = True)
# Create empty DataArray for each variable
for variable in calculation_variables:
# Assign new empty DataArray
variables_t1[variable] = (empty_dataset.dims, np.zeros(tuple(empty_dataset.dims[d] for d in list(empty_dataset.dims)), dtype = 'float32'))
variables_t1[variable].attrs['name'] = variable # set name in attributes
# Create new copy of the variables_t1 dataset
variables_t2 = variables_t1.copy(deep = True)
# Create dataset for constant values
constant_values = empty_dataset.copy(deep = True)
# Create empty DataArray for each value
for value in calculation_constant_values:
# Assign new empty DataArray
constant_values[value] = (empty_dataset.dims, np.zeros(tuple(empty_dataset.dims[d] for d in list(empty_dataset.dims)), dtype = 'int16'))
constant_values[value].attrs['name'] = value # set name in attributes
constant_values[value].attrs['description'] = 'Values which stays constant during the SAMIR time loop' # set description in attributes
return variables_t1, variables_t2, constant_values
def run_samir():
......
......@@ -94,13 +94,14 @@ def calculate_ndvi(extracted_paths: Union[List[str], str], save_dir: str, bounda
# Mask and scale ndvi
ndvi['ndvi'] = xr.where(ndvi.ndvi < 0, 0, ndvi.ndvi)
ndvi['ndvi'] = xr.where(ndvi.ndvi > 1, 1, ndvi.ndvi)
ndvi['ndvi'] = (ndvi.ndvi*255) #.astype('u1')
ndvi['ndvi'] = (ndvi.ndvi*255).sortby('time')
# Write attributes
ndvi['ndvi'].attrs['long_name'] = 'Normalized Difference Vegetation Index'
ndvi['ndvi'].attrs['units'] = 'None'
ndvi['ndvi'].attrs['standard_name'] = 'NDVI'
ndvi['ndvi'].attrs['comment'] = 'Normalized difference of the near infrared and red band. A value of one is a high vegetation presence.'
ndvi['ndvi'].attrs['scale factor'] = '255'
# Create save path
ndvi_cube_path = save_dir + os.sep + 'NDVI_precube_' + dates[0].strftime('%d-%m-%Y') + '_' + dates[-1].strftime('%d-%m-%Y') + '.nc'
......
......@@ -14,11 +14,11 @@ import xarray as xr # to manage nc files
import pandas as pd # to manage dataframes
import geopandas as gpd # to manage shapefiles
from psutil import cpu_count # to get number of physical cores available
import input.lib_era5_land as era5land # custom built functions for ERA5-Land data download
import input.lib_era5_land_pixel as era5land # custom built functions for ERA5-Land data download
from config.config import config # to import config file
def request_ER5_weather(input_file: str) -> str:
def request_ER5_weather(input_file: str, ndvi_path: str) -> str:
# Get config file
config_params = config(input_file)
......@@ -129,6 +129,7 @@ def request_ER5_weather(input_file: str) -> str:
aggregated_files = era5land.concat_monthly_nc_file(list_era5land_hourly_ncFiles, variable_list, save_dir)
# Calculate ET0 over the whole time period
era5land.era5Land_nc_daily_to_ET0(aggregated_files, weather_daily_ncFile, h = wind_height)
era5land.era5Land_nc_daily_to_ET0(aggregated_files, weather_daily_ncFile, ndvi_path, h = wind_height)
print(weather_daily_ncFile)
return weather_daily_ncFile
\ No newline at end of file
This diff is collapsed.
name: modspa_pixel
channels:
- anaconda
- iota2
- pytorch
- conda-forge
- defaults
dependencies:
- _libgcc_mutex=0.1=main
- _openmp_mutex=5.1=1_gnu
- asttokens=2.0.5=pyhd3eb1b0_0
- backcall=0.2.0=pyhd3eb1b0_0
- bzip2=1.0.8=h7b6447c_0
- ca-certificates=2023.01.10=h06a4308_0
- certifi=2022.12.7=py310h06a4308_0
- comm=0.1.2=py310h06a4308_0
- debugpy=1.5.1=py310h295c915_0
- decorator=5.1.1=pyhd3eb1b0_0
- entrypoints=0.4=py310h06a4308_0
- executing=0.8.3=pyhd3eb1b0_0
- ipykernel=6.19.2=py310h2f386ee_0
- ipython=8.8.0=py310h06a4308_0
- jedi=0.18.1=py310h06a4308_1
- jupyter_client=7.4.8=py310h06a4308_0
- jupyter_core=5.1.1=py310h06a4308_0
- ld_impl_linux-64=2.38=h1181459_1
- libffi=3.4.2=h6a678d5_6
- libgcc-ng=11.2.0=h1234567_1
- libgomp=11.2.0=h1234567_1
- libsodium=1.0.18=h7b6447c_0
- libstdcxx-ng=11.2.0=h1234567_1
- libuuid=1.41.5=h5eee18b_0
- matplotlib-inline=0.1.6=py310h06a4308_0
- ncurses=6.4=h6a678d5_0
- nest-asyncio=1.5.6=py310h06a4308_0
- openssl=1.1.1s=h7f8727e_0
- packaging=22.0=py310h06a4308_0
- parso=0.8.3=pyhd3eb1b0_0
- pexpect=4.8.0=pyhd3eb1b0_3
- pickleshare=0.7.5=pyhd3eb1b0_1003
- pip=22.3.1=py310h06a4308_0
- platformdirs=2.5.2=py310h06a4308_0
- prompt-toolkit=3.0.36=py310h06a4308_0
- psutil=5.9.0=py310h5eee18b_0
- ptyprocess=0.7.0=pyhd3eb1b0_2
- pure_eval=0.2.2=pyhd3eb1b0_0
- pygments=2.11.2=pyhd3eb1b0_0
- python=3.10.9=h7a1cb2a_0
- python-dateutil=2.8.2=pyhd3eb1b0_0
- pyzmq=23.2.0=py310h6a678d5_0
- readline=8.2=h5eee18b_0
- setuptools=65.6.3=py310h06a4308_0
- six=1.16.0=pyhd3eb1b0_1
- sqlite=3.40.1=h5082296_0
- stack_data=0.2.0=pyhd3eb1b0_0
- tk=8.6.12=h1ccaba5_0
- tornado=6.2=py310h5eee18b_0
- traitlets=5.7.1=py310h06a4308_0
- wcwidth=0.2.5=pyhd3eb1b0_0
- wheel=0.37.1=pyhd3eb1b0_0
- xz=5.2.10=h5eee18b_1
- zeromq=4.3.4=h2531618_0
- zlib=1.2.13=h5eee18b_0
- pip:
- affine==2.4.0
- attrs==23.1.0
- blinker==1.6.2
- bokeh==3.2.0
- boto3==1.27.0
- botocore==1.30.0
- cdsapi==0.6.1
- cftime==1.6.2
- charset-normalizer==3.1.0
- click==8.1.3
- click-plugins==1.1.1
- cligj==0.7.2
- cloudpickle==2.2.1
- contourpy==1.1.0
- cycler==0.11.0
- dask==2023.6.1
- dill==0.3.6
- distributed==2023.6.1
- ecmwf-api-client==1.6.3
- eodag==2.10.0
- eodag-sentinelsat==0.4.1
- eto==1.1.0
- fiona==1.9.4.post1
- flasgger==0.9.7.1
- flask==2.3.2
- fonttools==4.40.0
- fsspec==2023.6.0
- geojson==3.0.1
- geomet==1.0.0
- geopandas==0.13.2
- html2text==2020.1.16
- idna==3.4
- importlib-metadata==6.7.0
- itsdangerous==2.1.2
- jinja2==3.1.2
- jmespath==1.0.1
- jsonpath-ng==1.5.3
- jsonschema==4.17.3
- kiwisolver==1.4.4
- locket==1.0.0
- lxml==4.9.2
- markupsafe==2.1.3
- matplotlib==3.7.1
- mistune==3.0.1
- msgpack==1.0.5
- multiprocess==0.70.14
- netcdf==66.0.2
- netcdf4==1.6.4
- numpy==1.25.0
- orjson==3.9.1
- owslib==0.25.0
- p-tqdm==1.4.0
- pandas==2.0.3
- param==1.13.0
- partd==1.4.0
- pathos==0.3.0
- pillow==10.0.0
- ply==3.11
- pox==0.3.2
- ppft==1.7.6.6
- pyparsing==3.1.0
- pyproj==3.6.0
- pyrsistent==0.19.3
- pyshp==2.3.1
- pystac==1.8.1
- pytz==2023.3
- pyyaml==6.0
- rasterio==1.3.8
- requests==2.31.0
- requests-futures==1.0.1
- rioxarray==0.14.1
- s3transfer==0.6.1
- scipy==1.11.1
- sentinelsat==1.2.1
- shapely==2.0.1
- snuggs==1.4.7
- sortedcontainers==2.4.0
- tblib==2.0.0
- toolz==0.12.0
- tqdm==4.65.0
- tzdata==2023.3
- urllib3==1.26.16
- usgs==0.3.5
- werkzeug==2.3.6
- whoosh==2.7.4
- xarray==2023.6.0
- xyzservices==2023.5.0
- zict==3.0.0
- zipp==3.15.0
prefix: /home/auclairj/anaconda3/envs/modspa_pixel
......@@ -8,289 +8,68 @@ Classes to load and store SAMIR parameters.
"""
from pandas import read_csv # to read csv parameter files
from numpy import nan # to fill nan values
import param # type: ignore
class samir_parameters_LC:
"""
This class allows to store all the SAMIR parameters for one land cover class
"""
def __init__(self, csvLine, defaultClass, mode_init = 1):
# List of parameters that will be optimised (and hence that are not read in the param csv file)
self.optimList = []
if defaultClass:
#print(csvLine)
for v in csvLine.values():
if v == '':
raise ValueError("All fields must be filled for the default value line")
self.name = csvLine['ClassName']
self.number = int(csvLine['ClassNumber'])
# Parameters for the NDVI - Fraction Cover relation
if (csvLine['FminFC'] != "optim"):
self.ndviFCminFC = param.Number(float(csvLine['FminFC']), bounds=(0., 1.)).default
else:
self.optimList.append("FminFC")
if (csvLine['FmaxFC'] != "optim"):
self.ndviFCmaxFC = param.Number(float(csvLine['FmaxFC']), bounds=(0., 1.)).default
else:
self.optimList.append("FmaxFC")
if (csvLine['Fslope'] != "optim"):
self.ndviFCslope = param.Number(float(csvLine['Fslope']), bounds=(0., 10)).default
else:
self.optimList.append("Fslope")
if (csvLine['Foffset'] != "optim"):
self.ndviFCoffset = param.Number(float(csvLine['Foffset']), bounds=(-1, 1)).default
else:
self.optimList.append("Foffset")
if (csvLine['Plateau'] != "optim"):
self.ndviPlateau = param.Number(int(float(csvLine['Plateau'])), bounds=(0, 365)).default
else:
self.optimList.append("Plateau")
# Parameters for the NDVI -Kcb relation
if (csvLine['KminKcb'] != "optim"):
self.ndviKcbminKcb = param.Number(float(csvLine['KminKcb']), bounds=(0, 0.5)).default
else:
self.optimList.append("KminKcb")
if (csvLine['KmaxKcb'] != "optim"):
self.ndviKcbmaxKcb = param.Number(float(csvLine['KmaxKcb']), bounds=(0.5, 2)).default
else:
self.optimList.append("KmaxKcb")
if (csvLine['Kslope'] != "optim"):
self.ndviKcbslope = param.Number(float(csvLine['Kslope'])).default
else:
self.optimList.append("Kslope")
if (csvLine['Koffset'] != "optim"):
self.ndviKcboffset = param.Number(float(csvLine['Koffset'])).default
else:
self.optimList.append("Koffset")
# Soil parameters
if (csvLine['Zsoil'] != "optim"):
self.Zsoil = param.Number(float(csvLine['Zsoil']), bounds=(100, 10000), doc = "Soil depth (in mm)").default
else:
self.optimList.append("Zsoil")
if (csvLine['Ze'] != "optim"):
self.Ze = param.Number(float(csvLine['Ze']), bounds=(1, self.Zsoil), doc = "Evaporative layer depth (in mm)").default
else:
self.optimList.append("Ze")
if mode_init == 1 or mode_init == 3:
if (csvLine['Init_RU'] != "optim"):
self.Init_RU = param.Number(float(csvLine['Init_RU']), doc = "Filling rate of the available water").default
else:
self.optimList.append("Init_RU")
else :
self.Dei = param.Number(float(csvLine['Init_Dei']), bounds=(0, None), doc = "Initial Depletion of the evaporative layer (irrigation + precipitation) (in mm)").default
self.Dep = param.Number(float(csvLine['Init_Dep']), bounds=(0, None), doc = "Initial Depletion of the evaporative layer (precipitation only) (in mm)").default
self.Dr = param.Number(float(csvLine['Init_Dr']), bounds=(0, None), doc = "Initial Depletion of the root layer (in mm)").default
self.Dd = param.Number(float(csvLine['Init_Dd']), bounds=(0, None), doc = "Initial Depletion of the deep layer (in mm)").default
if (csvLine['DiffE'] != "optim"):
self.DiffE = param.Number(float(csvLine['DiffE']), bounds=(0, 1000), doc = "Diffusion coefficient between evaporative and root layers (unitless)").default
else:
self.optimList.append("DiffE")
if (csvLine['DiffR'] != "optim"):
self.DiffR = param.Number(float(csvLine['DiffR']), bounds=(0, 1000), doc = "Diffusion coefficient between root and deep layers (unitless)").default
else:
self.optimList.append("DiffR")
if (csvLine['REW'] != "optim"):
self.REW = param.Number(float(csvLine['REW']), bounds=(-1000, 1000), doc = "Readily Evaporable Water (in mm)").default
else:
self.optimList.append("REW")
if (csvLine['m'] != "optim"):
self.m = param.Number(float(csvLine['m']), bounds=(0, 1), doc = "").default ## si utilise, REW minimum doit etre à 0 ?
else:
self.optimList.append("m")
# Crop parameters
if (csvLine['minZr'] != "optim"):
if (csvLine['Ze'] != "optim") & (csvLine['Zsoil'] != "optim"):
self.minZr = param.Number(float(csvLine['minZr']), bounds=(self.Ze, self.Zsoil), doc = "Minimum root depth (mm)").default
else:
self.minZr = param.Number(float(csvLine['minZr']), bounds=(1, 10000), doc = "Minimum root depth (mm)").default
else:
self.optimList.append("minZr")
if (csvLine['maxZr'] != "optim"):
if (csvLine['Zsoil'] != "optim"):
self.maxZr = param.Number(float(csvLine['maxZr']), bounds=(0, self.Zsoil-1), doc = "Maximum root depth (mm)").default
else:
self.maxZr = param.Number(float(csvLine['maxZr']), bounds=(0, 10000-1), doc = "Maximum root depth (mm)").default
else:
self.optimList.append("maxZr")
if (csvLine['p'] != "optim"):
self.p = param.Number(float(csvLine['p']), bounds=(0, 1), doc = "Fraction of readily available water").default
else:
self.optimList.append("p")
# Irrigation parameters
self.irrigFW = param.Number(float(csvLine['FW']), bounds=(0, 100), doc = "% of soil wetted by irrigation").default
self.Irrig_auto = param.Integer(int(float(csvLine['Irrig_auto'])), doc = "1 if the automatic irrigation mode is activated").default
self.Irrig_man = param.Integer(int(float(csvLine['Irrig_man'])), doc = "1 if the manual irrigation mode is activated").default
if (csvLine['Lame_max'] != "optim"):
self.Lame_max = param.Number(float(csvLine['Lame_max']), doc = "Maximum of irrigation height for each irrigation event (in mm)").default
else:
self.optimList.append("Lame_max")
if (csvLine['minDays'] != "optim"):
self.irrigMinDays = param.Integer(int(float(csvLine['minDays'])), bounds=(0, None), doc = "Minimum number of days between two irrigation events").default
else:
self.optimList.append("minDays")
if (csvLine['Kcbmin_start'] != "optim"):
self.Kcbmin_start = param.Number(float(csvLine['Kcbmin_start']), bounds=(0, 1), doc = "Minimum Kcb value above which irrigation may start").default
else:
self.optimList.append("Kcbmin_start")
if (csvLine['Kcbmax_stop'] != "optim"):
self.Kcbmax_stop = param.Number(float(csvLine['Kcbmax_stop']), bounds=(0, 1), doc = "Fraction of peak Kcb value below which irrigation stops").default
else:
self.optimList.append("Kcbmax_stop")
if (csvLine['Kcmax'] != "optim"):
self.Kcmax = param.Number(float(csvLine['Kcmax']), bounds=(0, None), doc = "pas d'info").default
else:
self.optimList.append("Kcmax")
if (csvLine['Fc_stop'] != "optim"):
self.Fc_stop = param.Number(float(csvLine['Fc_stop']), bounds=(0, None), doc = "pas d'info").default
else:
self.optimList.append("Fc_stop")
if (csvLine['Start_date_Irr'] != "optim"):
self.Start_date_Irr = param.Number(int(float(csvLine['Start_date_Irr'])), bounds=(0, None), doc = "pas d'info").default
else:
self.optimList.append("Start_date_Irr")
if (csvLine["p_trigger"] != "optim"):
self.p_trigger = param.Number(float(csvLine['p_trigger']), bounds=(-1, 1), doc = "Fraction of water storage capacity below which irrigation is triggered").default
else:
self.optimList.append("Fc_stop")
def setParam(self, paramName, value):
# Soil parameters
if paramName == "REW":
self.REW = value
elif paramName == "Init_RU":
self.Init_RU = value
elif paramName == "minZr":
self.minZr = value
elif paramName == "maxZr":
self.maxZr = value
elif paramName == "Ze":
self.Ze = value
elif paramName == "Zsoil":
self.Zsoil = value
elif paramName == "DiffR":
self.DiffR = value
elif paramName == "DiffE":
self.DiffE = value
# Irrigation parameters
elif paramName == "Lame_max":
self.Lame_max = value
elif paramName == "minDays":
self.irrigMinDays = value
# Vegetation parameters
elif paramName == "FminFC":
self.ndviFCminFC = value
elif paramName == "FmaxFC":
self.ndviFCmaxFC = value
elif paramName == "Fc_stop":
self.Fc_stop = value
elif paramName == "Kcmax":
self.Kcmax = value
elif paramName == "Kcbmin_start" :
self.Kcbmin_start = value
elif paramName == "Kcbmax_stop" :
self.Kcbmax_stop = value
elif paramName == "Plateau" :
self.ndviPlateau = value
elif paramName == "Fslope" :
self.ndviFCslope = value
elif paramName == "Foffset" :
self.ndviFCoffset = value
elif paramName == "KmaxKcb" :
self.ndviKcbmaxKcb = value
elif paramName == "KminKcb" :
self.ndviKcbminKcb = value
elif paramName == "Kslope" :
self.ndviKcbslope = value
elif paramName == "Koffset" :
self.ndviKcboffset = value
elif paramName == "m" :
self.m = value
elif paramName == "p" :
self.p = value
elif paramName == "p_trigger":
self.p_trigger = value
class samir_parameters:
"""
Load all parameters for multiples classes in one object.
Load all parameters for multiples classes in one object.
The object has one
attribute (`.table`) that contains a `pandas DataFrame` with all paramters (rows)
for all classes (columns).
It also contains :
- a `scale_factor` column (first column) that allows to convert all parameters to
integer values for reduced memory usage
- a `Default` column (second column) that contains default values to fill in
missing values
Example of the parameter table:
```
scale_factor Default class1 class2 class3
ClassName
ClassNumber 1 0.00 1.00 2.000 3.000
FminNDVI 1000 0.20 0.20 0.100 0.100
FmaxNDVI 1000 0.90 0.90 0.900 0.900
FminFC 1000 0.90 0.90 0.900 0.900
FmaxFC 1000 1.00 0.90 1.000 1.000
Fslope 1000 1.40 1.50 1.500 1.500
Foffset 1000 -0.10 -0.10 -0.100 -0.100
Plateau 1 70.00 70.00 70.000 70.000
KminNDVI 1000 0.10 0.10 0.100 0.100
KmaxNDVI 1000 0.90 0.90 0.900 0.900
KminKcb 1000 0.00 0.20 0.000 0.000
KmaxKcb 1000 0.98 1.00 1.100 1.100
Kslope 1000 1.60 1.60 1.600 1.600
Koffset 1000 -0.10 -0.10 -0.100 -0.100
Zsoil 1 2000.00 1600.00 1550.000 1550.000
... ... ... ... ... ...
Kcmax 1000 1.15 1.15 1.15 1.15
Fc_stop 1000 0.15 0.15 0.15 0.15
Start_date_Irr 1 0.00 0.00 0.00 0.00
p_trigger 1 0.00 0.00 0.00 0.00
```
"""
def __init__(self, paramFile, mode_init = 1):
self.classes = {}
def __init__(self, paramFile):
# Read csv file with Pandas
csvFile = read_csv(paramFile, header = None)
csvFile = read_csv(paramFile)
# Index file for correct conversion to dictionnary
csvFile.index = csvFile.iloc[:,0]
csvFile.replace(nan, '', inplace = True)
defaultClass = True
csvFile.drop(columns = ['ClassName'], inplace = True)
# Loop on columns
for column in csvFile.columns[1:]:
# Convert pandas column to dictionnary
line = csvFile[column].to_dict()
#TODO : @VR+@CO Intoduire ici une verification des valeurs
#!! notamment si min=max alors error_rel=0
#!! Ajouter la possibilité de configurer plusieurs land cover
if defaultClass:
defaultLine = line.copy()
elif line['ClassName'] in ['error_rel','error_abs','min','max']:
self.classes[line['ClassName']] ={}
for k in line.keys():
if k != 'ClassName':
if line[k] == '':
line[k] = 0
self.classes[line['ClassName']][k] = float(line[k])
continue
else:
for k in line.keys():
if line[k] == '':
line[k] = defaultLine[k]
self.classes[line['ClassName']] = samir_parameters_LC(line, defaultClass, mode_init)
defaultClass = False
# Replace missing parameters by their default values
csvFile[csvFile.columns[1:]] = csvFile[csvFile.columns[1:]].astype('float32')
for col in csvFile.columns[2:]:
mask = csvFile[col].isna()
csvFile.loc[mask, col] = csvFile.loc[mask, 'Default']
# Store dataframe in attribute table
self.table = csvFile
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment