Index: wflow-py/Sandbox/wflow_topoflex/reservoir_Sus.py =================================================================== diff -u -r5f72a83356683168a37f127593b6f33c4eccd3b5 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/Sandbox/wflow_topoflex/reservoir_Sus.py (.../reservoir_Sus.py) (revision 5f72a83356683168a37f127593b6f33c4eccd3b5) +++ wflow-py/Sandbox/wflow_topoflex/reservoir_Sus.py (.../reservoir_Sus.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -10,27 +10,28 @@ """ - import numpy import pdb from copy import copy as copylist try: - from wflow.wf_DynamicFramework import * + from wflow.wf_DynamicFramework import * except ImportError: - from wf_DynamicFramework import * + from wf_DynamicFramework import * import scipy + def selectSusR(i): if i == 1: - name = 'unsatSatZone_GWout' - elif i ==2: - name = 'unsatSatZone_noGWout' + name = "unsatSatZone_GWout" + elif i == 2: + name = "unsatSatZone_noGWout" elif i == 3: - name = 'unsatSatZone_noGWout_VSA' + name = "unsatSatZone_noGWout_VSA" return name -def unsatSatZone_noGWout_VSA(self,k): + +def unsatSatZone_noGWout_VSA(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Evaporation rate constrained by moisture stress via LP @@ -41,31 +42,50 @@ area is estimated, linear relation is derived from HAND distribution in wetland) - Code for ini-file: 3 """ - -# pdb.set_trace() - A = min(self.Co[k] * (1 + ((self.Sus_t[k]-self.susmax2[k])*(1-self.Co[k])) / ((self.susmax3[k]-self.susmax2[k])*self.Co[k])),1) - self.Qo = ifthenelse (self.Sus_t[k] >= self.susmax2[k], self.Pe * A,0) + + # pdb.set_trace() + A = min( + self.Co[k] + * ( + 1 + + ((self.Sus_t[k] - self.susmax2[k]) * (1 - self.Co[k])) + / ((self.susmax3[k] - self.susmax2[k]) * self.Co[k]) + ), + 1, + ) + self.Qo = ifthenelse(self.Sus_t[k] >= self.susmax2[k], self.Pe * A, 0) self.Sus[k] = self.Sus_t[k] + (self.Pe - self.Qo) - self.Eu1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sus[k] / (self.susmax2[k] * self.LP[k]),1) + self.Eu1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sus[k] / (self.susmax2[k] * self.LP[k]), 1 + ) self.Qd1 = self.Kd[k] * max((self.Sus[k] - self.susmax1[k]), 0) - + self.Sus[k] = self.Sus_t[k] + (self.Pe - self.Qo) - self.Eu1 - self.Qd1 - + self.Su_diff = ifthenelse(self.Sus[k] < 0, self.Sus[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qd1 + self.Eu1 > 0 , self.Qd1 + self.Eu1, 1)) * self.Su_diff - self.Qd = self.Qd1 + (self.Qd1/ifthenelse(self.Qd1 + self.Eu1 > 0 , self.Qd1 + self.Eu1, 1)) * self.Su_diff + self.Eu = ( + self.Eu1 + + (self.Eu1 / ifthenelse(self.Qd1 + self.Eu1 > 0, self.Qd1 + self.Eu1, 1)) + * self.Su_diff + ) + self.Qd = ( + self.Qd1 + + (self.Qd1 / ifthenelse(self.Qd1 + self.Eu1 > 0, self.Qd1 + self.Eu1, 1)) + * self.Su_diff + ) self.Sus[k] = self.Sus_t[k] + self.Pe - self.Qo - self.Eu - self.Qd - self.Sus[k] = ifthenelse(self.Sus[k] < 0, 0 , self.Sus[k]) - self.Su_diff2 = ifthen(self.Sus[k] < 0, self.Sus[k]) - - self.wbSus_[k] = self.Pe - self.Qo - self.Qd - self.Eu - self.Sus[k] + self.Sus_t[k] - + self.Sus[k] = ifthenelse(self.Sus[k] < 0, 0, self.Sus[k]) + self.Su_diff2 = ifthen(self.Sus[k] < 0, self.Sus[k]) + + self.wbSus_[k] = self.Pe - self.Qo - self.Qd - self.Eu - self.Sus[k] + self.Sus_t[k] + self.Eu_[k] = self.Eu self.Qo_[k] = self.Qo self.Qd_[k] = self.Qd self.Su_diff_[k] = self.Su_diff -def unsatSatZone_noGWout(self,k): + +def unsatSatZone_noGWout(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Evaporation rate constrained by moisture stress via LP @@ -74,29 +94,40 @@ - the saturated part of the reservoir has only drainage outflow - Code for ini-file: 2 """ - - self.Qo = max (self.Pe - (self.susmax2[k] - self.Sus_t[k]), 0) + + self.Qo = max(self.Pe - (self.susmax2[k] - self.Sus_t[k]), 0) self.Sus[k] = self.Sus_t[k] + self.Pe - self.Qo - self.Eu1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sus[k] / (self.susmax2[k] * self.LP[k]),1) + self.Eu1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sus[k] / (self.susmax2[k] * self.LP[k]), 1 + ) self.Qd1 = self.Kd[k] * max((self.Sus[k] - self.susmax1[k]), 0) - + self.Sus[k] = self.Sus_t[k] + self.Pe - self.Qo - self.Eu1 - self.Qd1 - + self.Su_diff = ifthenelse(self.Sus[k] < 0, self.Sus[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qd1 + self.Eu1 > 0 , self.Qd1 + self.Eu1, 1)) * self.Su_diff - self.Qd = self.Qd1 + (self.Qd1/ifthenelse(self.Qd1 + self.Eu1 > 0 , self.Qd1 + self.Eu1, 1)) * self.Su_diff + self.Eu = ( + self.Eu1 + + (self.Eu1 / ifthenelse(self.Qd1 + self.Eu1 > 0, self.Qd1 + self.Eu1, 1)) + * self.Su_diff + ) + self.Qd = ( + self.Qd1 + + (self.Qd1 / ifthenelse(self.Qd1 + self.Eu1 > 0, self.Qd1 + self.Eu1, 1)) + * self.Su_diff + ) self.Sus[k] = self.Sus_t[k] + self.Pe - self.Qo - self.Eu - self.Qd - self.Sus[k] = ifthenelse(self.Sus[k] < 0, 0 , self.Sus[k]) - self.Su_diff2 = ifthen(self.Sus[k] < 0, self.Sus[k]) - - self.wbSus_[k] = self.Pe - self.Qo - self.Qd - self.Eu - self.Sus[k] + self.Sus_t[k] - + self.Sus[k] = ifthenelse(self.Sus[k] < 0, 0, self.Sus[k]) + self.Su_diff2 = ifthen(self.Sus[k] < 0, self.Sus[k]) + + self.wbSus_[k] = self.Pe - self.Qo - self.Qd - self.Eu - self.Sus[k] + self.Sus_t[k] + self.Eu_[k] = self.Eu self.Qo_[k] = self.Qo self.Qd_[k] = self.Qd self.Su_diff_[k] = self.Su_diff -def unsatSatZone_GWout(self,k): + +def unsatSatZone_GWout(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Evaporation rate constrained by moisture stress via LP @@ -106,28 +137,40 @@ - NIET UITGEBREID GETEST VOOR SLUITEN WB, NU OOK CONFLICT MET Qs - Code for ini-file: 1 """ - - self.Qo = max (self.Pe - (self.susmax2[k] - self.Sus_t[k]), 0) + + self.Qo = max(self.Pe - (self.susmax2[k] - self.Sus_t[k]), 0) self.Sus[k] = self.Sus_t[k] + self.Pe - self.Qo - self.Eu1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sus[k] / (self.susmax2[k] * self.LP[k]),1) + self.Eu1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sus[k] / (self.susmax2[k] * self.LP[k]), 1 + ) self.Qd1 = self.Kd[k] * max((self.Sus[k] - self.susmax1[k]), 0) - + self.Sus[k] = self.Sus_t[k] + self.Pe - self.Qo - self.Eu1 - self.Qd1 - + self.Su_diff = ifthenelse(self.Sus[k] < 0, self.Sus[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qd1 + self.Eu1 > 0 , self.Qd1 + self.Eu1, 1)) * self.Su_diff - self.Qd = self.Qd1 + (self.Qd1/ifthenelse(self.Qd1 + self.Eu1 > 0 , self.Qd1 + self.Eu1, 1)) * self.Su_diff + self.Eu = ( + self.Eu1 + + (self.Eu1 / ifthenelse(self.Qd1 + self.Eu1 > 0, self.Qd1 + self.Eu1, 1)) + * self.Su_diff + ) + self.Qd = ( + self.Qd1 + + (self.Qd1 / ifthenelse(self.Qd1 + self.Eu1 > 0, self.Qd1 + self.Eu1, 1)) + * self.Su_diff + ) self.Sus[k] = self.Sus_t[k] + self.Pe - self.Qo - self.Eu - self.Qd - self.Sus[k] = ifthenelse(self.Sus[k] < 0, 0 , self.Sus[k]) - self.Su_diff2 = ifthen(self.Sus[k] < 0, self.Sus[k]) - - self.Qus = self.Ks[k] * self.Sus[k] + self.Sus[k] = ifthenelse(self.Sus[k] < 0, 0, self.Sus[k]) + self.Su_diff2 = ifthen(self.Sus[k] < 0, self.Sus[k]) + + self.Qus = self.Ks[k] * self.Sus[k] self.Sus[k] = self.Sus[k] - self.Qus - - self.wbSus_[k] = self.Pe - self.Qo - self.Qd - self.Eu - self.Qus - self.Sus + self.Sus_t - + + self.wbSus_[k] = ( + self.Pe - self.Qo - self.Qd - self.Eu - self.Qus - self.Sus + self.Sus_t + ) + self.Eu_[k] = self.Eu self.Qo_[k] = self.Qo self.Qd_[k] = self.Qd self.Qus_[k] = self.Qus - self.Su_diff_[k] = self.Su_diff \ No newline at end of file + self.Su_diff_[k] = self.Su_diff Index: wflow-py/Scripts/wtools_py/modelbuilder.py =================================================================== diff -u -re1f340bff3b1ce5d876896ccac87be92642b8215 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/Scripts/wtools_py/modelbuilder.py (.../modelbuilder.py) (revision e1f340bff3b1ce5d876896ccac87be92642b8215) +++ wflow-py/Scripts/wtools_py/modelbuilder.py (.../modelbuilder.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -25,57 +25,95 @@ import wflow.wflowtools_lib as wt from wflow import ogr2ogr -SERVER_URL = 'http://hydro-engine.appspot.com' +SERVER_URL = "http://hydro-engine.appspot.com" @click.command() -@click.option('--geojson-path', - help='Path to a GeoJSON file with the geometry that needs to be part of the model.') -@click.option('--cellsize', - default=0.01, show_default=True, - help='Desired model cell size in decimal degrees.') -@click.option('--model', - type=click.Choice(['sbm', 'hbv', 'w3ra']), - default='sbm', show_default=True, - help='Name of the WFlow model concept.') -@click.option('--timestep', - type=click.Choice(['hourly', 'daily']), - default='daily', show_default=True, - help='Model time step - daily or hourly (only for hbv).') -@click.option('--name', - help='Name of the WFlow case.') -@click.option('--case-template', - help='Name of the template WFlow case.') -@click.option('--case-path', - default='.', show_default=True, - help='Path where both the template and created case reside.') -@click.option('--fews/--no-fews', - default=False, show_default=True, - help='Flag indicating whether the WFlow case is part of a Delft-FEWS setup.') -@click.option('--fews-config-path', - default='Config', show_default=True, - help='Path to the Delft-FEWS config directory.') -@click.option('--dem-path', - help='Optionally provide a local or improved Digital Elevation Model (DEM) ' - 'to use instead of the default global DEM.') -@click.option('--river-path', - help='Optionally provide a local or improved river vector file ' - 'to use instead of the default global one.') -@click.option('--outlet-path', - help='Optionally provide a point layer with outlets ' - 'to use instead of the automatically generated one.') -@click.option('--region-filter', - type=click.Choice( - ['catchments-upstream', 'catchments-intersection', 'region']), - default='catchments-upstream', show_default=True, - help='Tell hydro-engine which model area to pick, by default this ' - 'is everything upstream of the provided geometry, but it is also ' - 'possible to get only the current catchment (catchments-intersection), ' - 'or just exactly the provided geometry (region), like your own ' - 'catchment polygon.') -def build_model(geojson_path, cellsize, model, timestep, name, case_template, - case_path, fews, fews_config_path, dem_path, river_path, outlet_path, - region_filter): +@click.option( + "--geojson-path", + help="Path to a GeoJSON file with the geometry that needs to be part of the model.", +) +@click.option( + "--cellsize", + default=0.01, + show_default=True, + help="Desired model cell size in decimal degrees.", +) +@click.option( + "--model", + type=click.Choice(["sbm", "hbv", "w3ra"]), + default="sbm", + show_default=True, + help="Name of the WFlow model concept.", +) +@click.option( + "--timestep", + type=click.Choice(["hourly", "daily"]), + default="daily", + show_default=True, + help="Model time step - daily or hourly (only for hbv).", +) +@click.option("--name", help="Name of the WFlow case.") +@click.option("--case-template", help="Name of the template WFlow case.") +@click.option( + "--case-path", + default=".", + show_default=True, + help="Path where both the template and created case reside.", +) +@click.option( + "--fews/--no-fews", + default=False, + show_default=True, + help="Flag indicating whether the WFlow case is part of a Delft-FEWS setup.", +) +@click.option( + "--fews-config-path", + default="Config", + show_default=True, + help="Path to the Delft-FEWS config directory.", +) +@click.option( + "--dem-path", + help="Optionally provide a local or improved Digital Elevation Model (DEM) " + "to use instead of the default global DEM.", +) +@click.option( + "--river-path", + help="Optionally provide a local or improved river vector file " + "to use instead of the default global one.", +) +@click.option( + "--outlet-path", + help="Optionally provide a point layer with outlets " + "to use instead of the automatically generated one.", +) +@click.option( + "--region-filter", + type=click.Choice(["catchments-upstream", "catchments-intersection", "region"]), + default="catchments-upstream", + show_default=True, + help="Tell hydro-engine which model area to pick, by default this " + "is everything upstream of the provided geometry, but it is also " + "possible to get only the current catchment (catchments-intersection), " + "or just exactly the provided geometry (region), like your own " + "catchment polygon.", +) +def build_model( + geojson_path, + cellsize, + model, + timestep, + name, + case_template, + case_path, + fews, + fews_config_path, + dem_path, + river_path, + outlet_path, + region_filter, +): """Prepare a simple WFlow model, anywhere, based on global datasets.""" # lists below need to stay synchronized, not sure of a better way @@ -90,35 +128,38 @@ dem_path, river_path, outlet_path, - region_filter - ] = [encode_utf8(p) for p in [ - geojson_path, - model, - timestep, - name, - case_template, - case_path, - fews_config_path, - dem_path, - river_path, - outlet_path, - region_filter - ]] + region_filter, + ] = [ + encode_utf8(p) + for p in [ + geojson_path, + model, + timestep, + name, + case_template, + case_path, + fews_config_path, + dem_path, + river_path, + outlet_path, + region_filter, + ] + ] # fill in the dependent defaults if name is None: - name = 'wflow_{}_case'.format(model) + name = "wflow_{}_case".format(model) if case_template is None: - case_template = 'wflow_{}_template'.format(model) - if model == 'hbv': - if timestep == 'hourly': - case_template = 'wflow_{}_hourly_template'.format(model) + case_template = "wflow_{}_template".format(model) + if model == "hbv": + if timestep == "hourly": + case_template = "wflow_{}_hourly_template".format(model) else: - case_template = 'wflow_{}_daily_template'.format(model) + case_template = "wflow_{}_daily_template".format(model) # assumes it is in decimal degrees, see Geod case = os.path.join(case_path, name) - path_catchment = os.path.join(case, 'data/catchments/catchments.geojson') + path_catchment = os.path.join(case, "data/catchments/catchments.geojson") region = hydro_engine_geometry(geojson_path, region_filter) @@ -127,9 +168,9 @@ x, y = centroid.x, centroid.y filter_upstream_gt = 1000 - crs = 'EPSG:4326' + crs = "EPSG:4326" - g = Geod(ellps='WGS84') + g = Geod(ellps="WGS84") # convert to meters in the center of the grid # Earth Engine expects meters _, _, crossdist_m = g.inv(x, y, x + cellsize, y + cellsize) @@ -139,133 +180,178 @@ copycase(case_template, case) # create folder structure for data folder - for d in ['catchments', 'dem', 'rivers']: - dir_data = os.path.join(case, 'data', d) - ensure_dir_exists(dir_data) + for d in ["catchments", "dem", "rivers"]: + dir_data = os.path.join(case, "data", d) + ensure_dir_exists(dir_data) # create grid - path_log = 'wtools_create_grid.log' - dir_mask = os.path.join(case, 'mask') - projection = 'EPSG:4326' + path_log = "wtools_create_grid.log" + dir_mask = os.path.join(case, "mask") + projection = "EPSG:4326" - download_catchments(region, path_catchment, geojson_path, region_filter=region_filter) + download_catchments( + region, path_catchment, geojson_path, region_filter=region_filter + ) cg_extent = path_catchment - cg.main(path_log, dir_mask, cg_extent, projection, - cellsize, locationid=name, snap=True) - mask_tif = os.path.join(dir_mask, 'mask.tif') + cg.main( + path_log, dir_mask, cg_extent, projection, cellsize, locationid=name, snap=True + ) + mask_tif = os.path.join(dir_mask, "mask.tif") with rasterio.open(mask_tif) as ds: bbox = ds.bounds - # create static maps - dir_dest = os.path.join(case, 'staticmaps') + dir_dest = os.path.join(case, "staticmaps") # use custom inifile, default high res ldd takes too long - path_inifile = os.path.join(case, 'data/staticmaps.ini') - path_dem_in = os.path.join(case, 'data/dem/dem.tif') - dir_lai = os.path.join(case, 'data/parameters/clim') + path_inifile = os.path.join(case, "data/staticmaps.ini") + path_dem_in = os.path.join(case, "data/dem/dem.tif") + dir_lai = os.path.join(case, "data/parameters/clim") if river_path is None: # download the global dataset - river_data_path = os.path.join(case, 'data/rivers/rivers.geojson') + river_data_path = os.path.join(case, "data/rivers/rivers.geojson") # raise ValueError("User must supply river_path for now, see hydro-engine#14") - download_rivers(region, river_data_path, - filter_upstream_gt, region_filter=region_filter) + download_rivers( + region, river_data_path, filter_upstream_gt, region_filter=region_filter + ) else: # take the local dataset, reproject and clip # command line equivalent of # ogr2ogr -t_srs EPSG:4326 -f GPKG -overwrite -clipdst xmin ymin xmax ymax rivers.gpkg rivers.shp - river_data_path = os.path.join(case, 'data/rivers/rivers.gpkg') - ogr2ogr.main(['', '-t_srs', 'EPSG:4326', '-f', 'GPKG', '-overwrite', '-clipdst', - str(bbox.left), str(bbox.bottom), str(bbox.right), str(bbox.top), river_data_path, river_path]) + river_data_path = os.path.join(case, "data/rivers/rivers.gpkg") + ogr2ogr.main( + [ + "", + "-t_srs", + "EPSG:4326", + "-f", + "GPKG", + "-overwrite", + "-clipdst", + str(bbox.left), + str(bbox.bottom), + str(bbox.right), + str(bbox.top), + river_data_path, + river_path, + ] + ) if dem_path is None: # download the global dem - download_raster(region, path_dem_in, 'dem', cellsize_m, - crs, region_filter=region_filter) + download_raster( + region, path_dem_in, "dem", cellsize_m, crs, region_filter=region_filter + ) else: # warp the local dem onto model grid - wt.warp_like(dem_path, path_dem_in, mask_tif, - format='GTiff', co={'dtype': 'float32'}, resampling=warp.Resampling.med) + wt.warp_like( + dem_path, + path_dem_in, + mask_tif, + format="GTiff", + co={"dtype": "float32"}, + resampling=warp.Resampling.med, + ) other_maps = { - 'sbm': [ - 'FirstZoneCapacity', - 'FirstZoneKsatVer', - 'FirstZoneMinCapacity', - 'InfiltCapSoil', - 'M', - 'PathFrac', - 'WaterFrac', - 'thetaS', - 'soil_type', - 'landuse'], - 'hbv': [ - 'BetaSeepage', - 'Cfmax', - 'CFR', - 'FC', - 'K0', - 'LP', - 'Pcorr', - 'PERC', - 'SFCF', - 'TT', - 'WHC']} + "sbm": [ + "FirstZoneCapacity", + "FirstZoneKsatVer", + "FirstZoneMinCapacity", + "InfiltCapSoil", + "M", + "PathFrac", + "WaterFrac", + "thetaS", + "soil_type", + "landuse", + ], + "hbv": [ + "BetaSeepage", + "Cfmax", + "CFR", + "FC", + "K0", + "LP", + "Pcorr", + "PERC", + "SFCF", + "TT", + "WHC", + ], + } # TODO rename these in hydro-engine newnames = { - 'FirstZoneKsatVer': 'KsatVer', - 'FirstZoneMinCapacity': 'SoilMinThickness', - 'FirstZoneCapacity': 'SoilThickness', - 'landuse': 'wflow_landuse', - 'soil_type': 'wflow_soil' + "FirstZoneKsatVer": "KsatVer", + "FirstZoneMinCapacity": "SoilMinThickness", + "FirstZoneCapacity": "SoilThickness", + "landuse": "wflow_landuse", + "soil_type": "wflow_soil", } # destination paths path_other_maps = [] for param in other_maps[model]: - path = os.path.join(case, 'data/parameters', - newnames.get(param, param) + '.tif') + path = os.path.join( + case, "data/parameters", newnames.get(param, param) + ".tif" + ) path_other_maps.append(path) for param, path in zip(other_maps[model], path_other_maps): - if model == 'sbm': - download_raster(region, path, param, cellsize_m, - crs, region_filter=region_filter) - elif model == 'hbv': + if model == "sbm": + download_raster( + region, path, param, cellsize_m, crs, region_filter=region_filter + ) + elif model == "hbv": # these are not yet in the earth engine, use local paths - if timestep == 'hourly': - path_staticmaps_global = r'p:\1209286-earth2observe\HBV-GLOBAL\staticmaps_hourly' + if timestep == "hourly": + path_staticmaps_global = ( + r"p:\1209286-earth2observe\HBV-GLOBAL\staticmaps_hourly" + ) else: - path_staticmaps_global = r'p:\1209286-earth2observe\HBV-GLOBAL\staticmaps' - path_in = os.path.join(path_staticmaps_global, param + '.tif') - + path_staticmaps_global = ( + r"p:\1209286-earth2observe\HBV-GLOBAL\staticmaps" + ) + path_in = os.path.join(path_staticmaps_global, param + ".tif") + # warp the local staticmaps onto model grid - wt.warp_like(path_in, path, mask_tif, - format='GTiff', co={'dtype': 'float32'}, resampling=warp.Resampling.med) + wt.warp_like( + path_in, + path, + mask_tif, + format="GTiff", + co={"dtype": "float32"}, + resampling=warp.Resampling.med, + ) - - if model == 'sbm': + if model == "sbm": ensure_dir_exists(dir_lai) for m in range(1, 13): mm = str(m).zfill(2) - path = os.path.join(dir_lai, 'LAI00000.0{}'.format(mm)) + path = os.path.join(dir_lai, "LAI00000.0{}".format(mm)) download_raster( - region, path, 'LAI{}'.format(mm), cellsize_m, crs, region_filter=region_filter) + region, + path, + "LAI{}".format(mm), + cellsize_m, + crs, + region_filter=region_filter, + ) else: # TODO this creates defaults in static_maps, disable this behavior? # or otherwise adapt static_maps for the other models dir_lai = None # create default folder structure for running wflow - dir_inmaps = os.path.join(case, 'inmaps') + dir_inmaps = os.path.join(case, "inmaps") ensure_dir_exists(dir_inmaps) - dir_instate = os.path.join(case, 'instate') + dir_instate = os.path.join(case, "instate") ensure_dir_exists(dir_instate) - for d in ['instate', 'intbl', 'intss', 'outmaps', 'outstate', 'outsum', 'runinfo']: - dir_run = os.path.join(case, 'run_default', d) + for d in ["instate", "intbl", "intss", "outmaps", "outstate", "outsum", "runinfo"]: + dir_run = os.path.join(case, "run_default", d) ensure_dir_exists(dir_run) if outlet_path is None: @@ -274,49 +360,90 @@ outlets = outlets_coords(path_catchment, river_data_path) else: # take the local dataset, reproject and clip - outlet_data_path = os.path.join(case, 'data/rivers/outlets.gpkg') - ogr2ogr.main(['', '-t_srs', 'EPSG:4326', '-f', 'GPKG', '-overwrite', '-clipdst', - str(bbox.left), str(bbox.bottom), str(bbox.right), str(bbox.top), outlet_data_path, outlet_path]) + outlet_data_path = os.path.join(case, "data/rivers/outlets.gpkg") + ogr2ogr.main( + [ + "", + "-t_srs", + "EPSG:4326", + "-f", + "GPKG", + "-overwrite", + "-clipdst", + str(bbox.left), + str(bbox.bottom), + str(bbox.right), + str(bbox.top), + outlet_data_path, + outlet_path, + ] + ) x = [] y = [] with fiona.open(outlet_data_path) as c: for f in c: - coords = f['geometry']['coordinates'] + coords = f["geometry"]["coordinates"] x.append(coords[0]) y.append(coords[1]) outlets_x = np.array(x) outlets_y = np.array(y) outlets = outlets_x, outlets_y - sm.main(dir_mask, dir_dest, path_inifile, path_dem_in, river_data_path, - path_catchment, lai=dir_lai, other_maps=path_other_maps, - outlets=outlets) + sm.main( + dir_mask, + dir_dest, + path_inifile, + path_dem_in, + river_data_path, + path_catchment, + lai=dir_lai, + other_maps=path_other_maps, + outlets=outlets, + ) if fews: # save default state-files in FEWS-config - dir_state = os.path.join(case, 'outstate') + dir_state = os.path.join(case, "outstate") ensure_dir_exists(dir_state) - if model == 'sbm': - state_files = ['CanopyStorage.map', 'GlacierStore.map', 'ReservoirVolume.map', 'SatWaterDepth.map', 'Snow.map', - 'SnowWater.map', 'SurfaceRunoff.map', 'SurfaceRunoffDyn.map', 'TSoil.map', - 'UStoreLayerDepth_0.map', 'WaterLevel.map', 'WaterLevelDyn.map'] - elif model == 'hbv': - state_files = ['DrySnow.map', 'FreeWater.map', 'InterceptionStorage.map', 'LowerZoneStorage.map', - 'SoilMoisture.map', 'SurfaceRunoff.map', 'UpperZoneStorage.map', 'WaterLevel.map'] - zip_name = name + '_GA_Historical default.zip' + if model == "sbm": + state_files = [ + "CanopyStorage.map", + "GlacierStore.map", + "ReservoirVolume.map", + "SatWaterDepth.map", + "Snow.map", + "SnowWater.map", + "SurfaceRunoff.map", + "SurfaceRunoffDyn.map", + "TSoil.map", + "UStoreLayerDepth_0.map", + "WaterLevel.map", + "WaterLevelDyn.map", + ] + elif model == "hbv": + state_files = [ + "DrySnow.map", + "FreeWater.map", + "InterceptionStorage.map", + "LowerZoneStorage.map", + "SoilMoisture.map", + "SurfaceRunoff.map", + "UpperZoneStorage.map", + "WaterLevel.map", + ] + zip_name = name + "_GA_Historical default.zip" - zip_loc = os.path.join(fews_config_path, 'ColdStateFiles', zip_name) + zip_loc = os.path.join(fews_config_path, "ColdStateFiles", zip_name) path_csf = os.path.dirname(zip_loc) ensure_dir_exists(path_csf) - mask = pcr.readmap(os.path.join(dir_mask, 'mask.map')) + mask = pcr.readmap(os.path.join(dir_mask, "mask.map")) - with zipfile.ZipFile(zip_loc, mode='w') as zf: + with zipfile.ZipFile(zip_loc, mode="w") as zf: for state_file in state_files: state_path = os.path.join(dir_state, state_file) pcr.report(pcr.cover(mask, pcr.scalar(0)), state_path) - zf.write(state_path, state_file, - compress_type=zipfile.ZIP_DEFLATED) + zf.write(state_path, state_file, compress_type=zipfile.ZIP_DEFLATED) def copycase(srccase, dstcase): @@ -350,61 +477,89 @@ return r -def download_catchments(region, path, path_geojson, - region_filter='catchments-upstream', catchment_level=6): +def download_catchments( + region, path, path_geojson, region_filter="catchments-upstream", catchment_level=6 +): """Download a GeoJSON of the catchment upstream of `region`. Function copied from hydroengine, with added error reporting""" - if region_filter == 'region': + if region_filter == "region": # use the geojson as catchment # some checks are already done in hydro_engine_geometry shutil.copy2(path_geojson, path) else: - data = {'type': 'get_catchments', 'region': region, 'dissolve': True, - 'region_filter': region_filter, 'catchment_level': catchment_level} - r = post_data(SERVER_URL + '/get_catchments', data) - with open(path, 'w') as f: + data = { + "type": "get_catchments", + "region": region, + "dissolve": True, + "region_filter": region_filter, + "catchment_level": catchment_level, + } + r = post_data(SERVER_URL + "/get_catchments", data) + with open(path, "w") as f: f.write(r.text) -def download_rivers(region, path, filter_upstream_gt, - region_filter='catchments-upstream', catchment_level=6): +def download_rivers( + region, + path, + filter_upstream_gt, + region_filter="catchments-upstream", + catchment_level=6, +): """Download a GeoJSON of the rivers in the upstream catchment of `region`. Function copied from hydroengine, with added error reporting""" - data = {'type': 'get_rivers', 'region': region, - 'region_filter': region_filter, 'catchment_level': catchment_level} + data = { + "type": "get_rivers", + "region": region, + "region_filter": region_filter, + "catchment_level": catchment_level, + } if filter_upstream_gt: - data['filter_upstream_gt'] = filter_upstream_gt + data["filter_upstream_gt"] = filter_upstream_gt - r = post_data(SERVER_URL + '/get_rivers', data) + r = post_data(SERVER_URL + "/get_rivers", data) # download from url - url = json.loads(r.text)['url'] + url = json.loads(r.text)["url"] r = get_data(url) - with open(path, 'wb') as f: + with open(path, "wb") as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) -def download_raster(region, path, variable, cell_size, crs, - region_filter='catchments-upstream', catchment_level=6): +def download_raster( + region, + path, + variable, + cell_size, + crs, + region_filter="catchments-upstream", + catchment_level=6, +): """Download a GeoTIFF raster of `variable` in the upstream catchment of `region`. Function copied from hydroengine, with added error reporting""" path_name = os.path.splitext(path)[0] # print region.type - with open('db.json', 'w') as f: + with open("db.json", "w") as f: f.write(geojson.dumps(region)) # print region - data = {'type': 'get_raster', 'region': region, 'variable': variable, - 'cell_size': cell_size, 'crs': crs, 'region_filter': region_filter, - 'catchment_level': catchment_level} + data = { + "type": "get_raster", + "region": region, + "variable": variable, + "cell_size": cell_size, + "crs": crs, + "region_filter": region_filter, + "catchment_level": catchment_level, + } - r = post_data(SERVER_URL + '/get_raster', data) + r = post_data(SERVER_URL + "/get_raster", data) # download from url - url = json.loads(r.text)['url'] + url = json.loads(r.text)["url"] r = get_data(url) # download zip into a temporary file @@ -415,13 +570,13 @@ temp_dir = tempfile.mkdtemp() # unzip and rename both tfw and tif - with zipfile.ZipFile(f.name, 'r') as zf: + with zipfile.ZipFile(f.name, "r") as zf: items = zf.namelist() zf.extractall(temp_dir) # move extracted files to the target path src_tfw = os.path.join(temp_dir, items[0]) - dst_tfw = path_name + '.tfw' + dst_tfw = path_name + ".tfw" if os.path.exists(dst_tfw): os.remove(dst_tfw) os.rename(src_tfw, dst_tfw) @@ -451,29 +606,33 @@ if not d.is_valid: raise AssertionError( - '{} is not a valid GeoJSON file\n{}'.format(path_geojson, d.errors())) + "{} is not a valid GeoJSON file\n{}".format(path_geojson, d.errors()) + ) # this needs special casing since we want to be able to specify a # FeatureCollection of catchment polygons, though at the same time make it # compatible with the hydro-engine 1 geometry requirement - polytypes = ('Polygon', 'MultiPolygon') - if region_filter == 'region': + polytypes = ("Polygon", "MultiPolygon") + if region_filter == "region": # these polygon checks should cover all types of GeoJSON - if d.type == 'FeatureCollection': + if d.type == "FeatureCollection": # this should check all features gtype = d.features[0].geometry.type if gtype not in polytypes: raise ValueError( - 'Geometry type in {} is {}, needs to be a polygon'.format(path_geojson, gtype)) + "Geometry type in {} is {}, needs to be a polygon".format( + path_geojson, gtype + ) + ) # combine features into 1 geometry polys = [] for fcatch in d.features: - g = sg.shape(fcatch['geometry']) + g = sg.shape(fcatch["geometry"]) polys.append(g) # now simplify it to a rectangular polygon bnds = unary_union(polys).bounds geom = sg.mapping(sg.box(*bnds)) - elif d.type == 'Feature': + elif d.type == "Feature": assert d.geometry.type in polytypes geom = d.geometry else: @@ -483,13 +642,16 @@ bnds = sg.shape(geom).bounds geom = sg.mapping(sg.box(*bnds)) else: - if d.type == 'FeatureCollection': + if d.type == "FeatureCollection": nfeatures = len(d.features) if nfeatures != 1: raise AssertionError( - 'Expecting 1 feature in {}, found {}'.format(path_geojson, nfeatures)) + "Expecting 1 feature in {}, found {}".format( + path_geojson, nfeatures + ) + ) geom = d.features[0].geometry - elif d.type == 'Feature': + elif d.type == "Feature": geom = d.geometry else: geom = d @@ -503,35 +665,37 @@ if path is None: return None else: - return path.encode('utf-8') + return path.encode("utf-8") def outlets_coords(path_catchment, river_data_path): """Get an array of X and Y coordinates of the outlets.""" - + outlets = find_outlets(path_catchment, river_data_path, max_dist=0.02) - outlets = sg.mapping(outlets)['coordinates'] - + outlets = sg.mapping(outlets)["coordinates"] + outlets_x = np.array([c[0] for c in outlets]) outlets_y = np.array([c[1] for c in outlets]) return outlets_x, outlets_y -def ne_coastal_zone(scale='medium', buffer=0.1): +def ne_coastal_zone(scale="medium", buffer=0.1): """Get a MultiPolygon of the coastal zone from Natural Earth""" - scales = {'large': '10m', 'medium': '50m', 'small': '110m'} + scales = {"large": "10m", "medium": "50m", "small": "110m"} res = scales[scale] - coastline_url = ('https://raw.githubusercontent.com/nvkelso/' - 'natural-earth-vector/master/geojson/ne_{}_coastline.geojson'.format(res)) + coastline_url = ( + "https://raw.githubusercontent.com/nvkelso/" + "natural-earth-vector/master/geojson/ne_{}_coastline.geojson".format(res) + ) r = requests.get(coastline_url) r.raise_for_status() js = r.json() coasts = [] - for f in js['features']: - linestring = sg.shape(f['geometry']) + for f in js["features"]: + linestring = sg.shape(f["geometry"]) polygon = linestring.buffer(buffer) coasts.append(polygon) @@ -560,7 +724,7 @@ geoms = [] with fiona.open(catch_path) as c: for f in c: - g = sg.shape(f['geometry']).boundary + g = sg.shape(f["geometry"]).boundary geoms.append(g) return unary_union(geoms) @@ -583,7 +747,7 @@ mp1 = [] # line end nodes with fiona.open(riv_path) as c: for f in c: - coords = f['geometry']['coordinates'] + coords = f["geometry"]["coordinates"] mp0.append(sg.Point(coords[0])) mp1.append(sg.Point(coords[-1])) @@ -593,7 +757,7 @@ return mp0.symmetric_difference(mp1) -if __name__ == '__main__': +if __name__ == "__main__": # use sys.argv[1:] to allow using PyCharm debugger # https://github.com/pallets/click/issues/536 build_model(sys.argv[1:]) Index: wflow-py/UnitTests/TestBMI_Init.py =================================================================== diff -u -r8b703906feb45c1eff40558e71f3e758b5b7b388 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/UnitTests/TestBMI_Init.py (.../TestBMI_Init.py) (revision 8b703906feb45c1eff40558e71f3e758b5b7b388) +++ wflow-py/UnitTests/TestBMI_Init.py (.../TestBMI_Init.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,21 +1,24 @@ -__author__ = 'schelle' +__author__ = "schelle" import unittest import logging import wflow.wflow_bmi as bmi import time import os import datetime + """ Simple test for wflow bmi framework """ -class MyTest(unittest.TestCase): +class MyTest(unittest.TestCase): def testbmiinitfuncs(self): bmiobj = bmi.wflowbmi_csdms() - bmiobj.initialize_config('wflow_sceleton/wflow_sceleton_notime.ini',loglevel=logging.INFO) + bmiobj.initialize_config( + "wflow_sceleton/wflow_sceleton_notime.ini", loglevel=logging.INFO + ) print("-------------- Time units: ") print(bmiobj.get_time_units()) print("-------------- Default current time: ") @@ -34,10 +37,9 @@ print("-------------- Updated end time: ") etime = datetime.datetime.utcfromtimestamp(bmiobj.get_end_time()) - print("Init model...") bmiobj.initialize_model() - print(bmiobj.dynModel._userModel().config.get("run",'starttime')) + print(bmiobj.dynModel._userModel().config.get("run", "starttime")) nstime = datetime.datetime.utcfromtimestamp(bmiobj.get_start_time()) @@ -64,5 +66,5 @@ bmiobj.finalize() -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() Index: wflow-py/UnitTests/TestBMI_bmi2runner.py =================================================================== diff -u -r00ef8178f6ccf04e542c869caa35837fd08279b5 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/UnitTests/TestBMI_bmi2runner.py (.../TestBMI_bmi2runner.py) (revision 00ef8178f6ccf04e542c869caa35837fd08279b5) +++ wflow-py/UnitTests/TestBMI_bmi2runner.py (.../TestBMI_bmi2runner.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,10 +1,11 @@ -__author__ = 'schelle' +__author__ = "schelle" import unittest import logging import sys -sys.path = ['../wflow'] + ['../'] + sys.path -sys.path = ['../Scripts'] + sys.path + +sys.path = ["../wflow"] + ["../"] + sys.path +sys.path = ["../Scripts"] + sys.path import bmi2runner as bmirun import time import os @@ -16,14 +17,11 @@ class MyTest(unittest.TestCase): - def testbmirunner(self): - bmirun.main(['-c','combined/bmirunner.ini']) - self.assertTrue(os.path.exists('combined/run_default/wflow.log')) + bmirun.main(["-c", "combined/bmirunner.ini"]) + self.assertTrue(os.path.exists("combined/run_default/wflow.log")) - - -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() Index: wflow-py/UnitTests/TestBMI_bmi2runner2.py =================================================================== diff -u -r00ef8178f6ccf04e542c869caa35837fd08279b5 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/UnitTests/TestBMI_bmi2runner2.py (.../TestBMI_bmi2runner2.py) (revision 00ef8178f6ccf04e542c869caa35837fd08279b5) +++ wflow-py/UnitTests/TestBMI_bmi2runner2.py (.../TestBMI_bmi2runner2.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,10 +1,11 @@ -__author__ = 'schelle' +__author__ = "schelle" import unittest import logging import sys -sys.path = ['../wflow'] + ['../'] + sys.path -sys.path = ['../Scripts'] + sys.path + +sys.path = ["../wflow"] + ["../"] + sys.path +sys.path = ["../Scripts"] + sys.path import bmi2runner as bmirun import time import os @@ -16,12 +17,9 @@ class MyTest(unittest.TestCase): - - - def testbmirunner_set(self): - configfile = 'combined/bmirunner.ini' + configfile = "combined/bmirunner.ini" bmiobj = bmi.wflowbmi_csdms() bmiobj.initialize_config(configfile) bmiobj.initialize_model() @@ -41,5 +39,6 @@ bmiobj.finalize() -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() Index: wflow-py/UnitTests/TestFrameWork.py =================================================================== diff -u -ra7b8df48f8c04b3fcc5f44d47492037b05872793 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/UnitTests/TestFrameWork.py (.../TestFrameWork.py) (revision a7b8df48f8c04b3fcc5f44d47492037b05872793) +++ wflow-py/UnitTests/TestFrameWork.py (.../TestFrameWork.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,47 +1,50 @@ -__author__ = 'schelle' +__author__ = "schelle" import unittest import wflow.wflow_sceleton as wf import os + """ Run sceleton for 10 steps and checks if the outcome is approx that of the reference run """ -class MyTest(unittest.TestCase): +class MyTest(unittest.TestCase): def testapirun(self): startTime = 1 stopTime = 20 currentTime = 1 - # set runid, clonemap and casename. Also define the ini file + # set runid, clonemap and casename. Also define the ini file runId = "unittest" - configfile="wflow_sceleton.ini" - wflow_cloneMap = 'wflow_catchment.map' - caseName="wflow_sceleton" + configfile = "wflow_sceleton.ini" + wflow_cloneMap = "wflow_catchment.map" + caseName = "wflow_sceleton" - myModel = wf.WflowModel(wflow_cloneMap, caseName,runId,configfile) - # initialise the framework - dynModelFw = wf.wf_DynamicFramework(myModel, stopTime,startTime) + myModel = wf.WflowModel(wflow_cloneMap, caseName, runId, configfile) + # initialise the framework + dynModelFw = wf.wf_DynamicFramework(myModel, stopTime, startTime) - # Load model config from files and check directory structure - dynModelFw.createRunId(NoOverWrite=False,level=wf.logging.DEBUG) + # Load model config from files and check directory structure + dynModelFw.createRunId(NoOverWrite=False, level=wf.logging.DEBUG) # Run the initial part of the model (reads parameters and sets initial values) - dynModelFw._runInitial() # Runs initial part + dynModelFw._runInitial() # Runs initial part - dynModelFw._runResume() # gets the state variables + dynModelFw._runResume() # gets the state variables - for ts in range(startTime,stopTime): - dynModelFw._runDynamic(ts,ts) # runs for all timesteps + for ts in range(startTime, stopTime): + dynModelFw._runDynamic(ts, ts) # runs for all timesteps dynModelFw.logger.info("Doing step: " + str(ts)) - dynModelFw._runSuspend() # saves the state variables + dynModelFw._runSuspend() # saves the state variables dynModelFw._wf_shutdown() - my_data = wf.genfromtxt(os.path.join(caseName,runId,"tes.csv"), delimiter=',') - self.assertAlmostEquals(14.885358393192291,my_data[:,2].sum()) - my_data_mean = wf.genfromtxt(os.path.join(caseName, runId, "tes_mean_5.csv"), delimiter=',') - self.assertAlmostEquals( 20.727288454771042, my_data_mean[:, 2].sum()) + my_data = wf.genfromtxt(os.path.join(caseName, runId, "tes.csv"), delimiter=",") + self.assertAlmostEquals(14.885358393192291, my_data[:, 2].sum()) + my_data_mean = wf.genfromtxt( + os.path.join(caseName, runId, "tes_mean_5.csv"), delimiter="," + ) + self.assertAlmostEquals(20.727288454771042, my_data_mean[:, 2].sum()) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() Index: wflow-py/UnitTests/Test_w3ra_BMI.py =================================================================== diff -u -rbdfa3d1385a52bc7f29970984983d36d7ef63759 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/UnitTests/Test_w3ra_BMI.py (.../Test_w3ra_BMI.py) (revision bdfa3d1385a52bc7f29970984983d36d7ef63759) +++ wflow-py/UnitTests/Test_w3ra_BMI.py (.../Test_w3ra_BMI.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,10 +1,11 @@ -__author__ = 'schelle' +__author__ = "schelle" import unittest import logging import sys import datetime -sys.path = ['../'] + sys.path + +sys.path = ["../"] + sys.path import wflow.wflow_bmi as bmi import time from dateutil import parser @@ -19,21 +20,19 @@ class MyTest(unittest.TestCase): - - - - def testbmirunnetcdfw3ra(self): bmiobj = bmi.wflowbmi_csdms() - bmiobj.initialize_config('../../examples/openstreams_w3ra_usa/wflow_w3ra.ini',loglevel=logging.DEBUG) - bmiobj.set_attribute_value('run:runlengthdetermination','intervals') + bmiobj.initialize_config( + "../../examples/openstreams_w3ra_usa/wflow_w3ra.ini", loglevel=logging.DEBUG + ) + bmiobj.set_attribute_value("run:runlengthdetermination", "intervals") - stime= calendar.timegm(parser.parse("2014-05-13 00:00:00").utctimetuple()) + stime = calendar.timegm(parser.parse("2014-05-13 00:00:00").utctimetuple()) etime = calendar.timegm(parser.parse("2014-05-21 00:00:00").utctimetuple()) bmiobj.set_start_time(stime) bmiobj.set_end_time(etime) st = bmiobj.get_start_time() - #print st + # print st ett = bmiobj.get_end_time() ts = bmiobj.get_time_step() @@ -42,19 +41,21 @@ cnt = 0 lastcurtime = bmiobj.get_current_time() while curtime < ett: - avar = bmiobj.get_value('LAI1') - bmiobj.set_value('PRECIP',avar) + avar = bmiobj.get_value("LAI1") + bmiobj.set_value("PRECIP", avar) cnt = cnt + 1 bmiobj.update_until(curtime + ts) - #print (curtime + ts)/ts + # print (curtime + ts)/ts curtime = bmiobj.get_current_time() - #print bmiobj.get_current_time() - lastcurtime + # print bmiobj.get_current_time() - lastcurtime lastcurtime = bmiobj.get_current_time() - bmiobj.finalize() # Check the values in a state file as a refrence. This is what the baselien model gives - x, y, data, FillVal = wf.readMap('../../examples/openstreams_w3ra_usa/run_default/outstate/Sd2.map','PCRaster') + x, y, data, FillVal = wf.readMap( + "../../examples/openstreams_w3ra_usa/run_default/outstate/Sd2.map", + "PCRaster", + ) tmean = np.ma.masked_invalid(data.astype(np.float64)).mean() tmax = np.ma.masked_invalid(data.astype(np.float64)).max() tmin = np.ma.masked_invalid(data.astype(np.float64)).min() @@ -63,6 +64,5 @@ self.assertAlmostEquals(-3.4028234663852886e+38, tmin) - -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() Index: wflow-py/UnitTests/Testwflow_sbm.py =================================================================== diff -u -r4ba26ea013a53dc8248a7f8c5124c5d77a0db944 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/UnitTests/Testwflow_sbm.py (.../Testwflow_sbm.py) (revision 4ba26ea013a53dc8248a7f8c5124c5d77a0db944) +++ wflow-py/UnitTests/Testwflow_sbm.py (.../Testwflow_sbm.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,4 +1,4 @@ -__author__ = 'schelle' +__author__ = "schelle" import unittest import wflow.wflow_sbm as wf @@ -8,59 +8,63 @@ Run wflow_sbm for 10 steps and checks if the outcome is approx that of the reference run """ -class MyTest(unittest.TestCase): +class MyTest(unittest.TestCase): def testapirun(self): startTime = 1 stopTime = 30 currentTime = 1 - # set runid, clonemap and casename. Also define the ini file + # set runid, clonemap and casename. Also define the ini file runId = "unittestsbm" - configfile="wflow_sbm.ini" - wflow_cloneMap = 'wflow_catchment.map' - caseName="wflow_sbm" + configfile = "wflow_sbm.ini" + wflow_cloneMap = "wflow_catchment.map" + caseName = "wflow_sbm" - myModel = wf.WflowModel(wflow_cloneMap, caseName,runId,configfile) - # initialise the framework - dynModelFw = wf.wf_DynamicFramework(myModel, stopTime,startTime) + myModel = wf.WflowModel(wflow_cloneMap, caseName, runId, configfile) + # initialise the framework + dynModelFw = wf.wf_DynamicFramework(myModel, stopTime, startTime) - # Load model config from files and check directory structure - dynModelFw.createRunId(NoOverWrite=False,level=wf.logging.WARN) + # Load model config from files and check directory structure + dynModelFw.createRunId(NoOverWrite=False, level=wf.logging.WARN) # Run the initial part of the model (reads parameters and sets initial values) - dynModelFw._runInitial() # Runs initial part + dynModelFw._runInitial() # Runs initial part - dynModelFw._runResume() # gets the state variables + dynModelFw._runResume() # gets the state variables sump = 0.0 - for ts in range(startTime,stopTime): - if ts <10: - dynModelFw.wf_setValues('P', 0.0) + for ts in range(startTime, stopTime): + if ts < 10: + dynModelFw.wf_setValues("P", 0.0) elif ts <= 15: - dynModelFw.wf_setValues('P', 5.0) + dynModelFw.wf_setValues("P", 5.0) sump = sump + 5.0 else: - dynModelFw.wf_setValues('P', 0.0) + dynModelFw.wf_setValues("P", 0.0) - dynModelFw.wf_setValues('PET', 3.0) - dynModelFw.wf_setValues('TEMP', 10.0) - dynModelFw._runDynamic(ts,ts) # runs for all timesteps + dynModelFw.wf_setValues("PET", 3.0) + dynModelFw.wf_setValues("TEMP", 10.0) + dynModelFw._runDynamic(ts, ts) # runs for all timesteps dynModelFw.logger.info("Doing step: " + str(ts)) - dynModelFw._runSuspend() # saves the state variables + dynModelFw._runSuspend() # saves the state variables dynModelFw._wf_shutdown() # now read the csv results acn check of they match the first run # Sum should be approx c 4.569673676 - my_data = wf.genfromtxt(os.path.join(caseName,runId,"wbsurf.csv"), delimiter=',') + my_data = wf.genfromtxt( + os.path.join(caseName, runId, "wbsurf.csv"), delimiter="," + ) print("Checking surface water budget ....") - self.assertAlmostEquals(-1.003901559215592e-06,my_data[:,2].sum(),places=4) - my_data = wf.genfromtxt(os.path.join(caseName,runId,"wbsoil.csv"), delimiter=',') + self.assertAlmostEquals(-1.003901559215592e-06, my_data[:, 2].sum(), places=4) + my_data = wf.genfromtxt( + os.path.join(caseName, runId, "wbsoil.csv"), delimiter="," + ) print("Checking soil water budget ....") - self.assertAlmostEquals(0.00055469494748194847,my_data[:,2].sum(),places=4) + self.assertAlmostEquals(0.00055469494748194847, my_data[:, 2].sum(), places=4) print("Checking precip sum ....") - my_data = wf.genfromtxt(os.path.join(caseName,runId,"P.csv"), delimiter=',') - self.assertAlmostEquals(sump,my_data[:,2].sum()) + my_data = wf.genfromtxt(os.path.join(caseName, runId, "P.csv"), delimiter=",") + self.assertAlmostEquals(sump, my_data[:, 2].sum()) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() Index: wflow-py/UnitTests/Testwflow_sbm2.py =================================================================== diff -u -r37e269ce4338ed9cfba3e4e6b6720ed3af463818 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/UnitTests/Testwflow_sbm2.py (.../Testwflow_sbm2.py) (revision 37e269ce4338ed9cfba3e4e6b6720ed3af463818) +++ wflow-py/UnitTests/Testwflow_sbm2.py (.../Testwflow_sbm2.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,4 +1,4 @@ -__author__ = 'schelle' +__author__ = "schelle" import unittest import wflow.wflow_sbm2 as wf @@ -8,59 +8,63 @@ Run wflow_sbm for 10 steps and checks if the outcome is approx that of the reference run """ -class MyTest(unittest.TestCase): +class MyTest(unittest.TestCase): def testapirun(self): startTime = 1 stopTime = 30 currentTime = 1 - # set runid, clonemap and casename. Also define the ini file + # set runid, clonemap and casename. Also define the ini file runId = "unittestsbm2" - configfile="wflow_sbm.ini" - wflow_cloneMap = 'wflow_catchment.map' - caseName="wflow_sbm" + configfile = "wflow_sbm.ini" + wflow_cloneMap = "wflow_catchment.map" + caseName = "wflow_sbm" - myModel = wf.WflowModel(wflow_cloneMap, caseName,runId,configfile) - # initialise the framework - dynModelFw = wf.wf_DynamicFramework(myModel, stopTime,startTime) + myModel = wf.WflowModel(wflow_cloneMap, caseName, runId, configfile) + # initialise the framework + dynModelFw = wf.wf_DynamicFramework(myModel, stopTime, startTime) - # Load model config from files and check directory structure - dynModelFw.createRunId(NoOverWrite=False,level=wf.logging.ERROR) + # Load model config from files and check directory structure + dynModelFw.createRunId(NoOverWrite=False, level=wf.logging.ERROR) # Run the initial part of the model (reads parameters and sets initial values) - dynModelFw._runInitial() # Runs initial part + dynModelFw._runInitial() # Runs initial part - dynModelFw._runResume() # gets the state variables + dynModelFw._runResume() # gets the state variables sump = 0.0 - for ts in range(startTime,stopTime): - if ts <10: - dynModelFw.wf_setValues('P', 0.0) + for ts in range(startTime, stopTime): + if ts < 10: + dynModelFw.wf_setValues("P", 0.0) elif ts <= 15: - dynModelFw.wf_setValues('P', 5.0) + dynModelFw.wf_setValues("P", 5.0) sump = sump + 5.0 else: - dynModelFw.wf_setValues('P', 0.0) + dynModelFw.wf_setValues("P", 0.0) - dynModelFw.wf_setValues('PET', 3.0) - dynModelFw.wf_setValues('TEMP', 10.0) - dynModelFw._runDynamic(ts,ts) # runs for all timesteps + dynModelFw.wf_setValues("PET", 3.0) + dynModelFw.wf_setValues("TEMP", 10.0) + dynModelFw._runDynamic(ts, ts) # runs for all timesteps dynModelFw.logger.info("Doing step: " + str(ts)) - dynModelFw._runSuspend() # saves the state variables + dynModelFw._runSuspend() # saves the state variables dynModelFw._wf_shutdown() # now read the csv results acn check of they match the first run # Sum should be approx c 4.569673676 - my_data = wf.genfromtxt(os.path.join(caseName,runId,"wbsurf.csv"), delimiter=',') + my_data = wf.genfromtxt( + os.path.join(caseName, runId, "wbsurf.csv"), delimiter="," + ) print("Checking surface water budget ....") - self.assertAlmostEquals(-1.003901559215592e-06,my_data[:,2].sum(),places=4) - my_data = wf.genfromtxt(os.path.join(caseName,runId,"wbsoil.csv"), delimiter=',') + self.assertAlmostEquals(-1.003901559215592e-06, my_data[:, 2].sum(), places=4) + my_data = wf.genfromtxt( + os.path.join(caseName, runId, "wbsoil.csv"), delimiter="," + ) print("Checking soil water budget ....") - self.assertAlmostEquals(0.00055434828220768395,my_data[:,2].sum(),places=4) + self.assertAlmostEquals(0.00055434828220768395, my_data[:, 2].sum(), places=4) print("Checking precip sum ....") - my_data = wf.genfromtxt(os.path.join(caseName,runId,"P.csv"), delimiter=',') - self.assertAlmostEquals(sump,my_data[:,2].sum()) + my_data = wf.genfromtxt(os.path.join(caseName, runId, "P.csv"), delimiter=",") + self.assertAlmostEquals(sump, my_data[:, 2].sum()) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() Index: wflow-py/UnitTests/Testwflow_sbm2bmi.py =================================================================== diff -u -r3e605fb3dec01e1b369744cf6c2769e2c1344b8b -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/UnitTests/Testwflow_sbm2bmi.py (.../Testwflow_sbm2bmi.py) (revision 3e605fb3dec01e1b369744cf6c2769e2c1344b8b) +++ wflow-py/UnitTests/Testwflow_sbm2bmi.py (.../Testwflow_sbm2bmi.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,4 +1,4 @@ -__author__ = 'schelle' +__author__ = "schelle" import unittest import wflow.wflow_sbm as wf @@ -8,14 +8,15 @@ Run wflow_sbm for 10 steps and checks if the outcome is approx that of the reference run """ -class MyTest(unittest.TestCase): - +class MyTest(unittest.TestCase): def TestBMIrun(self): import wflow.wflow_bmi as bmi + bmimodel = bmi.wflowbmi_csdms() - bmimodel.initialize('../../examples/wflow_rhine_sbm2/wflow_sbm2.ini') + bmimodel.initialize("../../examples/wflow_rhine_sbm2/wflow_sbm2.ini") bmimodel.update() -if __name__ == '__main__': + +if __name__ == "__main__": unittest.main() Index: wflow-py/UnitTests/Testwflow_sbm_dynveg.py =================================================================== diff -u -r34093e71c2f49d90a1e7df46b73ecf07913ca68f -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/UnitTests/Testwflow_sbm_dynveg.py (.../Testwflow_sbm_dynveg.py) (revision 34093e71c2f49d90a1e7df46b73ecf07913ca68f) +++ wflow-py/UnitTests/Testwflow_sbm_dynveg.py (.../Testwflow_sbm_dynveg.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,66 +1,70 @@ -__author__ = 'schelle' +__author__ = "schelle" import unittest import wflow.wflow_sbm as wf import os + """ Run sceleton for 10 steps and checks if the outcome is approx that of the reference run """ -class MyTest(unittest.TestCase): +class MyTest(unittest.TestCase): def testapirun_netcfd(self): startTime = 1 stopTime = 30 currentTime = 1 - # set runid, clonemap and casename. Also define the ini file + # set runid, clonemap and casename. Also define the ini file runId = "unittest" - configfile="wflow_sbm_dynveg.ini" - wflow_cloneMap = 'wflow_catchment.map' - caseName="wflow_sbm" + configfile = "wflow_sbm_dynveg.ini" + wflow_cloneMap = "wflow_catchment.map" + caseName = "wflow_sbm" - myModel = wf.WflowModel(wflow_cloneMap, caseName,runId,configfile) - # initialise the framework - dynModelFw = wf.wf_DynamicFramework(myModel, stopTime,startTime) + myModel = wf.WflowModel(wflow_cloneMap, caseName, runId, configfile) + # initialise the framework + dynModelFw = wf.wf_DynamicFramework(myModel, stopTime, startTime) - # Load model config from files and check directory structure - dynModelFw.createRunId(NoOverWrite=False,level=wf.logging.ERROR) + # Load model config from files and check directory structure + dynModelFw.createRunId(NoOverWrite=False, level=wf.logging.ERROR) # Run the initial part of the model (reads parameters and sets initial values) - dynModelFw._runInitial() # Runs initial part + dynModelFw._runInitial() # Runs initial part - dynModelFw._runResume() # gets the state variables + dynModelFw._runResume() # gets the state variables sump = 0.0 - for ts in range(startTime,stopTime): - if ts <10: - dynModelFw.wf_setValues('P', 0.0) + for ts in range(startTime, stopTime): + if ts < 10: + dynModelFw.wf_setValues("P", 0.0) elif ts <= 15: - dynModelFw.wf_setValues('P', 10.0) + dynModelFw.wf_setValues("P", 10.0) sump = sump + 10.0 else: - dynModelFw.wf_setValues('P', 0.0) + dynModelFw.wf_setValues("P", 0.0) - dynModelFw.wf_setValues('PET', 2.0) - dynModelFw.wf_setValues('TEMP', 10.0) - dynModelFw._runDynamic(ts,ts) # runs for all timesteps + dynModelFw.wf_setValues("PET", 2.0) + dynModelFw.wf_setValues("TEMP", 10.0) + dynModelFw._runDynamic(ts, ts) # runs for all timesteps dynModelFw.logger.info("Doing step: " + str(ts)) - dynModelFw._runSuspend() # saves the state variables + dynModelFw._runSuspend() # saves the state variables dynModelFw._wf_shutdown() # nore read the csv results acn check of they match the first run # Sum should be approx c 4.569673676 - my_data = wf.genfromtxt(os.path.join(caseName,runId,"wbsurf.csv"), delimiter=',',skip_header=1) + my_data = wf.genfromtxt( + os.path.join(caseName, runId, "wbsurf.csv"), delimiter=",", skip_header=1 + ) print("Checking surface water budget ....") - self.assertAlmostEquals(-1.003901559215592e-06,my_data[:,2].sum(),places=4) - my_data = wf.genfromtxt(os.path.join(caseName,runId,"wbsoil.csv"), delimiter=',') + self.assertAlmostEquals(-1.003901559215592e-06, my_data[:, 2].sum(), places=4) + my_data = wf.genfromtxt( + os.path.join(caseName, runId, "wbsoil.csv"), delimiter="," + ) print("Checking soil water budget ....") - self.assertAlmostEquals(0.0006305182757557759,my_data[:,2].sum(),places=4) + self.assertAlmostEquals(0.0006305182757557759, my_data[:, 2].sum(), places=4) print("Checking precip sum ....") - my_data = wf.genfromtxt(os.path.join(caseName,runId,"P.csv"), delimiter=',') - self.assertAlmostEquals(sump,my_data[:,2].sum()) + my_data = wf.genfromtxt(os.path.join(caseName, runId, "P.csv"), delimiter=",") + self.assertAlmostEquals(sump, my_data[:, 2].sum()) - -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() Index: wflow-py/UnitTests/Testwflow_sbm_example.py =================================================================== diff -u -re879b0af6cf75726bb1ebd542a245abdffe48cef -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/UnitTests/Testwflow_sbm_example.py (.../Testwflow_sbm_example.py) (revision e879b0af6cf75726bb1ebd542a245abdffe48cef) +++ wflow-py/UnitTests/Testwflow_sbm_example.py (.../Testwflow_sbm_example.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,4 +1,4 @@ -__author__ = 'schelle' +__author__ = "schelle" import unittest import wflow.wflow_sbm as wf @@ -8,47 +8,49 @@ Run wflow_sbm for 10 steps and checks if the outcome is approx that of the reference run """ -class MyTest(unittest.TestCase): +class MyTest(unittest.TestCase): def testapirunexample(self): startTime = 1 stopTime = 30 currentTime = 1 orgdir = os.getcwd() - os.chdir('../../examples/') - # set runid, clonemap and casename. Also define the ini file + os.chdir("../../examples/") + # set runid, clonemap and casename. Also define the ini file runId = "unittestsbm" - configfile="wflow_sbm.ini" - wflow_cloneMap = 'wflow_subcatch.map' - caseName="wflow_rhine_sbm/" + configfile = "wflow_sbm.ini" + wflow_cloneMap = "wflow_subcatch.map" + caseName = "wflow_rhine_sbm/" - myModel = wf.WflowModel(wflow_cloneMap, caseName,runId,configfile) - # initialise the framework - dynModelFw = wf.wf_DynamicFramework(myModel, stopTime,startTime) + myModel = wf.WflowModel(wflow_cloneMap, caseName, runId, configfile) + # initialise the framework + dynModelFw = wf.wf_DynamicFramework(myModel, stopTime, startTime) - # Load model config from files and check directory structure - dynModelFw.createRunId(NoOverWrite=False,level=wf.logging.WARN) + # Load model config from files and check directory structure + dynModelFw.createRunId(NoOverWrite=False, level=wf.logging.WARN) # Run the initial part of the model (reads parameters and sets initial values) - dynModelFw._runInitial() # Runs initial part + dynModelFw._runInitial() # Runs initial part - dynModelFw._runResume() # gets the state variables + dynModelFw._runResume() # gets the state variables sump = 0.0 - for ts in range(startTime,stopTime): - dynModelFw._runDynamic(ts,ts) # runs for all timesteps + for ts in range(startTime, stopTime): + dynModelFw._runDynamic(ts, ts) # runs for all timesteps dynModelFw.logger.info("Doing step: " + str(ts)) - dynModelFw._runSuspend() # saves the state variables + dynModelFw._runSuspend() # saves the state variables dynModelFw._wf_shutdown() # now read the csv results acn check of they match the first run # Sum should be approx c 4.569673676 - my_data = wf.genfromtxt(os.path.join(caseName,runId,"specrun.csv"), delimiter=',') + my_data = wf.genfromtxt( + os.path.join(caseName, runId, "specrun.csv"), delimiter="," + ) print("Checking specific runoff ....") - self.assertAlmostEquals(46.839179277420044,my_data[:,2].sum(),places=4) + self.assertAlmostEquals(46.839179277420044, my_data[:, 2].sum(), places=4) os.chdir(orgdir) -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() Index: wflow-py/UnitTests/Testwflow_sbm_nc.py =================================================================== diff -u -re71ad2de03777dca02510a47f65dd6f7075a876b -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/UnitTests/Testwflow_sbm_nc.py (.../Testwflow_sbm_nc.py) (revision e71ad2de03777dca02510a47f65dd6f7075a876b) +++ wflow-py/UnitTests/Testwflow_sbm_nc.py (.../Testwflow_sbm_nc.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,66 +1,72 @@ -__author__ = 'schelle' +__author__ = "schelle" import unittest import wflow.wflow_sbm as wf import os + """ Run sceleton for 10 steps and checks if the outcome is approx that of the reference run """ -class MyTest(unittest.TestCase): +class MyTest(unittest.TestCase): def testapirun_netcfd(self): startTime = 1 stopTime = 30 currentTime = 1 - # set runid, clonemap and casename. Also define the ini file + # set runid, clonemap and casename. Also define the ini file runId = "unittest" - configfile="wflow_sbm_nc.ini" - wflow_cloneMap = 'wflow_catchment.map' - caseName="wflow_sbm" + configfile = "wflow_sbm_nc.ini" + wflow_cloneMap = "wflow_catchment.map" + caseName = "wflow_sbm" - myModel = wf.WflowModel(wflow_cloneMap, caseName,runId,configfile) - # initialise the framework - dynModelFw = wf.wf_DynamicFramework(myModel, 0,0) + myModel = wf.WflowModel(wflow_cloneMap, caseName, runId, configfile) + # initialise the framework + dynModelFw = wf.wf_DynamicFramework(myModel, 0, 0) - # Load model config from files and check directory structure - dynModelFw.createRunId(NoOverWrite=False,level=wf.logging.DEBUG) + # Load model config from files and check directory structure + dynModelFw.createRunId(NoOverWrite=False, level=wf.logging.DEBUG) # Run the initial part of the model (reads parameters and sets initial values) - dynModelFw._runInitial() # Runs initial part + dynModelFw._runInitial() # Runs initial part - dynModelFw._runResume() # gets the state variables + dynModelFw._runResume() # gets the state variables sump = 0.0 - for ts in range(startTime,stopTime + 1): - if ts <10: - dynModelFw.wf_setValues('P', 0.0) + for ts in range(startTime, stopTime + 1): + if ts < 10: + dynModelFw.wf_setValues("P", 0.0) elif ts <= 15: - dynModelFw.wf_setValues('P', 10.0) + dynModelFw.wf_setValues("P", 10.0) sump = sump + 10.0 else: - dynModelFw.wf_setValues('P', 0.0) + dynModelFw.wf_setValues("P", 0.0) - dynModelFw.wf_setValues('PET', 2.0) - dynModelFw.wf_setValues('TEMP', 10.0) - dynModelFw._runDynamic(ts,ts) # runs for all timesteps + dynModelFw.wf_setValues("PET", 2.0) + dynModelFw.wf_setValues("TEMP", 10.0) + dynModelFw._runDynamic(ts, ts) # runs for all timesteps - dynModelFw._runSuspend() # saves the state variables + dynModelFw._runSuspend() # saves the state variables dynModelFw._wf_shutdown() # nore read the csv results acn check of they match the first run # Sum should be approx c 4.569673676 - my_data = wf.genfromtxt(os.path.join(caseName,runId,"wbsurf.csv"), delimiter=',',usecols=(0,1,2,3,4)) + my_data = wf.genfromtxt( + os.path.join(caseName, runId, "wbsurf.csv"), + delimiter=",", + usecols=(0, 1, 2, 3, 4), + ) print("Checking surface water budget ....") - self.assertAlmostEquals(3.574188167654313e-09,my_data[:,2].sum(),places=4) - my_data = wf.genfromtxt(os.path.join(caseName,runId,"wbsoil.csv"), delimiter=',') + self.assertAlmostEquals(3.574188167654313e-09, my_data[:, 2].sum(), places=4) + my_data = wf.genfromtxt( + os.path.join(caseName, runId, "wbsoil.csv"), delimiter="," + ) print("Checking soil water budget ....") - self.assertAlmostEquals(0.002721056049267645,my_data[:,2].sum(),places=4) + self.assertAlmostEquals(0.002721056049267645, my_data[:, 2].sum(), places=4) print("Checking precip sum ....") - my_data = wf.genfromtxt(os.path.join(caseName,runId,"P.csv"), delimiter=',') - self.assertAlmostEquals(sump,my_data[:,2].sum()) + my_data = wf.genfromtxt(os.path.join(caseName, runId, "P.csv"), delimiter=",") + self.assertAlmostEquals(sump, my_data[:, 2].sum()) - -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() Index: wflow-py/UnitTests/Testwflow_sbm_nc2.py =================================================================== diff -u -r048e9fa4ca4b2c6a7c14169de0b192ea2ff9b983 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/UnitTests/Testwflow_sbm_nc2.py (.../Testwflow_sbm_nc2.py) (revision 048e9fa4ca4b2c6a7c14169de0b192ea2ff9b983) +++ wflow-py/UnitTests/Testwflow_sbm_nc2.py (.../Testwflow_sbm_nc2.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,45 +1,43 @@ -__author__ = 'schelle' +__author__ = "schelle" import unittest import wflow.wflow_sbm as wf import os + """ Run sceleton for 10 steps and checks if the outcome is approx that of the reference run """ -class MyTest(unittest.TestCase): +class MyTest(unittest.TestCase): def testapirun_netcfd2(self): startTime = 1 stopTime = 30 currentTime = 1 - # set runid, clonemap and casename. Also define the ini file + # set runid, clonemap and casename. Also define the ini file runId = "unittest" - configfile="wflow_sbm_NC2.ini" - wflow_cloneMap = 'wflow_catchment.map' - caseName="../../examples\wflow_rhine_sbm_nc" + configfile = "wflow_sbm_NC2.ini" + wflow_cloneMap = "wflow_catchment.map" + caseName = "../../examples\wflow_rhine_sbm_nc" - myModel = wf.WflowModel(wflow_cloneMap, caseName,runId,configfile) - # initialise the framework - dynModelFw = wf.wf_DynamicFramework(myModel, stopTime,startTime) + myModel = wf.WflowModel(wflow_cloneMap, caseName, runId, configfile) + # initialise the framework + dynModelFw = wf.wf_DynamicFramework(myModel, stopTime, startTime) - # Load model config from files and check directory structure - dynModelFw.createRunId(NoOverWrite=False,level=wf.logging.DEBUG) + # Load model config from files and check directory structure + dynModelFw.createRunId(NoOverWrite=False, level=wf.logging.DEBUG) # Run the initial part of the model (reads parameters and sets initial values) - dynModelFw._runInitial() # Runs initial part + dynModelFw._runInitial() # Runs initial part - dynModelFw._runResume() # gets the state variables + dynModelFw._runResume() # gets the state variables sump = 0.0 - for ts in range(startTime,stopTime + 1): - dynModelFw._runDynamic(ts,ts) # runs for all timesteps + for ts in range(startTime, stopTime + 1): + dynModelFw._runDynamic(ts, ts) # runs for all timesteps - dynModelFw._runSuspend() # saves the state variables + dynModelFw._runSuspend() # saves the state variables dynModelFw._wf_shutdown() - - - -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() Index: wflow-py/WflowDeltashell/plotcsv.py =================================================================== diff -u -r08a987702d1e404792fecefc8fbc97b005449a20 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/WflowDeltashell/plotcsv.py (.../plotcsv.py) (revision 08a987702d1e404792fecefc8fbc97b005449a20) +++ wflow-py/WflowDeltashell/plotcsv.py (.../plotcsv.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,141 +1,164 @@ -import csv # import the python csv library +import csv # import the python csv library from Libraries.StandardFunctions import * from Libraries.ChartFunctions import * import WflowDeltashell.wflib as wfl import os # Needed if this .net thing is not loaded yet import clr + clr.AddReference("System.Windows.Forms") from System.Windows.Forms import OpenFileDialog, DialogResult def getcsvname(): - themodel = wfl.GetModelByPartialName('wflow') - - dialog = OpenFileDialog() - - if themodel: - dialog.InitialDirectory = os.path.join(themodel.DirectoryPath,themodel.DefaultOutputDirectoryName) - else: - dialog.InitialDirectory ="C:\\" - - dialog.Filter = "csv files (*.csv) | *.csv" - dialog.FilterIndex = 1 - dialog.RestoreDirectory = False - dialog.Title = "Select a WFlow result csv file: " - - if (dialog.ShowDialog() == DialogResult.OK): - thefile = dialog.FileName - - return thefile + themodel = wfl.GetModelByPartialName("wflow") + dialog = OpenFileDialog() + if themodel: + dialog.InitialDirectory = os.path.join( + themodel.DirectoryPath, themodel.DefaultOutputDirectoryName + ) + else: + dialog.InitialDirectory = "C:\\" + + dialog.Filter = "csv files (*.csv) | *.csv" + dialog.FilterIndex = 1 + dialog.RestoreDirectory = False + dialog.Title = "Select a WFlow result csv file: " + + if dialog.ShowDialog() == DialogResult.OK: + thefile = dialog.FileName + + return thefile + + def plotit(filename): - colors = [Color.Red,Color.Black, Color.Green, Color.Black, Color.Orange, Color.YellowGreen, Color.Azure,\ - Color.Cyan, Color.Brown, Color.Aquamarine, Color.CornflowerBlue, Color.DarkBlue, Color.BlanchedAlmond,\ - Color.LightYellow, Color.SlateGray] - - runid = os.path.basename(os.path.dirname(filename)) - - lineSeries = [] - - olines = wfl.readwfcsv(filename) + colors = [ + Color.Red, + Color.Black, + Color.Green, + Color.Black, + Color.Orange, + Color.YellowGreen, + Color.Azure, + Color.Cyan, + Color.Brown, + Color.Aquamarine, + Color.CornflowerBlue, + Color.DarkBlue, + Color.BlanchedAlmond, + Color.LightYellow, + Color.SlateGray, + ] - - for yval in range(1,len(olines[0])): - x = [[col[0],col[yval]] for col in olines] - - lineSeries.append(CreateLineSeries(x)) - - - lineSeries[-1].Color = colors[yval -1] - lineSeries[-1].Width = 1 - lineSeries[-1].PointerVisible = False - lineSeries[-1].PointerSize = 0 - lineSeries[-1].PointerColor = Color.Red - lineSeries[-1].PointerLineVisible = True - lineSeries[-1].PointerLineColor = colors[yval -1] - lineSeries[-1].Transparency = 0 - lineSeries[-1].ShowInLegend= True - lineSeries[-1].Title="Id: " + str(yval) - - chart = CreateChart(lineSeries) - - # Configure the chart - chart.TitleVisible = True - chart.Title = "run: " + runid + ": " + os.path.basename(filename) - chart.BackGroundColor = Color.White - chart.Legend.Visible = True - chart.Name = chart.Title - - - # Configure the bottom axis - chart.BottomAxis.Automatic = True - chart.BottomAxis.Title = "Timestep" - - # Configure the left axis - chart.LeftAxis.Title = os.path.basename(filename) - - - # Show the chart - view = OpenView(chart) - + runid = os.path.basename(os.path.dirname(filename)) + lineSeries = [] -def complot(dirnames,file,ids): - colors = [Color.Red,Color.Black, Color.Green, Color.Black, Color.Orange, Color.YellowGreen, Color.Azure,\ - Color.Cyan, Color.Brown, Color.Aquamarine, Color.CornflowerBlue, Color.DarkBlue, Color.BlanchedAlmond,\ - Color.LightYellow, Color.SlateGray] - + olines = wfl.readwfcsv(filename) - cnt = 0 - lineSeries = [] - for dirname in dirnames: - runid = os.path.dirname(dirname) - - ftoread = os.path.join(dirname,file) - - if os.path.exists(ftoread): - olines = wfl.readwfcsv(os.path.join(dirname,file)) - - for yval in ids: - x = [[col[0],col[yval]] for col in olines] - - lineSeries.append(CreateLineSeries(x)) - - - lineSeries[-1].Color = colors[cnt] - lineSeries[-1].Width = 1 - lineSeries[-1].PointerVisible = False - lineSeries[-1].PointerSize = 0 - lineSeries[-1].PointerColor = Color.Red - lineSeries[-1].PointerLineVisible = True - lineSeries[-1].PointerLineColor = colors[cnt] - lineSeries[-1].Transparency = 0 - lineSeries[-1].ShowInLegend= True - lineSeries[-1].Title="Col: " + str(yval) + " Run: " + str(os.path.basename(runid)) - cnt = cnt + 1 - - casename = os.path.basename(os.path.dirname(os.path.dirname(dirname))) - chart = CreateChart(lineSeries) - - # Configure the chart - chart.TitleVisible = True - chart.Title = casename.upper() + ":" + os.path.basename(file) - chart.BackGroundColor = Color.White - chart.Legend.Visible = True - chart.Name = chart.Title - - - # Configure the bottom axis - chart.BottomAxis.Automatic = True - chart.BottomAxis.Title = "Timestep" - - # Configure the left axis - chart.LeftAxis.Title = os.path.basename(file) - - - # Show the chart - view = OpenView(chart) - + for yval in range(1, len(olines[0])): + x = [[col[0], col[yval]] for col in olines] + + lineSeries.append(CreateLineSeries(x)) + + lineSeries[-1].Color = colors[yval - 1] + lineSeries[-1].Width = 1 + lineSeries[-1].PointerVisible = False + lineSeries[-1].PointerSize = 0 + lineSeries[-1].PointerColor = Color.Red + lineSeries[-1].PointerLineVisible = True + lineSeries[-1].PointerLineColor = colors[yval - 1] + lineSeries[-1].Transparency = 0 + lineSeries[-1].ShowInLegend = True + lineSeries[-1].Title = "Id: " + str(yval) + + chart = CreateChart(lineSeries) + + # Configure the chart + chart.TitleVisible = True + chart.Title = "run: " + runid + ": " + os.path.basename(filename) + chart.BackGroundColor = Color.White + chart.Legend.Visible = True + chart.Name = chart.Title + + # Configure the bottom axis + chart.BottomAxis.Automatic = True + chart.BottomAxis.Title = "Timestep" + + # Configure the left axis + chart.LeftAxis.Title = os.path.basename(filename) + + # Show the chart + view = OpenView(chart) + + +def complot(dirnames, file, ids): + colors = [ + Color.Red, + Color.Black, + Color.Green, + Color.Black, + Color.Orange, + Color.YellowGreen, + Color.Azure, + Color.Cyan, + Color.Brown, + Color.Aquamarine, + Color.CornflowerBlue, + Color.DarkBlue, + Color.BlanchedAlmond, + Color.LightYellow, + Color.SlateGray, + ] + + cnt = 0 + lineSeries = [] + for dirname in dirnames: + runid = os.path.dirname(dirname) + + ftoread = os.path.join(dirname, file) + + if os.path.exists(ftoread): + olines = wfl.readwfcsv(os.path.join(dirname, file)) + + for yval in ids: + x = [[col[0], col[yval]] for col in olines] + + lineSeries.append(CreateLineSeries(x)) + + lineSeries[-1].Color = colors[cnt] + lineSeries[-1].Width = 1 + lineSeries[-1].PointerVisible = False + lineSeries[-1].PointerSize = 0 + lineSeries[-1].PointerColor = Color.Red + lineSeries[-1].PointerLineVisible = True + lineSeries[-1].PointerLineColor = colors[cnt] + lineSeries[-1].Transparency = 0 + lineSeries[-1].ShowInLegend = True + lineSeries[-1].Title = ( + "Col: " + str(yval) + " Run: " + str(os.path.basename(runid)) + ) + cnt = cnt + 1 + + casename = os.path.basename(os.path.dirname(os.path.dirname(dirname))) + chart = CreateChart(lineSeries) + + # Configure the chart + chart.TitleVisible = True + chart.Title = casename.upper() + ":" + os.path.basename(file) + chart.BackGroundColor = Color.White + chart.Legend.Visible = True + chart.Name = chart.Title + + # Configure the bottom axis + chart.BottomAxis.Automatic = True + chart.BottomAxis.Title = "Timestep" + + # Configure the left axis + chart.LeftAxis.Title = os.path.basename(file) + + # Show the chart + view = OpenView(chart) Index: wflow-py/_version.py =================================================================== diff -u -rc9d975a5a82cb34652cdc5d2ee9afd734c18d3c7 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/_version.py (.../_version.py) (revision c9d975a5a82cb34652cdc5d2ee9afd734c18d3c7) +++ wflow-py/_version.py (.../_version.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -58,28 +58,32 @@ def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f + return decorate -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) + p = subprocess.Popen( + [c] + args, + cwd=cwd, + env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr else None), + ) break except EnvironmentError: e = sys.exc_info()[1] @@ -116,16 +120,22 @@ for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} + return { + "version": dirname[len(parentdir_prefix) :], + "full-revisionid": None, + "dirty": False, + "error": None, + "date": None, + } else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) + print( + "Tried directories %s but none started with prefix %s" + % (str(rootdirs), parentdir_prefix) + ) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @@ -181,7 +191,7 @@ # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -190,27 +200,34 @@ # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = set([r for r in refs if re.search(r"\d", r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] + r = ref[len(tag_prefix) :] if verbose: print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} + return { + "version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": None, + "date": date, + } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} + return { + "version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": "no suitable tags", + "date": None, + } @register_vcs_handler("git", "pieces_from_vcs") @@ -225,19 +242,27 @@ if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) + describe_out, rc = run_command( + GITS, + [ + "describe", + "--tags", + "--dirty", + "--always", + "--long", + "--match", + "%s*" % tag_prefix, + ], + cwd=root, + ) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") @@ -260,17 +285,16 @@ dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] + git_describe = git_describe[: git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) + pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag @@ -279,10 +303,12 @@ if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) + pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( + full_tag, + tag_prefix, + ) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] + pieces["closest-tag"] = full_tag[len(tag_prefix) :] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -293,13 +319,13 @@ else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], - cwd=root)[0].strip() + date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ + 0 + ].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces @@ -330,8 +356,7 @@ rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -445,11 +470,13 @@ def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} + return { + "version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None, + } if not style or style == "default": style = "pep440" # the default @@ -469,9 +496,13 @@ else: raise ValueError("unknown style '%s'" % style) - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} + return { + "version": rendered, + "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], + "error": None, + "date": pieces.get("date"), + } def get_versions(): @@ -485,8 +516,7 @@ verbose = cfg.verbose try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) + return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass @@ -495,13 +525,16 @@ # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): + for i in cfg.versionfile_source.split("/"): root = os.path.dirname(root) except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to find root of source tree", + "date": None, + } try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) @@ -515,6 +548,10 @@ except NotThisMethod: pass - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", + "date": None, + } Index: wflow-py/make_wflow_exe_buildserver.py =================================================================== diff -u -r4cfef1af4528cf5a50095f81ed30ba193809adc2 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/make_wflow_exe_buildserver.py (.../make_wflow_exe_buildserver.py) (revision 4cfef1af4528cf5a50095f81ed30ba193809adc2) +++ wflow-py/make_wflow_exe_buildserver.py (.../make_wflow_exe_buildserver.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -13,7 +13,7 @@ from cx_Freeze import setup, Executable, hooks -import ctypes,glob,os,shutil +import ctypes, glob, os, shutil import matplotlib import scipy import sys @@ -22,34 +22,33 @@ import versioneer import subprocess -target = 'normal' +target = "normal" # Filter out wflow specific options if "--openda" in sys.argv: - target = 'openda' + target = "openda" sys.argv.remove("--openda") if "--normal" in sys.argv: - target = 'normal' + target = "normal" sys.argv.remove("--normal") if "--deltashell" in sys.argv: - target = 'deltashell' + target = "deltashell" sys.argv.remove("--deltashell") pdir = os.path.dirname(sys.executable) + "/" -if sys.platform == 'win32': +if sys.platform == "win32": mkl_file = glob.glob(pdir + "conda-meta" + "/" + "mkl-[!service]*.json")[0] data = json.load(open(mkl_file)) -MKL_files = [(pdir + s) for s in data['files']] +MKL_files = [(pdir + s) for s in data["files"]] os.system("c:\Anaconda\python mkversion_buildserver.py") - -data_files=[] +data_files = [] scipy_path = os.path.dirname(scipy.__file__) data_files.append(scipy_path) @@ -61,166 +60,208 @@ finder.IncludePackage("scipy._lib") # Changed include from scipy.lib to scipy._lib finder.IncludePackage("scipy.misc") + hooks.load_scipy = load_scipy_patched -def mkdatatuples(thelist,destdir="."): + +def mkdatatuples(thelist, destdir="."): """ input list of input files output lis list of tuples including destination :param list: :return: """ ret = [] for item in thelist: - destfile = os.path.join(destdir,os.path.basename(item)) - ret.append((item,destfile)) + destfile = os.path.join(destdir, os.path.basename(item)) + ret.append((item, destfile)) return ret -data_files.append('packages.txt') -os.system('c:\anaconda\scripts\conda list' + ">" + os.path.join('packages.txt')) + +data_files.append("packages.txt") +os.system("c:\anaconda\scripts\conda list" + ">" + os.path.join("packages.txt")) # matplolib data files -mpl = matplotlib.get_py2exe_datafiles() +mpl = matplotlib.get_py2exe_datafiles() mplfiles = [] for mpldir in mpl: - ddir = os.path.join('mpl-data',os.path.basename(mpldir[0])) - data_files.extend(mkdatatuples(mpldir[1],destdir=ddir)) + ddir = os.path.join("mpl-data", os.path.basename(mpldir[0])) + data_files.extend(mkdatatuples(mpldir[1], destdir=ddir)) -if sys.platform == 'win32': +if sys.platform == "win32": # MKL files - data_files.extend(mkdatatuples(MKL_files,destdir=".")) + data_files.extend(mkdatatuples(MKL_files, destdir=".")) # pcraster dll's for teamcity ddir = "d:/BuildAgent/work/wflow_exe/pcraster-4.1.0_x86-64/lib" - data_files.extend(mkdatatuples(glob.glob(ddir + "/*.dll"),destdir='.')) + data_files.extend(mkdatatuples(glob.glob(ddir + "/*.dll"), destdir=".")) # GDAL data files gdaldata = os.getenv("GDAL_DATA") if gdaldata == None: gdaldata = "c:\Anaconda\Library\share\gdal" -data_files.extend(mkdatatuples(glob.glob(gdaldata + "/*.*"),destdir='gdal-data')) +data_files.extend(mkdatatuples(glob.glob(gdaldata + "/*.*"), destdir="gdal-data")) nrbits = str(ctypes.sizeof(ctypes.c_voidp) * 8) -#includes = ['wflow.wflow_bmi','wflow.wflow_w3ra','wflow.wflow_bmi_combined','bmi','bmi.wrapper',"pcraster","osgeo.ogr"] +# includes = ['wflow.wflow_bmi','wflow.wflow_w3ra','wflow.wflow_bmi_combined','bmi','bmi.wrapper',"pcraster","osgeo.ogr"] -#clean wflow-bin dir -bf = os.path.join(os.getcwd(),"wflow-bin") -shutil.rmtree(bf,ignore_errors=True) +# clean wflow-bin dir +bf = os.path.join(os.getcwd(), "wflow-bin") +shutil.rmtree(bf, ignore_errors=True) -#a = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], shell=True).strip() +# a = subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], shell=True).strip() versions = versioneer.get_versions() -MVERSION = versions['version'].split('+')[0] +MVERSION = versions["version"].split("+")[0] -thename = "wflow-bin/Wflow-"+MVERSION+'-'+target+'-'+sys.platform+'-'+nrbits +thename = ( + "wflow-bin/Wflow-" + MVERSION + "-" + target + "-" + sys.platform + "-" + nrbits +) -data_files.append( os.path.join(os.getcwd(), 'build/lib/wflow/_version.py')) +data_files.append(os.path.join(os.getcwd(), "build/lib/wflow/_version.py")) packages = ["osgeo"] -if target == 'openda': +if target == "openda": import thrift.protocol.TBinaryProtocol as TBinaryProtocol import thrift.transport.THttpClient as THttpClient import thrift.protocol.TBinaryProtocol as TBinaryProtocol import thrift.transport.THttpClient as THttpClient - includes = ['wflow.wflow_bmi','wflow.wflow_w3ra','wflow.wflow_bmi_combined','lxml.etree', 'lxml._elementpath', 'gzip', 'numpy.core._methods', 'numpy.lib.format'] - packages.append('openda_bmi') -elif target == 'deltashell': + + includes = [ + "wflow.wflow_bmi", + "wflow.wflow_w3ra", + "wflow.wflow_bmi_combined", + "lxml.etree", + "lxml._elementpath", + "gzip", + "numpy.core._methods", + "numpy.lib.format", + ] + packages.append("openda_bmi") +elif target == "deltashell": import zmq.libzmq - data_files.extend([zmq.libzmq.__file__, ]) - includes = ["zmq.backend.cython","zmq.utils.garbage","requests","zmq.eventloop.zmqstream", - 'wflow.wflow_bmi','wflow.wflow_w3ra','wflow.wflow_bmi_combined','lxml.etree', 'lxml._elementpath', 'gzip'] - packages.append('zmq.backend.cython') - packages.append('bmi') - #packages.append('pkg_resources') + + data_files.extend([zmq.libzmq.__file__]) + includes = [ + "zmq.backend.cython", + "zmq.utils.garbage", + "requests", + "zmq.eventloop.zmqstream", + "wflow.wflow_bmi", + "wflow.wflow_w3ra", + "wflow.wflow_bmi_combined", + "lxml.etree", + "lxml._elementpath", + "gzip", + ] + packages.append("zmq.backend.cython") + packages.append("bmi") + # packages.append('pkg_resources') else: - includes = ['wflow.wflow_bmi', 'wflow.wflow_w3ra', 'wflow.wflow_bmi_combined','lxml.etree', 'lxml._elementpath', 'gzip', 'numpy.core._methods', 'numpy.lib.format'] + includes = [ + "wflow.wflow_bmi", + "wflow.wflow_w3ra", + "wflow.wflow_bmi_combined", + "lxml.etree", + "lxml._elementpath", + "gzip", + "numpy.core._methods", + "numpy.lib.format", + ] # "include_msvcr": True, -options = {"includes": includes, "packages": packages,'include_files': data_files, "build_exe": thename, - 'excludes': ['collections.abc']} -base=None +options = { + "includes": includes, + "packages": packages, + "include_files": data_files, + "build_exe": thename, + "excludes": ["collections.abc"], +} +base = None -if target == 'openda': +if target == "openda": import thrift + executables = [ - Executable('Scripts/wtools_py/CatchRiver.py', base=base), - Executable('wflow/create_grid.py', base=base), - Executable('wflow/static_maps.py', base=base), - Executable('Scripts/pcr2netcdf.py', base=base), - Executable('Scripts/bmi2runner.py', base=base), - Executable('openda_bmi/opendapy.py', base=base), - Executable('Scripts/wflow_prepare_step2.py', base=base), - Executable('Scripts/wflow_prepare_step1.py', base=base), - Executable('Scripts/wflow_sbm_rtc.py', base=base), - Executable('wflow/wflow_topoflex.py', base=base), - Executable('wflow/wflow_sbm.py', base=base), - Executable('wflow/wflow_adapt.py', base=base), - Executable('wflow/wflow_w3ra.py', base=base), - Executable('wflow/wflow_delwaq.py', base=base), - Executable('wflow/wflow_wave.py', base=base), - Executable('wflow/wflow_gr4.py', base=base), - Executable('wflow/wflow_floodmap.py', base=base), - Executable('wflow/wflow_routing.py', base=base), - Executable('wflow/wflow_hbv.py', base=base), - Executable('wflow/wflow_sphy.py', base=base), - Executable('wflow/wflow_pcrglobwb.py', base=base) + Executable("Scripts/wtools_py/CatchRiver.py", base=base), + Executable("wflow/create_grid.py", base=base), + Executable("wflow/static_maps.py", base=base), + Executable("Scripts/pcr2netcdf.py", base=base), + Executable("Scripts/bmi2runner.py", base=base), + Executable("openda_bmi/opendapy.py", base=base), + Executable("Scripts/wflow_prepare_step2.py", base=base), + Executable("Scripts/wflow_prepare_step1.py", base=base), + Executable("Scripts/wflow_sbm_rtc.py", base=base), + Executable("wflow/wflow_topoflex.py", base=base), + Executable("wflow/wflow_sbm.py", base=base), + Executable("wflow/wflow_adapt.py", base=base), + Executable("wflow/wflow_w3ra.py", base=base), + Executable("wflow/wflow_delwaq.py", base=base), + Executable("wflow/wflow_wave.py", base=base), + Executable("wflow/wflow_gr4.py", base=base), + Executable("wflow/wflow_floodmap.py", base=base), + Executable("wflow/wflow_routing.py", base=base), + Executable("wflow/wflow_hbv.py", base=base), + Executable("wflow/wflow_sphy.py", base=base), + Executable("wflow/wflow_pcrglobwb.py", base=base), ] -elif target == 'deltashell': +elif target == "deltashell": executables = [ - Executable('Scripts/wtools_py/CatchRiver.py', base=base), - Executable('wflow/create_grid.py', base=base), - Executable('wflow/static_maps.py', base=base), - Executable('Scripts/pcr2netcdf.py', base=base), - Executable('Scripts/bmi2runner.py', base=base), - Executable('Scripts/wfds_core.py', base=base), - Executable('Scripts/wflow_prepare_step2.py', base=base), - Executable('Scripts/wflow_prepare_step1.py', base=base), - Executable('Scripts/wflow_sbm_rtc.py', base=base), - Executable('wflow/wflow_topoflex.py', base=base), - Executable('wflow/wflow_routing.py', base=base), - Executable('wflow/wflow_sbm.py', base=base), - Executable('wflow/wflow_adapt.py', base=base), - Executable('wflow/wflow_w3ra.py', base=base), - Executable('wflow/wflow_delwaq.py', base=base), - Executable('wflow/wflow_wave.py', base=base), - Executable('wflow/wflow_gr4.py', base=base), - Executable('wflow/wflow_floodmap.py', base=base), - Executable('wflow/wflow_hbv.py', base=base), - Executable('wflow/wflow_sphy.py', base=base), - Executable('wflow/wflow_pcrglobwb.py', base=base) + Executable("Scripts/wtools_py/CatchRiver.py", base=base), + Executable("wflow/create_grid.py", base=base), + Executable("wflow/static_maps.py", base=base), + Executable("Scripts/pcr2netcdf.py", base=base), + Executable("Scripts/bmi2runner.py", base=base), + Executable("Scripts/wfds_core.py", base=base), + Executable("Scripts/wflow_prepare_step2.py", base=base), + Executable("Scripts/wflow_prepare_step1.py", base=base), + Executable("Scripts/wflow_sbm_rtc.py", base=base), + Executable("wflow/wflow_topoflex.py", base=base), + Executable("wflow/wflow_routing.py", base=base), + Executable("wflow/wflow_sbm.py", base=base), + Executable("wflow/wflow_adapt.py", base=base), + Executable("wflow/wflow_w3ra.py", base=base), + Executable("wflow/wflow_delwaq.py", base=base), + Executable("wflow/wflow_wave.py", base=base), + Executable("wflow/wflow_gr4.py", base=base), + Executable("wflow/wflow_floodmap.py", base=base), + Executable("wflow/wflow_hbv.py", base=base), + Executable("wflow/wflow_sphy.py", base=base), + Executable("wflow/wflow_pcrglobwb.py", base=base), ] else: executables = [ - Executable('Scripts/wtools_py/CatchRiver.py', base=base), - Executable('wflow/create_grid.py', base=base), - Executable('wflow/static_maps.py', base=base), - Executable('Scripts/pcr2netcdf.py', base=base), - Executable('Scripts/bmi2runner.py', base=base), - Executable('Scripts/wflow_prepare_step2.py', base=base), - Executable('Scripts/wflow_prepare_step1.py', base=base), - Executable('Scripts/wflow_sbm_rtc.py', base=base), - Executable('wflow/wflow_topoflex.py', base=base), - Executable('wflow/wflow_sbm.py', base=base), - Executable('wflow/wflow_routing.py', base=base), - Executable('wflow/wflow_adapt.py', base=base), - Executable('wflow/wflow_w3ra.py', base=base), - Executable('wflow/wflow_delwaq.py', base=base), - Executable('wflow/wflow_wave.py', base=base), - Executable('wflow/wflow_gr4.py', base=base), - Executable('wflow/wflow_floodmap.py', base=base), - Executable('wflow/wflow_hbv.py', base=base), - Executable('wflow/wflow_sphy.py', base=base), - Executable('wflow/wflow_pcrglobwb.py', base=base) + Executable("Scripts/wtools_py/CatchRiver.py", base=base), + Executable("wflow/create_grid.py", base=base), + Executable("wflow/static_maps.py", base=base), + Executable("Scripts/pcr2netcdf.py", base=base), + Executable("Scripts/bmi2runner.py", base=base), + Executable("Scripts/wflow_prepare_step2.py", base=base), + Executable("Scripts/wflow_prepare_step1.py", base=base), + Executable("Scripts/wflow_sbm_rtc.py", base=base), + Executable("wflow/wflow_topoflex.py", base=base), + Executable("wflow/wflow_sbm.py", base=base), + Executable("wflow/wflow_routing.py", base=base), + Executable("wflow/wflow_adapt.py", base=base), + Executable("wflow/wflow_w3ra.py", base=base), + Executable("wflow/wflow_delwaq.py", base=base), + Executable("wflow/wflow_wave.py", base=base), + Executable("wflow/wflow_gr4.py", base=base), + Executable("wflow/wflow_floodmap.py", base=base), + Executable("wflow/wflow_hbv.py", base=base), + Executable("wflow/wflow_sphy.py", base=base), + Executable("wflow/wflow_pcrglobwb.py", base=base), ] -setup(name='wflow', - version=MVERSION, - description='Wflow', - options={"build_exe" : options}, - executables=executables, - ) +setup( + name="wflow", + version=MVERSION, + description="Wflow", + options={"build_exe": options}, + executables=executables, +) Index: wflow-py/make_wflow_exe_cx.py =================================================================== diff -u -rc9d975a5a82cb34652cdc5d2ee9afd734c18d3c7 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/make_wflow_exe_cx.py (.../make_wflow_exe_cx.py) (revision c9d975a5a82cb34652cdc5d2ee9afd734c18d3c7) +++ wflow-py/make_wflow_exe_cx.py (.../make_wflow_exe_cx.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -12,41 +12,40 @@ from cx_Freeze import setup, Executable, hooks -import ctypes,glob,os,shutil +import ctypes, glob, os, shutil import matplotlib import scipy import sys import versioneer import json -target = 'normal' +target = "normal" # Filter out wflow specific options if "--openda" in sys.argv: - target = 'openda' + target = "openda" sys.argv.remove("--openda") if "--normal" in sys.argv: - target = 'normal' + target = "normal" sys.argv.remove("--normal") if "--deltashell" in sys.argv: - target = 'deltashell' + target = "deltashell" sys.argv.remove("--deltashell") pdir = os.path.dirname(sys.executable) + "/" -if sys.platform == 'win32': +if sys.platform == "win32": mkl_file = glob.glob(pdir + "conda-meta" + "/" + "mkl-[!service]*.json")[0] data = json.load(open(mkl_file)) -MKL_files = [(pdir + s) for s in data['files']] +MKL_files = [(pdir + s) for s in data["files"]] os.system("python mkversion.py") - -data_files=[] +data_files = [] scipy_path = os.path.dirname(scipy.__file__) data_files.append(scipy_path) @@ -58,162 +57,202 @@ finder.IncludePackage("scipy._lib") # Changed include from scipy.lib to scipy._lib finder.IncludePackage("scipy.misc") + hooks.load_scipy = load_scipy_patched -def mkdatatuples(thelist,destdir="."): + +def mkdatatuples(thelist, destdir="."): """ input list of input files output lis list of tuples including destination :param list: :return: """ ret = [] for item in thelist: - destfile = os.path.join(destdir,os.path.basename(item)) - ret.append((item,destfile)) + destfile = os.path.join(destdir, os.path.basename(item)) + ret.append((item, destfile)) return ret -data_files.append('packages.txt') -#os.system('conda list' + ">" + os.path.join('packages.txt')) + +data_files.append("packages.txt") +# os.system('conda list' + ">" + os.path.join('packages.txt')) # matplolib data files -mpl = matplotlib.get_py2exe_datafiles() +mpl = matplotlib.get_py2exe_datafiles() mplfiles = [] for mpldir in mpl: - ddir = os.path.join('mpl-data',os.path.basename(mpldir[0])) - data_files.extend(mkdatatuples(mpldir[1],destdir=ddir)) + ddir = os.path.join("mpl-data", os.path.basename(mpldir[0])) + data_files.extend(mkdatatuples(mpldir[1], destdir=ddir)) -if sys.platform == 'win32': +if sys.platform == "win32": # MKL files - data_files.extend(mkdatatuples(MKL_files,destdir=".")) + data_files.extend(mkdatatuples(MKL_files, destdir=".")) # pcraster dll's - #ddir = "c:/pcraster/lib/" + # ddir = "c:/pcraster/lib/" ddir = "d:\pcraster-4.0.1_x86-64" - data_files.extend(mkdatatuples(glob.glob(ddir + "/*.dll"),destdir='.')) + data_files.extend(mkdatatuples(glob.glob(ddir + "/*.dll"), destdir=".")) # GDAL data files gdaldata = os.getenv("GDAL_DATA") if gdaldata == None: gdaldata = "c:\Anaconda\Library\share\gdal" -data_files.extend(mkdatatuples(glob.glob(gdaldata + "/*.*"),destdir='gdal-data')) +data_files.extend(mkdatatuples(glob.glob(gdaldata + "/*.*"), destdir="gdal-data")) nrbits = str(ctypes.sizeof(ctypes.c_voidp) * 8) -#includes = ['wflow.wflow_bmi','wflow.wflow_w3ra','wflow.wflow_bmi_combined','bmi','bmi.wrapper',"pcraster","osgeo.ogr"] +# includes = ['wflow.wflow_bmi','wflow.wflow_w3ra','wflow.wflow_bmi_combined','bmi','bmi.wrapper',"pcraster","osgeo.ogr"] versions = versioneer.get_versions() -MVERSION = versions['version'] +MVERSION = versions["version"] -thename = "wflow-bin/Wflow"+MVERSION+'-'+target+'-'+sys.platform+'-'+nrbits +thename = ( + "wflow-bin/Wflow" + MVERSION + "-" + target + "-" + sys.platform + "-" + nrbits +) packages = ["osgeo"] -if target == 'openda': +if target == "openda": import thrift.protocol.TBinaryProtocol as TBinaryProtocol import thrift.transport.THttpClient as THttpClient import thrift.protocol.TBinaryProtocol as TBinaryProtocol import thrift.transport.THttpClient as THttpClient - includes = ['wflow.wflow_bmi','wflow.wflow_w3ra','wflow.wflow_bmi_combined','lxml.etree', 'lxml._elementpath', 'gzip'] - packages.append('openda_bmi') -elif target == 'deltashell': + + includes = [ + "wflow.wflow_bmi", + "wflow.wflow_w3ra", + "wflow.wflow_bmi_combined", + "lxml.etree", + "lxml._elementpath", + "gzip", + ] + packages.append("openda_bmi") +elif target == "deltashell": import zmq.libzmq - data_files.extend([zmq.libzmq.__file__, ]) - includes = ["zmq.backend.cython","zmq.utils.garbage","requests","zmq.eventloop.zmqstream", - 'wflow.wflow_bmi','wflow.wflow_w3ra','wflow.wflow_bmi_combined','lxml.etree', 'lxml._elementpath', 'gzip'] - packages.append('zmq.backend.cython') - packages.append('bmi') - #packages.append('pkg_resources') + + data_files.extend([zmq.libzmq.__file__]) + includes = [ + "zmq.backend.cython", + "zmq.utils.garbage", + "requests", + "zmq.eventloop.zmqstream", + "wflow.wflow_bmi", + "wflow.wflow_w3ra", + "wflow.wflow_bmi_combined", + "lxml.etree", + "lxml._elementpath", + "gzip", + ] + packages.append("zmq.backend.cython") + packages.append("bmi") + # packages.append('pkg_resources') else: - includes = ["matplotlib.backends.backend_qt4agg", 'wflow.pcrglobwb.landCover', 'wflow.wflow_bmi', 'wflow.wflow_w3ra', 'wflow.wflow_bmi_combined','lxml.etree', 'lxml._elementpath', 'gzip', 'numpy.core._methods', 'numpy.lib.format'] + includes = [ + "matplotlib.backends.backend_qt4agg", + "wflow.pcrglobwb.landCover", + "wflow.wflow_bmi", + "wflow.wflow_w3ra", + "wflow.wflow_bmi_combined", + "lxml.etree", + "lxml._elementpath", + "gzip", + "numpy.core._methods", + "numpy.lib.format", + ] # "include_msvcr": True, -options = {"includes": includes, "packages": packages,'include_files': data_files, "build_exe": thename, - 'excludes': ['collections.abc']} -base=None +options = { + "includes": includes, + "packages": packages, + "include_files": data_files, + "build_exe": thename, + "excludes": ["collections.abc"], +} +base = None - - -if target == 'openda': +if target == "openda": import thrift + executables = [ - Executable('Scripts/wtools_py/CatchRiver.py', base=base), - Executable('wflow/create_grid.py', base=base), - Executable('wflow/static_maps.py', base=base), - Executable('Scripts/pcr2netcdf.py', base=base), - Executable('Scripts/bmi2runner.py', base=base), - Executable('openda_bmi/opendapy.py', base=base), - Executable('Scripts/wflow_prepare_step2.py', base=base), - Executable('Scripts/wflow_prepare_step1.py', base=base), - Executable('Scripts/wflow_sbm_rtc.py', base=base), - Executable('wflow/wflow_topoflex.py', base=base), - Executable('wflow/wflow_sbm.py', base=base), - Executable('wflow/wflow_adapt.py', base=base), - Executable('wflow/wflow_w3ra.py', base=base), - Executable('wflow/wflow_delwaq.py', base=base), - Executable('wflow/wflow_wave.py', base=base), - Executable('wflow/wflow_gr4.py', base=base), - Executable('wflow/wflow_floodmap.py', base=base), - Executable('wflow/wflow_routing.py', base=base), - Executable('wflow/wflow_hbv.py', base=base), - Executable('wflow/wflow_sphy.py', base=base), - Executable('wflow/wflow_pcrglobwb.py', base=base) + Executable("Scripts/wtools_py/CatchRiver.py", base=base), + Executable("wflow/create_grid.py", base=base), + Executable("wflow/static_maps.py", base=base), + Executable("Scripts/pcr2netcdf.py", base=base), + Executable("Scripts/bmi2runner.py", base=base), + Executable("openda_bmi/opendapy.py", base=base), + Executable("Scripts/wflow_prepare_step2.py", base=base), + Executable("Scripts/wflow_prepare_step1.py", base=base), + Executable("Scripts/wflow_sbm_rtc.py", base=base), + Executable("wflow/wflow_topoflex.py", base=base), + Executable("wflow/wflow_sbm.py", base=base), + Executable("wflow/wflow_adapt.py", base=base), + Executable("wflow/wflow_w3ra.py", base=base), + Executable("wflow/wflow_delwaq.py", base=base), + Executable("wflow/wflow_wave.py", base=base), + Executable("wflow/wflow_gr4.py", base=base), + Executable("wflow/wflow_floodmap.py", base=base), + Executable("wflow/wflow_routing.py", base=base), + Executable("wflow/wflow_hbv.py", base=base), + Executable("wflow/wflow_sphy.py", base=base), + Executable("wflow/wflow_pcrglobwb.py", base=base), ] -elif target == 'deltashell': +elif target == "deltashell": executables = [ - Executable('Scripts/wtools_py/CatchRiver.py', base=base), - Executable('wflow/create_grid.py', base=base), - Executable('wflow/static_maps.py', base=base), - Executable('Scripts/pcr2netcdf.py', base=base), - Executable('Scripts/bmi2runner.py', base=base), - Executable('Scripts/wfds_core.py', base=base), - Executable('Scripts/wflow_prepare_step2.py', base=base), - Executable('Scripts/wflow_prepare_step1.py', base=base), - Executable('Scripts/wflow_sbm_rtc.py', base=base), - Executable('wflow/wflow_topoflex.py', base=base), - Executable('wflow/wflow_routing.py', base=base), - Executable('wflow/wflow_sbm.py', base=base), - Executable('wflow/wflow_adapt.py', base=base), - Executable('wflow/wflow_w3ra.py', base=base), - Executable('wflow/wflow_delwaq.py', base=base), - Executable('wflow/wflow_wave.py', base=base), - Executable('wflow/wflow_gr4.py', base=base), - Executable('wflow/wflow_floodmap.py', base=base), - Executable('wflow/wflow_hbv.py', base=base), - Executable('wflow/wflow_sphy.py', base=base), - Executable('wflow/wflow_pcrglobwb.py', base=base) + Executable("Scripts/wtools_py/CatchRiver.py", base=base), + Executable("wflow/create_grid.py", base=base), + Executable("wflow/static_maps.py", base=base), + Executable("Scripts/pcr2netcdf.py", base=base), + Executable("Scripts/bmi2runner.py", base=base), + Executable("Scripts/wfds_core.py", base=base), + Executable("Scripts/wflow_prepare_step2.py", base=base), + Executable("Scripts/wflow_prepare_step1.py", base=base), + Executable("Scripts/wflow_sbm_rtc.py", base=base), + Executable("wflow/wflow_topoflex.py", base=base), + Executable("wflow/wflow_routing.py", base=base), + Executable("wflow/wflow_sbm.py", base=base), + Executable("wflow/wflow_adapt.py", base=base), + Executable("wflow/wflow_w3ra.py", base=base), + Executable("wflow/wflow_delwaq.py", base=base), + Executable("wflow/wflow_wave.py", base=base), + Executable("wflow/wflow_gr4.py", base=base), + Executable("wflow/wflow_floodmap.py", base=base), + Executable("wflow/wflow_hbv.py", base=base), + Executable("wflow/wflow_sphy.py", base=base), + Executable("wflow/wflow_pcrglobwb.py", base=base), ] else: executables = [ - Executable('Scripts/wtools_py/CatchRiver.py', base=base), - Executable('wflow/create_grid.py', base=base), - Executable('wflow/static_maps.py', base=base), - Executable('Scripts/pcr2netcdf.py', base=base), - Executable('Scripts/bmi2runner.py', base=base), - Executable('Scripts/wflow_prepare_step2.py', base=base), - Executable('Scripts/wflow_prepare_step1.py', base=base), - Executable('Scripts/wflow_sbm_rtc.py', base=base), - Executable('wflow/wflow_topoflex.py', base=base), - Executable('wflow/wflow_sbm.py', base=base), - Executable('wflow/wflow_lintul.py', base=base), - Executable('wflow/wflow_routing.py', base=base), - Executable('wflow/wflow_adapt.py', base=base), - Executable('wflow/wflow_w3ra.py', base=base), - Executable('wflow/wflow_delwaq.py', base=base), - Executable('wflow/wflow_wave.py', base=base), - Executable('wflow/wflow_gr4.py', base=base), - Executable('wflow/wflow_floodmap.py', base=base), - Executable('wflow/wflow_hbv.py', base=base), - Executable('wflow/wflow_sphy.py', base=base), - Executable('wflow/wflow_pcrglobwb.py', base=base) + Executable("Scripts/wtools_py/CatchRiver.py", base=base), + Executable("wflow/create_grid.py", base=base), + Executable("wflow/static_maps.py", base=base), + Executable("Scripts/pcr2netcdf.py", base=base), + Executable("Scripts/bmi2runner.py", base=base), + Executable("Scripts/wflow_prepare_step2.py", base=base), + Executable("Scripts/wflow_prepare_step1.py", base=base), + Executable("Scripts/wflow_sbm_rtc.py", base=base), + Executable("wflow/wflow_topoflex.py", base=base), + Executable("wflow/wflow_sbm.py", base=base), + Executable("wflow/wflow_lintul.py", base=base), + Executable("wflow/wflow_routing.py", base=base), + Executable("wflow/wflow_adapt.py", base=base), + Executable("wflow/wflow_w3ra.py", base=base), + Executable("wflow/wflow_delwaq.py", base=base), + Executable("wflow/wflow_wave.py", base=base), + Executable("wflow/wflow_gr4.py", base=base), + Executable("wflow/wflow_floodmap.py", base=base), + Executable("wflow/wflow_hbv.py", base=base), + Executable("wflow/wflow_sphy.py", base=base), + Executable("wflow/wflow_pcrglobwb.py", base=base), ] -setup(name='wflow', - version=MVERSION.split('+')[0], - description='Wflow', - options={"build_exe" : options}, - executables=executables, - ) +setup( + name="wflow", + version=MVERSION.split("+")[0], + description="Wflow", + options={"build_exe": options}, + executables=executables, +) Index: wflow-py/openda_bmi/bmi.py =================================================================== diff -u -rcef24d27dba76b014028787be46dd9ae3a2c30b6 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/openda_bmi/bmi.py (.../bmi.py) (revision cef24d27dba76b014028787be46dd9ae3a2c30b6) +++ wflow-py/openda_bmi/bmi.py (.../bmi.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -385,66 +385,65 @@ ??? """ raise NotImplementedError - - + + class EBmi(Bmi): - @abstractmethod def initialize_config(self, config_file): """ First step of two-phase initialize. In this step only the configuration is read in. This allows a user to then change settings and parameters before fully initializing the model """ raise NotImplementedError - + @abstractmethod def initialize_model(self, source_directory): """ Second step of two-phase initialize. In this step the model is setup, and will now allow reading/setting values. """ raise NotImplementedError - + @abstractmethod def set_start_time(self, start_time): """ Set the start time of the model. Can usually only be called after initialize_config and before initialize_model. Expects a value in the time units of the model """ raise NotImplementedError - + @abstractmethod def set_end_time(self, end_time): """ Set the end time of the model. Can usually only be called after initialize_config and before initialize_model. Expects a value in the time units of the model. """ raise NotImplementedError - + @abstractmethod def get_attribute_names(self): """ Gets a list of all supported attributes for this model. Attributes can be considered the meta-data of a model, for instance author, version, model specific settings, etc. """ raise NotImplementedError - + @abstractmethod def get_attribute_value(self, attribute_name): """ Gets the value of a certain attribute for this model. Attributes can be considered the meta-data of a model, for instance author, version, model specific settings, etc. """ raise NotImplementedError - + @abstractmethod def set_attribute_value(self, attribute_name, attribute_value): """ Sets the value of a certain attribute for this model. Usually only string values are allowed. Attributes can be considered the meta-data of a model, for instance author, version, model specific settings, etc. """ raise NotImplementedError - + @abstractmethod def save_state(self, destination_directory): """ @@ -455,7 +454,7 @@ File destination_directory: the directory in which the state files should be written. """ raise NotImplementedError - + @abstractmethod def load_state(self, source_directory): """ Index: wflow-py/openda_bmi/openda/bmi/thrift/BMIService.py =================================================================== diff -u -rcef24d27dba76b014028787be46dd9ae3a2c30b6 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/openda_bmi/openda/bmi/thrift/BMIService.py (.../BMIService.py) (revision cef24d27dba76b014028787be46dd9ae3a2c30b6) +++ wflow-py/openda_bmi/openda/bmi/thrift/BMIService.py (.../BMIService.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -11,6776 +11,7833 @@ from thrift.Thrift import TProcessor from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol + try: - from thrift.protocol import fastbinary + from thrift.protocol import fastbinary except: - fastbinary = None + fastbinary = None class Iface(object): - def initialize(self, file): - """ + def initialize(self, file): + """ Parameters: - file """ - pass + pass - def update(self, ): - pass + def update(self,): + pass - def update_until(self, time): - """ + def update_until(self, time): + """ Parameters: - time """ - pass + pass - def update_frac(self, frac): - """ + def update_frac(self, frac): + """ Parameters: - frac """ - pass + pass - def finalize_model(self, ): - pass + def finalize_model(self,): + pass - def get_component_name(self, ): - pass + def get_component_name(self,): + pass - def get_input_var_names(self, ): - pass + def get_input_var_names(self,): + pass - def get_output_var_names(self, ): - pass + def get_output_var_names(self,): + pass - def get_var_type(self, long_var_name): - """ + def get_var_type(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_var_units(self, long_var_name): - """ + def get_var_units(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_var_rank(self, long_var_name): - """ + def get_var_rank(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_var_size(self, long_var_name): - """ + def get_var_size(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_var_nbytes(self, long_var_name): - """ + def get_var_nbytes(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_start_time(self, ): - pass + def get_start_time(self,): + pass - def get_current_time(self, ): - pass + def get_current_time(self,): + pass - def get_end_time(self, ): - pass + def get_end_time(self,): + pass - def get_time_step(self, ): - pass + def get_time_step(self,): + pass - def get_time_units(self, ): - pass + def get_time_units(self,): + pass - def get_value(self, long_var_name): - """ + def get_value(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_value_at_indices(self, long_var_name, inds): - """ + def get_value_at_indices(self, long_var_name, inds): + """ Parameters: - long_var_name - inds """ - pass + pass - def set_value(self, long_var_name, src): - """ + def set_value(self, long_var_name, src): + """ Parameters: - long_var_name - src """ - pass + pass - def set_value_at_indices(self, long_var_name, inds, src): - """ + def set_value_at_indices(self, long_var_name, inds, src): + """ Parameters: - long_var_name - inds - src """ - pass + pass - def get_grid_type(self, long_var_name): - """ + def get_grid_type(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_grid_shape(self, long_var_name): - """ + def get_grid_shape(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_grid_spacing(self, long_var_name): - """ + def get_grid_spacing(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_grid_origin(self, long_var_name): - """ + def get_grid_origin(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_grid_x(self, long_var_name): - """ + def get_grid_x(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_grid_y(self, long_var_name): - """ + def get_grid_y(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_grid_z(self, long_var_name): - """ + def get_grid_z(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_grid_connectivity(self, long_var_name): - """ + def get_grid_connectivity(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def get_grid_offset(self, long_var_name): - """ + def get_grid_offset(self, long_var_name): + """ Parameters: - long_var_name """ - pass + pass - def initialize_config(self, file): - """ + def initialize_config(self, file): + """ Parameters: - file """ - pass + pass - def initialize_model(self, ): - pass + def initialize_model(self,): + pass - def set_start_time(self, start_time): - """ + def set_start_time(self, start_time): + """ Parameters: - start_time """ - pass + pass - def set_end_time(self, end_time): - """ + def set_end_time(self, end_time): + """ Parameters: - end_time """ - pass + pass - def get_attribute_names(self, ): - pass + def get_attribute_names(self,): + pass - def get_attribute_value(self, attribute_name): - """ + def get_attribute_value(self, attribute_name): + """ Parameters: - attribute_name """ - pass + pass - def set_attribute_value(self, attribute_name, attribute_value): - """ + def set_attribute_value(self, attribute_name, attribute_value): + """ Parameters: - attribute_name - attribute_value """ - pass + pass - def save_state(self, destination_directory): - """ + def save_state(self, destination_directory): + """ Parameters: - destination_directory """ - pass + pass - def load_state(self, source_directory): - """ + def load_state(self, source_directory): + """ Parameters: - source_directory """ - pass + pass class Client(Iface): - def __init__(self, iprot, oprot=None): - self._iprot = self._oprot = iprot - if oprot is not None: - self._oprot = oprot - self._seqid = 0 + def __init__(self, iprot, oprot=None): + self._iprot = self._oprot = iprot + if oprot is not None: + self._oprot = oprot + self._seqid = 0 - def initialize(self, file): - """ + def initialize(self, file): + """ Parameters: - file """ - self.send_initialize(file) - self.recv_initialize() + self.send_initialize(file) + self.recv_initialize() - def send_initialize(self, file): - self._oprot.writeMessageBegin('initialize', TMessageType.CALL, self._seqid) - args = initialize_args() - args.file = file - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_initialize(self, file): + self._oprot.writeMessageBegin("initialize", TMessageType.CALL, self._seqid) + args = initialize_args() + args.file = file + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_initialize(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = initialize_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_initialize(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = initialize_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def update(self, ): - self.send_update() - self.recv_update() + def update(self,): + self.send_update() + self.recv_update() - def send_update(self, ): - self._oprot.writeMessageBegin('update', TMessageType.CALL, self._seqid) - args = update_args() - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_update(self,): + self._oprot.writeMessageBegin("update", TMessageType.CALL, self._seqid) + args = update_args() + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_update(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = update_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_update(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = update_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def update_until(self, time): - """ + def update_until(self, time): + """ Parameters: - time """ - self.send_update_until(time) - self.recv_update_until() + self.send_update_until(time) + self.recv_update_until() - def send_update_until(self, time): - self._oprot.writeMessageBegin('update_until', TMessageType.CALL, self._seqid) - args = update_until_args() - args.time = time - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_update_until(self, time): + self._oprot.writeMessageBegin("update_until", TMessageType.CALL, self._seqid) + args = update_until_args() + args.time = time + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_update_until(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = update_until_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_update_until(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = update_until_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def update_frac(self, frac): - """ + def update_frac(self, frac): + """ Parameters: - frac """ - self.send_update_frac(frac) - self.recv_update_frac() + self.send_update_frac(frac) + self.recv_update_frac() - def send_update_frac(self, frac): - self._oprot.writeMessageBegin('update_frac', TMessageType.CALL, self._seqid) - args = update_frac_args() - args.frac = frac - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_update_frac(self, frac): + self._oprot.writeMessageBegin("update_frac", TMessageType.CALL, self._seqid) + args = update_frac_args() + args.frac = frac + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_update_frac(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = update_frac_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_update_frac(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = update_frac_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def finalize_model(self, ): - self.send_finalize_model() - self.recv_finalize_model() + def finalize_model(self,): + self.send_finalize_model() + self.recv_finalize_model() - def send_finalize_model(self, ): - self._oprot.writeMessageBegin('finalize_model', TMessageType.CALL, self._seqid) - args = finalize_model_args() - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_finalize_model(self,): + self._oprot.writeMessageBegin("finalize_model", TMessageType.CALL, self._seqid) + args = finalize_model_args() + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_finalize_model(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = finalize_model_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_finalize_model(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = finalize_model_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def get_component_name(self, ): - self.send_get_component_name() - return self.recv_get_component_name() + def get_component_name(self,): + self.send_get_component_name() + return self.recv_get_component_name() - def send_get_component_name(self, ): - self._oprot.writeMessageBegin('get_component_name', TMessageType.CALL, self._seqid) - args = get_component_name_args() - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_component_name(self,): + self._oprot.writeMessageBegin( + "get_component_name", TMessageType.CALL, self._seqid + ) + args = get_component_name_args() + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_component_name(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_component_name_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - if result.error is not None: - raise result.error - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_component_name failed: unknown result"); + def recv_get_component_name(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_component_name_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + if result.error is not None: + raise result.error + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_component_name failed: unknown result", + ) - def get_input_var_names(self, ): - self.send_get_input_var_names() - return self.recv_get_input_var_names() + def get_input_var_names(self,): + self.send_get_input_var_names() + return self.recv_get_input_var_names() - def send_get_input_var_names(self, ): - self._oprot.writeMessageBegin('get_input_var_names', TMessageType.CALL, self._seqid) - args = get_input_var_names_args() - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_input_var_names(self,): + self._oprot.writeMessageBegin( + "get_input_var_names", TMessageType.CALL, self._seqid + ) + args = get_input_var_names_args() + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_input_var_names(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_input_var_names_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_input_var_names failed: unknown result"); + def recv_get_input_var_names(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_input_var_names_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_input_var_names failed: unknown result", + ) - def get_output_var_names(self, ): - self.send_get_output_var_names() - return self.recv_get_output_var_names() + def get_output_var_names(self,): + self.send_get_output_var_names() + return self.recv_get_output_var_names() - def send_get_output_var_names(self, ): - self._oprot.writeMessageBegin('get_output_var_names', TMessageType.CALL, self._seqid) - args = get_output_var_names_args() - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_output_var_names(self,): + self._oprot.writeMessageBegin( + "get_output_var_names", TMessageType.CALL, self._seqid + ) + args = get_output_var_names_args() + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_output_var_names(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_output_var_names_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_output_var_names failed: unknown result"); + def recv_get_output_var_names(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_output_var_names_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_output_var_names failed: unknown result", + ) - def get_var_type(self, long_var_name): - """ + def get_var_type(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_var_type(long_var_name) - return self.recv_get_var_type() + self.send_get_var_type(long_var_name) + return self.recv_get_var_type() - def send_get_var_type(self, long_var_name): - self._oprot.writeMessageBegin('get_var_type', TMessageType.CALL, self._seqid) - args = get_var_type_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_var_type(self, long_var_name): + self._oprot.writeMessageBegin("get_var_type", TMessageType.CALL, self._seqid) + args = get_var_type_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_var_type(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_var_type_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_var_type failed: unknown result"); + def recv_get_var_type(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_var_type_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, "get_var_type failed: unknown result" + ) - def get_var_units(self, long_var_name): - """ + def get_var_units(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_var_units(long_var_name) - return self.recv_get_var_units() + self.send_get_var_units(long_var_name) + return self.recv_get_var_units() - def send_get_var_units(self, long_var_name): - self._oprot.writeMessageBegin('get_var_units', TMessageType.CALL, self._seqid) - args = get_var_units_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_var_units(self, long_var_name): + self._oprot.writeMessageBegin("get_var_units", TMessageType.CALL, self._seqid) + args = get_var_units_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_var_units(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_var_units_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_var_units failed: unknown result"); + def recv_get_var_units(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_var_units_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, "get_var_units failed: unknown result" + ) - def get_var_rank(self, long_var_name): - """ + def get_var_rank(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_var_rank(long_var_name) - return self.recv_get_var_rank() + self.send_get_var_rank(long_var_name) + return self.recv_get_var_rank() - def send_get_var_rank(self, long_var_name): - self._oprot.writeMessageBegin('get_var_rank', TMessageType.CALL, self._seqid) - args = get_var_rank_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_var_rank(self, long_var_name): + self._oprot.writeMessageBegin("get_var_rank", TMessageType.CALL, self._seqid) + args = get_var_rank_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_var_rank(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_var_rank_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_var_rank failed: unknown result"); + def recv_get_var_rank(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_var_rank_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, "get_var_rank failed: unknown result" + ) - def get_var_size(self, long_var_name): - """ + def get_var_size(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_var_size(long_var_name) - return self.recv_get_var_size() + self.send_get_var_size(long_var_name) + return self.recv_get_var_size() - def send_get_var_size(self, long_var_name): - self._oprot.writeMessageBegin('get_var_size', TMessageType.CALL, self._seqid) - args = get_var_size_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_var_size(self, long_var_name): + self._oprot.writeMessageBegin("get_var_size", TMessageType.CALL, self._seqid) + args = get_var_size_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_var_size(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_var_size_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_var_size failed: unknown result"); + def recv_get_var_size(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_var_size_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, "get_var_size failed: unknown result" + ) - def get_var_nbytes(self, long_var_name): - """ + def get_var_nbytes(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_var_nbytes(long_var_name) - return self.recv_get_var_nbytes() + self.send_get_var_nbytes(long_var_name) + return self.recv_get_var_nbytes() - def send_get_var_nbytes(self, long_var_name): - self._oprot.writeMessageBegin('get_var_nbytes', TMessageType.CALL, self._seqid) - args = get_var_nbytes_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_var_nbytes(self, long_var_name): + self._oprot.writeMessageBegin("get_var_nbytes", TMessageType.CALL, self._seqid) + args = get_var_nbytes_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_var_nbytes(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_var_nbytes_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_var_nbytes failed: unknown result"); + def recv_get_var_nbytes(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_var_nbytes_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_var_nbytes failed: unknown result", + ) - def get_start_time(self, ): - self.send_get_start_time() - return self.recv_get_start_time() + def get_start_time(self,): + self.send_get_start_time() + return self.recv_get_start_time() - def send_get_start_time(self, ): - self._oprot.writeMessageBegin('get_start_time', TMessageType.CALL, self._seqid) - args = get_start_time_args() - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_start_time(self,): + self._oprot.writeMessageBegin("get_start_time", TMessageType.CALL, self._seqid) + args = get_start_time_args() + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_start_time(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_start_time_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_start_time failed: unknown result"); + def recv_get_start_time(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_start_time_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_start_time failed: unknown result", + ) - def get_current_time(self, ): - self.send_get_current_time() - return self.recv_get_current_time() + def get_current_time(self,): + self.send_get_current_time() + return self.recv_get_current_time() - def send_get_current_time(self, ): - self._oprot.writeMessageBegin('get_current_time', TMessageType.CALL, self._seqid) - args = get_current_time_args() - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_current_time(self,): + self._oprot.writeMessageBegin( + "get_current_time", TMessageType.CALL, self._seqid + ) + args = get_current_time_args() + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_current_time(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_current_time_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_current_time failed: unknown result"); + def recv_get_current_time(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_current_time_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_current_time failed: unknown result", + ) - def get_end_time(self, ): - self.send_get_end_time() - return self.recv_get_end_time() + def get_end_time(self,): + self.send_get_end_time() + return self.recv_get_end_time() - def send_get_end_time(self, ): - self._oprot.writeMessageBegin('get_end_time', TMessageType.CALL, self._seqid) - args = get_end_time_args() - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_end_time(self,): + self._oprot.writeMessageBegin("get_end_time", TMessageType.CALL, self._seqid) + args = get_end_time_args() + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_end_time(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_end_time_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_end_time failed: unknown result"); + def recv_get_end_time(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_end_time_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, "get_end_time failed: unknown result" + ) - def get_time_step(self, ): - self.send_get_time_step() - return self.recv_get_time_step() + def get_time_step(self,): + self.send_get_time_step() + return self.recv_get_time_step() - def send_get_time_step(self, ): - self._oprot.writeMessageBegin('get_time_step', TMessageType.CALL, self._seqid) - args = get_time_step_args() - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_time_step(self,): + self._oprot.writeMessageBegin("get_time_step", TMessageType.CALL, self._seqid) + args = get_time_step_args() + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_time_step(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_time_step_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_time_step failed: unknown result"); + def recv_get_time_step(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_time_step_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, "get_time_step failed: unknown result" + ) - def get_time_units(self, ): - self.send_get_time_units() - return self.recv_get_time_units() + def get_time_units(self,): + self.send_get_time_units() + return self.recv_get_time_units() - def send_get_time_units(self, ): - self._oprot.writeMessageBegin('get_time_units', TMessageType.CALL, self._seqid) - args = get_time_units_args() - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_time_units(self,): + self._oprot.writeMessageBegin("get_time_units", TMessageType.CALL, self._seqid) + args = get_time_units_args() + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_time_units(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_time_units_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_time_units failed: unknown result"); + def recv_get_time_units(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_time_units_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_time_units failed: unknown result", + ) - def get_value(self, long_var_name): - """ + def get_value(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_value(long_var_name) - return self.recv_get_value() + self.send_get_value(long_var_name) + return self.recv_get_value() - def send_get_value(self, long_var_name): - self._oprot.writeMessageBegin('get_value', TMessageType.CALL, self._seqid) - args = get_value_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_value(self, long_var_name): + self._oprot.writeMessageBegin("get_value", TMessageType.CALL, self._seqid) + args = get_value_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_value(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_value_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - if result.error is not None: - raise result.error - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_value failed: unknown result"); + def recv_get_value(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_value_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + if result.error is not None: + raise result.error + raise TApplicationException( + TApplicationException.MISSING_RESULT, "get_value failed: unknown result" + ) - def get_value_at_indices(self, long_var_name, inds): - """ + def get_value_at_indices(self, long_var_name, inds): + """ Parameters: - long_var_name - inds """ - self.send_get_value_at_indices(long_var_name, inds) - return self.recv_get_value_at_indices() + self.send_get_value_at_indices(long_var_name, inds) + return self.recv_get_value_at_indices() - def send_get_value_at_indices(self, long_var_name, inds): - self._oprot.writeMessageBegin('get_value_at_indices', TMessageType.CALL, self._seqid) - args = get_value_at_indices_args() - args.long_var_name = long_var_name - args.inds = inds - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_value_at_indices(self, long_var_name, inds): + self._oprot.writeMessageBegin( + "get_value_at_indices", TMessageType.CALL, self._seqid + ) + args = get_value_at_indices_args() + args.long_var_name = long_var_name + args.inds = inds + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_value_at_indices(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_value_at_indices_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - if result.error is not None: - raise result.error - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_value_at_indices failed: unknown result"); + def recv_get_value_at_indices(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_value_at_indices_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + if result.error is not None: + raise result.error + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_value_at_indices failed: unknown result", + ) - def set_value(self, long_var_name, src): - """ + def set_value(self, long_var_name, src): + """ Parameters: - long_var_name - src """ - self.send_set_value(long_var_name, src) - self.recv_set_value() + self.send_set_value(long_var_name, src) + self.recv_set_value() - def send_set_value(self, long_var_name, src): - self._oprot.writeMessageBegin('set_value', TMessageType.CALL, self._seqid) - args = set_value_args() - args.long_var_name = long_var_name - args.src = src - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_set_value(self, long_var_name, src): + self._oprot.writeMessageBegin("set_value", TMessageType.CALL, self._seqid) + args = set_value_args() + args.long_var_name = long_var_name + args.src = src + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_set_value(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = set_value_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_set_value(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = set_value_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def set_value_at_indices(self, long_var_name, inds, src): - """ + def set_value_at_indices(self, long_var_name, inds, src): + """ Parameters: - long_var_name - inds - src """ - self.send_set_value_at_indices(long_var_name, inds, src) - self.recv_set_value_at_indices() + self.send_set_value_at_indices(long_var_name, inds, src) + self.recv_set_value_at_indices() - def send_set_value_at_indices(self, long_var_name, inds, src): - self._oprot.writeMessageBegin('set_value_at_indices', TMessageType.CALL, self._seqid) - args = set_value_at_indices_args() - args.long_var_name = long_var_name - args.inds = inds - args.src = src - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_set_value_at_indices(self, long_var_name, inds, src): + self._oprot.writeMessageBegin( + "set_value_at_indices", TMessageType.CALL, self._seqid + ) + args = set_value_at_indices_args() + args.long_var_name = long_var_name + args.inds = inds + args.src = src + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_set_value_at_indices(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = set_value_at_indices_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_set_value_at_indices(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = set_value_at_indices_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def get_grid_type(self, long_var_name): - """ + def get_grid_type(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_grid_type(long_var_name) - return self.recv_get_grid_type() + self.send_get_grid_type(long_var_name) + return self.recv_get_grid_type() - def send_get_grid_type(self, long_var_name): - self._oprot.writeMessageBegin('get_grid_type', TMessageType.CALL, self._seqid) - args = get_grid_type_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_grid_type(self, long_var_name): + self._oprot.writeMessageBegin("get_grid_type", TMessageType.CALL, self._seqid) + args = get_grid_type_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_grid_type(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_grid_type_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - if result.error is not None: - raise result.error - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_grid_type failed: unknown result"); + def recv_get_grid_type(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_grid_type_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + if result.error is not None: + raise result.error + raise TApplicationException( + TApplicationException.MISSING_RESULT, "get_grid_type failed: unknown result" + ) - def get_grid_shape(self, long_var_name): - """ + def get_grid_shape(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_grid_shape(long_var_name) - return self.recv_get_grid_shape() + self.send_get_grid_shape(long_var_name) + return self.recv_get_grid_shape() - def send_get_grid_shape(self, long_var_name): - self._oprot.writeMessageBegin('get_grid_shape', TMessageType.CALL, self._seqid) - args = get_grid_shape_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_grid_shape(self, long_var_name): + self._oprot.writeMessageBegin("get_grid_shape", TMessageType.CALL, self._seqid) + args = get_grid_shape_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_grid_shape(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_grid_shape_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_grid_shape failed: unknown result"); + def recv_get_grid_shape(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_grid_shape_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_grid_shape failed: unknown result", + ) - def get_grid_spacing(self, long_var_name): - """ + def get_grid_spacing(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_grid_spacing(long_var_name) - return self.recv_get_grid_spacing() + self.send_get_grid_spacing(long_var_name) + return self.recv_get_grid_spacing() - def send_get_grid_spacing(self, long_var_name): - self._oprot.writeMessageBegin('get_grid_spacing', TMessageType.CALL, self._seqid) - args = get_grid_spacing_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_grid_spacing(self, long_var_name): + self._oprot.writeMessageBegin( + "get_grid_spacing", TMessageType.CALL, self._seqid + ) + args = get_grid_spacing_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_grid_spacing(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_grid_spacing_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_grid_spacing failed: unknown result"); + def recv_get_grid_spacing(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_grid_spacing_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_grid_spacing failed: unknown result", + ) - def get_grid_origin(self, long_var_name): - """ + def get_grid_origin(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_grid_origin(long_var_name) - return self.recv_get_grid_origin() + self.send_get_grid_origin(long_var_name) + return self.recv_get_grid_origin() - def send_get_grid_origin(self, long_var_name): - self._oprot.writeMessageBegin('get_grid_origin', TMessageType.CALL, self._seqid) - args = get_grid_origin_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_grid_origin(self, long_var_name): + self._oprot.writeMessageBegin("get_grid_origin", TMessageType.CALL, self._seqid) + args = get_grid_origin_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_grid_origin(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_grid_origin_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_grid_origin failed: unknown result"); + def recv_get_grid_origin(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_grid_origin_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_grid_origin failed: unknown result", + ) - def get_grid_x(self, long_var_name): - """ + def get_grid_x(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_grid_x(long_var_name) - return self.recv_get_grid_x() + self.send_get_grid_x(long_var_name) + return self.recv_get_grid_x() - def send_get_grid_x(self, long_var_name): - self._oprot.writeMessageBegin('get_grid_x', TMessageType.CALL, self._seqid) - args = get_grid_x_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_grid_x(self, long_var_name): + self._oprot.writeMessageBegin("get_grid_x", TMessageType.CALL, self._seqid) + args = get_grid_x_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_grid_x(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_grid_x_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_grid_x failed: unknown result"); + def recv_get_grid_x(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_grid_x_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, "get_grid_x failed: unknown result" + ) - def get_grid_y(self, long_var_name): - """ + def get_grid_y(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_grid_y(long_var_name) - return self.recv_get_grid_y() + self.send_get_grid_y(long_var_name) + return self.recv_get_grid_y() - def send_get_grid_y(self, long_var_name): - self._oprot.writeMessageBegin('get_grid_y', TMessageType.CALL, self._seqid) - args = get_grid_y_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_grid_y(self, long_var_name): + self._oprot.writeMessageBegin("get_grid_y", TMessageType.CALL, self._seqid) + args = get_grid_y_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_grid_y(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_grid_y_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_grid_y failed: unknown result"); + def recv_get_grid_y(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_grid_y_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, "get_grid_y failed: unknown result" + ) - def get_grid_z(self, long_var_name): - """ + def get_grid_z(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_grid_z(long_var_name) - return self.recv_get_grid_z() + self.send_get_grid_z(long_var_name) + return self.recv_get_grid_z() - def send_get_grid_z(self, long_var_name): - self._oprot.writeMessageBegin('get_grid_z', TMessageType.CALL, self._seqid) - args = get_grid_z_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_grid_z(self, long_var_name): + self._oprot.writeMessageBegin("get_grid_z", TMessageType.CALL, self._seqid) + args = get_grid_z_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_grid_z(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_grid_z_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_grid_z failed: unknown result"); + def recv_get_grid_z(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_grid_z_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, "get_grid_z failed: unknown result" + ) - def get_grid_connectivity(self, long_var_name): - """ + def get_grid_connectivity(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_grid_connectivity(long_var_name) - return self.recv_get_grid_connectivity() + self.send_get_grid_connectivity(long_var_name) + return self.recv_get_grid_connectivity() - def send_get_grid_connectivity(self, long_var_name): - self._oprot.writeMessageBegin('get_grid_connectivity', TMessageType.CALL, self._seqid) - args = get_grid_connectivity_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_grid_connectivity(self, long_var_name): + self._oprot.writeMessageBegin( + "get_grid_connectivity", TMessageType.CALL, self._seqid + ) + args = get_grid_connectivity_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_grid_connectivity(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_grid_connectivity_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_grid_connectivity failed: unknown result"); + def recv_get_grid_connectivity(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_grid_connectivity_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_grid_connectivity failed: unknown result", + ) - def get_grid_offset(self, long_var_name): - """ + def get_grid_offset(self, long_var_name): + """ Parameters: - long_var_name """ - self.send_get_grid_offset(long_var_name) - return self.recv_get_grid_offset() + self.send_get_grid_offset(long_var_name) + return self.recv_get_grid_offset() - def send_get_grid_offset(self, long_var_name): - self._oprot.writeMessageBegin('get_grid_offset', TMessageType.CALL, self._seqid) - args = get_grid_offset_args() - args.long_var_name = long_var_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_grid_offset(self, long_var_name): + self._oprot.writeMessageBegin("get_grid_offset", TMessageType.CALL, self._seqid) + args = get_grid_offset_args() + args.long_var_name = long_var_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_grid_offset(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_grid_offset_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_grid_offset failed: unknown result"); + def recv_get_grid_offset(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_grid_offset_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_grid_offset failed: unknown result", + ) - def initialize_config(self, file): - """ + def initialize_config(self, file): + """ Parameters: - file """ - self.send_initialize_config(file) - self.recv_initialize_config() + self.send_initialize_config(file) + self.recv_initialize_config() - def send_initialize_config(self, file): - self._oprot.writeMessageBegin('initialize_config', TMessageType.CALL, self._seqid) - args = initialize_config_args() - args.file = file - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_initialize_config(self, file): + self._oprot.writeMessageBegin( + "initialize_config", TMessageType.CALL, self._seqid + ) + args = initialize_config_args() + args.file = file + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_initialize_config(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = initialize_config_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_initialize_config(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = initialize_config_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def initialize_model(self, ): - self.send_initialize_model() - self.recv_initialize_model() + def initialize_model(self,): + self.send_initialize_model() + self.recv_initialize_model() - def send_initialize_model(self, ): - self._oprot.writeMessageBegin('initialize_model', TMessageType.CALL, self._seqid) - args = initialize_model_args() - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_initialize_model(self,): + self._oprot.writeMessageBegin( + "initialize_model", TMessageType.CALL, self._seqid + ) + args = initialize_model_args() + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_initialize_model(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = initialize_model_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_initialize_model(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = initialize_model_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def set_start_time(self, start_time): - """ + def set_start_time(self, start_time): + """ Parameters: - start_time """ - self.send_set_start_time(start_time) - self.recv_set_start_time() + self.send_set_start_time(start_time) + self.recv_set_start_time() - def send_set_start_time(self, start_time): - self._oprot.writeMessageBegin('set_start_time', TMessageType.CALL, self._seqid) - args = set_start_time_args() - args.start_time = start_time - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_set_start_time(self, start_time): + self._oprot.writeMessageBegin("set_start_time", TMessageType.CALL, self._seqid) + args = set_start_time_args() + args.start_time = start_time + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_set_start_time(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = set_start_time_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_set_start_time(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = set_start_time_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def set_end_time(self, end_time): - """ + def set_end_time(self, end_time): + """ Parameters: - end_time """ - self.send_set_end_time(end_time) - self.recv_set_end_time() + self.send_set_end_time(end_time) + self.recv_set_end_time() - def send_set_end_time(self, end_time): - self._oprot.writeMessageBegin('set_end_time', TMessageType.CALL, self._seqid) - args = set_end_time_args() - args.end_time = end_time - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_set_end_time(self, end_time): + self._oprot.writeMessageBegin("set_end_time", TMessageType.CALL, self._seqid) + args = set_end_time_args() + args.end_time = end_time + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_set_end_time(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = set_end_time_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_set_end_time(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = set_end_time_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def get_attribute_names(self, ): - self.send_get_attribute_names() - return self.recv_get_attribute_names() + def get_attribute_names(self,): + self.send_get_attribute_names() + return self.recv_get_attribute_names() - def send_get_attribute_names(self, ): - self._oprot.writeMessageBegin('get_attribute_names', TMessageType.CALL, self._seqid) - args = get_attribute_names_args() - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_attribute_names(self,): + self._oprot.writeMessageBegin( + "get_attribute_names", TMessageType.CALL, self._seqid + ) + args = get_attribute_names_args() + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_attribute_names(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_attribute_names_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_attribute_names failed: unknown result"); + def recv_get_attribute_names(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_attribute_names_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_attribute_names failed: unknown result", + ) - def get_attribute_value(self, attribute_name): - """ + def get_attribute_value(self, attribute_name): + """ Parameters: - attribute_name """ - self.send_get_attribute_value(attribute_name) - return self.recv_get_attribute_value() + self.send_get_attribute_value(attribute_name) + return self.recv_get_attribute_value() - def send_get_attribute_value(self, attribute_name): - self._oprot.writeMessageBegin('get_attribute_value', TMessageType.CALL, self._seqid) - args = get_attribute_value_args() - args.attribute_name = attribute_name - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_get_attribute_value(self, attribute_name): + self._oprot.writeMessageBegin( + "get_attribute_value", TMessageType.CALL, self._seqid + ) + args = get_attribute_value_args() + args.attribute_name = attribute_name + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_get_attribute_value(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = get_attribute_value_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.success is not None: - return result.success - if result.error is not None: - raise result.error - raise TApplicationException(TApplicationException.MISSING_RESULT, "get_attribute_value failed: unknown result"); + def recv_get_attribute_value(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = get_attribute_value_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.success is not None: + return result.success + if result.error is not None: + raise result.error + raise TApplicationException( + TApplicationException.MISSING_RESULT, + "get_attribute_value failed: unknown result", + ) - def set_attribute_value(self, attribute_name, attribute_value): - """ + def set_attribute_value(self, attribute_name, attribute_value): + """ Parameters: - attribute_name - attribute_value """ - self.send_set_attribute_value(attribute_name, attribute_value) - self.recv_set_attribute_value() + self.send_set_attribute_value(attribute_name, attribute_value) + self.recv_set_attribute_value() - def send_set_attribute_value(self, attribute_name, attribute_value): - self._oprot.writeMessageBegin('set_attribute_value', TMessageType.CALL, self._seqid) - args = set_attribute_value_args() - args.attribute_name = attribute_name - args.attribute_value = attribute_value - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_set_attribute_value(self, attribute_name, attribute_value): + self._oprot.writeMessageBegin( + "set_attribute_value", TMessageType.CALL, self._seqid + ) + args = set_attribute_value_args() + args.attribute_name = attribute_name + args.attribute_value = attribute_value + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_set_attribute_value(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = set_attribute_value_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_set_attribute_value(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = set_attribute_value_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def save_state(self, destination_directory): - """ + def save_state(self, destination_directory): + """ Parameters: - destination_directory """ - self.send_save_state(destination_directory) - self.recv_save_state() + self.send_save_state(destination_directory) + self.recv_save_state() - def send_save_state(self, destination_directory): - self._oprot.writeMessageBegin('save_state', TMessageType.CALL, self._seqid) - args = save_state_args() - args.destination_directory = destination_directory - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_save_state(self, destination_directory): + self._oprot.writeMessageBegin("save_state", TMessageType.CALL, self._seqid) + args = save_state_args() + args.destination_directory = destination_directory + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_save_state(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = save_state_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_save_state(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = save_state_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return - def load_state(self, source_directory): - """ + def load_state(self, source_directory): + """ Parameters: - source_directory """ - self.send_load_state(source_directory) - self.recv_load_state() + self.send_load_state(source_directory) + self.recv_load_state() - def send_load_state(self, source_directory): - self._oprot.writeMessageBegin('load_state', TMessageType.CALL, self._seqid) - args = load_state_args() - args.source_directory = source_directory - args.write(self._oprot) - self._oprot.writeMessageEnd() - self._oprot.trans.flush() + def send_load_state(self, source_directory): + self._oprot.writeMessageBegin("load_state", TMessageType.CALL, self._seqid) + args = load_state_args() + args.source_directory = source_directory + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() - def recv_load_state(self, ): - (fname, mtype, rseqid) = self._iprot.readMessageBegin() - if mtype == TMessageType.EXCEPTION: - x = TApplicationException() - x.read(self._iprot) - self._iprot.readMessageEnd() - raise x - result = load_state_result() - result.read(self._iprot) - self._iprot.readMessageEnd() - if result.error is not None: - raise result.error - return + def recv_load_state(self,): + (fname, mtype, rseqid) = self._iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(self._iprot) + self._iprot.readMessageEnd() + raise x + result = load_state_result() + result.read(self._iprot) + self._iprot.readMessageEnd() + if result.error is not None: + raise result.error + return class Processor(Iface, TProcessor): - def __init__(self, handler): - self._handler = handler - self._processMap = {} - self._processMap["initialize"] = Processor.process_initialize - self._processMap["update"] = Processor.process_update - self._processMap["update_until"] = Processor.process_update_until - self._processMap["update_frac"] = Processor.process_update_frac - self._processMap["finalize_model"] = Processor.process_finalize_model - self._processMap["get_component_name"] = Processor.process_get_component_name - self._processMap["get_input_var_names"] = Processor.process_get_input_var_names - self._processMap["get_output_var_names"] = Processor.process_get_output_var_names - self._processMap["get_var_type"] = Processor.process_get_var_type - self._processMap["get_var_units"] = Processor.process_get_var_units - self._processMap["get_var_rank"] = Processor.process_get_var_rank - self._processMap["get_var_size"] = Processor.process_get_var_size - self._processMap["get_var_nbytes"] = Processor.process_get_var_nbytes - self._processMap["get_start_time"] = Processor.process_get_start_time - self._processMap["get_current_time"] = Processor.process_get_current_time - self._processMap["get_end_time"] = Processor.process_get_end_time - self._processMap["get_time_step"] = Processor.process_get_time_step - self._processMap["get_time_units"] = Processor.process_get_time_units - self._processMap["get_value"] = Processor.process_get_value - self._processMap["get_value_at_indices"] = Processor.process_get_value_at_indices - self._processMap["set_value"] = Processor.process_set_value - self._processMap["set_value_at_indices"] = Processor.process_set_value_at_indices - self._processMap["get_grid_type"] = Processor.process_get_grid_type - self._processMap["get_grid_shape"] = Processor.process_get_grid_shape - self._processMap["get_grid_spacing"] = Processor.process_get_grid_spacing - self._processMap["get_grid_origin"] = Processor.process_get_grid_origin - self._processMap["get_grid_x"] = Processor.process_get_grid_x - self._processMap["get_grid_y"] = Processor.process_get_grid_y - self._processMap["get_grid_z"] = Processor.process_get_grid_z - self._processMap["get_grid_connectivity"] = Processor.process_get_grid_connectivity - self._processMap["get_grid_offset"] = Processor.process_get_grid_offset - self._processMap["initialize_config"] = Processor.process_initialize_config - self._processMap["initialize_model"] = Processor.process_initialize_model - self._processMap["set_start_time"] = Processor.process_set_start_time - self._processMap["set_end_time"] = Processor.process_set_end_time - self._processMap["get_attribute_names"] = Processor.process_get_attribute_names - self._processMap["get_attribute_value"] = Processor.process_get_attribute_value - self._processMap["set_attribute_value"] = Processor.process_set_attribute_value - self._processMap["save_state"] = Processor.process_save_state - self._processMap["load_state"] = Processor.process_load_state + def __init__(self, handler): + self._handler = handler + self._processMap = {} + self._processMap["initialize"] = Processor.process_initialize + self._processMap["update"] = Processor.process_update + self._processMap["update_until"] = Processor.process_update_until + self._processMap["update_frac"] = Processor.process_update_frac + self._processMap["finalize_model"] = Processor.process_finalize_model + self._processMap["get_component_name"] = Processor.process_get_component_name + self._processMap["get_input_var_names"] = Processor.process_get_input_var_names + self._processMap[ + "get_output_var_names" + ] = Processor.process_get_output_var_names + self._processMap["get_var_type"] = Processor.process_get_var_type + self._processMap["get_var_units"] = Processor.process_get_var_units + self._processMap["get_var_rank"] = Processor.process_get_var_rank + self._processMap["get_var_size"] = Processor.process_get_var_size + self._processMap["get_var_nbytes"] = Processor.process_get_var_nbytes + self._processMap["get_start_time"] = Processor.process_get_start_time + self._processMap["get_current_time"] = Processor.process_get_current_time + self._processMap["get_end_time"] = Processor.process_get_end_time + self._processMap["get_time_step"] = Processor.process_get_time_step + self._processMap["get_time_units"] = Processor.process_get_time_units + self._processMap["get_value"] = Processor.process_get_value + self._processMap[ + "get_value_at_indices" + ] = Processor.process_get_value_at_indices + self._processMap["set_value"] = Processor.process_set_value + self._processMap[ + "set_value_at_indices" + ] = Processor.process_set_value_at_indices + self._processMap["get_grid_type"] = Processor.process_get_grid_type + self._processMap["get_grid_shape"] = Processor.process_get_grid_shape + self._processMap["get_grid_spacing"] = Processor.process_get_grid_spacing + self._processMap["get_grid_origin"] = Processor.process_get_grid_origin + self._processMap["get_grid_x"] = Processor.process_get_grid_x + self._processMap["get_grid_y"] = Processor.process_get_grid_y + self._processMap["get_grid_z"] = Processor.process_get_grid_z + self._processMap[ + "get_grid_connectivity" + ] = Processor.process_get_grid_connectivity + self._processMap["get_grid_offset"] = Processor.process_get_grid_offset + self._processMap["initialize_config"] = Processor.process_initialize_config + self._processMap["initialize_model"] = Processor.process_initialize_model + self._processMap["set_start_time"] = Processor.process_set_start_time + self._processMap["set_end_time"] = Processor.process_set_end_time + self._processMap["get_attribute_names"] = Processor.process_get_attribute_names + self._processMap["get_attribute_value"] = Processor.process_get_attribute_value + self._processMap["set_attribute_value"] = Processor.process_set_attribute_value + self._processMap["save_state"] = Processor.process_save_state + self._processMap["load_state"] = Processor.process_load_state - def process(self, iprot, oprot): - (name, type, seqid) = iprot.readMessageBegin() - if name not in self._processMap: - iprot.skip(TType.STRUCT) - iprot.readMessageEnd() - x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name)) - oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) - x.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() - return - else: - self._processMap[name](self, seqid, iprot, oprot) - return True + def process(self, iprot, oprot): + (name, type, seqid) = iprot.readMessageBegin() + if name not in self._processMap: + iprot.skip(TType.STRUCT) + iprot.readMessageEnd() + x = TApplicationException( + TApplicationException.UNKNOWN_METHOD, "Unknown function %s" % (name) + ) + oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) + x.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() + return + else: + self._processMap[name](self, seqid, iprot, oprot) + return True - def process_initialize(self, seqid, iprot, oprot): - args = initialize_args() - args.read(iprot) - iprot.readMessageEnd() - result = initialize_result() - try: - self._handler.initialize(args.file) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("initialize", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_initialize(self, seqid, iprot, oprot): + args = initialize_args() + args.read(iprot) + iprot.readMessageEnd() + result = initialize_result() + try: + self._handler.initialize(args.file) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("initialize", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_update(self, seqid, iprot, oprot): - args = update_args() - args.read(iprot) - iprot.readMessageEnd() - result = update_result() - try: - self._handler.update() - except ModelException as error: - result.error = error - oprot.writeMessageBegin("update", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_update(self, seqid, iprot, oprot): + args = update_args() + args.read(iprot) + iprot.readMessageEnd() + result = update_result() + try: + self._handler.update() + except ModelException as error: + result.error = error + oprot.writeMessageBegin("update", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_update_until(self, seqid, iprot, oprot): - args = update_until_args() - args.read(iprot) - iprot.readMessageEnd() - result = update_until_result() - try: - self._handler.update_until(args.time) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("update_until", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_update_until(self, seqid, iprot, oprot): + args = update_until_args() + args.read(iprot) + iprot.readMessageEnd() + result = update_until_result() + try: + self._handler.update_until(args.time) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("update_until", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_update_frac(self, seqid, iprot, oprot): - args = update_frac_args() - args.read(iprot) - iprot.readMessageEnd() - result = update_frac_result() - try: - self._handler.update_frac(args.frac) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("update_frac", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_update_frac(self, seqid, iprot, oprot): + args = update_frac_args() + args.read(iprot) + iprot.readMessageEnd() + result = update_frac_result() + try: + self._handler.update_frac(args.frac) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("update_frac", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_finalize_model(self, seqid, iprot, oprot): - args = finalize_model_args() - args.read(iprot) - iprot.readMessageEnd() - result = finalize_model_result() - try: - self._handler.finalize_model() - except ModelException as error: - result.error = error - oprot.writeMessageBegin("finalize_model", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_finalize_model(self, seqid, iprot, oprot): + args = finalize_model_args() + args.read(iprot) + iprot.readMessageEnd() + result = finalize_model_result() + try: + self._handler.finalize_model() + except ModelException as error: + result.error = error + oprot.writeMessageBegin("finalize_model", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_component_name(self, seqid, iprot, oprot): - args = get_component_name_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_component_name_result() - try: - result.success = self._handler.get_component_name() - except ModelException as error: - result.error = error - oprot.writeMessageBegin("get_component_name", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_component_name(self, seqid, iprot, oprot): + args = get_component_name_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_component_name_result() + try: + result.success = self._handler.get_component_name() + except ModelException as error: + result.error = error + oprot.writeMessageBegin("get_component_name", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_input_var_names(self, seqid, iprot, oprot): - args = get_input_var_names_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_input_var_names_result() - result.success = self._handler.get_input_var_names() - oprot.writeMessageBegin("get_input_var_names", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_input_var_names(self, seqid, iprot, oprot): + args = get_input_var_names_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_input_var_names_result() + result.success = self._handler.get_input_var_names() + oprot.writeMessageBegin("get_input_var_names", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_output_var_names(self, seqid, iprot, oprot): - args = get_output_var_names_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_output_var_names_result() - result.success = self._handler.get_output_var_names() - oprot.writeMessageBegin("get_output_var_names", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_output_var_names(self, seqid, iprot, oprot): + args = get_output_var_names_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_output_var_names_result() + result.success = self._handler.get_output_var_names() + oprot.writeMessageBegin("get_output_var_names", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_var_type(self, seqid, iprot, oprot): - args = get_var_type_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_var_type_result() - result.success = self._handler.get_var_type(args.long_var_name) - oprot.writeMessageBegin("get_var_type", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_var_type(self, seqid, iprot, oprot): + args = get_var_type_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_var_type_result() + result.success = self._handler.get_var_type(args.long_var_name) + oprot.writeMessageBegin("get_var_type", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_var_units(self, seqid, iprot, oprot): - args = get_var_units_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_var_units_result() - result.success = self._handler.get_var_units(args.long_var_name) - oprot.writeMessageBegin("get_var_units", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_var_units(self, seqid, iprot, oprot): + args = get_var_units_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_var_units_result() + result.success = self._handler.get_var_units(args.long_var_name) + oprot.writeMessageBegin("get_var_units", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_var_rank(self, seqid, iprot, oprot): - args = get_var_rank_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_var_rank_result() - result.success = self._handler.get_var_rank(args.long_var_name) - oprot.writeMessageBegin("get_var_rank", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_var_rank(self, seqid, iprot, oprot): + args = get_var_rank_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_var_rank_result() + result.success = self._handler.get_var_rank(args.long_var_name) + oprot.writeMessageBegin("get_var_rank", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_var_size(self, seqid, iprot, oprot): - args = get_var_size_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_var_size_result() - result.success = self._handler.get_var_size(args.long_var_name) - oprot.writeMessageBegin("get_var_size", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_var_size(self, seqid, iprot, oprot): + args = get_var_size_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_var_size_result() + result.success = self._handler.get_var_size(args.long_var_name) + oprot.writeMessageBegin("get_var_size", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_var_nbytes(self, seqid, iprot, oprot): - args = get_var_nbytes_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_var_nbytes_result() - result.success = self._handler.get_var_nbytes(args.long_var_name) - oprot.writeMessageBegin("get_var_nbytes", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_var_nbytes(self, seqid, iprot, oprot): + args = get_var_nbytes_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_var_nbytes_result() + result.success = self._handler.get_var_nbytes(args.long_var_name) + oprot.writeMessageBegin("get_var_nbytes", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_start_time(self, seqid, iprot, oprot): - args = get_start_time_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_start_time_result() - result.success = self._handler.get_start_time() - oprot.writeMessageBegin("get_start_time", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_start_time(self, seqid, iprot, oprot): + args = get_start_time_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_start_time_result() + result.success = self._handler.get_start_time() + oprot.writeMessageBegin("get_start_time", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_current_time(self, seqid, iprot, oprot): - args = get_current_time_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_current_time_result() - result.success = self._handler.get_current_time() - oprot.writeMessageBegin("get_current_time", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_current_time(self, seqid, iprot, oprot): + args = get_current_time_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_current_time_result() + result.success = self._handler.get_current_time() + oprot.writeMessageBegin("get_current_time", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_end_time(self, seqid, iprot, oprot): - args = get_end_time_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_end_time_result() - result.success = self._handler.get_end_time() - oprot.writeMessageBegin("get_end_time", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_end_time(self, seqid, iprot, oprot): + args = get_end_time_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_end_time_result() + result.success = self._handler.get_end_time() + oprot.writeMessageBegin("get_end_time", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_time_step(self, seqid, iprot, oprot): - args = get_time_step_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_time_step_result() - result.success = self._handler.get_time_step() - oprot.writeMessageBegin("get_time_step", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_time_step(self, seqid, iprot, oprot): + args = get_time_step_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_time_step_result() + result.success = self._handler.get_time_step() + oprot.writeMessageBegin("get_time_step", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_time_units(self, seqid, iprot, oprot): - args = get_time_units_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_time_units_result() - result.success = self._handler.get_time_units() - oprot.writeMessageBegin("get_time_units", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_time_units(self, seqid, iprot, oprot): + args = get_time_units_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_time_units_result() + result.success = self._handler.get_time_units() + oprot.writeMessageBegin("get_time_units", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_value(self, seqid, iprot, oprot): - args = get_value_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_value_result() - try: - result.success = self._handler.get_value(args.long_var_name) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("get_value", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_value(self, seqid, iprot, oprot): + args = get_value_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_value_result() + try: + result.success = self._handler.get_value(args.long_var_name) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("get_value", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_value_at_indices(self, seqid, iprot, oprot): - args = get_value_at_indices_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_value_at_indices_result() - try: - result.success = self._handler.get_value_at_indices(args.long_var_name, args.inds) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("get_value_at_indices", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_value_at_indices(self, seqid, iprot, oprot): + args = get_value_at_indices_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_value_at_indices_result() + try: + result.success = self._handler.get_value_at_indices( + args.long_var_name, args.inds + ) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("get_value_at_indices", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_set_value(self, seqid, iprot, oprot): - args = set_value_args() - args.read(iprot) - iprot.readMessageEnd() - result = set_value_result() - try: - self._handler.set_value(args.long_var_name, args.src) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("set_value", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_set_value(self, seqid, iprot, oprot): + args = set_value_args() + args.read(iprot) + iprot.readMessageEnd() + result = set_value_result() + try: + self._handler.set_value(args.long_var_name, args.src) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("set_value", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_set_value_at_indices(self, seqid, iprot, oprot): - args = set_value_at_indices_args() - args.read(iprot) - iprot.readMessageEnd() - result = set_value_at_indices_result() - try: - self._handler.set_value_at_indices(args.long_var_name, args.inds, args.src) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("set_value_at_indices", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_set_value_at_indices(self, seqid, iprot, oprot): + args = set_value_at_indices_args() + args.read(iprot) + iprot.readMessageEnd() + result = set_value_at_indices_result() + try: + self._handler.set_value_at_indices(args.long_var_name, args.inds, args.src) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("set_value_at_indices", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_grid_type(self, seqid, iprot, oprot): - args = get_grid_type_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_grid_type_result() - try: - result.success = self._handler.get_grid_type(args.long_var_name) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("get_grid_type", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_grid_type(self, seqid, iprot, oprot): + args = get_grid_type_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_grid_type_result() + try: + result.success = self._handler.get_grid_type(args.long_var_name) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("get_grid_type", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_grid_shape(self, seqid, iprot, oprot): - args = get_grid_shape_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_grid_shape_result() - result.success = self._handler.get_grid_shape(args.long_var_name) - oprot.writeMessageBegin("get_grid_shape", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_grid_shape(self, seqid, iprot, oprot): + args = get_grid_shape_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_grid_shape_result() + result.success = self._handler.get_grid_shape(args.long_var_name) + oprot.writeMessageBegin("get_grid_shape", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_grid_spacing(self, seqid, iprot, oprot): - args = get_grid_spacing_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_grid_spacing_result() - result.success = self._handler.get_grid_spacing(args.long_var_name) - oprot.writeMessageBegin("get_grid_spacing", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_grid_spacing(self, seqid, iprot, oprot): + args = get_grid_spacing_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_grid_spacing_result() + result.success = self._handler.get_grid_spacing(args.long_var_name) + oprot.writeMessageBegin("get_grid_spacing", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_grid_origin(self, seqid, iprot, oprot): - args = get_grid_origin_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_grid_origin_result() - result.success = self._handler.get_grid_origin(args.long_var_name) - oprot.writeMessageBegin("get_grid_origin", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_grid_origin(self, seqid, iprot, oprot): + args = get_grid_origin_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_grid_origin_result() + result.success = self._handler.get_grid_origin(args.long_var_name) + oprot.writeMessageBegin("get_grid_origin", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_grid_x(self, seqid, iprot, oprot): - args = get_grid_x_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_grid_x_result() - result.success = self._handler.get_grid_x(args.long_var_name) - oprot.writeMessageBegin("get_grid_x", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_grid_x(self, seqid, iprot, oprot): + args = get_grid_x_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_grid_x_result() + result.success = self._handler.get_grid_x(args.long_var_name) + oprot.writeMessageBegin("get_grid_x", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_grid_y(self, seqid, iprot, oprot): - args = get_grid_y_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_grid_y_result() - result.success = self._handler.get_grid_y(args.long_var_name) - oprot.writeMessageBegin("get_grid_y", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_grid_y(self, seqid, iprot, oprot): + args = get_grid_y_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_grid_y_result() + result.success = self._handler.get_grid_y(args.long_var_name) + oprot.writeMessageBegin("get_grid_y", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_grid_z(self, seqid, iprot, oprot): - args = get_grid_z_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_grid_z_result() - result.success = self._handler.get_grid_z(args.long_var_name) - oprot.writeMessageBegin("get_grid_z", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_grid_z(self, seqid, iprot, oprot): + args = get_grid_z_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_grid_z_result() + result.success = self._handler.get_grid_z(args.long_var_name) + oprot.writeMessageBegin("get_grid_z", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_grid_connectivity(self, seqid, iprot, oprot): - args = get_grid_connectivity_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_grid_connectivity_result() - result.success = self._handler.get_grid_connectivity(args.long_var_name) - oprot.writeMessageBegin("get_grid_connectivity", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_grid_connectivity(self, seqid, iprot, oprot): + args = get_grid_connectivity_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_grid_connectivity_result() + result.success = self._handler.get_grid_connectivity(args.long_var_name) + oprot.writeMessageBegin("get_grid_connectivity", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_grid_offset(self, seqid, iprot, oprot): - args = get_grid_offset_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_grid_offset_result() - result.success = self._handler.get_grid_offset(args.long_var_name) - oprot.writeMessageBegin("get_grid_offset", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_grid_offset(self, seqid, iprot, oprot): + args = get_grid_offset_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_grid_offset_result() + result.success = self._handler.get_grid_offset(args.long_var_name) + oprot.writeMessageBegin("get_grid_offset", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_initialize_config(self, seqid, iprot, oprot): - args = initialize_config_args() - args.read(iprot) - iprot.readMessageEnd() - result = initialize_config_result() - try: - self._handler.initialize_config(args.file) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("initialize_config", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_initialize_config(self, seqid, iprot, oprot): + args = initialize_config_args() + args.read(iprot) + iprot.readMessageEnd() + result = initialize_config_result() + try: + self._handler.initialize_config(args.file) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("initialize_config", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_initialize_model(self, seqid, iprot, oprot): - args = initialize_model_args() - args.read(iprot) - iprot.readMessageEnd() - result = initialize_model_result() - try: - self._handler.initialize_model() - except ModelException as error: - result.error = error - oprot.writeMessageBegin("initialize_model", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_initialize_model(self, seqid, iprot, oprot): + args = initialize_model_args() + args.read(iprot) + iprot.readMessageEnd() + result = initialize_model_result() + try: + self._handler.initialize_model() + except ModelException as error: + result.error = error + oprot.writeMessageBegin("initialize_model", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_set_start_time(self, seqid, iprot, oprot): - args = set_start_time_args() - args.read(iprot) - iprot.readMessageEnd() - result = set_start_time_result() - try: - self._handler.set_start_time(args.start_time) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("set_start_time", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_set_start_time(self, seqid, iprot, oprot): + args = set_start_time_args() + args.read(iprot) + iprot.readMessageEnd() + result = set_start_time_result() + try: + self._handler.set_start_time(args.start_time) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("set_start_time", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_set_end_time(self, seqid, iprot, oprot): - args = set_end_time_args() - args.read(iprot) - iprot.readMessageEnd() - result = set_end_time_result() - try: - self._handler.set_end_time(args.end_time) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("set_end_time", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_set_end_time(self, seqid, iprot, oprot): + args = set_end_time_args() + args.read(iprot) + iprot.readMessageEnd() + result = set_end_time_result() + try: + self._handler.set_end_time(args.end_time) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("set_end_time", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_attribute_names(self, seqid, iprot, oprot): - args = get_attribute_names_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_attribute_names_result() - result.success = self._handler.get_attribute_names() - oprot.writeMessageBegin("get_attribute_names", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_attribute_names(self, seqid, iprot, oprot): + args = get_attribute_names_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_attribute_names_result() + result.success = self._handler.get_attribute_names() + oprot.writeMessageBegin("get_attribute_names", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_get_attribute_value(self, seqid, iprot, oprot): - args = get_attribute_value_args() - args.read(iprot) - iprot.readMessageEnd() - result = get_attribute_value_result() - try: - result.success = self._handler.get_attribute_value(args.attribute_name) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("get_attribute_value", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_get_attribute_value(self, seqid, iprot, oprot): + args = get_attribute_value_args() + args.read(iprot) + iprot.readMessageEnd() + result = get_attribute_value_result() + try: + result.success = self._handler.get_attribute_value(args.attribute_name) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("get_attribute_value", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_set_attribute_value(self, seqid, iprot, oprot): - args = set_attribute_value_args() - args.read(iprot) - iprot.readMessageEnd() - result = set_attribute_value_result() - try: - self._handler.set_attribute_value(args.attribute_name, args.attribute_value) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("set_attribute_value", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_set_attribute_value(self, seqid, iprot, oprot): + args = set_attribute_value_args() + args.read(iprot) + iprot.readMessageEnd() + result = set_attribute_value_result() + try: + self._handler.set_attribute_value(args.attribute_name, args.attribute_value) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("set_attribute_value", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_save_state(self, seqid, iprot, oprot): - args = save_state_args() - args.read(iprot) - iprot.readMessageEnd() - result = save_state_result() - try: - self._handler.save_state(args.destination_directory) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("save_state", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_save_state(self, seqid, iprot, oprot): + args = save_state_args() + args.read(iprot) + iprot.readMessageEnd() + result = save_state_result() + try: + self._handler.save_state(args.destination_directory) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("save_state", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() - def process_load_state(self, seqid, iprot, oprot): - args = load_state_args() - args.read(iprot) - iprot.readMessageEnd() - result = load_state_result() - try: - self._handler.load_state(args.source_directory) - except ModelException as error: - result.error = error - oprot.writeMessageBegin("load_state", TMessageType.REPLY, seqid) - result.write(oprot) - oprot.writeMessageEnd() - oprot.trans.flush() + def process_load_state(self, seqid, iprot, oprot): + args = load_state_args() + args.read(iprot) + iprot.readMessageEnd() + result = load_state_result() + try: + self._handler.load_state(args.source_directory) + except ModelException as error: + result.error = error + oprot.writeMessageBegin("load_state", TMessageType.REPLY, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() # HELPER FUNCTIONS AND STRUCTURES + class initialize_args(object): - """ + """ Attributes: - file """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'file', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "file", None, None)) # 0 # 1 - def __init__(self, file=None,): - self.file = file + def __init__(self, file=None): + self.file = file - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.file = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.file = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('initialize_args') - if self.file is not None: - oprot.writeFieldBegin('file', TType.STRING, 1) - oprot.writeString(self.file) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("initialize_args") + if self.file is not None: + oprot.writeFieldBegin("file", TType.STRING, 1) + oprot.writeString(self.file) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class initialize_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('initialize_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("initialize_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class update_args(object): - thrift_spec = ( - ) + thrift_spec = () - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('update_args') - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("update_args") + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class update_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('update_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("update_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class update_until_args(object): - """ + """ Attributes: - time """ - thrift_spec = ( - None, # 0 - (1, TType.DOUBLE, 'time', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.DOUBLE, "time", None, None)) # 0 # 1 - def __init__(self, time=None,): - self.time = time + def __init__(self, time=None): + self.time = time - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.DOUBLE: - self.time = iprot.readDouble(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.DOUBLE: + self.time = iprot.readDouble() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('update_until_args') - if self.time is not None: - oprot.writeFieldBegin('time', TType.DOUBLE, 1) - oprot.writeDouble(self.time) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("update_until_args") + if self.time is not None: + oprot.writeFieldBegin("time", TType.DOUBLE, 1) + oprot.writeDouble(self.time) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class update_until_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('update_until_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("update_until_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class update_frac_args(object): - """ + """ Attributes: - frac """ - thrift_spec = ( - None, # 0 - (1, TType.DOUBLE, 'frac', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.DOUBLE, "frac", None, None)) # 0 # 1 - def __init__(self, frac=None,): - self.frac = frac + def __init__(self, frac=None): + self.frac = frac - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.DOUBLE: - self.frac = iprot.readDouble(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.DOUBLE: + self.frac = iprot.readDouble() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('update_frac_args') - if self.frac is not None: - oprot.writeFieldBegin('frac', TType.DOUBLE, 1) - oprot.writeDouble(self.frac) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("update_frac_args") + if self.frac is not None: + oprot.writeFieldBegin("frac", TType.DOUBLE, 1) + oprot.writeDouble(self.frac) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class update_frac_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('update_frac_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("update_frac_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class finalize_model_args(object): - thrift_spec = ( - ) + thrift_spec = () - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('finalize_model_args') - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("finalize_model_args") + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class finalize_model_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('finalize_model_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("finalize_model_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_component_name_args(object): - thrift_spec = ( - ) + thrift_spec = () - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_component_name_args') - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_component_name_args") + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_component_name_result(object): - """ + """ Attributes: - success - error """ - thrift_spec = ( - (0, TType.STRING, 'success', None, None, ), # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + (0, TType.STRING, "success", None, None), # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, success=None, error=None,): - self.success = success - self.error = error + def __init__(self, success=None, error=None): + self.success = success + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.STRING: - self.success = iprot.readString(); - else: - iprot.skip(ftype) - elif fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.STRING: + self.success = iprot.readString() + else: + iprot.skip(ftype) + elif fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_component_name_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.STRING, 0) - oprot.writeString(self.success) - oprot.writeFieldEnd() - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_component_name_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.STRING, 0) + oprot.writeString(self.success) + oprot.writeFieldEnd() + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_input_var_names_args(object): - thrift_spec = ( - ) + thrift_spec = () - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_input_var_names_args') - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_input_var_names_args") + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_input_var_names_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.LIST, 'success', (TType.STRING,None), None, ), # 0 - ) + thrift_spec = ((0, TType.LIST, "success", (TType.STRING, None), None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.LIST: - self.success = [] - (_etype3, _size0) = iprot.readListBegin() - for _i4 in xrange(_size0): - _elem5 = iprot.readString(); - self.success.append(_elem5) - iprot.readListEnd() - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.LIST: + self.success = [] + (_etype3, _size0) = iprot.readListBegin() + for _i4 in xrange(_size0): + _elem5 = iprot.readString() + self.success.append(_elem5) + iprot.readListEnd() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_input_var_names_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.LIST, 0) - oprot.writeListBegin(TType.STRING, len(self.success)) - for iter6 in self.success: - oprot.writeString(iter6) - oprot.writeListEnd() - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_input_var_names_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.LIST, 0) + oprot.writeListBegin(TType.STRING, len(self.success)) + for iter6 in self.success: + oprot.writeString(iter6) + oprot.writeListEnd() + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_output_var_names_args(object): - thrift_spec = ( - ) + thrift_spec = () - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_output_var_names_args') - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_output_var_names_args") + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_output_var_names_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.LIST, 'success', (TType.STRING,None), None, ), # 0 - ) + thrift_spec = ((0, TType.LIST, "success", (TType.STRING, None), None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.LIST: - self.success = [] - (_etype10, _size7) = iprot.readListBegin() - for _i11 in xrange(_size7): - _elem12 = iprot.readString(); - self.success.append(_elem12) - iprot.readListEnd() - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.LIST: + self.success = [] + (_etype10, _size7) = iprot.readListBegin() + for _i11 in xrange(_size7): + _elem12 = iprot.readString() + self.success.append(_elem12) + iprot.readListEnd() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_output_var_names_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.LIST, 0) - oprot.writeListBegin(TType.STRING, len(self.success)) - for iter13 in self.success: - oprot.writeString(iter13) - oprot.writeListEnd() - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_output_var_names_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.LIST, 0) + oprot.writeListBegin(TType.STRING, len(self.success)) + for iter13 in self.success: + oprot.writeString(iter13) + oprot.writeListEnd() + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_var_type_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_var_type_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_var_type_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_var_type_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.STRING, 'success', None, None, ), # 0 - ) + thrift_spec = ((0, TType.STRING, "success", None, None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.STRING: - self.success = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.STRING: + self.success = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_var_type_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.STRING, 0) - oprot.writeString(self.success) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_var_type_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.STRING, 0) + oprot.writeString(self.success) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_var_units_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_var_units_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_var_units_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_var_units_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.STRING, 'success', None, None, ), # 0 - ) + thrift_spec = ((0, TType.STRING, "success", None, None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.STRING: - self.success = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.STRING: + self.success = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_var_units_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.STRING, 0) - oprot.writeString(self.success) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_var_units_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.STRING, 0) + oprot.writeString(self.success) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_var_rank_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_var_rank_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_var_rank_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_var_rank_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.I32, 'success', None, None, ), # 0 - ) + thrift_spec = ((0, TType.I32, "success", None, None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.I32: - self.success = iprot.readI32(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.I32: + self.success = iprot.readI32() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_var_rank_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.I32, 0) - oprot.writeI32(self.success) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_var_rank_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.I32, 0) + oprot.writeI32(self.success) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_var_size_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_var_size_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_var_size_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_var_size_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.I32, 'success', None, None, ), # 0 - ) + thrift_spec = ((0, TType.I32, "success", None, None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.I32: - self.success = iprot.readI32(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.I32: + self.success = iprot.readI32() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_var_size_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.I32, 0) - oprot.writeI32(self.success) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_var_size_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.I32, 0) + oprot.writeI32(self.success) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_var_nbytes_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_var_nbytes_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_var_nbytes_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_var_nbytes_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.I32, 'success', None, None, ), # 0 - ) + thrift_spec = ((0, TType.I32, "success", None, None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.I32: - self.success = iprot.readI32(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.I32: + self.success = iprot.readI32() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_var_nbytes_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.I32, 0) - oprot.writeI32(self.success) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_var_nbytes_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.I32, 0) + oprot.writeI32(self.success) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_start_time_args(object): - thrift_spec = ( - ) + thrift_spec = () - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_start_time_args') - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_start_time_args") + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_start_time_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.DOUBLE, 'success', None, None, ), # 0 - ) + thrift_spec = ((0, TType.DOUBLE, "success", None, None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.DOUBLE: - self.success = iprot.readDouble(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.DOUBLE: + self.success = iprot.readDouble() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_start_time_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.DOUBLE, 0) - oprot.writeDouble(self.success) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_start_time_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.DOUBLE, 0) + oprot.writeDouble(self.success) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_current_time_args(object): - thrift_spec = ( - ) + thrift_spec = () - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_current_time_args') - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_current_time_args") + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_current_time_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.DOUBLE, 'success', None, None, ), # 0 - ) + thrift_spec = ((0, TType.DOUBLE, "success", None, None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.DOUBLE: - self.success = iprot.readDouble(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.DOUBLE: + self.success = iprot.readDouble() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_current_time_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.DOUBLE, 0) - oprot.writeDouble(self.success) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_current_time_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.DOUBLE, 0) + oprot.writeDouble(self.success) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_end_time_args(object): - thrift_spec = ( - ) + thrift_spec = () - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_end_time_args') - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_end_time_args") + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_end_time_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.DOUBLE, 'success', None, None, ), # 0 - ) + thrift_spec = ((0, TType.DOUBLE, "success", None, None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.DOUBLE: - self.success = iprot.readDouble(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.DOUBLE: + self.success = iprot.readDouble() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_end_time_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.DOUBLE, 0) - oprot.writeDouble(self.success) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_end_time_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.DOUBLE, 0) + oprot.writeDouble(self.success) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_time_step_args(object): - thrift_spec = ( - ) + thrift_spec = () - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_time_step_args') - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_time_step_args") + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_time_step_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.DOUBLE, 'success', None, None, ), # 0 - ) + thrift_spec = ((0, TType.DOUBLE, "success", None, None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.DOUBLE: - self.success = iprot.readDouble(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.DOUBLE: + self.success = iprot.readDouble() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_time_step_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.DOUBLE, 0) - oprot.writeDouble(self.success) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_time_step_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.DOUBLE, 0) + oprot.writeDouble(self.success) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_time_units_args(object): - thrift_spec = ( - ) + thrift_spec = () - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_time_units_args') - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_time_units_args") + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_time_units_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.STRING, 'success', None, None, ), # 0 - ) + thrift_spec = ((0, TType.STRING, "success", None, None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.STRING: - self.success = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.STRING: + self.success = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_time_units_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.STRING, 0) - oprot.writeString(self.success) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_time_units_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.STRING, 0) + oprot.writeString(self.success) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_value_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_value_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_value_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_value_result(object): - """ + """ Attributes: - success - error """ - thrift_spec = ( - (0, TType.STRING, 'success', None, None, ), # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + (0, TType.STRING, "success", None, None), # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, success=None, error=None,): - self.success = success - self.error = error + def __init__(self, success=None, error=None): + self.success = success + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.STRING: - self.success = iprot.readString(); - else: - iprot.skip(ftype) - elif fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.STRING: + self.success = iprot.readString() + else: + iprot.skip(ftype) + elif fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_value_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.STRING, 0) - oprot.writeString(self.success) - oprot.writeFieldEnd() - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_value_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.STRING, 0) + oprot.writeString(self.success) + oprot.writeFieldEnd() + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_value_at_indices_args(object): - """ + """ Attributes: - long_var_name - inds """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - (2, TType.LIST, 'inds', (TType.I32,None), None, ), # 2 - ) + thrift_spec = ( + None, # 0 + (1, TType.STRING, "long_var_name", None, None), # 1 + (2, TType.LIST, "inds", (TType.I32, None), None), # 2 + ) - def __init__(self, long_var_name=None, inds=None,): - self.long_var_name = long_var_name - self.inds = inds + def __init__(self, long_var_name=None, inds=None): + self.long_var_name = long_var_name + self.inds = inds - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - elif fid == 2: - if ftype == TType.LIST: - self.inds = [] - (_etype17, _size14) = iprot.readListBegin() - for _i18 in xrange(_size14): - _elem19 = iprot.readI32(); - self.inds.append(_elem19) - iprot.readListEnd() - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + elif fid == 2: + if ftype == TType.LIST: + self.inds = [] + (_etype17, _size14) = iprot.readListBegin() + for _i18 in xrange(_size14): + _elem19 = iprot.readI32() + self.inds.append(_elem19) + iprot.readListEnd() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_value_at_indices_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - if self.inds is not None: - oprot.writeFieldBegin('inds', TType.LIST, 2) - oprot.writeListBegin(TType.I32, len(self.inds)) - for iter20 in self.inds: - oprot.writeI32(iter20) - oprot.writeListEnd() - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_value_at_indices_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + if self.inds is not None: + oprot.writeFieldBegin("inds", TType.LIST, 2) + oprot.writeListBegin(TType.I32, len(self.inds)) + for iter20 in self.inds: + oprot.writeI32(iter20) + oprot.writeListEnd() + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_value_at_indices_result(object): - """ + """ Attributes: - success - error """ - thrift_spec = ( - (0, TType.STRING, 'success', None, None, ), # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + (0, TType.STRING, "success", None, None), # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, success=None, error=None,): - self.success = success - self.error = error + def __init__(self, success=None, error=None): + self.success = success + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.STRING: - self.success = iprot.readString(); - else: - iprot.skip(ftype) - elif fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.STRING: + self.success = iprot.readString() + else: + iprot.skip(ftype) + elif fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_value_at_indices_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.STRING, 0) - oprot.writeString(self.success) - oprot.writeFieldEnd() - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_value_at_indices_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.STRING, 0) + oprot.writeString(self.success) + oprot.writeFieldEnd() + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class set_value_args(object): - """ + """ Attributes: - long_var_name - src """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - (2, TType.STRING, 'src', None, None, ), # 2 - ) + thrift_spec = ( + None, # 0 + (1, TType.STRING, "long_var_name", None, None), # 1 + (2, TType.STRING, "src", None, None), # 2 + ) - def __init__(self, long_var_name=None, src=None,): - self.long_var_name = long_var_name - self.src = src + def __init__(self, long_var_name=None, src=None): + self.long_var_name = long_var_name + self.src = src - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - elif fid == 2: - if ftype == TType.STRING: - self.src = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + elif fid == 2: + if ftype == TType.STRING: + self.src = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('set_value_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - if self.src is not None: - oprot.writeFieldBegin('src', TType.STRING, 2) - oprot.writeString(self.src) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("set_value_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + if self.src is not None: + oprot.writeFieldBegin("src", TType.STRING, 2) + oprot.writeString(self.src) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class set_value_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('set_value_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("set_value_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class set_value_at_indices_args(object): - """ + """ Attributes: - long_var_name - inds - src """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - (2, TType.LIST, 'inds', (TType.I32,None), None, ), # 2 - (3, TType.STRING, 'src', None, None, ), # 3 - ) + thrift_spec = ( + None, # 0 + (1, TType.STRING, "long_var_name", None, None), # 1 + (2, TType.LIST, "inds", (TType.I32, None), None), # 2 + (3, TType.STRING, "src", None, None), # 3 + ) - def __init__(self, long_var_name=None, inds=None, src=None,): - self.long_var_name = long_var_name - self.inds = inds - self.src = src + def __init__(self, long_var_name=None, inds=None, src=None): + self.long_var_name = long_var_name + self.inds = inds + self.src = src - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - elif fid == 2: - if ftype == TType.LIST: - self.inds = [] - (_etype24, _size21) = iprot.readListBegin() - for _i25 in xrange(_size21): - _elem26 = iprot.readI32(); - self.inds.append(_elem26) - iprot.readListEnd() - else: - iprot.skip(ftype) - elif fid == 3: - if ftype == TType.STRING: - self.src = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + elif fid == 2: + if ftype == TType.LIST: + self.inds = [] + (_etype24, _size21) = iprot.readListBegin() + for _i25 in xrange(_size21): + _elem26 = iprot.readI32() + self.inds.append(_elem26) + iprot.readListEnd() + else: + iprot.skip(ftype) + elif fid == 3: + if ftype == TType.STRING: + self.src = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('set_value_at_indices_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - if self.inds is not None: - oprot.writeFieldBegin('inds', TType.LIST, 2) - oprot.writeListBegin(TType.I32, len(self.inds)) - for iter27 in self.inds: - oprot.writeI32(iter27) - oprot.writeListEnd() - oprot.writeFieldEnd() - if self.src is not None: - oprot.writeFieldBegin('src', TType.STRING, 3) - oprot.writeString(self.src) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("set_value_at_indices_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + if self.inds is not None: + oprot.writeFieldBegin("inds", TType.LIST, 2) + oprot.writeListBegin(TType.I32, len(self.inds)) + for iter27 in self.inds: + oprot.writeI32(iter27) + oprot.writeListEnd() + oprot.writeFieldEnd() + if self.src is not None: + oprot.writeFieldBegin("src", TType.STRING, 3) + oprot.writeString(self.src) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class set_value_at_indices_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('set_value_at_indices_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("set_value_at_indices_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_type_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_type_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_type_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_type_result(object): - """ + """ Attributes: - success - error """ - thrift_spec = ( - (0, TType.I32, 'success', None, None, ), # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + (0, TType.I32, "success", None, None), # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, success=None, error=None,): - self.success = success - self.error = error + def __init__(self, success=None, error=None): + self.success = success + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.I32: - self.success = iprot.readI32(); - else: - iprot.skip(ftype) - elif fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.I32: + self.success = iprot.readI32() + else: + iprot.skip(ftype) + elif fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_type_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.I32, 0) - oprot.writeI32(self.success) - oprot.writeFieldEnd() - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_type_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.I32, 0) + oprot.writeI32(self.success) + oprot.writeFieldEnd() + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_shape_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_shape_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_shape_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_shape_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.LIST, 'success', (TType.I32,None), None, ), # 0 - ) + thrift_spec = ((0, TType.LIST, "success", (TType.I32, None), None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.LIST: - self.success = [] - (_etype31, _size28) = iprot.readListBegin() - for _i32 in xrange(_size28): - _elem33 = iprot.readI32(); - self.success.append(_elem33) - iprot.readListEnd() - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.LIST: + self.success = [] + (_etype31, _size28) = iprot.readListBegin() + for _i32 in xrange(_size28): + _elem33 = iprot.readI32() + self.success.append(_elem33) + iprot.readListEnd() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_shape_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.LIST, 0) - oprot.writeListBegin(TType.I32, len(self.success)) - for iter34 in self.success: - oprot.writeI32(iter34) - oprot.writeListEnd() - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_shape_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.LIST, 0) + oprot.writeListBegin(TType.I32, len(self.success)) + for iter34 in self.success: + oprot.writeI32(iter34) + oprot.writeListEnd() + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_spacing_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_spacing_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_spacing_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_spacing_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.LIST, 'success', (TType.DOUBLE,None), None, ), # 0 - ) + thrift_spec = ((0, TType.LIST, "success", (TType.DOUBLE, None), None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.LIST: - self.success = [] - (_etype38, _size35) = iprot.readListBegin() - for _i39 in xrange(_size35): - _elem40 = iprot.readDouble(); - self.success.append(_elem40) - iprot.readListEnd() - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.LIST: + self.success = [] + (_etype38, _size35) = iprot.readListBegin() + for _i39 in xrange(_size35): + _elem40 = iprot.readDouble() + self.success.append(_elem40) + iprot.readListEnd() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_spacing_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.LIST, 0) - oprot.writeListBegin(TType.DOUBLE, len(self.success)) - for iter41 in self.success: - oprot.writeDouble(iter41) - oprot.writeListEnd() - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_spacing_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.LIST, 0) + oprot.writeListBegin(TType.DOUBLE, len(self.success)) + for iter41 in self.success: + oprot.writeDouble(iter41) + oprot.writeListEnd() + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_origin_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_origin_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_origin_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_origin_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.LIST, 'success', (TType.DOUBLE,None), None, ), # 0 - ) + thrift_spec = ((0, TType.LIST, "success", (TType.DOUBLE, None), None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.LIST: - self.success = [] - (_etype45, _size42) = iprot.readListBegin() - for _i46 in xrange(_size42): - _elem47 = iprot.readDouble(); - self.success.append(_elem47) - iprot.readListEnd() - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.LIST: + self.success = [] + (_etype45, _size42) = iprot.readListBegin() + for _i46 in xrange(_size42): + _elem47 = iprot.readDouble() + self.success.append(_elem47) + iprot.readListEnd() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_origin_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.LIST, 0) - oprot.writeListBegin(TType.DOUBLE, len(self.success)) - for iter48 in self.success: - oprot.writeDouble(iter48) - oprot.writeListEnd() - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_origin_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.LIST, 0) + oprot.writeListBegin(TType.DOUBLE, len(self.success)) + for iter48 in self.success: + oprot.writeDouble(iter48) + oprot.writeListEnd() + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_x_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_x_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_x_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_x_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.LIST, 'success', (TType.DOUBLE,None), None, ), # 0 - ) + thrift_spec = ((0, TType.LIST, "success", (TType.DOUBLE, None), None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.LIST: - self.success = [] - (_etype52, _size49) = iprot.readListBegin() - for _i53 in xrange(_size49): - _elem54 = iprot.readDouble(); - self.success.append(_elem54) - iprot.readListEnd() - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.LIST: + self.success = [] + (_etype52, _size49) = iprot.readListBegin() + for _i53 in xrange(_size49): + _elem54 = iprot.readDouble() + self.success.append(_elem54) + iprot.readListEnd() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_x_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.LIST, 0) - oprot.writeListBegin(TType.DOUBLE, len(self.success)) - for iter55 in self.success: - oprot.writeDouble(iter55) - oprot.writeListEnd() - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_x_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.LIST, 0) + oprot.writeListBegin(TType.DOUBLE, len(self.success)) + for iter55 in self.success: + oprot.writeDouble(iter55) + oprot.writeListEnd() + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_y_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_y_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_y_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_y_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.LIST, 'success', (TType.DOUBLE,None), None, ), # 0 - ) + thrift_spec = ((0, TType.LIST, "success", (TType.DOUBLE, None), None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.LIST: - self.success = [] - (_etype59, _size56) = iprot.readListBegin() - for _i60 in xrange(_size56): - _elem61 = iprot.readDouble(); - self.success.append(_elem61) - iprot.readListEnd() - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.LIST: + self.success = [] + (_etype59, _size56) = iprot.readListBegin() + for _i60 in xrange(_size56): + _elem61 = iprot.readDouble() + self.success.append(_elem61) + iprot.readListEnd() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_y_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.LIST, 0) - oprot.writeListBegin(TType.DOUBLE, len(self.success)) - for iter62 in self.success: - oprot.writeDouble(iter62) - oprot.writeListEnd() - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_y_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.LIST, 0) + oprot.writeListBegin(TType.DOUBLE, len(self.success)) + for iter62 in self.success: + oprot.writeDouble(iter62) + oprot.writeListEnd() + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_z_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_z_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_z_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_z_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.LIST, 'success', (TType.DOUBLE,None), None, ), # 0 - ) + thrift_spec = ((0, TType.LIST, "success", (TType.DOUBLE, None), None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.LIST: - self.success = [] - (_etype66, _size63) = iprot.readListBegin() - for _i67 in xrange(_size63): - _elem68 = iprot.readDouble(); - self.success.append(_elem68) - iprot.readListEnd() - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.LIST: + self.success = [] + (_etype66, _size63) = iprot.readListBegin() + for _i67 in xrange(_size63): + _elem68 = iprot.readDouble() + self.success.append(_elem68) + iprot.readListEnd() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_z_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.LIST, 0) - oprot.writeListBegin(TType.DOUBLE, len(self.success)) - for iter69 in self.success: - oprot.writeDouble(iter69) - oprot.writeListEnd() - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_z_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.LIST, 0) + oprot.writeListBegin(TType.DOUBLE, len(self.success)) + for iter69 in self.success: + oprot.writeDouble(iter69) + oprot.writeListEnd() + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_connectivity_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_connectivity_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_connectivity_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_connectivity_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.LIST, 'success', (TType.I32,None), None, ), # 0 - ) + thrift_spec = ((0, TType.LIST, "success", (TType.I32, None), None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.LIST: - self.success = [] - (_etype73, _size70) = iprot.readListBegin() - for _i74 in xrange(_size70): - _elem75 = iprot.readI32(); - self.success.append(_elem75) - iprot.readListEnd() - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.LIST: + self.success = [] + (_etype73, _size70) = iprot.readListBegin() + for _i74 in xrange(_size70): + _elem75 = iprot.readI32() + self.success.append(_elem75) + iprot.readListEnd() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_connectivity_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.LIST, 0) - oprot.writeListBegin(TType.I32, len(self.success)) - for iter76 in self.success: - oprot.writeI32(iter76) - oprot.writeListEnd() - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_connectivity_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.LIST, 0) + oprot.writeListBegin(TType.I32, len(self.success)) + for iter76 in self.success: + oprot.writeI32(iter76) + oprot.writeListEnd() + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_offset_args(object): - """ + """ Attributes: - long_var_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'long_var_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "long_var_name", None, None)) # 0 # 1 - def __init__(self, long_var_name=None,): - self.long_var_name = long_var_name + def __init__(self, long_var_name=None): + self.long_var_name = long_var_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.long_var_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.long_var_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_offset_args') - if self.long_var_name is not None: - oprot.writeFieldBegin('long_var_name', TType.STRING, 1) - oprot.writeString(self.long_var_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_offset_args") + if self.long_var_name is not None: + oprot.writeFieldBegin("long_var_name", TType.STRING, 1) + oprot.writeString(self.long_var_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_grid_offset_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.LIST, 'success', (TType.I32,None), None, ), # 0 - ) + thrift_spec = ((0, TType.LIST, "success", (TType.I32, None), None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.LIST: - self.success = [] - (_etype80, _size77) = iprot.readListBegin() - for _i81 in xrange(_size77): - _elem82 = iprot.readI32(); - self.success.append(_elem82) - iprot.readListEnd() - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.LIST: + self.success = [] + (_etype80, _size77) = iprot.readListBegin() + for _i81 in xrange(_size77): + _elem82 = iprot.readI32() + self.success.append(_elem82) + iprot.readListEnd() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_grid_offset_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.LIST, 0) - oprot.writeListBegin(TType.I32, len(self.success)) - for iter83 in self.success: - oprot.writeI32(iter83) - oprot.writeListEnd() - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_grid_offset_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.LIST, 0) + oprot.writeListBegin(TType.I32, len(self.success)) + for iter83 in self.success: + oprot.writeI32(iter83) + oprot.writeListEnd() + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class initialize_config_args(object): - """ + """ Attributes: - file """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'file', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "file", None, None)) # 0 # 1 - def __init__(self, file=None,): - self.file = file + def __init__(self, file=None): + self.file = file - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.file = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.file = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('initialize_config_args') - if self.file is not None: - oprot.writeFieldBegin('file', TType.STRING, 1) - oprot.writeString(self.file) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("initialize_config_args") + if self.file is not None: + oprot.writeFieldBegin("file", TType.STRING, 1) + oprot.writeString(self.file) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class initialize_config_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('initialize_config_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("initialize_config_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class initialize_model_args(object): - thrift_spec = ( - ) + thrift_spec = () - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('initialize_model_args') - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("initialize_model_args") + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class initialize_model_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('initialize_model_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("initialize_model_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class set_start_time_args(object): - """ + """ Attributes: - start_time """ - thrift_spec = ( - None, # 0 - (1, TType.DOUBLE, 'start_time', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.DOUBLE, "start_time", None, None)) # 0 # 1 - def __init__(self, start_time=None,): - self.start_time = start_time + def __init__(self, start_time=None): + self.start_time = start_time - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.DOUBLE: - self.start_time = iprot.readDouble(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.DOUBLE: + self.start_time = iprot.readDouble() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('set_start_time_args') - if self.start_time is not None: - oprot.writeFieldBegin('start_time', TType.DOUBLE, 1) - oprot.writeDouble(self.start_time) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("set_start_time_args") + if self.start_time is not None: + oprot.writeFieldBegin("start_time", TType.DOUBLE, 1) + oprot.writeDouble(self.start_time) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class set_start_time_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('set_start_time_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("set_start_time_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class set_end_time_args(object): - """ + """ Attributes: - end_time """ - thrift_spec = ( - None, # 0 - (1, TType.DOUBLE, 'end_time', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.DOUBLE, "end_time", None, None)) # 0 # 1 - def __init__(self, end_time=None,): - self.end_time = end_time + def __init__(self, end_time=None): + self.end_time = end_time - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.DOUBLE: - self.end_time = iprot.readDouble(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.DOUBLE: + self.end_time = iprot.readDouble() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('set_end_time_args') - if self.end_time is not None: - oprot.writeFieldBegin('end_time', TType.DOUBLE, 1) - oprot.writeDouble(self.end_time) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("set_end_time_args") + if self.end_time is not None: + oprot.writeFieldBegin("end_time", TType.DOUBLE, 1) + oprot.writeDouble(self.end_time) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class set_end_time_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('set_end_time_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("set_end_time_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_attribute_names_args(object): - thrift_spec = ( - ) + thrift_spec = () - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_attribute_names_args') - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_attribute_names_args") + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_attribute_names_result(object): - """ + """ Attributes: - success """ - thrift_spec = ( - (0, TType.LIST, 'success', (TType.STRING,None), None, ), # 0 - ) + thrift_spec = ((0, TType.LIST, "success", (TType.STRING, None), None),) # 0 - def __init__(self, success=None,): - self.success = success + def __init__(self, success=None): + self.success = success - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.LIST: - self.success = [] - (_etype87, _size84) = iprot.readListBegin() - for _i88 in xrange(_size84): - _elem89 = iprot.readString(); - self.success.append(_elem89) - iprot.readListEnd() - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.LIST: + self.success = [] + (_etype87, _size84) = iprot.readListBegin() + for _i88 in xrange(_size84): + _elem89 = iprot.readString() + self.success.append(_elem89) + iprot.readListEnd() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_attribute_names_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.LIST, 0) - oprot.writeListBegin(TType.STRING, len(self.success)) - for iter90 in self.success: - oprot.writeString(iter90) - oprot.writeListEnd() - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_attribute_names_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.LIST, 0) + oprot.writeListBegin(TType.STRING, len(self.success)) + for iter90 in self.success: + oprot.writeString(iter90) + oprot.writeListEnd() + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_attribute_value_args(object): - """ + """ Attributes: - attribute_name """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'attribute_name', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "attribute_name", None, None)) # 0 # 1 - def __init__(self, attribute_name=None,): - self.attribute_name = attribute_name + def __init__(self, attribute_name=None): + self.attribute_name = attribute_name - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.attribute_name = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.attribute_name = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_attribute_value_args') - if self.attribute_name is not None: - oprot.writeFieldBegin('attribute_name', TType.STRING, 1) - oprot.writeString(self.attribute_name) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_attribute_value_args") + if self.attribute_name is not None: + oprot.writeFieldBegin("attribute_name", TType.STRING, 1) + oprot.writeString(self.attribute_name) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class get_attribute_value_result(object): - """ + """ Attributes: - success - error """ - thrift_spec = ( - (0, TType.STRING, 'success', None, None, ), # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + (0, TType.STRING, "success", None, None), # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, success=None, error=None,): - self.success = success - self.error = error + def __init__(self, success=None, error=None): + self.success = success + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 0: - if ftype == TType.STRING: - self.success = iprot.readString(); - else: - iprot.skip(ftype) - elif fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.STRING: + self.success = iprot.readString() + else: + iprot.skip(ftype) + elif fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('get_attribute_value_result') - if self.success is not None: - oprot.writeFieldBegin('success', TType.STRING, 0) - oprot.writeString(self.success) - oprot.writeFieldEnd() - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("get_attribute_value_result") + if self.success is not None: + oprot.writeFieldBegin("success", TType.STRING, 0) + oprot.writeString(self.success) + oprot.writeFieldEnd() + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class set_attribute_value_args(object): - """ + """ Attributes: - attribute_name - attribute_value """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'attribute_name', None, None, ), # 1 - (2, TType.STRING, 'attribute_value', None, None, ), # 2 - ) + thrift_spec = ( + None, # 0 + (1, TType.STRING, "attribute_name", None, None), # 1 + (2, TType.STRING, "attribute_value", None, None), # 2 + ) - def __init__(self, attribute_name=None, attribute_value=None,): - self.attribute_name = attribute_name - self.attribute_value = attribute_value + def __init__(self, attribute_name=None, attribute_value=None): + self.attribute_name = attribute_name + self.attribute_value = attribute_value - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.attribute_name = iprot.readString(); - else: - iprot.skip(ftype) - elif fid == 2: - if ftype == TType.STRING: - self.attribute_value = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.attribute_name = iprot.readString() + else: + iprot.skip(ftype) + elif fid == 2: + if ftype == TType.STRING: + self.attribute_value = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('set_attribute_value_args') - if self.attribute_name is not None: - oprot.writeFieldBegin('attribute_name', TType.STRING, 1) - oprot.writeString(self.attribute_name) - oprot.writeFieldEnd() - if self.attribute_value is not None: - oprot.writeFieldBegin('attribute_value', TType.STRING, 2) - oprot.writeString(self.attribute_value) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("set_attribute_value_args") + if self.attribute_name is not None: + oprot.writeFieldBegin("attribute_name", TType.STRING, 1) + oprot.writeString(self.attribute_name) + oprot.writeFieldEnd() + if self.attribute_value is not None: + oprot.writeFieldBegin("attribute_value", TType.STRING, 2) + oprot.writeString(self.attribute_value) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class set_attribute_value_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('set_attribute_value_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("set_attribute_value_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class save_state_args(object): - """ + """ Attributes: - destination_directory """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'destination_directory', None, None, ), # 1 - ) + thrift_spec = ( + None, # 0 + (1, TType.STRING, "destination_directory", None, None), # 1 + ) - def __init__(self, destination_directory=None,): - self.destination_directory = destination_directory + def __init__(self, destination_directory=None): + self.destination_directory = destination_directory - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.destination_directory = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.destination_directory = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('save_state_args') - if self.destination_directory is not None: - oprot.writeFieldBegin('destination_directory', TType.STRING, 1) - oprot.writeString(self.destination_directory) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("save_state_args") + if self.destination_directory is not None: + oprot.writeFieldBegin("destination_directory", TType.STRING, 1) + oprot.writeString(self.destination_directory) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class save_state_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('save_state_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("save_state_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class load_state_args(object): - """ + """ Attributes: - source_directory """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'source_directory', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "source_directory", None, None)) # 0 # 1 - def __init__(self, source_directory=None,): - self.source_directory = source_directory + def __init__(self, source_directory=None): + self.source_directory = source_directory - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.source_directory = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.source_directory = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('load_state_args') - if self.source_directory is not None: - oprot.writeFieldBegin('source_directory', TType.STRING, 1) - oprot.writeString(self.source_directory) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("load_state_args") + if self.source_directory is not None: + oprot.writeFieldBegin("source_directory", TType.STRING, 1) + oprot.writeString(self.source_directory) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + def __ne__(self, other): + return not (self == other) - def __ne__(self, other): - return not (self == other) class load_state_result(object): - """ + """ Attributes: - error """ - thrift_spec = ( - None, # 0 - (1, TType.STRUCT, 'error', (ModelException, ModelException.thrift_spec), None, ), # 1 - ) + thrift_spec = ( + None, # 0 + ( + 1, + TType.STRUCT, + "error", + (ModelException, ModelException.thrift_spec), + None, + ), # 1 + ) - def __init__(self, error=None,): - self.error = error + def __init__(self, error=None): + self.error = error - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRUCT: - self.error = ModelException() - self.error.read(iprot) - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRUCT: + self.error = ModelException() + self.error.read(iprot) + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('load_state_result') - if self.error is not None: - oprot.writeFieldBegin('error', TType.STRUCT, 1) - self.error.write(oprot) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("load_state_result") + if self.error is not None: + oprot.writeFieldBegin("error", TType.STRUCT, 1) + self.error.write(oprot) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - return + def validate(self): + return + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - - def __ne__(self, other): - return not (self == other) + def __ne__(self, other): + return not (self == other) Index: wflow-py/openda_bmi/openda/bmi/thrift/__init__.py =================================================================== diff -u -rcef24d27dba76b014028787be46dd9ae3a2c30b6 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/openda_bmi/openda/bmi/thrift/__init__.py (.../__init__.py) (revision cef24d27dba76b014028787be46dd9ae3a2c30b6) +++ wflow-py/openda_bmi/openda/bmi/thrift/__init__.py (.../__init__.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1 +1 @@ -__all__ = ['ttypes', 'constants', 'BMIService'] +__all__ = ["ttypes", "constants", "BMIService"] Index: wflow-py/openda_bmi/openda/bmi/thrift/constants.py =================================================================== diff -u -rcef24d27dba76b014028787be46dd9ae3a2c30b6 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/openda_bmi/openda/bmi/thrift/constants.py (.../constants.py) (revision cef24d27dba76b014028787be46dd9ae3a2c30b6) +++ wflow-py/openda_bmi/openda/bmi/thrift/constants.py (.../constants.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -8,4 +8,3 @@ from thrift.Thrift import TType, TMessageType, TException, TApplicationException from ttypes import * - Index: wflow-py/openda_bmi/openda/bmi/thrift/ttypes.py =================================================================== diff -u -rcef24d27dba76b014028787be46dd9ae3a2c30b6 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/openda_bmi/openda/bmi/thrift/ttypes.py (.../ttypes.py) (revision cef24d27dba76b014028787be46dd9ae3a2c30b6) +++ wflow-py/openda_bmi/openda/bmi/thrift/ttypes.py (.../ttypes.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -10,97 +10,108 @@ from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol, TProtocol + try: - from thrift.protocol import fastbinary + from thrift.protocol import fastbinary except: - fastbinary = None + fastbinary = None class BmiGridType(object): - UNKNOWN = 0 - UNIFORM = 1 - RECTILINEAR = 2 - STRUCTURED = 3 - UNSTRUCTURED = 4 + UNKNOWN = 0 + UNIFORM = 1 + RECTILINEAR = 2 + STRUCTURED = 3 + UNSTRUCTURED = 4 - _VALUES_TO_NAMES = { - 0: "UNKNOWN", - 1: "UNIFORM", - 2: "RECTILINEAR", - 3: "STRUCTURED", - 4: "UNSTRUCTURED", - } + _VALUES_TO_NAMES = { + 0: "UNKNOWN", + 1: "UNIFORM", + 2: "RECTILINEAR", + 3: "STRUCTURED", + 4: "UNSTRUCTURED", + } - _NAMES_TO_VALUES = { - "UNKNOWN": 0, - "UNIFORM": 1, - "RECTILINEAR": 2, - "STRUCTURED": 3, - "UNSTRUCTURED": 4, - } + _NAMES_TO_VALUES = { + "UNKNOWN": 0, + "UNIFORM": 1, + "RECTILINEAR": 2, + "STRUCTURED": 3, + "UNSTRUCTURED": 4, + } class ModelException(TException): - """ + """ Attributes: - message """ - thrift_spec = ( - None, # 0 - (1, TType.STRING, 'message', None, None, ), # 1 - ) + thrift_spec = (None, (1, TType.STRING, "message", None, None)) # 0 # 1 - def __init__(self, message=None,): - self.message = message + def __init__(self, message=None): + self.message = message - def read(self, iprot): - if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: - fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) - return - iprot.readStructBegin() - while True: - (fname, ftype, fid) = iprot.readFieldBegin() - if ftype == TType.STOP: - break - if fid == 1: - if ftype == TType.STRING: - self.message = iprot.readString(); - else: - iprot.skip(ftype) - else: - iprot.skip(ftype) - iprot.readFieldEnd() - iprot.readStructEnd() + def read(self, iprot): + if ( + iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and isinstance(iprot.trans, TTransport.CReadableTransport) + and self.thrift_spec is not None + and fastbinary is not None + ): + fastbinary.decode_binary( + self, iprot.trans, (self.__class__, self.thrift_spec) + ) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.message = iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() - def write(self, oprot): - if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: - oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) - return - oprot.writeStructBegin('ModelException') - if self.message is not None: - oprot.writeFieldBegin('message', TType.STRING, 1) - oprot.writeString(self.message) - oprot.writeFieldEnd() - oprot.writeFieldStop() - oprot.writeStructEnd() + def write(self, oprot): + if ( + oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated + and self.thrift_spec is not None + and fastbinary is not None + ): + oprot.trans.write( + fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)) + ) + return + oprot.writeStructBegin("ModelException") + if self.message is not None: + oprot.writeFieldBegin("message", TType.STRING, 1) + oprot.writeString(self.message) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() - def validate(self): - if self.message is None: - raise TProtocol.TProtocolException(message='Required field message is unset!') - return + def validate(self): + if self.message is None: + raise TProtocol.TProtocolException( + message="Required field message is unset!" + ) + return + def __str__(self): + return repr(self) - def __str__(self): - return repr(self) + def __repr__(self): + L = ["%s=%r" % (key, value) for key, value in self.__dict__.iteritems()] + return "%s(%s)" % (self.__class__.__name__, ", ".join(L)) - def __repr__(self): - L = ['%s=%r' % (key, value) - for key, value in self.__dict__.iteritems()] - return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - def __eq__(self, other): - return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ - - def __ne__(self, other): - return not (self == other) + def __ne__(self, other): + return not (self == other) Index: wflow-py/openda_bmi/opendapy.py =================================================================== diff -u -r18f6d7bdbb7643aa86db300fcfb7c074eea1c324 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/openda_bmi/opendapy.py (.../opendapy.py) (revision 18f6d7bdbb7643aa86db300fcfb7c074eea1c324) +++ wflow-py/openda_bmi/opendapy.py (.../opendapy.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,11 +1,10 @@ -''' +""" Created on Jul 8, 2014 @author: niels -''' +""" - from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol @@ -23,63 +22,62 @@ logger = logging.getLogger(__name__) -class ModelHandler(Iface): +class ModelHandler(Iface): def __init__(self, model): self.model = model def initialize(self, config_file): if config_file is None or config_file == "": config_file = None - + try: model.initialize(config_file) except Exception as e: - raise ModelException(str(e)) - + raise ModelException(str(e)) + def update(self): try: model.update() except Exception as e: - raise ModelException(str(e)) - + raise ModelException(str(e)) + def update_until(self, time): try: model.update_until(time) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) - def update_frac(self, frac): try: model.update_frac(frac) except Exception as e: - raise ModelException(str(e)) - + raise ModelException(str(e)) + def finalize_model(self): try: model.finalize() except Exception as e: - raise ModelException(str(e)) - + raise ModelException(str(e)) + def get_component_name(self): try: return model.get_component_name() except Exception as e: - raise ModelException(str(e)) - + raise ModelException(str(e)) + def get_input_var_names(self): try: return model.get_input_var_names() except Exception as e: raise ModelException(str(e)) - + def get_output_var_names(self): try: return model.get_output_var_names() except Exception as e: raise ModelException(str(e)) - + def get_var_type(self, long_var_name): """ Get type of a variable, as a numpy dtype value string @@ -88,31 +86,31 @@ return model.get_var_type(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_var_units(self, long_var_name): try: return model.get_var_units(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_var_rank(self, long_var_name): try: return model.get_var_rank(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_var_size(self, long_var_name): try: return model.get_var_size(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_var_nbytes(self, long_var_name): try: return model.get_var_nbytes(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_start_time(self): try: return model.get_start_time() @@ -124,61 +122,63 @@ return model.get_current_time() except Exception as e: raise ModelException(str(e)) - + def get_end_time(self): try: return model.get_end_time() except Exception as e: raise ModelException(str(e)) - + def get_time_step(self): try: return model.get_time_step() except Exception as e: raise ModelException(str(e)) - + def get_time_units(self): try: return model.get_time_units() except Exception as e: raise ModelException(str(e)) - + def get_value(self, long_var_name): try: return model.get_value(long_var_name).flatten().tostring() except Exception as e: raise ModelException(str(e)) - + def get_value_at_indices(self, long_var_name, inds): try: return model.get_value_at_indices(long_var_name, inds).tostring() except Exception as e: raise ModelException(str(e)) - + def set_value(self, long_var_name, src): try: logger.info("received %s bytes", len(src)) - + vartype = model.get_var_type(long_var_name) varshape = model.get_grid_shape(long_var_name) - + logger.info("var type, shape %s, %s", str(vartype), str(varshape)) - + flatarray = np.fromstring(src, dtype=np.dtype(vartype)) - + logger.info("flat array now shaped %s", str(flatarray.shape)) - + value = np.reshape(flatarray, varshape) - + model.set_value(long_var_name, value) except Exception as e: raise ModelException(str(e)) - + def set_value_at_indices(self, long_var_name, inds, src): try: vartype = model.get_var_type(long_var_name) - - model.set_value_at_indices(long_var_name, inds, np.fromstring(src, dtype=vartype)) + + model.set_value_at_indices( + long_var_name, inds, np.fromstring(src, dtype=vartype) + ) except Exception as e: raise ModelException(str(e)) @@ -187,7 +187,7 @@ return model.get_grid_type(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_grid_shape(self, long_var_name): try: return model.get_grid_shape(long_var_name) @@ -205,31 +205,31 @@ return model.get_grid_origin(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_grid_x(self, long_var_name): try: return model.get_grid_x(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_grid_y(self, long_var_name): try: return model.get_grid_y(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_grid_z(self, long_var_name): try: return model.get_grid_z(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_grid_connectivity(self, long_var_name): try: return model.get_grid_connectivity(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_grid_offset(self, long_var_name): try: return model.get_grid_offset(long_var_name) @@ -241,94 +241,95 @@ def initialize_config(self, config_file): if config_file is None or config_file == "": config_file = None - + try: model.initialize_config(config_file) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def initialize_model(self): try: model.initialize_model() except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def set_start_time(self, start_time): try: model.set_start_time(start_time) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def set_end_time(self, end_time): try: model.set_end_time(end_time) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def get_attribute_names(self): try: return model.get_attribute_names() except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def get_attribute_value(self, attribute_name): try: return model.get_attribute_value(attribute_name) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def set_attribute_value(self, attribute_name, attribute_value): try: model.set_attribute_value(attribute_name, attribute_value) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def save_state(self, destination_directory): try: model.save_state(destination_directory) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def load_state(self, source_directory): try: model.load_state(source_directory) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) - + def handleSIGINT(sig, frame): - #clean up state or what ever is necessary + # clean up state or what ever is necessary sys.exit(0) -if __name__ == '__main__': - #setup root logger to catch any warnings and errors. Most models will override and/or add to these settings. +if __name__ == "__main__": + + # setup root logger to catch any warnings and errors. Most models will override and/or add to these settings. logging.basicConfig(level=logging.WARNING) - + model_module_name = sys.argv[3] model_class_name = sys.argv[4] - + model_module = importlib.import_module(model_module_name) model_class = getattr(model_module, model_class_name) - + model = model_class() - + handler = ModelHandler(model) processor = Processor(handler) - - transport = TSocket.TServerSocket(host=sys.argv[5],port=sys.argv[6]) + transport = TSocket.TServerSocket(host=sys.argv[5], port=sys.argv[6]) + tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() - + server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) - + signal.signal(signal.SIGINT, handleSIGINT) - + logger.info(server) logger.info("serving") - + server.serve() - + logger.info("done") Index: wflow-py/openda_bmi/thrift_bmi_raster_server.py =================================================================== diff -u -re6e17cee83b8147c1be514bbe4c6bdc16bd9719b -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/openda_bmi/thrift_bmi_raster_server.py (.../thrift_bmi_raster_server.py) (revision e6e17cee83b8147c1be514bbe4c6bdc16bd9719b) +++ wflow-py/openda_bmi/thrift_bmi_raster_server.py (.../thrift_bmi_raster_server.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,11 +1,10 @@ -''' +""" Created on Jul 8, 2014 @author: niels -''' +""" - from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol @@ -23,63 +22,62 @@ logger = logging.getLogger(__name__) -class ModelHandler(Iface): +class ModelHandler(Iface): def __init__(self, model): self.model = model def initialize(self, config_file): if config_file is None or config_file == "": config_file = None - + try: model.initialize(config_file) except Exception as e: - raise ModelException(str(e)) - + raise ModelException(str(e)) + def update(self): try: model.update() except Exception as e: - raise ModelException(str(e)) - + raise ModelException(str(e)) + def update_until(self, time): try: model.update_until(time) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) - def update_frac(self, frac): try: model.update_frac(frac) except Exception as e: - raise ModelException(str(e)) - + raise ModelException(str(e)) + def finalize_model(self): try: model.finalize() except Exception as e: - raise ModelException(str(e)) - + raise ModelException(str(e)) + def get_component_name(self): try: return model.get_component_name() except Exception as e: - raise ModelException(str(e)) - + raise ModelException(str(e)) + def get_input_var_names(self): try: return model.get_input_var_names() except Exception as e: raise ModelException(str(e)) - + def get_output_var_names(self): try: return model.get_output_var_names() except Exception as e: raise ModelException(str(e)) - + def get_var_type(self, long_var_name): """ Get type of a variable, as a numpy dtype value string @@ -88,31 +86,31 @@ return model.get_var_type(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_var_units(self, long_var_name): try: return model.get_var_units(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_var_rank(self, long_var_name): try: return model.get_var_rank(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_var_size(self, long_var_name): try: return model.get_var_size(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_var_nbytes(self, long_var_name): try: return model.get_var_nbytes(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_start_time(self): try: return model.get_start_time() @@ -124,61 +122,63 @@ return model.get_current_time() except Exception as e: raise ModelException(str(e)) - + def get_end_time(self): try: return model.get_end_time() except Exception as e: raise ModelException(str(e)) - + def get_time_step(self): try: return model.get_time_step() except Exception as e: raise ModelException(str(e)) - + def get_time_units(self): try: return model.get_time_units() except Exception as e: raise ModelException(str(e)) - + def get_value(self, long_var_name): try: return model.get_value(long_var_name).flatten().tostring() except Exception as e: raise ModelException(str(e)) - + def get_value_at_indices(self, long_var_name, inds): try: return model.get_value_at_indices(long_var_name, inds).tostring() except Exception as e: raise ModelException(str(e)) - + def set_value(self, long_var_name, src): try: logger.info("received %s bytes", len(src)) - + vartype = model.get_var_type(long_var_name) varshape = model.get_grid_shape(long_var_name) - + logger.info("var type, shape %s, %s", str(vartype), str(varshape)) - + flatarray = np.fromstring(src, dtype=np.dtype(vartype)) - + logger.info("flat array now shaped %s", str(flatarray.shape)) - + value = np.reshape(flatarray, varshape) - + model.set_value(long_var_name, value) except Exception as e: raise ModelException(str(e)) - + def set_value_at_indices(self, long_var_name, inds, src): try: vartype = model.get_var_type(long_var_name) - - model.set_value_at_indices(long_var_name, inds, np.fromstring(src, dtype=vartype)) + + model.set_value_at_indices( + long_var_name, inds, np.fromstring(src, dtype=vartype) + ) except Exception as e: raise ModelException(str(e)) @@ -187,7 +187,7 @@ return model.get_grid_type(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_grid_shape(self, long_var_name): try: return model.get_grid_shape(long_var_name) @@ -205,31 +205,31 @@ return model.get_grid_origin(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_grid_x(self, long_var_name): try: return model.get_grid_x(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_grid_y(self, long_var_name): try: return model.get_grid_y(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_grid_z(self, long_var_name): try: return model.get_grid_z(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_grid_connectivity(self, long_var_name): try: return model.get_grid_connectivity(long_var_name) except Exception as e: raise ModelException(str(e)) - + def get_grid_offset(self, long_var_name): try: return model.get_grid_offset(long_var_name) @@ -241,94 +241,95 @@ def initialize_config(self, config_file): if config_file is None or config_file == "": config_file = None - + try: model.initialize_config(config_file) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def initialize_model(self): try: model.initialize_model() except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def set_start_time(self, start_time): try: model.set_start_time(start_time) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def set_end_time(self, end_time): try: model.set_end_time(end_time) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def get_attribute_names(self): try: return model.get_attribute_names() except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def get_attribute_value(self, attribute_name): try: return model.get_attribute_value(attribute_name) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def set_attribute_value(self, attribute_name, attribute_value): try: model.set_attribute_value(attribute_name, attribute_value) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def save_state(self, destination_directory): try: model.save_state(destination_directory) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) def load_state(self, source_directory): try: model.load_state(source_directory) except Exception as e: - raise ModelException(str(e)) + raise ModelException(str(e)) - + def handleSIGINT(sig, frame): - #clean up state or what ever is necessary + # clean up state or what ever is necessary sys.exit(0) -if __name__ == '__main__': - #setup root logger to catch any warnings and errors. Most models will override and/or add to these settings. +if __name__ == "__main__": + + # setup root logger to catch any warnings and errors. Most models will override and/or add to these settings. logging.basicConfig(level=logging.WARNING) - + model_module_name = sys.argv[1] model_class_name = sys.argv[2] - + model_module = importlib.import_module(model_module_name) model_class = getattr(model_module, model_class_name) - + model = model_class() - + handler = ModelHandler(model) processor = Processor(handler) - - transport = TSocket.TServerSocket(host=sys.argv[3],port=sys.argv[4]) + transport = TSocket.TServerSocket(host=sys.argv[3], port=sys.argv[4]) + tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() - + server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) - + signal.signal(signal.SIGINT, handleSIGINT) - + logger.info(server) logger.info("serving") - + server.serve() - + logger.info("done") Index: wflow-py/setup.py =================================================================== diff -u -r5a61603915d87c16ec04d083c314805c86318984 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/setup.py (.../setup.py) (revision 5a61603915d87c16ec04d083c314805c86318984) +++ wflow-py/setup.py (.../setup.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -5,13 +5,13 @@ except ImportError: from distutils.core import setup from setuptools import find_packages + here = os.path.abspath(os.path.dirname(__file__)) -README = open(os.path.join(here, '../README.rst')).read() -TODO = open(os.path.join(here, 'TODO.txt')).read() +README = open(os.path.join(here, "../README.rst")).read() +TODO = open(os.path.join(here, "TODO.txt")).read() - try: import osgeo except: @@ -25,7 +25,9 @@ try: import pcraster except: - print("Could not import pcraster, make sure it is installed including the python extensions") + print( + "Could not import pcraster, make sure it is installed including the python extensions" + ) print("see www.pcraster.eu") try: @@ -44,23 +46,42 @@ print("Could not import versioneer, make sure it is installed") # Source dist -setup(name='wflow',version=versioneer.get_version().split('+')[0], - cmdclass=versioneer.get_cmdclass(), - #version= MVERSION, - packages=['wflow','wflow.pcrglobwb','wflow.sphy','wflow.wrappers.rtc'], - package_dir={'wflow': 'wflow'}, - author='J. Schellekens', - author_email='jaap.schellekens@deltares.nl', - url='http://www.openstreams.nl', - license = "GPL", - zip_safe = False, - scripts=['Scripts/pcr2netcdf.py','Scripts/tss2xml.py','Scripts/wflow_subcatch.py', - 'wflow/wflow_extract.py','wflow/wflow_sceleton.py', - 'wflow/wflow_gr4.py','wflow/plottss.py','wflow/wflow_wave.py', 'wflow/wflow_topoflex.py', - 'wflow/wflow_cqf.py','wflow/wflow_floodmap.py','wflow/wflow_upscale.py', - 'wflow/wflow_fit.py','wflow/wflow_adapt.py','wflow/wflow_delwaq.py', - 'Scripts/wflow_prepare_step1.py','Scripts/wflow_prepare_step2.py', - 'wflow/wflow_sbm.py','wflow/wflow_hbv.py','wflow/wflow_w3ra.py', - 'wflow/wflow_upscale.py','wflow/wflow_routing.py','Scripts/bmi2runner.py'], - description='the wflow hydrological models (part of OpenStreams)', - ) \ No newline at end of file +setup( + name="wflow", + version=versioneer.get_version().split("+")[0], + cmdclass=versioneer.get_cmdclass(), + # version= MVERSION, + packages=["wflow", "wflow.pcrglobwb", "wflow.sphy", "wflow.wrappers.rtc"], + package_dir={"wflow": "wflow"}, + author="J. Schellekens", + author_email="jaap.schellekens@deltares.nl", + url="http://www.openstreams.nl", + license="GPL", + zip_safe=False, + scripts=[ + "Scripts/pcr2netcdf.py", + "Scripts/tss2xml.py", + "Scripts/wflow_subcatch.py", + "wflow/wflow_extract.py", + "wflow/wflow_sceleton.py", + "wflow/wflow_gr4.py", + "wflow/plottss.py", + "wflow/wflow_wave.py", + "wflow/wflow_topoflex.py", + "wflow/wflow_cqf.py", + "wflow/wflow_floodmap.py", + "wflow/wflow_upscale.py", + "wflow/wflow_fit.py", + "wflow/wflow_adapt.py", + "wflow/wflow_delwaq.py", + "Scripts/wflow_prepare_step1.py", + "Scripts/wflow_prepare_step2.py", + "wflow/wflow_sbm.py", + "wflow/wflow_hbv.py", + "wflow/wflow_w3ra.py", + "wflow/wflow_upscale.py", + "wflow/wflow_routing.py", + "Scripts/bmi2runner.py", + ], + description="the wflow hydrological models (part of OpenStreams)", +) Index: wflow-py/versioneer.py =================================================================== diff -u -rc9d975a5a82cb34652cdc5d2ee9afd734c18d3c7 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/versioneer.py (.../versioneer.py) (revision c9d975a5a82cb34652cdc5d2ee9afd734c18d3c7) +++ wflow-py/versioneer.py (.../versioneer.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -277,6 +277,7 @@ """ from __future__ import print_function + try: import configparser except ImportError: @@ -308,11 +309,13 @@ setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") + err = ( + "Versioneer was unable to run the project root directory. " + "Versioneer requires setup.py to be executed from " + "its immediate directory (like 'python setup.py COMMAND'), " + "or in a way that lets it use sys.argv[0] to find the root " + "(like 'python path/to/setup.py COMMAND')." + ) raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools @@ -325,8 +328,10 @@ me_dir = os.path.normcase(os.path.splitext(me)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir: - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(me), versioneer_py)) + print( + "Warning: build in %s is using versioneer.py from %s" + % (os.path.dirname(me), versioneer_py) + ) except NameError: pass return root @@ -348,6 +353,7 @@ if parser.has_option("versioneer", name): return parser.get("versioneer", name) return None + cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = get(parser, "style") or "" @@ -372,28 +378,32 @@ def register_vcs_handler(vcs, method): # decorator """Decorator to mark a method as the handler for a particular VCS.""" + def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f + return decorate -def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, - env=None): +def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git - p = subprocess.Popen([c] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None)) + p = subprocess.Popen( + [c] + args, + cwd=cwd, + env=env, + stdout=subprocess.PIPE, + stderr=(subprocess.PIPE if hide_stderr else None), + ) break except EnvironmentError: e = sys.exc_info()[1] @@ -418,7 +428,9 @@ return stdout, p.returncode -LONG_VERSION_PY['git'] = ''' +LONG_VERSION_PY[ + "git" +] = ''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build @@ -993,7 +1005,7 @@ # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " - tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) + tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d @@ -1002,27 +1014,34 @@ # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = set([r for r in refs if re.search(r"\d", r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] + r = ref[len(tag_prefix) :] if verbose: print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} + return { + "version": r, + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": None, + "date": date, + } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} + return { + "version": "0+unknown", + "full-revisionid": keywords["full"].strip(), + "dirty": False, + "error": "no suitable tags", + "date": None, + } @register_vcs_handler("git", "pieces_from_vcs") @@ -1037,19 +1056,27 @@ if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] - out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=True) + out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty", - "--always", "--long", - "--match", "%s*" % tag_prefix], - cwd=root) + describe_out, rc = run_command( + GITS, + [ + "describe", + "--tags", + "--dirty", + "--always", + "--long", + "--match", + "%s*" % tag_prefix, + ], + cwd=root, + ) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") @@ -1072,17 +1099,16 @@ dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] + git_describe = git_describe[: git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) + pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out return pieces # tag @@ -1091,10 +1117,12 @@ if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) + pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % ( + full_tag, + tag_prefix, + ) return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] + pieces["closest-tag"] = full_tag[len(tag_prefix) :] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) @@ -1105,13 +1133,13 @@ else: # HEX: no tags pieces["closest-tag"] = None - count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], - cwd=root) + count_out, rc = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], - cwd=root)[0].strip() + date = run_command(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[ + 0 + ].strip() pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces @@ -1167,16 +1195,22 @@ for i in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} + return { + "version": dirname[len(parentdir_prefix) :], + "full-revisionid": None, + "dirty": False, + "error": None, + "date": None, + } else: rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) + print( + "Tried directories %s but none started with prefix %s" + % (str(rootdirs), parentdir_prefix) + ) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @@ -1205,11 +1239,13 @@ contents = f.read() except EnvironmentError: raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) + mo = re.search( + r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S + ) if not mo: - mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) + mo = re.search( + r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S + ) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) @@ -1218,8 +1254,7 @@ def write_to_version_file(filename, versions): """Write the given version number to the given _version.py file.""" os.unlink(filename) - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) + contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) @@ -1251,8 +1286,7 @@ rendered += ".dirty" else: # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) + rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered @@ -1366,11 +1400,13 @@ def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} + return { + "version": "unknown", + "full-revisionid": pieces.get("long"), + "dirty": None, + "error": pieces["error"], + "date": None, + } if not style or style == "default": style = "pep440" # the default @@ -1390,9 +1426,13 @@ else: raise ValueError("unknown style '%s'" % style) - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} + return { + "version": rendered, + "full-revisionid": pieces["long"], + "dirty": pieces["dirty"], + "error": None, + "date": pieces.get("date"), + } class VersioneerBadRootError(Exception): @@ -1415,8 +1455,9 @@ handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" + assert ( + cfg.versionfile_source is not None + ), "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) @@ -1470,9 +1511,13 @@ if verbose: print("unable to compute version") - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version", - "date": None} + return { + "version": "0+unknown", + "full-revisionid": None, + "dirty": None, + "error": "unable to compute version", + "date": None, + } def get_version(): @@ -1521,6 +1566,7 @@ print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) + cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools @@ -1553,14 +1599,15 @@ # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) + target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) + cmds["build_py"] = cmd_build_py if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe + # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ @@ -1581,17 +1628,21 @@ os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) + f.write( + LONG + % { + "DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + } + ) + cmds["build_exe"] = cmd_build_exe del cmds["build_py"] - if 'py2exe' in sys.modules: # py2exe enabled? + if "py2exe" in sys.modules: # py2exe enabled? try: from py2exe.distutils_buildexe import py2exe as _py2exe # py3 except ImportError: @@ -1610,13 +1661,17 @@ os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) + f.write( + LONG + % { + "DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + } + ) + cmds["py2exe"] = cmd_py2exe # we override different "sdist" commands for both environments @@ -1643,8 +1698,10 @@ # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) + write_to_version_file( + target_versionfile, self._versioneer_generated_versions + ) + cmds["sdist"] = cmd_sdist return cmds @@ -1699,11 +1756,13 @@ root = get_root() try: cfg = get_config_from_root(root) - except (EnvironmentError, configparser.NoSectionError, - configparser.NoOptionError) as e: + except ( + EnvironmentError, + configparser.NoSectionError, + configparser.NoOptionError, + ) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) + print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) @@ -1712,15 +1771,18 @@ print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) + f.write( + LONG + % { + "DOLLAR": "$", + "STYLE": cfg.style, + "TAG_PREFIX": cfg.tag_prefix, + "PARENTDIR_PREFIX": cfg.parentdir_prefix, + "VERSIONFILE_SOURCE": cfg.versionfile_source, + } + ) - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") + ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: @@ -1762,8 +1824,10 @@ else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: - print(" appending versionfile_source ('%s') to MANIFEST.in" % - cfg.versionfile_source) + print( + " appending versionfile_source ('%s') to MANIFEST.in" + % cfg.versionfile_source + ) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: Index: wflow-py/wflow/JarvisCoefficients.py =================================================================== diff -u -r9cda4f050ab505ec75d1cf9064980e9182f83aca -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/JarvisCoefficients.py (.../JarvisCoefficients.py) (revision 9cda4f050ab505ec75d1cf9064980e9182f83aca) +++ wflow-py/wflow/JarvisCoefficients.py (.../JarvisCoefficients.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -21,89 +21,112 @@ from copy import copy as copylist try: - from wflow.wf_DynamicFramework import * + from wflow.wf_DynamicFramework import * except ImportError: - from wf_DynamicFramework import * + from wf_DynamicFramework import * import scipy -def calcEp(self,k): +def calcEp(self, k): """ REQUIRED INPUT: """ -# resistenceAeroD(self) -# potential_evaporation(self,k) - self.EpDay = ifthenelse(self.Sw_t[k] > 0, self.EpDaySnow2, self.EpDay2) #EpDaySnow added on 18-02-2016 - downscale_evaporation(self,k) - -def calcEpSnow(self,k): + # resistenceAeroD(self) + # potential_evaporation(self,k) + self.EpDay = ifthenelse( + self.Sw_t[k] > 0, self.EpDaySnow2, self.EpDay2 + ) # EpDaySnow added on 18-02-2016 + downscale_evaporation(self, k) + + +def calcEpSnow(self, k): """ REQUIRED INPUT: daily input data """ -# resistenceAeroD(self) -# potential_evaporation(self,k) - self.EpDaySnow = ifthenelse(self.Sw_t[k] > 0, self.EpDaySnow2 * self.lamda / self.lamdaS, self.EpDay2 * self.lamda / self.lamdaS) #EpDaySnow added on 18-02-2016 -# self.EpDaySnow = self.EpDay * self.lamda / self.lamdaS - downscale_evaporation_snow(self,k) + # resistenceAeroD(self) + # potential_evaporation(self,k) + self.EpDaySnow = ifthenelse( + self.Sw_t[k] > 0, + self.EpDaySnow2 * self.lamda / self.lamdaS, + self.EpDay2 * self.lamda / self.lamdaS, + ) # EpDaySnow added on 18-02-2016 + # self.EpDaySnow = self.EpDay * self.lamda / self.lamdaS + downscale_evaporation_snow(self, k) -def calcEpSnowHour(self,k): + +def calcEpSnowHour(self, k): """ REQUIRED INPUT: hourly input data """ -# resistenceAeroD(self) -# potential_evaporation(self,k) - self.EpHour = ifthenelse(self.Sw_t[k] > 0, self.EpDaySnow2 * self.lamda / self.lamdaS, self.EpDay2 * self.lamda / self.lamdaS) #EpDaySnow added on 31-03-2016 - -def calcEu_laiFixed(self,k): + # resistenceAeroD(self) + # potential_evaporation(self,k) + self.EpHour = ifthenelse( + self.Sw_t[k] > 0, + self.EpDaySnow2 * self.lamda / self.lamdaS, + self.EpDay2 * self.lamda / self.lamdaS, + ) # EpDaySnow added on 31-03-2016 + + +def calcEu_laiFixed(self, k): """ REQUIRED INPUT: """ - JC_temperature(self,k) - JC_vapourDeficit(self,k) - JC_LAIeffective(self,k) - JC_solarRadiation(self,k) - JC_soilMoisture(self,k) + JC_temperature(self, k) + JC_vapourDeficit(self, k) + JC_LAIeffective(self, k) + JC_solarRadiation(self, k) + JC_soilMoisture(self, k) resistenceAeroD(self) - resistenceTotal(self,k) -# potential_evaporation(self,k) - downscale_evaporation(self,k) + resistenceTotal(self, k) + # potential_evaporation(self,k) + downscale_evaporation(self, k) self.EupHour = self.EpHour - self.Ei_[k] self.Eu = self.EupHour * self.k - -def calcEu(self,k,n): + + +def calcEu(self, k, n): """ REQUIRED INPUT: n = number of evaporation fluxes above the reservoir to be calculated (to decrease Ep) """ - JC_temperature(self,k) - JC_vapourDeficit(self,k) - JC_solarRadiation(self,k) - JC_soilMoisture(self,k) + JC_temperature(self, k) + JC_vapourDeficit(self, k) + JC_solarRadiation(self, k) + JC_soilMoisture(self, k) resistenceAeroD(self) - resistenceTotal_laiHRU(self,k) - downscale_evaporation(self,k) + resistenceTotal_laiHRU(self, k) + downscale_evaporation(self, k) if n == 1: self.EupHour = self.EpHour - self.Ei_[k] elif n == 2: self.EupHour = self.EpHour - self.Ei_[k] - self.Ea_[k] self.Eu = self.EupHour * self.k -def JC_temperature(self,k): +def JC_temperature(self, k): """ REQUIRED INPUT: - mean daily temperature (K) PARAMETERS: - Topt (optimum temperature for transpiration, based on elevation and latitude (Cui et al, 2012)) """ - self.JC_ToptC = self.JC_Topt - 273.15 # changed on 9/4/2015, before Topt in K - JC_temp1 = ifthenelse(self.Tmean < 273.15, 0, ifthenelse(pcrand(self.Tmean >= self.JC_Topt - 1, self.Tmean <= self.JC_Topt + 1), 1, 1 - self.JC_Topt ** -2 * (self.Tmean - self.JC_Topt) ** 2)) + self.JC_ToptC = self.JC_Topt - 273.15 # changed on 9/4/2015, before Topt in K + JC_temp1 = ifthenelse( + self.Tmean < 273.15, + 0, + ifthenelse( + pcrand(self.Tmean >= self.JC_Topt - 1, self.Tmean <= self.JC_Topt + 1), + 1, + 1 - self.JC_Topt ** -2 * (self.Tmean - self.JC_Topt) ** 2, + ), + ) self.JC_temp = ifthenelse(JC_temp1 < 0, 0, JC_temp1) self.JC_temp_[k] = self.JC_temp -def JC_vapourDeficit(self,k): + +def JC_vapourDeficit(self, k): """ REQUIRED INPUT: - vapour pressure deficit (kPa) @@ -112,37 +135,41 @@ - Cd1 (first vapour pressure parameter, fixed at 3 (Matsumoto et al. 2008)) - Cd2 (second vapour pressure parameter, fixed at 0.1 (Matsumoto et al. 2008)) """ - + denom = 1 + (self.vpd / self.JC_D05[k]) ** self.JC_cd1[k] - JC_vpd1 = (1 / denom) * (1 - self.JC_cd2[k]) + self.JC_cd2[k] - self.JC_vpd = ifthenelse(JC_vpd1 < 0, 0, JC_vpd1) + JC_vpd1 = (1 / denom) * (1 - self.JC_cd2[k]) + self.JC_cd2[k] + self.JC_vpd = ifthenelse(JC_vpd1 < 0, 0, JC_vpd1) self.JC_vpd_[k] = self.JC_vpd - -def JC_LAIeffective(self,k): + + +def JC_LAIeffective(self, k): """ REQUIRED INPUT: - LAI (-) PARAMETERS: - none (Allen et al., 2006 & Zhou et al., 2006) """ - - self.JC_laiEff = self.LAI / (0.2 * self.LAI + 1) - -def JC_solarRadiation(self,k): + self.JC_laiEff = self.LAI / (0.2 * self.LAI + 1) + + +def JC_solarRadiation(self, k): """ REQUIRED INPUT: - incoming short wave radiation (W/m2) PARAMETERS: - Cr (radiation stress parameter, fixed at 100 (Zhou et al. 2006)) - """ - + """ + rad_si_Wm2 = self.rad_si / 86400 - JC_rad1 = rad_si_Wm2 * (1 + self.JC_cr[k]/1000) * (1 / (self.JC_cr[k] + rad_si_Wm2)) - self.JC_rad = ifthenelse(JC_rad1 < 0, 0, JC_rad1) + JC_rad1 = ( + rad_si_Wm2 * (1 + self.JC_cr[k] / 1000) * (1 / (self.JC_cr[k] + rad_si_Wm2)) + ) + self.JC_rad = ifthenelse(JC_rad1 < 0, 0, JC_rad1) self.JC_rad_[k] = self.JC_rad - -def JC_soilMoisture(self,k): + + +def JC_soilMoisture(self, k): """ REQUIRED INPUT: - storage unsaturated zone @@ -151,12 +178,22 @@ - SuFC (level of saturation in soil at field capacity) - SuWP (level of saturation in soil at wilting point) """ - SuN = self.Su[k] / self.sumax[k] - JC_sm1 = ifthenelse(SuN < self.SuWP[k], 0, ifthenelse(SuN > self.SuFC[k], 1,\ - (SuN - self.SuWP[k]) * (self.SuFC[k] - self.SuWP[k] + self.JC_cuz[k]) / ((self.SuFC[k] - self.SuWP[k]) * (SuN - self.SuWP[k] + self.JC_cuz[k])))) + SuN = self.Su[k] / self.sumax[k] + JC_sm1 = ifthenelse( + SuN < self.SuWP[k], + 0, + ifthenelse( + SuN > self.SuFC[k], + 1, + (SuN - self.SuWP[k]) + * (self.SuFC[k] - self.SuWP[k] + self.JC_cuz[k]) + / ((self.SuFC[k] - self.SuWP[k]) * (SuN - self.SuWP[k] + self.JC_cuz[k])), + ), + ) self.JC_sm = ifthenelse(JC_sm1 < 0, 0, JC_sm1) self.JC_sm_[k] = self.JC_sm + def resistenceAeroD(self): """ REQUIRED INPUT: @@ -169,7 +206,8 @@ """ self.aeroRes = 245 / (86400 * (0.54 * self.wind2m + 0.5)) -def resistenceTotal(self,k): + +def resistenceTotal(self, k): """ REQUIRED INPUT: - all Jarvis stress functions @@ -182,12 +220,15 @@ JC_all = self.JC_laiEff * self.JC_rad * self.JC_vpd * self.JC_temp * self.JC_sm stomRes1 = ifthenelse(JC_all == 0, 50000, self.JC_rstmin[k] / JC_all) stomRes2 = ifthenelse(stomRes1 > 50000, 50000, stomRes1) - self.stomRes = stomRes2 / (3600*24) - - self.k = 1 / (1 + self.stomRes * self.gamma / (self.aeroRes * (self.sgamma + self.gamma))) - self.JC_k_[k] = self.k - -def resistenceTotal_laiHRU(self,k): + self.stomRes = stomRes2 / (3600 * 24) + + self.k = 1 / ( + 1 + self.stomRes * self.gamma / (self.aeroRes * (self.sgamma + self.gamma)) + ) + self.JC_k_[k] = self.k + + +def resistenceTotal_laiHRU(self, k): """ REQUIRED INPUT: - all Jarvis stress functions @@ -200,12 +241,15 @@ JC_all = self.JC_rad * self.JC_vpd * self.JC_temp * self.JC_sm stomRes1 = ifthenelse(JC_all == 0, 50000, self.rst_lai[k] / JC_all) stomRes2 = ifthenelse(stomRes1 > 50000, 50000, stomRes1) - self.stomRes = stomRes2 / (3600*24) - - self.k = 1 / (1 + self.stomRes * self.gamma / (self.aeroRes * (self.sgamma + self.gamma))) - self.JC_k_[k] = self.k + self.stomRes = stomRes2 / (3600 * 24) -def potential_evaporation(self,k): + self.k = 1 / ( + 1 + self.stomRes * self.gamma / (self.aeroRes * (self.sgamma + self.gamma)) + ) + self.JC_k_[k] = self.k + + +def potential_evaporation(self, k): """ REQUIRED INPUT: - net radiation @@ -219,13 +263,13 @@ - rhoW (density of water) - lamda (latent heat of vaporisation) """ - nom = self.sgamma * self.Rn + self.rhoA * self.Cp * self.vpd / self.aeroRes + nom = self.sgamma * self.Rn + self.rhoA * self.Cp * self.vpd / self.aeroRes denom = self.rhoW * self.lamda * (self.sgamma + self.gamma) self.EpDay = (nom / denom) * 1000 self.EpD_[k] = self.EpDay - -def downscale_evaporation(self,k): + +def downscale_evaporation(self, k): """ REQUIRED INPUT: daily evaporation (EpDay) @@ -235,21 +279,30 @@ PARAMETERS: - """ - - #teller = numpy.nanmax(pcr2numpy(self.thestep,nan)) - teller = pcr2numpy(self.thestep,nan)[0,0] - x = teller - floor(teller/24) * 24 * scalar(self.catchArea) + + # teller = numpy.nanmax(pcr2numpy(self.thestep,nan)) + teller = pcr2numpy(self.thestep, nan)[0, 0] + x = teller - floor(teller / 24) * 24 * scalar(self.catchArea) DL = self.DE - self.DS + 1 - P = 2 * pi / (2 * DL) # period - SH = DL - 12 #horizontal shift of new signal - aN = -1 * self.EpDay * P # nominator of the amplitude - aDN = sin((P * (self.DE + SH)) * 180 / pi) - sin((P * (self.DS + SH)) * 180 / pi) # denominator of the amplitude - ampl = aN / aDN # amplitude of new signal + P = 2 * pi / (2 * DL) # period + SH = DL - 12 # horizontal shift of new signal + aN = -1 * self.EpDay * P # nominator of the amplitude + aDN = sin((P * (self.DE + SH)) * 180 / pi) - sin( + (P * (self.DS + SH)) * 180 / pi + ) # denominator of the amplitude + ampl = aN / aDN # amplitude of new signal - self.EpHour = max(ifthenelse(pcrand(x >= self.DS, x <= self.DE), -1 * ampl * cos((P * (x + SH)) * 180 / pi), 0), 0) - + self.EpHour = max( + ifthenelse( + pcrand(x >= self.DS, x <= self.DE), + -1 * ampl * cos((P * (x + SH)) * 180 / pi), + 0, + ), + 0, + ) -def downscale_evaporation_snow(self,k): + +def downscale_evaporation_snow(self, k): """ REQUIRED INPUT: daily evaporation (EpDay) @@ -259,20 +312,23 @@ PARAMETERS: - """ - - teller = pcr2numpy(self.thestep,nan)[0,0] - x = teller - floor(teller/24) * 24 * scalar(self.catchArea) + + teller = pcr2numpy(self.thestep, nan)[0, 0] + x = teller - floor(teller / 24) * 24 * scalar(self.catchArea) DL = self.DE - self.DS + 1 - P = 2 * pi / (2 * DL) # period - SH = DL - 12 #horizontal shift of new signal - aN = -1 * self.EpDaySnow * P # nominator of the amplitude - aDN = sin((P * (self.DE + SH)) * 180 / pi) - sin((P * (self.DS + SH)) * 180 / pi) # denominator of the amplitude - ampl = aN / aDN # amplitude of new signal - - self.EpHour = max(ifthenelse(pcrand(x >= self.DS, x <= self.DE), -1 * ampl * cos((P * (x + SH)) * 180 / pi), 0), 0) - - - - - - \ No newline at end of file + P = 2 * pi / (2 * DL) # period + SH = DL - 12 # horizontal shift of new signal + aN = -1 * self.EpDaySnow * P # nominator of the amplitude + aDN = sin((P * (self.DE + SH)) * 180 / pi) - sin( + (P * (self.DS + SH)) * 180 / pi + ) # denominator of the amplitude + ampl = aN / aDN # amplitude of new signal + + self.EpHour = max( + ifthenelse( + pcrand(x >= self.DS, x <= self.DE), + -1 * ampl * cos((P * (x + SH)) * 180 / pi), + 0, + ), + 0, + ) Index: wflow-py/wflow/__init__.py =================================================================== diff -u -rc9d975a5a82cb34652cdc5d2ee9afd734c18d3c7 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/__init__.py (.../__init__.py) (revision c9d975a5a82cb34652cdc5d2ee9afd734c18d3c7) +++ wflow-py/wflow/__init__.py (.../__init__.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,23 +1,31 @@ -__all__ = ['wflow_funcs','wflow_adapt','wflow_lib','pcrut','wf_DynamicFramework','stats'] +__all__ = [ + "wflow_funcs", + "wflow_adapt", + "wflow_lib", + "pcrut", + "wf_DynamicFramework", + "stats", +] import os, sys import osgeo.gdal as gdal -if getattr(sys, 'frozen', False): +if getattr(sys, "frozen", False): # running in a bundle # sys._MEIPASS is set by PyInstaller - basedir = getattr(sys, '_MEIPASS', None) + basedir = getattr(sys, "_MEIPASS", None) # support also other bundlers if not basedir: basedir = os.path.dirname(sys.executable) # use the included gdal-data - gdal_data_path = os.path.join(basedir, 'gdal-data') - gdal.SetConfigOption('GDAL_DATA', gdal_data_path) + gdal_data_path = os.path.join(basedir, "gdal-data") + gdal.SetConfigOption("GDAL_DATA", gdal_data_path) # set environment variable instead of pyproj_datadir such # that child processes will inherit it - os.environ['PROJ_DIR'] = os.path.join(basedir, 'proj-data') + os.environ["PROJ_DIR"] = os.path.join(basedir, "proj-data") from ._version import get_versions -__version__ = get_versions()['version'] + +__version__ = get_versions()["version"] del get_versions Index: wflow-py/wflow/_version.py =================================================================== diff -u -rb1002f0952029227c2a4e6eb543a362299fc0476 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/_version.py (.../_version.py) (revision b1002f0952029227c2a4e6eb543a362299fc0476) +++ wflow-py/wflow/_version.py (.../_version.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -6,15 +6,15 @@ import json -version_json = ''' +version_json = """ { "date": "2018-03-30T08:42:06+0200", "dirty": false, "error": null, "full-revisionid": "4cfef1af4528cf5a50095f81ed30ba193809adc2", "version": "2017.01+216.g4cfef1a" } -''' # END VERSION_JSON +""" # END VERSION_JSON def get_versions(): Index: wflow-py/wflow/bmimodel.py =================================================================== diff -u -r5146577206d9aab9bde79b912dbe038515b57bb7 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/bmimodel.py (.../bmimodel.py) (revision 5146577206d9aab9bde79b912dbe038515b57bb7) +++ wflow-py/wflow/bmimodel.py (.../bmimodel.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,4 +1 @@ # Simple script to link to python wflow bmi models - - - Index: wflow-py/wflow/ogr2ogr.py =================================================================== diff -u -r5ac17d89004ae2e135b343bf4fe375f990193c94 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/ogr2ogr.py (.../ogr2ogr.py) (revision 5ac17d89004ae2e135b343bf4fe375f990193c94) +++ wflow-py/wflow/ogr2ogr.py (.../ogr2ogr.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,6 +1,6 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -#***************************************************************************** +# ***************************************************************************** # $Id$ # # Project: OpenGIS Simple Features Reference Implementation @@ -9,7 +9,7 @@ # # Port from ogr2ogr.cpp whose author is Frank Warmerdam # -#***************************************************************************** +# ***************************************************************************** # Copyright (c) 2010-2013, Even Rouault # Copyright (c) 1999, Frank Warmerdam # @@ -30,7 +30,7 @@ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. -#************************************************************************** +# ************************************************************************** # Note : this is the most direct port of ogr2ogr.cpp possible # It could be made much more Python'ish ! @@ -45,35 +45,42 @@ ############################################################################### + class ScaledProgressObject: - def __init__(self, min, max, cbk, cbk_data = None): + def __init__(self, min, max, cbk, cbk_data=None): self.min = min self.max = max self.cbk = cbk self.cbk_data = cbk_data + ############################################################################### + def ScaledProgressFunc(pct, msg, data): if data.cbk is None: return True return data.cbk(data.min + pct * (data.max - data.min), msg, data.cbk_data) + ############################################################################### + def EQUAL(a, b): return a.lower() == b.lower() + ############################################################################### # Redefinition of GDALTermProgress, so that autotest/pyscripts/test_ogr2ogr_py.py # can check that the progress bar is displayed nLastTick = -1 -def TermProgress( dfComplete, pszMessage, pProgressArg ): +def TermProgress(dfComplete, pszMessage, pProgressArg): + global nLastTick - nThisTick = (int) (dfComplete * 40.0) + nThisTick = (int)(dfComplete * 40.0) if nThisTick < 0: nThisTick = 0 @@ -90,49 +97,55 @@ while nThisTick > nLastTick: nLastTick = nLastTick + 1 if (nLastTick % 4) == 0: - sys.stdout.write('%d' % ((nLastTick / 4) * 10)) + sys.stdout.write("%d" % ((nLastTick / 4) * 10)) else: - sys.stdout.write('.') + sys.stdout.write(".") if nThisTick == 40: - print(" - done." ) + print(" - done.") else: sys.stdout.flush() return True + class TargetLayerInfo: def __init__(self): self.poDstLayer = None self.poCT = None - #self.papszTransformOptions = None + # self.papszTransformOptions = None self.panMap = None self.iSrcZField = None + class AssociatedLayers: def __init__(self): self.poSrcLayer = None self.psInfo = None -#********************************************************************** + +# ********************************************************************** # main() -#********************************************************************** +# ********************************************************************** bSkipFailures = False nGroupTransactions = 200 bPreserveFID = False nFIDToFetch = ogr.NullFID + class Enum(set): def __getattr__(self, name): if name in self: return name raise AttributeError + GeomOperation = Enum(["NONE", "SEGMENTIZE", "SIMPLIFY_PRESERVE_TOPOLOGY"]) -def main(args = None, progress_func = TermProgress, progress_data = None): +def main(args=None, progress_func=TermProgress, progress_data=None): + global bSkipFailures global nGroupTransactions global bPreserveFID @@ -179,8 +192,8 @@ pszClipDstSQL = None pszClipDstLayer = None pszClipDstWhere = None - #pszSrcEncoding = None - #pszDstEncoding = None + # pszSrcEncoding = None + # pszDstEncoding = None bWrapDateline = False bExplodeCollections = False pszZField = None @@ -189,371 +202,396 @@ if args is None: args = sys.argv - args = ogr.GeneralCmdLineProcessor( args ) + args = ogr.GeneralCmdLineProcessor(args) -# -------------------------------------------------------------------- -# Processing command line arguments. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Processing command line arguments. + # -------------------------------------------------------------------- if args is None: return False nArgc = len(args) iArg = 1 while iArg < nArgc: - if EQUAL(args[iArg],"-f") and iArg < nArgc-1: + if EQUAL(args[iArg], "-f") and iArg < nArgc - 1: iArg = iArg + 1 pszFormat = args[iArg] - elif EQUAL(args[iArg],"-dsco") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-dsco") and iArg < nArgc - 1: iArg = iArg + 1 - papszDSCO.append(args[iArg] ) + papszDSCO.append(args[iArg]) - elif EQUAL(args[iArg],"-lco") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-lco") and iArg < nArgc - 1: iArg = iArg + 1 - papszLCO.append(args[iArg] ) + papszLCO.append(args[iArg]) - elif EQUAL(args[iArg],"-preserve_fid"): + elif EQUAL(args[iArg], "-preserve_fid"): bPreserveFID = True elif len(args[iArg]) >= 5 and EQUAL(args[iArg][0:5], "-skip"): bSkipFailures = True - nGroupTransactions = 1 # #2409 + nGroupTransactions = 1 # #2409 - elif EQUAL(args[iArg],"-append"): + elif EQUAL(args[iArg], "-append"): bAppend = True bUpdate = True - elif EQUAL(args[iArg],"-overwrite"): + elif EQUAL(args[iArg], "-overwrite"): bOverwrite = True bUpdate = True - elif EQUAL(args[iArg],"-update"): + elif EQUAL(args[iArg], "-update"): bUpdate = True - elif EQUAL(args[iArg],"-fid") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-fid") and iArg < nArgc - 1: iArg = iArg + 1 nFIDToFetch = int(args[iArg]) - elif EQUAL(args[iArg],"-sql") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-sql") and iArg < nArgc - 1: iArg = iArg + 1 pszSQLStatement = args[iArg] - elif EQUAL(args[iArg],"-nln") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-nln") and iArg < nArgc - 1: iArg = iArg + 1 pszNewLayerName = args[iArg] - elif EQUAL(args[iArg],"-nlt") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-nlt") and iArg < nArgc - 1: - if EQUAL(args[iArg+1],"NONE"): + if EQUAL(args[iArg + 1], "NONE"): eGType = ogr.wkbNone - elif EQUAL(args[iArg+1],"GEOMETRY"): + elif EQUAL(args[iArg + 1], "GEOMETRY"): eGType = ogr.wkbUnknown - elif EQUAL(args[iArg+1],"PROMOTE_TO_MULTI"): + elif EQUAL(args[iArg + 1], "PROMOTE_TO_MULTI"): bPromoteToMulti = True - elif EQUAL(args[iArg+1],"POINT"): + elif EQUAL(args[iArg + 1], "POINT"): eGType = ogr.wkbPoint - elif EQUAL(args[iArg+1],"LINESTRING"): + elif EQUAL(args[iArg + 1], "LINESTRING"): eGType = ogr.wkbLineString - elif EQUAL(args[iArg+1],"POLYGON"): + elif EQUAL(args[iArg + 1], "POLYGON"): eGType = ogr.wkbPolygon - elif EQUAL(args[iArg+1],"GEOMETRYCOLLECTION"): + elif EQUAL(args[iArg + 1], "GEOMETRYCOLLECTION"): eGType = ogr.wkbGeometryCollection - elif EQUAL(args[iArg+1],"MULTIPOINT"): + elif EQUAL(args[iArg + 1], "MULTIPOINT"): eGType = ogr.wkbMultiPoint - elif EQUAL(args[iArg+1],"MULTILINESTRING"): + elif EQUAL(args[iArg + 1], "MULTILINESTRING"): eGType = ogr.wkbMultiLineString - elif EQUAL(args[iArg+1],"MULTIPOLYGON"): + elif EQUAL(args[iArg + 1], "MULTIPOLYGON"): eGType = ogr.wkbMultiPolygon - elif EQUAL(args[iArg+1],"GEOMETRY25D"): + elif EQUAL(args[iArg + 1], "GEOMETRY25D"): eGType = ogr.wkbUnknown | ogr.wkb25DBit - elif EQUAL(args[iArg+1],"POINT25D"): + elif EQUAL(args[iArg + 1], "POINT25D"): eGType = ogr.wkbPoint25D - elif EQUAL(args[iArg+1],"LINESTRING25D"): + elif EQUAL(args[iArg + 1], "LINESTRING25D"): eGType = ogr.wkbLineString25D - elif EQUAL(args[iArg+1],"POLYGON25D"): + elif EQUAL(args[iArg + 1], "POLYGON25D"): eGType = ogr.wkbPolygon25D - elif EQUAL(args[iArg+1],"GEOMETRYCOLLECTION25D"): + elif EQUAL(args[iArg + 1], "GEOMETRYCOLLECTION25D"): eGType = ogr.wkbGeometryCollection25D - elif EQUAL(args[iArg+1],"MULTIPOINT25D"): + elif EQUAL(args[iArg + 1], "MULTIPOINT25D"): eGType = ogr.wkbMultiPoint25D - elif EQUAL(args[iArg+1],"MULTILINESTRING25D"): + elif EQUAL(args[iArg + 1], "MULTILINESTRING25D"): eGType = ogr.wkbMultiLineString25D - elif EQUAL(args[iArg+1],"MULTIPOLYGON25D"): + elif EQUAL(args[iArg + 1], "MULTIPOLYGON25D"): eGType = ogr.wkbMultiPolygon25D else: - print("-nlt %s: type not recognised." % args[iArg+1]) + print("-nlt %s: type not recognised." % args[iArg + 1]) return False iArg = iArg + 1 - elif EQUAL(args[iArg],"-dim") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-dim") and iArg < nArgc - 1: - nCoordDim = int(args[iArg+1]) + nCoordDim = int(args[iArg + 1]) if nCoordDim != 2 and nCoordDim != 3: - print("-dim %s: value not handled." % args[iArg+1]) + print("-dim %s: value not handled." % args[iArg + 1]) return False iArg = iArg + 1 - elif (EQUAL(args[iArg],"-tg") or \ - EQUAL(args[iArg],"-gt")) and iArg < nArgc-1: + elif ( + EQUAL(args[iArg], "-tg") or EQUAL(args[iArg], "-gt") + ) and iArg < nArgc - 1: iArg = iArg + 1 nGroupTransactions = int(args[iArg]) - elif EQUAL(args[iArg],"-s_srs") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-s_srs") and iArg < nArgc - 1: iArg = iArg + 1 pszSourceSRSDef = args[iArg] - elif EQUAL(args[iArg],"-a_srs") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-a_srs") and iArg < nArgc - 1: iArg = iArg + 1 pszOutputSRSDef = args[iArg] - if EQUAL(pszOutputSRSDef, "NULL") or \ - EQUAL(pszOutputSRSDef, "NONE"): + if EQUAL(pszOutputSRSDef, "NULL") or EQUAL(pszOutputSRSDef, "NONE"): pszOutputSRSDef = None bNullifyOutputSRS = True - elif EQUAL(args[iArg],"-t_srs") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-t_srs") and iArg < nArgc - 1: iArg = iArg + 1 pszOutputSRSDef = args[iArg] bTransform = True - elif EQUAL(args[iArg],"-spat") and iArg + 4 < nArgc: + elif EQUAL(args[iArg], "-spat") and iArg + 4 < nArgc: oRing = ogr.Geometry(ogr.wkbLinearRing) - oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+2]) ) - oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+4]) ) - oRing.AddPoint_2D( float(args[iArg+3]), float(args[iArg+4]) ) - oRing.AddPoint_2D( float(args[iArg+3]), float(args[iArg+2]) ) - oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+2]) ) + oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 2])) + oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 4])) + oRing.AddPoint_2D(float(args[iArg + 3]), float(args[iArg + 4])) + oRing.AddPoint_2D(float(args[iArg + 3]), float(args[iArg + 2])) + oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 2])) poSpatialFilter = ogr.Geometry(ogr.wkbPolygon) poSpatialFilter.AddGeometry(oRing) iArg = iArg + 4 - elif EQUAL(args[iArg],"-where") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-where") and iArg < nArgc - 1: iArg = iArg + 1 pszWHERE = args[iArg] - elif EQUAL(args[iArg],"-select") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-select") and iArg < nArgc - 1: iArg = iArg + 1 pszSelect = args[iArg] - if pszSelect.find(',') != -1: - papszSelFields = pszSelect.split(',') + if pszSelect.find(",") != -1: + papszSelFields = pszSelect.split(",") else: - papszSelFields = pszSelect.split(' ') - if papszSelFields[0] == '': + papszSelFields = pszSelect.split(" ") + if papszSelFields[0] == "": papszSelFields = [] - elif EQUAL(args[iArg],"-simplify") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-simplify") and iArg < nArgc - 1: iArg = iArg + 1 eGeomOp = GeomOperation.SIMPLIFY_PRESERVE_TOPOLOGY dfGeomOpParam = float(args[iArg]) - elif EQUAL(args[iArg],"-segmentize") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-segmentize") and iArg < nArgc - 1: iArg = iArg + 1 eGeomOp = GeomOperation.SEGMENTIZE dfGeomOpParam = float(args[iArg]) - elif EQUAL(args[iArg],"-fieldTypeToString") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-fieldTypeToString") and iArg < nArgc - 1: iArg = iArg + 1 pszFieldTypeToString = args[iArg] - if pszFieldTypeToString.find(',') != -1: - tokens = pszFieldTypeToString.split(',') + if pszFieldTypeToString.find(",") != -1: + tokens = pszFieldTypeToString.split(",") else: - tokens = pszFieldTypeToString.split(' ') + tokens = pszFieldTypeToString.split(" ") for token in tokens: - if EQUAL(token,"Integer") or \ - EQUAL(token,"Real") or \ - EQUAL(token,"String") or \ - EQUAL(token,"Date") or \ - EQUAL(token,"Time") or \ - EQUAL(token,"DateTime") or \ - EQUAL(token,"Binary") or \ - EQUAL(token,"IntegerList") or \ - EQUAL(token,"RealList") or \ - EQUAL(token,"StringList"): + if ( + EQUAL(token, "Integer") + or EQUAL(token, "Real") + or EQUAL(token, "String") + or EQUAL(token, "Date") + or EQUAL(token, "Time") + or EQUAL(token, "DateTime") + or EQUAL(token, "Binary") + or EQUAL(token, "IntegerList") + or EQUAL(token, "RealList") + or EQUAL(token, "StringList") + ): papszFieldTypesToString.append(token) - elif EQUAL(token,"All"): - papszFieldTypesToString = [ 'All' ] + elif EQUAL(token, "All"): + papszFieldTypesToString = ["All"] break else: print("Unhandled type for fieldtypeasstring option : %s " % token) return Usage() - elif EQUAL(args[iArg],"-progress"): + elif EQUAL(args[iArg], "-progress"): bDisplayProgress = True - #elif EQUAL(args[iArg],"-wrapdateline") ) - #{ + # elif EQUAL(args[iArg],"-wrapdateline") ) + # { # bWrapDateline = True; - #} + # } # - elif EQUAL(args[iArg],"-clipsrc") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-clipsrc") and iArg < nArgc - 1: bClipSrc = True - if IsNumber(args[iArg+1]) and iArg < nArgc - 4: + if IsNumber(args[iArg + 1]) and iArg < nArgc - 4: oRing = ogr.Geometry(ogr.wkbLinearRing) - oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+2]) ) - oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+4]) ) - oRing.AddPoint_2D( float(args[iArg+3]), float(args[iArg+4]) ) - oRing.AddPoint_2D( float(args[iArg+3]), float(args[iArg+2]) ) - oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+2]) ) + oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 2])) + oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 4])) + oRing.AddPoint_2D(float(args[iArg + 3]), float(args[iArg + 4])) + oRing.AddPoint_2D(float(args[iArg + 3]), float(args[iArg + 2])) + oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 2])) poClipSrc = ogr.Geometry(ogr.wkbPolygon) poClipSrc.AddGeometry(oRing) iArg = iArg + 4 - elif (len(args[iArg+1]) >= 7 and EQUAL(args[iArg+1][0:7],"POLYGON") ) or \ - (len(args[iArg+1]) >= 12 and EQUAL(args[iArg+1][0:12],"MULTIPOLYGON") ) : - poClipSrc = ogr.CreateGeometryFromWkt(args[iArg+1]) + elif ( + len(args[iArg + 1]) >= 7 and EQUAL(args[iArg + 1][0:7], "POLYGON") + ) or ( + len(args[iArg + 1]) >= 12 + and EQUAL(args[iArg + 1][0:12], "MULTIPOLYGON") + ): + poClipSrc = ogr.CreateGeometryFromWkt(args[iArg + 1]) if poClipSrc is None: - print("FAILURE: Invalid geometry. Must be a valid POLYGON or MULTIPOLYGON WKT\n") + print( + "FAILURE: Invalid geometry. Must be a valid POLYGON or MULTIPOLYGON WKT\n" + ) return Usage() iArg = iArg + 1 - elif EQUAL(args[iArg+1],"spat_extent"): + elif EQUAL(args[iArg + 1], "spat_extent"): iArg = iArg + 1 else: - pszClipSrcDS = args[iArg+1] + pszClipSrcDS = args[iArg + 1] iArg = iArg + 1 - elif EQUAL(args[iArg],"-clipsrcsql") and iArg < nArgc-1: - pszClipSrcSQL = args[iArg+1] + elif EQUAL(args[iArg], "-clipsrcsql") and iArg < nArgc - 1: + pszClipSrcSQL = args[iArg + 1] iArg = iArg + 1 - elif EQUAL(args[iArg],"-clipsrclayer") and iArg < nArgc-1: - pszClipSrcLayer = args[iArg+1] + elif EQUAL(args[iArg], "-clipsrclayer") and iArg < nArgc - 1: + pszClipSrcLayer = args[iArg + 1] iArg = iArg + 1 - elif EQUAL(args[iArg],"-clipsrcwhere") and iArg < nArgc-1: - pszClipSrcWhere = args[iArg+1] + elif EQUAL(args[iArg], "-clipsrcwhere") and iArg < nArgc - 1: + pszClipSrcWhere = args[iArg + 1] iArg = iArg + 1 - elif EQUAL(args[iArg],"-clipdst") and iArg < nArgc-1: + elif EQUAL(args[iArg], "-clipdst") and iArg < nArgc - 1: - if IsNumber(args[iArg+1]) and iArg < nArgc - 4: + if IsNumber(args[iArg + 1]) and iArg < nArgc - 4: oRing = ogr.Geometry(ogr.wkbLinearRing) - oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+2]) ) - oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+4]) ) - oRing.AddPoint_2D( float(args[iArg+3]), float(args[iArg+4]) ) - oRing.AddPoint_2D( float(args[iArg+3]), float(args[iArg+2]) ) - oRing.AddPoint_2D( float(args[iArg+1]), float(args[iArg+2]) ) + oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 2])) + oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 4])) + oRing.AddPoint_2D(float(args[iArg + 3]), float(args[iArg + 4])) + oRing.AddPoint_2D(float(args[iArg + 3]), float(args[iArg + 2])) + oRing.AddPoint_2D(float(args[iArg + 1]), float(args[iArg + 2])) poClipDst = ogr.Geometry(ogr.wkbPolygon) poClipDst.AddGeometry(oRing) iArg = iArg + 4 - elif (len(args[iArg+1]) >= 7 and EQUAL(args[iArg+1][0:7],"POLYGON") ) or \ - (len(args[iArg+1]) >= 12 and EQUAL(args[iArg+1][0:12],"MULTIPOLYGON") ) : - poClipDst = ogr.CreateGeometryFromWkt(args[iArg+1]) + elif ( + len(args[iArg + 1]) >= 7 and EQUAL(args[iArg + 1][0:7], "POLYGON") + ) or ( + len(args[iArg + 1]) >= 12 + and EQUAL(args[iArg + 1][0:12], "MULTIPOLYGON") + ): + poClipDst = ogr.CreateGeometryFromWkt(args[iArg + 1]) if poClipDst is None: - print("FAILURE: Invalid geometry. Must be a valid POLYGON or MULTIPOLYGON WKT\n") + print( + "FAILURE: Invalid geometry. Must be a valid POLYGON or MULTIPOLYGON WKT\n" + ) return Usage() iArg = iArg + 1 - elif EQUAL(args[iArg+1],"spat_extent"): + elif EQUAL(args[iArg + 1], "spat_extent"): iArg = iArg + 1 else: - pszClipDstDS = args[iArg+1] + pszClipDstDS = args[iArg + 1] iArg = iArg + 1 - elif EQUAL(args[iArg],"-clipdstsql") and iArg < nArgc-1: - pszClipDstSQL = args[iArg+1] + elif EQUAL(args[iArg], "-clipdstsql") and iArg < nArgc - 1: + pszClipDstSQL = args[iArg + 1] iArg = iArg + 1 - elif EQUAL(args[iArg],"-clipdstlayer") and iArg < nArgc-1: - pszClipDstLayer = args[iArg+1] + elif EQUAL(args[iArg], "-clipdstlayer") and iArg < nArgc - 1: + pszClipDstLayer = args[iArg + 1] iArg = iArg + 1 - elif EQUAL(args[iArg],"-clipdstwhere") and iArg < nArgc-1: - pszClipDstWhere = args[iArg+1] + elif EQUAL(args[iArg], "-clipdstwhere") and iArg < nArgc - 1: + pszClipDstWhere = args[iArg + 1] iArg = iArg + 1 - elif EQUAL(args[iArg],"-explodecollections"): + elif EQUAL(args[iArg], "-explodecollections"): bExplodeCollections = True - elif EQUAL(args[iArg],"-zfield") and iArg < nArgc-1: - pszZField = args[iArg+1] + elif EQUAL(args[iArg], "-zfield") and iArg < nArgc - 1: + pszZField = args[iArg + 1] iArg = iArg + 1 - elif args[iArg][0] == '-': + elif args[iArg][0] == "-": return Usage() elif pszDestDataSource is None: pszDestDataSource = args[iArg] elif pszDataSource is None: pszDataSource = args[iArg] else: - papszLayers.append (args[iArg] ) + papszLayers.append(args[iArg]) iArg = iArg + 1 if pszDataSource is None: return Usage() if bPreserveFID and bExplodeCollections: - print("FAILURE: cannot use -preserve_fid and -explodecollections at the same time\n\n") + print( + "FAILURE: cannot use -preserve_fid and -explodecollections at the same time\n\n" + ) return Usage() if bClipSrc and pszClipSrcDS is not None: - poClipSrc = LoadGeometry(pszClipSrcDS, pszClipSrcSQL, pszClipSrcLayer, pszClipSrcWhere) + poClipSrc = LoadGeometry( + pszClipSrcDS, pszClipSrcSQL, pszClipSrcLayer, pszClipSrcWhere + ) if poClipSrc is None: - print("FAILURE: cannot load source clip geometry\n" ) + print("FAILURE: cannot load source clip geometry\n") return Usage() elif bClipSrc and poClipSrc is None: if poSpatialFilter is not None: poClipSrc = poSpatialFilter.Clone() if poClipSrc is None: - print("FAILURE: -clipsrc must be used with -spat option or a\n" + \ - "bounding box, WKT string or datasource must be specified\n") + print( + "FAILURE: -clipsrc must be used with -spat option or a\n" + + "bounding box, WKT string or datasource must be specified\n" + ) return Usage() if pszClipDstDS is not None: - poClipDst = LoadGeometry(pszClipDstDS, pszClipDstSQL, pszClipDstLayer, pszClipDstWhere) + poClipDst = LoadGeometry( + pszClipDstDS, pszClipDstSQL, pszClipDstLayer, pszClipDstWhere + ) if poClipDst is None: - print("FAILURE: cannot load dest clip geometry\n" ) + print("FAILURE: cannot load dest clip geometry\n") return Usage() -# -------------------------------------------------------------------- -# Open data source. -# -------------------------------------------------------------------- - poDS = ogr.Open( pszDataSource, False ) + # -------------------------------------------------------------------- + # Open data source. + # -------------------------------------------------------------------- + poDS = ogr.Open(pszDataSource, False) -# -------------------------------------------------------------------- -# Report failure -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Report failure + # -------------------------------------------------------------------- if poDS is None: - print("FAILURE:\n" + \ - "Unable to open datasource `%s' with the following drivers." % pszDataSource) + print( + "FAILURE:\n" + + "Unable to open datasource `%s' with the following drivers." + % pszDataSource + ) for iDriver in range(ogr.GetDriverCount()): - print(" -> " + ogr.GetDriver(iDriver).GetName() ) + print(" -> " + ogr.GetDriver(iDriver).GetName()) return False -# -------------------------------------------------------------------- -# Try opening the output datasource as an existing, writable -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Try opening the output datasource as an existing, writable + # -------------------------------------------------------------------- poODS = None poDriver = None if bUpdate: - poODS = ogr.Open( pszDestDataSource, True ) + poODS = ogr.Open(pszDestDataSource, True) if poODS is None: if bOverwrite or bAppend: - poODS = ogr.Open( pszDestDataSource, False ) + poODS = ogr.Open(pszDestDataSource, False) if poODS is None: # the datasource doesn't exist at all bUpdate = False @@ -562,49 +600,58 @@ poODS = None if bUpdate: - print("FAILURE:\n" + - "Unable to open existing output datasource `%s'." % pszDestDataSource) + print( + "FAILURE:\n" + + "Unable to open existing output datasource `%s'." + % pszDestDataSource + ) return False elif len(papszDSCO) > 0: - print("WARNING: Datasource creation options ignored since an existing datasource\n" + \ - " being updated." ) + print( + "WARNING: Datasource creation options ignored since an existing datasource\n" + + " being updated." + ) if poODS is not None: poDriver = poODS.GetDriver() -# -------------------------------------------------------------------- -# Find the output driver. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Find the output driver. + # -------------------------------------------------------------------- if not bUpdate: poDriver = ogr.GetDriverByName(pszFormat) if poDriver is None: print("Unable to find driver `%s'." % pszFormat) - print( "The following drivers are available:" ) + print("The following drivers are available:") for iDriver in range(ogr.GetDriverCount()): - print(" -> %s" % ogr.GetDriver(iDriver).GetName() ) + print(" -> %s" % ogr.GetDriver(iDriver).GetName()) return False - if poDriver.TestCapability( ogr.ODrCCreateDataSource ) == False: - print( "%s driver does not support data source creation." % pszFormat) + if poDriver.TestCapability(ogr.ODrCCreateDataSource) == False: + print("%s driver does not support data source creation." % pszFormat) return False -# -------------------------------------------------------------------- -# Special case to improve user experience when translating -# a datasource with multiple layers into a shapefile. If the -# user gives a target datasource with .shp and it does not exist, -# the shapefile driver will try to create a file, but this is not -# appropriate because here we have several layers, so create -# a directory instead. -# -------------------------------------------------------------------- - if EQUAL(poDriver.GetName(), "ESRI Shapefile") and \ - pszSQLStatement is None and \ - (len(papszLayers) > 1 or \ - (len(papszLayers) == 0 and poDS.GetLayerCount() > 1)) and \ - pszNewLayerName is None and \ - EQUAL(os.path.splitext(pszDestDataSource)[1], ".SHP") : + # -------------------------------------------------------------------- + # Special case to improve user experience when translating + # a datasource with multiple layers into a shapefile. If the + # user gives a target datasource with .shp and it does not exist, + # the shapefile driver will try to create a file, but this is not + # appropriate because here we have several layers, so create + # a directory instead. + # -------------------------------------------------------------------- + if ( + EQUAL(poDriver.GetName(), "ESRI Shapefile") + and pszSQLStatement is None + and ( + len(papszLayers) > 1 + or (len(papszLayers) == 0 and poDS.GetLayerCount() > 1) + ) + and pszNewLayerName is None + and EQUAL(os.path.splitext(pszDestDataSource)[1], ".SHP") + ): try: os.stat(pszDestDataSource) @@ -614,58 +661,58 @@ # this syntax is only supported by Python >= 2.6 os.mkdir(pszDestDataSource, 493) except: - print("Failed to create directory %s\n" - "for shapefile datastore.\n" % pszDestDataSource ) + print( + "Failed to create directory %s\n" + "for shapefile datastore.\n" % pszDestDataSource + ) return False -# -------------------------------------------------------------------- -# Create the output data source. -# -------------------------------------------------------------------- - poODS = poDriver.CreateDataSource( pszDestDataSource, options = papszDSCO ) + # -------------------------------------------------------------------- + # Create the output data source. + # -------------------------------------------------------------------- + poODS = poDriver.CreateDataSource(pszDestDataSource, options=papszDSCO) if poODS is None: - print( "%s driver failed to create %s" % (pszFormat, pszDestDataSource )) + print("%s driver failed to create %s" % (pszFormat, pszDestDataSource)) return False -# -------------------------------------------------------------------- -# Parse the output SRS definition if possible. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Parse the output SRS definition if possible. + # -------------------------------------------------------------------- if pszOutputSRSDef is not None: poOutputSRS = osr.SpatialReference() - if poOutputSRS.SetFromUserInput( pszOutputSRSDef ) != 0: - print( "Failed to process SRS definition: %s" % pszOutputSRSDef ) + if poOutputSRS.SetFromUserInput(pszOutputSRSDef) != 0: + print("Failed to process SRS definition: %s" % pszOutputSRSDef) return False -# -------------------------------------------------------------------- -# Parse the source SRS definition if possible. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Parse the source SRS definition if possible. + # -------------------------------------------------------------------- if pszSourceSRSDef is not None: poSourceSRS = osr.SpatialReference() - if poSourceSRS.SetFromUserInput( pszSourceSRSDef ) != 0: - print( "Failed to process SRS definition: %s" % pszSourceSRSDef ) + if poSourceSRS.SetFromUserInput(pszSourceSRSDef) != 0: + print("Failed to process SRS definition: %s" % pszSourceSRSDef) return False -# -------------------------------------------------------------------- -# For OSM file. -# -------------------------------------------------------------------- - bSrcIsOSM = poDS.GetDriver() is not None and \ - poDS.GetDriver().GetName() == "OSM" + # -------------------------------------------------------------------- + # For OSM file. + # -------------------------------------------------------------------- + bSrcIsOSM = poDS.GetDriver() is not None and poDS.GetDriver().GetName() == "OSM" nSrcFileSize = 0 if bSrcIsOSM and poDS.GetName() != "/vsistdin/": sStat = gdal.VSIStatL(poDS.GetName()) if sStat is not None: nSrcFileSize = sStat.size -# -------------------------------------------------------------------- -# Special case for -sql clause. No source layers required. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Special case for -sql clause. No source layers required. + # -------------------------------------------------------------------- if pszSQLStatement is not None: if pszWHERE is not None: - print( "-where clause ignored in combination with -sql." ) + print("-where clause ignored in combination with -sql.") if len(papszLayers) > 0: - print( "layer names ignored in combination with -sql." ) + print("layer names ignored in combination with -sql.") - poResultSet = poDS.ExecuteSQL( pszSQLStatement, poSpatialFilter, \ - None ) + poResultSet = poDS.ExecuteSQL(pszSQLStatement, poSpatialFilter, None) if poResultSet is not None: nCountLayerFeatures = 0 @@ -675,106 +722,129 @@ pProgressArg = progress_data elif not poResultSet.TestCapability(ogr.OLCFastFeatureCount): - print( "Progress turned off as fast feature count is not available.") + print("Progress turned off as fast feature count is not available.") bDisplayProgress = False else: nCountLayerFeatures = poResultSet.GetFeatureCount() pfnProgress = progress_func pProgressArg = progress_data -# -------------------------------------------------------------------- -# Special case to improve user experience when translating into -# single file shapefile and source has only one layer, and that -# the layer name isn't specified -# -------------------------------------------------------------------- - if EQUAL(poDriver.GetName(), "ESRI Shapefile") and \ - pszNewLayerName is None: + # -------------------------------------------------------------------- + # Special case to improve user experience when translating into + # single file shapefile and source has only one layer, and that + # the layer name isn't specified + # -------------------------------------------------------------------- + if EQUAL(poDriver.GetName(), "ESRI Shapefile") and pszNewLayerName is None: try: mode = os.stat(pszDestDataSource).st_mode if (mode & stat.S_IFDIR) == 0: - pszNewLayerName = os.path.splitext(os.path.basename(pszDestDataSource))[0] + pszNewLayerName = os.path.splitext( + os.path.basename(pszDestDataSource) + )[0] except: pass + psInfo = SetupTargetLayer( + poDS, + poResultSet, + poODS, + papszLCO, + pszNewLayerName, + bTransform, + poOutputSRS, + bNullifyOutputSRS, + poSourceSRS, + papszSelFields, + bAppend, + eGType, + bPromoteToMulti, + nCoordDim, + bOverwrite, + papszFieldTypesToString, + bWrapDateline, + bExplodeCollections, + pszZField, + pszWHERE, + ) - psInfo = SetupTargetLayer( poDS, \ - poResultSet, - poODS, \ - papszLCO, \ - pszNewLayerName, \ - bTransform, \ - poOutputSRS, \ - bNullifyOutputSRS, \ - poSourceSRS, \ - papszSelFields, \ - bAppend, eGType, bPromoteToMulti, nCoordDim, bOverwrite, \ - papszFieldTypesToString, \ - bWrapDateline, \ - bExplodeCollections, \ - pszZField, \ - pszWHERE ) - poResultSet.ResetReading() - if psInfo is None or not TranslateLayer( psInfo, poDS, poResultSet, poODS, \ - poOutputSRS, bNullifyOutputSRS, \ - eGType, bPromoteToMulti, nCoordDim, \ - eGeomOp, dfGeomOpParam, \ - nCountLayerFeatures, \ - poClipSrc, poClipDst, \ - bExplodeCollections, \ - nSrcFileSize, None, \ - pfnProgress, pProgressArg ): + if psInfo is None or not TranslateLayer( + psInfo, + poDS, + poResultSet, + poODS, + poOutputSRS, + bNullifyOutputSRS, + eGType, + bPromoteToMulti, + nCoordDim, + eGeomOp, + dfGeomOpParam, + nCountLayerFeatures, + poClipSrc, + poClipDst, + bExplodeCollections, + nSrcFileSize, + None, + pfnProgress, + pProgressArg, + ): print( - "Terminating translation prematurely after failed\n" + \ - "translation from sql statement." ) + "Terminating translation prematurely after failed\n" + + "translation from sql statement." + ) return False - poDS.ReleaseResultSet( poResultSet ) + poDS.ReleaseResultSet(poResultSet) - -# -------------------------------------------------------------------- -# Special case for layer interleaving mode. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Special case for layer interleaving mode. + # -------------------------------------------------------------------- elif bSrcIsOSM and gdal.GetConfigOption("OGR_INTERLEAVED_READING", None) is None: gdal.SetConfigOption("OGR_INTERLEAVED_READING", "YES") - #if (bSplitListFields) - #{ + # if (bSplitListFields) + # { # fprintf( stderr, "FAILURE: -splitlistfields not supported in this mode\n" ); # exit( 1 ); - #} + # } nSrcLayerCount = poDS.GetLayerCount() - pasAssocLayers = [ AssociatedLayers() for i in range(nSrcLayerCount) ] + pasAssocLayers = [AssociatedLayers() for i in range(nSrcLayerCount)] -# -------------------------------------------------------------------- -# Special case to improve user experience when translating into -# single file shapefile and source has only one layer, and that -# the layer name isn't specified -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Special case to improve user experience when translating into + # single file shapefile and source has only one layer, and that + # the layer name isn't specified + # -------------------------------------------------------------------- - if EQUAL(poDriver.GetName(), "ESRI Shapefile") and \ - (len(papszLayers) == 1 or nSrcLayerCount == 1) and pszNewLayerName is None: + if ( + EQUAL(poDriver.GetName(), "ESRI Shapefile") + and (len(papszLayers) == 1 or nSrcLayerCount == 1) + and pszNewLayerName is None + ): try: mode = os.stat(pszDestDataSource).st_mode if (mode & stat.S_IFDIR) == 0: - pszNewLayerName = os.path.splitext(os.path.basename(pszDestDataSource))[0] + pszNewLayerName = os.path.splitext( + os.path.basename(pszDestDataSource) + )[0] except: pass if bDisplayProgress and bSrcIsOSM: pfnProgress = progress_func pProgressArg = progress_data -# -------------------------------------------------------------------- -# If no target layer specified, use all source layers. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # If no target layer specified, use all source layers. + # -------------------------------------------------------------------- if len(papszLayers) == 0: - papszLayers = [ None for i in range(nSrcLayerCount) ] + papszLayers = [None for i in range(nSrcLayerCount)] for iLayer in range(nSrcLayerCount): poLayer = poDS.GetLayer(iLayer) if poLayer is None: @@ -792,9 +862,9 @@ poDS.ExecuteSQL(osInterestLayers, None, None) -# -------------------------------------------------------------------- -# First pass to set filters and create target layers. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # First pass to set filters and create target layers. + # -------------------------------------------------------------------- for iLayer in range(nSrcLayerCount): poLayer = poDS.GetLayer(iLayer) if poLayer is None: @@ -805,30 +875,39 @@ if CSLFindString(papszLayers, poLayer.GetName()) >= 0: if pszWHERE is not None: - if poLayer.SetAttributeFilter( pszWHERE ) != 0: - print("FAILURE: SetAttributeFilter(%s) on layer '%s' failed.\n" % (pszWHERE, poLayer.GetName()) ) + if poLayer.SetAttributeFilter(pszWHERE) != 0: + print( + "FAILURE: SetAttributeFilter(%s) on layer '%s' failed.\n" + % (pszWHERE, poLayer.GetName()) + ) if not bSkipFailures: return False if poSpatialFilter is not None: - poLayer.SetSpatialFilter( poSpatialFilter ) + poLayer.SetSpatialFilter(poSpatialFilter) - psInfo = SetupTargetLayer( poDS, \ - poLayer, \ - poODS, \ - papszLCO, \ - pszNewLayerName, \ - bTransform, \ - poOutputSRS, \ - bNullifyOutputSRS, \ - poSourceSRS, \ - papszSelFields, \ - bAppend, eGType, bPromoteToMulti, nCoordDim, bOverwrite, \ - papszFieldTypesToString, \ - bWrapDateline, \ - bExplodeCollections, \ - pszZField, \ - pszWHERE ) + psInfo = SetupTargetLayer( + poDS, + poLayer, + poODS, + papszLCO, + pszNewLayerName, + bTransform, + poOutputSRS, + bNullifyOutputSRS, + poSourceSRS, + papszSelFields, + bAppend, + eGType, + bPromoteToMulti, + nCoordDim, + bOverwrite, + papszFieldTypesToString, + bWrapDateline, + bExplodeCollections, + pszZField, + pszWHERE, + ) if psInfo is None and not bSkipFailures: return False @@ -837,9 +916,9 @@ else: pasAssocLayers[iLayer].psInfo = None -# -------------------------------------------------------------------- -# Second pass to process features in a interleaved layer mode. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Second pass to process features in a interleaved layer mode. + # -------------------------------------------------------------------- bHasLayersNonEmpty = True while bHasLayersNonEmpty: bHasLayersNonEmpty = False @@ -850,20 +929,36 @@ anReadFeatureCount = [0] if psInfo is not None: - if not TranslateLayer(psInfo, poDS, poLayer, poODS, \ - poOutputSRS, bNullifyOutputSRS, \ - eGType, bPromoteToMulti, nCoordDim, \ - eGeomOp, dfGeomOpParam, \ - 0, \ - poClipSrc, poClipDst, \ - bExplodeCollections, \ - nSrcFileSize, \ - anReadFeatureCount, \ - pfnProgress, pProgressArg ) \ - and not bSkipFailures: + if ( + not TranslateLayer( + psInfo, + poDS, + poLayer, + poODS, + poOutputSRS, + bNullifyOutputSRS, + eGType, + bPromoteToMulti, + nCoordDim, + eGeomOp, + dfGeomOpParam, + 0, + poClipSrc, + poClipDst, + bExplodeCollections, + nSrcFileSize, + anReadFeatureCount, + pfnProgress, + pProgressArg, + ) + and not bSkipFailures + ): print( - "Terminating translation prematurely after failed\n" + \ - "translation of layer " + poLayer.GetName() + " (use -skipfailures to skip errors)") + "Terminating translation prematurely after failed\n" + + "translation of layer " + + poLayer.GetName() + + " (use -skipfailures to skip errors)" + ) return False else: @@ -882,9 +977,9 @@ nLayerCount = 0 papoLayers = [] -# -------------------------------------------------------------------- -# Process each data source layer. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Process each data source layer. + # -------------------------------------------------------------------- if len(papszLayers) == 0: nLayerCount = poDS.GetLayerCount() papoLayers = [None for i in range(nLayerCount)] @@ -900,9 +995,9 @@ papoLayers[iLayer] = poLayer iLayer = iLayer + 1 -# -------------------------------------------------------------------- -# Process specified data source layers. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Process specified data source layers. + # -------------------------------------------------------------------- else: nLayerCount = len(papszLayers) papoLayers = [None for i in range(nLayerCount)] @@ -927,13 +1022,13 @@ poLayer = papoLayers[iLayer] if pszWHERE is not None: - if poLayer.SetAttributeFilter( pszWHERE ) != 0: + if poLayer.SetAttributeFilter(pszWHERE) != 0: print("FAILURE: SetAttributeFilter(%s) failed." % pszWHERE) if not bSkipFailures: return False if poSpatialFilter is not None: - poLayer.SetSpatialFilter( poSpatialFilter ) + poLayer.SetSpatialFilter(poSpatialFilter) if bDisplayProgress and not bSrcIsOSM: if not poLayer.TestCapability(ogr.OLCFastFeatureCount): @@ -953,137 +1048,178 @@ pProgressArg = progress_data else: pfnProgress = ScaledProgressFunc - pProgressArg = ScaledProgressObject( \ - nAccCountFeatures * 1.0 / nCountLayersFeatures, \ - (nAccCountFeatures + panLayerCountFeatures[iLayer]) * 1.0 / nCountLayersFeatures, \ - progress_func, progress_data) + pProgressArg = ScaledProgressObject( + nAccCountFeatures * 1.0 / nCountLayersFeatures, + (nAccCountFeatures + panLayerCountFeatures[iLayer]) + * 1.0 + / nCountLayersFeatures, + progress_func, + progress_data, + ) nAccCountFeatures += panLayerCountFeatures[iLayer] -# -------------------------------------------------------------------- -# Special case to improve user experience when translating into -# single file shapefile and source has only one layer, and that -# the layer name isn't specified -# -------------------------------------------------------------------- - if EQUAL(poDriver.GetName(), "ESRI Shapefile") and \ - nLayerCount == 1 and pszNewLayerName is None: + # -------------------------------------------------------------------- + # Special case to improve user experience when translating into + # single file shapefile and source has only one layer, and that + # the layer name isn't specified + # -------------------------------------------------------------------- + if ( + EQUAL(poDriver.GetName(), "ESRI Shapefile") + and nLayerCount == 1 + and pszNewLayerName is None + ): try: mode = os.stat(pszDestDataSource).st_mode if (mode & stat.S_IFDIR) == 0: - pszNewLayerName = os.path.splitext(os.path.basename(pszDestDataSource))[0] + pszNewLayerName = os.path.splitext( + os.path.basename(pszDestDataSource) + )[0] except: pass + psInfo = SetupTargetLayer( + poDS, + poLayer, + poODS, + papszLCO, + pszNewLayerName, + bTransform, + poOutputSRS, + bNullifyOutputSRS, + poSourceSRS, + papszSelFields, + bAppend, + eGType, + bPromoteToMulti, + nCoordDim, + bOverwrite, + papszFieldTypesToString, + bWrapDateline, + bExplodeCollections, + pszZField, + pszWHERE, + ) - psInfo = SetupTargetLayer( poDS, \ - poLayer, \ - poODS, \ - papszLCO, \ - pszNewLayerName, \ - bTransform, \ - poOutputSRS, \ - bNullifyOutputSRS, \ - poSourceSRS, \ - papszSelFields, \ - bAppend, eGType, bPromoteToMulti, nCoordDim, bOverwrite, \ - papszFieldTypesToString, \ - bWrapDateline, \ - bExplodeCollections, \ - pszZField, \ - pszWHERE ) - poLayer.ResetReading() - if (psInfo is None or \ - not TranslateLayer( psInfo, poDS, poLayer, poODS, \ - poOutputSRS, bNullifyOutputSRS, \ - eGType, bPromoteToMulti, nCoordDim, \ - eGeomOp, dfGeomOpParam, \ - panLayerCountFeatures[iLayer], \ - poClipSrc, poClipDst, \ - bExplodeCollections, \ - nSrcFileSize, None, \ - pfnProgress, pProgressArg )) \ - and not bSkipFailures: + if ( + psInfo is None + or not TranslateLayer( + psInfo, + poDS, + poLayer, + poODS, + poOutputSRS, + bNullifyOutputSRS, + eGType, + bPromoteToMulti, + nCoordDim, + eGeomOp, + dfGeomOpParam, + panLayerCountFeatures[iLayer], + poClipSrc, + poClipDst, + bExplodeCollections, + nSrcFileSize, + None, + pfnProgress, + pProgressArg, + ) + ) and not bSkipFailures: print( - "Terminating translation prematurely after failed\n" + \ - "translation of layer " + poLayer.GetLayerDefn().GetName() + " (use -skipfailures to skip errors)") + "Terminating translation prematurely after failed\n" + + "translation of layer " + + poLayer.GetLayerDefn().GetName() + + " (use -skipfailures to skip errors)" + ) return False -# -------------------------------------------------------------------- -# Close down. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Close down. + # -------------------------------------------------------------------- # We must explicitly destroy the output dataset in order the file # to be properly closed ! poODS.Destroy() poDS.Destroy() return True -#********************************************************************** + +# ********************************************************************** # Usage() -#********************************************************************** +# ********************************************************************** + def Usage(): - print( "Usage: ogr2ogr [--help-general] [-skipfailures] [-append] [-update] [-gt n]\n" + \ - " [-select field_list] [-where restricted_where] \n" + \ - " [-progress] [-sql ] \n" + \ - " [-spat xmin ymin xmax ymax] [-preserve_fid] [-fid FID]\n" + \ - " [-a_srs srs_def] [-t_srs srs_def] [-s_srs srs_def]\n" + \ - " [-f format_name] [-overwrite] [[-dsco NAME=VALUE] ...]\n" + \ - " [-simplify tolerance]\n" + \ - #// " [-segmentize max_dist] [-fieldTypeToString All|(type1[,type2]*)]\n" + \ - " [-fieldTypeToString All|(type1[,type2]*)] [-explodecollections] \n" + \ - " dst_datasource_name src_datasource_name\n" + \ - " [-lco NAME=VALUE] [-nln name] [-nlt type] [-dim 2|3] [layer [layer ...]]\n" + \ - "\n" + \ - " -f format_name: output file format name, possible values are:") + print( + "Usage: ogr2ogr [--help-general] [-skipfailures] [-append] [-update] [-gt n]\n" + + " [-select field_list] [-where restricted_where] \n" + + " [-progress] [-sql ] \n" + + " [-spat xmin ymin xmax ymax] [-preserve_fid] [-fid FID]\n" + + " [-a_srs srs_def] [-t_srs srs_def] [-s_srs srs_def]\n" + + " [-f format_name] [-overwrite] [[-dsco NAME=VALUE] ...]\n" + + " [-simplify tolerance]\n" + + + # // " [-segmentize max_dist] [-fieldTypeToString All|(type1[,type2]*)]\n" + \ + " [-fieldTypeToString All|(type1[,type2]*)] [-explodecollections] \n" + + " dst_datasource_name src_datasource_name\n" + + " [-lco NAME=VALUE] [-nln name] [-nlt type] [-dim 2|3] [layer [layer ...]]\n" + + "\n" + + " -f format_name: output file format name, possible values are:" + ) for iDriver in range(ogr.GetDriverCount()): poDriver = ogr.GetDriver(iDriver) - if poDriver.TestCapability( ogr.ODrCCreateDataSource ): - print( " -f \"" + poDriver.GetName() + "\"" ) + if poDriver.TestCapability(ogr.ODrCCreateDataSource): + print(' -f "' + poDriver.GetName() + '"') - print( " -append: Append to existing layer instead of creating new if it exists\n" + \ - " -overwrite: delete the output layer and recreate it empty\n" + \ - " -update: Open existing output datasource in update mode\n" + \ - " -progress: Display progress on terminal. Only works if input layers have the \"fast feature count\" capability\n" + \ - " -select field_list: Comma-delimited list of fields from input layer to\n" + \ - " copy to the new layer (defaults to all)\n" + \ - " -where restricted_where: Attribute query (like SQL WHERE)\n" + \ - " -sql statement: Execute given SQL statement and save result.\n" + \ - " -skipfailures: skip features or layers that fail to convert\n" + \ - " -gt n: group n features per transaction (default 200)\n" + \ - " -spat xmin ymin xmax ymax: spatial query extents\n" + \ - " -simplify tolerance: distance tolerance for simplification.\n" + \ - #//" -segmentize max_dist: maximum distance between 2 nodes.\n" + \ - #//" Used to create intermediate points\n" + \ - " -dsco NAME=VALUE: Dataset creation option (format specific)\n" + \ - " -lco NAME=VALUE: Layer creation option (format specific)\n" + \ - " -nln name: Assign an alternate name to the new layer\n" + \ - " -nlt type: Force a geometry type for new layer. One of NONE, GEOMETRY,\n" + \ - " POINT, LINESTRING, POLYGON, GEOMETRYCOLLECTION, MULTIPOINT,\n" + \ - " MULTIPOLYGON, or MULTILINESTRING. Add \"25D\" for 3D layers.\n" + \ - " Default is type of source layer.\n" + \ - " -dim dimension: Force the coordinate dimension to the specified value.\n" + \ - " -fieldTypeToString type1,...: Converts fields of specified types to\n" + \ - " fields of type string in the new layer. Valid types are : \n" + \ - " Integer, Real, String, Date, Time, DateTime, Binary, IntegerList, RealList,\n" + \ - " StringList. Special value All can be used to convert all fields to strings.") + print( + " -append: Append to existing layer instead of creating new if it exists\n" + + " -overwrite: delete the output layer and recreate it empty\n" + + " -update: Open existing output datasource in update mode\n" + + ' -progress: Display progress on terminal. Only works if input layers have the "fast feature count" capability\n' + + " -select field_list: Comma-delimited list of fields from input layer to\n" + + " copy to the new layer (defaults to all)\n" + + " -where restricted_where: Attribute query (like SQL WHERE)\n" + + " -sql statement: Execute given SQL statement and save result.\n" + + " -skipfailures: skip features or layers that fail to convert\n" + + " -gt n: group n features per transaction (default 200)\n" + + " -spat xmin ymin xmax ymax: spatial query extents\n" + + " -simplify tolerance: distance tolerance for simplification.\n" + + + # //" -segmentize max_dist: maximum distance between 2 nodes.\n" + \ + # //" Used to create intermediate points\n" + \ + " -dsco NAME=VALUE: Dataset creation option (format specific)\n" + + " -lco NAME=VALUE: Layer creation option (format specific)\n" + + " -nln name: Assign an alternate name to the new layer\n" + + " -nlt type: Force a geometry type for new layer. One of NONE, GEOMETRY,\n" + + " POINT, LINESTRING, POLYGON, GEOMETRYCOLLECTION, MULTIPOINT,\n" + + ' MULTIPOLYGON, or MULTILINESTRING. Add "25D" for 3D layers.\n' + + " Default is type of source layer.\n" + + " -dim dimension: Force the coordinate dimension to the specified value.\n" + + " -fieldTypeToString type1,...: Converts fields of specified types to\n" + + " fields of type string in the new layer. Valid types are : \n" + + " Integer, Real, String, Date, Time, DateTime, Binary, IntegerList, RealList,\n" + + " StringList. Special value All can be used to convert all fields to strings." + ) - print(" -a_srs srs_def: Assign an output SRS\n" + print( + " -a_srs srs_def: Assign an output SRS\n" " -t_srs srs_def: Reproject/transform to this SRS on output\n" " -s_srs srs_def: Override source SRS\n" "\n" " Srs_def can be a full WKT definition (hard to escape properly),\n" " or a well known definition (i.e. EPSG:4326) or a file with a WKT\n" - " definition." ) + " definition." + ) return False + def CSLFindString(v, mystr): i = 0 for strIter in v: @@ -1092,22 +1228,24 @@ i = i + 1 return -1 -def IsNumber( pszStr): + +def IsNumber(pszStr): try: (float)(pszStr) return True except: return False -def LoadGeometry( pszDS, pszSQL, pszLyr, pszWhere): + +def LoadGeometry(pszDS, pszSQL, pszLyr, pszWhere): poGeom = None - poDS = ogr.Open( pszDS, False ) + poDS = ogr.Open(pszDS, False) if poDS is None: return None if pszSQL is not None: - poLyr = poDS.ExecuteSQL( pszSQL, None, None ) + poLyr = poDS.ExecuteSQL(pszSQL, None, None) elif pszLyr is not None: poLyr = poDS.GetLayerByName(pszLyr) else: @@ -1128,25 +1266,25 @@ eType = wkbFlatten(poSrcGeom.GetGeometryType()) if poGeom is None: - poGeom = ogr.Geometry( ogr.wkbMultiPolygon ) + poGeom = ogr.Geometry(ogr.wkbMultiPolygon) if eType == ogr.wkbPolygon: - poGeom.AddGeometry( poSrcGeom ) + poGeom.AddGeometry(poSrcGeom) elif eType == ogr.wkbMultiPolygon: for iGeom in range(poSrcGeom.GetGeometryCount()): - poGeom.AddGeometry(poSrcGeom.GetGeometryRef(iGeom) ) + poGeom.AddGeometry(poSrcGeom.GetGeometryRef(iGeom)) else: - print("ERROR: Geometry not of polygon type." ) + print("ERROR: Geometry not of polygon type.") if pszSQL is not None: - poDS.ReleaseResultSet( poLyr ) + poDS.ReleaseResultSet(poLyr) poDS.Destroy() return None poFeat = poLyr.GetNextFeature() if pszSQL is not None: - poDS.ReleaseResultSet( poLyr ) + poDS.ReleaseResultSet(poLyr) poDS.Destroy() return poGeom @@ -1155,95 +1293,121 @@ def wkbFlatten(x): return x & (~ogr.wkb25DBit) -#********************************************************************** + +# ********************************************************************** # SetZ() -#********************************************************************** +# ********************************************************************** -def SetZ (poGeom, dfZ ): +def SetZ(poGeom, dfZ): + if poGeom is None: return eGType = wkbFlatten(poGeom.GetGeometryType()) if eGType == ogr.wkbPoint: poGeom.SetPoint(0, poGeom.GetX(), poGeom.GetY(), dfZ) - elif eGType == ogr.wkbLineString or \ - eGType == ogr.wkbLinearRing: + elif eGType == ogr.wkbLineString or eGType == ogr.wkbLinearRing: for i in range(poGeom.GetPointCount()): poGeom.SetPoint(i, poGeom.GetX(i), poGeom.GetY(i), dfZ) - elif eGType == ogr.wkbPolygon or \ - eGType == ogr.wkbMultiPoint or \ - eGType == ogr.wkbMultiLineString or \ - eGType == ogr.wkbMultiPolygon or \ - eGType == ogr.wkbGeometryCollection: + elif ( + eGType == ogr.wkbPolygon + or eGType == ogr.wkbMultiPoint + or eGType == ogr.wkbMultiLineString + or eGType == ogr.wkbMultiPolygon + or eGType == ogr.wkbGeometryCollection + ): for i in range(poGeom.GetGeometryCount()): SetZ(poGeom.GetGeometryRef(i), dfZ) -#********************************************************************** + +# ********************************************************************** # SetupTargetLayer() -#********************************************************************** +# ********************************************************************** -def SetupTargetLayer( poSrcDS, poSrcLayer, poDstDS, papszLCO, pszNewLayerName, \ - bTransform, poOutputSRS, bNullifyOutputSRS, poSourceSRS, papszSelFields, \ - bAppend, eGType, bPromoteToMulti, nCoordDim, bOverwrite, \ - papszFieldTypesToString, bWrapDateline, \ - bExplodeCollections, pszZField, pszWHERE) : +def SetupTargetLayer( + poSrcDS, + poSrcLayer, + poDstDS, + papszLCO, + pszNewLayerName, + bTransform, + poOutputSRS, + bNullifyOutputSRS, + poSourceSRS, + papszSelFields, + bAppend, + eGType, + bPromoteToMulti, + nCoordDim, + bOverwrite, + papszFieldTypesToString, + bWrapDateline, + bExplodeCollections, + pszZField, + pszWHERE, +): + if pszNewLayerName is None: pszNewLayerName = poSrcLayer.GetLayerDefn().GetName() -# -------------------------------------------------------------------- -# Setup coordinate transformation if we need it. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Setup coordinate transformation if we need it. + # -------------------------------------------------------------------- poCT = None if bTransform: if poSourceSRS is None: poSourceSRS = poSrcLayer.GetSpatialRef() if poSourceSRS is None: - print("Can't transform coordinates, source layer has no\n" + \ - "coordinate system. Use -s_srs to set one." ) + print( + "Can't transform coordinates, source layer has no\n" + + "coordinate system. Use -s_srs to set one." + ) return None - poCT = osr.CoordinateTransformation( poSourceSRS, poOutputSRS ) - if gdal.GetLastErrorMsg().find( 'Unable to load PROJ.4 library' ) != -1: + poCT = osr.CoordinateTransformation(poSourceSRS, poOutputSRS) + if gdal.GetLastErrorMsg().find("Unable to load PROJ.4 library") != -1: poCT = None if poCT is None: pszWKT = None - print("Failed to create coordinate transformation between the\n" + \ - "following coordinate systems. This may be because they\n" + \ - "are not transformable, or because projection services\n" + \ - "(PROJ.4 DLL/.so) could not be loaded." ) + print( + "Failed to create coordinate transformation between the\n" + + "following coordinate systems. This may be because they\n" + + "are not transformable, or because projection services\n" + + "(PROJ.4 DLL/.so) could not be loaded." + ) - pszWKT = poSourceSRS.ExportToPrettyWkt( 0 ) - print( "Source:\n" + pszWKT ) + pszWKT = poSourceSRS.ExportToPrettyWkt(0) + print("Source:\n" + pszWKT) - pszWKT = poOutputSRS.ExportToPrettyWkt( 0 ) - print( "Target:\n" + pszWKT ) + pszWKT = poOutputSRS.ExportToPrettyWkt(0) + print("Target:\n" + pszWKT) return None -# -------------------------------------------------------------------- -# Get other info. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Get other info. + # -------------------------------------------------------------------- poSrcFDefn = poSrcLayer.GetLayerDefn() if poOutputSRS is None and not bNullifyOutputSRS: poOutputSRS = poSrcLayer.GetSpatialRef() -# -------------------------------------------------------------------- -# Find the layer. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Find the layer. + # -------------------------------------------------------------------- # GetLayerByName() can instantiate layers that would have been # 'hidden' otherwise, for example, non-spatial tables in a # PostGIS-enabled database, so this apparently useless command is # not useless. (#4012) - gdal.PushErrorHandler('CPLQuietErrorHandler') + gdal.PushErrorHandler("CPLQuietErrorHandler") poDstLayer = poDstDS.GetLayerByName(pszNewLayerName) gdal.PopErrorHandler() gdal.ErrorReset() @@ -1255,29 +1419,28 @@ poLayer = poDstDS.GetLayer(iLayer) # The .cpp version compares on pointers directly, but we cannot # do this with swig object, so just compare the names. - if poLayer is not None \ - and poLayer.GetName() == poDstLayer.GetName(): + if poLayer is not None and poLayer.GetName() == poDstLayer.GetName(): break - if (iLayer == nLayerCount): + if iLayer == nLayerCount: # Shouldn't happen with an ideal driver poDstLayer = None -# -------------------------------------------------------------------- -# If the user requested overwrite, and we have the layer in -# question we need to delete it now so it will get recreated -# (overwritten). -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # If the user requested overwrite, and we have the layer in + # question we need to delete it now so it will get recreated + # (overwritten). + # -------------------------------------------------------------------- if poDstLayer is not None and bOverwrite: - if poDstDS.DeleteLayer( iLayer ) != 0: - print("DeleteLayer() failed when overwrite requested." ) + if poDstDS.DeleteLayer(iLayer) != 0: + print("DeleteLayer() failed when overwrite requested.") return None poDstLayer = None -# -------------------------------------------------------------------- -# If the layer does not exist, then create it. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # If the layer does not exist, then create it. + # -------------------------------------------------------------------- if poDstLayer is None: if eGType == -2: eGType = poSrcFDefn.GetGeomType() @@ -1307,42 +1470,51 @@ elif nCoordDim == 3: eGType = eGType | ogr.wkb25DBit - if poDstDS.TestCapability( ogr.ODsCCreateLayer ) == False: - print("Layer " + pszNewLayerName + "not found, and CreateLayer not supported by driver.") + if poDstDS.TestCapability(ogr.ODsCCreateLayer) == False: + print( + "Layer " + + pszNewLayerName + + "not found, and CreateLayer not supported by driver." + ) return None gdal.ErrorReset() - poDstLayer = poDstDS.CreateLayer( pszNewLayerName, poOutputSRS, \ - eGType, papszLCO ) + poDstLayer = poDstDS.CreateLayer(pszNewLayerName, poOutputSRS, eGType, papszLCO) if poDstLayer is None: return None bAppend = False -# -------------------------------------------------------------------- -# Otherwise we will append to it, if append was requested. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Otherwise we will append to it, if append was requested. + # -------------------------------------------------------------------- elif not bAppend: - print("FAILED: Layer " + pszNewLayerName + "already exists, and -append not specified.\n" + \ - " Consider using -append, or -overwrite.") + print( + "FAILED: Layer " + + pszNewLayerName + + "already exists, and -append not specified.\n" + + " Consider using -append, or -overwrite." + ) return None else: if len(papszLCO) > 0: - print("WARNING: Layer creation options ignored since an existing layer is\n" + \ - " being appended to." ) + print( + "WARNING: Layer creation options ignored since an existing layer is\n" + + " being appended to." + ) -# -------------------------------------------------------------------- -# Add fields. Default to copy all field. -# If only a subset of all fields requested, then output only -# the selected fields, and in the order that they were -# selected. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Add fields. Default to copy all field. + # If only a subset of all fields requested, then output only + # the selected fields, and in the order that they were + # selected. + # -------------------------------------------------------------------- # Initialize the index-to-index map to -1's nSrcFieldCount = poSrcFDefn.GetFieldCount() - panMap = [ -1 for i in range(nSrcFieldCount) ] + panMap = [-1 for i in range(nSrcFieldCount)] poDstFDefn = poDstLayer.GetLayerDefn() @@ -1357,15 +1529,20 @@ iSrcField = poSrcFDefn.GetFieldIndex(papszSelFields[iField]) if iSrcField >= 0: poSrcFieldDefn = poSrcFDefn.GetFieldDefn(iSrcField) - oFieldDefn = ogr.FieldDefn( poSrcFieldDefn.GetNameRef(), - poSrcFieldDefn.GetType() ) - oFieldDefn.SetWidth( poSrcFieldDefn.GetWidth() ) - oFieldDefn.SetPrecision( poSrcFieldDefn.GetPrecision() ) + oFieldDefn = ogr.FieldDefn( + poSrcFieldDefn.GetNameRef(), poSrcFieldDefn.GetType() + ) + oFieldDefn.SetWidth(poSrcFieldDefn.GetWidth()) + oFieldDefn.SetPrecision(poSrcFieldDefn.GetPrecision()) - if papszFieldTypesToString is not None and \ - (CSLFindString(papszFieldTypesToString, "All") != -1 or \ - CSLFindString(papszFieldTypesToString, \ - ogr.GetFieldTypeName(poSrcFieldDefn.GetType())) != -1): + if papszFieldTypesToString is not None and ( + CSLFindString(papszFieldTypesToString, "All") != -1 + or CSLFindString( + papszFieldTypesToString, + ogr.GetFieldTypeName(poSrcFieldDefn.GetType()), + ) + != -1 + ): oFieldDefn.SetType(ogr.OFTString) @@ -1375,21 +1552,28 @@ iDstField = poDstFDefn.GetFieldIndex(oFieldDefn.GetNameRef()) if iDstField >= 0: panMap[iSrcField] = iDstField - elif poDstLayer.CreateField( oFieldDefn ) == 0: + elif poDstLayer.CreateField(oFieldDefn) == 0: # now that we've created a field, GetLayerDefn() won't return NULL if poDstFDefn is None: poDstFDefn = poDstLayer.GetLayerDefn() # Sanity check : if it fails, the driver is buggy - if poDstFDefn is not None and \ - poDstFDefn.GetFieldCount() != nDstFieldCount + 1: - print("The output driver has claimed to have added the %s field, but it did not!" % oFieldDefn.GetNameRef() ) + if ( + poDstFDefn is not None + and poDstFDefn.GetFieldCount() != nDstFieldCount + 1 + ): + print( + "The output driver has claimed to have added the %s field, but it did not!" + % oFieldDefn.GetNameRef() + ) else: panMap[iSrcField] = nDstFieldCount nDstFieldCount = nDstFieldCount + 1 else: - print("Field '" + papszSelFields[iField] + "' not found in source layer.") + print( + "Field '" + papszSelFields[iField] + "' not found in source layer." + ) if not bSkipFailures: return None @@ -1428,33 +1612,43 @@ for iField in range(nSrcFieldCount): poSrcFieldDefn = poSrcFDefn.GetFieldDefn(iField) - oFieldDefn = ogr.FieldDefn( poSrcFieldDefn.GetNameRef(), - poSrcFieldDefn.GetType() ) - oFieldDefn.SetWidth( poSrcFieldDefn.GetWidth() ) - oFieldDefn.SetPrecision( poSrcFieldDefn.GetPrecision() ) + oFieldDefn = ogr.FieldDefn( + poSrcFieldDefn.GetNameRef(), poSrcFieldDefn.GetType() + ) + oFieldDefn.SetWidth(poSrcFieldDefn.GetWidth()) + oFieldDefn.SetPrecision(poSrcFieldDefn.GetPrecision()) - if papszFieldTypesToString is not None and \ - (CSLFindString(papszFieldTypesToString, "All") != -1 or \ - CSLFindString(papszFieldTypesToString, \ - ogr.GetFieldTypeName(poSrcFieldDefn.GetType())) != -1): + if papszFieldTypesToString is not None and ( + CSLFindString(papszFieldTypesToString, "All") != -1 + or CSLFindString( + papszFieldTypesToString, + ogr.GetFieldTypeName(poSrcFieldDefn.GetType()), + ) + != -1 + ): oFieldDefn.SetType(ogr.OFTString) # The field may have been already created at layer creation iDstField = -1 if poDstFDefn is not None: - iDstField = poDstFDefn.GetFieldIndex(oFieldDefn.GetNameRef()) + iDstField = poDstFDefn.GetFieldIndex(oFieldDefn.GetNameRef()) if iDstField >= 0: panMap[iField] = iDstField - elif poDstLayer.CreateField( oFieldDefn ) == 0: + elif poDstLayer.CreateField(oFieldDefn) == 0: # now that we've created a field, GetLayerDefn() won't return NULL if poDstFDefn is None: poDstFDefn = poDstLayer.GetLayerDefn() # Sanity check : if it fails, the driver is buggy - if poDstFDefn is not None and \ - poDstFDefn.GetFieldCount() != nDstFieldCount + 1: - print("The output driver has claimed to have added the %s field, but it did not!" % oFieldDefn.GetNameRef() ) + if ( + poDstFDefn is not None + and poDstFDefn.GetFieldCount() != nDstFieldCount + 1 + ): + print( + "The output driver has claimed to have added the %s field, but it did not!" + % oFieldDefn.GetNameRef() + ) else: panMap[iField] = nDstFieldCount nDstFieldCount = nDstFieldCount + 1 @@ -1463,7 +1657,7 @@ # For an existing layer, build the map by fetching the index in the destination # layer for each source field if poDstFDefn is None: - print( "poDstFDefn == NULL.\n" ) + print("poDstFDefn == NULL.\n") return None for iField in range(nSrcFieldCount): @@ -1479,29 +1673,46 @@ psInfo = TargetLayerInfo() psInfo.poDstLayer = poDstLayer psInfo.poCT = poCT - #psInfo.papszTransformOptions = papszTransformOptions + # psInfo.papszTransformOptions = papszTransformOptions psInfo.panMap = panMap psInfo.iSrcZField = iSrcZField return psInfo -#********************************************************************** + +# ********************************************************************** # TranslateLayer() -#********************************************************************** +# ********************************************************************** -def TranslateLayer( psInfo, poSrcDS, poSrcLayer, poDstDS, \ - poOutputSRS, bNullifyOutputSRS, \ - eGType, bPromoteToMulti, nCoordDim, eGeomOp, dfGeomOpParam, \ - nCountLayerFeatures, \ - poClipSrc, poClipDst, bExplodeCollections, nSrcFileSize, \ - pnReadFeatureCount, pfnProgress, pProgressArg) : +def TranslateLayer( + psInfo, + poSrcDS, + poSrcLayer, + poDstDS, + poOutputSRS, + bNullifyOutputSRS, + eGType, + bPromoteToMulti, + nCoordDim, + eGeomOp, + dfGeomOpParam, + nCountLayerFeatures, + poClipSrc, + poClipDst, + bExplodeCollections, + nSrcFileSize, + pnReadFeatureCount, + pfnProgress, + pProgressArg, +): + bForceToPolygon = False bForceToMultiPolygon = False bForceToMultiLineString = False poDstLayer = psInfo.poDstLayer - #papszTransformOptions = psInfo.papszTransformOptions + # papszTransformOptions = psInfo.papszTransformOptions poCT = psInfo.poCT panMap = psInfo.panMap iSrcZField = psInfo.iSrcZField @@ -1516,9 +1727,9 @@ elif wkbFlatten(eGType) == ogr.wkbMultiLineString: bForceToMultiLineString = True -# -------------------------------------------------------------------- -# Transfer features. -# -------------------------------------------------------------------- + # -------------------------------------------------------------------- + # Transfer features. + # -------------------------------------------------------------------- nFeaturesInTransaction = 0 nCount = 0 @@ -1530,7 +1741,7 @@ if nFIDToFetch != ogr.NullFID: - #// Only fetch feature on first pass. + # // Only fetch feature on first pass. if nFeaturesInTransaction == 0: poFeature = poSrcLayer.GetFeature(nFIDToFetch) else: @@ -1548,14 +1759,16 @@ poSrcGeometry = poFeature.GetGeometryRef() if poSrcGeometry is not None: eSrcType = wkbFlatten(poSrcGeometry.GetGeometryType()) - if eSrcType == ogr.wkbMultiPoint or \ - eSrcType == ogr.wkbMultiLineString or \ - eSrcType == ogr.wkbMultiPolygon or \ - eSrcType == ogr.wkbGeometryCollection: - nParts = poSrcGeometry.GetGeometryCount() - nIters = nParts - if nIters == 0: - nIters = 1 + if ( + eSrcType == ogr.wkbMultiPoint + or eSrcType == ogr.wkbMultiLineString + or eSrcType == ogr.wkbMultiPolygon + or eSrcType == ogr.wkbGeometryCollection + ): + nParts = poSrcGeometry.GetGeometryCount() + nIters = nParts + if nIters == 0: + nIters = 1 for iPart in range(nIters): nFeaturesInTransaction = nFeaturesInTransaction + 1 @@ -1565,19 +1778,22 @@ nFeaturesInTransaction = 0 gdal.ErrorReset() - poDstFeature = ogr.Feature( poDstLayer.GetLayerDefn() ) + poDstFeature = ogr.Feature(poDstLayer.GetLayerDefn()) - if poDstFeature.SetFromWithMap( poFeature, 1, panMap ) != 0: + if poDstFeature.SetFromWithMap(poFeature, 1, panMap) != 0: if nGroupTransactions > 0: poDstLayer.CommitTransaction() - print("Unable to translate feature %d from layer %s" % (poFeature.GetFID() , poSrcLayer.GetName() )) + print( + "Unable to translate feature %d from layer %s" + % (poFeature.GetFID(), poSrcLayer.GetName()) + ) return False if bPreserveFID: - poDstFeature.SetFID( poFeature.GetFID() ) + poDstFeature.SetFID(poFeature.GetFID()) poDstGeometry = poDstFeature.GetGeometryRef() if poDstGeometry is not None: @@ -1595,15 +1811,17 @@ poDstFeature.SetGeometryDirectly(poDupGeometry) poDstGeometry = poDupGeometry - if nCoordDim == 2 or nCoordDim == 3: - poDstGeometry.SetCoordinateDimension( nCoordDim ) + poDstGeometry.SetCoordinateDimension(nCoordDim) if eGeomOp == GeomOperation.SEGMENTIZE: pass - #if (poDstFeature.GetGeometryRef() is not None and dfGeomOpParam > 0) + # if (poDstFeature.GetGeometryRef() is not None and dfGeomOpParam > 0) # poDstFeature.GetGeometryRef().segmentize(dfGeomOpParam); - elif eGeomOp == GeomOperation.SIMPLIFY_PRESERVE_TOPOLOGY and dfGeomOpParam > 0: + elif ( + eGeomOp == GeomOperation.SIMPLIFY_PRESERVE_TOPOLOGY + and dfGeomOpParam > 0 + ): poNewGeom = poDstGeometry.SimplifyPreserveTopology(dfGeomOpParam) if poNewGeom is not None: poDstFeature.SetGeometryDirectly(poNewGeom) @@ -1613,21 +1831,26 @@ poClipped = poDstGeometry.Intersection(poClipSrc) if poClipped is None or poClipped.IsEmpty(): # Report progress - nCount = nCount +1 + nCount = nCount + 1 if pfnProgress is not None: - pfnProgress(nCount * 1.0 / nCountLayerFeatures, "", pProgressArg) + pfnProgress( + nCount * 1.0 / nCountLayerFeatures, "", pProgressArg + ) continue poDstFeature.SetGeometryDirectly(poClipped) poDstGeometry = poClipped if poCT is not None: - eErr = poDstGeometry.Transform( poCT ) + eErr = poDstGeometry.Transform(poCT) if eErr != 0: if nGroupTransactions > 0: poDstLayer.CommitTransaction() - print("Failed to reproject feature %d (geometry probably out of source or destination SRS)." % poFeature.GetFID()) + print( + "Failed to reproject feature %d (geometry probably out of source or destination SRS)." + % poFeature.GetFID() + ) if not bSkipFailures: return False @@ -1645,23 +1868,31 @@ if bForceToPolygon: poDstFeature.SetGeometryDirectly(ogr.ForceToPolygon(poDstGeometry)) - elif bForceToMultiPolygon or \ - (bPromoteToMulti and wkbFlatten(poDstGeometry.GetGeometryType()) == ogr.wkbPolygon): - poDstFeature.SetGeometryDirectly(ogr.ForceToMultiPolygon(poDstGeometry)) + elif bForceToMultiPolygon or ( + bPromoteToMulti + and wkbFlatten(poDstGeometry.GetGeometryType()) == ogr.wkbPolygon + ): + poDstFeature.SetGeometryDirectly( + ogr.ForceToMultiPolygon(poDstGeometry) + ) - elif bForceToMultiLineString or \ - (bPromoteToMulti and wkbFlatten(poDstGeometry.GetGeometryType()) == ogr.wkbLineString): - poDstFeature.SetGeometryDirectly(ogr.ForceToMultiLineString(poDstGeometry)) + elif bForceToMultiLineString or ( + bPromoteToMulti + and wkbFlatten(poDstGeometry.GetGeometryType()) == ogr.wkbLineString + ): + poDstFeature.SetGeometryDirectly( + ogr.ForceToMultiLineString(poDstGeometry) + ) gdal.ErrorReset() - if poDstLayer.CreateFeature( poDstFeature ) != 0 and not bSkipFailures: + if poDstLayer.CreateFeature(poDstFeature) != 0 and not bSkipFailures: if nGroupTransactions > 0: poDstLayer.RollbackTransaction() return False # Report progress - nCount = nCount + 1 + nCount = nCount + 1 if pfnProgress is not None: if nSrcFileSize != 0: if (nCount % 1000) == 0: @@ -1671,7 +1902,9 @@ if poFeat is not None: pszReadSize = poFeat.GetFieldAsString(0) nReadSize = int(pszReadSize) - pfnProgress(nReadSize * 1.0 / nSrcFileSize, "", pProgressArg) + pfnProgress( + nReadSize * 1.0 / nSrcFileSize, "", pProgressArg + ) poSrcDS.ReleaseResultSet(poFCLayer) else: pfnProgress(nCount * 1.0 / nCountLayerFeatures, "", pProgressArg) @@ -1684,10 +1917,11 @@ return True -if __name__ == '__main__': - version_num = int(gdal.VersionInfo('VERSION_NUM')) - if version_num < 1800: # because of ogr.GetFieldTypeName - print('ERROR: Python bindings of GDAL 1.8.0 or later required') + +if __name__ == "__main__": + version_num = int(gdal.VersionInfo("VERSION_NUM")) + if version_num < 1800: # because of ogr.GetFieldTypeName + print("ERROR: Python bindings of GDAL 1.8.0 or later required") sys.exit(1) if not main(sys.argv): Index: wflow-py/wflow/pcrglobwb/groundwater.py =================================================================== diff -u -r2d84b2c3f986344e96a4fa357e54dd77fe817fe4 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/pcrglobwb/groundwater.py (.../groundwater.py) (revision 2d84b2c3f986344e96a4fa357e54dd77fe817fe4) +++ wflow-py/wflow/pcrglobwb/groundwater.py (.../groundwater.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -30,29 +30,36 @@ import pcraster as pcr import logging -logger = logging.getLogger('wflow_pcrglobwb') +logger = logging.getLogger("wflow_pcrglobwb") + import virtualOS as vos from ncConverter import * from wflow.wf_DynamicFramework import configsection from wflow.wf_DynamicFramework import configget + class Groundwater(object): - def getState(self): result = {} - result['storGroundwater'] = self.storGroundwater # unit: m - result['storGroundwaterFossil'] = self.storGroundwaterFossil # unit: m - result['avgTotalGroundwaterAbstraction'] = self.avgAbstraction # unit: m/day - result['avgTotalGroundwaterAllocationLong'] = self.avgAllocation # unit: m/day - result['avgTotalGroundwaterAllocationShort'] = self.avgAllocationShort # unit: m/day - result['avgNonFossilGroundwaterAllocationLong'] = self.avgNonFossilAllocation # unit: m/day - result['avgNonFossilGroundwaterAllocationShort'] = self.avgNonFossilAllocationShort # unit: m/day + result["storGroundwater"] = self.storGroundwater # unit: m + result["storGroundwaterFossil"] = self.storGroundwaterFossil # unit: m + result["avgTotalGroundwaterAbstraction"] = self.avgAbstraction # unit: m/day + result["avgTotalGroundwaterAllocationLong"] = self.avgAllocation # unit: m/day + result[ + "avgTotalGroundwaterAllocationShort" + ] = self.avgAllocationShort # unit: m/day + result[ + "avgNonFossilGroundwaterAllocationLong" + ] = self.avgNonFossilAllocation # unit: m/day + result[ + "avgNonFossilGroundwaterAllocationShort" + ] = self.avgNonFossilAllocationShort # unit: m/day # states that needed for the coupling between PCR-GLOBWB and MODFLOW: - result['relativeGroundwaterHead'] = self.relativeGroundwaterHead # unit: m - result['baseflow'] = self.baseflow # unit: m/day + result["relativeGroundwaterHead"] = self.relativeGroundwaterHead # unit: m + result["baseflow"] = self.baseflow # unit: m/day return result @@ -61,33 +68,51 @@ return result - def __init__(self, iniItems,landmask,spinUp,Dir, staticmaps, cloneMap): + def __init__(self, iniItems, landmask, spinUp, Dir, staticmaps, cloneMap): object.__init__(self) - self.cloneMap = cloneMap #iniItems.cloneMap - self.tmpDir = os.path.join(os.path.abspath(Dir),"tmp") #iniItems.tmpDir - self.inputDir = os.path.join(os.path.abspath(Dir),staticmaps) #iniItems.globalOptions['inputDir'] + self.cloneMap = cloneMap # iniItems.cloneMap + self.tmpDir = os.path.join(os.path.abspath(Dir), "tmp") # iniItems.tmpDir + self.inputDir = os.path.join( + os.path.abspath(Dir), staticmaps + ) # iniItems.globalOptions['inputDir'] self.landmask = landmask # configuration from the ini file self.iniItems = iniItems # option to activate a water balance check self.debugWaterBalance = True - if configget(iniItems,"routingOptions","debugWaterBalance","True") == "False": self.debugWaterBalance = False + if ( + configget(iniItems, "routingOptions", "debugWaterBalance", "True") + == "False" + ): + self.debugWaterBalance = False self.useMODFLOW = False - if configget(iniItems,"groundwaterOptions","useMODFLOW","False") == "True": self.useMODFLOW = True + if configget(iniItems, "groundwaterOptions", "useMODFLOW", "False") == "True": + self.useMODFLOW = True - ##################################################################################################################################################### # limitAbstraction options self.limitAbstraction = False - if configget(iniItems,"landSurfaceOptions","limitAbstraction","False") == "True": self.limitAbstraction = True + if ( + configget(iniItems, "landSurfaceOptions", "limitAbstraction", "False") + == "True" + ): + self.limitAbstraction = True # option for limitting fossil groundwater abstractions: self.limitFossilGroundwaterAbstraction = False - if configget(iniItems,"groundwaterOptions","limitFossilGroundWaterAbstraction","False") == "True": + if ( + configget( + iniItems, + "groundwaterOptions", + "limitFossilGroundWaterAbstraction", + "False", + ) + == "True" + ): self.limitFossilGroundwaterAbstraction = True # if using MODFLOW, limitAbstraction must be True (the abstraction cannot exceed storGroundwater, the concept of fossil groundwater is abandoned) @@ -96,487 +121,835 @@ self.limitFossilGroundwaterAbstraction = False # option for limitting regional groundwater abstractions - if configget(iniItems,"groundwaterOptions","pumpingCapacityNC","None") != "None": - logger.info('Limit for annual regional groundwater abstraction is used.') + if ( + configget(iniItems, "groundwaterOptions", "pumpingCapacityNC", "None") + != "None" + ): + logger.info("Limit for annual regional groundwater abstraction is used.") self.limitRegionalAnnualGroundwaterAbstraction = True - self.pumpingCapacityNC = vos.getFullPath(\ - iniItems.get("groundwaterOptions","pumpingCapacityNC"),self.inputDir,False) + self.pumpingCapacityNC = vos.getFullPath( + iniItems.get("groundwaterOptions", "pumpingCapacityNC"), + self.inputDir, + False, + ) else: - logger.warning('NO LIMIT for regional groundwater (annual) pumping. It may result too high groundwater abstraction.') + logger.warning( + "NO LIMIT for regional groundwater (annual) pumping. It may result too high groundwater abstraction." + ) self.limitRegionalAnnualGroundwaterAbstraction = False ##################################################################################################################################################### - ###################################################################################### # a netcdf file containing the groundwater properties - if configget(iniItems,"groundwaterOptions","groundwaterPropertiesNC","None") != "None": - groundwaterPropertiesNC = vos.getFullPath(\ - iniItems.get("groundwaterOptions"\ - ,"groundwaterPropertiesNC"),self.inputDir) + if ( + configget(iniItems, "groundwaterOptions", "groundwaterPropertiesNC", "None") + != "None" + ): + groundwaterPropertiesNC = vos.getFullPath( + iniItems.get("groundwaterOptions", "groundwaterPropertiesNC"), + self.inputDir, + ) ###################################################################################### - ##################################################################################################################################################### # assign aquifer specific yield (dimensionless) - if configget(iniItems,"groundwaterOptions","groundwaterPropertiesNC","None") == "None" or 'specificYield' in iniItems._sections["groundwaterOptions"]: - self.specificYield = vos.readPCRmapClone(\ - iniItems.get("groundwaterOptions","specificYield"),self.cloneMap,self.tmpDir,self.inputDir) + if ( + configget(iniItems, "groundwaterOptions", "groundwaterPropertiesNC", "None") + == "None" + or "specificYield" in iniItems._sections["groundwaterOptions"] + ): + self.specificYield = vos.readPCRmapClone( + iniItems.get("groundwaterOptions", "specificYield"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) else: - self.specificYield = vos.netcdf2PCRobjCloneWithoutTime(\ - groundwaterPropertiesNC,'specificYield',self.cloneMap) - self.specificYield = pcr.cover(self.specificYield,0.0) - self.specificYield = pcr.max(0.010,self.specificYield) # TODO: Set the minimum values of specific yield. - self.specificYield = pcr.min(1.000,self.specificYield) + self.specificYield = vos.netcdf2PCRobjCloneWithoutTime( + groundwaterPropertiesNC, "specificYield", self.cloneMap + ) + self.specificYield = pcr.cover(self.specificYield, 0.0) + self.specificYield = pcr.max( + 0.010, self.specificYield + ) # TODO: Set the minimum values of specific yield. + self.specificYield = pcr.min(1.000, self.specificYield) ##################################################################################################################################################### - ##################################################################################################################################################### # assign aquifer hydraulic conductivity (unit: m/day) - if configget(iniItems,"groundwaterOptions","groundwaterPropertiesNC","None") == "None" or 'kSatAquifer' in iniItems._sections['groundwaterOptions']: - self.kSatAquifer = vos.readPCRmapClone(\ - iniItems.get("groundwaterOptions","kSatAquifer"),self.cloneMap,self.tmpDir,self.inputDir) + if ( + configget(iniItems, "groundwaterOptions", "groundwaterPropertiesNC", "None") + == "None" + or "kSatAquifer" in iniItems._sections["groundwaterOptions"] + ): + self.kSatAquifer = vos.readPCRmapClone( + iniItems.get("groundwaterOptions", "kSatAquifer"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) else: - self.kSatAquifer = vos.netcdf2PCRobjCloneWithoutTime(\ - groundwaterPropertiesNC,'kSatAquifer',self.cloneMap) - self.kSatAquifer = pcr.cover(self.kSatAquifer,0.0) - self.kSatAquifer = pcr.max(0.010,self.kSatAquifer) + self.kSatAquifer = vos.netcdf2PCRobjCloneWithoutTime( + groundwaterPropertiesNC, "kSatAquifer", self.cloneMap + ) + self.kSatAquifer = pcr.cover(self.kSatAquifer, 0.0) + self.kSatAquifer = pcr.max(0.010, self.kSatAquifer) ##################################################################################################################################################### - ##################################################################################################################################################### # try to assign the reccesion coefficient (unit: day-1) from the netcdf file of groundwaterPropertiesNC try: - self.recessionCoeff = vos.netcdf2PCRobjCloneWithoutTime(\ - groundwaterPropertiesNC,'recessionCoeff',\ - cloneMapFileName = self.cloneMap) + self.recessionCoeff = vos.netcdf2PCRobjCloneWithoutTime( + groundwaterPropertiesNC, + "recessionCoeff", + cloneMapFileName=self.cloneMap, + ) except: self.recessionCoeff = None - msg = "The 'recessionCoeff' cannot be read from the file: "+groundwaterPropertiesNC + msg = ( + "The 'recessionCoeff' cannot be read from the file: " + + groundwaterPropertiesNC + ) logger.warning(msg) # assign the reccession coefficient based on the given pcraster file - if 'recessionCoeff' in iniItems._sections['groundwaterOptions']: - if configget(iniItems,"groundwaterOptions","recessionCoeff","None") != "None":\ - self.recessionCoeff = vos.readPCRmapClone(iniItems.get("groundwaterOptions","recessionCoeff"),self.cloneMap,self.tmpDir,self.inputDir) + if "recessionCoeff" in iniItems._sections["groundwaterOptions"]: + if ( + configget(iniItems, "groundwaterOptions", "recessionCoeff", "None") + != "None" + ): + self.recessionCoeff = vos.readPCRmapClone( + iniItems.get("groundwaterOptions", "recessionCoeff"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) # calculate the reccession coefficient based on the given parameters - if isinstance(self.recessionCoeff,types.NoneType) and\ - 'recessionCoeff' not in iniItems._sections['groundwaterOptions']: + if ( + isinstance(self.recessionCoeff, types.NoneType) + and "recessionCoeff" not in iniItems._sections["groundwaterOptions"] + ): msg = "Calculating the groundwater linear reccesion coefficient based on the given parameters." logger.info(msg) # reading the 'aquiferWidth' value from the landSurfaceOptions (slopeLength) - if configget(iniItems,"landSurfaceOptions","topographyNC","None") == None: - aquiferWidth = vos.readPCRmapClone(iniItems.get("landSurfaceOptions","slopeLength"),self.cloneMap,self.tmpDir,self.inputDir) + if ( + configget(iniItems, "landSurfaceOptions", "topographyNC", "None") + == None + ): + aquiferWidth = vos.readPCRmapClone( + iniItems.get("landSurfaceOptions", "slopeLength"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) else: - topoPropertiesNC = vos.getFullPath(iniItems.get("landSurfaceOptions","topographyNC"),self.inputDir) - aquiferWidth = vos.netcdf2PCRobjCloneWithoutTime(topoPropertiesNC,'slopeLength',self.cloneMap) + topoPropertiesNC = vos.getFullPath( + iniItems.get("landSurfaceOptions", "topographyNC"), self.inputDir + ) + aquiferWidth = vos.netcdf2PCRobjCloneWithoutTime( + topoPropertiesNC, "slopeLength", self.cloneMap + ) # covering aquiferWidth with its maximum value - aquiferWidth = pcr.ifthen(self.landmask, pcr.cover(aquiferWidth, pcr.mapmaximum(aquiferWidth))) + aquiferWidth = pcr.ifthen( + self.landmask, pcr.cover(aquiferWidth, pcr.mapmaximum(aquiferWidth)) + ) # aquifer thickness (unit: m) for recession coefficient - aquiferThicknessForRecessionCoeff = vos.readPCRmapClone(iniItems.get("groundwaterOptions","aquiferThicknessForRecessionCoeff"),\ - self.cloneMap,self.tmpDir,self.inputDir) + aquiferThicknessForRecessionCoeff = vos.readPCRmapClone( + iniItems.get("groundwaterOptions", "aquiferThicknessForRecessionCoeff"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) # calculate recessionCoeff (unit; day-1) - self.recessionCoeff = (math.pi**2.) * aquiferThicknessForRecessionCoeff / \ - (4.*self.specificYield*(aquiferWidth**2.)) + self.recessionCoeff = ( + (math.pi ** 2.) + * aquiferThicknessForRecessionCoeff + / (4. * self.specificYield * (aquiferWidth ** 2.)) + ) # assign the reccession coefficient based on the given pcraster file - if 'recessionCoeff' in iniItems._sections['groundwaterOptions']: - if configget(iniItems,"groundwaterOptions","recessionCoeff","None") != "None":\ - self.recessionCoeff = vos.readPCRmapClone(iniItems.get("groundwaterOptions","recessionCoeff"),self.cloneMap,self.tmpDir,self.inputDir) + if "recessionCoeff" in iniItems._sections["groundwaterOptions"]: + if ( + configget(iniItems, "groundwaterOptions", "recessionCoeff", "None") + != "None" + ): + self.recessionCoeff = vos.readPCRmapClone( + iniItems.get("groundwaterOptions", "recessionCoeff"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) # minimum and maximum values for groundwater recession coefficient (day-1) - self.recessionCoeff = pcr.cover(self.recessionCoeff,0.00) - self.recessionCoeff = pcr.min(0.9999,self.recessionCoeff) - if 'minRecessionCoeff' in iniItems._sections['groundwaterOptions']: - minRecessionCoeff = float(iniItems.get("groundwaterOptions","minRecessionCoeff")) + self.recessionCoeff = pcr.cover(self.recessionCoeff, 0.00) + self.recessionCoeff = pcr.min(0.9999, self.recessionCoeff) + if "minRecessionCoeff" in iniItems._sections["groundwaterOptions"]: + minRecessionCoeff = float( + iniItems.get("groundwaterOptions", "minRecessionCoeff") + ) else: - minRecessionCoeff = 1.0e-4 # This is the minimum value used in Van Beek et al. (2011). - self.recessionCoeff = pcr.max(minRecessionCoeff,self.recessionCoeff) + minRecessionCoeff = ( + 1.0e-4 + ) # This is the minimum value used in Van Beek et al. (2011). + self.recessionCoeff = pcr.max(minRecessionCoeff, self.recessionCoeff) ##################################################################################################################################################### - ##################################################################################################################################################### # assign the river/stream/surface water bed conductivity # - the default value is equal to kSatAquifer self.riverBedConductivity = self.kSatAquifer # - assign riverBedConductivity coefficient based on the given pcraster file - if 'riverBedConductivity' in iniItems._sections['groundwaterOptions']: - if configget(iniItems,"groundwaterOptions","riverBedConductivity","None") != "None":\ - self.riverBedConductivity = vos.readPCRmapClone(iniItems.get("groundwaterOptions","riverBedConductivity"),self.cloneMap,self.tmpDir,self.inputDir) + if "riverBedConductivity" in iniItems._sections["groundwaterOptions"]: + if ( + configget( + iniItems, "groundwaterOptions", "riverBedConductivity", "None" + ) + != "None" + ): + self.riverBedConductivity = vos.readPCRmapClone( + iniItems.get("groundwaterOptions", "riverBedConductivity"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) ##################################################################################################################################################### - ##################################################################################################################################################### # total groundwater thickness (unit: m) # - For PCR-GLOBWB, the estimate of total groundwater thickness is needed to estimate for the following purpose: # - to estimate fossil groundwater capacity (this is needed only for runs without MODFLOW) # - to determine productive aquifer areas (where capillary rise can occur and groundwater depletion can occur) (for runs with/without MODFLOW) # - Note that for runs with MODFLOW, ideally, we want to minimize enormous drawdown in non-productive aquifer areas totalGroundwaterThickness = None - if 'estimateOfTotalGroundwaterThickness' in iniItems._sections['groundwaterOptions'] and\ - (self.limitFossilGroundwaterAbstraction or self.useMODFLOW): + if "estimateOfTotalGroundwaterThickness" in iniItems._sections[ + "groundwaterOptions" + ] and (self.limitFossilGroundwaterAbstraction or self.useMODFLOW): - totalGroundwaterThickness = vos.readPCRmapClone(iniItems.get("groundwaterOptions","estimateOfTotalGroundwaterThickness"), - self.cloneMap, self.tmpDir, self.inputDir) + totalGroundwaterThickness = vos.readPCRmapClone( + iniItems.get( + "groundwaterOptions", "estimateOfTotalGroundwaterThickness" + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) # extrapolation of totalGroundwaterThickness # - TODO: Make a general extrapolation option as a function in the virtualOS.py - totalGroundwaterThickness = pcr.cover(totalGroundwaterThickness, - pcr.windowaverage(totalGroundwaterThickness, 0.75)) - totalGroundwaterThickness = pcr.cover(totalGroundwaterThickness, - pcr.windowaverage(totalGroundwaterThickness, 0.75)) - totalGroundwaterThickness = pcr.cover(totalGroundwaterThickness, - pcr.windowaverage(totalGroundwaterThickness, 0.75)) - totalGroundwaterThickness = pcr.cover(totalGroundwaterThickness, - pcr.windowaverage(totalGroundwaterThickness, 1.00)) + totalGroundwaterThickness = pcr.cover( + totalGroundwaterThickness, + pcr.windowaverage(totalGroundwaterThickness, 0.75), + ) + totalGroundwaterThickness = pcr.cover( + totalGroundwaterThickness, + pcr.windowaverage(totalGroundwaterThickness, 0.75), + ) + totalGroundwaterThickness = pcr.cover( + totalGroundwaterThickness, + pcr.windowaverage(totalGroundwaterThickness, 0.75), + ) + totalGroundwaterThickness = pcr.cover( + totalGroundwaterThickness, + pcr.windowaverage(totalGroundwaterThickness, 1.00), + ) totalGroundwaterThickness = pcr.cover(totalGroundwaterThickness, 0.0) # set minimum thickness - if 'minimumTotalGroundwaterThickness' in iniItems._sections['groundwaterOptions']: - minimumThickness = pcr.scalar(float(\ - iniItems.get("groundwaterOptions","minimumTotalGroundwaterThickness"))) - totalGroundwaterThickness = pcr.max(minimumThickness, totalGroundwaterThickness) + if ( + "minimumTotalGroundwaterThickness" + in iniItems._sections["groundwaterOptions"] + ): + minimumThickness = pcr.scalar( + float( + iniItems.get( + "groundwaterOptions", "minimumTotalGroundwaterThickness" + ) + ) + ) + totalGroundwaterThickness = pcr.max( + minimumThickness, totalGroundwaterThickness + ) # set maximum thickness - if 'maximumTotalGroundwaterThickness' in iniItems._sections['groundwaterOptions'] and\ - (configget(iniItems,"groundwaterOptions","maximumTotalGroundwaterThickness","None") != "None"): - maximumThickness = float(iniItems.get("groundwaterOptions","maximumTotalGroundwaterThickness")) - totalGroundwaterThickness = pcr.min(maximumThickness, totalGroundwaterThickness) + if "maximumTotalGroundwaterThickness" in iniItems._sections[ + "groundwaterOptions" + ] and ( + configget( + iniItems, + "groundwaterOptions", + "maximumTotalGroundwaterThickness", + "None", + ) + != "None" + ): + maximumThickness = float( + iniItems.get( + "groundwaterOptions", "maximumTotalGroundwaterThickness" + ) + ) + totalGroundwaterThickness = pcr.min( + maximumThickness, totalGroundwaterThickness + ) # estimate of total groundwater thickness (unit: m) self.totalGroundwaterThickness = totalGroundwaterThickness ##################################################################################################################################################### - ##################################################################################################################################################### # extent of the productive aquifer (a boolean map) # - Principle: In non-productive aquifer areas, no capillary rise and groundwater abstraction should not exceed recharge # self.productive_aquifer = pcr.ifthen(self.landmask, pcr.boolean(1.0)) excludeUnproductiveAquifer = True if excludeUnproductiveAquifer: - if 'minimumTransmissivityForProductiveAquifer' in iniItems._sections['groundwaterOptions'] and\ - (configget(iniItems,"groundwaterOptions","minimumTransmissivityForProductiveAquifer","None") != "None" or\ - configget(iniItems,"groundwaterOptions","minimumTransmissivityForProductiveAquifer","False") != "False"): - minimumTransmissivityForProductiveAquifer = \ - vos.readPCRmapClone(iniItems.get("groundwaterOptions","minimumTransmissivityForProductiveAquifer"),\ - self.cloneMap, self.tmpDir, self.inputDir) - self.productive_aquifer = pcr.cover(\ - pcr.ifthen(self.kSatAquifer * totalGroundwaterThickness > minimumTransmissivityForProductiveAquifer, pcr.boolean(1.0)), pcr.boolean(0.0)) + if "minimumTransmissivityForProductiveAquifer" in iniItems._sections[ + "groundwaterOptions" + ] and ( + configget( + iniItems, + "groundwaterOptions", + "minimumTransmissivityForProductiveAquifer", + "None", + ) + != "None" + or configget( + iniItems, + "groundwaterOptions", + "minimumTransmissivityForProductiveAquifer", + "False", + ) + != "False" + ): + minimumTransmissivityForProductiveAquifer = vos.readPCRmapClone( + iniItems.get( + "groundwaterOptions", + "minimumTransmissivityForProductiveAquifer", + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.productive_aquifer = pcr.cover( + pcr.ifthen( + self.kSatAquifer * totalGroundwaterThickness + > minimumTransmissivityForProductiveAquifer, + pcr.boolean(1.0), + ), + pcr.boolean(0.0), + ) self.productive_aquifer = pcr.cover(self.productive_aquifer, pcr.boolean(0.0)) # - TODO: Check and re-calculate the GLHYMPS map to confirm the kSatAquifer value in groundwaterPropertiesNC (e.g. we miss some parts of HPA). ##################################################################################################################################################### - ##################################################################################################################################################### # estimate of fossil groundwater capacity (based on the aquifer thickness and specific yield) - if configget(iniItems,"groundwaterOptions","limitFossilGroundWaterAbstraction","False") == "True" and self.limitAbstraction == False: + if ( + configget( + iniItems, + "groundwaterOptions", + "limitFossilGroundWaterAbstraction", + "False", + ) + == "True" + and self.limitAbstraction == False + ): - logger.info('Fossil groundwater abstractions are allowed with LIMIT.') + logger.info("Fossil groundwater abstractions are allowed with LIMIT.") - logger.info('Estimating fossil groundwater capacities based on aquifer thicknesses and specific yield.') + logger.info( + "Estimating fossil groundwater capacities based on aquifer thicknesses and specific yield." + ) # TODO: Make the following aquifer thickness information can be used to define the extent of productive aquifer. # estimate of capacity (unit: m) of renewable groundwater (to correct the initial estimate of fossil groundwater capacity) # - this value is NOT relevant, but requested in the IWMI project - if 'estimateOfRenewableGroundwaterCapacity' not in iniItems._sections['groundwaterOptions']:\ - configset(iniItems,"groundwaterOptions","estimateOfRenewableGroundwaterCapacity","0.0") - storGroundwaterCap = pcr.cover( - vos.readPCRmapClone(\ - float(iniItems.get("groundwaterOptions","estimateOfRenewableGroundwaterCapacity")), - self.cloneMap,self.tmpDir,self.inputDir), 0.0) + if ( + "estimateOfRenewableGroundwaterCapacity" + not in iniItems._sections["groundwaterOptions"] + ): + configset( + iniItems, + "groundwaterOptions", + "estimateOfRenewableGroundwaterCapacity", + "0.0", + ) + storGroundwaterCap = pcr.cover( + vos.readPCRmapClone( + float( + iniItems.get( + "groundwaterOptions", + "estimateOfRenewableGroundwaterCapacity", + ) + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ), + 0.0, + ) # fossil groundwater capacity (unit: m) - self.fossilWaterCap = pcr.ifthen(self.landmask,\ - pcr.max(0.0,\ - totalGroundwaterThickness*self.specificYield - storGroundwaterCap)) + self.fossilWaterCap = pcr.ifthen( + self.landmask, + pcr.max( + 0.0, + totalGroundwaterThickness * self.specificYield - storGroundwaterCap, + ), + ) ##################################################################################################################################################### - ##################################################################################################################################################### # zones at which groundwater allocations are determined self.usingAllocSegments = False # - by default, it is consistent with the one defined in the landSurfaceOptions - if configget(iniItems,"landSurfaceOptions","allocationSegmentsForGroundSurfaceWater","None") not in ["None", "False"]: + if configget( + iniItems, + "landSurfaceOptions", + "allocationSegmentsForGroundSurfaceWater", + "None", + ) not in ["None", "False"]: self.usingAllocSegments = True - groundwaterAllocationSegments = iniItems.get("landSurfaceOptions","allocationSegmentsForGroundSurfaceWater") + groundwaterAllocationSegments = iniItems.get( + "landSurfaceOptions", "allocationSegmentsForGroundSurfaceWater" + ) # - yet, we can also define a specific one for groundwater - if "allocationSegmentsForGroundwater" in iniItems._sections['groundwaterOptions']: - if configget(iniItems,"groundwaterOptions","allocationSegmentsForGroundwater","None") not in ["None", "False"]: + if ( + "allocationSegmentsForGroundwater" + in iniItems._sections["groundwaterOptions"] + ): + if configget( + iniItems, + "groundwaterOptions", + "allocationSegmentsForGroundwater", + "None", + ) not in ["None", "False"]: self.usingAllocSegments = True - groundwaterAllocationSegments = iniItems.get("groundwaterOptions","allocationSegmentsForGroundwater") + groundwaterAllocationSegments = iniItems.get( + "groundwaterOptions", "allocationSegmentsForGroundwater" + ) else: self.usingAllocSegments = False else: self.usingAllocSegments = False ##################################################################################################################################################### - ##################################################################################################################################################### # incorporating groundwater distribution network: if self.usingAllocSegments: - self.allocSegments = vos.readPCRmapClone(\ - groundwaterAllocationSegments, - self.cloneMap,self.tmpDir,self.inputDir,isLddMap=False,cover=None,isNomMap=True) + self.allocSegments = vos.readPCRmapClone( + groundwaterAllocationSegments, + self.cloneMap, + self.tmpDir, + self.inputDir, + isLddMap=False, + cover=None, + isNomMap=True, + ) self.allocSegments = pcr.ifthen(self.landmask, self.allocSegments) - cellArea = vos.readPCRmapClone(\ - iniItems.get("routingOptions","cellAreaMap"), - self.cloneMap,self.tmpDir,self.inputDir) - cellArea = pcr.ifthen(self.landmask, cellArea) # TODO: integrate this one with the one coming from the routing module + cellArea = vos.readPCRmapClone( + iniItems.get("routingOptions", "cellAreaMap"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + cellArea = pcr.ifthen( + self.landmask, cellArea + ) # TODO: integrate this one with the one coming from the routing module - self.segmentArea = pcr.areatotal(pcr.cover(cellArea, 0.0), self.allocSegments) + self.segmentArea = pcr.areatotal( + pcr.cover(cellArea, 0.0), self.allocSegments + ) self.segmentArea = pcr.ifthen(self.landmask, self.segmentArea) ##################################################################################################################################################### - ##################################################################################################################################################### # maximumDailyGroundwaterAbstraction (unit: m/day) - in order to avoid over-abstraction of groundwater source - self.maximumDailyGroundwaterAbstraction = vos.readPCRmapClone(configget(iniItems,"groundwaterOptions","maximumDailyGroundwaterAbstraction","0.050"), - self.cloneMap,self.tmpDir,self.inputDir) + self.maximumDailyGroundwaterAbstraction = vos.readPCRmapClone( + configget( + iniItems, + "groundwaterOptions", + "maximumDailyGroundwaterAbstraction", + "0.050", + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) ##################################################################################################################################################### - ##################################################################################################################################################### # maximumDailyFossilGroundwaterAbstraction (unit: m/day) - in order to avoid over-abstraction of groundwater source - self.maximumDailyFossilGroundwaterAbstraction = vos.readPCRmapClone(configget(iniItems,"groundwaterOptions","maximumDailyFossilGroundwaterAbstraction","0.020"), - self.cloneMap,self.tmpDir,self.inputDir) + self.maximumDailyFossilGroundwaterAbstraction = vos.readPCRmapClone( + configget( + iniItems, + "groundwaterOptions", + "maximumDailyFossilGroundwaterAbstraction", + "0.020", + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) ##################################################################################################################################################### - # get the initial conditions - self.getICs(iniItems,spinUp) + self.getICs(iniItems, spinUp) # initiate old style reporting (this is useful for debugging) self.initiate_old_style_groundwater_reporting(iniItems) - def initiate_old_style_groundwater_reporting(self,iniItems): + def initiate_old_style_groundwater_reporting(self, iniItems): self.report = True try: - self.outDailyTotNC = iniItems.get("groundwaterOptions","outDailyTotNC").split(",") - self.outMonthTotNC = iniItems.get("groundwaterOptions","outMonthTotNC").split(",") - self.outMonthAvgNC = iniItems.get("groundwaterOptions","outMonthAvgNC").split(",") - self.outMonthEndNC = iniItems.get("groundwaterOptions","outMonthEndNC").split(",") - self.outAnnuaTotNC = iniItems.get("groundwaterOptions","outAnnuaTotNC").split(",") - self.outAnnuaAvgNC = iniItems.get("groundwaterOptions","outAnnuaAvgNC").split(",") - self.outAnnuaEndNC = iniItems.get("groundwaterOptions","outAnnuaEndNC").split(",") + self.outDailyTotNC = iniItems.get( + "groundwaterOptions", "outDailyTotNC" + ).split(",") + self.outMonthTotNC = iniItems.get( + "groundwaterOptions", "outMonthTotNC" + ).split(",") + self.outMonthAvgNC = iniItems.get( + "groundwaterOptions", "outMonthAvgNC" + ).split(",") + self.outMonthEndNC = iniItems.get( + "groundwaterOptions", "outMonthEndNC" + ).split(",") + self.outAnnuaTotNC = iniItems.get( + "groundwaterOptions", "outAnnuaTotNC" + ).split(",") + self.outAnnuaAvgNC = iniItems.get( + "groundwaterOptions", "outAnnuaAvgNC" + ).split(",") + self.outAnnuaEndNC = iniItems.get( + "groundwaterOptions", "outAnnuaEndNC" + ).split(",") except: self.report = False if self.report == True: - #include self.outNCDir in wflow_pcrgobwb? - self.outNCDir = vos.getFullPath("netcdf/", \ - iniItems.get("globalOptions","outputDir")) #iniItems.outNCDir + # include self.outNCDir in wflow_pcrgobwb? + self.outNCDir = vos.getFullPath( + "netcdf/", iniItems.get("globalOptions", "outputDir") + ) # iniItems.outNCDir self.netcdfObj = PCR2netCDF(iniItems) # # daily output in netCDF files: if self.outDailyTotNC[0] != "None": for var in self.outDailyTotNC: # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_dailyTot.nc",\ - var,"undefined") + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_dailyTot.nc", + var, + "undefined", + ) # MONTHly output in netCDF files: # - cummulative if self.outMonthTotNC[0] != "None": for var in self.outMonthTotNC: # initiating monthlyVarTot (accumulator variable): - vars(self)[var+'MonthTot'] = None + vars(self)[var + "MonthTot"] = None # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthTot.nc",\ - var,"undefined") + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthTot.nc", + var, + "undefined", + ) # - average if self.outMonthAvgNC[0] != "None": for var in self.outMonthAvgNC: # initiating monthlyTotAvg (accumulator variable) - vars(self)[var+'MonthTot'] = None + vars(self)[var + "MonthTot"] = None # initiating monthlyVarAvg: - vars(self)[var+'MonthAvg'] = None - # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthAvg.nc",\ - var,"undefined") + vars(self)[var + "MonthAvg"] = None + # creating the netCDF files: + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthAvg.nc", + var, + "undefined", + ) # - last day of the month if self.outMonthEndNC[0] != "None": for var in self.outMonthEndNC: - # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthEnd.nc",\ - var,"undefined") + # creating the netCDF files: + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthEnd.nc", + var, + "undefined", + ) # YEARly output in netCDF files: # - cummulative if self.outAnnuaTotNC[0] != "None": for var in self.outAnnuaTotNC: # initiating yearly accumulator variable: - vars(self)[var+'AnnuaTot'] = None + vars(self)[var + "AnnuaTot"] = None # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaTot.nc",\ - var,"undefined") + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaTot.nc", + var, + "undefined", + ) # - average if self.outAnnuaAvgNC[0] != "None": for var in self.outAnnuaAvgNC: # initiating annualyVarAvg: - vars(self)[var+'AnnuaAvg'] = None + vars(self)[var + "AnnuaAvg"] = None # initiating annualyTotAvg (accumulator variable) - vars(self)[var+'AnnuaTot'] = None - # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaAvg.nc",\ - var,"undefined") + vars(self)[var + "AnnuaTot"] = None + # creating the netCDF files: + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaAvg.nc", + var, + "undefined", + ) # - last day of the year if self.outAnnuaEndNC[0] != "None": for var in self.outAnnuaEndNC: - # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaEnd.nc",\ - var,"undefined") + # creating the netCDF files: + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaEnd.nc", + var, + "undefined", + ) - def getICs(self,iniItems,iniConditions = None): + def getICs(self, iniItems, iniConditions=None): self.initialize_states(iniItems, iniConditions) def initialize_states(self, iniItems, iniConditions): # initial conditions (unit: m) - if iniConditions == None: # when the model just start (reading the initial conditions from file) + if ( + iniConditions == None + ): # when the model just start (reading the initial conditions from file) + self.storGroundwater = vos.readPCRmapClone( + configget(iniItems, "groundwaterOptions", "storGroundwaterIni", "0.0"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.avgAbstraction = vos.readPCRmapClone( + configget( + iniItems, + "groundwaterOptions", + "avgTotalGroundwaterAbstractionIni", + "0.0", + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.avgAllocation = vos.readPCRmapClone( + configget( + iniItems, + "groundwaterOptions", + "avgTotalGroundwaterAllocationLongIni", + "0.0", + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.avgAllocationShort = vos.readPCRmapClone( + configget( + iniItems, + "groundwaterOptions", + "avgTotalGroundwaterAllocationShortIni", + "0.0", + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.avgNonFossilAllocation = vos.readPCRmapClone( + configget( + iniItems, + "groundwaterOptions", + "avgNonFossilGroundwaterAllocationLongIni", + "0.0", + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.avgNonFossilAllocationShort = vos.readPCRmapClone( + configget( + iniItems, + "groundwaterOptions", + "avgNonFossilGroundwaterAllocationShortIni", + "0.0", + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) - self.storGroundwater = vos.readPCRmapClone(\ - configget(iniItems,"groundwaterOptions","storGroundwaterIni","0.0"), - self.cloneMap,self.tmpDir,self.inputDir) - self.avgAbstraction = vos.readPCRmapClone(\ - configget(iniItems,"groundwaterOptions","avgTotalGroundwaterAbstractionIni","0.0"), - self.cloneMap,self.tmpDir,self.inputDir) - self.avgAllocation = vos.readPCRmapClone(\ - configget(iniItems,"groundwaterOptions","avgTotalGroundwaterAllocationLongIni","0.0"), - self.cloneMap,self.tmpDir,self.inputDir) - self.avgAllocationShort = vos.readPCRmapClone(\ - configget(iniItems,"groundwaterOptions","avgTotalGroundwaterAllocationShortIni","0.0"), - self.cloneMap,self.tmpDir,self.inputDir) - self.avgNonFossilAllocation = vos.readPCRmapClone(\ - configget(iniItems,"groundwaterOptions","avgNonFossilGroundwaterAllocationLongIni","0.0"), - self.cloneMap,self.tmpDir,self.inputDir) - self.avgNonFossilAllocationShort = vos.readPCRmapClone(\ - configget(iniItems,"groundwaterOptions","avgNonFossilGroundwaterAllocationShortIni","0.0"), - self.cloneMap,self.tmpDir,self.inputDir) - # additional initial conditions (needed ONLY for the online coupling between PCR-GLOBWB and MODFLOW)) - if configget(iniItems,"groundwaterOptions","relativeGroundwaterHeadIni","None") != "None":\ - self.relativeGroundwaterHead = vos.readPCRmapClone(\ - iniItems.get("groundwaterOptions","relativeGroundwaterHeadIni"), - self.cloneMap,self.tmpDir,self.inputDir) + if ( + configget( + iniItems, "groundwaterOptions", "relativeGroundwaterHeadIni", "None" + ) + != "None" + ): + self.relativeGroundwaterHead = vos.readPCRmapClone( + iniItems.get("groundwaterOptions", "relativeGroundwaterHeadIni"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) else: self.relativeGroundwaterHead = self.storGroundwater / self.specificYield - self.baseflow = vos.readPCRmapClone(\ - configget(iniItems,"groundwaterOptions","baseflowIni","0.0"), - self.cloneMap,self.tmpDir,self.inputDir) + self.baseflow = vos.readPCRmapClone( + configget(iniItems, "groundwaterOptions", "baseflowIni", "0.0"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) - else: # during/after spinUp - self.storGroundwater = iniConditions['groundwater']['storGroundwater'] - self.avgAbstraction = iniConditions['groundwater']['avgTotalGroundwaterAbstraction'] - self.avgAllocation = iniConditions['groundwater']['avgTotalGroundwaterAllocationLong'] - self.avgAllocationShort = iniConditions['groundwater']['avgTotalGroundwaterAllocationShort'] - self.avgNonFossilAllocation = iniConditions['groundwater']['avgNonFossilGroundwaterAllocationLong'] - self.avgNonFossilAllocationShort = iniConditions['groundwater']['avgNonFossilGroundwaterAllocationShort'] + else: # during/after spinUp + self.storGroundwater = iniConditions["groundwater"]["storGroundwater"] + self.avgAbstraction = iniConditions["groundwater"][ + "avgTotalGroundwaterAbstraction" + ] + self.avgAllocation = iniConditions["groundwater"][ + "avgTotalGroundwaterAllocationLong" + ] + self.avgAllocationShort = iniConditions["groundwater"][ + "avgTotalGroundwaterAllocationShort" + ] + self.avgNonFossilAllocation = iniConditions["groundwater"][ + "avgNonFossilGroundwaterAllocationLong" + ] + self.avgNonFossilAllocationShort = iniConditions["groundwater"][ + "avgNonFossilGroundwaterAllocationShort" + ] - self.relativeGroundwaterHead = iniConditions['groundwater']['relativeGroundwaterHead'] - self.baseflow = iniConditions['groundwater']['baseflow'] + self.relativeGroundwaterHead = iniConditions["groundwater"][ + "relativeGroundwaterHead" + ] + self.baseflow = iniConditions["groundwater"]["baseflow"] # initial condition for storGroundwaterFossil (unit: m) # # Note that storGroundwaterFossil should not be depleted during the spin-up. # - if configget(iniItems,"groundwaterOptions","storGroundwaterFossilIni","0.0") == "Maximum" and\ - self.limitFossilGroundwaterAbstraction and self.limitAbstraction == False: - logger.info("Assuming 'full' fossilWaterCap as the initial condition for fossil groundwater storage.") + if ( + configget(iniItems, "groundwaterOptions", "storGroundwaterFossilIni", "0.0") + == "Maximum" + and self.limitFossilGroundwaterAbstraction + and self.limitAbstraction == False + ): + logger.info( + "Assuming 'full' fossilWaterCap as the initial condition for fossil groundwater storage." + ) self.storGroundwaterFossil = self.fossilWaterCap # - if configget(iniItems,"groundwaterOptions","storGroundwaterFossilIni","0.0") != "Maximum": - logger.info("Using a pre-defined initial condition for fossil groundwater storage.") - self.storGroundwaterFossil = vos.readPCRmapClone(\ - iniItems.get("groundwaterOptions","storGroundwaterFossilIni"), - self.cloneMap,self.tmpDir,self.inputDir) + if ( + configget(iniItems, "groundwaterOptions", "storGroundwaterFossilIni", "0.0") + != "Maximum" + ): + logger.info( + "Using a pre-defined initial condition for fossil groundwater storage." + ) + self.storGroundwaterFossil = vos.readPCRmapClone( + iniItems.get("groundwaterOptions", "storGroundwaterFossilIni"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) # - if configget(iniItems,"groundwaterOptions","storGroundwaterFossilIni","0.0") != "Maximum" and\ - self.limitFossilGroundwaterAbstraction and self.limitAbstraction == False: - logger.info("The pre-defined initial condition for fossil groundwater is limited by fossilWaterCap (full capacity).") - self.storGroundwaterFossil = pcr.min(self.storGroundwaterFossil, self.fossilWaterCap) + if ( + configget(iniItems, "groundwaterOptions", "storGroundwaterFossilIni", "0.0") + != "Maximum" + and self.limitFossilGroundwaterAbstraction + and self.limitAbstraction == False + ): + logger.info( + "The pre-defined initial condition for fossil groundwater is limited by fossilWaterCap (full capacity)." + ) + self.storGroundwaterFossil = pcr.min( + self.storGroundwaterFossil, self.fossilWaterCap + ) self.storGroundwaterFossil = pcr.max(0.0, self.storGroundwaterFossil) # make sure that active storGroundwater, avgAbstraction and avgNonFossilAllocation cannot be negative # - self.storGroundwater = pcr.cover( self.storGroundwater,0.0) - self.storGroundwater = pcr.max(0.,self.storGroundwater) - self.storGroundwater = pcr.ifthen(self.landmask,\ - self.storGroundwater) + self.storGroundwater = pcr.cover(self.storGroundwater, 0.0) + self.storGroundwater = pcr.max(0., self.storGroundwater) + self.storGroundwater = pcr.ifthen(self.landmask, self.storGroundwater) # - self.avgAbstraction = pcr.cover( self.avgAbstraction,0.0) - self.avgAbstraction = pcr.max(0.,self.avgAbstraction) - self.avgAbstraction = pcr.ifthen(self.landmask,\ - self.avgAbstraction) + self.avgAbstraction = pcr.cover(self.avgAbstraction, 0.0) + self.avgAbstraction = pcr.max(0., self.avgAbstraction) + self.avgAbstraction = pcr.ifthen(self.landmask, self.avgAbstraction) # - self.avgAllocation = pcr.cover( self.avgAllocation,0.0) - self.avgAllocation = pcr.max(0.,self.avgAllocation) - self.avgAllocation = pcr.ifthen(self.landmask,\ - self.avgAllocation) + self.avgAllocation = pcr.cover(self.avgAllocation, 0.0) + self.avgAllocation = pcr.max(0., self.avgAllocation) + self.avgAllocation = pcr.ifthen(self.landmask, self.avgAllocation) # - self.avgAllocationShort = pcr.cover( self.avgAllocationShort,0.0) - self.avgAllocationShort = pcr.max(0.,self.avgAllocationShort) - self.avgAllocationShort = pcr.ifthen(self.landmask,\ - self.avgAllocationShort) + self.avgAllocationShort = pcr.cover(self.avgAllocationShort, 0.0) + self.avgAllocationShort = pcr.max(0., self.avgAllocationShort) + self.avgAllocationShort = pcr.ifthen(self.landmask, self.avgAllocationShort) # - self.avgNonFossilAllocation = pcr.cover( self.avgNonFossilAllocation,0.0) - self.avgNonFossilAllocation = pcr.max(0.,self.avgNonFossilAllocation) - self.avgNonFossilAllocation = pcr.ifthen(self.landmask,\ - self.avgNonFossilAllocation) + self.avgNonFossilAllocation = pcr.cover(self.avgNonFossilAllocation, 0.0) + self.avgNonFossilAllocation = pcr.max(0., self.avgNonFossilAllocation) + self.avgNonFossilAllocation = pcr.ifthen( + self.landmask, self.avgNonFossilAllocation + ) # - self.avgNonFossilAllocationShort = pcr.cover( self.avgNonFossilAllocationShort,0.0) - self.avgNonFossilAllocationShort = pcr.max(0.,self.avgNonFossilAllocationShort) - self.avgNonFossilAllocationShort = pcr.ifthen(self.landmask,\ - self.avgNonFossilAllocationShort) + self.avgNonFossilAllocationShort = pcr.cover( + self.avgNonFossilAllocationShort, 0.0 + ) + self.avgNonFossilAllocationShort = pcr.max(0., self.avgNonFossilAllocationShort) + self.avgNonFossilAllocationShort = pcr.ifthen( + self.landmask, self.avgNonFossilAllocationShort + ) self.relativeGroundwaterHead = pcr.cover(self.relativeGroundwaterHead, 0.0) - self.relativeGroundwaterHead = pcr.ifthen(self.landmask, self.relativeGroundwaterHead) + self.relativeGroundwaterHead = pcr.ifthen( + self.landmask, self.relativeGroundwaterHead + ) self.baseflow = pcr.cover(self.baseflow, 0.0) self.baseflow = pcr.ifthen(self.landmask, self.baseflow) # storGroundwaterFossil can be negative (particularly if limitFossilGroundwaterAbstraction == False) - self.storGroundwaterFossil = pcr.cover( self.storGroundwaterFossil, 0.0) - self.storGroundwaterFossil = pcr.ifthen(self.landmask,\ - self.storGroundwaterFossil) + self.storGroundwaterFossil = pcr.cover(self.storGroundwaterFossil, 0.0) + self.storGroundwaterFossil = pcr.ifthen( + self.landmask, self.storGroundwaterFossil + ) def perturb(self, name, **parameters): if name == "groundwater": # factor for perturbing the initial storGroundwater - self.storGroundwater = self.storGroundwater * (mapnormal()*parameters['standard_deviation']+1) - self.storGroundwater = pcr.max(0.,self.storGroundwater) + self.storGroundwater = self.storGroundwater * ( + mapnormal() * parameters["standard_deviation"] + 1 + ) + self.storGroundwater = pcr.max(0., self.storGroundwater) else: print("Error: only groundwater may be updated at this time") return -1 - def update(self,landSurface,routing,currTimeStep): + def update(self, landSurface, routing, currTimeStep): if self.useMODFLOW: - self.update_with_MODFLOW(landSurface,routing,currTimeStep) + self.update_with_MODFLOW(landSurface, routing, currTimeStep) else: - self.update_without_MODFLOW(landSurface,routing,currTimeStep) + self.update_without_MODFLOW(landSurface, routing, currTimeStep) self.calculate_statistics(routing) # old-style reporting - self.old_style_groundwater_reporting(currTimeStep) # TODO: remove this one + self.old_style_groundwater_reporting(currTimeStep) # TODO: remove this one - def update_with_MODFLOW(self,landSurface,routing,currTimeStep): + def update_with_MODFLOW(self, landSurface, routing, currTimeStep): logger.info("Updating groundwater based on the MODFLOW output.") @@ -588,20 +961,38 @@ if currTimeStep.day == 1 and currTimeStep.timeStepPCR > 1: # for online coupling, we will read files from pcraster maps, using the previous day values - directory = self.iniItems.get("globalOptions","outputDir") + "/modflow/transient/maps/" + directory = ( + self.iniItems.get("globalOptions", "outputDir") + + "/modflow/transient/maps/" + ) yesterday = str(currTimeStep.yesterday()) # - relative groundwater head from MODFLOW filename = directory + "relativeGroundwaterHead_" + str(yesterday) + ".map" - self.relativeGroundwaterHead = pcr.ifthen(self.landmask, pcr.cover(vos.readPCRmapClone(filename, self.cloneMap, self.tmpDir), 0.0)) + self.relativeGroundwaterHead = pcr.ifthen( + self.landmask, + pcr.cover( + vos.readPCRmapClone(filename, self.cloneMap, self.tmpDir), 0.0 + ), + ) # - storGroundwater from MODFLOW filename = directory + "storGroundwater_" + str(yesterday) + ".map" - self.storGroundwater = pcr.ifthen(self.landmask, pcr.cover(vos.readPCRmapClone(filename, self.cloneMap, self.tmpDir), 0.0)) + self.storGroundwater = pcr.ifthen( + self.landmask, + pcr.cover( + vos.readPCRmapClone(filename, self.cloneMap, self.tmpDir), 0.0 + ), + ) # - baseflow from MODFLOW filename = directory + "baseflow_" + str(yesterday) + ".map" - self.baseflow = pcr.ifthen(self.landmask, pcr.cover(vos.readPCRmapClone(filename, self.cloneMap, self.tmpDir), 0.0)) + self.baseflow = pcr.ifthen( + self.landmask, + pcr.cover( + vos.readPCRmapClone(filename, self.cloneMap, self.tmpDir), 0.0 + ), + ) # river bed exchange has been accomodated in baseflow (via MODFLOW, river and drain packages) self.surfaceWaterInf = pcr.scalar(0.0) @@ -614,47 +1005,46 @@ # groundwater allocation (Note: This is done in the landSurface module) self.allocNonFossilGroundwater = landSurface.allocNonFossilGroundwater - self.fossilGroundwaterAlloc = landSurface.fossilGroundwaterAlloc + self.fossilGroundwaterAlloc = landSurface.fossilGroundwaterAlloc # groundwater allocation (Note: This is done in the landSurface module) self.allocNonFossilGroundwater = landSurface.allocNonFossilGroundwater - self.fossilGroundwaterAlloc = landSurface.fossilGroundwaterAlloc + self.fossilGroundwaterAlloc = landSurface.fossilGroundwaterAlloc # Note: The following variable (unmetDemand) is a bad name and used in the past. # Its definition is actually as follows: (the amount of demand that is satisfied/allocated from fossil groundwater) # self.unmetDemand = self.fossilGroundwaterAlloc + def update_without_MODFLOW(self, landSurface, routing, currTimeStep): - def update_without_MODFLOW(self,landSurface,routing,currTimeStep): - logger.info("Updating groundwater") if self.debugWaterBalance: - preStorGroundwater = self.storGroundwater + preStorGroundwater = self.storGroundwater preStorGroundwaterFossil = self.storGroundwaterFossil # get riverbed infiltration from the previous time step (from routing) - self.surfaceWaterInf = routing.riverbedExchange/\ - routing.cellArea # unit: m + self.surfaceWaterInf = routing.riverbedExchange / routing.cellArea # unit: m self.storGroundwater += self.surfaceWaterInf # get net recharge (percolation-capRise) and update storage: - self.storGroundwater = pcr.max(0.,\ - self.storGroundwater + landSurface.gwRecharge) + self.storGroundwater = pcr.max( + 0., self.storGroundwater + landSurface.gwRecharge + ) # non fossil groundwater abstraction self.nonFossilGroundwaterAbs = landSurface.nonFossilGroundwaterAbs - self.storGroundwater = pcr.max(0.,\ - self.storGroundwater - self.nonFossilGroundwaterAbs) + self.storGroundwater = pcr.max( + 0., self.storGroundwater - self.nonFossilGroundwaterAbs + ) # baseflow - self.baseflow = pcr.max(0.,\ - pcr.min(self.storGroundwater,\ - self.recessionCoeff* \ - self.storGroundwater)) - self.storGroundwater = pcr.max(0.,\ - self.storGroundwater - self.baseflow) + self.baseflow = pcr.max( + 0., + pcr.min(self.storGroundwater, self.recessionCoeff * self.storGroundwater), + ) + self.storGroundwater = pcr.max(0., self.storGroundwater - self.baseflow) # PS: baseflow must be calculated at the end (to ensure the availability of storGroundwater to support nonFossilGroundwaterAbs) # fossil groundwater abstraction: @@ -667,104 +1057,125 @@ # groundwater allocation (Note: This is done in the landSurface module) self.allocNonFossilGroundwater = landSurface.allocNonFossilGroundwater - self.fossilGroundwaterAlloc = landSurface.fossilGroundwaterAlloc + self.fossilGroundwaterAlloc = landSurface.fossilGroundwaterAlloc # Note: The following variable (unmetDemand) is a bad name and used in the past. # Its definition is actually as follows: (the amount of demand that is satisfied/allocated from fossil groundwater) self.unmetDemand = self.fossilGroundwaterAlloc # calculate relative groundwater head above the minimum level (unit: m) # - needed to estimate areas influenced by capillary rise - self.relativeGroundwaterHead = self.storGroundwater/self.specificYield + self.relativeGroundwaterHead = self.storGroundwater / self.specificYield if self.debugWaterBalance: - vos.waterBalanceCheck([self.surfaceWaterInf,\ - landSurface.gwRecharge],\ - [self.baseflow,\ - self.nonFossilGroundwaterAbs],\ - [ preStorGroundwater],\ - [self.storGroundwater],\ - 'storGroundwater',\ - True,\ - currTimeStep.fulldate,threshold=1e-4) + vos.waterBalanceCheck( + [self.surfaceWaterInf, landSurface.gwRecharge], + [self.baseflow, self.nonFossilGroundwaterAbs], + [preStorGroundwater], + [self.storGroundwater], + "storGroundwater", + True, + currTimeStep.fulldate, + threshold=1e-4, + ) if self.debugWaterBalance: - vos.waterBalanceCheck([pcr.scalar(0.0)],\ - [self.fossilGroundwaterAbstr],\ - [ preStorGroundwaterFossil],\ - [self.storGroundwaterFossil],\ - 'storGroundwaterFossil',\ - True,\ - currTimeStep.fulldate,threshold=1e-3) + vos.waterBalanceCheck( + [pcr.scalar(0.0)], + [self.fossilGroundwaterAbstr], + [preStorGroundwaterFossil], + [self.storGroundwaterFossil], + "storGroundwaterFossil", + True, + currTimeStep.fulldate, + threshold=1e-3, + ) if self.debugWaterBalance: - vos.waterBalanceCheck([landSurface.desalinationAllocation,\ - self.unmetDemand, \ - self.allocNonFossilGroundwater, \ - landSurface.allocSurfaceWaterAbstract],\ - [landSurface.totalPotentialGrossDemand],\ - [pcr.scalar(0.)],\ - [pcr.scalar(0.)],\ - 'demand allocation (desalination, surface water, groundwater & unmetDemand. Error here may be due to rounding error.',\ - True,\ - currTimeStep.fulldate,threshold=1e-3) - + vos.waterBalanceCheck( + [ + landSurface.desalinationAllocation, + self.unmetDemand, + self.allocNonFossilGroundwater, + landSurface.allocSurfaceWaterAbstract, + ], + [landSurface.totalPotentialGrossDemand], + [pcr.scalar(0.)], + [pcr.scalar(0.)], + "demand allocation (desalination, surface water, groundwater & unmetDemand. Error here may be due to rounding error.", + True, + currTimeStep.fulldate, + threshold=1e-3, + ) def calculate_statistics(self, routing): # calculate the average total groundwater abstraction (m/day) from the last 365 days: - totalAbstraction = self.fossilGroundwaterAbstr + self.nonFossilGroundwaterAbs - deltaAbstraction = totalAbstraction - self.avgAbstraction - self.avgAbstraction = self.avgAbstraction +\ - deltaAbstraction/\ - pcr.min(365., pcr.max(1.0, routing.timestepsToAvgDischarge)) + totalAbstraction = self.fossilGroundwaterAbstr + self.nonFossilGroundwaterAbs + deltaAbstraction = totalAbstraction - self.avgAbstraction + self.avgAbstraction = self.avgAbstraction + deltaAbstraction / pcr.min( + 365., pcr.max(1.0, routing.timestepsToAvgDischarge) + ) self.avgAbstraction = pcr.max(0.0, self.avgAbstraction) # calculate the average non fossil groundwater allocation (m/day) # - from the last 365 days: - deltaAllocation = self.allocNonFossilGroundwater - self.avgNonFossilAllocation - self.avgNonFossilAllocation = self.avgNonFossilAllocation +\ - deltaAllocation/\ - pcr.min(365., pcr.max(1.0, routing.timestepsToAvgDischarge)) + deltaAllocation = self.allocNonFossilGroundwater - self.avgNonFossilAllocation + self.avgNonFossilAllocation = ( + self.avgNonFossilAllocation + + deltaAllocation + / pcr.min(365., pcr.max(1.0, routing.timestepsToAvgDischarge)) + ) self.avgNonFossilAllocation = pcr.max(0.0, self.avgNonFossilAllocation) # - from the last 7 days: - deltaAllocationShort = self.allocNonFossilGroundwater - self.avgNonFossilAllocationShort - self.avgNonFossilAllocationShort = self.avgNonFossilAllocationShort +\ - deltaAllocationShort/\ - pcr.min(7., pcr.max(1.0, routing.timestepsToAvgDischarge)) - self.avgNonFossilAllocationShort = pcr.max(0.0, self.avgNonFossilAllocationShort) + deltaAllocationShort = ( + self.allocNonFossilGroundwater - self.avgNonFossilAllocationShort + ) + self.avgNonFossilAllocationShort = ( + self.avgNonFossilAllocationShort + + deltaAllocationShort + / pcr.min(7., pcr.max(1.0, routing.timestepsToAvgDischarge)) + ) + self.avgNonFossilAllocationShort = pcr.max( + 0.0, self.avgNonFossilAllocationShort + ) # calculate the average total (fossil + non fossil) groundwater allocation (m/day) - totalGroundwaterAllocation = self.allocNonFossilGroundwater + self.fossilGroundwaterAlloc + totalGroundwaterAllocation = ( + self.allocNonFossilGroundwater + self.fossilGroundwaterAlloc + ) # - from the last 365 days: - deltaAllocation = totalGroundwaterAllocation - self.avgAllocation - self.avgAllocation = self.avgAllocation +\ - deltaAllocation/\ - pcr.min(365., pcr.max(1.0, routing.timestepsToAvgDischarge)) - self.avgAllocation = pcr.max(0.0, self.avgAllocation) + deltaAllocation = totalGroundwaterAllocation - self.avgAllocation + self.avgAllocation = self.avgAllocation + deltaAllocation / pcr.min( + 365., pcr.max(1.0, routing.timestepsToAvgDischarge) + ) + self.avgAllocation = pcr.max(0.0, self.avgAllocation) # - from the last 7 days: - deltaAllocationShort = totalGroundwaterAllocation - self.avgAllocationShort - self.avgAllocationShort = self.avgAllocationShort +\ - deltaAllocationShort/\ - pcr.min(7., pcr.max(1.0, routing.timestepsToAvgDischarge)) - self.avgAllocationShort = pcr.max(0.0, self.avgAllocationShort) + deltaAllocationShort = totalGroundwaterAllocation - self.avgAllocationShort + self.avgAllocationShort = ( + self.avgAllocationShort + + deltaAllocationShort + / pcr.min(7., pcr.max(1.0, routing.timestepsToAvgDischarge)) + ) + self.avgAllocationShort = pcr.max(0.0, self.avgAllocationShort) - def old_style_groundwater_reporting(self,currTimeStep): + def old_style_groundwater_reporting(self, currTimeStep): if self.report == True: - timeStamp = datetime.datetime(currTimeStep.year,\ - currTimeStep.month,\ - currTimeStep.day,\ - 0) + timeStamp = datetime.datetime( + currTimeStep.year, currTimeStep.month, currTimeStep.day, 0 + ) # writing daily output to netcdf files timestepPCR = currTimeStep.timeStepPCR if self.outDailyTotNC[0] != "None": for var in self.outDailyTotNC: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_dailyTot.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var),vos.MV),\ - timeStamp,timestepPCR-1) + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_dailyTot.nc", + var, + pcr2numpy(self.__getattribute__(var), vos.MV), + timeStamp, + timestepPCR - 1, + ) # writing monthly output to netcdf files # -cummulative @@ -773,20 +1184,21 @@ # introduce variables at the beginning of simulation or # reset variables at the beginning of the month - if currTimeStep.timeStepPCR == 1 or \ - currTimeStep.day == 1:\ - vars(self)[var+'MonthTot'] = pcr.scalar(0.0) + if currTimeStep.timeStepPCR == 1 or currTimeStep.day == 1: + vars(self)[var + "MonthTot"] = pcr.scalar(0.0) # accumulating - vars(self)[var+'MonthTot'] += vars(self)[var] + vars(self)[var + "MonthTot"] += vars(self)[var] # reporting at the end of the month: if currTimeStep.endMonth == True: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthTot.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var+'MonthTot'),\ - vos.MV),timeStamp,currTimeStep.monthIdx-1) + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthTot.nc", + var, + pcr2numpy(self.__getattribute__(var + "MonthTot"), vos.MV), + timeStamp, + currTimeStep.monthIdx - 1, + ) # -average if self.outMonthAvgNC[0] != "None": for var in self.outMonthAvgNC: @@ -795,32 +1207,36 @@ # introduce accumulator at the beginning of simulation or # reset accumulator at the beginning of the month - if currTimeStep.timeStepPCR == 1 or \ - currTimeStep.day == 1:\ - vars(self)[var+'MonthTot'] = pcr.scalar(0.0) + if currTimeStep.timeStepPCR == 1 or currTimeStep.day == 1: + vars(self)[var + "MonthTot"] = pcr.scalar(0.0) # accumulating - vars(self)[var+'MonthTot'] += vars(self)[var] + vars(self)[var + "MonthTot"] += vars(self)[var] # calculating average & reporting at the end of the month: if currTimeStep.endMonth == True: - vars(self)[var+'MonthAvg'] = vars(self)[var+'MonthTot']/\ - currTimeStep.day - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthAvg.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var+'MonthAvg'),\ - vos.MV),timeStamp,currTimeStep.monthIdx-1) + vars(self)[var + "MonthAvg"] = ( + vars(self)[var + "MonthTot"] / currTimeStep.day + ) + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthAvg.nc", + var, + pcr2numpy(self.__getattribute__(var + "MonthAvg"), vos.MV), + timeStamp, + currTimeStep.monthIdx - 1, + ) # # -last day of the month if self.outMonthEndNC[0] != "None": for var in self.outMonthEndNC: # reporting at the end of the month: if currTimeStep.endMonth == True: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthEnd.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var),vos.MV),\ - timeStamp,currTimeStep.monthIdx-1) + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthEnd.nc", + var, + pcr2numpy(self.__getattribute__(var), vos.MV), + timeStamp, + currTimeStep.monthIdx - 1, + ) # writing yearly output to netcdf files # -cummulative @@ -829,51 +1245,55 @@ # introduce variables at the beginning of simulation or # reset variables at the beginning of the month - if currTimeStep.timeStepPCR == 1 or \ - currTimeStep.doy == 1:\ - vars(self)[var+'AnnuaTot'] = pcr.scalar(0.0) + if currTimeStep.timeStepPCR == 1 or currTimeStep.doy == 1: + vars(self)[var + "AnnuaTot"] = pcr.scalar(0.0) # accumulating - vars(self)[var+'AnnuaTot'] += vars(self)[var] + vars(self)[var + "AnnuaTot"] += vars(self)[var] # reporting at the end of the year: if currTimeStep.endYear == True: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaTot.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var+'AnnuaTot'),\ - vos.MV),timeStamp,currTimeStep.annuaIdx-1) + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaTot.nc", + var, + pcr2numpy(self.__getattribute__(var + "AnnuaTot"), vos.MV), + timeStamp, + currTimeStep.annuaIdx - 1, + ) # -average if self.outAnnuaAvgNC[0] != "None": for var in self.outAnnuaAvgNC: # only if a accumulator variable has not been defined: if var not in self.outAnnuaTotNC: # introduce accumulator at the beginning of simulation or # reset accumulator at the beginning of the year - if currTimeStep.timeStepPCR == 1 or \ - currTimeStep.doy == 1:\ - vars(self)[var+'AnnuaTot'] = pcr.scalar(0.0) + if currTimeStep.timeStepPCR == 1 or currTimeStep.doy == 1: + vars(self)[var + "AnnuaTot"] = pcr.scalar(0.0) # accumulating - vars(self)[var+'AnnuaTot'] += vars(self)[var] + vars(self)[var + "AnnuaTot"] += vars(self)[var] # # calculating average & reporting at the end of the year: if currTimeStep.endYear == True: - vars(self)[var+'AnnuaAvg'] = vars(self)[var+'AnnuaTot']/\ - currTimeStep.doy - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaAvg.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var+'AnnuaAvg'),\ - vos.MV),timeStamp,currTimeStep.annuaIdx-1) + vars(self)[var + "AnnuaAvg"] = ( + vars(self)[var + "AnnuaTot"] / currTimeStep.doy + ) + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaAvg.nc", + var, + pcr2numpy(self.__getattribute__(var + "AnnuaAvg"), vos.MV), + timeStamp, + currTimeStep.annuaIdx - 1, + ) # # -last day of the year if self.outAnnuaEndNC[0] != "None": for var in self.outAnnuaEndNC: # reporting at the end of the year: if currTimeStep.endYear == True: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaEnd.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var),vos.MV),\ - timeStamp,currTimeStep.annuaIdx-1) - + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaEnd.nc", + var, + pcr2numpy(self.__getattribute__(var), vos.MV), + timeStamp, + currTimeStep.annuaIdx - 1, + ) Index: wflow-py/wflow/pcrglobwb/landSurface.py =================================================================== diff -u -r2d84b2c3f986344e96a4fa357e54dd77fe817fe4 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/pcrglobwb/landSurface.py (.../landSurface.py) (revision 2d84b2c3f986344e96a4fa357e54dd77fe817fe4) +++ wflow-py/wflow/pcrglobwb/landSurface.py (.../landSurface.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -27,8 +27,9 @@ import virtualOS as vos import logging -logger = logging.getLogger('wflow_pcrglobwb') +logger = logging.getLogger("wflow_pcrglobwb") + from ncConverter import * import landCover as lc @@ -38,1378 +39,2281 @@ from wflow.wf_DynamicFramework import configsection from wflow.wf_DynamicFramework import configget + class LandSurface(object): - def getState(self): result = {} - + if self.numberOfSoilLayers == 2: for coverType in self.coverTypes: result[coverType] = {} - result[coverType]['interceptStor'] = \ - self.landCoverObj[coverType].interceptStor - result[coverType]['snowCoverSWE' ] = \ - self.landCoverObj[coverType].snowCoverSWE - result[coverType]['snowFreeWater'] = \ - self.landCoverObj[coverType].snowFreeWater - result[coverType]['topWaterLayer'] = \ - self.landCoverObj[coverType].topWaterLayer - result[coverType]['storUpp'] = \ - self.landCoverObj[coverType].storUpp - result[coverType]['storLow'] = \ - self.landCoverObj[coverType].storLow - result[coverType]['interflow' ] = \ - self.landCoverObj[coverType].interflow + result[coverType]["interceptStor"] = self.landCoverObj[ + coverType + ].interceptStor + result[coverType]["snowCoverSWE"] = self.landCoverObj[ + coverType + ].snowCoverSWE + result[coverType]["snowFreeWater"] = self.landCoverObj[ + coverType + ].snowFreeWater + result[coverType]["topWaterLayer"] = self.landCoverObj[ + coverType + ].topWaterLayer + result[coverType]["storUpp"] = self.landCoverObj[coverType].storUpp + result[coverType]["storLow"] = self.landCoverObj[coverType].storLow + result[coverType]["interflow"] = self.landCoverObj[coverType].interflow if self.numberOfSoilLayers == 3: for coverType in self.coverTypes: result[coverType] = {} - result[coverType]['interceptStor'] = \ - self.landCoverObj[coverType].interceptStor - result[coverType]['snowCoverSWE' ] = \ - self.landCoverObj[coverType].snowCoverSWE - result[coverType]['snowFreeWater'] = \ - self.landCoverObj[coverType].snowFreeWater - result[coverType]['topWaterLayer'] = \ - self.landCoverObj[coverType].topWaterLayer - result[coverType]['storUpp000005'] = \ - self.landCoverObj[coverType].storUpp000005 - result[coverType]['storUpp005030'] = \ - self.landCoverObj[coverType].storUpp005030 - result[coverType]['storLow030150'] = \ - self.landCoverObj[coverType].storLow030150 - result[coverType]['interflow' ] = \ - self.landCoverObj[coverType].interflow - + result[coverType]["interceptStor"] = self.landCoverObj[ + coverType + ].interceptStor + result[coverType]["snowCoverSWE"] = self.landCoverObj[ + coverType + ].snowCoverSWE + result[coverType]["snowFreeWater"] = self.landCoverObj[ + coverType + ].snowFreeWater + result[coverType]["topWaterLayer"] = self.landCoverObj[ + coverType + ].topWaterLayer + result[coverType]["storUpp000005"] = self.landCoverObj[ + coverType + ].storUpp000005 + result[coverType]["storUpp005030"] = self.landCoverObj[ + coverType + ].storUpp005030 + result[coverType]["storLow030150"] = self.landCoverObj[ + coverType + ].storLow030150 + result[coverType]["interflow"] = self.landCoverObj[coverType].interflow + return result - - + def getPseudoState(self): result = {} - + if self.numberOfSoilLayers == 2: - result['interceptStor'] = self.interceptStor - result['snowCoverSWE'] = self.snowCoverSWE - result['snowFreeWater'] = self.snowFreeWater - result['topWaterLayer'] = self.topWaterLayer - result['storUpp'] = self.storUpp - result['storLow'] = self.storLow + result["interceptStor"] = self.interceptStor + result["snowCoverSWE"] = self.snowCoverSWE + result["snowFreeWater"] = self.snowFreeWater + result["topWaterLayer"] = self.topWaterLayer + result["storUpp"] = self.storUpp + result["storLow"] = self.storLow if self.numberOfSoilLayers == 3: - result['interceptStor'] = self.interceptStor - result['snowCoverSWE'] = self.snowCoverSWE - result['snowFreeWater'] = self.snowFreeWater - result['topWaterLayer'] = self.topWaterLayer - result['storUpp000005'] = self.storUpp000005 - result['storUpp005030'] = self.storUpp005030 - result['storLow030150'] = self.storLow030150 - + result["interceptStor"] = self.interceptStor + result["snowCoverSWE"] = self.snowCoverSWE + result["snowFreeWater"] = self.snowFreeWater + result["topWaterLayer"] = self.topWaterLayer + result["storUpp000005"] = self.storUpp000005 + result["storUpp005030"] = self.storUpp005030 + result["storLow030150"] = self.storLow030150 + return result - - - def __init__(self,iniItems,landmask,Dir,staticmaps,cloneMap,startTime,initialState=None): + def __init__( + self, + iniItems, + landmask, + Dir, + staticmaps, + cloneMap, + startTime, + initialState=None, + ): object.__init__(self) # clone map, temporary directory, absolute path of input directory, and landmask - self.cloneMap = cloneMap #iniItems.cloneMap - self.tmpDir = os.path.join(os.path.abspath(Dir),"tmp") #iniItems.tmpDir - self.inputDir = os.path.join(os.path.abspath(Dir),staticmaps) #iniItems.globalOptions['inputDir'] + self.cloneMap = cloneMap # iniItems.cloneMap + self.tmpDir = os.path.join(os.path.abspath(Dir), "tmp") # iniItems.tmpDir + self.inputDir = os.path.join( + os.path.abspath(Dir), staticmaps + ) # iniItems.globalOptions['inputDir'] self.landmask = landmask self.startTime = startTime # cellArea (unit: m2) - self.cellArea = vos.readPCRmapClone(iniItems.get("routingOptions","cellAreaMap"), #iniItems.routingOptions['cellAreaMap'], \ - self.cloneMap, self.tmpDir, self.inputDir) + self.cellArea = vos.readPCRmapClone( + iniItems.get( + "routingOptions", "cellAreaMap" + ), # iniItems.routingOptions['cellAreaMap'], \ + self.cloneMap, + self.tmpDir, + self.inputDir, + ) self.cellArea = pcr.ifthen(self.landmask, self.cellArea) - + # number of soil layers: - self.numberOfSoilLayers = int(configget(iniItems,"landSurfaceOptions","numberOfUpperSoilLayers","2")) #int(iniItems.landSurfaceOptions['numberOfUpperSoilLayers']) - + self.numberOfSoilLayers = int( + configget(iniItems, "landSurfaceOptions", "numberOfUpperSoilLayers", "2") + ) # int(iniItems.landSurfaceOptions['numberOfUpperSoilLayers']) + # list of aggregated variables that MUST be defined in the module: # - aggregated from landCover modules - # - some are needed for water balance checking + # - some are needed for water balance checking # - some are needed in other modules (e.g. routing, groundwater) # - some are needed for initialConditions - # + # # main state variables (unit: m) - self.mainStates = ['interceptStor',\ - 'snowCoverSWE' ,\ - 'snowFreeWater',\ - 'topWaterLayer'] + self.mainStates = [ + "interceptStor", + "snowCoverSWE", + "snowFreeWater", + "topWaterLayer", + ] # # state variables (unit: m) - self.stateVars = ['storUppTotal', - 'storLowTotal', - 'satDegUppTotal', - 'satDegLowTotal'] + self.stateVars = [ + "storUppTotal", + "storLowTotal", + "satDegUppTotal", + "satDegLowTotal", + ] # # flux variables (unit: m/day) - self.fluxVars = ['infiltration','gwRecharge','netLqWaterToSoil', - 'totalPotET', - 'actualET', - 'interceptEvap', - 'openWaterEvap', - 'actSnowFreeWaterEvap', - 'actBareSoilEvap', - 'actTranspiUppTotal', - 'actTranspiLowTotal', - 'actTranspiTotal', - 'directRunoff', - 'interflow', - 'interflowTotal', - 'irrGrossDemand', - 'nonIrrGrossDemand', - 'totalPotentialGrossDemand', - 'actSurfaceWaterAbstract', - 'allocSurfaceWaterAbstract', - 'desalinationAbstraction', - 'desalinationAllocation', - 'nonFossilGroundwaterAbs', - 'allocNonFossilGroundwater', - 'fossilGroundwaterAbstr', - 'fossilGroundwaterAlloc', - 'landSurfaceRunoff', - 'satExcess', - 'snowMelt', - 'totalGroundwaterAbstraction', - 'totalGroundwaterAllocation', - 'totalPotentialMaximumGrossDemand', - 'totalPotentialMaximumIrrGrossDemand', - 'totalPotentialMaximumIrrGrossDemandPaddy', - 'totalPotentialMaximumIrrGrossDemandNonPaddy', - 'totalPotentialMaximumNonIrrGrossDemand', - 'irrGrossDemandPaddy', - 'irrGrossDemandNonPaddy', - 'domesticWaterWithdrawal', - 'industryWaterWithdrawal', - 'livestockWaterWithdrawal', - 'nonIrrReturnFlow', - 'irrigationTranspirationDeficit'] + self.fluxVars = [ + "infiltration", + "gwRecharge", + "netLqWaterToSoil", + "totalPotET", + "actualET", + "interceptEvap", + "openWaterEvap", + "actSnowFreeWaterEvap", + "actBareSoilEvap", + "actTranspiUppTotal", + "actTranspiLowTotal", + "actTranspiTotal", + "directRunoff", + "interflow", + "interflowTotal", + "irrGrossDemand", + "nonIrrGrossDemand", + "totalPotentialGrossDemand", + "actSurfaceWaterAbstract", + "allocSurfaceWaterAbstract", + "desalinationAbstraction", + "desalinationAllocation", + "nonFossilGroundwaterAbs", + "allocNonFossilGroundwater", + "fossilGroundwaterAbstr", + "fossilGroundwaterAlloc", + "landSurfaceRunoff", + "satExcess", + "snowMelt", + "totalGroundwaterAbstraction", + "totalGroundwaterAllocation", + "totalPotentialMaximumGrossDemand", + "totalPotentialMaximumIrrGrossDemand", + "totalPotentialMaximumIrrGrossDemandPaddy", + "totalPotentialMaximumIrrGrossDemandNonPaddy", + "totalPotentialMaximumNonIrrGrossDemand", + "irrGrossDemandPaddy", + "irrGrossDemandNonPaddy", + "domesticWaterWithdrawal", + "industryWaterWithdrawal", + "livestockWaterWithdrawal", + "nonIrrReturnFlow", + "irrigationTranspirationDeficit", + ] # # specific variables for 2 and 3 layer soil models: # if self.numberOfSoilLayers == 2: - self.mainStates += ['storUpp','storLow'] - self.stateVars += self.mainStates - self.fluxVars += ['actTranspiUpp','actTranspiLow','netPercUpp'] - # + self.mainStates += ["storUpp", "storLow"] + self.stateVars += self.mainStates + self.fluxVars += ["actTranspiUpp", "actTranspiLow", "netPercUpp"] + # if self.numberOfSoilLayers == 3: - self.mainStates += ['storUpp000005', 'storUpp005030', 'storLow030150'] - self.stateVars += self.mainStates - self.fluxVars += ['actTranspiUpp000005','actTranspiUpp005030','actTranspiLow030150', - 'netPercUpp000005', 'netPercUpp005030', - 'interflowUpp005030'] - + self.mainStates += ["storUpp000005", "storUpp005030", "storLow030150"] + self.stateVars += self.mainStates + self.fluxVars += [ + "actTranspiUpp000005", + "actTranspiUpp005030", + "actTranspiLow030150", + "netPercUpp000005", + "netPercUpp005030", + "interflowUpp005030", + ] + # list of all variables that will be calculated/reported in landSurface.py self.aggrVars = self.stateVars + self.fluxVars - if self.numberOfSoilLayers == 2: self.aggrVars += ['satDegUpp','satDegLow'] - if self.numberOfSoilLayers == 3: self.aggrVars += ['satDegUpp000005','satDegUpp005030','satDegLow030150'] + if self.numberOfSoilLayers == 2: + self.aggrVars += ["satDegUpp", "satDegLow"] + if self.numberOfSoilLayers == 3: + self.aggrVars += ["satDegUpp000005", "satDegUpp005030", "satDegLow030150"] - self.debugWaterBalance = iniItems.get("landSurfaceOptions","debugWaterBalance") #iniItems.landSurfaceOptions['debugWaterBalance'] - # TDOD: Perform water balance checks for aggregates values (from values of each land cover type). - + self.debugWaterBalance = iniItems.get( + "landSurfaceOptions", "debugWaterBalance" + ) # iniItems.landSurfaceOptions['debugWaterBalance'] + # TDOD: Perform water balance checks for aggregates values (from values of each land cover type). + # limitAbstraction self.limitAbstraction = False - #if iniItems.landSurfaceOptions['limitAbstraction'] == "True": self.limitAbstraction = True - if configget(iniItems,"landSurfaceOptions","limitAbstraction","False") == "True":self.limitAbstraction = True + # if iniItems.landSurfaceOptions['limitAbstraction'] == "True": self.limitAbstraction = True + if ( + configget(iniItems, "landSurfaceOptions", "limitAbstraction", "False") + == "True" + ): + self.limitAbstraction = True - # landCover types included in the simulation: - self.coverTypes = ["forest","grassland"] + # landCover types included in the simulation: + self.coverTypes = ["forest", "grassland"] # self.includeIrrigation = False - #if iniItems.landSurfaceOptions['includeIrrigation'] == "True": - if configget(iniItems,"landSurfaceOptions","includeIrrigation","False") == "True": + # if iniItems.landSurfaceOptions['includeIrrigation'] == "True": + if ( + configget(iniItems, "landSurfaceOptions", "includeIrrigation", "False") + == "True" + ): self.includeIrrigation = True - self.coverTypes += ["irrPaddy","irrNonPaddy"] + self.coverTypes += ["irrPaddy", "irrNonPaddy"] logger.info("Irrigation is included/considered in this run.") - else: + else: logger.info("Irrigation is NOT included/considered in this run.") - - # if user define their land cover types: - if 'landCoverTypes' in configsection(iniItems,"landSurfaceOptions"): #iniItems.landSurfaceOptions.keys(): - self.coverTypes = iniItems.get("landSurfaceOptions","landCoverTypes").split(",") #iniItems.landSurfaceOptions['landCoverTypes'].split(",") - # water demand options: irrigation efficiency, non irrigation water demand, and desalination supply + # if user define their land cover types: + if "landCoverTypes" in configsection( + iniItems, "landSurfaceOptions" + ): # iniItems.landSurfaceOptions.keys(): + self.coverTypes = iniItems.get( + "landSurfaceOptions", "landCoverTypes" + ).split( + "," + ) # iniItems.landSurfaceOptions['landCoverTypes'].split(",") + + # water demand options: irrigation efficiency, non irrigation water demand, and desalination supply self.waterDemandOptions(iniItems) - + # TODO: Make an option so that users can easily perform natural runs (without water user, without reservoirs). - + # pre-defined surface water source fraction for satisfying irrigation and livestock water demand self.swAbstractionFractionData = None self.swAbstractionFractionDataQuality = None - if 'irrigationSurfaceWaterAbstractionFractionData' in configsection(iniItems,"landSurfaceOptions") and\ - 'irrigationSurfaceWaterAbstractionFractionDataQuality' in configsection(iniItems,"landSurfaceOptions"): - if configget(iniItems,"landSurfaceOptions","irrigationSurfaceWaterAbstractionFractionData","None") not in ["None", "False"] or\ - configget(iniItems,"landSurfaceOptions","irrigationSurfaceWaterAbstractionFractionDataQuality", "None") not in ["None", "False"]: - #iniItems.landSurfaceOptions['irrigationSurfaceWaterAbstractionFractionDataQuality'] not in ["None", "False"]: - - logger.info('Using/incorporating the predefined surface water source of Siebert et al. (2010) for satisfying irrigation and livestock demand.') - self.swAbstractionFractionData = pcr.cover(\ - #vos.readPCRmapClone(iniItems.landSurfaceOptions['irrigationSurfaceWaterAbstractionFractionData'],\ - vos.readPCRmapClone(configget(iniItems,"landSurfaceOptions","irrigationSurfaceWaterAbstractionFractionData","None"),\ - self.cloneMap,self.tmpDir,self.inputDir), 0.0) - self.swAbstractionFractionData = pcr.ifthen(self.swAbstractionFractionData >= 0.0, \ - self.swAbstractionFractionData ) - self.swAbstractionFractionDataQuality = \ - pcr.cover(\ - #vos.readPCRmapClone(iniItems.landSurfaceOptions['irrigationSurfaceWaterAbstractionFractionDataQuality'],\ - vos.readPCRmapClone(configget(iniItems,"landSurfaceOptions","irrigationSurfaceWaterAbstractionFractionDataQuality","None"),\ - self.cloneMap,self.tmpDir,self.inputDir), 0.0) - # ignore value with the quality above 5 (very bad) - # - Note: The resulting map has values only in cells with the data auality <= 5.0 - self.swAbstractionFractionData = pcr.ifthen(self.swAbstractionFractionDataQuality <= 5.0, \ - self.swAbstractionFractionData) + if "irrigationSurfaceWaterAbstractionFractionData" in configsection( + iniItems, "landSurfaceOptions" + ) and "irrigationSurfaceWaterAbstractionFractionDataQuality" in configsection( + iniItems, "landSurfaceOptions" + ): + if configget( + iniItems, + "landSurfaceOptions", + "irrigationSurfaceWaterAbstractionFractionData", + "None", + ) not in ["None", "False"] or configget( + iniItems, + "landSurfaceOptions", + "irrigationSurfaceWaterAbstractionFractionDataQuality", + "None", + ) not in [ + "None", + "False", + ]: + # iniItems.landSurfaceOptions['irrigationSurfaceWaterAbstractionFractionDataQuality'] not in ["None", "False"]: + logger.info( + "Using/incorporating the predefined surface water source of Siebert et al. (2010) for satisfying irrigation and livestock demand." + ) + self.swAbstractionFractionData = pcr.cover( + # vos.readPCRmapClone(iniItems.landSurfaceOptions['irrigationSurfaceWaterAbstractionFractionData'],\ + vos.readPCRmapClone( + configget( + iniItems, + "landSurfaceOptions", + "irrigationSurfaceWaterAbstractionFractionData", + "None", + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ), + 0.0, + ) + self.swAbstractionFractionData = pcr.ifthen( + self.swAbstractionFractionData >= 0.0, + self.swAbstractionFractionData, + ) + self.swAbstractionFractionDataQuality = pcr.cover( + # vos.readPCRmapClone(iniItems.landSurfaceOptions['irrigationSurfaceWaterAbstractionFractionDataQuality'],\ + vos.readPCRmapClone( + configget( + iniItems, + "landSurfaceOptions", + "irrigationSurfaceWaterAbstractionFractionDataQuality", + "None", + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ), + 0.0, + ) + # ignore value with the quality above 5 (very bad) + # - Note: The resulting map has values only in cells with the data auality <= 5.0 + self.swAbstractionFractionData = pcr.ifthen( + self.swAbstractionFractionDataQuality <= 5.0, + self.swAbstractionFractionData, + ) + # maximum pre-defined surface water source fraction for satisfying industrial and domestic water demand: - # - if not defined (default), set it to the maximum + # - if not defined (default), set it to the maximum self.maximumNonIrrigationSurfaceWaterAbstractionFractionData = pcr.scalar(1.0) # - based on the map of McDonald et al. (2014) - if 'maximumNonIrrigationSurfaceWaterAbstractionFractionData' in configsection(iniItems,"landSurfaceOptions"): - if configget(iniItems,"landSurfaceOptions","maximumNonIrrigationSurfaceWaterAbstractionFractionData","None") != "None" or\ - configget(iniItems,"landSurfaceOptions","maximumNonIrrigationSurfaceWaterAbstractionFractionData","False") != "False": + if "maximumNonIrrigationSurfaceWaterAbstractionFractionData" in configsection( + iniItems, "landSurfaceOptions" + ): + if ( + configget( + iniItems, + "landSurfaceOptions", + "maximumNonIrrigationSurfaceWaterAbstractionFractionData", + "None", + ) + != "None" + or configget( + iniItems, + "landSurfaceOptions", + "maximumNonIrrigationSurfaceWaterAbstractionFractionData", + "False", + ) + != "False" + ): - logger.info('Using/incorporating the predefined surface water source of McDonald et al. (2014) for satisfying domestic and industrial demand.') - self.maximumNonIrrigationSurfaceWaterAbstractionFractionData = pcr.min(1.0,\ - pcr.cover(\ - #vos.readPCRmapClone(iniItems.landSurfaceOptions['maximumNonIrrigationSurfaceWaterAbstractionFractionData'],\ - vos.readPCRmapClone(configget(iniItems,"landSurfaceOptions","maximumNonIrrigationSurfaceWaterAbstractionFractionData","None"),\ - self.cloneMap,self.tmpDir,self.inputDir), 1.0)) + logger.info( + "Using/incorporating the predefined surface water source of McDonald et al. (2014) for satisfying domestic and industrial demand." + ) + self.maximumNonIrrigationSurfaceWaterAbstractionFractionData = pcr.min( + 1.0, + pcr.cover( + # vos.readPCRmapClone(iniItems.landSurfaceOptions['maximumNonIrrigationSurfaceWaterAbstractionFractionData'],\ + vos.readPCRmapClone( + configget( + iniItems, + "landSurfaceOptions", + "maximumNonIrrigationSurfaceWaterAbstractionFractionData", + "None", + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ), + 1.0, + ), + ) # threshold values defining the preference for irrigation water source (unit: fraction/percentage) - self.treshold_to_maximize_irrigation_surface_water = \ - vos.readPCRmapClone(configget(iniItems,"landSurfaceOptions","treshold_to_maximize_irrigation_surface_water","1.0"),\ - #vos.readPCRmapClone(iniItems.landSurfaceOptions['treshold_to_maximize_irrigation_surface_water'],\ - self.cloneMap,self.tmpDir,self.inputDir) - self.treshold_to_minimize_fossil_groundwater_irrigation = \ - vos.readPCRmapClone(configget(iniItems,"landSurfaceOptions","treshold_to_minimize_fossil_groundwater_irrigation","1.0"),\ - #vos.readPCRmapClone(iniItems.landSurfaceOptions['treshold_to_minimize_fossil_groundwater_irrigation'],\ - - self.cloneMap,self.tmpDir,self.inputDir) - + self.treshold_to_maximize_irrigation_surface_water = vos.readPCRmapClone( + configget( + iniItems, + "landSurfaceOptions", + "treshold_to_maximize_irrigation_surface_water", + "1.0", + ), + # vos.readPCRmapClone(iniItems.landSurfaceOptions['treshold_to_maximize_irrigation_surface_water'],\ + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.treshold_to_minimize_fossil_groundwater_irrigation = vos.readPCRmapClone( + configget( + iniItems, + "landSurfaceOptions", + "treshold_to_minimize_fossil_groundwater_irrigation", + "1.0", + ), + # vos.readPCRmapClone(iniItems.landSurfaceOptions['treshold_to_minimize_fossil_groundwater_irrigation'],\ + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + # assign the topography and soil parameters self.soil_topo_parameters = {} - # - default values used for all land cover types - self.soil_topo_parameters['default'] = parSoilAndTopo.SoilAndTopoParameters(iniItems,self.landmask,self.inputDir,self.cloneMap,self.tmpDir) - self.soil_topo_parameters['default'].read(iniItems) - # - specific soil and topography parameter (per land cover type) + # - default values used for all land cover types + self.soil_topo_parameters["default"] = parSoilAndTopo.SoilAndTopoParameters( + iniItems, self.landmask, self.inputDir, self.cloneMap, self.tmpDir + ) + self.soil_topo_parameters["default"].read(iniItems) + # - specific soil and topography parameter (per land cover type) for coverType in self.coverTypes: - name_of_section_given_in_ini_file = str(coverType)+'Options' - dictionary_of_land_cover_settings = iniItems._sections[name_of_section_given_in_ini_file] #__getattribute__(name_of_section_given_in_ini_file) - - if 'usingSpecificSoilTopo' not in dictionary_of_land_cover_settings.keys(): dictionary_of_land_cover_settings['usingSpecificSoilTopo'] = "False" - if dictionary_of_land_cover_settings['usingSpecificSoilTopo'] == "True": - - msg = "Using a specific set of soil and topo parameters " - msg += "as defined in the "+name_of_section_given_in_ini_file+" of the ini/configuration file." - - self.soil_topo_parameters[coverType] = parSoilAndTopo.SoilAndTopoParameters(iniItems,self.landmask,self.inputDir,self.cloneMap,self.tmpDir) - self.soil_topo_parameters[coverType].read(iniItems, dictionary_of_land_cover_settings) + name_of_section_given_in_ini_file = str(coverType) + "Options" + dictionary_of_land_cover_settings = iniItems._sections[ + name_of_section_given_in_ini_file + ] # __getattribute__(name_of_section_given_in_ini_file) + + if "usingSpecificSoilTopo" not in dictionary_of_land_cover_settings.keys(): + dictionary_of_land_cover_settings["usingSpecificSoilTopo"] = "False" + if dictionary_of_land_cover_settings["usingSpecificSoilTopo"] == "True": + + msg = "Using a specific set of soil and topo parameters " + msg += ( + "as defined in the " + + name_of_section_given_in_ini_file + + " of the ini/configuration file." + ) + + self.soil_topo_parameters[ + coverType + ] = parSoilAndTopo.SoilAndTopoParameters( + iniItems, self.landmask, self.inputDir, self.cloneMap, self.tmpDir + ) + self.soil_topo_parameters[coverType].read( + iniItems, dictionary_of_land_cover_settings + ) else: - msg = "Using the default set of soil and topo parameters " - msg += "as defined in the landSurfaceOptions of the ini/configuration file." + msg = "Using the default set of soil and topo parameters " + msg += "as defined in the landSurfaceOptions of the ini/configuration file." - self.soil_topo_parameters[coverType] = self.soil_topo_parameters['default'] + self.soil_topo_parameters[coverType] = self.soil_topo_parameters[ + "default" + ] logger.info(msg) - # instantiate self.landCoverObj[coverType] self.landCoverObj = {} - for coverType in self.coverTypes: - self.landCoverObj[coverType] = lc.LandCover(iniItems,\ - str(coverType)+'Options',\ - self.soil_topo_parameters[coverType],self.landmask,\ - self.irrigationEfficiency,\ - self.cloneMap, self.inputDir, self.tmpDir, self.usingAllocSegments) - + for coverType in self.coverTypes: + self.landCoverObj[coverType] = lc.LandCover( + iniItems, + str(coverType) + "Options", + self.soil_topo_parameters[coverType], + self.landmask, + self.irrigationEfficiency, + self.cloneMap, + self.inputDir, + self.tmpDir, + self.usingAllocSegments, + ) + # rescale landCover Fractions # - by default, the land cover fraction will always be corrected (to ensure the total of all fractions = 1.0) self.noLandCoverFractionCorrection = False - if "noLandCoverFractionCorrection" in configsection(iniItems,"landSurfaceOptions"): #iniItems.landSurfaceOptions.keys(): - #if iniItems.landSurfaceOptions["noLandCoverFractionCorrection"] == "True": self.noLandCoverFractionCorrection = True: - if configget(iniItems,"landSurfaceOptions","noLandCoverFractionCorrection","False") == "True": self.noLandCoverFractionCorrection = True + if "noLandCoverFractionCorrection" in configsection( + iniItems, "landSurfaceOptions" + ): # iniItems.landSurfaceOptions.keys(): + # if iniItems.landSurfaceOptions["noLandCoverFractionCorrection"] == "True": self.noLandCoverFractionCorrection = True: + if ( + configget( + iniItems, + "landSurfaceOptions", + "noLandCoverFractionCorrection", + "False", + ) + == "True" + ): + self.noLandCoverFractionCorrection = True # - rescaling land cover fractions if self.noLandCoverFractionCorrection == False: self.scaleNaturalLandCoverFractions() - if self.includeIrrigation: self.scaleModifiedLandCoverFractions() - + if self.includeIrrigation: + self.scaleModifiedLandCoverFractions() + # an option to introduce changes of land cover parameters (not only fracVegCover) self.noAnnualChangesInLandCoverParameter = True - if 'annualChangesInLandCoverParameters' in configsection(iniItems,"landSurfaceOptions"): - #if iniItems.landSurfaceOptions['annualChangesInLandCoverParameters'] == "True": self.noAnnualChangesInLandCoverParameter = False - if configget(iniItems,"landSurfaceOptions","annualChangesInLandCoverParameters","False") == "True": self.noAnnualChangesInLandCoverParameter = False + if "annualChangesInLandCoverParameters" in configsection( + iniItems, "landSurfaceOptions" + ): + # if iniItems.landSurfaceOptions['annualChangesInLandCoverParameters'] == "True": self.noAnnualChangesInLandCoverParameter = False + if ( + configget( + iniItems, + "landSurfaceOptions", + "annualChangesInLandCoverParameters", + "False", + ) + == "True" + ): + self.noAnnualChangesInLandCoverParameter = False # Note that "dynamicIrrigationArea" CANNOT be combined with "noLandCoverFractionCorrection" - if self.noLandCoverFractionCorrection: self.dynamicIrrigationArea = False - + if self.noLandCoverFractionCorrection: + self.dynamicIrrigationArea = False + # Also note that "noAnnualChangesInLandCoverParameter = False" must be followed by "noLandCoverFractionCorrection" - if self.noAnnualChangesInLandCoverParameter == False and self.noLandCoverFractionCorrection == False: + if ( + self.noAnnualChangesInLandCoverParameter == False + and self.noLandCoverFractionCorrection == False + ): self.noLandCoverFractionCorrection = True msg = "WARNING! No land cover fraction correction will be performed. Please make sure that the 'total' of all fracVegCover adds to one." - logger.warning(msg) - logger.warning(msg) - logger.warning(msg) - logger.warning(msg) - logger.warning(msg) - - ######################################################################################################################################################################################### - # 29 July 2014: - # - # If using historical/dynamic irrigation file (changing every year), we have to get fraction over irrigation area + logger.warning(msg) + logger.warning(msg) + logger.warning(msg) + logger.warning(msg) + logger.warning(msg) + + ######################################################################################################################################################################################### + # 29 July 2014: + # + # If using historical/dynamic irrigation file (changing every year), we have to get fraction over irrigation area # (in order to calculate irrigation area for each irrigation type) # # Note that: totalIrrAreaFrac = fraction irrigated areas (e.g. paddy + nonPaddy) over the entire cell area (dimensionless) ; this value changes (if self.dynamicIrrigationArea = True) # irrTypeFracOverIrr = fraction each land cover type (paddy or nonPaddy) over the irrigation area (dimensionless) ; this value is constant for the entire simulation # if self.dynamicIrrigationArea: - - logger.info('Determining fraction of total irrigated areas over each cell') - # Note that this is needed ONLY if historical irrigation areas are used (if self.dynamicIrrigationArea = True). - - # total irrigated area fraction (over the entire cell) - totalIrrAreaFrac = 0.0 + + logger.info("Determining fraction of total irrigated areas over each cell") + # Note that this is needed ONLY if historical irrigation areas are used (if self.dynamicIrrigationArea = True). + + # total irrigated area fraction (over the entire cell) + totalIrrAreaFrac = 0.0 for coverType in self.coverTypes: - if coverType.startswith('irr'): + if coverType.startswith("irr"): totalIrrAreaFrac += self.landCoverObj[coverType].fracVegCover - - # fraction over irrigation area + + # fraction over irrigation area for coverType in self.coverTypes: - if coverType.startswith('irr'): - self.landCoverObj[coverType].irrTypeFracOverIrr = vos.getValDivZero(self.landCoverObj[coverType].fracVegCover,\ - totalIrrAreaFrac, vos.smallNumber) + if coverType.startswith("irr"): + self.landCoverObj[coverType].irrTypeFracOverIrr = vos.getValDivZero( + self.landCoverObj[coverType].fracVegCover, + totalIrrAreaFrac, + vos.smallNumber, + ) # get the initial conditions (for every land cover type) self.getInitialConditions(iniItems, initialState) # initiate old style reporting (this is useful for debuging) self.initiate_old_style_land_surface_reporting(iniItems) - + # make iniItems available for the other methods/functions: self.iniItems = iniItems + def initiate_old_style_land_surface_reporting(self, iniItems): - def initiate_old_style_land_surface_reporting(self,iniItems): - self.report = True try: - self.outDailyTotNC = iniItems.get("landSurfaceOptions","outDailyTotNC").split(",") - self.outMonthTotNC = iniItems.get("landSurfaceOptions","outMonthTotNC").split(",") - self.outMonthAvgNC = iniItems.get("landSurfaceOptions","outMonthAvgNC").split(",") - self.outMonthEndNC = iniItems.get("landSurfaceOptions","outMonthEndNC").split(",") - self.outAnnuaTotNC = iniItems.get("landSurfaceOptions","outAnnuaTotNC").split(",") - self.outAnnuaAvgNC = iniItems.get("landSurfaceOptions","outAnnuaAvgNC").split(",") - self.outAnnuaEndNC = iniItems.get("landSurfaceOptions","outAnnuaEndNC").split(",") + self.outDailyTotNC = iniItems.get( + "landSurfaceOptions", "outDailyTotNC" + ).split(",") + self.outMonthTotNC = iniItems.get( + "landSurfaceOptions", "outMonthTotNC" + ).split(",") + self.outMonthAvgNC = iniItems.get( + "landSurfaceOptions", "outMonthAvgNC" + ).split(",") + self.outMonthEndNC = iniItems.get( + "landSurfaceOptions", "outMonthEndNC" + ).split(",") + self.outAnnuaTotNC = iniItems.get( + "landSurfaceOptions", "outAnnuaTotNC" + ).split(",") + self.outAnnuaAvgNC = iniItems.get( + "landSurfaceOptions", "outAnnuaAvgNC" + ).split(",") + self.outAnnuaEndNC = iniItems.get( + "landSurfaceOptions", "outAnnuaEndNC" + ).split(",") except: self.report = False if self.report == True: - #include self.outNCDir in wflow_pcrgobwb? - self.outNCDir = vos.getFullPath("netcdf/", \ - iniItems.get("globalOptions","outputDir")) #iniItems.outNCDir + # include self.outNCDir in wflow_pcrgobwb? + self.outNCDir = vos.getFullPath( + "netcdf/", iniItems.get("globalOptions", "outputDir") + ) # iniItems.outNCDir self.netcdfObj = PCR2netCDF(iniItems) # # daily output in netCDF files: if self.outDailyTotNC[0] != "None": for var in self.outDailyTotNC: # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_dailyTot.nc",\ - var,"undefined") + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_dailyTot.nc", + var, + "undefined", + ) # MONTHly output in netCDF files: # - cummulative if self.outMonthTotNC[0] != "None": for var in self.outMonthTotNC: # initiating monthlyVarTot (accumulator variable): - vars(self)[var+'MonthTot'] = None + vars(self)[var + "MonthTot"] = None # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthTot.nc",\ - var,"undefined") + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthTot.nc", + var, + "undefined", + ) # - average if self.outMonthAvgNC[0] != "None": for var in self.outMonthAvgNC: # initiating monthlyTotAvg (accumulator variable) - vars(self)[var+'MonthTot'] = None + vars(self)[var + "MonthTot"] = None # initiating monthlyVarAvg: - vars(self)[var+'MonthAvg'] = None - # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthAvg.nc",\ - var,"undefined") + vars(self)[var + "MonthAvg"] = None + # creating the netCDF files: + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthAvg.nc", + var, + "undefined", + ) # - last day of the month if self.outMonthEndNC[0] != "None": for var in self.outMonthEndNC: - # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthEnd.nc",\ - var,"undefined") + # creating the netCDF files: + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthEnd.nc", + var, + "undefined", + ) # YEARly output in netCDF files: # - cummulative if self.outAnnuaTotNC[0] != "None": for var in self.outAnnuaTotNC: # initiating yearly accumulator variable: - vars(self)[var+'AnnuaTot'] = None + vars(self)[var + "AnnuaTot"] = None # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaTot.nc",\ - var,"undefined") + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaTot.nc", + var, + "undefined", + ) # - average if self.outAnnuaAvgNC[0] != "None": for var in self.outAnnuaAvgNC: # initiating annualyVarAvg: - vars(self)[var+'AnnuaAvg'] = None + vars(self)[var + "AnnuaAvg"] = None # initiating annualyTotAvg (accumulator variable) - vars(self)[var+'AnnuaTot'] = None - # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaAvg.nc",\ - var,"undefined") + vars(self)[var + "AnnuaTot"] = None + # creating the netCDF files: + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaAvg.nc", + var, + "undefined", + ) # - last day of the year if self.outAnnuaEndNC[0] != "None": for var in self.outAnnuaEndNC: - # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaEnd.nc",\ - var,"undefined") + # creating the netCDF files: + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaEnd.nc", + var, + "undefined", + ) - def getInitialConditions(self, iniItems, iniConditions = None): + def getInitialConditions(self, iniItems, iniConditions=None): # starting year in integer - starting_year = self.startTime.timetuple().tm_year#int(iniItems.get("run","starttime")[0:4]) + starting_year = ( + self.startTime.timetuple().tm_year + ) # int(iniItems.get("run","starttime")[0:4]) # # check if the run start at the first day of the year: start_on_1_Jan = False - #if iniItems.get("run","starttime")[-5:] == "01-01": start_on_1_Jan = True: - if self.startTime.timetuple().tm_yday == 1 and self.startTime.month == 1: + # if iniItems.get("run","starttime")[-5:] == "01-01": start_on_1_Jan = True: + if self.startTime.timetuple().tm_yday == 1 and self.startTime.month == 1: start_on_1_Jan = True - # condition to consider previous year land cover fraction + # condition to consider previous year land cover fraction consider_previous_year_land_cover_fraction = False - ####################################################################################################################################### # obtaining initial land cover fractions for runs with dynamicIrrigationArea # - # For non spin-up runs that start at the first day of the year (1 January), + # For non spin-up runs that start at the first day of the year (1 January), # - we have to consider the previous year land cover fractions, specifically if we consider the dynamic/expansion of irrigation areas # - if iniConditions == None and start_on_1_Jan == True and \ - self.dynamicIrrigationArea and self.noLandCoverFractionCorrection == False: + if ( + iniConditions == None + and start_on_1_Jan == True + and self.dynamicIrrigationArea + and self.noLandCoverFractionCorrection == False + ): # obtain the previous year land cover fractions: - self.scaleDynamicIrrigation(starting_year - 1) # the previous year land cover fractions + self.scaleDynamicIrrigation( + starting_year - 1 + ) # the previous year land cover fractions consider_previous_year_land_cover_fraction = True # # For spin-up runs or for runs that start after 1 January, # - we do not have to consider the previous year land cover fractions # - if consider_previous_year_land_cover_fraction == False and \ - self.dynamicIrrigationArea and self.noLandCoverFractionCorrection == False: + if ( + consider_previous_year_land_cover_fraction == False + and self.dynamicIrrigationArea + and self.noLandCoverFractionCorrection == False + ): # just using the current year land cover fractions: - self.scaleDynamicIrrigation(starting_year) # the current year land cover fractions + self.scaleDynamicIrrigation( + starting_year + ) # the current year land cover fractions # ################################################################################################################################# ####################################################################################################################################### - # obtaining initial land cover fractions for runs with noLandCoverFractionCorrection and annualChangesInLandCoverParameters + # obtaining initial land cover fractions for runs with noLandCoverFractionCorrection and annualChangesInLandCoverParameters # - # For non spin-up runs that start at the first day of the year (1 January), + # For non spin-up runs that start at the first day of the year (1 January), # - we have to consider the previous year land cover fractions # - if iniConditions == None and start_on_1_Jan == True and \ - self.noLandCoverFractionCorrection and self.noAnnualChangesInLandCoverParameter == False: + if ( + iniConditions == None + and start_on_1_Jan == True + and self.noLandCoverFractionCorrection + and self.noAnnualChangesInLandCoverParameter == False + ): # obtain the previous year land cover fractions: previous_year = starting_year - 1 - one_january_prev_year = str(previous_year)+"-01-01" + one_january_prev_year = str(previous_year) + "-01-01" for coverType in self.coverTypes: - self.landCoverObj[coverType].previousFracVegCover = self.landCoverObj[coverType].get_land_cover_parameters(date_in_string = one_january_prev_year, \ - get_only_fracVegCover = True) - + self.landCoverObj[coverType].previousFracVegCover = self.landCoverObj[ + coverType + ].get_land_cover_parameters( + date_in_string=one_january_prev_year, get_only_fracVegCover=True + ) + #################################################################################################################################################################### # correcting land cover fractions total_fractions = pcr.scalar(0.0) for coverType in self.coverTypes: - total_fractions += self.landCoverObj[coverType].previousFracVegCover + total_fractions += self.landCoverObj[coverType].previousFracVegCover - if 'grassland' in self.landCoverObj.keys(): - self.landCoverObj['grassland'].previousFracVegCover = pcr.ifthenelse(total_fractions > 0.1, self.landCoverObj['grassland'].previousFracVegCover, 1.0) - - if 'short_natural' in self.landCoverObj.keys(): - self.landCoverObj['short_natural'].previousFracVegCover = pcr.ifthenelse(total_fractions > 0.1, self.landCoverObj['short_natural'].previousFracVegCover, 1.0) + if "grassland" in self.landCoverObj.keys(): + self.landCoverObj["grassland"].previousFracVegCover = pcr.ifthenelse( + total_fractions > 0.1, + self.landCoverObj["grassland"].previousFracVegCover, + 1.0, + ) + if "short_natural" in self.landCoverObj.keys(): + self.landCoverObj[ + "short_natural" + ].previousFracVegCover = pcr.ifthenelse( + total_fractions > 0.1, + self.landCoverObj["short_natural"].previousFracVegCover, + 1.0, + ) + total_fractions = pcr.scalar(0.0) for coverType in self.coverTypes: - total_fractions += self.landCoverObj[coverType].previousFracVegCover + total_fractions += self.landCoverObj[coverType].previousFracVegCover for coverType in self.coverTypes: - self.landCoverObj[coverType].previousFracVegCover = self.landCoverObj[coverType].previousFracVegCover / total_fractions + self.landCoverObj[coverType].previousFracVegCover = ( + self.landCoverObj[coverType].previousFracVegCover / total_fractions + ) #################################################################################################################################################################### - + consider_previous_year_land_cover_fraction = True # For spin-up runs or for runs that start after 1 January, # - we do not have to consider the previous year land cover fractions # - if consider_previous_year_land_cover_fraction == False and \ - self.noLandCoverFractionCorrection and self.noAnnualChangesInLandCoverParameter == False: + if ( + consider_previous_year_land_cover_fraction == False + and self.noLandCoverFractionCorrection + and self.noAnnualChangesInLandCoverParameter == False + ): # just using the current year land cover fractions: - one_january_this_year = str(starting_year)+"-01-01" + one_january_this_year = str(starting_year) + "-01-01" for coverType in self.coverTypes: - self.landCoverObj[coverType].previousFracVegCover = self.landCoverObj[coverType].get_land_cover_parameters(date_in_string = one_january_this_year, \ - get_only_fracVegCover = True) + self.landCoverObj[coverType].previousFracVegCover = self.landCoverObj[ + coverType + ].get_land_cover_parameters( + date_in_string=one_january_this_year, get_only_fracVegCover=True + ) #################################################################################################################################################################### # correcting land cover fractions total_fractions = pcr.scalar(0.0) for coverType in self.coverTypes: - total_fractions += self.landCoverObj[coverType].previousFracVegCover + total_fractions += self.landCoverObj[coverType].previousFracVegCover - if 'grassland' in self.landCoverObj.keys(): - self.landCoverObj['grassland'].previousFracVegCover = pcr.ifthenelse(total_fractions > 0.1, self.landCoverObj['grassland'].previousFracVegCover, 1.0) - - if 'short_natural' in self.landCoverObj.keys(): - self.landCoverObj['short_natural'].previousFracVegCover = pcr.ifthenelse(total_fractions > 0.1, self.landCoverObj['short_natural'].previousFracVegCover, 1.0) + if "grassland" in self.landCoverObj.keys(): + self.landCoverObj["grassland"].previousFracVegCover = pcr.ifthenelse( + total_fractions > 0.1, + self.landCoverObj["grassland"].previousFracVegCover, + 1.0, + ) + if "short_natural" in self.landCoverObj.keys(): + self.landCoverObj[ + "short_natural" + ].previousFracVegCover = pcr.ifthenelse( + total_fractions > 0.1, + self.landCoverObj["short_natural"].previousFracVegCover, + 1.0, + ) + total_fractions = pcr.scalar(0.0) for coverType in self.coverTypes: - total_fractions += self.landCoverObj[coverType].previousFracVegCover + total_fractions += self.landCoverObj[coverType].previousFracVegCover for coverType in self.coverTypes: - self.landCoverObj[coverType].previousFracVegCover = self.landCoverObj[coverType].previousFracVegCover / total_fractions + self.landCoverObj[coverType].previousFracVegCover = ( + self.landCoverObj[coverType].previousFracVegCover / total_fractions + ) #################################################################################################################################################################### - - + # get initial conditions - # - first, we set all aggregated states to zero (only the ones in mainStates): - for var in self.mainStates: vars(self)[var] = pcr.scalar(0.0) - # - then we initiate them in the following loop of land cover types: + # - first, we set all aggregated states to zero (only the ones in mainStates): + for var in self.mainStates: + vars(self)[var] = pcr.scalar(0.0) + # - then we initiate them in the following loop of land cover types: for coverType in self.coverTypes: if iniConditions != None: - self.landCoverObj[coverType].getICsLC(iniItems,iniConditions['landSurface'][coverType]) + self.landCoverObj[coverType].getICsLC( + iniItems, iniConditions["landSurface"][coverType] + ) else: self.landCoverObj[coverType].getICsLC(iniItems) # summarize/aggregate the initial states/storages (using the initial land cover fractions: previousFracVegCover) for var in self.mainStates: - # - initial land cover fractions (dimensionless) - if isinstance(self.landCoverObj[coverType].previousFracVegCover, types.NoneType): - self.landCoverObj[coverType].previousFracVegCover = self.landCoverObj[coverType].fracVegCover + # - initial land cover fractions (dimensionless) + if isinstance( + self.landCoverObj[coverType].previousFracVegCover, types.NoneType + ): + self.landCoverObj[ + coverType + ].previousFracVegCover = self.landCoverObj[coverType].fracVegCover land_cover_fraction = self.landCoverObj[coverType].previousFracVegCover # - initial land cover states (unit: m) land_cover_states = vars(self.landCoverObj[coverType])[var] - vars(self)[var] += land_cover_states * land_cover_fraction + vars(self)[var] += land_cover_states * land_cover_fraction - def waterDemandOptions(self,iniItems): + def waterDemandOptions(self, iniItems): # domestic water demand (unit: m/day) # self.domesticWaterDemandOption = False - if configget(iniItems,"landSurfaceOptions","includeDomesticWaterDemand","False") == "True": + if ( + configget( + iniItems, "landSurfaceOptions", "includeDomesticWaterDemand", "False" + ) + == "True" + ): logger.info("Domestic water demand is included in the calculation.") - self.domesticWaterDemandOption = True + self.domesticWaterDemandOption = True else: logger.info("Domestic water demand is NOT included in the calculation.") # if self.domesticWaterDemandOption: - self.domesticWaterDemandFile = vos.getFullPath(\ - configget(iniItems,"landSurfaceOptions","domesticWaterDemandFile","None"),self.inputDir,False) + self.domesticWaterDemandFile = vos.getFullPath( + configget( + iniItems, "landSurfaceOptions", "domesticWaterDemandFile", "None" + ), + self.inputDir, + False, + ) # industry water demand (unit: m/day) # self.industryWaterDemandOption = False - if configget(iniItems,"landSurfaceOptions","includeIndustryWaterDemand","False") == "True": + if ( + configget( + iniItems, "landSurfaceOptions", "includeIndustryWaterDemand", "False" + ) + == "True" + ): logger.info("Industry water demand is included in the calculation.") - self.industryWaterDemandOption = True + self.industryWaterDemandOption = True else: logger.info("Industry water demand is NOT included in the calculation.") # if self.industryWaterDemandOption: - self.industryWaterDemandFile = vos.getFullPath(\ - configget(iniItems,"landSurfaceOptions","industryWaterDemandFile","None"),self.inputDir,False) + self.industryWaterDemandFile = vos.getFullPath( + configget( + iniItems, "landSurfaceOptions", "industryWaterDemandFile", "None" + ), + self.inputDir, + False, + ) # livestock water demand (unit: m/day) self.livestockWaterDemandOption = False - if configget(iniItems,"landSurfaceOptions","includeLivestockWaterDemand","False") == "True": + if ( + configget( + iniItems, "landSurfaceOptions", "includeLivestockWaterDemand", "False" + ) + == "True" + ): logger.info("Livestock water demand is included in the calculation.") - self.livestockWaterDemandOption = True + self.livestockWaterDemandOption = True else: logger.info("Livestock water demand is NOT included in the calculation.") # if self.livestockWaterDemandOption: - self.livestockWaterDemandFile = vos.getFullPath(\ - configget(iniItems,"landSurfaceOptions","livestockWaterDemandFile","None"),self.inputDir,False) - + self.livestockWaterDemandFile = vos.getFullPath( + configget( + iniItems, "landSurfaceOptions", "livestockWaterDemandFile", "None" + ), + self.inputDir, + False, + ) + # historical irrigation area (unit: hectar) self.dynamicIrrigationArea = False - if configget(iniItems,"landSurfaceOptions","historicalIrrigationArea","None") != "None": - logger.info("Using the dynamicIrrigationArea option. Extent of irrigation areas is based on the file provided in the 'historicalIrrigationArea'.") + if ( + configget( + iniItems, "landSurfaceOptions", "historicalIrrigationArea", "None" + ) + != "None" + ): + logger.info( + "Using the dynamicIrrigationArea option. Extent of irrigation areas is based on the file provided in the 'historicalIrrigationArea'." + ) self.dynamicIrrigationArea = True # if self.dynamicIrrigationArea: - self.dynamicIrrigationAreaFile = vos.getFullPath(\ - configget(iniItems,"landSurfaceOptions","historicalIrrigationArea","None"),self.inputDir,False) - - # irrigation efficiency map (in percentage) # TODO: Using the time series of efficiency (considering historical technological development). - self.irrigationEfficiency = vos.readPCRmapClone(\ - configget(iniItems,"landSurfaceOptions","irrigationEfficiency","1.00"), - self.cloneMap,self.tmpDir,self.inputDir) - # extrapolate efficiency map: # TODO: Make a better extrapolation algorithm (considering cell size, etc.). + self.dynamicIrrigationAreaFile = vos.getFullPath( + configget( + iniItems, "landSurfaceOptions", "historicalIrrigationArea", "None" + ), + self.inputDir, + False, + ) + + # irrigation efficiency map (in percentage) # TODO: Using the time series of efficiency (considering historical technological development). + self.irrigationEfficiency = vos.readPCRmapClone( + configget(iniItems, "landSurfaceOptions", "irrigationEfficiency", "1.00"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + # extrapolate efficiency map: # TODO: Make a better extrapolation algorithm (considering cell size, etc.). window_size = 1.25 * pcr.clone().cellSize() - window_size = min(window_size, min(pcr.clone().nrRows(), pcr.clone().nrCols())*pcr.clone().cellSize()) + window_size = min( + window_size, + min(pcr.clone().nrRows(), pcr.clone().nrCols()) * pcr.clone().cellSize(), + ) try: - self.irrigationEfficiency = pcr.cover(self.irrigationEfficiency, pcr.windowaverage(self.irrigationEfficiency, window_size)) - self.irrigationEfficiency = pcr.cover(self.irrigationEfficiency, pcr.windowaverage(self.irrigationEfficiency, window_size)) - self.irrigationEfficiency = pcr.cover(self.irrigationEfficiency, pcr.windowaverage(self.irrigationEfficiency, window_size)) - self.irrigationEfficiency = pcr.cover(self.irrigationEfficiency, pcr.windowaverage(self.irrigationEfficiency, window_size)) - self.irrigationEfficiency = pcr.cover(self.irrigationEfficiency, pcr.windowaverage(self.irrigationEfficiency, window_size)) - self.irrigationEfficiency = pcr.cover(self.irrigationEfficiency, pcr.windowaverage(self.irrigationEfficiency, 0.75)) - self.irrigationEfficiency = pcr.cover(self.irrigationEfficiency, pcr.windowaverage(self.irrigationEfficiency, 1.00)) - self.irrigationEfficiency = pcr.cover(self.irrigationEfficiency, pcr.windowaverage(self.irrigationEfficiency, 1.50)) - except: + self.irrigationEfficiency = pcr.cover( + self.irrigationEfficiency, + pcr.windowaverage(self.irrigationEfficiency, window_size), + ) + self.irrigationEfficiency = pcr.cover( + self.irrigationEfficiency, + pcr.windowaverage(self.irrigationEfficiency, window_size), + ) + self.irrigationEfficiency = pcr.cover( + self.irrigationEfficiency, + pcr.windowaverage(self.irrigationEfficiency, window_size), + ) + self.irrigationEfficiency = pcr.cover( + self.irrigationEfficiency, + pcr.windowaverage(self.irrigationEfficiency, window_size), + ) + self.irrigationEfficiency = pcr.cover( + self.irrigationEfficiency, + pcr.windowaverage(self.irrigationEfficiency, window_size), + ) + self.irrigationEfficiency = pcr.cover( + self.irrigationEfficiency, + pcr.windowaverage(self.irrigationEfficiency, 0.75), + ) + self.irrigationEfficiency = pcr.cover( + self.irrigationEfficiency, + pcr.windowaverage(self.irrigationEfficiency, 1.00), + ) + self.irrigationEfficiency = pcr.cover( + self.irrigationEfficiency, + pcr.windowaverage(self.irrigationEfficiency, 1.50), + ) + except: pass - #~ self.irrigationEfficiency = pcr.ifthen(self.landmask, self.irrigationEfficiency) + # ~ self.irrigationEfficiency = pcr.ifthen(self.landmask, self.irrigationEfficiency) self.irrigationEfficiency = pcr.cover(self.irrigationEfficiency, 1.0) self.irrigationEfficiency = pcr.max(0.1, self.irrigationEfficiency) self.irrigationEfficiency = pcr.ifthen(self.landmask, self.irrigationEfficiency) - + # desalination water supply option self.includeDesalination = False - if configget(iniItems,"landSurfaceOptions","desalinationWater","False") not in ["None", "False"]: + if configget( + iniItems, "landSurfaceOptions", "desalinationWater", "False" + ) not in ["None", "False"]: logger.info("Monthly desalination water is included.") self.includeDesalination = True - self.desalinationWaterFile = vos.getFullPath(configget(iniItems,"landSurfaceOptions","desalinationWater","None"), self.inputDir) - else: + self.desalinationWaterFile = vos.getFullPath( + configget(iniItems, "landSurfaceOptions", "desalinationWater", "None"), + self.inputDir, + ) + else: logger.info("Monthly desalination water is NOT included.") # zones at which water allocation (surface and groundwater allocation) is determined self.usingAllocSegments = False self.allocSegments = None - if configget(iniItems,"landSurfaceOptions","allocationSegmentsForGroundSurfaceWater","None") != "None": - self.usingAllocSegments = True - - self.allocSegments = vos.readPCRmapClone(\ - configget(iniItems,"landSurfaceOptions","allocationSegmentsForGroundSurfaceWater","None"), - self.cloneMap,self.tmpDir,self.inputDir,isLddMap=False,cover=None,isNomMap=True) + if ( + configget( + iniItems, + "landSurfaceOptions", + "allocationSegmentsForGroundSurfaceWater", + "None", + ) + != "None" + ): + self.usingAllocSegments = True + + self.allocSegments = vos.readPCRmapClone( + configget( + iniItems, + "landSurfaceOptions", + "allocationSegmentsForGroundSurfaceWater", + "None", + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + isLddMap=False, + cover=None, + isNomMap=True, + ) self.allocSegments = pcr.ifthen(self.landmask, self.allocSegments) - - cellArea = vos.readPCRmapClone(\ - iniItems.get("routingOptions","cellAreaMap"), - self.cloneMap,self.tmpDir,self.inputDir) + + cellArea = vos.readPCRmapClone( + iniItems.get("routingOptions", "cellAreaMap"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) cellArea = pcr.ifthen(self.landmask, cellArea) - self.segmentArea = pcr.areatotal(pcr.cover(cellArea, 0.0), self.allocSegments) + self.segmentArea = pcr.areatotal( + pcr.cover(cellArea, 0.0), self.allocSegments + ) self.segmentArea = pcr.ifthen(self.landmask, self.segmentArea) else: - logger.info("If there is any, water demand is satisfied by local source only.") + logger.info( + "If there is any, water demand is satisfied by local source only." + ) + def scaleNaturalLandCoverFractions(self): + """ rescales natural land cover fractions (make sure the total = 1)""" - def scaleNaturalLandCoverFractions(self): - ''' rescales natural land cover fractions (make sure the total = 1)''' - # total land cover fractions pristineAreaFrac = 0.0 numb_of_lc_types = 0.0 - for coverType in self.coverTypes: - if not coverType.startswith('irr'): - pristineAreaFrac += pcr.cover(self.landCoverObj[coverType].fracVegCover, 0.0) + for coverType in self.coverTypes: + if not coverType.startswith("irr"): + pristineAreaFrac += pcr.cover( + self.landCoverObj[coverType].fracVegCover, 0.0 + ) numb_of_lc_types += 1.0 # Fill cells with pristineAreaFrac < 0.0 - with window average value within 0.5 and 1.5 degree - for coverType in self.coverTypes: - if not coverType.startswith('irr'): + for coverType in self.coverTypes: + if not coverType.startswith("irr"): - filled_fractions = pcr.windowaverage(self.landCoverObj[coverType].fracVegCover,0.5) - filled_fractions = pcr.cover(filled_fractions,\ - pcr.windowaverage(self.landCoverObj[coverType].fracVegCover,1.5)) + filled_fractions = pcr.windowaverage( + self.landCoverObj[coverType].fracVegCover, 0.5 + ) + filled_fractions = pcr.cover( + filled_fractions, + pcr.windowaverage(self.landCoverObj[coverType].fracVegCover, 1.5), + ) filled_fractions = pcr.max(0.0, filled_fractions) filled_fractions = pcr.min(1.0, filled_fractions) - - self.landCoverObj[coverType].fracVegCover = pcr.ifthen(pristineAreaFrac >= 0.0, self.landCoverObj[coverType].fracVegCover) - self.landCoverObj[coverType].fracVegCover = pcr.cover(\ - self.landCoverObj[coverType].fracVegCover,filled_fractions) - self.landCoverObj[coverType].fracVegCover = pcr.ifthen(self.landmask,\ - self.landCoverObj[coverType].fracVegCover) + self.landCoverObj[coverType].fracVegCover = pcr.ifthen( + pristineAreaFrac >= 0.0, self.landCoverObj[coverType].fracVegCover + ) + self.landCoverObj[coverType].fracVegCover = pcr.cover( + self.landCoverObj[coverType].fracVegCover, filled_fractions + ) + self.landCoverObj[coverType].fracVegCover = pcr.ifthen( + self.landmask, self.landCoverObj[coverType].fracVegCover + ) + # re-check total land cover fractions pristineAreaFrac = 0.0 numb_of_lc_types = 0.0 - for coverType in self.coverTypes: - if not coverType.startswith('irr'): - pristineAreaFrac += pcr.cover(self.landCoverObj[coverType].fracVegCover, 0.0) + for coverType in self.coverTypes: + if not coverType.startswith("irr"): + pristineAreaFrac += pcr.cover( + self.landCoverObj[coverType].fracVegCover, 0.0 + ) numb_of_lc_types += 1.0 # Fill cells with pristineAreaFrac = 0.0: - self.landCoverObj['forest'].fracVegCover = pcr.ifthenelse(pristineAreaFrac > 0.0, self.landCoverObj['forest'].fracVegCover, 0.0) - self.landCoverObj['forest'].fracVegCover = pcr.min(1.0, self.landCoverObj['forest'].fracVegCover) - self.landCoverObj['grassland'].fracVegCover = 1.0 - self.landCoverObj['forest'].fracVegCover + self.landCoverObj["forest"].fracVegCover = pcr.ifthenelse( + pristineAreaFrac > 0.0, self.landCoverObj["forest"].fracVegCover, 0.0 + ) + self.landCoverObj["forest"].fracVegCover = pcr.min( + 1.0, self.landCoverObj["forest"].fracVegCover + ) + self.landCoverObj["grassland"].fracVegCover = ( + 1.0 - self.landCoverObj["forest"].fracVegCover + ) # recalculate total land cover fractions pristineAreaFrac = 0.0 - for coverType in self.coverTypes: - if not coverType.startswith('irr'): - pristineAreaFrac += pcr.cover(self.landCoverObj[coverType].fracVegCover, 0.0) - - # correcting - for coverType in self.coverTypes: - if not coverType.startswith('irr'): - self.landCoverObj[coverType].fracVegCover = \ - self.landCoverObj[coverType].fracVegCover / pristineAreaFrac + for coverType in self.coverTypes: + if not coverType.startswith("irr"): + pristineAreaFrac += pcr.cover( + self.landCoverObj[coverType].fracVegCover, 0.0 + ) - pristineAreaFrac = 0.0 # reset + # correcting + for coverType in self.coverTypes: + if not coverType.startswith("irr"): + self.landCoverObj[coverType].fracVegCover = ( + self.landCoverObj[coverType].fracVegCover / pristineAreaFrac + ) + + pristineAreaFrac = 0.0 # reset # # checking pristineAreaFrac (must be equal to 1) - for coverType in self.coverTypes: - if not coverType.startswith('irr'): + for coverType in self.coverTypes: + if not coverType.startswith("irr"): pristineAreaFrac += self.landCoverObj[coverType].fracVegCover - self.landCoverObj[coverType].naturalFracVegCover = \ - self.landCoverObj[coverType].fracVegCover + self.landCoverObj[coverType].naturalFracVegCover = self.landCoverObj[ + coverType + ].fracVegCover # # check and make sure that totalArea = 1.0 for all cells totalArea = pristineAreaFrac - totalArea = pcr.ifthen(self.landmask,totalArea) + totalArea = pcr.ifthen(self.landmask, totalArea) totalArea = pcr.cover(totalArea, 1.0) check_map = totalArea - pcr.scalar(1.0) - a,b,c = vos.getMinMaxMean(check_map) + a, b, c = vos.getMinMaxMean(check_map) threshold = 1e-4 if abs(a) > threshold or abs(b) > threshold: - logger.error("total of 'Natural Area' fractions is not equal to 1.0 ... Min %f Max %f Mean %f" %(a,b,c)) + logger.error( + "total of 'Natural Area' fractions is not equal to 1.0 ... Min %f Max %f Mean %f" + % (a, b, c) + ) - def scaleModifiedLandCoverFractions(self): - ''' rescales the land cover fractions with irrigation areas''' + def scaleModifiedLandCoverFractions(self): + """ rescales the land cover fractions with irrigation areas""" - # calculate irrigatedAreaFrac (fraction of irrigation areas) + # calculate irrigatedAreaFrac (fraction of irrigation areas) irrigatedAreaFrac = pcr.spatial(pcr.scalar(0.0)) for coverType in self.coverTypes: - if coverType.startswith('irr'): - irrigatedAreaFrac = irrigatedAreaFrac + self.landCoverObj[coverType].fracVegCover + if coverType.startswith("irr"): + irrigatedAreaFrac = ( + irrigatedAreaFrac + self.landCoverObj[coverType].fracVegCover + ) - # correcting/scaling fracVegCover of irrigation if irrigatedAreaFrac > 1 + # correcting/scaling fracVegCover of irrigation if irrigatedAreaFrac > 1 for coverType in self.coverTypes: - if coverType.startswith('irr'): - self.landCoverObj[coverType].fracVegCover = pcr.ifthenelse(irrigatedAreaFrac > 1.0,\ - self.landCoverObj[coverType].fracVegCover/irrigatedAreaFrac,\ - self.landCoverObj[coverType].fracVegCover) - - # the corrected irrigated area fraction + if coverType.startswith("irr"): + self.landCoverObj[coverType].fracVegCover = pcr.ifthenelse( + irrigatedAreaFrac > 1.0, + self.landCoverObj[coverType].fracVegCover / irrigatedAreaFrac, + self.landCoverObj[coverType].fracVegCover, + ) + + # the corrected irrigated area fraction irrigatedAreaFrac = pcr.spatial(pcr.scalar(0.0)) for coverType in self.coverTypes: - if coverType.startswith('irr'): + if coverType.startswith("irr"): irrigatedAreaFrac += self.landCoverObj[coverType].fracVegCover - totalArea = pcr.spatial(pcr.scalar(0.0)) + totalArea = pcr.spatial(pcr.scalar(0.0)) totalArea += irrigatedAreaFrac # correction factor for forest and grassland (pristine Areas) lcFrac = pcr.max(0.0, 1.0 - totalArea) pristineAreaFrac = pcr.spatial(pcr.scalar(0.0)) - for coverType in self.coverTypes: - if not coverType.startswith('irr'): + for coverType in self.coverTypes: + if not coverType.startswith("irr"): self.landCoverObj[coverType].fracVegCover = 0.0 - self.landCoverObj[coverType].fracVegCover = \ - self.landCoverObj[coverType].naturalFracVegCover * lcFrac - pristineAreaFrac += pcr.cover(\ - self.landCoverObj[coverType].fracVegCover, 0.0) + self.landCoverObj[coverType].fracVegCover = ( + self.landCoverObj[coverType].naturalFracVegCover * lcFrac + ) + pristineAreaFrac += pcr.cover( + self.landCoverObj[coverType].fracVegCover, 0.0 + ) # check and make sure that totalArea = 1.0 for all cells totalArea += pristineAreaFrac - totalArea = pcr.ifthen(self.landmask,totalArea) + totalArea = pcr.ifthen(self.landmask, totalArea) totalArea = pcr.cover(totalArea, 1.0) - totalArea = pcr.ifthen(self.landmask,totalArea) - a,b,c = vos.getMinMaxMean(totalArea - pcr.scalar(1.0)) + totalArea = pcr.ifthen(self.landmask, totalArea) + a, b, c = vos.getMinMaxMean(totalArea - pcr.scalar(1.0)) threshold = 1e-4 if abs(a) > threshold or abs(b) > threshold: - logger.error("fraction total (from all land cover types) is not equal to 1.0 ... Min %f Max %f Mean %f" %(a,b,c)) + logger.error( + "fraction total (from all land cover types) is not equal to 1.0 ... Min %f Max %f Mean %f" + % (a, b, c) + ) - def obtainNonIrrWaterDemand(self,routing,currTimeStep): + def obtainNonIrrWaterDemand(self, routing, currTimeStep): # get NON-Irrigation GROSS water demand and its return flow fraction # domestic water demand if currTimeStep.timeStepPCR == 1 or currTimeStep.day == 1: - if self.domesticWaterDemandOption: + if self.domesticWaterDemandOption: # - if self.domesticWaterDemandFile.endswith(vos.netcdf_suffixes): + if self.domesticWaterDemandFile.endswith(vos.netcdf_suffixes): # - self.domesticGrossDemand = pcr.max(0.0, pcr.cover(\ - vos.netcdf2PCRobjClone(self.domesticWaterDemandFile,\ - 'domesticGrossDemand',\ - currTimeStep.fulldate, useDoy = 'monthly',\ - cloneMapFileName = self.cloneMap), 0.0)) + self.domesticGrossDemand = pcr.max( + 0.0, + pcr.cover( + vos.netcdf2PCRobjClone( + self.domesticWaterDemandFile, + "domesticGrossDemand", + currTimeStep.fulldate, + useDoy="monthly", + cloneMapFileName=self.cloneMap, + ), + 0.0, + ), + ) # - self.domesticNettoDemand = pcr.max(0.0, pcr.cover(\ - vos.netcdf2PCRobjClone(self.domesticWaterDemandFile,\ - 'domesticNettoDemand',\ - currTimeStep.fulldate, useDoy = 'monthly',\ - cloneMapFileName = self.cloneMap), 0.0)) + self.domesticNettoDemand = pcr.max( + 0.0, + pcr.cover( + vos.netcdf2PCRobjClone( + self.domesticWaterDemandFile, + "domesticNettoDemand", + currTimeStep.fulldate, + useDoy="monthly", + cloneMapFileName=self.cloneMap, + ), + 0.0, + ), + ) else: string_month = str(currTimeStep.month) - if currTimeStep.month < 10: string_month = "0"+str(currTimeStep.month) - grossFileName = self.domesticWaterDemandFile+"w"+str(currTimeStep.year)+".0"+string_month - self.domesticGrossDemand = pcr.max(pcr.cover(\ - vos.readPCRmapClone(grossFileName,self.cloneMap,self.tmpDir), 0.0), 0.0) - nettoFileName = self.domesticWaterDemandFile+"n"+str(currTimeStep.year)+".0"+string_month - self.domesticNettoDemand = pcr.max(pcr.cover(\ - vos.readPCRmapClone(nettoFileName,self.cloneMap,self.tmpDir), 0.0), 0.0) + if currTimeStep.month < 10: + string_month = "0" + str(currTimeStep.month) + grossFileName = ( + self.domesticWaterDemandFile + + "w" + + str(currTimeStep.year) + + ".0" + + string_month + ) + self.domesticGrossDemand = pcr.max( + pcr.cover( + vos.readPCRmapClone( + grossFileName, self.cloneMap, self.tmpDir + ), + 0.0, + ), + 0.0, + ) + nettoFileName = ( + self.domesticWaterDemandFile + + "n" + + str(currTimeStep.year) + + ".0" + + string_month + ) + self.domesticNettoDemand = pcr.max( + pcr.cover( + vos.readPCRmapClone( + nettoFileName, self.cloneMap, self.tmpDir + ), + 0.0, + ), + 0.0, + ) else: self.domesticGrossDemand = pcr.scalar(0.0) self.domesticNettoDemand = pcr.scalar(0.0) logger.debug("Domestic water demand is NOT included.") - + # gross and netto domestic water demand in m/day - self.domesticGrossDemand = pcr.cover(self.domesticGrossDemand,0.0) - self.domesticNettoDemand = pcr.cover(self.domesticNettoDemand,0.0) - self.domesticNettoDemand = pcr.min(self.domesticGrossDemand, self.domesticNettoDemand) + self.domesticGrossDemand = pcr.cover(self.domesticGrossDemand, 0.0) + self.domesticNettoDemand = pcr.cover(self.domesticNettoDemand, 0.0) + self.domesticNettoDemand = pcr.min( + self.domesticGrossDemand, self.domesticNettoDemand + ) # industry water demand if currTimeStep.timeStepPCR == 1 or currTimeStep.day == 1: - if self.industryWaterDemandOption: + if self.industryWaterDemandOption: # - if self.industryWaterDemandFile.endswith(vos.netcdf_suffixes): + if self.industryWaterDemandFile.endswith(vos.netcdf_suffixes): # - self.industryGrossDemand = pcr.max(0.0, pcr.cover(\ - vos.netcdf2PCRobjClone(self.industryWaterDemandFile,\ - 'industryGrossDemand',\ - currTimeStep.fulldate, useDoy = 'monthly',\ - cloneMapFileName = self.cloneMap), 0.0)) + self.industryGrossDemand = pcr.max( + 0.0, + pcr.cover( + vos.netcdf2PCRobjClone( + self.industryWaterDemandFile, + "industryGrossDemand", + currTimeStep.fulldate, + useDoy="monthly", + cloneMapFileName=self.cloneMap, + ), + 0.0, + ), + ) # - self.industryNettoDemand = pcr.max(0.0, pcr.cover(\ - vos.netcdf2PCRobjClone(self.industryWaterDemandFile,\ - 'industryNettoDemand',\ - currTimeStep.fulldate, useDoy = 'monthly',\ - cloneMapFileName = self.cloneMap), 0.0)) + self.industryNettoDemand = pcr.max( + 0.0, + pcr.cover( + vos.netcdf2PCRobjClone( + self.industryWaterDemandFile, + "industryNettoDemand", + currTimeStep.fulldate, + useDoy="monthly", + cloneMapFileName=self.cloneMap, + ), + 0.0, + ), + ) else: - grossFileName = self.industryWaterDemandFile+"w"+str(currTimeStep.year)+".map" - self.industryGrossDemand = pcr.max(0.0, pcr.cover(\ - vos.readPCRmapClone(grossFileName,self.cloneMap,self.tmpDir), 0.0)) - nettoFileName = self.industryWaterDemandFile+"n"+str(currTimeStep.year)+".map" - self.industryNettoDemand = pcr.max(0.0, pcr.cover(\ - vos.readPCRmapClone(nettoFileName,self.cloneMap,self.tmpDir), 0.0)) + grossFileName = ( + self.industryWaterDemandFile + + "w" + + str(currTimeStep.year) + + ".map" + ) + self.industryGrossDemand = pcr.max( + 0.0, + pcr.cover( + vos.readPCRmapClone( + grossFileName, self.cloneMap, self.tmpDir + ), + 0.0, + ), + ) + nettoFileName = ( + self.industryWaterDemandFile + + "n" + + str(currTimeStep.year) + + ".map" + ) + self.industryNettoDemand = pcr.max( + 0.0, + pcr.cover( + vos.readPCRmapClone( + nettoFileName, self.cloneMap, self.tmpDir + ), + 0.0, + ), + ) else: self.industryGrossDemand = pcr.scalar(0.0) self.industryNettoDemand = pcr.scalar(0.0) logger.debug("Industry water demand is NOT included.") - + # gross and netto industrial water demand in m/day - self.industryGrossDemand = pcr.cover(self.industryGrossDemand,0.0) - self.industryNettoDemand = pcr.cover(self.industryNettoDemand,0.0) - self.industryNettoDemand = pcr.min(self.industryGrossDemand, self.industryNettoDemand) + self.industryGrossDemand = pcr.cover(self.industryGrossDemand, 0.0) + self.industryNettoDemand = pcr.cover(self.industryNettoDemand, 0.0) + self.industryNettoDemand = pcr.min( + self.industryGrossDemand, self.industryNettoDemand + ) # livestock water demand if currTimeStep.timeStepPCR == 1 or currTimeStep.day == 1: - if self.livestockWaterDemandOption: + if self.livestockWaterDemandOption: # - if self.livestockWaterDemandFile.endswith(vos.netcdf_suffixes): + if self.livestockWaterDemandFile.endswith(vos.netcdf_suffixes): # - self.livestockGrossDemand = pcr.max(0.0, pcr.cover(\ - vos.netcdf2PCRobjClone(self.livestockWaterDemandFile,\ - 'livestockGrossDemand',\ - currTimeStep.fulldate, useDoy = 'monthly',\ - cloneMapFileName = self.cloneMap), 0.0)) + self.livestockGrossDemand = pcr.max( + 0.0, + pcr.cover( + vos.netcdf2PCRobjClone( + self.livestockWaterDemandFile, + "livestockGrossDemand", + currTimeStep.fulldate, + useDoy="monthly", + cloneMapFileName=self.cloneMap, + ), + 0.0, + ), + ) # - self.livestockNettoDemand = pcr.max(0.0, pcr.cover(\ - vos.netcdf2PCRobjClone(self.livestockWaterDemandFile,\ - 'livestockNettoDemand',\ - currTimeStep.fulldate, useDoy = 'monthly',\ - cloneMapFileName = self.cloneMap), 0.0)) + self.livestockNettoDemand = pcr.max( + 0.0, + pcr.cover( + vos.netcdf2PCRobjClone( + self.livestockWaterDemandFile, + "livestockNettoDemand", + currTimeStep.fulldate, + useDoy="monthly", + cloneMapFileName=self.cloneMap, + ), + 0.0, + ), + ) else: string_month = str(currTimeStep.month) - if currTimeStep.month < 10: string_month = "0"+str(currTimeStep.month) - grossFileName = self.livestockWaterDemandFile+"w"+str(currTimeStep.year)+".0"+string_month - self.livestockGrossDemand = pcr.max(pcr.cover(\ - vos.readPCRmapClone(grossFileName,self.cloneMap,self.tmpDir), 0.0), 0.0) - nettoFileName = self.livestockWaterDemandFile+"n"+str(currTimeStep.year)+".0"+string_month - self.livestockNettoDemand = pcr.max(pcr.cover(\ - vos.readPCRmapClone(nettoFileName,self.cloneMap,self.tmpDir), 0.0), 0.0) + if currTimeStep.month < 10: + string_month = "0" + str(currTimeStep.month) + grossFileName = ( + self.livestockWaterDemandFile + + "w" + + str(currTimeStep.year) + + ".0" + + string_month + ) + self.livestockGrossDemand = pcr.max( + pcr.cover( + vos.readPCRmapClone( + grossFileName, self.cloneMap, self.tmpDir + ), + 0.0, + ), + 0.0, + ) + nettoFileName = ( + self.livestockWaterDemandFile + + "n" + + str(currTimeStep.year) + + ".0" + + string_month + ) + self.livestockNettoDemand = pcr.max( + pcr.cover( + vos.readPCRmapClone( + nettoFileName, self.cloneMap, self.tmpDir + ), + 0.0, + ), + 0.0, + ) else: self.livestockGrossDemand = pcr.scalar(0.0) self.livestockNettoDemand = pcr.scalar(0.0) logger.debug("Livestock water demand is NOT included.") - + # gross and netto livestock water demand in m/day - self.livestockGrossDemand = pcr.cover(self.livestockGrossDemand,0.0) - self.livestockNettoDemand = pcr.cover(self.livestockNettoDemand,0.0) - self.livestockNettoDemand = pcr.min(self.livestockGrossDemand, self.livestockNettoDemand) + self.livestockGrossDemand = pcr.cover(self.livestockGrossDemand, 0.0) + self.livestockNettoDemand = pcr.cover(self.livestockNettoDemand, 0.0) + self.livestockNettoDemand = pcr.min( + self.livestockGrossDemand, self.livestockNettoDemand + ) # GROSS domestic, industrial and livestock water demands (unit: m/day) - self.domesticGrossDemand = pcr.ifthen(self.landmask, self.domesticGrossDemand ) - self.domesticNettoDemand = pcr.ifthen(self.landmask, self.domesticNettoDemand ) - self.industryGrossDemand = pcr.ifthen(self.landmask, self.industryGrossDemand ) - self.industryNettoDemand = pcr.ifthen(self.landmask, self.industryNettoDemand ) + self.domesticGrossDemand = pcr.ifthen(self.landmask, self.domesticGrossDemand) + self.domesticNettoDemand = pcr.ifthen(self.landmask, self.domesticNettoDemand) + self.industryGrossDemand = pcr.ifthen(self.landmask, self.industryGrossDemand) + self.industryNettoDemand = pcr.ifthen(self.landmask, self.industryNettoDemand) self.livestockGrossDemand = pcr.ifthen(self.landmask, self.livestockGrossDemand) self.livestockNettoDemand = pcr.ifthen(self.landmask, self.livestockNettoDemand) - + # RETURN FLOW fractions for domestic, industrial and livestock water demands (unit: fraction/percentage) - self.domesticReturnFlowFraction = pcr.min(1.0, pcr.max(0.0, 1.0 - vos.getValDivZero(self.domesticNettoDemand, self.domesticGrossDemand))) - self.industryReturnFlowFraction = pcr.min(1.0, pcr.max(0.0, 1.0 - vos.getValDivZero(self.industryNettoDemand, self.industryGrossDemand))) - self.livestockReturnFlowFraction = pcr.min(1.0, pcr.max(0.0, 1.0 - vos.getValDivZero(self.livestockNettoDemand, self.livestockGrossDemand))) - + self.domesticReturnFlowFraction = pcr.min( + 1.0, + pcr.max( + 0.0, + 1.0 + - vos.getValDivZero(self.domesticNettoDemand, self.domesticGrossDemand), + ), + ) + self.industryReturnFlowFraction = pcr.min( + 1.0, + pcr.max( + 0.0, + 1.0 + - vos.getValDivZero(self.industryNettoDemand, self.industryGrossDemand), + ), + ) + self.livestockReturnFlowFraction = pcr.min( + 1.0, + pcr.max( + 0.0, + 1.0 + - vos.getValDivZero( + self.livestockNettoDemand, self.livestockGrossDemand + ), + ), + ) + # make a dictionary summarizing potential demand (potential withdrawal) and its return flow fraction nonIrrigationWaterDemandDict = {} - nonIrrigationWaterDemandDict['potential_demand'] = {} - nonIrrigationWaterDemandDict['potential_demand']['domestic'] = self.domesticGrossDemand - nonIrrigationWaterDemandDict['potential_demand']['industry'] = self.industryGrossDemand - nonIrrigationWaterDemandDict['potential_demand']['livestock'] = self.livestockGrossDemand - nonIrrigationWaterDemandDict['return_flow_fraction'] = {} - nonIrrigationWaterDemandDict['return_flow_fraction']['domestic'] = pcr.cover(pcr.min(1.0, pcr.roundup(self.domesticReturnFlowFraction *1000.)/1000.), 1.0) - nonIrrigationWaterDemandDict['return_flow_fraction']['industry'] = pcr.cover(pcr.min(1.0, pcr.roundup(self.industryReturnFlowFraction *1000.)/1000.), 1.0) - nonIrrigationWaterDemandDict['return_flow_fraction']['livestock'] = pcr.cover(pcr.min(1.0, pcr.roundup(self.livestockReturnFlowFraction*1000.)/1000.), 1.0) - + nonIrrigationWaterDemandDict["potential_demand"] = {} + nonIrrigationWaterDemandDict["potential_demand"][ + "domestic" + ] = self.domesticGrossDemand + nonIrrigationWaterDemandDict["potential_demand"][ + "industry" + ] = self.industryGrossDemand + nonIrrigationWaterDemandDict["potential_demand"][ + "livestock" + ] = self.livestockGrossDemand + nonIrrigationWaterDemandDict["return_flow_fraction"] = {} + nonIrrigationWaterDemandDict["return_flow_fraction"]["domestic"] = pcr.cover( + pcr.min(1.0, pcr.roundup(self.domesticReturnFlowFraction * 1000.) / 1000.), + 1.0, + ) + nonIrrigationWaterDemandDict["return_flow_fraction"]["industry"] = pcr.cover( + pcr.min(1.0, pcr.roundup(self.industryReturnFlowFraction * 1000.) / 1000.), + 1.0, + ) + nonIrrigationWaterDemandDict["return_flow_fraction"]["livestock"] = pcr.cover( + pcr.min(1.0, pcr.roundup(self.livestockReturnFlowFraction * 1000.) / 1000.), + 1.0, + ) + return nonIrrigationWaterDemandDict - def calculateCapRiseFrac(self,groundwater,routing,currTimeStep): + def calculateCapRiseFrac(self, groundwater, routing, currTimeStep): # calculate cell fraction influenced by capillary rise: # relative groundwater head (m) above the minimum elevation within a grid cell if groundwater.useMODFLOW == True: - + dzGroundwater = groundwater.relativeGroundwaterHead - + # update dzGroundwater from file, from modflow calculation, using the previous time step # - assumption that it will be updated once every month - - if currTimeStep.day == 1 and currTimeStep.timeStepPCR > 1: + if currTimeStep.day == 1 and currTimeStep.timeStepPCR > 1: + # for online coupling, we will read files from pcraster maps - #directory = self.iniItems.main_output_directory + "/modflow/transient/maps/" - directory = iniItems.get("globalOptions","outputDir") + "/modflow/transient/maps/" - + # directory = self.iniItems.main_output_directory + "/modflow/transient/maps/" + directory = ( + iniItems.get("globalOptions", "outputDir") + + "/modflow/transient/maps/" + ) + # - relative groundwater head from MODFLOW yesterday = str(currTimeStep.yesterday()) - filename = directory + "relativeGroundwaterHead_" + str(yesterday) + ".map" - dzGroundwater = pcr.ifthen(self.landmask, pcr.cover(vos.readPCRmapClone(filename, self.cloneMap, self.tmpDir), 0.0)) - + filename = ( + directory + "relativeGroundwaterHead_" + str(yesterday) + ".map" + ) + dzGroundwater = pcr.ifthen( + self.landmask, + pcr.cover( + vos.readPCRmapClone(filename, self.cloneMap, self.tmpDir), 0.0 + ), + ) + else: - dzGroundwater = groundwater.storGroundwater/groundwater.specificYield + dzGroundwater = groundwater.storGroundwater / groundwater.specificYield # add some tolerance/influence level (unit: m) - dzGroundwater += self.soil_topo_parameters['default'].maxGWCapRise; - + dzGroundwater += self.soil_topo_parameters["default"].maxGWCapRise + # set minimum value to zero (zero relativeGroundwaterHead indicate no capRiseFrac) dzGroundwater = pcr.max(0.0, dzGroundwater) # approximate cell fraction under influence of capillary rise - FRACWAT = pcr.scalar(0.0); - if currTimeStep.timeStepPCR > 1: - FRACWAT = pcr.cover(routing.WaterBodies.fracWat, 0.0); + FRACWAT = pcr.scalar(0.0) + if currTimeStep.timeStepPCR > 1: + FRACWAT = pcr.cover(routing.WaterBodies.fracWat, 0.0) else: if routing.includeWaterBodies: if routing.WaterBodies.useNetCDF: - routing.WaterBodies.fracWat = vos.netcdf2PCRobjClone(\ - routing.WaterBodies.ncFileInp,'fracWaterInp', \ - currTimeStep.fulldate, useDoy = 'yearly',\ - cloneMapFileName = self.cloneMap) + routing.WaterBodies.fracWat = vos.netcdf2PCRobjClone( + routing.WaterBodies.ncFileInp, + "fracWaterInp", + currTimeStep.fulldate, + useDoy="yearly", + cloneMapFileName=self.cloneMap, + ) else: - routing.WaterBodies.fracWat = vos.readPCRmapClone(\ - routing.WaterBodies.fracWaterInp+str(currTimeStep.year)+".map", - self.cloneMap,self.tmpDir,self.inputDir) + routing.WaterBodies.fracWat = vos.readPCRmapClone( + routing.WaterBodies.fracWaterInp + + str(currTimeStep.year) + + ".map", + self.cloneMap, + self.tmpDir, + self.inputDir, + ) FRACWAT = pcr.cover(FRACWAT, 0.0) - + # zero fracwat assumption used for debugging against version 1.0 - if routing.zeroFracWatAllAndAlways: FRACWAT = pcr.scalar(0.0) + if routing.zeroFracWatAllAndAlways: + FRACWAT = pcr.scalar(0.0) + CRFRAC = pcr.min( + 1.0, + 1.0 + - (self.soil_topo_parameters["default"].dzRel0100 - dzGroundwater) + * 0.1 + / pcr.max( + 0.001, + self.soil_topo_parameters["default"].dzRel0100 + - self.soil_topo_parameters["default"].dzRel0090, + ), + ) + CRFRAC = pcr.ifthenelse( + dzGroundwater < self.soil_topo_parameters["default"].dzRel0090, + 0.9 + - (self.soil_topo_parameters["default"].dzRel0090 - dzGroundwater) + * 0.1 + / pcr.max( + 0.001, + self.soil_topo_parameters["default"].dzRel0090 + - self.soil_topo_parameters["default"].dzRel0080, + ), + CRFRAC, + ) + CRFRAC = pcr.ifthenelse( + dzGroundwater < self.soil_topo_parameters["default"].dzRel0080, + 0.8 + - (self.soil_topo_parameters["default"].dzRel0080 - dzGroundwater) + * 0.1 + / pcr.max( + 0.001, + self.soil_topo_parameters["default"].dzRel0080 + - self.soil_topo_parameters["default"].dzRel0070, + ), + CRFRAC, + ) + CRFRAC = pcr.ifthenelse( + dzGroundwater < self.soil_topo_parameters["default"].dzRel0070, + 0.7 + - (self.soil_topo_parameters["default"].dzRel0070 - dzGroundwater) + * 0.1 + / pcr.max( + 0.001, + self.soil_topo_parameters["default"].dzRel0070 + - self.soil_topo_parameters["default"].dzRel0060, + ), + CRFRAC, + ) + CRFRAC = pcr.ifthenelse( + dzGroundwater < self.soil_topo_parameters["default"].dzRel0060, + 0.6 + - (self.soil_topo_parameters["default"].dzRel0060 - dzGroundwater) + * 0.1 + / pcr.max( + 0.001, + self.soil_topo_parameters["default"].dzRel0060 + - self.soil_topo_parameters["default"].dzRel0050, + ), + CRFRAC, + ) + CRFRAC = pcr.ifthenelse( + dzGroundwater < self.soil_topo_parameters["default"].dzRel0050, + 0.5 + - (self.soil_topo_parameters["default"].dzRel0050 - dzGroundwater) + * 0.1 + / pcr.max( + 0.001, + self.soil_topo_parameters["default"].dzRel0050 + - self.soil_topo_parameters["default"].dzRel0040, + ), + CRFRAC, + ) + CRFRAC = pcr.ifthenelse( + dzGroundwater < self.soil_topo_parameters["default"].dzRel0040, + 0.4 + - (self.soil_topo_parameters["default"].dzRel0040 - dzGroundwater) + * 0.1 + / pcr.max( + 0.001, + self.soil_topo_parameters["default"].dzRel0040 + - self.soil_topo_parameters["default"].dzRel0030, + ), + CRFRAC, + ) + CRFRAC = pcr.ifthenelse( + dzGroundwater < self.soil_topo_parameters["default"].dzRel0030, + 0.3 + - (self.soil_topo_parameters["default"].dzRel0030 - dzGroundwater) + * 0.1 + / pcr.max( + 0.001, + self.soil_topo_parameters["default"].dzRel0030 + - self.soil_topo_parameters["default"].dzRel0020, + ), + CRFRAC, + ) + CRFRAC = pcr.ifthenelse( + dzGroundwater < self.soil_topo_parameters["default"].dzRel0020, + 0.2 + - (self.soil_topo_parameters["default"].dzRel0020 - dzGroundwater) + * 0.1 + / pcr.max( + 0.001, + self.soil_topo_parameters["default"].dzRel0020 + - self.soil_topo_parameters["default"].dzRel0010, + ), + CRFRAC, + ) + CRFRAC = pcr.ifthenelse( + dzGroundwater < self.soil_topo_parameters["default"].dzRel0010, + 0.1 + - (self.soil_topo_parameters["default"].dzRel0010 - dzGroundwater) + * 0.05 + / pcr.max( + 0.001, + self.soil_topo_parameters["default"].dzRel0010 + - self.soil_topo_parameters["default"].dzRel0005, + ), + CRFRAC, + ) + CRFRAC = pcr.ifthenelse( + dzGroundwater < self.soil_topo_parameters["default"].dzRel0005, + 0.05 + - (self.soil_topo_parameters["default"].dzRel0005 - dzGroundwater) + * 0.04 + / pcr.max( + 0.001, + self.soil_topo_parameters["default"].dzRel0005 + - self.soil_topo_parameters["default"].dzRel0001, + ), + CRFRAC, + ) + CRFRAC = pcr.ifthenelse( + dzGroundwater < self.soil_topo_parameters["default"].dzRel0001, + 0.01 + - (self.soil_topo_parameters["default"].dzRel0001 - dzGroundwater) + * 0.01 + / pcr.max(0.001, self.soil_topo_parameters["default"].dzRel0001), + CRFRAC, + ) - CRFRAC = pcr.min( 1.0,1.0 -(self.soil_topo_parameters['default'].dzRel0100-dzGroundwater)*0.1 /pcr.max(0.001,self.soil_topo_parameters['default'].dzRel0100-self.soil_topo_parameters['default'].dzRel0090) ); - CRFRAC = pcr.ifthenelse(dzGroundwater < self.soil_topo_parameters['default'].dzRel0090,0.9 -(self.soil_topo_parameters['default'].dzRel0090-dzGroundwater)*0.1 /pcr.max(0.001,self.soil_topo_parameters['default'].dzRel0090-self.soil_topo_parameters['default'].dzRel0080),CRFRAC); - CRFRAC = pcr.ifthenelse(dzGroundwater < self.soil_topo_parameters['default'].dzRel0080,0.8 -(self.soil_topo_parameters['default'].dzRel0080-dzGroundwater)*0.1 /pcr.max(0.001,self.soil_topo_parameters['default'].dzRel0080-self.soil_topo_parameters['default'].dzRel0070),CRFRAC); - CRFRAC = pcr.ifthenelse(dzGroundwater < self.soil_topo_parameters['default'].dzRel0070,0.7 -(self.soil_topo_parameters['default'].dzRel0070-dzGroundwater)*0.1 /pcr.max(0.001,self.soil_topo_parameters['default'].dzRel0070-self.soil_topo_parameters['default'].dzRel0060),CRFRAC); - CRFRAC = pcr.ifthenelse(dzGroundwater < self.soil_topo_parameters['default'].dzRel0060,0.6 -(self.soil_topo_parameters['default'].dzRel0060-dzGroundwater)*0.1 /pcr.max(0.001,self.soil_topo_parameters['default'].dzRel0060-self.soil_topo_parameters['default'].dzRel0050),CRFRAC); - CRFRAC = pcr.ifthenelse(dzGroundwater < self.soil_topo_parameters['default'].dzRel0050,0.5 -(self.soil_topo_parameters['default'].dzRel0050-dzGroundwater)*0.1 /pcr.max(0.001,self.soil_topo_parameters['default'].dzRel0050-self.soil_topo_parameters['default'].dzRel0040),CRFRAC); - CRFRAC = pcr.ifthenelse(dzGroundwater < self.soil_topo_parameters['default'].dzRel0040,0.4 -(self.soil_topo_parameters['default'].dzRel0040-dzGroundwater)*0.1 /pcr.max(0.001,self.soil_topo_parameters['default'].dzRel0040-self.soil_topo_parameters['default'].dzRel0030),CRFRAC); - CRFRAC = pcr.ifthenelse(dzGroundwater < self.soil_topo_parameters['default'].dzRel0030,0.3 -(self.soil_topo_parameters['default'].dzRel0030-dzGroundwater)*0.1 /pcr.max(0.001,self.soil_topo_parameters['default'].dzRel0030-self.soil_topo_parameters['default'].dzRel0020),CRFRAC); - CRFRAC = pcr.ifthenelse(dzGroundwater < self.soil_topo_parameters['default'].dzRel0020,0.2 -(self.soil_topo_parameters['default'].dzRel0020-dzGroundwater)*0.1 /pcr.max(0.001,self.soil_topo_parameters['default'].dzRel0020-self.soil_topo_parameters['default'].dzRel0010),CRFRAC); - CRFRAC = pcr.ifthenelse(dzGroundwater < self.soil_topo_parameters['default'].dzRel0010,0.1 -(self.soil_topo_parameters['default'].dzRel0010-dzGroundwater)*0.05/pcr.max(0.001,self.soil_topo_parameters['default'].dzRel0010-self.soil_topo_parameters['default'].dzRel0005),CRFRAC); - CRFRAC = pcr.ifthenelse(dzGroundwater < self.soil_topo_parameters['default'].dzRel0005,0.05-(self.soil_topo_parameters['default'].dzRel0005-dzGroundwater)*0.04/pcr.max(0.001,self.soil_topo_parameters['default'].dzRel0005-self.soil_topo_parameters['default'].dzRel0001),CRFRAC); - CRFRAC = pcr.ifthenelse(dzGroundwater < self.soil_topo_parameters['default'].dzRel0001,0.01-(self.soil_topo_parameters['default'].dzRel0001-dzGroundwater)*0.01/pcr.max(0.001,self.soil_topo_parameters['default'].dzRel0001 ),CRFRAC); + CRFRAC = pcr.ifthenelse( + FRACWAT < 1.0, pcr.max(0.0, CRFRAC - FRACWAT) / (1.0 - FRACWAT), 0.0 + ) - CRFRAC = pcr.ifthenelse(FRACWAT < 1.0,pcr.max(0.0,CRFRAC-FRACWAT)/(1.0-FRACWAT),0.0); - - capRiseFrac = pcr.max(0.0,pcr.min(1.0,CRFRAC)) - - #~ capRiseFrac = 0.0 - + capRiseFrac = pcr.max(0.0, pcr.min(1.0, CRFRAC)) + + # ~ capRiseFrac = 0.0 + return capRiseFrac - def partitioningGroundSurfaceAbstraction(self,groundwater,routing): + def partitioningGroundSurfaceAbstraction(self, groundwater, routing): # partitioning abstraction sources: groundwater and surface water - # de Graaf et al., 2014 principle: partitioning based on local average baseflow (m3/s) and upstream average discharge (m3/s) - # - estimates of fractions of groundwater and surface water abstractions + # de Graaf et al., 2014 principle: partitioning based on local average baseflow (m3/s) and upstream average discharge (m3/s) + # - estimates of fractions of groundwater and surface water abstractions averageBaseflowInput = routing.avgBaseflow - averageUpstreamInput = pcr.max(routing.avgDischarge, pcr.cover(pcr.upstream(routing.lddMap, routing.avgDischarge), 0.0)) - + averageUpstreamInput = pcr.max( + routing.avgDischarge, + pcr.cover(pcr.upstream(routing.lddMap, routing.avgDischarge), 0.0), + ) + if self.usingAllocSegments: - - averageBaseflowInput = pcr.max(0.0, pcr.ifthen(self.landmask, averageBaseflowInput)) - averageUpstreamInput = pcr.max(0.0, pcr.ifthen(self.landmask, averageUpstreamInput)) - - averageBaseflowInput = pcr.cover(pcr.areaaverage(averageBaseflowInput, self.allocSegments), 0.0) - averageUpstreamInput = pcr.cover(pcr.areamaximum(averageUpstreamInput, self.allocSegments), 0.0) + averageBaseflowInput = pcr.max( + 0.0, pcr.ifthen(self.landmask, averageBaseflowInput) + ) + averageUpstreamInput = pcr.max( + 0.0, pcr.ifthen(self.landmask, averageUpstreamInput) + ) + + averageBaseflowInput = pcr.cover( + pcr.areaaverage(averageBaseflowInput, self.allocSegments), 0.0 + ) + averageUpstreamInput = pcr.cover( + pcr.areamaximum(averageUpstreamInput, self.allocSegments), 0.0 + ) + else: logger.debug("Water demand can only be satisfied by local source.") - swAbstractionFraction = vos.getValDivZero(\ - averageUpstreamInput, - averageUpstreamInput+averageBaseflowInput, vos.smallNumber) - swAbstractionFraction = pcr.roundup(swAbstractionFraction*100.)/100. + swAbstractionFraction = vos.getValDivZero( + averageUpstreamInput, + averageUpstreamInput + averageBaseflowInput, + vos.smallNumber, + ) + swAbstractionFraction = pcr.roundup(swAbstractionFraction * 100.) / 100. swAbstractionFraction = pcr.max(0.0, swAbstractionFraction) swAbstractionFraction = pcr.min(1.0, swAbstractionFraction) if self.usingAllocSegments: - swAbstractionFraction = pcr.areamaximum(swAbstractionFraction, self.allocSegments) - + swAbstractionFraction = pcr.areamaximum( + swAbstractionFraction, self.allocSegments + ) + swAbstractionFraction = pcr.cover(swAbstractionFraction, 1.0) swAbstractionFraction = pcr.ifthen(self.landmask, swAbstractionFraction) - - # making a dictionary containing the surface water fraction for various purpose + + # making a dictionary containing the surface water fraction for various purpose swAbstractionFractionDict = {} # - the default estimate (based on de Graaf et al., 2014) - swAbstractionFractionDict['estimate'] = swAbstractionFraction + swAbstractionFractionDict["estimate"] = swAbstractionFraction # - for irrigation and livestock purpose - swAbstractionFractionDict['irrigation'] = swAbstractionFraction + swAbstractionFractionDict["irrigation"] = swAbstractionFraction # - for industrial and domestic purpose - swAbstractionFractionDict['max_for_non_irrigation'] = swAbstractionFraction + swAbstractionFractionDict["max_for_non_irrigation"] = swAbstractionFraction # - # - a treshold fraction value to optimize/maximize surface water withdrawal for irrigation + # - a treshold fraction value to optimize/maximize surface water withdrawal for irrigation # Principle: Areas with swAbstractionFractionDict['irrigation'] above this treshold will prioritize surface water use for irrigation purpose. - # A zero treshold value will ignore this principle. - swAbstractionFractionDict['treshold_to_maximize_irrigation_surface_water'] = self.treshold_to_maximize_irrigation_surface_water + # A zero treshold value will ignore this principle. + swAbstractionFractionDict[ + "treshold_to_maximize_irrigation_surface_water" + ] = self.treshold_to_maximize_irrigation_surface_water # # - a treshold fraction value to minimize fossil groundwater withdrawal, particularly to remove the unrealistic areas of fossil groundwater abstraction # Principle: Areas with swAbstractionFractionDict['irrigation'] above this treshold will not extract fossil groundwater. - swAbstractionFractionDict['treshold_to_minimize_fossil_groundwater_irrigation'] = self.treshold_to_minimize_fossil_groundwater_irrigation - - # if defined, incorporating the pre-defined fraction of surface water sources (e.g. based on Siebert et al., 2014 and McDonald et al., 2014) + swAbstractionFractionDict[ + "treshold_to_minimize_fossil_groundwater_irrigation" + ] = self.treshold_to_minimize_fossil_groundwater_irrigation + + # if defined, incorporating the pre-defined fraction of surface water sources (e.g. based on Siebert et al., 2014 and McDonald et al., 2014) if not isinstance(self.swAbstractionFractionData, types.NoneType): - - logger.debug('Using/incorporating the predefined fractions of surface water source.') - swAbstractionFractionDict['estimate'] = swAbstractionFraction - swAbstractionFractionDict['irrigation'] = self.partitioningGroundSurfaceAbstractionForIrrigation(swAbstractionFraction,\ - self.swAbstractionFractionData,\ - self.swAbstractionFractionDataQuality) - swAbstractionFractionDict['max_for_non_irrigation'] = self.maximumNonIrrigationSurfaceWaterAbstractionFractionData - - else: - logger.debug('NOT using/incorporating the predefined fractions of surface water source.') + logger.debug( + "Using/incorporating the predefined fractions of surface water source." + ) + swAbstractionFractionDict["estimate"] = swAbstractionFraction + swAbstractionFractionDict[ + "irrigation" + ] = self.partitioningGroundSurfaceAbstractionForIrrigation( + swAbstractionFraction, + self.swAbstractionFractionData, + self.swAbstractionFractionDataQuality, + ) + swAbstractionFractionDict[ + "max_for_non_irrigation" + ] = self.maximumNonIrrigationSurfaceWaterAbstractionFractionData + + else: + logger.debug( + "NOT using/incorporating the predefined fractions of surface water source." + ) + return swAbstractionFractionDict - def partitioningGroundSurfaceAbstractionForIrrigation(self,\ - swAbstractionFractionEstimate,\ - swAbstractionFractionData,\ - swAbstractionFractionDataQuality): + def partitioningGroundSurfaceAbstractionForIrrigation( + self, + swAbstractionFractionEstimate, + swAbstractionFractionData, + swAbstractionFractionDataQuality, + ): - # surface water source fraction based on Stefan Siebert's map: - factor = 0.5 # using this factor, the minimum value for the following 'data_weight_value' is 0.75 (for swAbstractionFractionDataQuality == 5) - data_weight_value = pcr.scalar(1.0) - \ - (pcr.min(5., pcr.max(0.0, swAbstractionFractionDataQuality))/10.0)*factor - - swAbstractionFractionForIrrigation = data_weight_value * swAbstractionFractionData +\ - (1.0 - data_weight_value) * swAbstractionFractionEstimate - - swAbstractionFractionForIrrigation = pcr.cover(swAbstractionFractionForIrrigation, swAbstractionFractionEstimate) - swAbstractionFractionForIrrigation = pcr.cover(swAbstractionFractionForIrrigation, 1.0) - swAbstractionFractionForIrrigation = pcr.ifthen(self.landmask, swAbstractionFractionForIrrigation) - - return swAbstractionFractionForIrrigation + # surface water source fraction based on Stefan Siebert's map: + factor = ( + 0.5 + ) # using this factor, the minimum value for the following 'data_weight_value' is 0.75 (for swAbstractionFractionDataQuality == 5) + data_weight_value = ( + pcr.scalar(1.0) + - (pcr.min(5., pcr.max(0.0, swAbstractionFractionDataQuality)) / 10.0) + * factor + ) - def scaleDynamicIrrigation(self,yearInInteger): + swAbstractionFractionForIrrigation = ( + data_weight_value * swAbstractionFractionData + + (1.0 - data_weight_value) * swAbstractionFractionEstimate + ) + + swAbstractionFractionForIrrigation = pcr.cover( + swAbstractionFractionForIrrigation, swAbstractionFractionEstimate + ) + swAbstractionFractionForIrrigation = pcr.cover( + swAbstractionFractionForIrrigation, 1.0 + ) + swAbstractionFractionForIrrigation = pcr.ifthen( + self.landmask, swAbstractionFractionForIrrigation + ) + + return swAbstractionFractionForIrrigation + + def scaleDynamicIrrigation(self, yearInInteger): # This method is to update fracVegCover of landCover for historical irrigation areas (done at yearly basis). - - - #~ # Available datasets are only from 1960 to 2010 (status on 24 September 2010) - #~ yearInInteger = int(yearInInteger) - #~ if float(yearInInteger) < 1960. or float(yearInInteger) > 2010.: - #~ msg = 'Dataset for the year '+str(yearInInteger)+" is not available. Dataset of historical irrigation areas is only available from 1960 to 2010." - #~ logger.warning(msg) - #~ yearInInteger = min(2010, max(1960, yearInInteger)) + + # ~ # Available datasets are only from 1960 to 2010 (status on 24 September 2010) + # ~ yearInInteger = int(yearInInteger) + # ~ if float(yearInInteger) < 1960. or float(yearInInteger) > 2010.: + # ~ msg = 'Dataset for the year '+str(yearInInteger)+" is not available. Dataset of historical irrigation areas is only available from 1960 to 2010." + # ~ logger.warning(msg) + # ~ yearInInteger = min(2010, max(1960, yearInInteger)) # # TODO: Generally, I do not need the aforementioned lines as I have defined the functions "findLastYearInNCTime" and "findFirstYearInNCTime" in the module virtualOS.py - # However, Niko still need them for his DA scheme as we somehow his DA scheme cannot handle the netcdf file of historical irrigation areas (and therefore we have to use pcraster map files). - + # However, Niko still need them for his DA scheme as we somehow his DA scheme cannot handle the netcdf file of historical irrigation areas (and therefore we have to use pcraster map files). - yearInString = str(yearInInteger) - - # read historical irrigation areas - if self.dynamicIrrigationAreaFile.endswith(('.nc4','.nc')): - fulldateInString = yearInString+"-01"+"-01" - self.irrigationArea = 10000. * pcr.cover(\ - vos.netcdf2PCRobjClone(self.dynamicIrrigationAreaFile,\ - 'irrigationArea',\ - fulldateInString, useDoy = 'yearly',\ - cloneMapFileName = self.cloneMap), 0.0) # unit: m2 (input file is in hectare) + yearInString = str(yearInInteger) + + # read historical irrigation areas + if self.dynamicIrrigationAreaFile.endswith((".nc4", ".nc")): + fulldateInString = yearInString + "-01" + "-01" + self.irrigationArea = 10000. * pcr.cover( + vos.netcdf2PCRobjClone( + self.dynamicIrrigationAreaFile, + "irrigationArea", + fulldateInString, + useDoy="yearly", + cloneMapFileName=self.cloneMap, + ), + 0.0, + ) # unit: m2 (input file is in hectare) else: - irrigation_pcraster_file = self.dynamicIrrigationAreaFile + yearInString + ".map" - logger.debug('reading irrigation area map from : '+irrigation_pcraster_file) - self.irrigationArea = 10000. * pcr.cover(\ - vos.readPCRmapClone(irrigation_pcraster_file,\ - self.cloneMap,self.tmpDir), 0.0) # unit: m2 (input file is in hectare) - - # TODO: Convert the input file, from hectare to percentage. + irrigation_pcraster_file = ( + self.dynamicIrrigationAreaFile + yearInString + ".map" + ) + logger.debug( + "reading irrigation area map from : " + irrigation_pcraster_file + ) + self.irrigationArea = 10000. * pcr.cover( + vos.readPCRmapClone( + irrigation_pcraster_file, self.cloneMap, self.tmpDir + ), + 0.0, + ) # unit: m2 (input file is in hectare) + + # TODO: Convert the input file, from hectare to percentage. # This is to avoid errors if somebody uses 30 min input to run his 5 min model. - + # area of irrigation is limited by cellArea - self.irrigationArea = pcr.max(self.irrigationArea, 0.0) - self.irrigationArea = pcr.min(self.irrigationArea, self.cellArea) # limited by cellArea - + self.irrigationArea = pcr.max(self.irrigationArea, 0.0) + self.irrigationArea = pcr.min( + self.irrigationArea, self.cellArea + ) # limited by cellArea + # calculate fracVegCover (for irrigation only) for coverType in self.coverTypes: - if coverType.startswith('irr'): - - self.landCoverObj[coverType].fractionArea = 0.0 # reset - self.landCoverObj[coverType].fractionArea = self.landCoverObj[coverType].irrTypeFracOverIrr * self.irrigationArea # unit: m2 - self.landCoverObj[coverType].fracVegCover = pcr.min(1.0, self.landCoverObj[coverType].fractionArea/ self.cellArea) + if coverType.startswith("irr"): + self.landCoverObj[coverType].fractionArea = 0.0 # reset + self.landCoverObj[coverType].fractionArea = ( + self.landCoverObj[coverType].irrTypeFracOverIrr + * self.irrigationArea + ) # unit: m2 + self.landCoverObj[coverType].fracVegCover = pcr.min( + 1.0, self.landCoverObj[coverType].fractionArea / self.cellArea + ) + # avoid small values - self.landCoverObj[coverType].fracVegCover = pcr.rounddown(self.landCoverObj[coverType].fracVegCover * 1000.)/1000. + self.landCoverObj[coverType].fracVegCover = ( + pcr.rounddown(self.landCoverObj[coverType].fracVegCover * 1000.) + / 1000. + ) # rescale land cover fractions (for all land cover types): self.scaleModifiedLandCoverFractions() - - def update(self,meteo,groundwater,routing,currTimeStep,wflow_logger): - + + def update(self, meteo, groundwater, routing, currTimeStep, wflow_logger): + # updating regional groundwater abstraction limit (at the begining of the year or at the beginning of simulation) if groundwater.limitRegionalAnnualGroundwaterAbstraction: - #logger.debug('Total groundwater abstraction is limited by regional annual pumping capacity.') + # logger.debug('Total groundwater abstraction is limited by regional annual pumping capacity.') if currTimeStep.doy == 1 or currTimeStep.timeStepPCR == 1: - - self.groundwater_pumping_region_ids = \ - vos.netcdf2PCRobjClone(groundwater.pumpingCapacityNC,'region_ids',\ - currTimeStep.fulldate, useDoy = 'yearly', cloneMapFileName = self.cloneMap) - other_ids = pcr.mapmaximum(self.groundwater_pumping_region_ids) + pcr.scalar(1000.) + pcr.uniqueid(self.landmask) - self.groundwater_pumping_region_ids = pcr.cover(self.groundwater_pumping_region_ids, other_ids) - self.groundwater_pumping_region_ids = pcr.ifthen(self.landmask, pcr.nominal(self.groundwater_pumping_region_ids)) - self.regionalAnnualGroundwaterAbstractionLimit = \ - pcr.ifthen(self.landmask,\ - pcr.cover(\ - vos.netcdf2PCRobjClone(groundwater.pumpingCapacityNC,'regional_pumping_limit',\ - currTimeStep.fulldate, useDoy = 'yearly', cloneMapFileName = self.cloneMap), 0.0)) - - self.regionalAnnualGroundwaterAbstractionLimit = pcr.areamaximum(self.regionalAnnualGroundwaterAbstractionLimit, self.groundwater_pumping_region_ids) - - self.regionalAnnualGroundwaterAbstractionLimit *= 1000. * 1000. * 1000. # unit: m3/year - self.regionalAnnualGroundwaterAbstractionLimit = pcr.ifthen(self.landmask,\ - self.regionalAnnualGroundwaterAbstractionLimit) + self.groundwater_pumping_region_ids = vos.netcdf2PCRobjClone( + groundwater.pumpingCapacityNC, + "region_ids", + currTimeStep.fulldate, + useDoy="yearly", + cloneMapFileName=self.cloneMap, + ) + other_ids = ( + pcr.mapmaximum(self.groundwater_pumping_region_ids) + + pcr.scalar(1000.) + + pcr.uniqueid(self.landmask) + ) + self.groundwater_pumping_region_ids = pcr.cover( + self.groundwater_pumping_region_ids, other_ids + ) + self.groundwater_pumping_region_ids = pcr.ifthen( + self.landmask, pcr.nominal(self.groundwater_pumping_region_ids) + ) + + self.regionalAnnualGroundwaterAbstractionLimit = pcr.ifthen( + self.landmask, + pcr.cover( + vos.netcdf2PCRobjClone( + groundwater.pumpingCapacityNC, + "regional_pumping_limit", + currTimeStep.fulldate, + useDoy="yearly", + cloneMapFileName=self.cloneMap, + ), + 0.0, + ), + ) + + self.regionalAnnualGroundwaterAbstractionLimit = pcr.areamaximum( + self.regionalAnnualGroundwaterAbstractionLimit, + self.groundwater_pumping_region_ids, + ) + + self.regionalAnnualGroundwaterAbstractionLimit *= ( + 1000. * 1000. * 1000. + ) # unit: m3/year + self.regionalAnnualGroundwaterAbstractionLimit = pcr.ifthen( + self.landmask, self.regionalAnnualGroundwaterAbstractionLimit + ) # minimum value (unit: m3/year at the regional scale) minimum_value = 1000. - self.regionalAnnualGroundwaterAbstractionLimit = pcr.max(minimum_value,\ - self.regionalAnnualGroundwaterAbstractionLimit) + self.regionalAnnualGroundwaterAbstractionLimit = pcr.max( + minimum_value, self.regionalAnnualGroundwaterAbstractionLimit + ) else: - - #logger.debug('Total groundwater abstraction is NOT limited by regional annual pumping capacity.') + + # logger.debug('Total groundwater abstraction is NOT limited by regional annual pumping capacity.') self.groundwater_pumping_region_ids = None self.regionalAnnualGroundwaterAbstractionLimit = None - - # updating fracVegCover of each landCover (landCover fraction) + + # updating fracVegCover of each landCover (landCover fraction) # - if considering dynamic/historical irrigation areas (expansion/reduction of irrigated areas) # - done at yearly basis, at the beginning of each year, also at the beginning of simulation # - if self.dynamicIrrigationArea and self.includeIrrigation and \ - (currTimeStep.timeStepPCR == 1 or currTimeStep.doy == 1) and self.noLandCoverFractionCorrection == False: - + if ( + self.dynamicIrrigationArea + and self.includeIrrigation + and (currTimeStep.timeStepPCR == 1 or currTimeStep.doy == 1) + and self.noLandCoverFractionCorrection == False + ): + # scale land cover fraction (due to expansion/reduction of irrigated areas) self.scaleDynamicIrrigation(currTimeStep.year) #################################################################################################################################################################### # correcting land cover fractions total_fractions = pcr.scalar(0.0) for coverType in self.coverTypes: - total_fractions += self.landCoverObj[coverType].fracVegCover - - if 'grassland' in self.landCoverObj.keys(): - self.landCoverObj['grassland'].fracVegCover = pcr.ifthenelse(total_fractions > 0.1, self.landCoverObj['grassland'].fracVegCover, 1.0) - - if 'short_natural' in self.landCoverObj.keys(): - self.landCoverObj['short_natural'].fracVegCover = pcr.ifthenelse(total_fractions > 0.1, self.landCoverObj['short_natural'].fracVegCover, 1.0) - + total_fractions += self.landCoverObj[coverType].fracVegCover + + if "grassland" in self.landCoverObj.keys(): + self.landCoverObj["grassland"].fracVegCover = pcr.ifthenelse( + total_fractions > 0.1, + self.landCoverObj["grassland"].fracVegCover, + 1.0, + ) + + if "short_natural" in self.landCoverObj.keys(): + self.landCoverObj["short_natural"].fracVegCover = pcr.ifthenelse( + total_fractions > 0.1, + self.landCoverObj["short_natural"].fracVegCover, + 1.0, + ) + total_fractions = pcr.scalar(0.0) for coverType in self.coverTypes: - total_fractions += self.landCoverObj[coverType].fracVegCover - + total_fractions += self.landCoverObj[coverType].fracVegCover + for coverType in self.coverTypes: - self.landCoverObj[coverType].fracVegCover = self.landCoverObj[coverType].fracVegCover / total_fractions + self.landCoverObj[coverType].fracVegCover = ( + self.landCoverObj[coverType].fracVegCover / total_fractions + ) #################################################################################################################################################################### - # read land cover fractions from netcdf files # - assumption: annual resolution - if self.noAnnualChangesInLandCoverParameter == False and self.dynamicIrrigationArea == False and \ - (currTimeStep.timeStepPCR == 1 or currTimeStep.doy == 1): - msg = 'Read land cover fractions based on the given netcdf file.' - #logger.debug(msg) + if ( + self.noAnnualChangesInLandCoverParameter == False + and self.dynamicIrrigationArea == False + and (currTimeStep.timeStepPCR == 1 or currTimeStep.doy == 1) + ): + msg = "Read land cover fractions based on the given netcdf file." + # logger.debug(msg) for coverType in self.coverTypes: - self.landCoverObj[coverType].fracVegCover = self.landCoverObj[coverType].get_land_cover_parameters(date_in_string = str(currTimeStep.fulldate), \ - get_only_fracVegCover = True) + self.landCoverObj[coverType].fracVegCover = self.landCoverObj[ + coverType + ].get_land_cover_parameters( + date_in_string=str(currTimeStep.fulldate), + get_only_fracVegCover=True, + ) #################################################################################################################################################################### # correcting land cover fractions total_fractions = pcr.scalar(0.0) for coverType in self.coverTypes: - total_fractions += self.landCoverObj[coverType].fracVegCover - - if 'grassland' in self.landCoverObj.keys(): - self.landCoverObj['grassland'].fracVegCover = pcr.ifthenelse(total_fractions > 0.1, self.landCoverObj['grassland'].fracVegCover, 1.0) - - if 'short_natural' in self.landCoverObj.keys(): - self.landCoverObj['short_natural'].fracVegCover = pcr.ifthenelse(total_fractions > 0.1, self.landCoverObj['short_natural'].fracVegCover, 1.0) - + total_fractions += self.landCoverObj[coverType].fracVegCover + + if "grassland" in self.landCoverObj.keys(): + self.landCoverObj["grassland"].fracVegCover = pcr.ifthenelse( + total_fractions > 0.1, + self.landCoverObj["grassland"].fracVegCover, + 1.0, + ) + + if "short_natural" in self.landCoverObj.keys(): + self.landCoverObj["short_natural"].fracVegCover = pcr.ifthenelse( + total_fractions > 0.1, + self.landCoverObj["short_natural"].fracVegCover, + 1.0, + ) + total_fractions = pcr.scalar(0.0) for coverType in self.coverTypes: - total_fractions += self.landCoverObj[coverType].fracVegCover - + total_fractions += self.landCoverObj[coverType].fracVegCover + for coverType in self.coverTypes: - self.landCoverObj[coverType].fracVegCover = self.landCoverObj[coverType].fracVegCover / total_fractions + self.landCoverObj[coverType].fracVegCover = ( + self.landCoverObj[coverType].fracVegCover / total_fractions + ) #################################################################################################################################################################### - # transfer some states, due to changes/dynamics in land cover conditions # - if considering dynamic/historical irrigation areas (expansion/reduction of irrigated areas) # - done at yearly basis, at the beginning of each year # - note that this must be done at the beginning of each year, including for the first time step (timeStepPCR == 1) # - if ((self.dynamicIrrigationArea and self.includeIrrigation) or self.noAnnualChangesInLandCoverParameter == False) and currTimeStep.doy == 1: + if ( + (self.dynamicIrrigationArea and self.includeIrrigation) + or self.noAnnualChangesInLandCoverParameter == False + ) and currTimeStep.doy == 1: # # loop for all main states: for var in self.mainStates: - - #logger.info("Transfering states for the variable "+str(var)) - moving_fraction = pcr.scalar(0.0) # total land cover fractions that will be transferred - moving_states = pcr.scalar(0.0) # total states that will be transferred - + # logger.info("Transfering states for the variable "+str(var)) + + moving_fraction = pcr.scalar( + 0.0 + ) # total land cover fractions that will be transferred + moving_states = pcr.scalar(0.0) # total states that will be transferred + for coverType in self.coverTypes: - + old_fraction = self.landCoverObj[coverType].previousFracVegCover new_fraction = self.landCoverObj[coverType].fracVegCover - - moving_fraction += pcr.max(0.0, old_fraction-new_fraction) - moving_states += pcr.max(0.0, old_fraction-new_fraction) * vars(self.landCoverObj[coverType])[var] + moving_fraction += pcr.max(0.0, old_fraction - new_fraction) + moving_states += ( + pcr.max(0.0, old_fraction - new_fraction) + * vars(self.landCoverObj[coverType])[var] + ) + previous_state = pcr.scalar(0.0) rescaled_state = pcr.scalar(0.0) - + # correcting states for coverType in self.coverTypes: - - old_states = vars(self.landCoverObj[coverType])[var] + + old_states = vars(self.landCoverObj[coverType])[var] old_fraction = self.landCoverObj[coverType].previousFracVegCover new_fraction = self.landCoverObj[coverType].fracVegCover - - correction = moving_states *\ - vos.getValDivZero( pcr.max(0.0, new_fraction - old_fraction),\ - moving_fraction, vos.smallNumber ) - - new_states = pcr.ifthenelse(new_fraction > old_fraction, - vos.getValDivZero( - old_states * old_fraction + correction, \ - new_fraction, vos.smallNumber), old_states) - - new_states = pcr.ifthenelse(new_fraction > 0.0, new_states, pcr.scalar(0.0)) - + + correction = moving_states * vos.getValDivZero( + pcr.max(0.0, new_fraction - old_fraction), + moving_fraction, + vos.smallNumber, + ) + + new_states = pcr.ifthenelse( + new_fraction > old_fraction, + vos.getValDivZero( + old_states * old_fraction + correction, + new_fraction, + vos.smallNumber, + ), + old_states, + ) + + new_states = pcr.ifthenelse( + new_fraction > 0.0, new_states, pcr.scalar(0.0) + ) + vars(self.landCoverObj[coverType])[var] = new_states previous_state += old_fraction * old_states rescaled_state += new_fraction * new_states - + # check and make sure that previous_state == rescaled_state check_map = previous_state - rescaled_state - a,b,c = vos.getMinMaxMean(check_map) + a, b, c = vos.getMinMaxMean(check_map) threshold = 1e-5 - #if abs(a) > threshold or abs(b) > threshold: + # if abs(a) > threshold or abs(b) > threshold: # logger.warning("Error in transfering states (due to dynamic in land cover fractions) ... Min %f Max %f Mean %f" %(a,b,c)) - #else: + # else: # logger.info("Successful in transfering states (after change in land cover fractions) ... Min %f Max %f Mean %f" %(a,b,c)) - # for the last day of the year, we have to save the previous land cover fractions (to be considered in the next time step) - if self.dynamicIrrigationArea and self.includeIrrigation and currTimeStep.isLastDayOfYear: + # for the last day of the year, we have to save the previous land cover fractions (to be considered in the next time step) + if ( + self.dynamicIrrigationArea + and self.includeIrrigation + and currTimeStep.isLastDayOfYear + ): # save the current state of fracVegCover - for coverType in self.coverTypes:\ - self.landCoverObj[coverType].previousFracVegCover = self.landCoverObj[coverType].fracVegCover + for coverType in self.coverTypes: + self.landCoverObj[coverType].previousFracVegCover = self.landCoverObj[ + coverType + ].fracVegCover # calculate cell fraction influenced by capillary rise: - self.capRiseFrac = self.calculateCapRiseFrac(groundwater,routing,currTimeStep) - + self.capRiseFrac = self.calculateCapRiseFrac(groundwater, routing, currTimeStep) + # get a dictionary containing livestock, domestic and industrial water demand, including their return flow fractions - self.nonIrrigationWaterDemandDict = self.obtainNonIrrWaterDemand(routing, currTimeStep) - + self.nonIrrigationWaterDemandDict = self.obtainNonIrrWaterDemand( + routing, currTimeStep + ) + # get a dictionary containing the partitioning of withdrawal/abstraction sources: (from groundwater and surface water) - self.swAbstractionFractionDict = self.partitioningGroundSurfaceAbstraction(groundwater,routing) - + self.swAbstractionFractionDict = self.partitioningGroundSurfaceAbstraction( + groundwater, routing + ) + # get desalination water use (m/day); assume this one as potential supply - if self.includeDesalination: - #logger.debug("Monthly desalination water use is included.") - if (currTimeStep.timeStepPCR == 1 or currTimeStep.day == 1): - desalinationWaterUse = \ - pcr.ifthen(self.landmask,\ - pcr.cover(\ - vos.netcdf2PCRobjClone(self.desalinationWaterFile,'desalination_water_use',\ - currTimeStep.fulldate, useDoy = 'monthly', cloneMapFileName = self.cloneMap), 0.0)) + if self.includeDesalination: + # logger.debug("Monthly desalination water use is included.") + if currTimeStep.timeStepPCR == 1 or currTimeStep.day == 1: + desalinationWaterUse = pcr.ifthen( + self.landmask, + pcr.cover( + vos.netcdf2PCRobjClone( + self.desalinationWaterFile, + "desalination_water_use", + currTimeStep.fulldate, + useDoy="monthly", + cloneMapFileName=self.cloneMap, + ), + 0.0, + ), + ) self.desalinationWaterUse = pcr.max(0.0, desalinationWaterUse) - else: - #logger.debug("Monthly desalination water use is NOT included.") + else: + # logger.debug("Monthly desalination water use is NOT included.") self.desalinationWaterUse = pcr.scalar(0.0) - + # update (loop per each land cover type): wflow_logger.info("start landsurface landcover") for coverType in self.coverTypes: - - #logger.info("Updating land cover: "+str(coverType)) - self.landCoverObj[coverType].updateLC(meteo,groundwater,routing,\ - self.capRiseFrac,\ - self.nonIrrigationWaterDemandDict,\ - self.swAbstractionFractionDict,\ - currTimeStep,\ - self.allocSegments,\ - self.desalinationWaterUse,\ - self.groundwater_pumping_region_ids,self.regionalAnnualGroundwaterAbstractionLimit,wflow_logger) - wflow_logger.info("end landsurface landcover") - # first, we set all aggregated values/variables to zero: - for var in self.aggrVars: vars(self)[var] = pcr.scalar(0.0) + + # logger.info("Updating land cover: "+str(coverType)) + self.landCoverObj[coverType].updateLC( + meteo, + groundwater, + routing, + self.capRiseFrac, + self.nonIrrigationWaterDemandDict, + self.swAbstractionFractionDict, + currTimeStep, + self.allocSegments, + self.desalinationWaterUse, + self.groundwater_pumping_region_ids, + self.regionalAnnualGroundwaterAbstractionLimit, + wflow_logger, + ) + wflow_logger.info("end landsurface landcover") + # first, we set all aggregated values/variables to zero: + for var in self.aggrVars: + vars(self)[var] = pcr.scalar(0.0) # # get or calculate the values of all aggregated values/variables for coverType in self.coverTypes: - # calculate the aggregrated or global landSurface values: + # calculate the aggregrated or global landSurface values: for var in self.aggrVars: - vars(self)[var] += \ - self.landCoverObj[coverType].fracVegCover * vars(self.landCoverObj[coverType])[var] - + vars(self)[var] += ( + self.landCoverObj[coverType].fracVegCover + * vars(self.landCoverObj[coverType])[var] + ) + # total storages (unit: m3) in the entire landSurface module - if self.numberOfSoilLayers == 2: self.totalSto = \ - self.snowCoverSWE + self.snowFreeWater + self.interceptStor +\ - self.topWaterLayer +\ - self.storUpp +\ - self.storLow + if self.numberOfSoilLayers == 2: + self.totalSto = ( + self.snowCoverSWE + + self.snowFreeWater + + self.interceptStor + + self.topWaterLayer + + self.storUpp + + self.storLow + ) # - if self.numberOfSoilLayers == 3: self.totalSto = \ - self.snowCoverSWE + self.snowFreeWater + self.interceptStor +\ - self.topWaterLayer +\ - self.storUpp000005 + self.storUpp005030 +\ - self.storLow030150 + if self.numberOfSoilLayers == 3: + self.totalSto = ( + self.snowCoverSWE + + self.snowFreeWater + + self.interceptStor + + self.topWaterLayer + + self.storUpp000005 + + self.storUpp005030 + + self.storLow030150 + ) - # old-style reporting (this is useful for debugging) - #self.old_style_land_surface_reporting(currTimeStep) + # old-style reporting (this is useful for debugging) + # self.old_style_land_surface_reporting(currTimeStep) - def old_style_land_surface_reporting(self,currTimeStep): + def old_style_land_surface_reporting(self, currTimeStep): if self.report == True: - timeStamp = datetime.datetime(currTimeStep.year,\ - currTimeStep.month,\ - currTimeStep.day,\ - 0) + timeStamp = datetime.datetime( + currTimeStep.year, currTimeStep.month, currTimeStep.day, 0 + ) # writing daily output to netcdf files timestepPCR = currTimeStep.timeStepPCR if self.outDailyTotNC[0] != "None": for var in self.outDailyTotNC: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_dailyTot.nc",\ - var,\ - pcr.pcr2numpy(self.__getattribute__(var),vos.MV),\ - timeStamp,timestepPCR-1) + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_dailyTot.nc", + var, + pcr.pcr2numpy(self.__getattribute__(var), vos.MV), + timeStamp, + timestepPCR - 1, + ) # writing monthly output to netcdf files # -cummulative @@ -1418,54 +2322,63 @@ # introduce variables at the beginning of simulation or # reset variables at the beginning of the month - if currTimeStep.timeStepPCR == 1 or \ - currTimeStep.day == 1:\ - vars(self)[var+'MonthTot'] = pcr.scalar(0.0) + if currTimeStep.timeStepPCR == 1 or currTimeStep.day == 1: + vars(self)[var + "MonthTot"] = pcr.scalar(0.0) # accumulating - vars(self)[var+'MonthTot'] += vars(self)[var] + vars(self)[var + "MonthTot"] += vars(self)[var] # reporting at the end of the month: - if currTimeStep.endMonth == True: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthTot.nc",\ - var,\ - pcr.pcr2numpy(self.__getattribute__(var+'MonthTot'),\ - vos.MV),timeStamp,currTimeStep.monthIdx-1) + if currTimeStep.endMonth == True: + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthTot.nc", + var, + pcr.pcr2numpy( + self.__getattribute__(var + "MonthTot"), vos.MV + ), + timeStamp, + currTimeStep.monthIdx - 1, + ) # -average if self.outMonthAvgNC[0] != "None": for var in self.outMonthAvgNC: - # only if a accumulator variable has not been defined: - if var not in self.outMonthTotNC: + # only if a accumulator variable has not been defined: + if var not in self.outMonthTotNC: # introduce accumulator at the beginning of simulation or # reset accumulator at the beginning of the month - if currTimeStep.timeStepPCR == 1 or \ - currTimeStep.day == 1:\ - vars(self)[var+'MonthTot'] = pcr.scalar(0.0) + if currTimeStep.timeStepPCR == 1 or currTimeStep.day == 1: + vars(self)[var + "MonthTot"] = pcr.scalar(0.0) # accumulating - vars(self)[var+'MonthTot'] += vars(self)[var] + vars(self)[var + "MonthTot"] += vars(self)[var] # calculating average & reporting at the end of the month: if currTimeStep.endMonth == True: - vars(self)[var+'MonthAvg'] = vars(self)[var+'MonthTot']/\ - currTimeStep.day - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthAvg.nc",\ - var,\ - pcr.pcr2numpy(self.__getattribute__(var+'MonthAvg'),\ - vos.MV),timeStamp,currTimeStep.monthIdx-1) + vars(self)[var + "MonthAvg"] = ( + vars(self)[var + "MonthTot"] / currTimeStep.day + ) + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthAvg.nc", + var, + pcr.pcr2numpy( + self.__getattribute__(var + "MonthAvg"), vos.MV + ), + timeStamp, + currTimeStep.monthIdx - 1, + ) # # -last day of the month if self.outMonthEndNC[0] != "None": for var in self.outMonthEndNC: # reporting at the end of the month: - if currTimeStep.endMonth == True: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthEnd.nc",\ - var,\ - pcr.pcr2numpy(self.__getattribute__(var),vos.MV),\ - timeStamp,currTimeStep.monthIdx-1) + if currTimeStep.endMonth == True: + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthEnd.nc", + var, + pcr.pcr2numpy(self.__getattribute__(var), vos.MV), + timeStamp, + currTimeStep.monthIdx - 1, + ) # writing yearly output to netcdf files # -cummulative @@ -1474,50 +2387,59 @@ # introduce variables at the beginning of simulation or # reset variables at the beginning of the month - if currTimeStep.timeStepPCR == 1 or \ - currTimeStep.doy == 1:\ - vars(self)[var+'AnnuaTot'] = pcr.scalar(0.0) + if currTimeStep.timeStepPCR == 1 or currTimeStep.doy == 1: + vars(self)[var + "AnnuaTot"] = pcr.scalar(0.0) # accumulating - vars(self)[var+'AnnuaTot'] += vars(self)[var] + vars(self)[var + "AnnuaTot"] += vars(self)[var] # reporting at the end of the year: - if currTimeStep.endYear == True: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaTot.nc",\ - var,\ - pcr.pcr2numpy(self.__getattribute__(var+'AnnuaTot'),\ - vos.MV),timeStamp,currTimeStep.annuaIdx-1) + if currTimeStep.endYear == True: + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaTot.nc", + var, + pcr.pcr2numpy( + self.__getattribute__(var + "AnnuaTot"), vos.MV + ), + timeStamp, + currTimeStep.annuaIdx - 1, + ) # -average if self.outAnnuaAvgNC[0] != "None": for var in self.outAnnuaAvgNC: - # only if a accumulator variable has not been defined: - if var not in self.outAnnuaTotNC: + # only if a accumulator variable has not been defined: + if var not in self.outAnnuaTotNC: # introduce accumulator at the beginning of simulation or # reset accumulator at the beginning of the year - if currTimeStep.timeStepPCR == 1 or \ - currTimeStep.doy == 1:\ - vars(self)[var+'AnnuaTot'] = pcr.scalar(0.0) + if currTimeStep.timeStepPCR == 1 or currTimeStep.doy == 1: + vars(self)[var + "AnnuaTot"] = pcr.scalar(0.0) # accumulating - vars(self)[var+'AnnuaTot'] += vars(self)[var] + vars(self)[var + "AnnuaTot"] += vars(self)[var] # # calculating average & reporting at the end of the year: if currTimeStep.endYear == True: - vars(self)[var+'AnnuaAvg'] = vars(self)[var+'AnnuaTot']/\ - currTimeStep.doy - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaAvg.nc",\ - var,\ - pcr.pcr2numpy(self.__getattribute__(var+'AnnuaAvg'),\ - vos.MV),timeStamp,currTimeStep.annuaIdx-1) + vars(self)[var + "AnnuaAvg"] = ( + vars(self)[var + "AnnuaTot"] / currTimeStep.doy + ) + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaAvg.nc", + var, + pcr.pcr2numpy( + self.__getattribute__(var + "AnnuaAvg"), vos.MV + ), + timeStamp, + currTimeStep.annuaIdx - 1, + ) # # -last day of the year if self.outAnnuaEndNC[0] != "None": for var in self.outAnnuaEndNC: # reporting at the end of the year: - if currTimeStep.endYear == True: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaEnd.nc",\ - var,\ - pcr.pcr2numpy(self.__getattribute__(var),vos.MV),\ - timeStamp,currTimeStep.annuaIdx-1) + if currTimeStep.endYear == True: + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaEnd.nc", + var, + pcr.pcr2numpy(self.__getattribute__(var), vos.MV), + timeStamp, + currTimeStep.annuaIdx - 1, + ) Index: wflow-py/wflow/pcrglobwb/ncConverter.py =================================================================== diff -u -rbec706d676b364d4a89a4e7141382db4511fa485 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/pcrglobwb/ncConverter.py (.../ncConverter.py) (revision bec706d676b364d4a89a4e7141382db4511fa485) +++ wflow-py/wflow/pcrglobwb/ncConverter.py (.../ncConverter.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -36,175 +36,219 @@ # TODO: defined the dictionary (e.g. filecache = dict()) to avoid open and closing files -class PCR2netCDF(): - - def __init__(self,iniItems,specificAttributeDictionary=None): - + +class PCR2netCDF: + def __init__(self, iniItems, specificAttributeDictionary=None): + # cloneMap pcr.setclone(iniItems.cloneMap) cloneMap = pcr.boolean(1.0) - + # latitudes and longitudes - self.latitudes = np.unique(pcr.pcr2numpy(pcr.ycoordinate(cloneMap), vos.MV))[::-1] + self.latitudes = np.unique(pcr.pcr2numpy(pcr.ycoordinate(cloneMap), vos.MV))[ + ::-1 + ] self.longitudes = np.unique(pcr.pcr2numpy(pcr.xcoordinate(cloneMap), vos.MV)) - - # Let users decide what their preference regarding latitude order. + + # Let users decide what their preference regarding latitude order. self.netcdf_y_orientation_follow_cf_convention = False - if 'netcdf_y_orientation_follow_cf_convention' in iniItems.reportingOptions.keys() and\ - iniItems.reportingOptions['netcdf_y_orientation_follow_cf_convention'] == "True": + if ( + "netcdf_y_orientation_follow_cf_convention" + in iniItems.reportingOptions.keys() + and iniItems.reportingOptions["netcdf_y_orientation_follow_cf_convention"] + == "True" + ): msg = "Latitude (y) orientation for output netcdf files start from the bottom to top." self.netcdf_y_orientation_follow_cf_convention = True - self.latitudes = np.unique(pcr.pcr2numpy(pcr.ycoordinate(cloneMap), vos.MV)) - - # set the general netcdf attributes (based on the information given in the ini/configuration file) + self.latitudes = np.unique(pcr.pcr2numpy(pcr.ycoordinate(cloneMap), vos.MV)) + + # set the general netcdf attributes (based on the information given in the ini/configuration file) self.set_general_netcdf_attributes(iniItems, specificAttributeDictionary) - - # netcdf format and zlib setup - self.format = 'NETCDF3_CLASSIC' + + # netcdf format and zlib setup + self.format = "NETCDF3_CLASSIC" self.zlib = False if "formatNetCDF" in iniItems.reportingOptions.keys(): - self.format = str(iniItems.reportingOptions['formatNetCDF']) + self.format = str(iniItems.reportingOptions["formatNetCDF"]) if "zlib" in iniItems.reportingOptions.keys(): - if iniItems.reportingOptions['zlib'] == "True": self.zlib = True - + if iniItems.reportingOptions["zlib"] == "True": + self.zlib = True # if given in the ini file, use the netcdf as given in the section 'specific_attributes_for_netcdf_output_files' - if 'specific_attributes_for_netcdf_output_files' in iniItems.allSections: + if "specific_attributes_for_netcdf_output_files" in iniItems.allSections: for key in iniItems.specific_attributes_for_netcdf_output_files.keys(): - self.attributeDictionary[key] = iniItems.specific_attributes_for_netcdf_output_files[key] - - if self.attributeDictionary[key] == "None": self.attributeDictionary[key] = "" + self.attributeDictionary[ + key + ] = iniItems.specific_attributes_for_netcdf_output_files[key] + if self.attributeDictionary[key] == "None": + self.attributeDictionary[key] = "" + if key == "history" and self.attributeDictionary[key] == "Default": - self.attributeDictionary[key] = \ - 'created on ' + datetime.datetime.today().isoformat(' ') - if self.attributeDictionary[key] == "Default" and\ - (key == "date_created" or key == "date_issued"): - self.attributeDictionary[key] = datetime.datetime.today().isoformat(' ') - - - def set_general_netcdf_attributes(self,iniItems,specificAttributeDictionary=None): + self.attributeDictionary[ + key + ] = "created on " + datetime.datetime.today().isoformat(" ") + if self.attributeDictionary[key] == "Default" and ( + key == "date_created" or key == "date_issued" + ): + self.attributeDictionary[key] = datetime.datetime.today().isoformat( + " " + ) + def set_general_netcdf_attributes(self, iniItems, specificAttributeDictionary=None): + # netCDF attributes (based on the configuration file or specificAttributeDictionary): self.attributeDictionary = {} if specificAttributeDictionary == None: - self.attributeDictionary['institution'] = iniItems.globalOptions['institution'] - self.attributeDictionary['title' ] = iniItems.globalOptions['title' ] - self.attributeDictionary['description'] = iniItems.globalOptions['description'] + self.attributeDictionary["institution"] = iniItems.globalOptions[ + "institution" + ] + self.attributeDictionary["title"] = iniItems.globalOptions["title"] + self.attributeDictionary["description"] = iniItems.globalOptions[ + "description" + ] else: - self.attributeDictionary['institution'] = specificAttributeDictionary['institution'] - self.attributeDictionary['title' ] = specificAttributeDictionary['title' ] - self.attributeDictionary['description'] = specificAttributeDictionary['description'] + self.attributeDictionary["institution"] = specificAttributeDictionary[ + "institution" + ] + self.attributeDictionary["title"] = specificAttributeDictionary["title"] + self.attributeDictionary["description"] = specificAttributeDictionary[ + "description" + ] - def createNetCDF(self, ncFileName, varName, varUnits, longName = None): + def createNetCDF(self, ncFileName, varName, varUnits, longName=None): - rootgrp = nc.Dataset(ncFileName,'w',format= self.format) + rootgrp = nc.Dataset(ncFileName, "w", format=self.format) - #-create dimensions - time is unlimited, others are fixed - rootgrp.createDimension('time',None) - rootgrp.createDimension('lat',len(self.latitudes)) - rootgrp.createDimension('lon',len(self.longitudes)) + # -create dimensions - time is unlimited, others are fixed + rootgrp.createDimension("time", None) + rootgrp.createDimension("lat", len(self.latitudes)) + rootgrp.createDimension("lon", len(self.longitudes)) - date_time = rootgrp.createVariable('time','f4',('time',)) - date_time.standard_name = 'time' - date_time.long_name = 'Days since 1901-01-01' + date_time = rootgrp.createVariable("time", "f4", ("time",)) + date_time.standard_name = "time" + date_time.long_name = "Days since 1901-01-01" - date_time.units = 'Days since 1901-01-01' - date_time.calendar = 'standard' + date_time.units = "Days since 1901-01-01" + date_time.calendar = "standard" - lat= rootgrp.createVariable('lat','f4',('lat',)) - lat.long_name = 'latitude' - lat.units = 'degrees_north' - lat.standard_name = 'latitude' + lat = rootgrp.createVariable("lat", "f4", ("lat",)) + lat.long_name = "latitude" + lat.units = "degrees_north" + lat.standard_name = "latitude" - lon= rootgrp.createVariable('lon','f4',('lon',)) - lon.standard_name = 'longitude' - lon.long_name = 'longitude' - lon.units = 'degrees_east' + lon = rootgrp.createVariable("lon", "f4", ("lon",)) + lon.standard_name = "longitude" + lon.long_name = "longitude" + lon.units = "degrees_east" - lat[:]= self.latitudes - lon[:]= self.longitudes + lat[:] = self.latitudes + lon[:] = self.longitudes shortVarName = varName - longVarName = varName - if longName != None: longVarName = longName + longVarName = varName + if longName != None: + longVarName = longName - var = rootgrp.createVariable(shortVarName,'f4',('time','lat','lon',) ,fill_value=vos.MV,zlib=self.zlib) + var = rootgrp.createVariable( + shortVarName, + "f4", + ("time", "lat", "lon"), + fill_value=vos.MV, + zlib=self.zlib, + ) var.standard_name = varName var.long_name = longVarName var.units = varUnits attributeDictionary = self.attributeDictionary - for k, v in attributeDictionary.items(): setattr(rootgrp,k,v) + for k, v in attributeDictionary.items(): + setattr(rootgrp, k, v) rootgrp.sync() rootgrp.close() def changeAtrribute(self, ncFileName, attributeDictionary): - rootgrp = nc.Dataset(ncFileName,'a') + rootgrp = nc.Dataset(ncFileName, "a") - for k, v in attributeDictionary.items(): setattr(rootgrp,k,v) + for k, v in attributeDictionary.items(): + setattr(rootgrp, k, v) rootgrp.sync() rootgrp.close() - def addNewVariable(self, ncFileName, varName, varUnits, longName = None): + def addNewVariable(self, ncFileName, varName, varUnits, longName=None): - rootgrp = nc.Dataset(ncFileName,'a') + rootgrp = nc.Dataset(ncFileName, "a") shortVarName = varName - longVarName = varName - if longName != None: longVarName = longName + longVarName = varName + if longName != None: + longVarName = longName - var = rootgrp.createVariable(shortVarName,'f4',('time','lat','lon',) ,fill_value=vos.MV,zlib=self.zlib) + var = rootgrp.createVariable( + shortVarName, + "f4", + ("time", "lat", "lon"), + fill_value=vos.MV, + zlib=self.zlib, + ) var.standard_name = varName var.long_name = longVarName var.units = varUnits rootgrp.sync() rootgrp.close() - def data2NetCDF(self, ncFileName, shortVarName, varField, timeStamp, posCnt = None): + def data2NetCDF(self, ncFileName, shortVarName, varField, timeStamp, posCnt=None): - rootgrp = nc.Dataset(ncFileName,'a') + rootgrp = nc.Dataset(ncFileName, "a") - date_time = rootgrp.variables['time'] - if posCnt == None: posCnt = len(date_time) - date_time[posCnt] = nc.date2num(timeStamp,date_time.units,date_time.calendar) + date_time = rootgrp.variables["time"] + if posCnt == None: + posCnt = len(date_time) + date_time[posCnt] = nc.date2num(timeStamp, date_time.units, date_time.calendar) # flip variable if necessary (to follow cf_convention) - if self.netcdf_y_orientation_follow_cf_convention: varField = np.flipud(varField) - - rootgrp.variables[shortVarName][posCnt,:,:] = varField + if self.netcdf_y_orientation_follow_cf_convention: + varField = np.flipud(varField) + rootgrp.variables[shortVarName][posCnt, :, :] = varField + rootgrp.sync() rootgrp.close() - def dataList2NetCDF(self, ncFileName, shortVarNameList, varFieldList, timeStamp, posCnt = None): + def dataList2NetCDF( + self, ncFileName, shortVarNameList, varFieldList, timeStamp, posCnt=None + ): - rootgrp = nc.Dataset(ncFileName,'a') + rootgrp = nc.Dataset(ncFileName, "a") - date_time = rootgrp.variables['time'] - if posCnt == None: posCnt = len(date_time) + date_time = rootgrp.variables["time"] + if posCnt == None: + posCnt = len(date_time) for shortVarName in shortVarNameList: - - date_time[posCnt] = nc.date2num(timeStamp,date_time.units,date_time.calendar) + + date_time[posCnt] = nc.date2num( + timeStamp, date_time.units, date_time.calendar + ) varField = varFieldList[shortVarName] - + # flip variable if necessary (to follow cf_convention) - if self.netcdf_y_orientation_follow_cf_convention: varField = np.flipud(varField) - - rootgrp.variables[shortVarName][posCnt,:,:] = varField + if self.netcdf_y_orientation_follow_cf_convention: + varField = np.flipud(varField) + rootgrp.variables[shortVarName][posCnt, :, :] = varField + rootgrp.sync() rootgrp.close() def close(self, ncFileName): - rootgrp = nc.Dataset(ncFileName,'w') + rootgrp = nc.Dataset(ncFileName, "w") - # closing the file + # closing the file rootgrp.close() Index: wflow-py/wflow/pcrglobwb/parameterSoilAndTopo.py =================================================================== diff -u -rbec706d676b364d4a89a4e7141382db4511fa485 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/pcrglobwb/parameterSoilAndTopo.py (.../parameterSoilAndTopo.py) (revision bec706d676b364d4a89a4e7141382db4511fa485) +++ wflow-py/wflow/pcrglobwb/parameterSoilAndTopo.py (.../parameterSoilAndTopo.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -30,381 +30,492 @@ from wflow.wflow_lib import configsection from wflow.wflow_lib import configget -class SoilAndTopoParameters(object): +class SoilAndTopoParameters(object): def __init__(self, iniItems, landmask, Dir, cloneMap, tmpDir): object.__init__(self) # cloneMap, tmpDir, inputDir based on the configuration/setting given in the ini/configuration file - self.cloneMap = cloneMap #iniItems.cloneMap - self.tmpDir = tmpDir #iniItems.tmpDir - self.inputDir = Dir #iniItems.globalOptions['inputDir'] + self.cloneMap = cloneMap # iniItems.cloneMap + self.tmpDir = tmpDir # iniItems.tmpDir + self.inputDir = Dir # iniItems.globalOptions['inputDir'] self.landmask = landmask - + # How many soil layers (excluding groundwater): - self.numberOfLayers = int(configget(iniItems,"landSurfaceOptions","numberOfUpperSoilLayers","2")) + self.numberOfLayers = int( + configget(iniItems, "landSurfaceOptions", "numberOfUpperSoilLayers", "2") + ) - def read(self, iniItems, optionDict = None): - + def read(self, iniItems, optionDict=None): + self.readTopo(iniItems, optionDict) self.readSoil(iniItems, optionDict) def readTopo(self, iniItems, optionDict): # a dictionary/section of options that will be used - if optionDict == None: optionDict = iniItems._sections["landSurfaceOptions"] + if optionDict == None: + optionDict = iniItems._sections["landSurfaceOptions"] - # maps of elevation attributes: - topoParams = ['tanslope','slopeLength','orographyBeta'] - if optionDict['topographyNC'] == str(None): + # maps of elevation attributes: + topoParams = ["tanslope", "slopeLength", "orographyBeta"] + if optionDict["topographyNC"] == str(None): for var in topoParams: - input = configget(iniItems,"landSurfaceOptions",str(var),"None") - vars(self)[var] = vos.readPCRmapClone(input,self.cloneMap, - self.tmpDir,self.inputDir) - if var != "slopeLength": vars(self)[var] = pcr.cover(vars(self)[var], 0.0) + input = configget(iniItems, "landSurfaceOptions", str(var), "None") + vars(self)[var] = vos.readPCRmapClone( + input, self.cloneMap, self.tmpDir, self.inputDir + ) + if var != "slopeLength": + vars(self)[var] = pcr.cover(vars(self)[var], 0.0) else: - topoPropertiesNC = vos.getFullPath(\ - optionDict['topographyNC'], - self.inputDir) + topoPropertiesNC = vos.getFullPath( + optionDict["topographyNC"], self.inputDir + ) for var in topoParams: - vars(self)[var] = vos.netcdf2PCRobjCloneWithoutTime(\ - topoPropertiesNC,var, \ - cloneMapFileName = self.cloneMap) - if var != "slopeLength": vars(self)[var] = pcr.cover(vars(self)[var], 0.0) + vars(self)[var] = vos.netcdf2PCRobjCloneWithoutTime( + topoPropertiesNC, var, cloneMapFileName=self.cloneMap + ) + if var != "slopeLength": + vars(self)[var] = pcr.cover(vars(self)[var], 0.0) - #~ self.tanslope = pcr.max(self.tanslope, 0.00001) # In principle, tanslope can be zero. Zero tanslope will provide zero TCL (no interflow) + # ~ self.tanslope = pcr.max(self.tanslope, 0.00001) # In principle, tanslope can be zero. Zero tanslope will provide zero TCL (no interflow) - # covering slopeLength with its maximum value + # covering slopeLength with its maximum value self.slopeLength = pcr.cover(self.slopeLength, pcr.mapmaximum(self.slopeLength)) - - # maps of relative elevation above flood plains - dzRel = ['dzRel0001','dzRel0005', - 'dzRel0010','dzRel0020','dzRel0030','dzRel0040','dzRel0050', - 'dzRel0060','dzRel0070','dzRel0080','dzRel0090','dzRel0100'] - if optionDict['topographyNC'] == str(None): + + # maps of relative elevation above flood plains + dzRel = [ + "dzRel0001", + "dzRel0005", + "dzRel0010", + "dzRel0020", + "dzRel0030", + "dzRel0040", + "dzRel0050", + "dzRel0060", + "dzRel0070", + "dzRel0080", + "dzRel0090", + "dzRel0100", + ] + if optionDict["topographyNC"] == str(None): for i in range(0, len(dzRel)): var = dzRel[i] input = optionDict[str(var)] - vars(self)[var] = vos.readPCRmapClone(input,self.cloneMap, - self.tmpDir,self.inputDir) + vars(self)[var] = vos.readPCRmapClone( + input, self.cloneMap, self.tmpDir, self.inputDir + ) vars(self)[var] = pcr.cover(vars(self)[var], 0.0) - if i > 0: vars(self)[var] = pcr.max(vars(self)[var], vars(self)[dzRel[i-1]]) + if i > 0: + vars(self)[var] = pcr.max(vars(self)[var], vars(self)[dzRel[i - 1]]) else: for i in range(0, len(dzRel)): var = dzRel[i] - vars(self)[var] = vos.netcdf2PCRobjCloneWithoutTime(\ - topoPropertiesNC,var, \ - cloneMapFileName = self.cloneMap) + vars(self)[var] = vos.netcdf2PCRobjCloneWithoutTime( + topoPropertiesNC, var, cloneMapFileName=self.cloneMap + ) vars(self)[var] = pcr.cover(vars(self)[var], 0.0) - if i > 0: vars(self)[var] = pcr.max(vars(self)[var], vars(self)[dzRel[i-1]]) + if i > 0: + vars(self)[var] = pcr.max(vars(self)[var], vars(self)[dzRel[i - 1]]) - def readSoilMapOfFAO(self, iniItems, optionDict = None): + def readSoilMapOfFAO(self, iniItems, optionDict=None): # a dictionary/section of options that will be used - if optionDict == None: optionDict = iniItems._sections["landSurfaceOptions"] #iniItems.landSurfaceOptions - + if optionDict == None: + optionDict = iniItems._sections[ + "landSurfaceOptions" + ] # iniItems.landSurfaceOptions + # soil variable names given either in the ini or netCDF file: - soilParameters = ['airEntryValue1','airEntryValue2', - 'poreSizeBeta1','poreSizeBeta2', - 'resVolWC1','resVolWC2', - 'satVolWC1','satVolWC2', - 'KSat1','KSat2', - 'percolationImp'] - if optionDict['soilPropertiesNC'] == str(None): + soilParameters = [ + "airEntryValue1", + "airEntryValue2", + "poreSizeBeta1", + "poreSizeBeta2", + "resVolWC1", + "resVolWC2", + "satVolWC1", + "satVolWC2", + "KSat1", + "KSat2", + "percolationImp", + ] + if optionDict["soilPropertiesNC"] == str(None): for var in soilParameters: input = optionDict[str(var)] - vars(self)[var] = \ - vos.readPCRmapClone(input,self.cloneMap,\ - self.tmpDir,self.inputDir) + vars(self)[var] = vos.readPCRmapClone( + input, self.cloneMap, self.tmpDir, self.inputDir + ) vars(self)[var] = pcr.scalar(vars(self)[var]) - if input == "percolationImp": vars(self)[var] = pcr.cover(vars(self)[var], 0.0) - - # extrapolation - # - TODO: Make a general extrapolation option as a function in the virtualOS.py - vars(self)[var] = pcr.cover(vars(self)[var], - pcr.windowaverage(vars(self)[var], 0.75)) - vars(self)[var] = pcr.cover(vars(self)[var], - pcr.windowaverage(vars(self)[var], 1.00)) - vars(self)[var] = pcr.cover(vars(self)[var], - pcr.windowaverage(vars(self)[var], 1.00)) - vars(self)[var] = pcr.cover(vars(self)[var], - pcr.windowaverage(vars(self)[var], 1.00)) - vars(self)[var] = pcr.cover(vars(self)[var], - pcr.windowaverage(vars(self)[var], 1.00)) - vars(self)[var] = pcr.cover(vars(self)[var], - pcr.windowaverage(vars(self)[var], 1.00)) + if input == "percolationImp": + vars(self)[var] = pcr.cover(vars(self)[var], 0.0) + + # extrapolation + # - TODO: Make a general extrapolation option as a function in the virtualOS.py + vars(self)[var] = pcr.cover( + vars(self)[var], pcr.windowaverage(vars(self)[var], 0.75) + ) + vars(self)[var] = pcr.cover( + vars(self)[var], pcr.windowaverage(vars(self)[var], 1.00) + ) + vars(self)[var] = pcr.cover( + vars(self)[var], pcr.windowaverage(vars(self)[var], 1.00) + ) + vars(self)[var] = pcr.cover( + vars(self)[var], pcr.windowaverage(vars(self)[var], 1.00) + ) + vars(self)[var] = pcr.cover( + vars(self)[var], pcr.windowaverage(vars(self)[var], 1.00) + ) + vars(self)[var] = pcr.cover( + vars(self)[var], pcr.windowaverage(vars(self)[var], 1.00) + ) vars(self)[var] = pcr.cover(vars(self)[var], 0.0) else: - soilPropertiesNC = vos.getFullPath(\ - optionDict['soilPropertiesNC'], - self.inputDir) + soilPropertiesNC = vos.getFullPath( + optionDict["soilPropertiesNC"], self.inputDir + ) for var in soilParameters: - vars(self)[var] = vos.netcdf2PCRobjCloneWithoutTime(\ - soilPropertiesNC,var, \ - cloneMapFileName = self.cloneMap) + vars(self)[var] = vos.netcdf2PCRobjCloneWithoutTime( + soilPropertiesNC, var, cloneMapFileName=self.cloneMap + ) - if var == "percolationImp": vars(self)[var] = pcr.cover(vars(self)[var], 0.0) + if var == "percolationImp": + vars(self)[var] = pcr.cover(vars(self)[var], 0.0) - # extrapolation - # - TODO: Make a general extrapolation option as a function in the virtualOS.py - vars(self)[var] = pcr.cover(vars(self)[var], - pcr.windowaverage(vars(self)[var], 0.75)) - vars(self)[var] = pcr.cover(vars(self)[var], - pcr.windowaverage(vars(self)[var], 1.00)) - vars(self)[var] = pcr.cover(vars(self)[var], - pcr.windowaverage(vars(self)[var], 1.00)) - vars(self)[var] = pcr.cover(vars(self)[var], - pcr.windowaverage(vars(self)[var], 1.00)) - vars(self)[var] = pcr.cover(vars(self)[var], - pcr.windowaverage(vars(self)[var], 1.00)) - vars(self)[var] = pcr.cover(vars(self)[var], - pcr.windowaverage(vars(self)[var], 1.00)) + # extrapolation + # - TODO: Make a general extrapolation option as a function in the virtualOS.py + vars(self)[var] = pcr.cover( + vars(self)[var], pcr.windowaverage(vars(self)[var], 0.75) + ) + vars(self)[var] = pcr.cover( + vars(self)[var], pcr.windowaverage(vars(self)[var], 1.00) + ) + vars(self)[var] = pcr.cover( + vars(self)[var], pcr.windowaverage(vars(self)[var], 1.00) + ) + vars(self)[var] = pcr.cover( + vars(self)[var], pcr.windowaverage(vars(self)[var], 1.00) + ) + vars(self)[var] = pcr.cover( + vars(self)[var], pcr.windowaverage(vars(self)[var], 1.00) + ) + vars(self)[var] = pcr.cover( + vars(self)[var], pcr.windowaverage(vars(self)[var], 1.00) + ) vars(self)[var] = pcr.cover(vars(self)[var], 0.01) - + # make sure that resVolWC1 <= satVolWC1 self.resVolWC1 = pcr.min(self.resVolWC1, self.satVolWC1) self.resVolWC2 = pcr.min(self.resVolWC2, self.satVolWC2) - + if self.numberOfLayers == 2: - self.satVolMoistContUpp = self.satVolWC1 # saturated volumetric moisture content (m3.m-3) + self.satVolMoistContUpp = ( + self.satVolWC1 + ) # saturated volumetric moisture content (m3.m-3) self.satVolMoistContLow = self.satVolWC2 - self.resVolMoistContUpp = self.resVolWC1 # residual volumetric moisture content (m3.m-3) + self.resVolMoistContUpp = ( + self.resVolWC1 + ) # residual volumetric moisture content (m3.m-3) self.resVolMoistContLow = self.resVolWC2 - self.airEntryValueUpp = self.airEntryValue1 # air entry value (m) according to soil water retention curve of Clapp & Hornberger (1978) - self.airEntryValueLow = self.airEntryValue2 - self.poreSizeBetaUpp = self.poreSizeBeta1 # pore size distribution parameter according to Clapp & Hornberger (1978) - self.poreSizeBetaLow = self.poreSizeBeta2 - self.kSatUpp = self.KSat1 # saturated hydraulic conductivity (m.day-1) - self.kSatLow = self.KSat2 + self.airEntryValueUpp = ( + self.airEntryValue1 + ) # air entry value (m) according to soil water retention curve of Clapp & Hornberger (1978) + self.airEntryValueLow = self.airEntryValue2 + self.poreSizeBetaUpp = ( + self.poreSizeBeta1 + ) # pore size distribution parameter according to Clapp & Hornberger (1978) + self.poreSizeBetaLow = self.poreSizeBeta2 + self.kSatUpp = self.KSat1 # saturated hydraulic conductivity (m.day-1) + self.kSatLow = self.KSat2 if self.numberOfLayers == 3: - self.satVolMoistContUpp000005 = self.satVolWC1 - self.satVolMoistContUpp005030 = self.satVolWC1 + self.satVolMoistContUpp000005 = self.satVolWC1 + self.satVolMoistContUpp005030 = self.satVolWC1 self.satVolMoistContLow030150 = self.satVolWC2 - self.resVolMoistContUpp000005 = self.resVolWC1 - self.resVolMoistContUpp005030 = self.resVolWC1 + self.resVolMoistContUpp000005 = self.resVolWC1 + self.resVolMoistContUpp005030 = self.resVolWC1 self.resVolMoistContLow030150 = self.resVolWC2 - self.airEntryValueUpp000005 = self.airEntryValue1 - self.airEntryValueUpp005030 = self.airEntryValue1 - self.airEntryValueLow030150 = self.airEntryValue2 - self.poreSizeBetaUpp000005 = self.poreSizeBeta1 - self.poreSizeBetaUpp005030 = self.poreSizeBeta1 - self.poreSizeBetaLow030150 = self.poreSizeBeta2 - self.kSatUpp000005 = self.KSat1 - self.kSatUpp005030 = self.KSat1 - self.kSatLow030150 = self.KSat2 + self.airEntryValueUpp000005 = self.airEntryValue1 + self.airEntryValueUpp005030 = self.airEntryValue1 + self.airEntryValueLow030150 = self.airEntryValue2 + self.poreSizeBetaUpp000005 = self.poreSizeBeta1 + self.poreSizeBetaUpp005030 = self.poreSizeBeta1 + self.poreSizeBetaLow030150 = self.poreSizeBeta2 + self.kSatUpp000005 = self.KSat1 + self.kSatUpp005030 = self.KSat1 + self.kSatLow030150 = self.KSat2 - self.percolationImp = pcr.cover(self.percolationImp, 0.0) # fractional area where percolation to groundwater store is impeded (dimensionless) + self.percolationImp = pcr.cover( + self.percolationImp, 0.0 + ) # fractional area where percolation to groundwater store is impeded (dimensionless) - # soil thickness and storage variable names + # soil thickness and storage variable names # as given either in the ini or netCDF file: - soilStorages = ['firstStorDepth', 'secondStorDepth', - 'soilWaterStorageCap1','soilWaterStorageCap2'] - if optionDict['soilPropertiesNC'] == str(None): + soilStorages = [ + "firstStorDepth", + "secondStorDepth", + "soilWaterStorageCap1", + "soilWaterStorageCap2", + ] + if optionDict["soilPropertiesNC"] == str(None): for var in soilStorages: input = optionDict[str(var)] - temp = str(var)+'Inp' - vars(self)[temp] = vos.readPCRmapClone(input,\ - self.cloneMap, - self.tmpDir,self.inputDir) + temp = str(var) + "Inp" + vars(self)[temp] = vos.readPCRmapClone( + input, self.cloneMap, self.tmpDir, self.inputDir + ) - # extrapolation - # - TODO: Make a general extrapolation option as a function in the virtualOS.py - vars(self)[temp] = pcr.cover(vars(self)[temp], - pcr.windowaverage(vars(self)[temp], 0.75)) - vars(self)[temp] = pcr.cover(vars(self)[temp], - pcr.windowaverage(vars(self)[temp], 1.05)) - vars(self)[temp] = pcr.cover(vars(self)[temp], - pcr.windowaverage(vars(self)[temp], 1.05)) - vars(self)[temp] = pcr.cover(vars(self)[temp], - pcr.windowaverage(vars(self)[temp], 1.05)) - vars(self)[temp] = pcr.cover(vars(self)[temp], - pcr.windowaverage(vars(self)[temp], 1.05)) - vars(self)[temp] = pcr.cover(vars(self)[temp], - pcr.windowaverage(vars(self)[temp], 1.05)) + # extrapolation + # - TODO: Make a general extrapolation option as a function in the virtualOS.py + vars(self)[temp] = pcr.cover( + vars(self)[temp], pcr.windowaverage(vars(self)[temp], 0.75) + ) + vars(self)[temp] = pcr.cover( + vars(self)[temp], pcr.windowaverage(vars(self)[temp], 1.05) + ) + vars(self)[temp] = pcr.cover( + vars(self)[temp], pcr.windowaverage(vars(self)[temp], 1.05) + ) + vars(self)[temp] = pcr.cover( + vars(self)[temp], pcr.windowaverage(vars(self)[temp], 1.05) + ) + vars(self)[temp] = pcr.cover( + vars(self)[temp], pcr.windowaverage(vars(self)[temp], 1.05) + ) + vars(self)[temp] = pcr.cover( + vars(self)[temp], pcr.windowaverage(vars(self)[temp], 1.05) + ) vars(self)[temp] = pcr.cover(vars(self)[temp], 0.0) else: - soilPropertiesNC = vos.getFullPath(\ - optionDict['soilPropertiesNC'], - self.inputDir) + soilPropertiesNC = vos.getFullPath( + optionDict["soilPropertiesNC"], self.inputDir + ) for var in soilStorages: - temp = str(var)+'Inp' - vars(self)[temp] = vos.netcdf2PCRobjCloneWithoutTime(\ - soilPropertiesNC,var, \ - cloneMapFileName = self.cloneMap) - # extrapolation - # - TODO: Make a general extrapolation option as a function in the virtualOS.py - vars(self)[temp] = pcr.cover(vars(self)[temp], - pcr.windowaverage(vars(self)[temp], 0.75)) - vars(self)[temp] = pcr.cover(vars(self)[temp], - pcr.windowaverage(vars(self)[temp], 1.05)) - vars(self)[temp] = pcr.cover(vars(self)[temp], - pcr.windowaverage(vars(self)[temp], 1.05)) - vars(self)[temp] = pcr.cover(vars(self)[temp], - pcr.windowaverage(vars(self)[temp], 1.05)) - vars(self)[temp] = pcr.cover(vars(self)[temp], - pcr.windowaverage(vars(self)[temp], 1.05)) - vars(self)[temp] = pcr.cover(vars(self)[temp], - pcr.windowaverage(vars(self)[temp], 1.05)) + temp = str(var) + "Inp" + vars(self)[temp] = vos.netcdf2PCRobjCloneWithoutTime( + soilPropertiesNC, var, cloneMapFileName=self.cloneMap + ) + # extrapolation + # - TODO: Make a general extrapolation option as a function in the virtualOS.py + vars(self)[temp] = pcr.cover( + vars(self)[temp], pcr.windowaverage(vars(self)[temp], 0.75) + ) + vars(self)[temp] = pcr.cover( + vars(self)[temp], pcr.windowaverage(vars(self)[temp], 1.05) + ) + vars(self)[temp] = pcr.cover( + vars(self)[temp], pcr.windowaverage(vars(self)[temp], 1.05) + ) + vars(self)[temp] = pcr.cover( + vars(self)[temp], pcr.windowaverage(vars(self)[temp], 1.05) + ) + vars(self)[temp] = pcr.cover( + vars(self)[temp], pcr.windowaverage(vars(self)[temp], 1.05) + ) + vars(self)[temp] = pcr.cover( + vars(self)[temp], pcr.windowaverage(vars(self)[temp], 1.05) + ) vars(self)[temp] = pcr.cover(vars(self)[temp], 0.0) # layer thickness if self.numberOfLayers == 2: - self.thickUpp = (0.30/0.30)*self.firstStorDepthInp - self.thickLow = (1.20/1.20)*self.secondStorDepthInp + self.thickUpp = (0.30 / 0.30) * self.firstStorDepthInp + self.thickLow = (1.20 / 1.20) * self.secondStorDepthInp if self.numberOfLayers == 3: - self.thickUpp000005 = (0.05/0.30)*self.firstStorDepthInp - self.thickUpp005030 = (0.25/0.30)*self.firstStorDepthInp - self.thickLow030150 = (1.20/1.20)*self.secondStorDepthInp + self.thickUpp000005 = (0.05 / 0.30) * self.firstStorDepthInp + self.thickUpp005030 = (0.25 / 0.30) * self.firstStorDepthInp + self.thickLow030150 = (1.20 / 1.20) * self.secondStorDepthInp # soil storage if self.numberOfLayers == 2: - #~ self.storCapUpp = (0.30/0.30)*self.soilWaterStorageCap1Inp - #~ self.storCapLow = (1.20/1.20)*self.soilWaterStorageCap2Inp # 22 Feb 2014: We can calculate this based on thickness and porosity. - self.storCapUpp = self.thickUpp * \ - (self.satVolMoistContUpp - self.resVolMoistContUpp) - self.storCapLow = self.thickLow * \ - (self.satVolMoistContLow - self.resVolMoistContLow) - self.rootZoneWaterStorageCap = self.storCapUpp + \ - self.storCapLow # This is called as WMAX in the original pcrcalc script. + # ~ self.storCapUpp = (0.30/0.30)*self.soilWaterStorageCap1Inp + # ~ self.storCapLow = (1.20/1.20)*self.soilWaterStorageCap2Inp # 22 Feb 2014: We can calculate this based on thickness and porosity. + self.storCapUpp = self.thickUpp * ( + self.satVolMoistContUpp - self.resVolMoistContUpp + ) + self.storCapLow = self.thickLow * ( + self.satVolMoistContLow - self.resVolMoistContLow + ) + self.rootZoneWaterStorageCap = ( + self.storCapUpp + self.storCapLow + ) # This is called as WMAX in the original pcrcalc script. if self.numberOfLayers == 3: - self.storCapUpp000005 = self.thickUpp000005 * \ - (self.satVolMoistContUpp000005 - self.resVolMoistContUpp000005) - self.storCapUpp005030 = self.thickUpp005030 * \ - (self.satVolMoistContUpp005030 - self.resVolMoistContUpp005030) - self.storCapLow030150 = self.thickLow030150 * \ - (self.satVolMoistContLow030150 - self.resVolMoistContLow030150) - self.rootZoneWaterStorageCap = self.storCapUpp000005 + \ - self.storCapUpp005030 + \ - self.storCapLow030150 + self.storCapUpp000005 = self.thickUpp000005 * ( + self.satVolMoistContUpp000005 - self.resVolMoistContUpp000005 + ) + self.storCapUpp005030 = self.thickUpp005030 * ( + self.satVolMoistContUpp005030 - self.resVolMoistContUpp005030 + ) + self.storCapLow030150 = self.thickLow030150 * ( + self.satVolMoistContLow030150 - self.resVolMoistContLow030150 + ) + self.rootZoneWaterStorageCap = ( + self.storCapUpp000005 + self.storCapUpp005030 + self.storCapLow030150 + ) - def readSoil(self, iniItems, optionDict = None): + def readSoil(self, iniItems, optionDict=None): # a dictionary/section of options that will be used - if optionDict == None: optionDict = iniItems._sections["landSurfaceOptions"] #iniItems.landSurfaceOptions + if optionDict == None: + optionDict = iniItems._sections[ + "landSurfaceOptions" + ] # iniItems.landSurfaceOptions # default values of soil parameters that are constant/uniform for the entire domain: - self.clappAddCoeff = pcr.scalar(3.0) # dimensionless - self.matricSuctionFC = pcr.scalar(1.0) # unit: m - #~ self.matricSuction50 = pcr.scalar(10./3.) # unit: m - self.matricSuction50 = pcr.scalar(3.33) # unit: m - self.matricSuctionWP = pcr.scalar(156.0) # unit: m - self.maxGWCapRise = pcr.scalar(5.0) # unit: m - # + self.clappAddCoeff = pcr.scalar(3.0) # dimensionless + self.matricSuctionFC = pcr.scalar(1.0) # unit: m + # ~ self.matricSuction50 = pcr.scalar(10./3.) # unit: m + self.matricSuction50 = pcr.scalar(3.33) # unit: m + self.matricSuctionWP = pcr.scalar(156.0) # unit: m + self.maxGWCapRise = pcr.scalar(5.0) # unit: m + # # values defined in the ini/configuration file: - soilParameterConstants = ['clappAddCoeff', - 'matricSuctionFC', - 'matricSuction50', - 'matricSuctionWP', - 'maxGWCapRise'] + soilParameterConstants = [ + "clappAddCoeff", + "matricSuctionFC", + "matricSuction50", + "matricSuctionWP", + "maxGWCapRise", + ] for var in soilParameterConstants: - if var in configsection(iniItems,"landSurfaceOptions"): - input = configget(iniItems,"landSurfaceOptions",str(var),"None") - vars(self)[var] = vos.readPCRmapClone(input,self.cloneMap,\ - self.tmpDir,self.inputDir) - + if var in configsection(iniItems, "landSurfaceOptions"): + input = configget(iniItems, "landSurfaceOptions", str(var), "None") + vars(self)[var] = vos.readPCRmapClone( + input, self.cloneMap, self.tmpDir, self.inputDir + ) + # read soil parameter based on the FAO soil map: - self.readSoilMapOfFAO(iniItems, optionDict) - - # assign Campbell's (1974) beta coefficient, as well as degree + self.readSoilMapOfFAO(iniItems, optionDict) + + # assign Campbell's (1974) beta coefficient, as well as degree # of saturation at field capacity and corresponding unsaturated hydraulic conductivity # if self.numberOfLayers == 2: - self.campbellBetaUpp = self.poreSizeBetaUpp*2.0 + \ - self.clappAddCoeff # Campbell's (1974) coefficient ; Rens's line: BCB = 2*BCH + BCH_ADD - self.campbellBetaLow = self.poreSizeBetaLow*2.0 + \ - self.clappAddCoeff + self.campbellBetaUpp = ( + self.poreSizeBetaUpp * 2.0 + self.clappAddCoeff + ) # Campbell's (1974) coefficient ; Rens's line: BCB = 2*BCH + BCH_ADD + self.campbellBetaLow = self.poreSizeBetaLow * 2.0 + self.clappAddCoeff - self.effSatAtFieldCapUpp = \ - (self.matricSuctionFC / self.airEntryValueUpp)**\ - (-1.0/ self.poreSizeBetaUpp ) # saturation degree at field capacity : THEFF_FC = (PSI_FC/PSI_A)**(-1/BCH) + self.effSatAtFieldCapUpp = ( + self.matricSuctionFC / self.airEntryValueUpp + ) ** ( + -1.0 / self.poreSizeBetaUpp + ) # saturation degree at field capacity : THEFF_FC = (PSI_FC/PSI_A)**(-1/BCH) self.effSatAtFieldCapUpp = pcr.cover(self.effSatAtFieldCapUpp, 1.0) - - self.effSatAtFieldCapLow = \ - (self.matricSuctionFC / self.airEntryValueLow)**\ - (-1.0/ self.poreSizeBetaLow ) + + self.effSatAtFieldCapLow = ( + self.matricSuctionFC / self.airEntryValueLow + ) ** (-1.0 / self.poreSizeBetaLow) self.effSatAtFieldCapLow = pcr.cover(self.effSatAtFieldCapLow, 1.0) - self.kUnsatAtFieldCapUpp = pcr.max(0., \ - (self.effSatAtFieldCapUpp ** self.campbellBetaUpp) * self.kSatUpp) # unsaturated conductivity at field capacity: KTHEFF_FC = max(0,THEFF_FC[TYPE]**BCB*KS1) - self.kUnsatAtFieldCapLow = pcr.max(0., \ - (self.effSatAtFieldCapLow ** self.campbellBetaLow) * self.kSatLow) + self.kUnsatAtFieldCapUpp = pcr.max( + 0., (self.effSatAtFieldCapUpp ** self.campbellBetaUpp) * self.kSatUpp + ) # unsaturated conductivity at field capacity: KTHEFF_FC = max(0,THEFF_FC[TYPE]**BCB*KS1) + self.kUnsatAtFieldCapLow = pcr.max( + 0., (self.effSatAtFieldCapLow ** self.campbellBetaLow) * self.kSatLow + ) # if self.numberOfLayers == 3: - self.campbellBetaUpp000005 = self.poreSizeBetaUpp000005*2.0 + \ - self.clappAddCoeff - self.campbellBetaUpp005030 = self.poreSizeBetaUpp005030*2.0 + \ - self.clappAddCoeff - self.campbellBetaLow030150 = self.poreSizeBetaLow030150*2.0 + \ - self.clappAddCoeff + self.campbellBetaUpp000005 = ( + self.poreSizeBetaUpp000005 * 2.0 + self.clappAddCoeff + ) + self.campbellBetaUpp005030 = ( + self.poreSizeBetaUpp005030 * 2.0 + self.clappAddCoeff + ) + self.campbellBetaLow030150 = ( + self.poreSizeBetaLow030150 * 2.0 + self.clappAddCoeff + ) - self.effSatAtFieldCapUpp000005 = \ - (self.matricSuctionFC / self.airEntryValueUpp000005)**\ - (-1.0/ self.poreSizeBetaUpp000005) - self.effSatAtFieldCapUpp005030 = \ - (self.matricSuctionFC / self.airEntryValueUpp005030)**\ - (-1.0/ self.poreSizeBetaUpp005030) - self.effSatAtFieldCapLow030150 = \ - (self.matricSuctionFC / self.airEntryValueLow030150)**\ - (-1.0/ self.poreSizeBetaLow030150) + self.effSatAtFieldCapUpp000005 = ( + self.matricSuctionFC / self.airEntryValueUpp000005 + ) ** (-1.0 / self.poreSizeBetaUpp000005) + self.effSatAtFieldCapUpp005030 = ( + self.matricSuctionFC / self.airEntryValueUpp005030 + ) ** (-1.0 / self.poreSizeBetaUpp005030) + self.effSatAtFieldCapLow030150 = ( + self.matricSuctionFC / self.airEntryValueLow030150 + ) ** (-1.0 / self.poreSizeBetaLow030150) - self.kUnsatAtFieldCapUpp000005 = pcr.max(0., \ - (self.effSatAtFieldCapUpp000005 ** self.campbellBetaUpp000005) * self.kSatUpp000005) - self.kUnsatAtFieldCapUpp005030 = pcr.max(0., \ - (self.effSatAtFieldCapUpp005030 ** self.campbellBetaUpp005030) * self.kSatUpp005030) - self.kUnsatAtFieldCapLow030150 = pcr.max(0., \ - (self.effSatAtFieldCapLow030150 ** self.campbellBetaLow030150) * self.kSatLow030150) + self.kUnsatAtFieldCapUpp000005 = pcr.max( + 0., + (self.effSatAtFieldCapUpp000005 ** self.campbellBetaUpp000005) + * self.kSatUpp000005, + ) + self.kUnsatAtFieldCapUpp005030 = pcr.max( + 0., + (self.effSatAtFieldCapUpp005030 ** self.campbellBetaUpp005030) + * self.kSatUpp005030, + ) + self.kUnsatAtFieldCapLow030150 = pcr.max( + 0., + (self.effSatAtFieldCapLow030150 ** self.campbellBetaLow030150) + * self.kSatLow030150, + ) - # calculate degree of saturation at which transpiration is halved (50) + # calculate degree of saturation at which transpiration is halved (50) # and at wilting point # if self.numberOfLayers == 2: - self.effSatAt50Upp = (self.matricSuction50/self.airEntryValueUpp)**\ - (-1.0/self.poreSizeBetaUpp) - self.effSatAt50Upp = pcr.cover(self.effSatAt50Upp, 1.0) - self.effSatAt50Low = (self.matricSuction50/self.airEntryValueLow)**\ - (-1.0/self.poreSizeBetaLow) - self.effSatAt50Low = pcr.cover(self.effSatAt50Low, 1.0) - self.effSatAtWiltPointUpp = pcr.cover(\ - (self.matricSuctionWP/self.airEntryValueUpp)**\ - (-1.0/self.poreSizeBetaUpp), 1.0) - self.effSatAtWiltPointLow = pcr.cover(\ - (self.matricSuctionWP/self.airEntryValueLow)**\ - (-1.0/self.poreSizeBetaLow), 1.0) + self.effSatAt50Upp = (self.matricSuction50 / self.airEntryValueUpp) ** ( + -1.0 / self.poreSizeBetaUpp + ) + self.effSatAt50Upp = pcr.cover(self.effSatAt50Upp, 1.0) + self.effSatAt50Low = (self.matricSuction50 / self.airEntryValueLow) ** ( + -1.0 / self.poreSizeBetaLow + ) + self.effSatAt50Low = pcr.cover(self.effSatAt50Low, 1.0) + self.effSatAtWiltPointUpp = pcr.cover( + (self.matricSuctionWP / self.airEntryValueUpp) + ** (-1.0 / self.poreSizeBetaUpp), + 1.0, + ) + self.effSatAtWiltPointLow = pcr.cover( + (self.matricSuctionWP / self.airEntryValueLow) + ** (-1.0 / self.poreSizeBetaLow), + 1.0, + ) if self.numberOfLayers == 3: - self.effSatAt50Upp000005 = (self.matricSuction50/self.airEntryValueUpp000005)**\ - (-1.0/self.poreSizeBetaUpp000005) - self.effSatAt50Upp005030 = (self.matricSuction50/self.airEntryValueUpp005030)**\ - (-1.0/self.poreSizeBetaUpp005030) - self.effSatAt50Low030150 = (self.matricSuction50/self.airEntryValueLow030150)**\ - (-1.0/self.poreSizeBetaLow030150) - self.effSatAtWiltPointUpp000005 = \ - (self.matricSuctionWP/self.airEntryValueUpp000005)**\ - (-1.0/self.poreSizeBetaUpp000005) - self.effSatAtWiltPointUpp005030 = \ - (self.matricSuctionWP/self.airEntryValueUpp005030)**\ - (-1.0/self.poreSizeBetaUpp005030) - self.effSatAtWiltPointLow030150 = \ - (self.matricSuctionWP/self.airEntryValueLow030150)**\ - (-1.0/self.poreSizeBetaLow030150) + self.effSatAt50Upp000005 = ( + self.matricSuction50 / self.airEntryValueUpp000005 + ) ** (-1.0 / self.poreSizeBetaUpp000005) + self.effSatAt50Upp005030 = ( + self.matricSuction50 / self.airEntryValueUpp005030 + ) ** (-1.0 / self.poreSizeBetaUpp005030) + self.effSatAt50Low030150 = ( + self.matricSuction50 / self.airEntryValueLow030150 + ) ** (-1.0 / self.poreSizeBetaLow030150) + self.effSatAtWiltPointUpp000005 = ( + self.matricSuctionWP / self.airEntryValueUpp000005 + ) ** (-1.0 / self.poreSizeBetaUpp000005) + self.effSatAtWiltPointUpp005030 = ( + self.matricSuctionWP / self.airEntryValueUpp005030 + ) ** (-1.0 / self.poreSizeBetaUpp005030) + self.effSatAtWiltPointLow030150 = ( + self.matricSuctionWP / self.airEntryValueLow030150 + ) ** (-1.0 / self.poreSizeBetaLow030150) - # calculate interflow parameter (TCL): + # calculate interflow parameter (TCL): # if self.numberOfLayers == 2: - self.interflowConcTime = (self.kSatLow * self.tanslope*2.0) / \ - (self.slopeLength * (1.- self.effSatAtFieldCapLow) * \ - (self.satVolMoistContLow - self.resVolMoistContLow)) # TCL = Duration*(2*KS2*TANSLOPE)/(LSLOPE*(1-THEFF2_FC)*(THETASAT2-THETARES2)) + self.interflowConcTime = (self.kSatLow * self.tanslope * 2.0) / ( + self.slopeLength + * (1. - self.effSatAtFieldCapLow) + * (self.satVolMoistContLow - self.resVolMoistContLow) + ) # TCL = Duration*(2*KS2*TANSLOPE)/(LSLOPE*(1-THEFF2_FC)*(THETASAT2-THETARES2)) # if self.numberOfLayers == 3: - self.interflowConcTime = (self.kSatLow030150 * self.tanslope*2.0) / \ - (self.slopeLength * (1.-self.effSatAtFieldCapLow030150) * \ - (self.satVolMoistContLow030150 - self.resVolMoistContLow030150)) - - self.interflowConcTime = pcr.max(0.0, pcr.cover(self.interflowConcTime, 0.0)) + self.interflowConcTime = (self.kSatLow030150 * self.tanslope * 2.0) / ( + self.slopeLength + * (1. - self.effSatAtFieldCapLow030150) + * (self.satVolMoistContLow030150 - self.resVolMoistContLow030150) + ) + + self.interflowConcTime = pcr.max(0.0, pcr.cover(self.interflowConcTime, 0.0)) Index: wflow-py/wflow/pcrglobwb/routing.py =================================================================== diff -u -r2d84b2c3f986344e96a4fa357e54dd77fe817fe4 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/pcrglobwb/routing.py (.../routing.py) (revision 2d84b2c3f986344e96a4fa357e54dd77fe817fe4) +++ wflow-py/wflow/pcrglobwb/routing.py (.../routing.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -31,8 +31,9 @@ import pcraster as pcr import logging -logger = logging.getLogger('wflow_pcrglobwb') +logger = logging.getLogger("wflow_pcrglobwb") + import virtualOS as vos from ncConverter import * @@ -41,428 +42,640 @@ from wflow.wf_DynamicFramework import configsection from wflow.wf_DynamicFramework import configget + class Routing(object): - - #TODO: remove + + # TODO: remove def getPseudoState(self): result = {} return result - #TODO: remove + # TODO: remove def getVariables(self, names): result = {} return result def getState(self): result = {} - - result['timestepsToAvgDischarge'] = self.timestepsToAvgDischarge # day - result['channelStorage'] = self.channelStorage # m3 ; channel storage, including lake and reservoir storage - result['readAvlChannelStorage'] = self.readAvlChannelStorage # m3 ; readily available channel storage that can be extracted to satisfy water demand - result['avgDischargeLong'] = self.avgDischarge # m3/s ; long term average discharge - result['m2tDischargeLong'] = self.m2tDischarge # (m3/s)^2 - - result['avgBaseflowLong'] = self.avgBaseflow # m3/s ; long term average baseflow - result['riverbedExchange'] = self.riverbedExchange # m3/day : river bed infiltration (from surface water bdoies to groundwater) - - result['waterBodyStorage'] = self.waterBodyStorage # m3 ; storages of lakes and reservoirs # values given are per water body id (not per cell) - result['avgLakeReservoirOutflowLong'] = self.avgOutflow # m3/s ; long term average lake & reservoir outflow # values given are per water body id (not per cell) - result['avgLakeReservoirInflowShort'] = self.avgInflow # m3/s ; short term average lake & reservoir inflow # values given are per water body id (not per cell) + result["timestepsToAvgDischarge"] = self.timestepsToAvgDischarge # day - result['avgDischargeShort'] = self.avgDischargeShort # m3/s ; short term average discharge + result[ + "channelStorage" + ] = ( + self.channelStorage + ) # m3 ; channel storage, including lake and reservoir storage + result[ + "readAvlChannelStorage" + ] = ( + self.readAvlChannelStorage + ) # m3 ; readily available channel storage that can be extracted to satisfy water demand + result[ + "avgDischargeLong" + ] = self.avgDischarge # m3/s ; long term average discharge + result["m2tDischargeLong"] = self.m2tDischarge # (m3/s)^2 + result[ + "avgBaseflowLong" + ] = self.avgBaseflow # m3/s ; long term average baseflow + result[ + "riverbedExchange" + ] = ( + self.riverbedExchange + ) # m3/day : river bed infiltration (from surface water bdoies to groundwater) + + result[ + "waterBodyStorage" + ] = ( + self.waterBodyStorage + ) # m3 ; storages of lakes and reservoirs # values given are per water body id (not per cell) + result[ + "avgLakeReservoirOutflowLong" + ] = ( + self.avgOutflow + ) # m3/s ; long term average lake & reservoir outflow # values given are per water body id (not per cell) + result[ + "avgLakeReservoirInflowShort" + ] = ( + self.avgInflow + ) # m3/s ; short term average lake & reservoir inflow # values given are per water body id (not per cell) + + result[ + "avgDischargeShort" + ] = self.avgDischargeShort # m3/s ; short term average discharge + # This variable needed only for kinematic wave methods (i.e. kinematicWave and simplifiedKinematicWave) - result['subDischarge'] = self.subDischarge # m3/s ; sub-time step discharge (needed for kinematic wave methods/approaches) + result[ + "subDischarge" + ] = ( + self.subDischarge + ) # m3/s ; sub-time step discharge (needed for kinematic wave methods/approaches) return result - def __init__(self,iniItems,initialConditions,lddMap, Dir, staticmaps, cloneMap): + def __init__(self, iniItems, initialConditions, lddMap, Dir, staticmaps, cloneMap): object.__init__(self) self.lddMap = lddMap - self.cloneMap = cloneMap #iniItems.cloneMap - self.tmpDir = os.path.join(os.path.abspath(Dir),"tmp") #iniItems.tmpDir - self.inputDir = os.path.join(os.path.abspath(Dir),staticmaps) #iniItems.globalOptions['inputDir'] + self.cloneMap = cloneMap # iniItems.cloneMap + self.tmpDir = os.path.join(os.path.abspath(Dir), "tmp") # iniItems.tmpDir + self.inputDir = os.path.join( + os.path.abspath(Dir), staticmaps + ) # iniItems.globalOptions['inputDir'] - # option to activate water balance check self.debugWaterBalance = True - if configget(iniItems,"routingOptions","debugWaterBalance","True") == "False": + if ( + configget(iniItems, "routingOptions", "debugWaterBalance", "True") + == "False" + ): self.debugWaterBalance = False - self.method = iniItems.get("routingOptions","routingMethod") + self.method = iniItems.get("routingOptions", "routingMethod") - # option to include lakes and reservoirs + # option to include lakes and reservoirs self.includeWaterBodies = True - if 'includeWaterBodies' in iniItems._sections['routingOptions']: - if configget(iniItems,"routingOptions","includeWaterBodies","True") == "False" or\ - configget(iniItems,"routingOptions","includeWaterBodies","True") == "None": + if "includeWaterBodies" in iniItems._sections["routingOptions"]: + if ( + configget(iniItems, "routingOptions", "includeWaterBodies", "True") + == "False" + or configget(iniItems, "routingOptions", "includeWaterBodies", "True") + == "None" + ): self.includeWaterBodies = False # local drainage direction: - self.lddMap = vos.readPCRmapClone(iniItems.get("routingOptions","lddMap"), - self.cloneMap,self.tmpDir,self.inputDir,True) + self.lddMap = vos.readPCRmapClone( + iniItems.get("routingOptions", "lddMap"), + self.cloneMap, + self.tmpDir, + self.inputDir, + True, + ) self.lddMap = pcr.lddrepair(pcr.ldd(self.lddMap)) self.lddMap = pcr.lddrepair(self.lddMap) # landmask: - if configget(iniItems,"globalOptions","landmask","None") != "None": - self.landmask = vos.readPCRmapClone(\ - iniItems.get("globalOptions","landmask"), - self.cloneMap,self.tmpDir,self.inputDir) - else: - self.landmask = pcr.defined(self.lddMap) + if configget(iniItems, "globalOptions", "landmask", "None") != "None": + self.landmask = vos.readPCRmapClone( + iniItems.get("globalOptions", "landmask"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + else: + self.landmask = pcr.defined(self.lddMap) self.landmask = pcr.ifthen(pcr.defined(self.lddMap), self.landmask) - self.landmask = pcr.cover(self.landmask, pcr.boolean(0)) + self.landmask = pcr.cover(self.landmask, pcr.boolean(0)) - # ldd mask + # ldd mask self.lddMap = pcr.lddmask(self.lddMap, self.landmask) # cell area (unit: m2) - self.cellArea = vos.readPCRmapClone(\ - iniItems.get("routingOptions","cellAreaMap"), - self.cloneMap,self.tmpDir,self.inputDir) + self.cellArea = vos.readPCRmapClone( + iniItems.get("routingOptions", "cellAreaMap"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) # model resolution in arc-degree unit - self.cellSizeInArcDeg = vos.getMapAttributes(self.cloneMap,"cellsize") + self.cellSizeInArcDeg = vos.getMapAttributes(self.cloneMap, "cellsize") # maximum number of days (timesteps) to calculate long term average flow values (default: 5 years = 5 * 365 days = 1825) - self.maxTimestepsToAvgDischargeLong = 1825. + self.maxTimestepsToAvgDischargeLong = 1825. # maximum number of days (timesteps) to calculate short term average values (default: 1 month = 1 * 30 days = 30) - self.maxTimestepsToAvgDischargeShort = 30. + self.maxTimestepsToAvgDischargeShort = 30. - routingParameters = ['gradient','manningsN'] + routingParameters = ["gradient", "manningsN"] for var in routingParameters: - input = iniItems.get("routingOptions",str(var)) - vars(self)[var] = vos.readPCRmapClone(input,\ - self.cloneMap,self.tmpDir,self.inputDir) + input = iniItems.get("routingOptions", str(var)) + vars(self)[var] = vos.readPCRmapClone( + input, self.cloneMap, self.tmpDir, self.inputDir + ) - # parameters needed to estimate channel dimensions/parameters - # - used in the method/function 'getRoutingParamAvgDischarge' + # parameters needed to estimate channel dimensions/parameters + # - used in the method/function 'getRoutingParamAvgDischarge' self.eta = 0.25 - self.nu = 0.40 + self.nu = 0.40 self.tau = 8.00 self.phi = 0.58 # option to use minimum channel width (m) self.minChannelWidth = pcr.scalar(0.0) - if "minimumChannelWidth" in iniItems._sections['routingOptions']: - if configget(iniItems,"routingOptions","minimumChannelWidth","None") != "None":\ - self.minChannelWidth = pcr.cover(vos.readPCRmapClone(\ - iniItems.get("routingOptions","minimumChannelWidth"), - self.cloneMap,self.tmpDir,self.inputDir), 0.0) - + if "minimumChannelWidth" in iniItems._sections["routingOptions"]: + if ( + configget(iniItems, "routingOptions", "minimumChannelWidth", "None") + != "None" + ): + self.minChannelWidth = pcr.cover( + vos.readPCRmapClone( + iniItems.get("routingOptions", "minimumChannelWidth"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ), + 0.0, + ) + # option to use constant/pre-defined channel width (m) self.predefinedChannelWidth = None - if "constantChannelWidth" in iniItems._sections['routingOptions']: - if configget(iniItems,"routingOptions","constantChannelWidth","None") != "None":\ - self.predefinedChannelWidth = pcr.cover(vos.readPCRmapClone(\ - iniItems.get("routingOptions","constantChannelWidth"), - self.cloneMap,self.tmpDir,self.inputDir), 0.0) + if "constantChannelWidth" in iniItems._sections["routingOptions"]: + if ( + configget(iniItems, "routingOptions", "constantChannelWidth", "None") + != "None" + ): + self.predefinedChannelWidth = pcr.cover( + vos.readPCRmapClone( + iniItems.get("routingOptions", "constantChannelWidth"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ), + 0.0, + ) # option to use constant/pre-defined channel depth (m) self.predefinedChannelDepth = None - if "constantChannelDepth" in iniItems._sections['routingOptions']: - if configget(iniItems,"routingOptions","constantChannelDepth","None") != "None":\ - self.predefinedChannelDepth = pcr.cover(vos.readPCRmapClone(\ - iniItems.get("routingOptions","constantChannelDepth"), - self.cloneMap,self.tmpDir,self.inputDir), 0.0) - + if "constantChannelDepth" in iniItems._sections["routingOptions"]: + if ( + configget(iniItems, "routingOptions", "constantChannelDepth", "None") + != "None" + ): + self.predefinedChannelDepth = pcr.cover( + vos.readPCRmapClone( + iniItems.get("routingOptions", "constantChannelDepth"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ), + 0.0, + ) - # an assumption for broad sheet flow in kinematic wave methods/approaches - self.beta = 0.6 - + # an assumption for broad sheet flow in kinematic wave methods/approaches + self.beta = 0.6 + # channelLength = approximation of channel length (unit: m) - # This is approximated by cell diagonal. - cellSizeInArcMin = self.cellSizeInArcDeg*60. - verticalSizeInMeter = cellSizeInArcMin*1852. + # This is approximated by cell diagonal. + cellSizeInArcMin = self.cellSizeInArcDeg * 60. + verticalSizeInMeter = cellSizeInArcMin * 1852. # - self.cellLengthFD = ((self.cellArea/verticalSizeInMeter)**(2)+\ - (verticalSizeInMeter)**(2))**(0.5) + self.cellLengthFD = ( + (self.cellArea / verticalSizeInMeter) ** (2) + (verticalSizeInMeter) ** (2) + ) ** (0.5) self.channelLength = self.cellLengthFD - # - # channel length (unit: m) - if "channelLength" in iniItems._sections['routingOptions']: - if configget(iniItems,"routingOptions","channelLength","None") != "None":\ - self.channelLength = pcr.cover( - vos.readPCRmapClone(\ - iniItems.get("routingOptions","channelLength"), - self.cloneMap,self.tmpDir,self.inputDir), self.channelLength) - - # dist2celllength in m/arcDegree (needed in the accuTravelTime function): - nrCellsDownstream = pcr.ldddist(self.lddMap,\ - self.lddMap == 5,1.) - distanceDownstream = pcr.ldddist(self.lddMap,\ - self.lddMap == 5,\ - self.channelLength) - channelLengthDownstream = \ - (self.channelLength + distanceDownstream)/\ - (nrCellsDownstream + 1) # unit: m - self.dist2celllength = channelLengthDownstream /\ - self.cellSizeInArcDeg # unit: m/arcDegree + # + # channel length (unit: m) + if "channelLength" in iniItems._sections["routingOptions"]: + if configget(iniItems, "routingOptions", "channelLength", "None") != "None": + self.channelLength = pcr.cover( + vos.readPCRmapClone( + iniItems.get("routingOptions", "channelLength"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ), + self.channelLength, + ) - # the channel gradient must be >= minGradient - minGradient = 0.00005 # 0.000005 - self.gradient = pcr.max(minGradient,\ - pcr.cover(self.gradient, minGradient)) + # dist2celllength in m/arcDegree (needed in the accuTravelTime function): + nrCellsDownstream = pcr.ldddist(self.lddMap, self.lddMap == 5, 1.) + distanceDownstream = pcr.ldddist( + self.lddMap, self.lddMap == 5, self.channelLength + ) + channelLengthDownstream = (self.channelLength + distanceDownstream) / ( + nrCellsDownstream + 1 + ) # unit: m + self.dist2celllength = ( + channelLengthDownstream / self.cellSizeInArcDeg + ) # unit: m/arcDegree + # the channel gradient must be >= minGradient + minGradient = 0.00005 # 0.000005 + self.gradient = pcr.max(minGradient, pcr.cover(self.gradient, minGradient)) + # initiate/create WaterBody class - self.WaterBodies = waterBodies.WaterBodies(iniItems,self.landmask,self.inputDir,self.cloneMap,self.tmpDir) + self.WaterBodies = waterBodies.WaterBodies( + iniItems, self.landmask, self.inputDir, self.cloneMap, self.tmpDir + ) # crop evaporation coefficient for surface water bodies self.no_zero_crop_water_coefficient = True - if configget(iniItems,"routingOptions","cropCoefficientWaterNC","None") == "None": + if ( + configget(iniItems, "routingOptions", "cropCoefficientWaterNC", "None") + == "None" + ): self.no_zero_crop_water_coefficient = False else: - self.fileCropKC = vos.getFullPath(\ - iniItems.get("routingOptions","cropCoefficientWaterNC"),\ - self.inputDir) + self.fileCropKC = vos.getFullPath( + iniItems.get("routingOptions", "cropCoefficientWaterNC"), self.inputDir + ) # courantNumber criteria for numerical stability in kinematic wave methods/approaches self.courantNumber = 0.50 # empirical values for minimum number of sub-time steps: - design_flood_speed = 5.00 # m/s - design_length_of_sub_time_step = pcr.cellvalue( - pcr.mapminimum( - self.courantNumber * self.channelLength / design_flood_speed),1)[0] + design_flood_speed = 5.00 # m/s + design_length_of_sub_time_step = pcr.cellvalue( + pcr.mapminimum( + self.courantNumber * self.channelLength / design_flood_speed + ), + 1, + )[0] self.limit_num_of_sub_time_steps = np.ceil( - vos.secondsPerDay() / design_length_of_sub_time_step) + vos.secondsPerDay() / design_length_of_sub_time_step + ) # - # minimum number of sub-time steps: 24 ; hourly resolution as used in Van Beek et al. (2011) - self.limit_num_of_sub_time_steps = max(24.0, self.limit_num_of_sub_time_steps) - - # minimum number of a sub time step based on the configuration/ini file: - if 'maxiumLengthOfSubTimeStep' in iniItems._sections['routingOptions']: - maxiumLengthOfSubTimeStep = float(iniItems.get("routingOptions","maxiumLengthOfSubTimeStep")) - minimum_number_of_sub_time_step = np.ceil( - vos.secondsPerDay() / maxiumLengthOfSubTimeStep ) - self.limit_num_of_sub_time_steps = max(\ - minimum_number_of_sub_time_step, \ - self.limit_num_of_sub_time_steps) - # + # minimum number of sub-time steps: 24 ; hourly resolution as used in Van Beek et al. (2011) + self.limit_num_of_sub_time_steps = max(24.0, self.limit_num_of_sub_time_steps) + + # minimum number of a sub time step based on the configuration/ini file: + if "maxiumLengthOfSubTimeStep" in iniItems._sections["routingOptions"]: + maxiumLengthOfSubTimeStep = float( + iniItems.get("routingOptions", "maxiumLengthOfSubTimeStep") + ) + minimum_number_of_sub_time_step = np.ceil( + vos.secondsPerDay() / maxiumLengthOfSubTimeStep + ) + self.limit_num_of_sub_time_steps = max( + minimum_number_of_sub_time_step, self.limit_num_of_sub_time_steps + ) + # self.limit_num_of_sub_time_steps = np.int(self.limit_num_of_sub_time_steps) - + # critical water height (m) used to select stable length of sub time step in kinematic wave methods/approaches - self.critical_water_height = 0.25; # used in Van Beek et al. (2011) + self.critical_water_height = 0.25 + # used in Van Beek et al. (2011) # assumption for the minimum fracwat value used for calculating water height - self.min_fracwat_for_water_height = 0.001 # dimensionless - - # assumption for minimum crop coefficient for surface water bodies + self.min_fracwat_for_water_height = 0.001 # dimensionless + + # assumption for minimum crop coefficient for surface water bodies self.minCropWaterKC = 0.00 - if 'minCropWaterKC' in iniItems._sections['routingOptions']: - self.minCropWaterKC = float(iniItems.get("routingOptions","minCropWaterKC")) - + if "minCropWaterKC" in iniItems._sections["routingOptions"]: + self.minCropWaterKC = float( + iniItems.get("routingOptions", "minCropWaterKC") + ) + # get the initialConditions self.getICs(iniItems, initialConditions) - + # flood plain options: ################################################################################# - self.floodPlain = configget(iniItems,"routingOptions","dynamicFloodPlain","False") == "True" + self.floodPlain = ( + configget(iniItems, "routingOptions", "dynamicFloodPlain", "False") + == "True" + ) if self.floodPlain: logger.info("Flood plain extents can vary during the simulation.") - + # get ManningsN for the flood plain areas - input = iniItems.get("routingOptions","floodplainManningsN") - self.floodplainManN = vos.readPCRmapClone(input,\ - self.cloneMap, self.tmpDir, self.inputDir) + input = iniItems.get("routingOptions", "floodplainManningsN") + self.floodplainManN = vos.readPCRmapClone( + input, self.cloneMap, self.tmpDir, self.inputDir + ) # reduction parameter of smoothing interval and error threshold self.reductionKK = 0.5 - if 'reductionKK' in iniItems._sections['routingOptions']: - self.reductionKK= float(iniItems.get("routingOptions","reductionKK")) + if "reductionKK" in iniItems._sections["routingOptions"]: + self.reductionKK = float(iniItems.get("routingOptions", "reductionKK")) self.criterionKK = 40.0 - if 'criterionKK' in iniItems._sections['routingOptions']: - self.criterionKK= float(iniItems.get("routingOptions","criterionKK")) + if "criterionKK" in iniItems._sections["routingOptions"]: + self.criterionKK = float(iniItems.get("routingOptions", "criterionKK")) # get relative elevation (above floodplain) profile per grid cell (including smoothing parameters) - self.nrZLevels, self.areaFractions, self.relZ, self.floodVolume, self.kSlope, self.mInterval = \ - self.getElevationProfile(iniItems) + self.nrZLevels, self.areaFractions, self.relZ, self.floodVolume, self.kSlope, self.mInterval = self.getElevationProfile( + iniItems + ) # get bankfull capacity (unit: m3) self.predefinedBankfullCapacity = None self.usingFixedBankfullCapacity = False - if configget(iniItems,"routingOptions","bankfullCapacity","None") != "None" : - + if ( + configget(iniItems, "routingOptions", "bankfullCapacity", "None") + != "None" + ): + self.usingFixedBankfullCapacity = True - self.predefinedBankfullCapacity = vos.readPCRmapClone(iniItems.get("routingOptions","bankfullCapacity"),\ - self.cloneMap, self.tmpDir, self.inputDir) - else: + self.predefinedBankfullCapacity = vos.readPCRmapClone( + iniItems.get("routingOptions", "bankfullCapacity"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + else: msg = "The bankfull channel storage capacity is NOT defined in the configuration file. " - - if isinstance(self.predefinedChannelWidth, types.NoneType) or\ - isinstance(self.predefinedChannelDepth, types.NoneType): - + + if isinstance( + self.predefinedChannelWidth, types.NoneType + ) or isinstance(self.predefinedChannelDepth, types.NoneType): + msg += "The bankfull capacity is estimated from average discharge (5 year long term average)." else: msg += "The bankfull capacity is estimated from the given channel depth and channel width." self.usingFixedBankfullCapacity = True - self.predefinedBankfullCapacity = self.estimateBankfullCapacity(self.predefinedChannelWidth,\ - self.predefinedChannelDepth) - + self.predefinedBankfullCapacity = self.estimateBankfullCapacity( + self.predefinedChannelWidth, self.predefinedChannelDepth + ) + logger.info(msg) - + # covering the value - self.predefinedBankfullCapacity = pcr.cover(self.predefinedBankfullCapacity, 0.0) + self.predefinedBankfullCapacity = pcr.cover( + self.predefinedBankfullCapacity, 0.0 + ) # zero fracwat assumption (used for debugging to the version 1) self.zeroFracWatAllAndAlways = False - if configget(iniItems,"globalOptions","debug_to_version_one","False"): self.zeroFracWatAllAndAlways = True - - # initiate old style reporting # This is still very useful during the 'debugging' process. + if configget(iniItems, "globalOptions", "debug_to_version_one", "False"): + self.zeroFracWatAllAndAlways = True + + # initiate old style reporting # This is still very useful during the 'debugging' process. self.initiate_old_style_routing_reporting(iniItems) - def getICs(self,iniItems,iniConditions = None): + def getICs(self, iniItems, iniConditions=None): if iniConditions == None: # read initial conditions from pcraster maps listed in the ini file (for the first time step of the model; when the model just starts) - - self.timestepsToAvgDischarge = vos.readPCRmapClone(iniItems.get("routingOptions","timestepsToAvgDischargeIni") ,self.cloneMap,self.tmpDir,self.inputDir) - - self.channelStorage = vos.readPCRmapClone(iniItems.get("routingOptions","channelStorageIni") ,self.cloneMap,self.tmpDir,self.inputDir) - self.readAvlChannelStorage = vos.readPCRmapClone(iniItems.get("routingOptions","readAvlChannelStorageIni") ,self.cloneMap,self.tmpDir,self.inputDir) - self.avgDischarge = vos.readPCRmapClone(iniItems.get("routingOptions","avgDischargeLongIni") ,self.cloneMap,self.tmpDir,self.inputDir) - self.m2tDischarge = vos.readPCRmapClone(iniItems.get("routingOptions","m2tDischargeLongIni") ,self.cloneMap,self.tmpDir,self.inputDir) - self.avgBaseflow = vos.readPCRmapClone(iniItems.get("routingOptions","avgBaseflowLongIni") ,self.cloneMap,self.tmpDir,self.inputDir) - self.riverbedExchange = vos.readPCRmapClone(iniItems.get("routingOptions","riverbedExchangeIni") ,self.cloneMap,self.tmpDir,self.inputDir) - - # New initial condition variable introduced in the version 2.0.2: avgDischargeShort - self.avgDischargeShort = vos.readPCRmapClone(iniItems.get("routingOptions","avgDischargeShortIni") ,self.cloneMap,self.tmpDir,self.inputDir) + self.timestepsToAvgDischarge = vos.readPCRmapClone( + iniItems.get("routingOptions", "timestepsToAvgDischargeIni"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + + self.channelStorage = vos.readPCRmapClone( + iniItems.get("routingOptions", "channelStorageIni"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.readAvlChannelStorage = vos.readPCRmapClone( + iniItems.get("routingOptions", "readAvlChannelStorageIni"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.avgDischarge = vos.readPCRmapClone( + iniItems.get("routingOptions", "avgDischargeLongIni"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.m2tDischarge = vos.readPCRmapClone( + iniItems.get("routingOptions", "m2tDischargeLongIni"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.avgBaseflow = vos.readPCRmapClone( + iniItems.get("routingOptions", "avgBaseflowLongIni"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.riverbedExchange = vos.readPCRmapClone( + iniItems.get("routingOptions", "riverbedExchangeIni"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + + # New initial condition variable introduced in the version 2.0.2: avgDischargeShort + self.avgDischargeShort = vos.readPCRmapClone( + iniItems.get("routingOptions", "avgDischargeShortIni"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + # Initial conditions needed for kinematic wave methods - self.subDischarge = vos.readPCRmapClone(configget(iniItems,"routingOptions","subDischargeIni","0.0"),self.cloneMap,self.tmpDir,self.inputDir) + self.subDischarge = vos.readPCRmapClone( + configget(iniItems, "routingOptions", "subDischargeIni", "0.0"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) - else: + else: # read initial conditions from the memory - self.timestepsToAvgDischarge = iniConditions['routing']['timestepsToAvgDischarge'] - - self.channelStorage = iniConditions['routing']['channelStorage'] - self.readAvlChannelStorage = iniConditions['routing']['readAvlChannelStorage'] - self.avgDischarge = iniConditions['routing']['avgDischargeLong'] - self.m2tDischarge = iniConditions['routing']['m2tDischargeLong'] - self.avgBaseflow = iniConditions['routing']['avgBaseflowLong'] - self.riverbedExchange = iniConditions['routing']['riverbedExchange'] - self.avgDischargeShort = iniConditions['routing']['avgDischargeShort'] - - self.subDischarge = iniConditions['routing']['subDischarge'] - - self.channelStorage = pcr.ifthen(self.landmask, pcr.cover(self.channelStorage, 0.0)) - self.readAvlChannelStorage = pcr.ifthen(self.landmask, pcr.cover(self.readAvlChannelStorage, 0.0)) - self.avgDischarge = pcr.ifthen(self.landmask, pcr.cover(self.avgDischarge, 0.0)) - self.m2tDischarge = pcr.ifthen(self.landmask, pcr.cover(self.m2tDischarge, 0.0)) - self.avgDischargeShort = pcr.ifthen(self.landmask, pcr.cover(self.avgDischargeShort, 0.0)) - self.avgBaseflow = pcr.ifthen(self.landmask, pcr.cover(self.avgBaseflow, 0.0)) - self.riverbedExchange = pcr.ifthen(self.landmask, pcr.cover(self.riverbedExchange, 0.0)) - self.subDischarge = pcr.ifthen(self.landmask, pcr.cover(self.subDischarge , 0.0)) + self.timestepsToAvgDischarge = iniConditions["routing"][ + "timestepsToAvgDischarge" + ] - self.readAvlChannelStorage = pcr.min(self.readAvlChannelStorage, self.channelStorage) + self.channelStorage = iniConditions["routing"]["channelStorage"] + self.readAvlChannelStorage = iniConditions["routing"][ + "readAvlChannelStorage" + ] + self.avgDischarge = iniConditions["routing"]["avgDischargeLong"] + self.m2tDischarge = iniConditions["routing"]["m2tDischargeLong"] + self.avgBaseflow = iniConditions["routing"]["avgBaseflowLong"] + self.riverbedExchange = iniConditions["routing"]["riverbedExchange"] + self.avgDischargeShort = iniConditions["routing"]["avgDischargeShort"] + + self.subDischarge = iniConditions["routing"]["subDischarge"] + + self.channelStorage = pcr.ifthen( + self.landmask, pcr.cover(self.channelStorage, 0.0) + ) + self.readAvlChannelStorage = pcr.ifthen( + self.landmask, pcr.cover(self.readAvlChannelStorage, 0.0) + ) + self.avgDischarge = pcr.ifthen(self.landmask, pcr.cover(self.avgDischarge, 0.0)) + self.m2tDischarge = pcr.ifthen(self.landmask, pcr.cover(self.m2tDischarge, 0.0)) + self.avgDischargeShort = pcr.ifthen( + self.landmask, pcr.cover(self.avgDischargeShort, 0.0) + ) + self.avgBaseflow = pcr.ifthen(self.landmask, pcr.cover(self.avgBaseflow, 0.0)) + self.riverbedExchange = pcr.ifthen( + self.landmask, pcr.cover(self.riverbedExchange, 0.0) + ) + self.subDischarge = pcr.ifthen(self.landmask, pcr.cover(self.subDischarge, 0.0)) + + self.readAvlChannelStorage = pcr.min( + self.readAvlChannelStorage, self.channelStorage + ) self.readAvlChannelStorage = pcr.max(self.readAvlChannelStorage, 0.0) # make sure that timestepsToAvgDischarge is consistent (or the same) for the entire map: try: self.timestepsToAvgDischarge = pcr.mapmaximum(self.timestepsToAvgDischarge) - except: - pass # We have to use 'try/except' because 'pcr.mapmaximum' cannot handle scalar value + except: + pass # We have to use 'try/except' because 'pcr.mapmaximum' cannot handle scalar value # for netcdf reporting, we have to make sure that timestepsToAvgDischarge is spatial and scalar (especially while performing pcr2numpy operations) - self.timestepsToAvgDischarge = pcr.spatial(pcr.scalar(self.timestepsToAvgDischarge)) - self.timestepsToAvgDischarge = pcr.ifthen(self.landmask, self.timestepsToAvgDischarge) + self.timestepsToAvgDischarge = pcr.spatial( + pcr.scalar(self.timestepsToAvgDischarge) + ) + self.timestepsToAvgDischarge = pcr.ifthen( + self.landmask, self.timestepsToAvgDischarge + ) # Initial conditions needed for water bodies: - # - initial short term average inflow (m3/s) and + # - initial short term average inflow (m3/s) and # long term average outflow (m3/s) if iniConditions == None: # read initial conditions from pcraster maps listed in the ini file (for the first time step of the model; when the model just starts) - self.avgInflow = vos.readPCRmapClone(configget(iniItems,"routingOptions","avgLakeReservoirInflowShortIni","0,0"),self.cloneMap,self.tmpDir,self.inputDir) - self.avgOutflow = vos.readPCRmapClone(configget(iniItems,"routingOptions","avgLakeReservoirOutflowLongIni","0.0"),self.cloneMap,self.tmpDir,self.inputDir) - if configget(iniItems,"routingOptions","waterBodyStorageIni","None") != "None": - self.waterBodyStorage = vos.readPCRmapClone(iniItems.get("routingOptions","waterBodyStorageIni"), self.cloneMap,self.tmpDir,self.inputDir) - self.waterBodyStorage = pcr.ifthen(self.landmask, pcr.cover(self.waterBodyStorage, 0.0)) + self.avgInflow = vos.readPCRmapClone( + configget( + iniItems, "routingOptions", "avgLakeReservoirInflowShortIni", "0,0" + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.avgOutflow = vos.readPCRmapClone( + configget( + iniItems, "routingOptions", "avgLakeReservoirOutflowLongIni", "0.0" + ), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + if ( + configget(iniItems, "routingOptions", "waterBodyStorageIni", "None") + != "None" + ): + self.waterBodyStorage = vos.readPCRmapClone( + iniItems.get("routingOptions", "waterBodyStorageIni"), + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.waterBodyStorage = pcr.ifthen( + self.landmask, pcr.cover(self.waterBodyStorage, 0.0) + ) else: self.waterBodyStorage = None else: # read initial conditions from the memory - self.avgInflow = iniConditions['routing']['avgLakeReservoirInflowShort'] - self.avgOutflow = iniConditions['routing']['avgLakeReservoirOutflowLong'] - self.waterBodyStorage = iniConditions['routing']['waterBodyStorage'] + self.avgInflow = iniConditions["routing"]["avgLakeReservoirInflowShort"] + self.avgOutflow = iniConditions["routing"]["avgLakeReservoirOutflowLong"] + self.waterBodyStorage = iniConditions["routing"]["waterBodyStorage"] - - self.avgInflow = pcr.ifthen(self.landmask, pcr.cover(self.avgInflow , 0.0)) + self.avgInflow = pcr.ifthen(self.landmask, pcr.cover(self.avgInflow, 0.0)) self.avgOutflow = pcr.ifthen(self.landmask, pcr.cover(self.avgOutflow, 0.0)) if not isinstance(self.waterBodyStorage, types.NoneType): - self.waterBodyStorage = pcr.ifthen(self.landmask, pcr.cover(self.waterBodyStorage, 0.0)) + self.waterBodyStorage = pcr.ifthen( + self.landmask, pcr.cover(self.waterBodyStorage, 0.0) + ) + def estimateBankfullDischarge(self, bankfullWidth, factor=4.8): - def estimateBankfullDischarge(self, bankfullWidth, factor = 4.8): - # bankfull discharge (unit: m3/s) # - from Lacey formula: P = B = 4.8 * (Qbf)**0.5 - bankfullDischarge = (bankfullWidth / factor ) ** (2.0) - + bankfullDischarge = (bankfullWidth / factor) ** (2.0) + return bankfullDischarge def estimateBankfullDepth(self, bankfullDischarge): # bankfull depth (unit: m) - # - from the Manning formula - # - assuming rectangular channel - - bankfullDepth = self.manningsN * ((bankfullDischarge)**(0.50)) - bankfullDepth = bankfullDepth / (4.8 * ((self.gradient)**(0.50))) - bankfullDepth = bankfullDepth**(3.0/5.0) + # - from the Manning formula + # - assuming rectangular channel + bankfullDepth = self.manningsN * ((bankfullDischarge) ** (0.50)) + bankfullDepth = bankfullDepth / (4.8 * ((self.gradient) ** (0.50))) + bankfullDepth = bankfullDepth ** (3.0 / 5.0) + return bankfullDepth - def estimateBankfullCapacity(self, width, depth, minWidth = 5.0, minDepth = 1.0): + def estimateBankfullCapacity(self, width, depth, minWidth=5.0, minDepth=1.0): # bankfull capacity (unit: m3) - bankfullCapacity = pcr.max(minWidth, width) * \ - pcr.max(minDepth, depth) * \ - self.channelLength - - return bankfullCapacity + bankfullCapacity = ( + pcr.max(minWidth, width) * pcr.max(minDepth, depth) * self.channelLength + ) + return bankfullCapacity + def getElevationProfile(self, iniItems): # get the profile of relative elevation above the floodplain (per grid cell) # output: dictionaries kSlope, mInterval, relZ and floodVolume with the keys iCnt (index, dimensionless) # - nrZLevels : number of intervals/levels # - areaFractions (dimensionless) : percentage/fraction of flooded/innundated area - # - relZ (m) : relative elevation above floodplain - # - floodVolume (m3) : flood volume above the channel bankfull capacity + # - relZ (m) : relative elevation above floodplain + # - floodVolume (m3) : flood volume above the channel bankfull capacity # - kSlope (dimensionless) : slope used during the interpolation - # - mInterval (m3) : smoothing interval (used in the interpolation) - - msg = 'Get the profile of relative elevation (relZ, unit: m) !!!' + # - mInterval (m3) : smoothing interval (used in the interpolation) + + msg = "Get the profile of relative elevation (relZ, unit: m) !!!" logger.info(msg) - relativeElevationFileNC = None # TODO define relative elevation files in a netdf file. - if relativeElevationFileNC != None: - pass # TODO: using a netcdf file + relativeElevationFileNC = ( + None + ) # TODO define relative elevation files in a netdf file. + if relativeElevationFileNC != None: + pass # TODO: using a netcdf file - if relativeElevationFileNC == None: + if relativeElevationFileNC == None: - relZFileName = vos.getFullPath(iniItems.get("routingOptions","relativeElevationFiles"),\ - iniItems.get("globalOptions","inputDir")) + relZFileName = vos.getFullPath( + iniItems.get("routingOptions", "relativeElevationFiles"), + iniItems.get("globalOptions", "inputDir"), + ) - # a dictionary contains areaFractions (dimensionless): fractions of flooded/innundated areas - areaFractions = map(float, iniItems.get("routingOptions","relativeElevationLevels").split(',')) + # a dictionary contains areaFractions (dimensionless): fractions of flooded/innundated areas + areaFractions = map( + float, + iniItems.get("routingOptions", "relativeElevationLevels").split(","), + ) # number of levels/intervals - nrZLevels = len(areaFractions) - # - TODO: Read areaFractions and nrZLevels automatically. - + nrZLevels = len(areaFractions) + # - TODO: Read areaFractions and nrZLevels automatically. + ######################################################################################################## # # patch elevations: those that are part of sills are updated on the basis of the floodplain gradient @@ -471,89 +684,117 @@ relZ = [0.] * nrZLevels for iCnt in range(0, nrZLevels): - - if relativeElevationFileNC == None: - inputName = relZFileName %(areaFractions[iCnt] * 100) - relZ[iCnt] = vos.readPCRmapClone(inputName, - self.cloneMap, self.tmpDir, self.inputDir) - if relativeElevationFileNC != None: - pass # TODO: using a netcdf file + if relativeElevationFileNC == None: + inputName = relZFileName % (areaFractions[iCnt] * 100) + relZ[iCnt] = vos.readPCRmapClone( + inputName, self.cloneMap, self.tmpDir, self.inputDir + ) + if relativeElevationFileNC != None: + pass # TODO: using a netcdf file + # covering elevation values relZ[iCnt] = pcr.ifthen(self.landmask, pcr.cover(relZ[iCnt], 0.0)) # make sure that relZ[iCnt] >= relZ[iCnt-1] (added by Edwin) - if iCnt > 0: relZ[iCnt] = pcr.max(relZ[iCnt], relZ[iCnt-1]) - - # - minimum slope of floodplain - # being defined as the longest sill, - # first used to retrieve longest cumulative distance - deltaX = [self.cellArea**0.5] * nrZLevels + if iCnt > 0: + relZ[iCnt] = pcr.max(relZ[iCnt], relZ[iCnt - 1]) + + # - minimum slope of floodplain + # being defined as the longest sill, + # first used to retrieve longest cumulative distance + deltaX = [self.cellArea ** 0.5] * nrZLevels deltaX[0] = 0.0 sumX = deltaX[:] minSlope = 0.0 for iCnt in range(nrZLevels): - if iCnt < nrZLevels-1: - deltaX[iCnt] = (areaFractions[iCnt+1]**0.5 - areaFractions[iCnt]**0.5) * deltaX[iCnt] + if iCnt < nrZLevels - 1: + deltaX[iCnt] = ( + areaFractions[iCnt + 1] ** 0.5 - areaFractions[iCnt] ** 0.5 + ) * deltaX[iCnt] else: - deltaX[iCnt] = (1.0 - areaFractions[iCnt-1]**0.5)*deltaX[iCnt] + deltaX[iCnt] = (1.0 - areaFractions[iCnt - 1] ** 0.5) * deltaX[iCnt] if iCnt > 0: - sumX[iCnt] = pcr.ifthenelse(relZ[iCnt] == relZ[iCnt-1], sumX[iCnt-1] + deltaX[iCnt], 0.0) - minSlope = pcr.ifthenelse(relZ[iCnt] == relZ[iCnt-1], pcr.max( sumX[iCnt], minSlope), minSlope) + sumX[iCnt] = pcr.ifthenelse( + relZ[iCnt] == relZ[iCnt - 1], sumX[iCnt - 1] + deltaX[iCnt], 0.0 + ) + minSlope = pcr.ifthenelse( + relZ[iCnt] == relZ[iCnt - 1], + pcr.max(sumX[iCnt], minSlope), + minSlope, + ) # - the maximum value for the floodplain slope is channel gradient (flow velocity is slower in the floodplain) - minSlope = pcr.min(self.gradient, 0.5* pcr.max(deltaX[1], minSlope)**-1.) - + minSlope = pcr.min(self.gradient, 0.5 * pcr.max(deltaX[1], minSlope) ** -1.) + # - add small increment to elevations to each sill (except in the case of lakes, #TODO: verify this) for iCnt in range(nrZLevels): - relZ[iCnt] = relZ[iCnt] + sumX[iCnt] * pcr.ifthenelse(relZ[nrZLevels-1] > 0., minSlope, 0.0) + relZ[iCnt] = relZ[iCnt] + sumX[iCnt] * pcr.ifthenelse( + relZ[nrZLevels - 1] > 0., minSlope, 0.0 + ) # make sure that relZ[iCnt] >= relZ[iCnt-1] (added by Edwin) - if iCnt > 0: relZ[iCnt] = pcr.max(relZ[iCnt], relZ[iCnt-1]) + if iCnt > 0: + relZ[iCnt] = pcr.max(relZ[iCnt], relZ[iCnt - 1]) # ######################################################################################################## - ######################################################################################################## # - set slope and smoothing interval between dy= y(i+1)-y(i) and dx= x(i+1)-x(i) # on the basis of volume # - floodVolume = [0.] * (nrZLevels) # volume (unit: m3) - mInterval = [0.] * (nrZLevels) # smoothing interval (unit: m3) - kSlope = [0.] * (nrZLevels) # slope (dimensionless) + floodVolume = [0.] * (nrZLevels) # volume (unit: m3) + mInterval = [0.] * (nrZLevels) # smoothing interval (unit: m3) + kSlope = [0.] * (nrZLevels) # slope (dimensionless) # for iCnt in range(1, nrZLevels): - floodVolume[iCnt] = floodVolume[iCnt-1] + \ - 0.5 * (areaFractions[iCnt] + areaFractions[iCnt-1]) * \ - (relZ[iCnt] - relZ[iCnt-1]) * self.cellArea - kSlope[iCnt-1] = (areaFractions[iCnt] - areaFractions[iCnt-1])/\ - pcr.max(0.001, floodVolume[iCnt] - floodVolume[iCnt-1]) + floodVolume[iCnt] = ( + floodVolume[iCnt - 1] + + 0.5 + * (areaFractions[iCnt] + areaFractions[iCnt - 1]) + * (relZ[iCnt] - relZ[iCnt - 1]) + * self.cellArea + ) + kSlope[iCnt - 1] = ( + areaFractions[iCnt] - areaFractions[iCnt - 1] + ) / pcr.max(0.001, floodVolume[iCnt] - floodVolume[iCnt - 1]) for iCnt in range(1, nrZLevels): - if iCnt < (nrZLevels-1): - mInterval[iCnt] = 0.5 * self.reductionKK * pcr.min(floodVolume[iCnt+1] - floodVolume[iCnt], \ - floodVolume[iCnt] - floodVolume[iCnt-1]) + if iCnt < (nrZLevels - 1): + mInterval[iCnt] = ( + 0.5 + * self.reductionKK + * pcr.min( + floodVolume[iCnt + 1] - floodVolume[iCnt], + floodVolume[iCnt] - floodVolume[iCnt - 1], + ) + ) else: - mInterval[iCnt] = 0.5 * self.reductionKK *(floodVolume[iCnt] - floodVolume[iCnt-1]) + mInterval[iCnt] = ( + 0.5 * self.reductionKK * (floodVolume[iCnt] - floodVolume[iCnt - 1]) + ) # ######################################################################################################## - + return nrZLevels, areaFractions, relZ, floodVolume, kSlope, mInterval - - def getRoutingParamAvgDischarge(self, avgDischarge, dist2celllength = None): + def getRoutingParamAvgDischarge(self, avgDischarge, dist2celllength=None): # obtain routing parameters based on average (longterm) discharge - # output: channel dimensions and + # output: channel dimensions and # characteristicDistance (for accuTravelTime input) - - yMean = self.eta * pow (avgDischarge, self.nu ) # avgDischarge in m3/s - wMean = self.tau * pow (avgDischarge, self.phi) - - wMean = pcr.max(wMean,0.01) # average flow width (m) - this could be used as an estimate of channel width (assuming rectangular channels) - wMean = pcr.cover(wMean,0.01) - yMean = pcr.max(yMean,0.01) # average flow depth (m) - this should NOT be used as an estimate of channel depth - yMean = pcr.cover(yMean,0.01) - + + yMean = self.eta * pow(avgDischarge, self.nu) # avgDischarge in m3/s + wMean = self.tau * pow(avgDischarge, self.phi) + + wMean = pcr.max( + wMean, 0.01 + ) # average flow width (m) - this could be used as an estimate of channel width (assuming rectangular channels) + wMean = pcr.cover(wMean, 0.01) + yMean = pcr.max( + yMean, 0.01 + ) # average flow depth (m) - this should NOT be used as an estimate of channel depth + yMean = pcr.cover(yMean, 0.01) + # option to use constant channel width (m) - if not isinstance(self.predefinedChannelWidth,types.NoneType):\ - wMean = pcr.cover(self.predefinedChannelWidth, wMean) + if not isinstance(self.predefinedChannelWidth, types.NoneType): + wMean = pcr.cover(self.predefinedChannelWidth, wMean) # # minimum channel width (m) wMean = pcr.max(self.minChannelWidth, wMean) @@ -565,245 +806,347 @@ # Manning's coefficient: usedManningsN = self.manningsN - # corrected Manning's coefficient: + # corrected Manning's coefficient: if self.floodPlain: # wetted perimeter - flood_only_wetted_perimeter = self.floodDepth * (2.0) + \ - pcr.max(0.0, self.innundatedFraction*self.cellArea/self.channelLength - self.channelWidth) - channel_only_wetted_perimeter = \ - pcr.min(self.channelDepth, vos.getValDivZero(self.channelStorage, self.channelLength*self.channelWidth, 0.0)) * 2.0 + \ - self.channelWidth + flood_only_wetted_perimeter = self.floodDepth * (2.0) + pcr.max( + 0.0, + self.innundatedFraction * self.cellArea / self.channelLength + - self.channelWidth, + ) + channel_only_wetted_perimeter = ( + pcr.min( + self.channelDepth, + vos.getValDivZero( + self.channelStorage, self.channelLength * self.channelWidth, 0.0 + ), + ) + * 2.0 + + self.channelWidth + ) # total channel wetted perimeter (unit: m) - channel_wetted_perimeter = channel_only_wetted_perimeter + \ - flood_only_wetted_perimeter + channel_wetted_perimeter = ( + channel_only_wetted_perimeter + flood_only_wetted_perimeter + ) # minimum channel wetted perimeter = 10 cm - channel_wetted_perimeter = pcr.max(0.1, channel_wetted_perimeter) + channel_wetted_perimeter = pcr.max(0.1, channel_wetted_perimeter) - usedManningsN = ((channel_only_wetted_perimeter/channel_wetted_perimeter) * self.manningsN**(1.5) + \ - ( flood_only_wetted_perimeter/channel_wetted_perimeter) * self.floodplainManN**(1.5))**(2./3.) - + usedManningsN = ( + (channel_only_wetted_perimeter / channel_wetted_perimeter) + * self.manningsN ** (1.5) + + (flood_only_wetted_perimeter / channel_wetted_perimeter) + * self.floodplainManN ** (1.5) + ) ** (2. / 3.) + # characteristicDistance (dimensionless) # - This will be used for accutraveltimeflux & accutraveltimestate # - discharge & storage = accutraveltimeflux & accutraveltimestate # - discharge = the total amount of material flowing through the cell (m3/s) # - storage = the amount of material which is deposited in the cell (m3) # - characteristicDistance = \ - ( (yMean * wMean)/ \ - (wMean + 2*yMean) )**(2./3.) * \ - ((self.gradient)**(0.5))/ \ - usedManningsN * \ - vos.secondsPerDay() # meter/day + characteristicDistance = ( + ((yMean * wMean) / (wMean + 2 * yMean)) ** (2. / 3.) + * ((self.gradient) ** (0.5)) + / usedManningsN + * vos.secondsPerDay() + ) # meter/day - characteristicDistance = \ - pcr.max((self.cellSizeInArcDeg)*0.000000001,\ - characteristicDistance/self.dist2celllength) # arcDeg/day - + characteristicDistance = pcr.max( + (self.cellSizeInArcDeg) * 0.000000001, + characteristicDistance / self.dist2celllength, + ) # arcDeg/day + # charateristicDistance for each lake/reservoir: - lakeReservoirCharacteristicDistance = pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0., - pcr.areaaverage(characteristicDistance, self.WaterBodies.waterBodyIds)) + lakeReservoirCharacteristicDistance = pcr.ifthen( + pcr.scalar(self.WaterBodies.waterBodyIds) > 0., + pcr.areaaverage(characteristicDistance, self.WaterBodies.waterBodyIds), + ) # # - make sure that all outflow will be released outside lakes and reservoirs - outlets = pcr.cover(pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyOut) > 0, pcr.boolean(1)), pcr.boolean(0)) - distance_to_outlets = pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0., - pcr.ldddist(self.lddMap, outlets, pcr.scalar(1.0))) - #~ lakeReservoirCharacteristicDistance = pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0., - #~ pcr.max(distance_to_outlets + pcr.downstreamdist(self.lddMap)*1.50, lakeReservoirCharacteristicDistance)) - lakeReservoirCharacteristicDistance = pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0., - pcr.max(distance_to_outlets + pcr.downstreamdist(self.lddMap)*2.50, lakeReservoirCharacteristicDistance)) - lakeReservoirCharacteristicDistance = pcr.areamaximum(lakeReservoirCharacteristicDistance, self.WaterBodies.waterBodyIds) + outlets = pcr.cover( + pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyOut) > 0, pcr.boolean(1)), + pcr.boolean(0), + ) + distance_to_outlets = pcr.ifthen( + pcr.scalar(self.WaterBodies.waterBodyIds) > 0., + pcr.ldddist(self.lddMap, outlets, pcr.scalar(1.0)), + ) + # ~ lakeReservoirCharacteristicDistance = pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0., + # ~ pcr.max(distance_to_outlets + pcr.downstreamdist(self.lddMap)*1.50, lakeReservoirCharacteristicDistance)) + lakeReservoirCharacteristicDistance = pcr.ifthen( + pcr.scalar(self.WaterBodies.waterBodyIds) > 0., + pcr.max( + distance_to_outlets + pcr.downstreamdist(self.lddMap) * 2.50, + lakeReservoirCharacteristicDistance, + ), + ) + lakeReservoirCharacteristicDistance = pcr.areamaximum( + lakeReservoirCharacteristicDistance, self.WaterBodies.waterBodyIds + ) # # TODO: calculate lakeReservoirCharacteristicDistance while obtaining lake & reservoir parameters - - characteristicDistance = pcr.cover(lakeReservoirCharacteristicDistance, characteristicDistance) - - # PS: In accutraveltime function: + + characteristicDistance = pcr.cover( + lakeReservoirCharacteristicDistance, characteristicDistance + ) + + # PS: In accutraveltime function: # If characteristicDistance (velocity) = 0 then: - # - accutraveltimestate will give zero - # - accutraveltimeflux will be very high - + # - accutraveltimestate will give zero + # - accutraveltimeflux will be very high + # TODO: Consider to use downstreamdist function. - - # current solution: using the function "roundup" to ignore - # zero and very small values - characteristicDistance = \ - pcr.roundup(characteristicDistance*100.)/100. # arcDeg/day - + + # current solution: using the function "roundup" to ignore + # zero and very small values + characteristicDistance = ( + pcr.roundup(characteristicDistance * 100.) / 100. + ) # arcDeg/day + # and set minimum value of characteristicDistance: - characteristicDistance = pcr.cover(characteristicDistance, 0.1*self.cellSizeInArcDeg) - characteristicDistance = pcr.max(0.100*self.cellSizeInArcDeg, characteristicDistance) # TODO: check what the minimum distance for accutraveltime function + characteristicDistance = pcr.cover( + characteristicDistance, 0.1 * self.cellSizeInArcDeg + ) + characteristicDistance = pcr.max( + 0.100 * self.cellSizeInArcDeg, characteristicDistance + ) # TODO: check what the minimum distance for accutraveltime function return characteristicDistance def accuTravelTime(self): - + # accuTravelTime ROUTING OPERATIONS ##############n############################################################################################################ # route only non negative channelStorage (otherwise stay): - channelStorageThatWillNotMove = pcr.ifthenelse(self.channelStorage < 0.0, self.channelStorage, 0.0) - self.channelStorage = pcr.max(0.0, self.channelStorage) - + channelStorageThatWillNotMove = pcr.ifthenelse( + self.channelStorage < 0.0, self.channelStorage, 0.0 + ) + self.channelStorage = pcr.max(0.0, self.channelStorage) + # also at least 1.0 m3 of water will stay - this is to minimize numerical errors due to float_32 pcraster implementations - channelStorageThatWillNotMove += self.channelStorage - pcr.rounddown(self.channelStorage) - self.channelStorage = pcr.rounddown(self.channelStorage) - + channelStorageThatWillNotMove += self.channelStorage - pcr.rounddown( + self.channelStorage + ) + self.channelStorage = pcr.rounddown(self.channelStorage) + # channelStorage that will be given to the ROUTING operation: channelStorageForAccuTravelTime = pcr.max(0.0, self.channelStorage) - channelStorageForAccuTravelTime = pcr.cover(channelStorageForAccuTravelTime,0.0) # TODO: check why do we have to use the "cover" operation? + channelStorageForAccuTravelTime = pcr.cover( + channelStorageForAccuTravelTime, 0.0 + ) # TODO: check why do we have to use the "cover" operation? characteristicDistance = self.getCharacteristicDistance(self.yMean, self.wMean) # estimating channel discharge (m3/day) - self.Q = pcr.accutraveltimeflux(self.lddMap,\ - channelStorageForAccuTravelTime,\ - pcr.max(0.0, characteristicDistance)) + self.Q = pcr.accutraveltimeflux( + self.lddMap, + channelStorageForAccuTravelTime, + pcr.max(0.0, characteristicDistance), + ) self.Q = pcr.cover(self.Q, 0.0) # for very small velocity (i.e. characteristicDistanceForAccuTravelTime), discharge can be missing value. # see: http://sourceforge.net/p/pcraster/bugs-and-feature-requests/543/ # http://karssenberg.geo.uu.nl/tt/TravelTimeSpecification.htm # # and make sure that no negative discharge - self.Q = pcr.max(0.0, self.Q) # unit: m3/day + self.Q = pcr.max(0.0, self.Q) # unit: m3/day # updating channelStorage (after routing) - self.channelStorage = pcr.accutraveltimestate(self.lddMap,\ - channelStorageForAccuTravelTime,\ - pcr.max(0.0, characteristicDistance)) # unit: m3 + self.channelStorage = pcr.accutraveltimestate( + self.lddMap, + channelStorageForAccuTravelTime, + pcr.max(0.0, characteristicDistance), + ) # unit: m3 # return channelStorageThatWillNotMove to channelStorage: - self.channelStorage += channelStorageThatWillNotMove # unit: m3 + self.channelStorage += channelStorageThatWillNotMove # unit: m3 # for non kinematic wave approaches, set subDishcarge Q in m3/s self.subDischarge = self.Q / vos.secondsPerDay() self.subDischarge = pcr.ifthen(self.landmask, self.subDischarge) - - def estimate_length_of_sub_time_step(self): + def estimate_length_of_sub_time_step(self): # estimate the length of sub-time step (unit: s): # - the shorter is the better # - estimated based on the initial or latest sub-time step discharge (unit: m3/s) - # - length_of_sub_time_step = pcr.ifthenelse(self.subDischarge > 0.0, - self.water_height * self.dynamicFracWat * self.cellArea / \ - self.subDischarge, vos.secondsPerDay()) - # TODO: Check this logic with Rens! + # + length_of_sub_time_step = pcr.ifthenelse( + self.subDischarge > 0.0, + self.water_height * self.dynamicFracWat * self.cellArea / self.subDischarge, + vos.secondsPerDay(), + ) + # TODO: Check this logic with Rens! # determine the number of sub time steps (based on Rens van Beek's method) # - critical_condition = (length_of_sub_time_step < vos.secondsPerDay()) & \ - (self.water_height > self.critical_water_height) & \ - (self.lddMap != pcr.ldd(5)) + critical_condition = ( + (length_of_sub_time_step < vos.secondsPerDay()) + & (self.water_height > self.critical_water_height) + & (self.lddMap != pcr.ldd(5)) + ) # - number_of_sub_time_steps = vos.secondsPerDay() /\ - pcr.cover( - pcr.areaminimum(\ - pcr.ifthen(critical_condition, \ - length_of_sub_time_step),self.landmask),\ - vos.secondsPerDay()/self.limit_num_of_sub_time_steps) + number_of_sub_time_steps = vos.secondsPerDay() / pcr.cover( + pcr.areaminimum( + pcr.ifthen(critical_condition, length_of_sub_time_step), self.landmask + ), + vos.secondsPerDay() / self.limit_num_of_sub_time_steps, + ) number_of_sub_time_steps = 1.25 * number_of_sub_time_steps + 1 number_of_sub_time_steps = pcr.roundup(number_of_sub_time_steps) # - number_of_loops = max(1.0, pcr.cellvalue(pcr.mapmaximum(number_of_sub_time_steps),1)[1]) # minimum number of sub_time_steps = 1 + number_of_loops = max( + 1.0, pcr.cellvalue(pcr.mapmaximum(number_of_sub_time_steps), 1)[1] + ) # minimum number of sub_time_steps = 1 number_of_loops = int(max(self.limit_num_of_sub_time_steps, number_of_loops)) - + # actual length of sub-time step (s) length_of_sub_time_step = vos.secondsPerDay() / number_of_loops - return (length_of_sub_time_step, number_of_loops) + return (length_of_sub_time_step, number_of_loops) - def simplifiedKinematicWave(self): + def simplifiedKinematicWave(self): """ The 'simplifiedKinematicWave': 1. First, assume that all local fluxes has been added to 'channelStorage'. This is done outside of this function/method. 2. Then, the 'channelStorage' is routed by using 'pcr.kinematic function' with 'lateral_inflow' = 0.0. """ ########################################################################################################################## - - # TODO: REMOVE THIS METHOD AS THIS IS IRRELEVANT. + # TODO: REMOVE THIS METHOD AS THIS IS IRRELEVANT. + logger.info("Using the simplifiedKinematicWave method ! ") - + # route only non negative channelStorage (otherwise stay): - channelStorageThatWillNotMove = pcr.ifthenelse(self.channelStorage < 0.0, self.channelStorage, 0.0) - + channelStorageThatWillNotMove = pcr.ifthenelse( + self.channelStorage < 0.0, self.channelStorage, 0.0 + ) + # channelStorage that will be given to the ROUTING operation: - channelStorageForRouting = pcr.max(0.0, self.channelStorage) # unit: m3 - + channelStorageForRouting = pcr.max(0.0, self.channelStorage) # unit: m3 + # estimate of water height (m) - # - needed to estimate the length of sub-time step and + # - needed to estimate the length of sub-time step and # also to estimate the channel wetted area (for the calculation of alpha and dischargeInitial) - self.water_height = channelStorageForRouting /\ - (pcr.max(self.min_fracwat_for_water_height, self.dynamicFracWat) * self.cellArea) + self.water_height = channelStorageForRouting / ( + pcr.max(self.min_fracwat_for_water_height, self.dynamicFracWat) + * self.cellArea + ) # estimate the length of sub-time step (unit: s): - length_of_sub_time_step, number_of_loops = self.estimate_length_of_sub_time_step() + length_of_sub_time_step, number_of_loops = ( + self.estimate_length_of_sub_time_step() + ) for i_loop in range(number_of_loops): - - msg = "sub-daily time step "+str(i_loop+1)+" from "+str(number_of_loops) + + msg = ( + "sub-daily time step " + + str(i_loop + 1) + + " from " + + str(number_of_loops) + ) logger.info(msg) - + # alpha parameter and initial discharge variable needed for kinematic wave - alpha, dischargeInitial = \ - self.calculate_alpha_and_initial_discharge_for_kinematic_wave(channelStorageForRouting, \ - self.water_height, \ - self.innundatedFraction, self.floodDepth) - + alpha, dischargeInitial = self.calculate_alpha_and_initial_discharge_for_kinematic_wave( + channelStorageForRouting, + self.water_height, + self.innundatedFraction, + self.floodDepth, + ) + # at the lake/reservoir outlets, use the discharge of water bofy outflow - waterBodyOutflowInM3PerSec = pcr.cover( - pcr.ifthen(\ - self.WaterBodies.waterBodyOut,\ - self.WaterBodies.waterBodyOutflow), 0.0) / vos.secondsPerDay() - waterBodyOutflowInM3PerSec = pcr.ifthen(\ - pcr.scalar(self.WaterBodies.waterBodyIds) > 0.0, \ - waterBodyOutflowInM3PerSec) - dischargeInitial = pcr.cover(waterBodyOutflowInM3PerSec, dischargeInitial) + waterBodyOutflowInM3PerSec = ( + pcr.cover( + pcr.ifthen( + self.WaterBodies.waterBodyOut, self.WaterBodies.waterBodyOutflow + ), + 0.0, + ) + / vos.secondsPerDay() + ) + waterBodyOutflowInM3PerSec = pcr.ifthen( + pcr.scalar(self.WaterBodies.waterBodyIds) > 0.0, + waterBodyOutflowInM3PerSec, + ) + dischargeInitial = pcr.cover(waterBodyOutflowInM3PerSec, dischargeInitial) # discharge (m3/s) based on kinematic wave approximation - #~ logger.debug('start pcr.kinematic') - self.subDischarge = pcr.kinematic(self.lddMap, dischargeInitial, 0.0, - alpha, self.beta, \ - 1, length_of_sub_time_step, self.channelLength) + # ~ logger.debug('start pcr.kinematic') + self.subDischarge = pcr.kinematic( + self.lddMap, + dischargeInitial, + 0.0, + alpha, + self.beta, + 1, + length_of_sub_time_step, + self.channelLength, + ) self.subDischarge = pcr.cover(self.subDischarge, 0.0) self.subDischarge = pcr.max(0.0, pcr.cover(self.subDischarge, 0.0)) - #~ logger.debug('done') - + # ~ logger.debug('done') + # make sure that we do not get negative channel storage - self.subDischarge = pcr.min(self.subDischarge * length_of_sub_time_step, \ - pcr.max(0.0, channelStorageForRouting + pcr.upstream(self.lddMap, self.subDischarge * length_of_sub_time_step)))/length_of_sub_time_step - + self.subDischarge = ( + pcr.min( + self.subDischarge * length_of_sub_time_step, + pcr.max( + 0.0, + channelStorageForRouting + + pcr.upstream( + self.lddMap, self.subDischarge * length_of_sub_time_step + ), + ), + ) + / length_of_sub_time_step + ) + # update channelStorage (m3) - storage_change_in_volume = pcr.upstream(self.lddMap, self.subDischarge * length_of_sub_time_step) - \ - self.subDischarge * length_of_sub_time_step - channelStorageForRouting += storage_change_in_volume + storage_change_in_volume = ( + pcr.upstream(self.lddMap, self.subDischarge * length_of_sub_time_step) + - self.subDischarge * length_of_sub_time_step + ) + channelStorageForRouting += storage_change_in_volume # # route only non negative channelStorage (otherwise stay): - channelStorageThatWillNotMove += pcr.ifthenelse(channelStorageForRouting < 0.0, channelStorageForRouting, 0.0) - channelStorageForRouting = pcr.max(0.000, channelStorageForRouting) - + channelStorageThatWillNotMove += pcr.ifthenelse( + channelStorageForRouting < 0.0, channelStorageForRouting, 0.0 + ) + channelStorageForRouting = pcr.max(0.000, channelStorageForRouting) + # update flood fraction and flood depth - self.inundatedFraction, self.floodDepth = self.returnInundationFractionAndFloodDepth(channelStorageForRouting) - + self.inundatedFraction, self.floodDepth = self.returnInundationFractionAndFloodDepth( + channelStorageForRouting + ) + # update dynamicFracWat: fraction of surface water bodies (dimensionless) including lakes and reservoirs # - lake and reservoir surface water fraction - self.dynamicFracWat = pcr.cover(\ - pcr.min(1.0, self.WaterBodies.fracWat), 0.0) - # - fraction of channel (including its excess above bankfull capacity) - self.dynamicFracWat += pcr.max(0.0, 1.0 - self.dynamicFracWat) * pcr.max(self.channelFraction, self.innundatedFraction) + self.dynamicFracWat = pcr.cover(pcr.min(1.0, self.WaterBodies.fracWat), 0.0) + # - fraction of channel (including its excess above bankfull capacity) + self.dynamicFracWat += pcr.max(0.0, 1.0 - self.dynamicFracWat) * pcr.max( + self.channelFraction, self.innundatedFraction + ) # - maximum value of dynamicFracWat is 1.0 - self.dynamicFracWat = pcr.ifthen(self.landmask, pcr.min(1.0, self.dynamicFracWat)) + self.dynamicFracWat = pcr.ifthen( + self.landmask, pcr.min(1.0, self.dynamicFracWat) + ) # estimate water_height for the next loop # - needed to estimate the channel wetted area (for the calculation of alpha and dischargeInitial) - self.water_height = channelStorageForRouting / (pcr.max(self.min_fracwat_for_water_height, self.dynamicFracWat) * self.cellArea) + self.water_height = channelStorageForRouting / ( + pcr.max(self.min_fracwat_for_water_height, self.dynamicFracWat) + * self.cellArea + ) # TODO: Check whether the usage of dynamicFracWat provides any problems? # total discharge_volume (m3) until this present i_loop - if i_loop == 0: discharge_volume = pcr.scalar(0.0) + if i_loop == 0: + discharge_volume = pcr.scalar(0.0) discharge_volume += self.subDischarge * length_of_sub_time_step # channel discharge (m3/day) = self.Q @@ -813,157 +1156,185 @@ self.channelStorage = channelStorageForRouting # return channelStorageThatWillNotMove to channelStorage: - self.channelStorage += channelStorageThatWillNotMove + self.channelStorage += channelStorageThatWillNotMove - def update(self,landSurface,groundwater,currTimeStep,meteo): + def update(self, landSurface, groundwater, currTimeStep, meteo): logger.info("routing in progress") - # waterBodies: + # waterBodies: # - get parameters at the beginning of each year or simulation - # - note that the following function should be called first, specifically because - # we have to define initial conditions at the beginning of simulaution, + # - note that the following function should be called first, specifically because + # we have to define initial conditions at the beginning of simulaution, # if currTimeStep.timeStepPCR == 1: initial_conditions_for_water_bodies = self.getState() - self.WaterBodies.getParameterFiles(currTimeStep,\ - self.cellArea,\ - self.lddMap,\ - initial_conditions_for_water_bodies) # the last line is for the initial conditions of lakes/reservoirs + self.WaterBodies.getParameterFiles( + currTimeStep, + self.cellArea, + self.lddMap, + initial_conditions_for_water_bodies, + ) # the last line is for the initial conditions of lakes/reservoirs if (currTimeStep.doy == 1) and (currTimeStep.timeStepPCR > 1): - self.WaterBodies.getParameterFiles(currTimeStep,\ - self.cellArea,\ - self.lddMap) + self.WaterBodies.getParameterFiles(currTimeStep, self.cellArea, self.lddMap) # if self.includeWaterBodies == False: - self.WaterBodies.waterBodyIds = pcr.ifthen(self.landmask, pcr.nominal(-1)) # ignoring all lakes and reservoirs - - # downstreamDemand (m3/s) for reservoirs + self.WaterBodies.waterBodyIds = pcr.ifthen( + self.landmask, pcr.nominal(-1) + ) # ignoring all lakes and reservoirs + + # downstreamDemand (m3/s) for reservoirs # - this one must be called before updating timestepsToAvgDischarge - # - estimated based on environmental flow discharge - self.downstreamDemand = self.estimate_discharge_for_environmental_flow(self.channelStorage) - + # - estimated based on environmental flow discharge + self.downstreamDemand = self.estimate_discharge_for_environmental_flow( + self.channelStorage + ) + # get routing/channel parameters/dimensions (based on avgDischarge) # and estimating water bodies fraction ; this is needed for calculating evaporation from water bodies - self.yMean, self.wMean = \ - self.getRoutingParamAvgDischarge(self.avgDischarge) - + self.yMean, self.wMean = self.getRoutingParamAvgDischarge(self.avgDischarge) + # channel width (unit: m) self.channelWidth = self.wMean - + # channel depth (unit: m) self.channelDepth = pcr.max(0.0, self.yMean) # # option to use constant channel depth (m) - if not isinstance(self.predefinedChannelDepth, types.NoneType):\ - self.channelDepth = pcr.cover(self.predefinedChannelDepth, self.channelDepth) + if not isinstance(self.predefinedChannelDepth, types.NoneType): + self.channelDepth = pcr.cover( + self.predefinedChannelDepth, self.channelDepth + ) # channel bankfull capacity (unit: m3) - if self.floodPlain: + if self.floodPlain: if self.usingFixedBankfullCapacity: self.channelStorageCapacity = self.predefinedBankfullCapacity else: - self.channelStorageCapacity = self.estimateBankfullCapacity(self.channelWidth, \ - self.channelDepth) - + self.channelStorageCapacity = self.estimateBankfullCapacity( + self.channelWidth, self.channelDepth + ) + # fraction of channel (dimensionless) # - mininum inundated fraction - self.channelFraction = pcr.max(0.0, pcr.min(1.0,\ - self.channelWidth * self.channelLength / (self.cellArea))) - + self.channelFraction = pcr.max( + 0.0, pcr.min(1.0, self.channelWidth * self.channelLength / (self.cellArea)) + ) + # fraction of innundation due to flood (dimensionless) and flood/innundation depth (m) - self.innundatedFraction, self.floodDepth = self.returnInundationFractionAndFloodDepth(self.channelStorage) - + self.innundatedFraction, self.floodDepth = self.returnInundationFractionAndFloodDepth( + self.channelStorage + ) + # fraction of surface water bodies (dimensionless) including lakes and reservoirs # - lake and reservoir surface water fraction - self.dynamicFracWat = pcr.cover(\ - pcr.min(1.0, self.WaterBodies.fracWat), 0.0) - # - fraction of channel (including its excess above bankfull capacity) - self.dynamicFracWat += pcr.max(0.0, 1.0 - self.dynamicFracWat) * pcr.max(self.channelFraction, self.innundatedFraction) + self.dynamicFracWat = pcr.cover(pcr.min(1.0, self.WaterBodies.fracWat), 0.0) + # - fraction of channel (including its excess above bankfull capacity) + self.dynamicFracWat += pcr.max(0.0, 1.0 - self.dynamicFracWat) * pcr.max( + self.channelFraction, self.innundatedFraction + ) # - maximum value of dynamicFracWat is 1.0 - self.dynamicFracWat = pcr.ifthen(self.landmask, pcr.min(1.0, self.dynamicFracWat)) - + self.dynamicFracWat = pcr.ifthen( + self.landmask, pcr.min(1.0, self.dynamicFracWat) + ) + # routing methods - if self.method == "accuTravelTime" or self.method == "simplifiedKinematicWave": \ - self.simple_update(landSurface, groundwater, currTimeStep, meteo) + if self.method == "accuTravelTime" or self.method == "simplifiedKinematicWave": + self.simple_update(landSurface, groundwater, currTimeStep, meteo) # - if self.method == "kinematicWave": \ - self.kinematic_wave_update(landSurface, groundwater, currTimeStep, meteo) + if self.method == "kinematicWave": + self.kinematic_wave_update(landSurface, groundwater, currTimeStep, meteo) # NOTE that this method require abstraction from fossil groundwater. - + # infiltration from surface water bodies (rivers/channels, as well as lakes and/or reservoirs) to groundwater bodies # - this exchange fluxes will be handed in the next time step # - in the future, this will be the interface between PCR-GLOBWB & MODFLOW (based on the difference between surface water levels & groundwater heads) # - self.calculate_exchange_to_groundwater(groundwater, currTimeStep) + self.calculate_exchange_to_groundwater(groundwater, currTimeStep) # volume water released in pits (losses: to the ocean / endorheic basin) - self.outgoing_volume_at_pits = pcr.ifthen(self.landmask, - pcr.cover( - pcr.ifthen(self.lddMap == pcr.ldd(5), self.Q), 0.0)) + self.outgoing_volume_at_pits = pcr.ifthen( + self.landmask, pcr.cover(pcr.ifthen(self.lddMap == pcr.ldd(5), self.Q), 0.0) + ) # TODO: accumulate water in endorheic basins that are considered as lakes/reservoirs - + # estimate volume of water that can be extracted for abstraction in the next time step - self.readAvlChannelStorage = pcr.max(0.0, self.estimate_available_volume_for_abstraction(self.channelStorage)) - - # old-style reporting - self.old_style_routing_reporting(currTimeStep) # TODO: remove this one + self.readAvlChannelStorage = pcr.max( + 0.0, self.estimate_available_volume_for_abstraction(self.channelStorage) + ) + # old-style reporting + self.old_style_routing_reporting(currTimeStep) # TODO: remove this one - def calculate_potential_evaporation(self,landSurface,currTimeStep,meteo,definedDynamicFracWat = None): + def calculate_potential_evaporation( + self, landSurface, currTimeStep, meteo, definedDynamicFracWat=None + ): - if self.no_zero_crop_water_coefficient == False: self.waterKC = 0.0 - + if self.no_zero_crop_water_coefficient == False: + self.waterKC = 0.0 + # potential evaporation from water bodies - # current principle: + # current principle: # - if landSurface.actualET < waterKC * meteo.referencePotET * self.fracWat # then, we add more evaporation # - if (currTimeStep.day == 1) or (currTimeStep.timeStepPCR == 1) and self.no_zero_crop_water_coefficient: - waterKC = vos.netcdf2PCRobjClone(self.fileCropKC,'kc', \ - currTimeStep.fulldate, useDoy = 'month',\ - cloneMapFileName = self.cloneMap) - self.waterKC = pcr.ifthen(self.landmask,\ - pcr.cover(waterKC, 0.0)) + if ( + (currTimeStep.day == 1) + or (currTimeStep.timeStepPCR == 1) + and self.no_zero_crop_water_coefficient + ): + waterKC = vos.netcdf2PCRobjClone( + self.fileCropKC, + "kc", + currTimeStep.fulldate, + useDoy="month", + cloneMapFileName=self.cloneMap, + ) + self.waterKC = pcr.ifthen(self.landmask, pcr.cover(waterKC, 0.0)) self.waterKC = pcr.max(self.minCropWaterKC, self.waterKC) - + # potential evaporation from water bodies (m/day)) - reduced by evaporation that has been calculated in the landSurface module - waterBodyPotEvapOvesSurfaceWaterArea = pcr.ifthen(self.landmask, \ - pcr.max(0.0,\ - self.waterKC * meteo.referencePotET -\ - landSurface.actualET )) # These values are NOT over the entire cell area. - + waterBodyPotEvapOvesSurfaceWaterArea = pcr.ifthen( + self.landmask, + pcr.max(0.0, self.waterKC * meteo.referencePotET - landSurface.actualET), + ) # These values are NOT over the entire cell area. + # potential evaporation from water bodies over the entire cell area (m/day) - if definedDynamicFracWat == None: dynamicFracWat = self.dynamicFracWat - waterBodyPotEvap = pcr.max(0.0, waterBodyPotEvapOvesSurfaceWaterArea * dynamicFracWat) + if definedDynamicFracWat == None: + dynamicFracWat = self.dynamicFracWat + waterBodyPotEvap = pcr.max( + 0.0, waterBodyPotEvapOvesSurfaceWaterArea * dynamicFracWat + ) return waterBodyPotEvap - def calculate_evaporation(self,landSurface,groundwater,currTimeStep,meteo): + def calculate_evaporation(self, landSurface, groundwater, currTimeStep, meteo): # calculate potential evaporation from water bodies OVER THE ENTIRE CELL AREA (m/day) ; not only over surface water bodies - self.waterBodyPotEvap = self.calculate_potential_evaporation(landSurface,currTimeStep,meteo) - + self.waterBodyPotEvap = self.calculate_potential_evaporation( + landSurface, currTimeStep, meteo + ) + # evaporation volume from water bodies (m3) - # - not limited to available channelStorage + # - not limited to available channelStorage volLocEvapWaterBody = self.waterBodyPotEvap * self.cellArea # - limited to available channelStorage - volLocEvapWaterBody = pcr.min(\ - pcr.max(0.0,self.channelStorage), volLocEvapWaterBody) + volLocEvapWaterBody = pcr.min( + pcr.max(0.0, self.channelStorage), volLocEvapWaterBody + ) # update channelStorage (m3) after evaporation from water bodies - self.channelStorage = self.channelStorage -\ - volLocEvapWaterBody + self.channelStorage = self.channelStorage - volLocEvapWaterBody self.local_input_to_surface_water -= volLocEvapWaterBody - - # evaporation (m) from water bodies + + # evaporation (m) from water bodies self.waterBodyEvaporation = volLocEvapWaterBody / self.cellArea self.waterBodyEvaporation = pcr.ifthen(self.landmask, self.waterBodyEvaporation) - def calculate_exchange_to_groundwater(self,groundwater,currTimeStep): + def calculate_exchange_to_groundwater(self, groundwater, currTimeStep): - if self.debugWaterBalance:\ - preStorage = self.channelStorage # unit: m3 + if self.debugWaterBalance: + preStorage = self.channelStorage # unit: m3 # riverbed infiltration (m3/day): # @@ -975,818 +1346,1091 @@ # - limited to available channelStorage # - this infiltration will be handed to groundwater in the next time step # - References: de Graaf et al. (2014); Wada et al. (2012); Wada et al. (2010) - # - TODO: This concept should be IMPROVED. + # - TODO: This concept should be IMPROVED. # if groundwater.useMODFLOW: - + # river bed exchange have been calculated within the MODFLOW (via baseflow variable) - + self.riverbedExchange = pcr.scalar(0.0) - + else: - - riverbedConductivity = groundwater.riverBedConductivity # unit: m/day - riverbedConductivity = pcr.min(0.1, riverbedConductivity) # maximum conductivity is 0.1 m/day (as recommended by Marc Bierkens: resistance = 1 day for 0.1 m river bed thickness) - total_groundwater_abstraction = pcr.max(0.0, groundwater.nonFossilGroundwaterAbs + groundwater.fossilGroundwaterAbstr) # unit: m - self.riverbedExchange = pcr.max(0.0,\ - pcr.min(pcr.max(0.0,self.channelStorage),\ - pcr.ifthenelse(groundwater.baseflow > 0.0, \ - pcr.ifthenelse(total_groundwater_abstraction > groundwater.baseflow, \ - riverbedConductivity * self.dynamicFracWat * self.cellArea, \ - 0.0), 0.0))) - self.riverbedExchange = pcr.cover(self.riverbedExchange, 0.0) - factor = 0.25 # to avoid flip flop - self.riverbedExchange = pcr.min(self.riverbedExchange, (1.0-factor)*pcr.max(0.0,self.channelStorage)) - self.riverbedExchange = pcr.ifthenelse(self.channelStorage < 0.0, 0.0, self.riverbedExchange) + + riverbedConductivity = groundwater.riverBedConductivity # unit: m/day + riverbedConductivity = pcr.min( + 0.1, riverbedConductivity + ) # maximum conductivity is 0.1 m/day (as recommended by Marc Bierkens: resistance = 1 day for 0.1 m river bed thickness) + total_groundwater_abstraction = pcr.max( + 0.0, + groundwater.nonFossilGroundwaterAbs + + groundwater.fossilGroundwaterAbstr, + ) # unit: m + self.riverbedExchange = pcr.max( + 0.0, + pcr.min( + pcr.max(0.0, self.channelStorage), + pcr.ifthenelse( + groundwater.baseflow > 0.0, + pcr.ifthenelse( + total_groundwater_abstraction > groundwater.baseflow, + riverbedConductivity * self.dynamicFracWat * self.cellArea, + 0.0, + ), + 0.0, + ), + ), + ) self.riverbedExchange = pcr.cover(self.riverbedExchange, 0.0) + factor = 0.25 # to avoid flip flop + self.riverbedExchange = pcr.min( + self.riverbedExchange, + (1.0 - factor) * pcr.max(0.0, self.channelStorage), + ) + self.riverbedExchange = pcr.ifthenelse( + self.channelStorage < 0.0, 0.0, self.riverbedExchange + ) + self.riverbedExchange = pcr.cover(self.riverbedExchange, 0.0) self.riverbedExchange = pcr.ifthen(self.landmask, self.riverbedExchange) - + # update channelStorage (m3) after riverbedExchange (m3) - self.channelStorage -= self.riverbedExchange + self.channelStorage -= self.riverbedExchange self.local_input_to_surface_water -= self.riverbedExchange - if self.debugWaterBalance:\ - vos.waterBalanceCheck([pcr.scalar(0.0)],\ - [self.riverbedExchange/self.cellArea],\ - [ preStorage/self.cellArea],\ - [ self.channelStorage/self.cellArea],\ - 'channelStorage after surface water infiltration',\ - True,\ - currTimeStep.fulldate,threshold=1e-4) + if self.debugWaterBalance: + vos.waterBalanceCheck( + [pcr.scalar(0.0)], + [self.riverbedExchange / self.cellArea], + [preStorage / self.cellArea], + [self.channelStorage / self.cellArea], + "channelStorage after surface water infiltration", + True, + currTimeStep.fulldate, + threshold=1e-4, + ) + def simple_update(self, landSurface, groundwater, currTimeStep, meteo): - def simple_update(self,landSurface,groundwater,currTimeStep,meteo): - # updating timesteps to calculate long and short term statistics values of avgDischarge, avgInflow, avgOutflow, etc. self.timestepsToAvgDischarge += 1. - if self.debugWaterBalance:\ - preStorage = self.channelStorage # unit: m3 + if self.debugWaterBalance: + preStorage = self.channelStorage # unit: m3 - # the following variable defines total local change (input) to surface water storage bodies # unit: m3 + # the following variable defines total local change (input) to surface water storage bodies # unit: m3 # - only local processes; therefore not considering any routing processes - self.local_input_to_surface_water = pcr.scalar(0.0) # initiate the variable, start from zero + self.local_input_to_surface_water = pcr.scalar( + 0.0 + ) # initiate the variable, start from zero # runoff from landSurface cells (unit: m/day) - self.runoff = landSurface.landSurfaceRunoff +\ - groundwater.baseflow - + self.runoff = landSurface.landSurfaceRunoff + groundwater.baseflow + # update channelStorage (unit: m3) after runoff self.channelStorage += self.runoff * self.cellArea self.local_input_to_surface_water += self.runoff * self.cellArea - # update channelStorage (unit: m3) after actSurfaceWaterAbstraction + # update channelStorage (unit: m3) after actSurfaceWaterAbstraction self.channelStorage -= landSurface.actSurfaceWaterAbstract * self.cellArea - self.local_input_to_surface_water -= landSurface.actSurfaceWaterAbstract * self.cellArea + self.local_input_to_surface_water -= ( + landSurface.actSurfaceWaterAbstract * self.cellArea + ) # reporting channelStorage after surface water abstraction (unit: m3) - self.channelStorageAfterAbstraction = pcr.ifthen(self.landmask, self.channelStorage) + self.channelStorageAfterAbstraction = pcr.ifthen( + self.landmask, self.channelStorage + ) # return flow from (m) non irrigation water demand - # - calculated in the landSurface.py module - nonIrrReturnFlowVol = landSurface.nonIrrReturnFlow*self.cellArea - self.channelStorage += nonIrrReturnFlowVol + # - calculated in the landSurface.py module + nonIrrReturnFlowVol = landSurface.nonIrrReturnFlow * self.cellArea + self.channelStorage += nonIrrReturnFlowVol self.local_input_to_surface_water += nonIrrReturnFlowVol # water consumption for non irrigation water demand (m) - this water is removed from the system/water balance - self.nonIrrWaterConsumption = pcr.max(0.0,\ - landSurface.nonIrrGrossDemand - \ - landSurface.nonIrrReturnFlow) - + self.nonIrrWaterConsumption = pcr.max( + 0.0, landSurface.nonIrrGrossDemand - landSurface.nonIrrReturnFlow + ) + # calculate evaporation from water bodies - this will return self.waterBodyEvaporation (unit: m) self.calculate_evaporation(landSurface, groundwater, currTimeStep, meteo) - - if self.debugWaterBalance:\ - vos.waterBalanceCheck([self.runoff,\ - landSurface.nonIrrReturnFlow],\ - [landSurface.actSurfaceWaterAbstract,self.waterBodyEvaporation],\ - [ preStorage/self.cellArea],\ - [ self.channelStorage/self.cellArea],\ - 'channelStorage (unit: m) before lake/reservoir outflow',\ - True,\ - currTimeStep.fulldate,threshold=5e-3) - + + if self.debugWaterBalance: + vos.waterBalanceCheck( + [self.runoff, landSurface.nonIrrReturnFlow], + [landSurface.actSurfaceWaterAbstract, self.waterBodyEvaporation], + [preStorage / self.cellArea], + [self.channelStorage / self.cellArea], + "channelStorage (unit: m) before lake/reservoir outflow", + True, + currTimeStep.fulldate, + threshold=5e-3, + ) + # LAKE AND RESERVOIR OPERATIONS ########################################################################################################################## - if self.debugWaterBalance: \ - preStorage = self.channelStorage # unit: m3 + if self.debugWaterBalance: + preStorage = self.channelStorage # unit: m3 # at cells where lakes and/or reservoirs defined, move channelStorage to waterBodyStorage # - storageAtLakeAndReservoirs = \ - pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0., - self.channelStorage) - storageAtLakeAndReservoirs = pcr.cover(storageAtLakeAndReservoirs,0.0) + storageAtLakeAndReservoirs = pcr.ifthen( + pcr.scalar(self.WaterBodies.waterBodyIds) > 0., self.channelStorage + ) + storageAtLakeAndReservoirs = pcr.cover(storageAtLakeAndReservoirs, 0.0) # # - move only non negative values and use rounddown values - storageAtLakeAndReservoirs = pcr.max(0.00, pcr.rounddown(storageAtLakeAndReservoirs)) - self.channelStorage -= storageAtLakeAndReservoirs # unit: m3 + storageAtLakeAndReservoirs = pcr.max( + 0.00, pcr.rounddown(storageAtLakeAndReservoirs) + ) + self.channelStorage -= storageAtLakeAndReservoirs # unit: m3 # update waterBodyStorage (inflow, storage and outflow) - self.WaterBodies.update(storageAtLakeAndReservoirs,\ - self.timestepsToAvgDischarge,\ - self.maxTimestepsToAvgDischargeShort,\ - self.maxTimestepsToAvgDischargeLong,\ - currTimeStep,\ - self.avgDischarge,\ - vos.secondsPerDay(),\ - self.downstreamDemand) + self.WaterBodies.update( + storageAtLakeAndReservoirs, + self.timestepsToAvgDischarge, + self.maxTimestepsToAvgDischargeShort, + self.maxTimestepsToAvgDischargeLong, + currTimeStep, + self.avgDischarge, + vos.secondsPerDay(), + self.downstreamDemand, + ) # waterBodyStorage (m3) after outflow: # values given are per water body id (not per cell) - self.waterBodyStorage = pcr.ifthen(self.landmask, - self.WaterBodies.waterBodyStorage) - + self.waterBodyStorage = pcr.ifthen( + self.landmask, self.WaterBodies.waterBodyStorage + ) + # transfer outflow from lakes and/or reservoirs to channelStorages - waterBodyOutflow = pcr.cover(\ - pcr.ifthen(\ - self.WaterBodies.waterBodyOut, - self.WaterBodies.waterBodyOutflow), 0.0) # unit: m3/day - + waterBodyOutflow = pcr.cover( + pcr.ifthen( + self.WaterBodies.waterBodyOut, self.WaterBodies.waterBodyOutflow + ), + 0.0, + ) # unit: m3/day + if self.method == "accuTravelTime": # distribute outflow to water body storage - # - this is to avoid 'waterBodyOutflow' skipping cells - # - this is done by distributing waterBodyOutflow within lake/reservoir cells + # - this is to avoid 'waterBodyOutflow' skipping cells + # - this is done by distributing waterBodyOutflow within lake/reservoir cells # - waterBodyOutflow = pcr.areaaverage(waterBodyOutflow, self.WaterBodies.waterBodyIds) - waterBodyOutflow = pcr.ifthen(\ - pcr.scalar(self.WaterBodies.waterBodyIds) > 0.0, - waterBodyOutflow) - self.waterBodyOutflow = pcr.cover(waterBodyOutflow, 0.0) # unit: m3/day + waterBodyOutflow = pcr.areaaverage( + waterBodyOutflow, self.WaterBodies.waterBodyIds + ) + waterBodyOutflow = pcr.ifthen( + pcr.scalar(self.WaterBodies.waterBodyIds) > 0.0, waterBodyOutflow + ) + self.waterBodyOutflow = pcr.cover(waterBodyOutflow, 0.0) # unit: m3/day # update channelStorage (m3) after waterBodyOutflow (m3) self.channelStorage += self.waterBodyOutflow # Note that local_input_to_surface_water does not include waterBodyOutflow - - if self.debugWaterBalance:\ - vos.waterBalanceCheck([self.waterBodyOutflow/self.cellArea],\ - [storageAtLakeAndReservoirs/self.cellArea],\ - [ preStorage/self.cellArea],\ - [ self.channelStorage/self.cellArea],\ - 'channelStorage (unit: m) after lake reservoir/outflow fluxes (errors here are most likely due to pcraster implementation in float_32)',\ - True,\ - currTimeStep.fulldate,threshold=1e-3) + if self.debugWaterBalance: + vos.waterBalanceCheck( + [self.waterBodyOutflow / self.cellArea], + [storageAtLakeAndReservoirs / self.cellArea], + [preStorage / self.cellArea], + [self.channelStorage / self.cellArea], + "channelStorage (unit: m) after lake reservoir/outflow fluxes (errors here are most likely due to pcraster implementation in float_32)", + True, + currTimeStep.fulldate, + threshold=1e-3, + ) + # ROUTING OPERATION: ########################################################################################################################## # - this will return new self.channelStorage (but still without waterBodyStorage) # - also, this will return self.Q which is channel discharge in m3/day # - if self.method == "accuTravelTime": self.accuTravelTime() - if self.method == "simplifiedKinematicWave": self.simplifiedKinematicWave() + if self.method == "accuTravelTime": + self.accuTravelTime() + if self.method == "simplifiedKinematicWave": + self.simplifiedKinematicWave() # # # channel discharge (m3/s): for current time step # self.discharge = self.Q / vos.secondsPerDay() - self.discharge = pcr.max(0., self.discharge) # reported channel discharge cannot be negative + self.discharge = pcr.max( + 0., self.discharge + ) # reported channel discharge cannot be negative self.discharge = pcr.ifthen(self.landmask, self.discharge) # - self.disChanWaterBody = pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0.,\ - pcr.areamaximum(self.discharge,self.WaterBodies.waterBodyIds)) + self.disChanWaterBody = pcr.ifthen( + pcr.scalar(self.WaterBodies.waterBodyIds) > 0., + pcr.areamaximum(self.discharge, self.WaterBodies.waterBodyIds), + ) self.disChanWaterBody = pcr.cover(self.disChanWaterBody, self.discharge) self.disChanWaterBody = pcr.ifthen(self.landmask, self.disChanWaterBody) # - self.disChanWaterBody = pcr.max(0.,self.disChanWaterBody) # reported channel discharge cannot be negative + self.disChanWaterBody = pcr.max( + 0., self.disChanWaterBody + ) # reported channel discharge cannot be negative # # ########################################################################################################################## # calculate the statistics of long and short term flow values self.calculate_statistics(groundwater) - - # return waterBodyStorage to channelStorage - self.channelStorage = self.return_water_body_storage_to_channel(self.channelStorage) - def calculate_alpha_and_initial_discharge_for_kinematic_wave(self, channelStorage, water_height, innundatedFraction, floodDepth): + # return waterBodyStorage to channelStorage + self.channelStorage = self.return_water_body_storage_to_channel( + self.channelStorage + ) - # calculate alpha (dimensionless), which is the roughness coefficient + def calculate_alpha_and_initial_discharge_for_kinematic_wave( + self, channelStorage, water_height, innundatedFraction, floodDepth + ): + + # calculate alpha (dimensionless), which is the roughness coefficient # - for kinewatic wave (see: http://pcraster.geo.uu.nl/pcraster/4.0.0/doc/manual/op_kinematic.html) # - based on wetted area (m2) and wetted perimeter (m), as well as self.beta (dimensionless) # - assuming rectangular channel - # - flood innundated areas with + # - flood innundated areas with # channel wetted area (m2) - # - the minimum wetted area is: water height x channel width (Edwin introduce this) + # - the minimum wetted area is: water height x channel width (Edwin introduce this) # - channel wetted area is mainly based on channelStorage and channelLength (Rens's approach) channel_wetted_area = water_height * self.channelWidth - channel_wetted_area = pcr.max(channel_wetted_area,\ - channelStorage / self.channelLength) + channel_wetted_area = pcr.max( + channel_wetted_area, channelStorage / self.channelLength + ) # wetted perimeter - flood_only_wetted_perimeter = floodDepth * (2.0) + \ - pcr.max(0.0, innundatedFraction*self.cellArea/self.channelLength - self.channelWidth) - channel_only_wetted_perimeter = \ - pcr.min(self.channelDepth, vos.getValDivZero(channelStorage, self.channelLength*self.channelWidth, 0.0)) * 2.0 + \ - self.channelWidth + flood_only_wetted_perimeter = floodDepth * (2.0) + pcr.max( + 0.0, + innundatedFraction * self.cellArea / self.channelLength - self.channelWidth, + ) + channel_only_wetted_perimeter = ( + pcr.min( + self.channelDepth, + vos.getValDivZero( + channelStorage, self.channelLength * self.channelWidth, 0.0 + ), + ) + * 2.0 + + self.channelWidth + ) # total channel wetted perimeter (unit: m) - channel_wetted_perimeter = channel_only_wetted_perimeter + \ - flood_only_wetted_perimeter + channel_wetted_perimeter = ( + channel_only_wetted_perimeter + flood_only_wetted_perimeter + ) # minimum channel wetted perimeter = 10 cm - channel_wetted_perimeter = pcr.max(0.1, channel_wetted_perimeter) - - # corrected Manning's coefficient: + channel_wetted_perimeter = pcr.max(0.1, channel_wetted_perimeter) + + # corrected Manning's coefficient: if self.floodPlain: - usedManningsN = ((channel_only_wetted_perimeter/channel_wetted_perimeter) * self.manningsN**(1.5) + \ - ( flood_only_wetted_perimeter/channel_wetted_perimeter) * self.floodplainManN**(1.5))**(2./3.) + usedManningsN = ( + (channel_only_wetted_perimeter / channel_wetted_perimeter) + * self.manningsN ** (1.5) + + (flood_only_wetted_perimeter / channel_wetted_perimeter) + * self.floodplainManN ** (1.5) + ) ** (2. / 3.) else: usedManningsN = self.manningsN - + # alpha (dimensionless) and initial estimate of channel discharge (m3/s) # - alpha = (usedManningsN*channel_wetted_perimeter**(2./3.)*self.gradient**(-0.5))**self.beta # dimensionless - dischargeInitial = pcr.ifthenelse(alpha > 0.0,\ - (channel_wetted_area / alpha)**(1.0/self.beta), 0.0) # unit: m3 - - return (alpha, dischargeInitial) + alpha = ( + usedManningsN + * channel_wetted_perimeter ** (2. / 3.) + * self.gradient ** (-0.5) + ) ** self.beta # dimensionless + dischargeInitial = pcr.ifthenelse( + alpha > 0.0, (channel_wetted_area / alpha) ** (1.0 / self.beta), 0.0 + ) # unit: m3 - def calculate_alpha_and_initial_discharge_for_kinematic_wave_OLD(self, channelStorage = None): + return (alpha, dischargeInitial) - # calculate alpha (dimensionless), which is the roughness coefficient + def calculate_alpha_and_initial_discharge_for_kinematic_wave_OLD( + self, channelStorage=None + ): + + # calculate alpha (dimensionless), which is the roughness coefficient # - for kinewatic wave (see: http://pcraster.geo.uu.nl/pcraster/4.0.0/doc/manual/op_kinematic.html) # - based on wetted area (m2) and wetted perimeter (m), as well as self.beta (dimensionless) # - assuming rectangular channel # Manning's coefficient: usedManningsN = self.manningsN - + # channel wetted area (m2) # - alternative 1: based on channelStorage and channelLength (Rens's approach) channel_wetted_area = self.water_height * self.channelWidth - # - alternative 2: the minimum wetted are is: water height x channel width (Edwin introduce this) - channel_wetted_area = pcr.max(channel_wetted_area,\ - channelStorage / self.channelLength) # unit: m2 + # - alternative 2: the minimum wetted are is: water height x channel width (Edwin introduce this) + channel_wetted_area = pcr.max( + channel_wetted_area, channelStorage / self.channelLength + ) # unit: m2 # channel wetted perimeter (m) - channel_wetted_perimeter = 2.0*channel_wetted_area/self.channelWidth + self.channelWidth # unit: m + channel_wetted_perimeter = ( + 2.0 * channel_wetted_area / self.channelWidth + self.channelWidth + ) # unit: m # flood fraction (dimensionless) and flood depth (unit: m) floodFraction = pcr.scalar(0.0) - floodDepth = pcr.scalar(0.0) - + floodDepth = pcr.scalar(0.0) + if self.floodPlain: - + # return flood fraction and flood/innundation depth above the flood plain - floodFraction, floodDepth = self.returnInundationFractionAndFloodDepth(channelStorage) - + floodFraction, floodDepth = self.returnInundationFractionAndFloodDepth( + channelStorage + ) + # wetted perimeter - flood_only_wetted_perimeter = pcr.max(0.0, floodFraction*self.cellArea/self.channelLength - self.channelWidth) + \ - floodDepth * (2.0) - channel_only_wetted_perimeter = \ - self.channelWidth + \ - 2.0 * pcr.min(self.channelDepth, channelStorage/(self.channelLength*self.channelWidth)) + flood_only_wetted_perimeter = pcr.max( + 0.0, + floodFraction * self.cellArea / self.channelLength - self.channelWidth, + ) + floodDepth * (2.0) + channel_only_wetted_perimeter = self.channelWidth + 2.0 * pcr.min( + self.channelDepth, + channelStorage / (self.channelLength * self.channelWidth), + ) # - channel_wetted_perimeter = channel_only_wetted_perimeter + flood_only_wetted_perimeter # unit: m - - # corrected Manning's coefficient: - usedManningsN = ((channel_only_wetted_perimeter/channel_wetted_perimeter) * self.manningsN**(1.5) + \ - ( flood_only_wetted_perimeter/channel_wetted_perimeter) * self.floodplainManN**(1.5))**(2./3.) - + channel_wetted_perimeter = ( + channel_only_wetted_perimeter + flood_only_wetted_perimeter + ) # unit: m + + # corrected Manning's coefficient: + usedManningsN = ( + (channel_only_wetted_perimeter / channel_wetted_perimeter) + * self.manningsN ** (1.5) + + (flood_only_wetted_perimeter / channel_wetted_perimeter) + * self.floodplainManN ** (1.5) + ) ** (2. / 3.) + # alpha (dimensionless) and estimate of channel discharge (m3/s) # - alpha = (usedManningsN*channel_wetted_perimeter**(2./3.)*self.gradient**(-0.5))**self.beta # dimensionless - dischargeInitial = pcr.ifthenelse(alpha > 0.0,\ - (channel_wetted_area / alpha)**(1.0/self.beta), 0.0) # unit: m3 - - return (alpha, dischargeInitial, floodFraction, floodDepth) + alpha = ( + usedManningsN + * channel_wetted_perimeter ** (2. / 3.) + * self.gradient ** (-0.5) + ) ** self.beta # dimensionless + dischargeInitial = pcr.ifthenelse( + alpha > 0.0, (channel_wetted_area / alpha) ** (1.0 / self.beta), 0.0 + ) # unit: m3 - def integralLogisticFunction(self,x): - + return (alpha, dischargeInitial, floodFraction, floodDepth) + + def integralLogisticFunction(self, x): + # returns a tupple of two values holding the integral of the logistic functions of (x) and (-x) - - logInt=pcr.ln(pcr.exp(-x)+1) - return logInt,x+logInt - + logInt = pcr.ln(pcr.exp(-x) + 1) + + return logInt, x + logInt + def returnInundationFractionAndFloodDepth(self, channelStorage): - + # flood/innundation depth above the flood plain (unit: m) floodDepth = 0.0 - + # channel and flood innundated fraction (dimensionless, the minimum value is channelFraction) inundatedFraction = self.channelFraction - + if self.floodPlain: - msg = 'Calculate channel inundated fraction and flood inundation depth above the floodplain.' + msg = "Calculate channel inundated fraction and flood inundation depth above the floodplain." logger.info(msg) - + # given the flood channel volume: channelStorage # - return the flooded fraction and the associated water height # - using a logistic smoother near intersections (K&K, 2007) - + # flood/innundation/excess volume (excess above the bankfull capacity, unit: m3) excessVolume = pcr.max(0.0, channelStorage - self.channelStorageCapacity) - - # find the match on the basis of the shortest distance + + # find the match on the basis of the shortest distance # to the available intersections or steps # - deltaXMin = self.floodVolume[self.nrZLevels-1] - y_i = pcr.scalar(1.0) - k = [pcr.scalar(0.0)]*2 - mInt = pcr.scalar(0.0) - for iCnt in range(self.nrZLevels-1,0,-1): + deltaXMin = self.floodVolume[self.nrZLevels - 1] + y_i = pcr.scalar(1.0) + k = [pcr.scalar(0.0)] * 2 + mInt = pcr.scalar(0.0) + for iCnt in range(self.nrZLevels - 1, 0, -1): # - find x_i for current volume and update match if applicable # also update slope and intercept - deltaX = excessVolume - self.floodVolume[iCnt] - mask = pcr.abs(deltaX) < pcr.abs(deltaXMin) + deltaX = excessVolume - self.floodVolume[iCnt] + mask = pcr.abs(deltaX) < pcr.abs(deltaXMin) deltaXMin = pcr.ifthenelse(mask, deltaX, deltaXMin) - y_i = pcr.ifthenelse(mask, self.areaFractions[iCnt], y_i) - k[0] = pcr.ifthenelse(mask, self.kSlope[iCnt-1], k[0]) + y_i = pcr.ifthenelse(mask, self.areaFractions[iCnt], y_i) + k[0] = pcr.ifthenelse(mask, self.kSlope[iCnt - 1], k[0]) k[1] = pcr.ifthenelse(mask, self.kSlope[iCnt], k[1]) mInt = pcr.ifthenelse(mask, self.mInterval[iCnt], mInt) - + # all values returned, process data: calculate scaled deltaX and smoothed function # on the basis of the integrated logistic functions PHI(x) and 1-PHI(x) # deltaX = deltaXMin - deltaXScaled = pcr.ifthenelse(deltaX < 0.,pcr.scalar(-1.),1.)*\ - pcr.min(self.criterionKK,pcr.abs(deltaX/pcr.max(1.,mInt))) + deltaXScaled = pcr.ifthenelse(deltaX < 0., pcr.scalar(-1.), 1.) * pcr.min( + self.criterionKK, pcr.abs(deltaX / pcr.max(1., mInt)) + ) logInt = self.integralLogisticFunction(deltaXScaled) - + # compute fractional inundated/flooded area - inundatedFraction = pcr.ifthenelse(excessVolume > 0.0,\ - pcr.ifthenelse(pcr.abs(deltaXScaled) < self.criterionKK,\ - y_i-k[0]*mInt*logInt[0]+k[1]*mInt*logInt[1],\ - y_i+pcr.ifthenelse(deltaX < 0.,k[0],k[1])*deltaX), 0.0) + inundatedFraction = pcr.ifthenelse( + excessVolume > 0.0, + pcr.ifthenelse( + pcr.abs(deltaXScaled) < self.criterionKK, + y_i - k[0] * mInt * logInt[0] + k[1] * mInt * logInt[1], + y_i + pcr.ifthenelse(deltaX < 0., k[0], k[1]) * deltaX, + ), + 0.0, + ) # - minimum value is channelFraction inundatedFraction = pcr.max(self.channelFraction, inundatedFraction) # - maximum value is 1.0 - inundatedFraction = pcr.max(0.,pcr.min(1.0, inundatedFraction)) # dimensionless - - # calculate flooded/inundated depth (unit: m) above the floodplain - #_- it will be zero if excessVolume == 0 - floodDepth = pcr.ifthenelse(inundatedFraction > 0., \ - excessVolume/(pcr.max(self.min_fracwat_for_water_height, inundatedFraction)*self.cellArea),0.) # unit: m + inundatedFraction = pcr.max( + 0., pcr.min(1.0, inundatedFraction) + ) # dimensionless + + # calculate flooded/inundated depth (unit: m) above the floodplain + # _- it will be zero if excessVolume == 0 + floodDepth = pcr.ifthenelse( + inundatedFraction > 0., + excessVolume + / ( + pcr.max(self.min_fracwat_for_water_height, inundatedFraction) + * self.cellArea + ), + 0., + ) # unit: m # - maximum flood depth max_flood_depth = 25.0 - floodDepth = pcr.max(0.0, pcr.min(max_flood_depth, floodDepth)) - + floodDepth = pcr.max(0.0, pcr.min(max_flood_depth, floodDepth)) + return inundatedFraction, floodDepth def return_water_body_storage_to_channel(self, channelStorage): - # return waterBodyStorage to channelStorage + # return waterBodyStorage to channelStorage # - waterBodyStorageTotal = \ - pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0., - pcr.areaaverage(\ - pcr.ifthen(self.landmask,self.WaterBodies.waterBodyStorage),\ - pcr.ifthen(self.landmask,self.WaterBodies.waterBodyIds)) + \ - pcr.areatotal(pcr.cover(\ - pcr.ifthen(self.landmask,channelStorage), 0.0),\ - pcr.ifthen(self.landmask,self.WaterBodies.waterBodyIds))) - waterBodyStoragePerCell = \ - waterBodyStorageTotal*\ - self.cellArea/\ - pcr.areatotal(pcr.cover(\ - self.cellArea, 0.0),\ - pcr.ifthen(self.landmask,self.WaterBodies.waterBodyIds)) - waterBodyStoragePerCell = \ - pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0., - waterBodyStoragePerCell) # unit: m3 + waterBodyStorageTotal = pcr.ifthen( + pcr.scalar(self.WaterBodies.waterBodyIds) > 0., + pcr.areaaverage( + pcr.ifthen(self.landmask, self.WaterBodies.waterBodyStorage), + pcr.ifthen(self.landmask, self.WaterBodies.waterBodyIds), + ) + + pcr.areatotal( + pcr.cover(pcr.ifthen(self.landmask, channelStorage), 0.0), + pcr.ifthen(self.landmask, self.WaterBodies.waterBodyIds), + ), + ) + waterBodyStoragePerCell = ( + waterBodyStorageTotal + * self.cellArea + / pcr.areatotal( + pcr.cover(self.cellArea, 0.0), + pcr.ifthen(self.landmask, self.WaterBodies.waterBodyIds), + ) + ) + waterBodyStoragePerCell = pcr.ifthen( + pcr.scalar(self.WaterBodies.waterBodyIds) > 0., waterBodyStoragePerCell + ) # unit: m3 # - channelStorage = pcr.cover(waterBodyStoragePerCell, channelStorage) # unit: m3 + channelStorage = pcr.cover(waterBodyStoragePerCell, channelStorage) # unit: m3 channelStorage = pcr.ifthen(self.landmask, channelStorage) return channelStorage - def kinematic_wave_update(self, landSurface, groundwater, currTimeStep, meteo): + def kinematic_wave_update(self, landSurface, groundwater, currTimeStep, meteo): logger.info("Using the fully kinematic wave method! ") - # updating timesteps to calculate long and short term statistics + # updating timesteps to calculate long and short term statistics # values of avgDischarge, avgInflow, avgOutflow, etc. self.timestepsToAvgDischarge += 1. - # the following variable defines total local change (input) to surface water storage bodies # unit: m3 + # the following variable defines total local change (input) to surface water storage bodies # unit: m3 # - only local processes; therefore not considering any routing processes - self.local_input_to_surface_water = pcr.scalar(0.0) # initiate the variable, start from zero + self.local_input_to_surface_water = pcr.scalar( + 0.0 + ) # initiate the variable, start from zero - # For simplification, surface water abstraction + # For simplification, surface water abstraction # is done outside the sub daily time steps. # - # update channelStorage (unit: m3) after actSurfaceWaterAbstraction + # update channelStorage (unit: m3) after actSurfaceWaterAbstraction self.channelStorage -= landSurface.actSurfaceWaterAbstract * self.cellArea - self.local_input_to_surface_water -= landSurface.actSurfaceWaterAbstract * self.cellArea + self.local_input_to_surface_water -= ( + landSurface.actSurfaceWaterAbstract * self.cellArea + ) # # reporting channelStorage after surface water abstraction (unit: m3) - self.channelStorageAfterAbstraction = pcr.ifthen(self.landmask, self.channelStorage) + self.channelStorageAfterAbstraction = pcr.ifthen( + self.landmask, self.channelStorage + ) - # return flow from (m) non irrigation water demand # - calculated in the landSurface.py module: landSurface.nonIrrReturnFlow # water consumption for non irrigation water demand (m) - this water is removed from the system/water balance - self.nonIrrWaterConsumption = pcr.max(0.0,\ - landSurface.nonIrrGrossDemand - \ - landSurface.nonIrrReturnFlow) + self.nonIrrWaterConsumption = pcr.max( + 0.0, landSurface.nonIrrGrossDemand - landSurface.nonIrrReturnFlow + ) - # runoff from landSurface cells (unit: m/day) - self.runoff = landSurface.landSurfaceRunoff +\ - groundwater.baseflow # values are over the entire cell area - + # runoff from landSurface cells (unit: m/day) + self.runoff = ( + landSurface.landSurfaceRunoff + groundwater.baseflow + ) # values are over the entire cell area # LAKE AND RESERVOIR OPERATIONS ########################################################################################################################## # # at cells where lakes and/or reservoirs defined, move channelStorage to waterBodyStorage - storageAtLakeAndReservoirs = \ - pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0., - self.channelStorage) - storageAtLakeAndReservoirs = pcr.cover(storageAtLakeAndReservoirs,0.0) + storageAtLakeAndReservoirs = pcr.ifthen( + pcr.scalar(self.WaterBodies.waterBodyIds) > 0., self.channelStorage + ) + storageAtLakeAndReservoirs = pcr.cover(storageAtLakeAndReservoirs, 0.0) # - move only non negative values and use rounddown values - storageAtLakeAndReservoirs = pcr.max(0.00, pcr.rounddown(storageAtLakeAndReservoirs)) - self.channelStorage -= storageAtLakeAndReservoirs # unit: m3 + storageAtLakeAndReservoirs = pcr.max( + 0.00, pcr.rounddown(storageAtLakeAndReservoirs) + ) + self.channelStorage -= storageAtLakeAndReservoirs # unit: m3 # # update waterBodyStorage (inflow, storage and outflow) - self.WaterBodies.update(storageAtLakeAndReservoirs,\ - self.timestepsToAvgDischarge,\ - self.maxTimestepsToAvgDischargeShort,\ - self.maxTimestepsToAvgDischargeLong,\ - currTimeStep,\ - self.avgDischarge,\ - vos.secondsPerDay(),\ - self.downstreamDemand) + self.WaterBodies.update( + storageAtLakeAndReservoirs, + self.timestepsToAvgDischarge, + self.maxTimestepsToAvgDischargeShort, + self.maxTimestepsToAvgDischargeLong, + currTimeStep, + self.avgDischarge, + vos.secondsPerDay(), + self.downstreamDemand, + ) # - waterBodyStorage (m3) after outflow: # values given are per water body id (not per cell) - self.waterBodyStorage = pcr.ifthen(self.landmask, - self.WaterBodies.waterBodyStorage) + self.waterBodyStorage = pcr.ifthen( + self.landmask, self.WaterBodies.waterBodyStorage + ) # # outflow from lakes and/or reservoirs at lake/reservoir outlet cells - waterBodyOutflow = pcr.cover(\ - pcr.ifthen(\ - self.WaterBodies.waterBodyOut, - self.WaterBodies.waterBodyOutflow), 0.0) # unit: m3/day + waterBodyOutflow = pcr.cover( + pcr.ifthen( + self.WaterBodies.waterBodyOut, self.WaterBodies.waterBodyOutflow + ), + 0.0, + ) # unit: m3/day # route only non negative channelStorage (otherwise stay): - # - note that, the following includes storages in - channelStorageThatWillNotMove = pcr.ifthenelse(self.channelStorage < 0.0, self.channelStorage, 0.0) - + # - note that, the following includes storages in + channelStorageThatWillNotMove = pcr.ifthenelse( + self.channelStorage < 0.0, self.channelStorage, 0.0 + ) + # channelStorage that will be given to the ROUTING operation: - channelStorageForRouting = pcr.max(0.0, self.channelStorage) # unit: m3 - + channelStorageForRouting = pcr.max(0.0, self.channelStorage) # unit: m3 + # estimate of water height (m) - # - needed to estimate the length of sub-time step and + # - needed to estimate the length of sub-time step and # also to estimate the channel wetted area (for the calculation of alpha and dischargeInitial) - self.water_height = channelStorageForRouting /\ - (pcr.max(self.min_fracwat_for_water_height, self.dynamicFracWat) * self.cellArea) + self.water_height = channelStorageForRouting / ( + pcr.max(self.min_fracwat_for_water_height, self.dynamicFracWat) + * self.cellArea + ) # estimate the length of sub-time step (unit: s): - length_of_sub_time_step, number_of_loops = self.estimate_length_of_sub_time_step() + length_of_sub_time_step, number_of_loops = ( + self.estimate_length_of_sub_time_step() + ) ####################################################################################################################### for i_loop in range(number_of_loops): - - msg = "sub-daily time step "+str(i_loop+1)+" from "+str(number_of_loops) + + msg = ( + "sub-daily time step " + + str(i_loop + 1) + + " from " + + str(number_of_loops) + ) logger.info(msg) - + # initiating accumulated values: if i_loop == 0: - acc_local_input_to_surface_water = pcr.scalar(0.0) # unit: m3 - acc_water_body_evaporation_volume = pcr.scalar(0.0) # unit: m3 - acc_discharge_volume = pcr.scalar(0.0) # unit: m3 - + acc_local_input_to_surface_water = pcr.scalar(0.0) # unit: m3 + acc_water_body_evaporation_volume = pcr.scalar(0.0) # unit: m3 + acc_discharge_volume = pcr.scalar(0.0) # unit: m3 - if self.debugWaterBalance:\ - preStorage = pcr.ifthen(self.landmask,\ - channelStorageForRouting) - + if self.debugWaterBalance: + preStorage = pcr.ifthen(self.landmask, channelStorageForRouting) + # update channelStorageForRouting after runoff and return flow from non irrigation demand - channelStorageForRouting += (self.runoff + landSurface.nonIrrReturnFlow) * \ - self.cellArea * length_of_sub_time_step/vos.secondsPerDay() # unit: m3 - acc_local_input_to_surface_water += (self.runoff + landSurface.nonIrrReturnFlow) * \ - self.cellArea * length_of_sub_time_step/vos.secondsPerDay() # unit: m3 + channelStorageForRouting += ( + (self.runoff + landSurface.nonIrrReturnFlow) + * self.cellArea + * length_of_sub_time_step + / vos.secondsPerDay() + ) # unit: m3 + acc_local_input_to_surface_water += ( + (self.runoff + landSurface.nonIrrReturnFlow) + * self.cellArea + * length_of_sub_time_step + / vos.secondsPerDay() + ) # unit: m3 - # potential evaporation within the sub-time step ; unit: m, values are over the entire cell area + # potential evaporation within the sub-time step ; unit: m, values are over the entire cell area # - water_body_potential_evaporation = self.calculate_potential_evaporation(landSurface,currTimeStep,meteo) *\ - length_of_sub_time_step/vos.secondsPerDay() + water_body_potential_evaporation = ( + self.calculate_potential_evaporation(landSurface, currTimeStep, meteo) + * length_of_sub_time_step + / vos.secondsPerDay() + ) # - accumulating potential evaporation if i_loop == 0: self.waterBodyPotEvap = pcr.scalar(0.0) - self.waterBodyPotEvap += water_body_potential_evaporation - + self.waterBodyPotEvap += water_body_potential_evaporation + # update channelStorageForRouting after evaporation - water_body_evaporation_volume = pcr.min(pcr.max(channelStorageForRouting, 0.0), \ - water_body_potential_evaporation * self.cellArea * length_of_sub_time_step/vos.secondsPerDay()) - channelStorageForRouting -= water_body_evaporation_volume - acc_local_input_to_surface_water -= water_body_evaporation_volume + water_body_evaporation_volume = pcr.min( + pcr.max(channelStorageForRouting, 0.0), + water_body_potential_evaporation + * self.cellArea + * length_of_sub_time_step + / vos.secondsPerDay(), + ) + channelStorageForRouting -= water_body_evaporation_volume + acc_local_input_to_surface_water -= water_body_evaporation_volume acc_water_body_evaporation_volume += water_body_evaporation_volume - - if self.debugWaterBalance:\ - vos.waterBalanceCheck([self.runoff * length_of_sub_time_step/vos.secondsPerDay(), \ - landSurface.nonIrrReturnFlow * length_of_sub_time_step/vos.secondsPerDay()],\ - [water_body_evaporation_volume/self.cellArea],\ - [preStorage/self.cellArea],\ - [channelStorageForRouting/self.cellArea],\ - 'channelStorageForRouting',\ - True,\ - currTimeStep.fulldate,threshold=5e-5) + if self.debugWaterBalance: + vos.waterBalanceCheck( + [ + self.runoff * length_of_sub_time_step / vos.secondsPerDay(), + landSurface.nonIrrReturnFlow + * length_of_sub_time_step + / vos.secondsPerDay(), + ], + [water_body_evaporation_volume / self.cellArea], + [preStorage / self.cellArea], + [channelStorageForRouting / self.cellArea], + "channelStorageForRouting", + True, + currTimeStep.fulldate, + threshold=5e-5, + ) + # alpha parameter and initial discharge variable needed for kinematic wave - alpha, dischargeInitial = \ - self.calculate_alpha_and_initial_discharge_for_kinematic_wave(channelStorageForRouting, \ - self.water_height, \ - self.innundatedFraction, self.floodDepth) - + alpha, dischargeInitial = self.calculate_alpha_and_initial_discharge_for_kinematic_wave( + channelStorageForRouting, + self.water_height, + self.innundatedFraction, + self.floodDepth, + ) + # discharge (m3/s) based on kinematic wave approximation - #~ logger.debug('start pcr.kinematic') - self.subDischarge = pcr.kinematic(self.lddMap, dischargeInitial, 0.0, - alpha, self.beta, \ - 1, length_of_sub_time_step, self.channelLength) + # ~ logger.debug('start pcr.kinematic') + self.subDischarge = pcr.kinematic( + self.lddMap, + dischargeInitial, + 0.0, + alpha, + self.beta, + 1, + length_of_sub_time_step, + self.channelLength, + ) self.subDischarge = pcr.max(0.0, pcr.cover(self.subDischarge, 0.0)) - #~ logger.debug('done') - - #~ # the kinematic wave is implemented only for channels (not to lakes and reservoirs) - Shall we do this? - #~ # - set discharge to zero for lakes and reservoirs: - #~ self.subDischarge = pcr.cover(\ - #~ pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0., pcr.scalar(0.0)), self.subDischarge) - + # ~ logger.debug('done') + + # ~ # the kinematic wave is implemented only for channels (not to lakes and reservoirs) - Shall we do this? + # ~ # - set discharge to zero for lakes and reservoirs: + # ~ self.subDischarge = pcr.cover(\ + # ~ pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0., pcr.scalar(0.0)), self.subDischarge) + # make sure that we do not get negative channel storage - self.subDischarge = pcr.min(self.subDischarge * length_of_sub_time_step, \ - pcr.max(0.0, channelStorageForRouting + pcr.upstream(self.lddMap, self.subDischarge * length_of_sub_time_step)))/length_of_sub_time_step + self.subDischarge = ( + pcr.min( + self.subDischarge * length_of_sub_time_step, + pcr.max( + 0.0, + channelStorageForRouting + + pcr.upstream( + self.lddMap, self.subDischarge * length_of_sub_time_step + ), + ), + ) + / length_of_sub_time_step + ) # update channelStorage (m3) - storage_change_in_volume = pcr.upstream(self.lddMap, self.subDischarge * length_of_sub_time_step) - self.subDischarge * length_of_sub_time_step - channelStorageForRouting += storage_change_in_volume - - if self.debugWaterBalance:\ - vos.waterBalanceCheck([self.runoff * length_of_sub_time_step/vos.secondsPerDay(), \ - landSurface.nonIrrReturnFlow * length_of_sub_time_step/vos.secondsPerDay(),\ - storage_change_in_volume/self.cellArea],\ - [water_body_evaporation_volume/self.cellArea],\ - [preStorage/self.cellArea],\ - [channelStorageForRouting/self.cellArea],\ - 'channelStorageForRouting (after routing, without lakes/reservoirs)',\ - True,\ - currTimeStep.fulldate,threshold=5e-4) + storage_change_in_volume = ( + pcr.upstream(self.lddMap, self.subDischarge * length_of_sub_time_step) + - self.subDischarge * length_of_sub_time_step + ) + channelStorageForRouting += storage_change_in_volume + if self.debugWaterBalance: + vos.waterBalanceCheck( + [ + self.runoff * length_of_sub_time_step / vos.secondsPerDay(), + landSurface.nonIrrReturnFlow + * length_of_sub_time_step + / vos.secondsPerDay(), + storage_change_in_volume / self.cellArea, + ], + [water_body_evaporation_volume / self.cellArea], + [preStorage / self.cellArea], + [channelStorageForRouting / self.cellArea], + "channelStorageForRouting (after routing, without lakes/reservoirs)", + True, + currTimeStep.fulldate, + threshold=5e-4, + ) + # transfer outflow from lakes and/or reservoirs # - update channelStorage (m3) after waterBodyOutflow (m3) - channelStorageForRouting += pcr.upstream(self.lddMap, waterBodyOutflow) * length_of_sub_time_step/vos.secondsPerDay() + channelStorageForRouting += ( + pcr.upstream(self.lddMap, waterBodyOutflow) + * length_of_sub_time_step + / vos.secondsPerDay() + ) # Note that local_input_to_surface_water does not include waterBodyOutflow - # - at the lake/reservoir outlets, add the discharge of water body outflow - waterBodyOutflowInM3PerSec = pcr.ifthen(\ - self.WaterBodies.waterBodyOut, - self.WaterBodies.waterBodyOutflow) / vos.secondsPerDay() - self.subDischarge = self.subDischarge + \ - pcr.cover(waterBodyOutflowInM3PerSec, 0.0) + # - at the lake/reservoir outlets, add the discharge of water body outflow + waterBodyOutflowInM3PerSec = ( + pcr.ifthen( + self.WaterBodies.waterBodyOut, self.WaterBodies.waterBodyOutflow + ) + / vos.secondsPerDay() + ) + self.subDischarge = self.subDischarge + pcr.cover( + waterBodyOutflowInM3PerSec, 0.0 + ) self.subDischarge = pcr.ifthen(self.landmask, self.subDischarge) - # total discharge_volume (m3) until this present i_loop acc_discharge_volume += self.subDischarge * length_of_sub_time_step # route only non negative channelStorage (otherwise stay): - channelStorageThatWillNotMove += pcr.ifthenelse(channelStorageForRouting < 0.0, channelStorageForRouting, 0.0) - channelStorageForRouting = pcr.max(0.000, channelStorageForRouting) + channelStorageThatWillNotMove += pcr.ifthenelse( + channelStorageForRouting < 0.0, channelStorageForRouting, 0.0 + ) + channelStorageForRouting = pcr.max(0.000, channelStorageForRouting) # update flood fraction and flood depth - self.inundatedFraction, self.floodDepth = self.returnInundationFractionAndFloodDepth(channelStorageForRouting) - + self.inundatedFraction, self.floodDepth = self.returnInundationFractionAndFloodDepth( + channelStorageForRouting + ) + # update dynamicFracWat: fraction of surface water bodies (dimensionless) including lakes and reservoirs # - lake and reservoir surface water fraction - self.dynamicFracWat = pcr.cover(\ - pcr.min(1.0, self.WaterBodies.fracWat), 0.0) - # - fraction of channel (including its excess above bankfull capacity) - self.dynamicFracWat += pcr.max(0.0, 1.0 - self.dynamicFracWat) * pcr.max(self.channelFraction, self.innundatedFraction) + self.dynamicFracWat = pcr.cover(pcr.min(1.0, self.WaterBodies.fracWat), 0.0) + # - fraction of channel (including its excess above bankfull capacity) + self.dynamicFracWat += pcr.max(0.0, 1.0 - self.dynamicFracWat) * pcr.max( + self.channelFraction, self.innundatedFraction + ) # - maximum value of dynamicFracWat is 1.0 - self.dynamicFracWat = pcr.ifthen(self.landmask, pcr.min(1.0, self.dynamicFracWat)) + self.dynamicFracWat = pcr.ifthen( + self.landmask, pcr.min(1.0, self.dynamicFracWat) + ) # estimate water_height for the next loop # - needed to estimate the channel wetted area (for the calculation of alpha and dischargeInitial) - self.water_height = channelStorageForRouting / (pcr.max(self.min_fracwat_for_water_height, self.dynamicFracWat) * self.cellArea) + self.water_height = channelStorageForRouting / ( + pcr.max(self.min_fracwat_for_water_height, self.dynamicFracWat) + * self.cellArea + ) # TODO: Check whether the usage of dynamicFracWat provides any problems? ####################################################################################################################### - + # evaporation (m/day) self.waterBodyEvaporation = water_body_evaporation_volume / self.cellArea - + # local input to surface water (m3) self.local_input_to_surface_water += acc_local_input_to_surface_water # channel discharge (m3/day) = self.Q self.Q = acc_discharge_volume - # return waterBodyStorage to channelStorage - channelStorageForRouting = self.return_water_body_storage_to_channel(channelStorageForRouting) + # return waterBodyStorage to channelStorage + channelStorageForRouting = self.return_water_body_storage_to_channel( + channelStorageForRouting + ) # updating channelStorage (after routing) self.channelStorage = channelStorageForRouting # return channelStorageThatWillNotMove to channelStorage: - self.channelStorage += channelStorageThatWillNotMove - + self.channelStorage += channelStorageThatWillNotMove + # channel discharge (m3/s): for current time step # self.discharge = self.Q / vos.secondsPerDay() - self.discharge = pcr.max(0., self.discharge) # reported channel discharge cannot be negative + self.discharge = pcr.max( + 0., self.discharge + ) # reported channel discharge cannot be negative self.discharge = pcr.ifthen(self.landmask, self.discharge) # - self.disChanWaterBody = pcr.ifthen(pcr.scalar(self.WaterBodies.waterBodyIds) > 0.,\ - pcr.areamaximum(self.discharge,self.WaterBodies.waterBodyIds)) + self.disChanWaterBody = pcr.ifthen( + pcr.scalar(self.WaterBodies.waterBodyIds) > 0., + pcr.areamaximum(self.discharge, self.WaterBodies.waterBodyIds), + ) self.disChanWaterBody = pcr.cover(self.disChanWaterBody, self.discharge) self.disChanWaterBody = pcr.ifthen(self.landmask, self.disChanWaterBody) # - self.disChanWaterBody = pcr.max(0.,self.disChanWaterBody) # reported channel discharge cannot be negative + self.disChanWaterBody = pcr.max( + 0., self.disChanWaterBody + ) # reported channel discharge cannot be negative # calculate the statistics of long and short term flow values self.calculate_statistics(groundwater) def calculate_statistics(self, groundwater): # short term average inflow (m3/s) and long term average outflow (m3/s) from lake and reservoirs - self.avgInflow = pcr.ifthen(self.landmask, pcr.cover(self.WaterBodies.avgInflow , 0.0)) - self.avgOutflow = pcr.ifthen(self.landmask, pcr.cover(self.WaterBodies.avgOutflow, 0.0)) + self.avgInflow = pcr.ifthen( + self.landmask, pcr.cover(self.WaterBodies.avgInflow, 0.0) + ) + self.avgOutflow = pcr.ifthen( + self.landmask, pcr.cover(self.WaterBodies.avgOutflow, 0.0) + ) # short term and long term average discharge (m3/s) # - see: online algorithm on http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance # # - long term average disharge # - dishargeUsed = pcr.max(0.0, self.discharge) - dishargeUsed = pcr.max(dishargeUsed, self.disChanWaterBody) + dishargeUsed = pcr.max(0.0, self.discharge) + dishargeUsed = pcr.max(dishargeUsed, self.disChanWaterBody) # - deltaAnoDischarge = dishargeUsed - self.avgDischarge - self.avgDischarge = self.avgDischarge +\ - deltaAnoDischarge/\ - pcr.min(self.maxTimestepsToAvgDischargeLong, self.timestepsToAvgDischarge) - self.avgDischarge = pcr.max(0.0, self.avgDischarge) - self.m2tDischarge = self.m2tDischarge + pcr.abs(deltaAnoDischarge*(dishargeUsed - self.avgDischarge)) + deltaAnoDischarge = dishargeUsed - self.avgDischarge + self.avgDischarge = self.avgDischarge + deltaAnoDischarge / pcr.min( + self.maxTimestepsToAvgDischargeLong, self.timestepsToAvgDischarge + ) + self.avgDischarge = pcr.max(0.0, self.avgDischarge) + self.m2tDischarge = self.m2tDischarge + pcr.abs( + deltaAnoDischarge * (dishargeUsed - self.avgDischarge) + ) # # - short term average disharge # - deltaAnoDischargeShort = dishargeUsed - self.avgDischargeShort - self.avgDischargeShort = self.avgDischargeShort +\ - deltaAnoDischargeShort/\ - pcr.min(self.maxTimestepsToAvgDischargeShort, self.timestepsToAvgDischarge) - self.avgDischargeShort = pcr.max(0.0, self.avgDischargeShort) + deltaAnoDischargeShort = dishargeUsed - self.avgDischargeShort + self.avgDischargeShort = ( + self.avgDischargeShort + + deltaAnoDischargeShort + / pcr.min( + self.maxTimestepsToAvgDischargeShort, self.timestepsToAvgDischarge + ) + ) + self.avgDischargeShort = pcr.max(0.0, self.avgDischargeShort) # long term average baseflow (m3/s) ; used as proxies for partitioning groundwater and surface water abstractions # baseflowM3PerSec = groundwater.baseflow * self.cellArea / vos.secondsPerDay() - deltaAnoBaseflow = baseflowM3PerSec - self.avgBaseflow - self.avgBaseflow = self.avgBaseflow +\ - deltaAnoBaseflow/\ - pcr.min(self.maxTimestepsToAvgDischargeLong, self.timestepsToAvgDischarge) + deltaAnoBaseflow = baseflowM3PerSec - self.avgBaseflow + self.avgBaseflow = self.avgBaseflow + deltaAnoBaseflow / pcr.min( + self.maxTimestepsToAvgDischargeLong, self.timestepsToAvgDischarge + ) self.avgBaseflow = pcr.max(0.0, self.avgBaseflow) def estimate_discharge_for_environmental_flow(self, channelStorage): # statistical assumptions: # - using z_score from the percentile 90 - z_score = 1.2816 - #~ # - using z_score from the percentile 95 - #~ z_score = 1.645 - + z_score = 1.2816 + # ~ # - using z_score from the percentile 95 + # ~ z_score = 1.645 + # long term variance and standard deviation of discharge values - varDischarge = self.m2tDischarge / \ - pcr.max(1.,\ - pcr.min(self.maxTimestepsToAvgDischargeLong, self.timestepsToAvgDischarge)-1.) - # see: online algorithm on http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance - stdDischarge = pcr.max(varDischarge**0.5, 0.0) - + varDischarge = self.m2tDischarge / pcr.max( + 1., + pcr.min(self.maxTimestepsToAvgDischargeLong, self.timestepsToAvgDischarge) + - 1., + ) + # see: online algorithm on http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance + stdDischarge = pcr.max(varDischarge ** 0.5, 0.0) + # calculate minimum discharge for environmental flow (m3/s) - minDischargeForEnvironmentalFlow = pcr.max(0.0, self.avgDischarge - z_score * stdDischarge) - factor = 0.10 # to avoid flip flop - minDischargeForEnvironmentalFlow = pcr.max(factor*self.avgDischarge, minDischargeForEnvironmentalFlow) # unit: m3/s - minDischargeForEnvironmentalFlow = pcr.max(0.0, minDischargeForEnvironmentalFlow) - + minDischargeForEnvironmentalFlow = pcr.max( + 0.0, self.avgDischarge - z_score * stdDischarge + ) + factor = 0.10 # to avoid flip flop + minDischargeForEnvironmentalFlow = pcr.max( + factor * self.avgDischarge, minDischargeForEnvironmentalFlow + ) # unit: m3/s + minDischargeForEnvironmentalFlow = pcr.max( + 0.0, minDischargeForEnvironmentalFlow + ) + return minDischargeForEnvironmentalFlow - - def estimate_available_volume_for_abstraction(self, channelStorage, length_of_time_step = vos.secondsPerDay()): + def estimate_available_volume_for_abstraction( + self, channelStorage, length_of_time_step=vos.secondsPerDay() + ): # input: channelStorage in m3 # estimate minimum discharge for environmental flow (m3/s) - minDischargeForEnvironmentalFlow = self.estimate_discharge_for_environmental_flow(channelStorage) + minDischargeForEnvironmentalFlow = self.estimate_discharge_for_environmental_flow( + channelStorage + ) # available channelStorage that can be extracted for surface water abstraction - readAvlChannelStorage = pcr.max(0.0,channelStorage) - + readAvlChannelStorage = pcr.max(0.0, channelStorage) + # reduce readAvlChannelStorage if the average discharge < minDischargeForEnvironmentalFlow - readAvlChannelStorage *= pcr.min(1.0,\ - vos.getValDivZero(pcr.max(0.0, pcr.min(self.avgDischargeShort, self.avgDischarge)), \ - minDischargeForEnvironmentalFlow, vos.smallNumber)) - + readAvlChannelStorage *= pcr.min( + 1.0, + vos.getValDivZero( + pcr.max(0.0, pcr.min(self.avgDischargeShort, self.avgDischarge)), + minDischargeForEnvironmentalFlow, + vos.smallNumber, + ), + ) + # maintaining environmental flow if average discharge > minDischargeForEnvironmentalFlow # TODO: Check why do we need this? - readAvlChannelStorage = pcr.ifthenelse(self.avgDischargeShort < minDischargeForEnvironmentalFlow, - readAvlChannelStorage, - pcr.max(readAvlChannelStorage, \ - pcr.max(0.0,\ - self.avgDischargeShort - minDischargeForEnvironmentalFlow)*length_of_time_step)) + readAvlChannelStorage = pcr.ifthenelse( + self.avgDischargeShort < minDischargeForEnvironmentalFlow, + readAvlChannelStorage, + pcr.max( + readAvlChannelStorage, + pcr.max(0.0, self.avgDischargeShort - minDischargeForEnvironmentalFlow) + * length_of_time_step, + ), + ) # maximum (precentage) of water can be abstracted from the channel - to avoid flip-flop maximum_percentage = 0.90 - readAvlChannelStorage = pcr.min(readAvlChannelStorage, \ - maximum_percentage*channelStorage) - readAvlChannelStorage = pcr.max(0.0,\ - readAvlChannelStorage) - + readAvlChannelStorage = pcr.min( + readAvlChannelStorage, maximum_percentage * channelStorage + ) + readAvlChannelStorage = pcr.max(0.0, readAvlChannelStorage) + # ignore small volume values - less than 0.1 m3 - readAvlChannelStorage = pcr.rounddown(readAvlChannelStorage*10.)/10. + readAvlChannelStorage = pcr.rounddown(readAvlChannelStorage * 10.) / 10. readAvlChannelStorage = pcr.ifthen(self.landmask, readAvlChannelStorage) - - return readAvlChannelStorage # unit: m3 - def initiate_old_style_routing_reporting(self,iniItems): + return readAvlChannelStorage # unit: m3 + def initiate_old_style_routing_reporting(self, iniItems): + self.report = True try: - self.outDailyTotNC = iniItems.get("routingOptions","outDailyTotNC").split(",") - self.outMonthTotNC = iniItems.get("routingOptions","outMonthTotNC").split(",") - self.outMonthAvgNC = iniItems.get("routingOptions","outMonthAvgNC").split(",") - self.outMonthEndNC = iniItems.get("routingOptions","outMonthEndNC").split(",") - self.outAnnuaTotNC = iniItems.get("routingOptions","outAnnuaTotNC").split(",") - self.outAnnuaAvgNC = iniItems.get("routingOptions","outAnnuaAvgNC").split(",") - self.outAnnuaEndNC = iniItems.get("routingOptions","outAnnuaEndNC").split(",") + self.outDailyTotNC = iniItems.get("routingOptions", "outDailyTotNC").split( + "," + ) + self.outMonthTotNC = iniItems.get("routingOptions", "outMonthTotNC").split( + "," + ) + self.outMonthAvgNC = iniItems.get("routingOptions", "outMonthAvgNC").split( + "," + ) + self.outMonthEndNC = iniItems.get("routingOptions", "outMonthEndNC").split( + "," + ) + self.outAnnuaTotNC = iniItems.get("routingOptions", "outAnnuaTotNC").split( + "," + ) + self.outAnnuaAvgNC = iniItems.get("routingOptions", "outAnnuaAvgNC").split( + "," + ) + self.outAnnuaEndNC = iniItems.get("routingOptions", "outAnnuaEndNC").split( + "," + ) except: self.report = False if self.report == True: # daily output in netCDF files: - #include self.outNCDir in wflow_pcrgobwb? - self.outNCDir = vos.getFullPath("netcdf/", \ - iniItems.get("globalOptions","outputDir")) #iniItems.outNCDir + # include self.outNCDir in wflow_pcrgobwb? + self.outNCDir = vos.getFullPath( + "netcdf/", iniItems.get("globalOptions", "outputDir") + ) # iniItems.outNCDir self.netcdfObj = PCR2netCDF(iniItems) # if self.outDailyTotNC[0] != "None": for var in self.outDailyTotNC: # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_dailyTot.nc",\ - var,"undefined") + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_dailyTot.nc", + var, + "undefined", + ) # MONTHly output in netCDF files: # - cummulative if self.outMonthTotNC[0] != "None": for var in self.outMonthTotNC: # initiating monthlyVarTot (accumulator variable): - vars(self)[var+'MonthTot'] = None + vars(self)[var + "MonthTot"] = None # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthTot.nc",\ - var,"undefined") + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthTot.nc", + var, + "undefined", + ) # - average if self.outMonthAvgNC[0] != "None": for var in self.outMonthAvgNC: # initiating monthlyTotAvg (accumulator variable) - vars(self)[var+'MonthTot'] = None + vars(self)[var + "MonthTot"] = None # initiating monthlyVarAvg: - vars(self)[var+'MonthAvg'] = None - # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthAvg.nc",\ - var,"undefined") + vars(self)[var + "MonthAvg"] = None + # creating the netCDF files: + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthAvg.nc", + var, + "undefined", + ) # - last day of the month if self.outMonthEndNC[0] != "None": for var in self.outMonthEndNC: - # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthEnd.nc",\ - var,"undefined") + # creating the netCDF files: + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthEnd.nc", + var, + "undefined", + ) # YEARly output in netCDF files: # - cummulative if self.outAnnuaTotNC[0] != "None": for var in self.outAnnuaTotNC: # initiating yearly accumulator variable: - vars(self)[var+'AnnuaTot'] = None + vars(self)[var + "AnnuaTot"] = None # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaTot.nc",\ - var,"undefined") + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaTot.nc", + var, + "undefined", + ) # - average if self.outAnnuaAvgNC[0] != "None": for var in self.outAnnuaAvgNC: # initiating annualyVarAvg: - vars(self)[var+'AnnuaAvg'] = None + vars(self)[var + "AnnuaAvg"] = None # initiating annualyTotAvg (accumulator variable) - vars(self)[var+'AnnuaTot'] = None - # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaAvg.nc",\ - var,"undefined") + vars(self)[var + "AnnuaTot"] = None + # creating the netCDF files: + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaAvg.nc", + var, + "undefined", + ) # - last day of the year if self.outAnnuaEndNC[0] != "None": for var in self.outAnnuaEndNC: - # creating the netCDF files: - self.netcdfObj.createNetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaEnd.nc",\ - var,"undefined") + # creating the netCDF files: + self.netcdfObj.createNetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaEnd.nc", + var, + "undefined", + ) - def old_style_routing_reporting(self,currTimeStep): + def old_style_routing_reporting(self, currTimeStep): if self.report == True: - timeStamp = datetime.datetime(currTimeStep.year,\ - currTimeStep.month,\ - currTimeStep.day,\ - 0) + timeStamp = datetime.datetime( + currTimeStep.year, currTimeStep.month, currTimeStep.day, 0 + ) # writing daily output to netcdf files timestepPCR = currTimeStep.timeStepPCR if self.outDailyTotNC[0] != "None": for var in self.outDailyTotNC: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_dailyTot.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var),vos.MV),\ - timeStamp,timestepPCR-1) + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_dailyTot.nc", + var, + pcr2numpy(self.__getattribute__(var), vos.MV), + timeStamp, + timestepPCR - 1, + ) # writing monthly output to netcdf files # -cummulative @@ -1795,54 +2439,59 @@ # introduce variables at the beginning of simulation or # reset variables at the beginning of the month - if currTimeStep.timeStepPCR == 1 or \ - currTimeStep.day == 1:\ - vars(self)[var+'MonthTot'] = pcr.scalar(0.0) + if currTimeStep.timeStepPCR == 1 or currTimeStep.day == 1: + vars(self)[var + "MonthTot"] = pcr.scalar(0.0) # accumulating - vars(self)[var+'MonthTot'] += vars(self)[var] + vars(self)[var + "MonthTot"] += vars(self)[var] # reporting at the end of the month: - if currTimeStep.endMonth == True: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthTot.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var+'MonthTot'),\ - vos.MV),timeStamp,currTimeStep.monthIdx-1) + if currTimeStep.endMonth == True: + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthTot.nc", + var, + pcr2numpy(self.__getattribute__(var + "MonthTot"), vos.MV), + timeStamp, + currTimeStep.monthIdx - 1, + ) # -average if self.outMonthAvgNC[0] != "None": for var in self.outMonthAvgNC: - # only if a accumulator variable has not been defined: - if var not in self.outMonthTotNC: + # only if a accumulator variable has not been defined: + if var not in self.outMonthTotNC: # introduce accumulator at the beginning of simulation or # reset accumulator at the beginning of the month - if currTimeStep.timeStepPCR == 1 or \ - currTimeStep.day == 1:\ - vars(self)[var+'MonthTot'] = pcr.scalar(0.0) + if currTimeStep.timeStepPCR == 1 or currTimeStep.day == 1: + vars(self)[var + "MonthTot"] = pcr.scalar(0.0) # accumulating - vars(self)[var+'MonthTot'] += vars(self)[var] + vars(self)[var + "MonthTot"] += vars(self)[var] # calculating average & reporting at the end of the month: if currTimeStep.endMonth == True: - vars(self)[var+'MonthAvg'] = vars(self)[var+'MonthTot']/\ - currTimeStep.day - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthAvg.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var+'MonthAvg'),\ - vos.MV),timeStamp,currTimeStep.monthIdx-1) + vars(self)[var + "MonthAvg"] = ( + vars(self)[var + "MonthTot"] / currTimeStep.day + ) + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthAvg.nc", + var, + pcr2numpy(self.__getattribute__(var + "MonthAvg"), vos.MV), + timeStamp, + currTimeStep.monthIdx - 1, + ) # # -last day of the month if self.outMonthEndNC[0] != "None": for var in self.outMonthEndNC: # reporting at the end of the month: - if currTimeStep.endMonth == True: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_monthEnd.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var),vos.MV),\ - timeStamp,currTimeStep.monthIdx-1) + if currTimeStep.endMonth == True: + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_monthEnd.nc", + var, + pcr2numpy(self.__getattribute__(var), vos.MV), + timeStamp, + currTimeStep.monthIdx - 1, + ) # writing yearly output to netcdf files # -cummulative @@ -1851,51 +2500,55 @@ # introduce variables at the beginning of simulation or # reset variables at the beginning of the month - if currTimeStep.timeStepPCR == 1 or \ - currTimeStep.doy == 1:\ - vars(self)[var+'AnnuaTot'] = pcr.scalar(0.0) + if currTimeStep.timeStepPCR == 1 or currTimeStep.doy == 1: + vars(self)[var + "AnnuaTot"] = pcr.scalar(0.0) # accumulating - vars(self)[var+'AnnuaTot'] += vars(self)[var] + vars(self)[var + "AnnuaTot"] += vars(self)[var] # reporting at the end of the year: - if currTimeStep.endYear == True: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaTot.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var+'AnnuaTot'),\ - vos.MV),timeStamp,currTimeStep.annuaIdx-1) + if currTimeStep.endYear == True: + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaTot.nc", + var, + pcr2numpy(self.__getattribute__(var + "AnnuaTot"), vos.MV), + timeStamp, + currTimeStep.annuaIdx - 1, + ) # -average if self.outAnnuaAvgNC[0] != "None": for var in self.outAnnuaAvgNC: - # only if a accumulator variable has not been defined: - if var not in self.outAnnuaTotNC: + # only if a accumulator variable has not been defined: + if var not in self.outAnnuaTotNC: # introduce accumulator at the beginning of simulation or # reset accumulator at the beginning of the year - if currTimeStep.timeStepPCR == 1 or \ - currTimeStep.doy == 1:\ - vars(self)[var+'AnnuaTot'] = pcr.scalar(0.0) + if currTimeStep.timeStepPCR == 1 or currTimeStep.doy == 1: + vars(self)[var + "AnnuaTot"] = pcr.scalar(0.0) # accumulating - vars(self)[var+'AnnuaTot'] += vars(self)[var] + vars(self)[var + "AnnuaTot"] += vars(self)[var] # # calculating average & reporting at the end of the year: if currTimeStep.endYear == True: - vars(self)[var+'AnnuaAvg'] = vars(self)[var+'AnnuaTot']/\ - currTimeStep.doy - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaAvg.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var+'AnnuaAvg'),\ - vos.MV),timeStamp,currTimeStep.annuaIdx-1) + vars(self)[var + "AnnuaAvg"] = ( + vars(self)[var + "AnnuaTot"] / currTimeStep.doy + ) + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaAvg.nc", + var, + pcr2numpy(self.__getattribute__(var + "AnnuaAvg"), vos.MV), + timeStamp, + currTimeStep.annuaIdx - 1, + ) # # -last day of the year if self.outAnnuaEndNC[0] != "None": for var in self.outAnnuaEndNC: # reporting at the end of the year: - if currTimeStep.endYear == True: - self.netcdfObj.data2NetCDF(str(self.outNCDir)+"/"+ \ - str(var)+"_annuaEnd.nc",\ - var,\ - pcr2numpy(self.__getattribute__(var),vos.MV),\ - timeStamp,currTimeStep.annuaIdx-1) - + if currTimeStep.endYear == True: + self.netcdfObj.data2NetCDF( + str(self.outNCDir) + "/" + str(var) + "_annuaEnd.nc", + var, + pcr2numpy(self.__getattribute__(var), vos.MV), + timeStamp, + currTimeStep.annuaIdx - 1, + ) Index: wflow-py/wflow/pcrglobwb/waterBodies.py =================================================================== diff -u -rbec706d676b364d4a89a4e7141382db4511fa485 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/pcrglobwb/waterBodies.py (.../waterBodies.py) (revision bec706d676b364d4a89a4e7141382db4511fa485) +++ wflow-py/wflow/pcrglobwb/waterBodies.py (.../waterBodies.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -29,576 +29,736 @@ import pcraster as pcr import logging -logger = logging.getLogger('wflow_pcrglobwb') +logger = logging.getLogger("wflow_pcrglobwb") + import virtualOS as vos from wflow.wf_DynamicFramework import configsection from wflow.wf_DynamicFramework import configget class WaterBodies(object): - - def __init__(self,iniItems,landmask,Dir,cloneMap,tmpDir): + def __init__(self, iniItems, landmask, Dir, cloneMap, tmpDir): object.__init__(self) # clone map file names, temporary directory and global/absolute path of input directory - self.cloneMap = cloneMap #iniItems.cloneMap - self.tmpDir = tmpDir #iniItems.tmpDir - self.inputDir = Dir #iniItems.globalOptions['inputDir'] + self.cloneMap = cloneMap # iniItems.cloneMap + self.tmpDir = tmpDir # iniItems.tmpDir + self.inputDir = Dir # iniItems.globalOptions['inputDir'] self.landmask = landmask - + # local drainage direction: - self.lddMap = vos.readPCRmapClone(iniItems.get("routingOptions","lddMap"), - self.cloneMap,self.tmpDir,self.inputDir,True) + self.lddMap = vos.readPCRmapClone( + iniItems.get("routingOptions", "lddMap"), + self.cloneMap, + self.tmpDir, + self.inputDir, + True, + ) self.lddMap = pcr.lddrepair(pcr.ldd(self.lddMap)) self.lddMap = pcr.lddrepair(self.lddMap) # option to activate water balance check self.debugWaterBalance = True - if configget(iniItems,"routingOptions","debugWaterBalance","True") == "False": + if ( + configget(iniItems, "routingOptions", "debugWaterBalance", "True") + == "False" + ): self.debugWaterBalance = False # option to perform a run with only natural lakes (without reservoirs) self.onlyNaturalWaterBodies = False - if "onlyNaturalWaterBodies" in iniItems._sections['routingOptions'] and configget(iniItems,"routingOptions","onlyNaturalWaterBodies","False") == "True": - logger.info("Using only natural water bodies identified in the year 1900. All reservoirs in 1900 are assumed as lakes.") - self.onlyNaturalWaterBodies = True - self.dateForNaturalCondition = "1900-01-01" # The run for a natural condition should access only this date. - + if ( + "onlyNaturalWaterBodies" in iniItems._sections["routingOptions"] + and configget(iniItems, "routingOptions", "onlyNaturalWaterBodies", "False") + == "True" + ): + logger.info( + "Using only natural water bodies identified in the year 1900. All reservoirs in 1900 are assumed as lakes." + ) + self.onlyNaturalWaterBodies = True + self.dateForNaturalCondition = ( + "1900-01-01" + ) # The run for a natural condition should access only this date. + # names of files containing water bodies parameters - if configget(iniItems,"routingOptions","waterBodyInputNC","None") == str(None): + if configget(iniItems, "routingOptions", "waterBodyInputNC", "None") == str( + None + ): self.useNetCDF = False - self.fracWaterInp = iniItems.get("routingOptions","fracWaterInp") - self.waterBodyIdsInp = iniItems.get("routingOptions","waterBodyIds") - self.waterBodyTypInp = iniItems.get("routingOptions","waterBodyTyp") - self.resMaxCapInp = iniItems.get("routingOptions","resMaxCapInp") - self.resSfAreaInp = iniItems.get("routingOptions","resSfAreaInp") + self.fracWaterInp = iniItems.get("routingOptions", "fracWaterInp") + self.waterBodyIdsInp = iniItems.get("routingOptions", "waterBodyIds") + self.waterBodyTypInp = iniItems.get("routingOptions", "waterBodyTyp") + self.resMaxCapInp = iniItems.get("routingOptions", "resMaxCapInp") + self.resSfAreaInp = iniItems.get("routingOptions", "resSfAreaInp") else: self.useNetCDF = True - self.ncFileInp = vos.getFullPath(\ - iniItems.get("routingOptions","waterBodyInputNC"),\ - self.inputDir) + self.ncFileInp = vos.getFullPath( + iniItems.get("routingOptions", "waterBodyInputNC"), self.inputDir + ) - # minimum width (m) used in the weir formula # TODO: define minWeirWidth based on the GLWD, GRanD database and/or bankfull discharge formula + # minimum width (m) used in the weir formula # TODO: define minWeirWidth based on the GLWD, GRanD database and/or bankfull discharge formula self.minWeirWidth = 10. - # lower and upper limits at which reservoir release is terminated and + # lower and upper limits at which reservoir release is terminated and # at which reservoir release is equal to long-term average outflow self.minResvrFrac = 0.10 self.maxResvrFrac = 0.75 - def getParameterFiles(self,currTimeStep,cellArea,ldd,\ - initial_condition_dictionary = None): + def getParameterFiles( + self, currTimeStep, cellArea, ldd, initial_condition_dictionary=None + ): - # parameters for Water Bodies: fracWat + # parameters for Water Bodies: fracWat # waterBodyIds # waterBodyOut - # waterBodyArea + # waterBodyArea # waterBodyTyp # waterBodyCap - + # cell surface area (m2) and ldd self.cellArea = cellArea ldd = pcr.ifthen(self.landmask, ldd) - + # date used for accessing/extracting water body information date_used = currTimeStep.fulldate year_used = currTimeStep.year if self.onlyNaturalWaterBodies == True: date_used = self.dateForNaturalCondition - year_used = self.dateForNaturalCondition[0:4] - + year_used = self.dateForNaturalCondition[0:4] + # fracWat = fraction of surface water bodies (dimensionless) self.fracWat = pcr.scalar(0.0) - + if self.useNetCDF: - self.fracWat = vos.netcdf2PCRobjClone(self.ncFileInp,'fracWaterInp', \ - date_used, useDoy = 'yearly',\ - cloneMapFileName = self.cloneMap) + self.fracWat = vos.netcdf2PCRobjClone( + self.ncFileInp, + "fracWaterInp", + date_used, + useDoy="yearly", + cloneMapFileName=self.cloneMap, + ) else: - self.fracWat = vos.readPCRmapClone(\ - self.fracWaterInp+str(year_used)+".map", - self.cloneMap,self.tmpDir,self.inputDir) - + self.fracWat = vos.readPCRmapClone( + self.fracWaterInp + str(year_used) + ".map", + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + self.fracWat = pcr.cover(self.fracWat, 0.0) - self.fracWat = pcr.max(0.0,self.fracWat) - self.fracWat = pcr.min(1.0,self.fracWat) - - self.waterBodyIds = pcr.nominal(0) # waterBody ids - self.waterBodyOut = pcr.boolean(0) # waterBody outlets - self.waterBodyArea = pcr.scalar(0.) # waterBody surface areas + self.fracWat = pcr.max(0.0, self.fracWat) + self.fracWat = pcr.min(1.0, self.fracWat) + self.waterBodyIds = pcr.nominal(0) # waterBody ids + self.waterBodyOut = pcr.boolean(0) # waterBody outlets + self.waterBodyArea = pcr.scalar(0.) # waterBody surface areas + # water body ids if self.useNetCDF: - self.waterBodyIds = vos.netcdf2PCRobjClone(self.ncFileInp,'waterBodyIds', \ - date_used, useDoy = 'yearly',\ - cloneMapFileName = self.cloneMap) + self.waterBodyIds = vos.netcdf2PCRobjClone( + self.ncFileInp, + "waterBodyIds", + date_used, + useDoy="yearly", + cloneMapFileName=self.cloneMap, + ) else: - self.waterBodyIds = vos.readPCRmapClone(\ - self.waterBodyIdsInp+str(year_used)+".map",\ - self.cloneMap,self.tmpDir,self.inputDir,False,None,True) + self.waterBodyIds = vos.readPCRmapClone( + self.waterBodyIdsInp + str(year_used) + ".map", + self.cloneMap, + self.tmpDir, + self.inputDir, + False, + None, + True, + ) # - self.waterBodyIds = pcr.ifthen(\ - pcr.scalar(self.waterBodyIds) > 0.,\ - pcr.nominal(self.waterBodyIds)) + self.waterBodyIds = pcr.ifthen( + pcr.scalar(self.waterBodyIds) > 0., pcr.nominal(self.waterBodyIds) + ) # water body outlets (correcting outlet positions) - wbCatchment = pcr.catchmenttotal(pcr.scalar(1),ldd) - self.waterBodyOut = pcr.ifthen(wbCatchment ==\ - pcr.areamaximum(wbCatchment, \ - self.waterBodyIds),\ - self.waterBodyIds) # = outlet ids - self.waterBodyOut = pcr.ifthen(\ - pcr.scalar(self.waterBodyIds) > 0.,\ - self.waterBodyOut) - # TODO: Please also consider endorheic lakes! + wbCatchment = pcr.catchmenttotal(pcr.scalar(1), ldd) + self.waterBodyOut = pcr.ifthen( + wbCatchment == pcr.areamaximum(wbCatchment, self.waterBodyIds), + self.waterBodyIds, + ) # = outlet ids + self.waterBodyOut = pcr.ifthen( + pcr.scalar(self.waterBodyIds) > 0., self.waterBodyOut + ) + # TODO: Please also consider endorheic lakes! # correcting water body ids - self.waterBodyIds = pcr.ifthen(\ - pcr.scalar(self.waterBodyIds) > 0.,\ - pcr.subcatchment(ldd,self.waterBodyOut)) - - # boolean map for water body outlets: - self.waterBodyOut = pcr.ifthen(\ - pcr.scalar(self.waterBodyOut) > 0.,\ - pcr.boolean(1)) + self.waterBodyIds = pcr.ifthen( + pcr.scalar(self.waterBodyIds) > 0., pcr.subcatchment(ldd, self.waterBodyOut) + ) + # boolean map for water body outlets: + self.waterBodyOut = pcr.ifthen( + pcr.scalar(self.waterBodyOut) > 0., pcr.boolean(1) + ) + # reservoir surface area (m2): if self.useNetCDF: - resSfArea = 1000. * 1000. * \ - vos.netcdf2PCRobjClone(self.ncFileInp,'resSfAreaInp', \ - date_used, useDoy = 'yearly',\ - cloneMapFileName = self.cloneMap) + resSfArea = ( + 1000. + * 1000. + * vos.netcdf2PCRobjClone( + self.ncFileInp, + "resSfAreaInp", + date_used, + useDoy="yearly", + cloneMapFileName=self.cloneMap, + ) + ) else: - resSfArea = 1000. * 1000. * vos.readPCRmapClone( - self.resSfAreaInp+str(year_used)+".map",\ - self.cloneMap,self.tmpDir,self.inputDir) - resSfArea = pcr.areaaverage(resSfArea,self.waterBodyIds) - resSfArea = pcr.cover(resSfArea,0.) + resSfArea = ( + 1000. + * 1000. + * vos.readPCRmapClone( + self.resSfAreaInp + str(year_used) + ".map", + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + ) + resSfArea = pcr.areaaverage(resSfArea, self.waterBodyIds) + resSfArea = pcr.cover(resSfArea, 0.) # water body surface area (m2): (lakes and reservoirs) - self.waterBodyArea = pcr.max(pcr.areatotal(\ - pcr.cover(\ - self.fracWat*self.cellArea, 0.0), self.waterBodyIds), - pcr.areaaverage(\ - pcr.cover(resSfArea, 0.0) , self.waterBodyIds)) - self.waterBodyArea = pcr.ifthen(self.waterBodyArea > 0.,\ - self.waterBodyArea) - + self.waterBodyArea = pcr.max( + pcr.areatotal( + pcr.cover(self.fracWat * self.cellArea, 0.0), self.waterBodyIds + ), + pcr.areaaverage(pcr.cover(resSfArea, 0.0), self.waterBodyIds), + ) + self.waterBodyArea = pcr.ifthen(self.waterBodyArea > 0., self.waterBodyArea) + # correcting water body ids and outlets (exclude all water bodies with surfaceArea = 0) - self.waterBodyIds = pcr.ifthen(self.waterBodyArea > 0., - self.waterBodyIds) - self.waterBodyOut = pcr.ifthen(pcr.boolean(self.waterBodyIds), - self.waterBodyOut) + self.waterBodyIds = pcr.ifthen(self.waterBodyArea > 0., self.waterBodyIds) + self.waterBodyOut = pcr.ifthen( + pcr.boolean(self.waterBodyIds), self.waterBodyOut + ) # water body types: # - 2 = reservoirs (regulated discharge) # - 1 = lakes (weirFormula) # - 0 = non lakes or reservoirs (e.g. wetland) self.waterBodyTyp = pcr.nominal(0) - + if self.useNetCDF: - self.waterBodyTyp = vos.netcdf2PCRobjClone(self.ncFileInp,'waterBodyTyp', \ - date_used, useDoy = 'yearly',\ - cloneMapFileName = self.cloneMap) + self.waterBodyTyp = vos.netcdf2PCRobjClone( + self.ncFileInp, + "waterBodyTyp", + date_used, + useDoy="yearly", + cloneMapFileName=self.cloneMap, + ) else: self.waterBodyTyp = vos.readPCRmapClone( - self.waterBodyTypInp+str(year_used)+".map",\ - self.cloneMap,self.tmpDir,self.inputDir,False,None,True) + self.waterBodyTypInp + str(year_used) + ".map", + self.cloneMap, + self.tmpDir, + self.inputDir, + False, + None, + True, + ) - # excluding wetlands (waterBodyTyp = 0) in all functions related to lakes/reservoirs + # excluding wetlands (waterBodyTyp = 0) in all functions related to lakes/reservoirs # - self.waterBodyTyp = pcr.ifthen(\ - pcr.scalar(self.waterBodyTyp) > 0,\ - pcr.nominal(self.waterBodyTyp)) - self.waterBodyTyp = pcr.ifthen(\ - pcr.scalar(self.waterBodyIds) > 0,\ - pcr.nominal(self.waterBodyTyp)) - self.waterBodyTyp = pcr.areamajority(self.waterBodyTyp,\ - self.waterBodyIds) # choose only one type: either lake or reservoir - self.waterBodyTyp = pcr.ifthen(\ - pcr.scalar(self.waterBodyTyp) > 0,\ - pcr.nominal(self.waterBodyTyp)) - self.waterBodyTyp = pcr.ifthen(pcr.boolean(self.waterBodyIds), - self.waterBodyTyp) + self.waterBodyTyp = pcr.ifthen( + pcr.scalar(self.waterBodyTyp) > 0, pcr.nominal(self.waterBodyTyp) + ) + self.waterBodyTyp = pcr.ifthen( + pcr.scalar(self.waterBodyIds) > 0, pcr.nominal(self.waterBodyTyp) + ) + self.waterBodyTyp = pcr.areamajority( + self.waterBodyTyp, self.waterBodyIds + ) # choose only one type: either lake or reservoir + self.waterBodyTyp = pcr.ifthen( + pcr.scalar(self.waterBodyTyp) > 0, pcr.nominal(self.waterBodyTyp) + ) + self.waterBodyTyp = pcr.ifthen( + pcr.boolean(self.waterBodyIds), self.waterBodyTyp + ) # correcting lakes and reservoirs ids and outlets - self.waterBodyIds = pcr.ifthen(pcr.scalar(self.waterBodyTyp) > 0, - self.waterBodyIds) - self.waterBodyOut = pcr.ifthen(pcr.scalar(self.waterBodyIds) > 0, - self.waterBodyOut) + self.waterBodyIds = pcr.ifthen( + pcr.scalar(self.waterBodyTyp) > 0, self.waterBodyIds + ) + self.waterBodyOut = pcr.ifthen( + pcr.scalar(self.waterBodyIds) > 0, self.waterBodyOut + ) # reservoir maximum capacity (m3): self.resMaxCap = pcr.scalar(0.0) self.waterBodyCap = pcr.scalar(0.0) if self.useNetCDF: - self.resMaxCap = 1000. * 1000. * \ - vos.netcdf2PCRobjClone(self.ncFileInp,'resMaxCapInp', \ - date_used, useDoy = 'yearly',\ - cloneMapFileName = self.cloneMap) + self.resMaxCap = ( + 1000. + * 1000. + * vos.netcdf2PCRobjClone( + self.ncFileInp, + "resMaxCapInp", + date_used, + useDoy="yearly", + cloneMapFileName=self.cloneMap, + ) + ) else: - self.resMaxCap = 1000. * 1000. * vos.readPCRmapClone(\ - self.resMaxCapInp+str(year_used)+".map", \ - self.cloneMap,self.tmpDir,self.inputDir) + self.resMaxCap = ( + 1000. + * 1000. + * vos.readPCRmapClone( + self.resMaxCapInp + str(year_used) + ".map", + self.cloneMap, + self.tmpDir, + self.inputDir, + ) + ) - self.resMaxCap = pcr.ifthen(self.resMaxCap > 0,\ - self.resMaxCap) - self.resMaxCap = pcr.areaaverage(self.resMaxCap,\ - self.waterBodyIds) - + self.resMaxCap = pcr.ifthen(self.resMaxCap > 0, self.resMaxCap) + self.resMaxCap = pcr.areaaverage(self.resMaxCap, self.waterBodyIds) + # water body capacity (m3): (lakes and reservoirs) - self.waterBodyCap = pcr.cover(self.resMaxCap,0.0) # Note: Most of lakes have capacities > 0. - self.waterBodyCap = pcr.ifthen(pcr.boolean(self.waterBodyIds), - self.waterBodyCap) - + self.waterBodyCap = pcr.cover( + self.resMaxCap, 0.0 + ) # Note: Most of lakes have capacities > 0. + self.waterBodyCap = pcr.ifthen( + pcr.boolean(self.waterBodyIds), self.waterBodyCap + ) + # correcting water body types: # Reservoirs that have zero capacities will be assumed as lakes. - self.waterBodyTyp = \ - pcr.ifthen(pcr.scalar(self.waterBodyTyp) > 0.,\ - self.waterBodyTyp) - self.waterBodyTyp = pcr.ifthenelse(self.waterBodyCap > 0.,\ - self.waterBodyTyp,\ - pcr.ifthenelse(pcr.scalar(self.waterBodyTyp) == 2,\ - pcr.nominal(1),\ - self.waterBodyTyp)) + self.waterBodyTyp = pcr.ifthen( + pcr.scalar(self.waterBodyTyp) > 0., self.waterBodyTyp + ) + self.waterBodyTyp = pcr.ifthenelse( + self.waterBodyCap > 0., + self.waterBodyTyp, + pcr.ifthenelse( + pcr.scalar(self.waterBodyTyp) == 2, pcr.nominal(1), self.waterBodyTyp + ), + ) # final corrections: - self.waterBodyTyp = pcr.ifthen(self.waterBodyArea > 0.,\ - self.waterBodyTyp) # make sure that all lakes and/or reservoirs have surface areas - self.waterBodyTyp = \ - pcr.ifthen(pcr.scalar(self.waterBodyTyp) > 0.,\ - self.waterBodyTyp) # make sure that only types 1 and 2 will be considered in lake/reservoir functions - self.waterBodyIds = pcr.ifthen(pcr.scalar(self.waterBodyTyp) > 0.,\ - self.waterBodyIds) # make sure that all lakes and/or reservoirs have ids - self.waterBodyOut = pcr.ifthen(pcr.scalar(self.waterBodyIds) > 0.,\ - self.waterBodyOut) # make sure that all lakes and/or reservoirs have outlets - - - # for a natural run (self.onlyNaturalWaterBodies == True) + self.waterBodyTyp = pcr.ifthen( + self.waterBodyArea > 0., self.waterBodyTyp + ) # make sure that all lakes and/or reservoirs have surface areas + self.waterBodyTyp = pcr.ifthen( + pcr.scalar(self.waterBodyTyp) > 0., self.waterBodyTyp + ) # make sure that only types 1 and 2 will be considered in lake/reservoir functions + self.waterBodyIds = pcr.ifthen( + pcr.scalar(self.waterBodyTyp) > 0., self.waterBodyIds + ) # make sure that all lakes and/or reservoirs have ids + self.waterBodyOut = pcr.ifthen( + pcr.scalar(self.waterBodyIds) > 0., self.waterBodyOut + ) # make sure that all lakes and/or reservoirs have outlets + + # for a natural run (self.onlyNaturalWaterBodies == True) # which uses only the year 1900, assume all reservoirs are lakes - if self.onlyNaturalWaterBodies == True and date_used == self.dateForNaturalCondition: - logger.info("Using only natural water bodies identified in the year 1900. All reservoirs in 1900 are assumed as lakes.") - self.waterBodyTyp = \ - pcr.ifthen(pcr.scalar(self.waterBodyTyp) > 0.,\ - pcr.nominal(1)) - + if ( + self.onlyNaturalWaterBodies == True + and date_used == self.dateForNaturalCondition + ): + logger.info( + "Using only natural water bodies identified in the year 1900. All reservoirs in 1900 are assumed as lakes." + ) + self.waterBodyTyp = pcr.ifthen( + pcr.scalar(self.waterBodyTyp) > 0., pcr.nominal(1) + ) + # check that all lakes and/or reservoirs have types, ids, surface areas and outlets: - test = pcr.defined(self.waterBodyTyp) & pcr.defined(self.waterBodyArea) &\ - pcr.defined(self.waterBodyIds) & pcr.boolean(pcr.areamaximum(pcr.scalar(self.waterBodyOut), self.waterBodyIds)) - a,b,c = vos.getMinMaxMean(pcr.cover(pcr.scalar(test), 1.0) - pcr.scalar(1.0)) + test = ( + pcr.defined(self.waterBodyTyp) + & pcr.defined(self.waterBodyArea) + & pcr.defined(self.waterBodyIds) + & pcr.boolean( + pcr.areamaximum(pcr.scalar(self.waterBodyOut), self.waterBodyIds) + ) + ) + a, b, c = vos.getMinMaxMean(pcr.cover(pcr.scalar(test), 1.0) - pcr.scalar(1.0)) threshold = 1e-3 if abs(a) > threshold or abs(b) > threshold: logger.warning("Missing information in some lakes and/or reservoirs.") # at the beginning of simulation period (timeStepPCR = 1) - # - we have to define/get the initial conditions + # - we have to define/get the initial conditions # if currTimeStep.timeStepPCR == 1: self.getICs(initial_condition_dictionary) - + # For each new reservoir (introduced at the beginning of the year) # initiating storage, average inflow and outflow # - self.waterBodyStorage = pcr.cover(self.waterBodyStorage,0.0) - self.avgInflow = pcr.cover(self.avgInflow ,0.0) - self.avgOutflow = pcr.cover(self.avgOutflow,0.0) + self.waterBodyStorage = pcr.cover(self.waterBodyStorage, 0.0) + self.avgInflow = pcr.cover(self.avgInflow, 0.0) + self.avgOutflow = pcr.cover(self.avgOutflow, 0.0) # cropping only in the landmask region: - self.fracWat = pcr.ifthen(self.landmask, self.fracWat ) - self.waterBodyIds = pcr.ifthen(self.landmask, self.waterBodyIds ) - self.waterBodyOut = pcr.ifthen(self.landmask, self.waterBodyOut ) - self.waterBodyArea = pcr.ifthen(self.landmask, self.waterBodyArea ) - self.waterBodyTyp = pcr.ifthen(self.landmask, self.waterBodyTyp ) - self.waterBodyCap = pcr.ifthen(self.landmask, self.waterBodyCap ) - self.waterBodyStorage = pcr.ifthen(self.landmask, self.waterBodyStorage) - self.avgInflow = pcr.ifthen(self.landmask, self.avgInflow ) - self.avgOutflow = pcr.ifthen(self.landmask, self.avgOutflow ) + self.fracWat = pcr.ifthen(self.landmask, self.fracWat) + self.waterBodyIds = pcr.ifthen(self.landmask, self.waterBodyIds) + self.waterBodyOut = pcr.ifthen(self.landmask, self.waterBodyOut) + self.waterBodyArea = pcr.ifthen(self.landmask, self.waterBodyArea) + self.waterBodyTyp = pcr.ifthen(self.landmask, self.waterBodyTyp) + self.waterBodyCap = pcr.ifthen(self.landmask, self.waterBodyCap) + self.waterBodyStorage = pcr.ifthen(self.landmask, self.waterBodyStorage) + self.avgInflow = pcr.ifthen(self.landmask, self.avgInflow) + self.avgOutflow = pcr.ifthen(self.landmask, self.avgOutflow) - def getICs(self,initial_condition): + def getICs(self, initial_condition): - avgInflow = initial_condition['avgLakeReservoirInflowShort'] - avgOutflow = initial_condition['avgLakeReservoirOutflowLong'] + avgInflow = initial_condition["avgLakeReservoirInflowShort"] + avgOutflow = initial_condition["avgLakeReservoirOutflowLong"] # - if not isinstance(initial_condition['waterBodyStorage'],types.NoneType): - # read directly - waterBodyStorage = initial_condition['waterBodyStorage'] + if not isinstance(initial_condition["waterBodyStorage"], types.NoneType): + # read directly + waterBodyStorage = initial_condition["waterBodyStorage"] else: # calculate waterBodyStorage at cells where lakes and/or reservoirs are defined # - storageAtLakeAndReservoirs = pcr.cover(\ - pcr.ifthen(pcr.scalar(self.waterBodyIds) > 0., initial_condition['channelStorage']), 0.0) + storageAtLakeAndReservoirs = pcr.cover( + pcr.ifthen( + pcr.scalar(self.waterBodyIds) > 0., + initial_condition["channelStorage"], + ), + 0.0, + ) # # - move only non negative values and use rounddown values - storageAtLakeAndReservoirs = pcr.max(0.00, pcr.rounddown(storageAtLakeAndReservoirs)) + storageAtLakeAndReservoirs = pcr.max( + 0.00, pcr.rounddown(storageAtLakeAndReservoirs) + ) # # lake and reservoir storages = waterBodyStorage (m3) ; values are given for the entire lake / reservoir cells - waterBodyStorage = pcr.ifthen(pcr.scalar(self.waterBodyIds) > 0., \ - pcr.areatotal(storageAtLakeAndReservoirs,\ - self.waterBodyIds)) - - self.avgInflow = pcr.cover(avgInflow , 0.0) # unit: m3/s - self.avgOutflow = pcr.cover(avgOutflow, 0.0) # unit: m3/s - self.waterBodyStorage = pcr.cover(waterBodyStorage, 0.0) # unit: m3 + waterBodyStorage = pcr.ifthen( + pcr.scalar(self.waterBodyIds) > 0., + pcr.areatotal(storageAtLakeAndReservoirs, self.waterBodyIds), + ) - self.avgInflow = pcr.ifthen(self.landmask, self.avgInflow) - self.avgOutflow = pcr.ifthen(self.landmask, self.avgOutflow) - self.waterBodyStorage = pcr.ifthen(self.landmask, self.waterBodyStorage) + self.avgInflow = pcr.cover(avgInflow, 0.0) # unit: m3/s + self.avgOutflow = pcr.cover(avgOutflow, 0.0) # unit: m3/s + self.waterBodyStorage = pcr.cover(waterBodyStorage, 0.0) # unit: m3 - def update(self,newStorageAtLakeAndReservoirs,\ - timestepsToAvgDischarge,\ - maxTimestepsToAvgDischargeShort,\ - maxTimestepsToAvgDischargeLong,\ - currTimeStep,\ - avgChannelDischarge,\ - length_of_time_step = vos.secondsPerDay(),\ - downstreamDemand = None): + self.avgInflow = pcr.ifthen(self.landmask, self.avgInflow) + self.avgOutflow = pcr.ifthen(self.landmask, self.avgOutflow) + self.waterBodyStorage = pcr.ifthen(self.landmask, self.waterBodyStorage) - if self.debugWaterBalance:\ - preStorage = self.waterBodyStorage # unit: m - - self.timestepsToAvgDischarge = timestepsToAvgDischarge # TODO: include this one in "currTimeStep" - + def update( + self, + newStorageAtLakeAndReservoirs, + timestepsToAvgDischarge, + maxTimestepsToAvgDischargeShort, + maxTimestepsToAvgDischargeLong, + currTimeStep, + avgChannelDischarge, + length_of_time_step=vos.secondsPerDay(), + downstreamDemand=None, + ): + + if self.debugWaterBalance: + preStorage = self.waterBodyStorage # unit: m + + self.timestepsToAvgDischarge = ( + timestepsToAvgDischarge + ) # TODO: include this one in "currTimeStep" + # obtain inflow (and update storage) - self.moveFromChannelToWaterBody(\ - newStorageAtLakeAndReservoirs,\ - timestepsToAvgDischarge,\ - maxTimestepsToAvgDischargeShort,\ - length_of_time_step) - + self.moveFromChannelToWaterBody( + newStorageAtLakeAndReservoirs, + timestepsToAvgDischarge, + maxTimestepsToAvgDischargeShort, + length_of_time_step, + ) + # calculate outflow (and update storage) - self.getWaterBodyOutflow(\ - maxTimestepsToAvgDischargeLong,\ - avgChannelDischarge,\ - length_of_time_step,\ - downstreamDemand) - - if self.debugWaterBalance:\ - vos.waterBalanceCheck([ pcr.cover(self.inflow/self.waterBodyArea,0.0)],\ - [pcr.cover(self.waterBodyOutflow/self.waterBodyArea,0.0)],\ - [ pcr.cover(preStorage/self.waterBodyArea,0.0)],\ - [pcr.cover(self.waterBodyStorage/self.waterBodyArea,0.0)],\ - 'WaterBodyStorage (unit: m)',\ - True,\ - currTimeStep.fulldate,threshold=5e-3) + self.getWaterBodyOutflow( + maxTimestepsToAvgDischargeLong, + avgChannelDischarge, + length_of_time_step, + downstreamDemand, + ) - def moveFromChannelToWaterBody(self,\ - newStorageAtLakeAndReservoirs,\ - timestepsToAvgDischarge,\ - maxTimestepsToAvgDischargeShort,\ - length_of_time_step = vos.secondsPerDay()): - + if self.debugWaterBalance: + vos.waterBalanceCheck( + [pcr.cover(self.inflow / self.waterBodyArea, 0.0)], + [pcr.cover(self.waterBodyOutflow / self.waterBodyArea, 0.0)], + [pcr.cover(preStorage / self.waterBodyArea, 0.0)], + [pcr.cover(self.waterBodyStorage / self.waterBodyArea, 0.0)], + "WaterBodyStorage (unit: m)", + True, + currTimeStep.fulldate, + threshold=5e-3, + ) + + def moveFromChannelToWaterBody( + self, + newStorageAtLakeAndReservoirs, + timestepsToAvgDischarge, + maxTimestepsToAvgDischargeShort, + length_of_time_step=vos.secondsPerDay(), + ): + # new lake and/or reservoir storages (m3) - newStorageAtLakeAndReservoirs = pcr.cover(\ - pcr.areatotal(newStorageAtLakeAndReservoirs,\ - self.waterBodyIds),0.0) + newStorageAtLakeAndReservoirs = pcr.cover( + pcr.areatotal(newStorageAtLakeAndReservoirs, self.waterBodyIds), 0.0 + ) # incoming volume (m3) self.inflow = newStorageAtLakeAndReservoirs - self.waterBodyStorage - + # inflowInM3PerSec (m3/s) inflowInM3PerSec = self.inflow / length_of_time_step - # updating (short term) average inflow (m3/s) ; + # updating (short term) average inflow (m3/s) ; # - needed to constrain lake outflow: # - temp = pcr.max(1.0, pcr.min(maxTimestepsToAvgDischargeShort, self.timestepsToAvgDischarge - 1.0 + length_of_time_step / vos.secondsPerDay())) - deltaInflow = inflowInM3PerSec - self.avgInflow - R = deltaInflow * ( length_of_time_step / vos.secondsPerDay() ) / temp - self.avgInflow = self.avgInflow + R + temp = pcr.max( + 1.0, + pcr.min( + maxTimestepsToAvgDischargeShort, + self.timestepsToAvgDischarge + - 1.0 + + length_of_time_step / vos.secondsPerDay(), + ), + ) + deltaInflow = inflowInM3PerSec - self.avgInflow + R = deltaInflow * (length_of_time_step / vos.secondsPerDay()) / temp + self.avgInflow = self.avgInflow + R self.avgInflow = pcr.max(0.0, self.avgInflow) # - # for the reference, see the "weighted incremental algorithm" in http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance + # for the reference, see the "weighted incremental algorithm" in http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance # updating waterBodyStorage (m3) self.waterBodyStorage = newStorageAtLakeAndReservoirs - def getWaterBodyOutflow(self,\ - maxTimestepsToAvgDischargeLong,\ - avgChannelDischarge,\ - length_of_time_step = vos.secondsPerDay(),\ - downstreamDemand = None): + def getWaterBodyOutflow( + self, + maxTimestepsToAvgDischargeLong, + avgChannelDischarge, + length_of_time_step=vos.secondsPerDay(), + downstreamDemand=None, + ): - # outflow in volume from water bodies with lake type (m3): - lakeOutflow = self.getLakeOutflow(avgChannelDischarge,length_of_time_step) - - # outflow in volume from water bodies with reservoir type (m3): - if isinstance(downstreamDemand, types.NoneType): downstreamDemand = pcr.scalar(0.0) - reservoirOutflow = self.getReservoirOutflow(avgChannelDischarge,length_of_time_step,downstreamDemand) + # outflow in volume from water bodies with lake type (m3): + lakeOutflow = self.getLakeOutflow(avgChannelDischarge, length_of_time_step) + # outflow in volume from water bodies with reservoir type (m3): + if isinstance(downstreamDemand, types.NoneType): + downstreamDemand = pcr.scalar(0.0) + reservoirOutflow = self.getReservoirOutflow( + avgChannelDischarge, length_of_time_step, downstreamDemand + ) + # outgoing/release volume from lakes and/or reservoirs - self.waterBodyOutflow = pcr.cover(reservoirOutflow, lakeOutflow) - + self.waterBodyOutflow = pcr.cover(reservoirOutflow, lakeOutflow) + # make sure that all water bodies have outflow: - self.waterBodyOutflow = pcr.max(0., - pcr.cover(self.waterBodyOutflow,0.0)) + self.waterBodyOutflow = pcr.max(0., pcr.cover(self.waterBodyOutflow, 0.0)) # limit outflow to available storage - factor = 0.25 # to avoid flip flop - self.waterBodyOutflow = pcr.min(self.waterBodyStorage * factor,\ - self.waterBodyOutflow) # unit: m3 - # use round values - self.waterBodyOutflow = pcr.rounddown(self.waterBodyOutflow/1.)*1. # unit: m3 - + factor = 0.25 # to avoid flip flop + self.waterBodyOutflow = pcr.min( + self.waterBodyStorage * factor, self.waterBodyOutflow + ) # unit: m3 + # use round values + self.waterBodyOutflow = ( + pcr.rounddown(self.waterBodyOutflow / 1.) * 1. + ) # unit: m3 + # outflow rate in m3 per sec - waterBodyOutflowInM3PerSec = self.waterBodyOutflow / length_of_time_step # unit: m3/s + waterBodyOutflowInM3PerSec = ( + self.waterBodyOutflow / length_of_time_step + ) # unit: m3/s - # updating (long term) average outflow (m3/s) ; + # updating (long term) average outflow (m3/s) ; # - needed to constrain/maintain reservoir outflow: # - temp = pcr.max(1.0, pcr.min(maxTimestepsToAvgDischargeLong, self.timestepsToAvgDischarge - 1.0 + length_of_time_step / vos.secondsPerDay())) - deltaOutflow = waterBodyOutflowInM3PerSec - self.avgOutflow - R = deltaOutflow * ( length_of_time_step / vos.secondsPerDay() ) / temp - self.avgOutflow = self.avgOutflow + R + temp = pcr.max( + 1.0, + pcr.min( + maxTimestepsToAvgDischargeLong, + self.timestepsToAvgDischarge + - 1.0 + + length_of_time_step / vos.secondsPerDay(), + ), + ) + deltaOutflow = waterBodyOutflowInM3PerSec - self.avgOutflow + R = deltaOutflow * (length_of_time_step / vos.secondsPerDay()) / temp + self.avgOutflow = self.avgOutflow + R self.avgOutflow = pcr.max(0.0, self.avgOutflow) # - # for the reference, see the "weighted incremental algorithm" in http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance + # for the reference, see the "weighted incremental algorithm" in http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance # update waterBodyStorage (after outflow): - self.waterBodyStorage = self.waterBodyStorage -\ - self.waterBodyOutflow - self.waterBodyStorage = pcr.max(0.0, self.waterBodyStorage) + self.waterBodyStorage = self.waterBodyStorage - self.waterBodyOutflow + self.waterBodyStorage = pcr.max(0.0, self.waterBodyStorage) - def weirFormula(self,waterHeight,weirWidth): # output: m3/s - sillElev = pcr.scalar(0.0) - weirCoef = pcr.scalar(1.0) - weirFormula = \ - (1.7*weirCoef*pcr.max(0,waterHeight-sillElev)**1.5) *\ - weirWidth # m3/s - return (weirFormula) + def weirFormula(self, waterHeight, weirWidth): # output: m3/s + sillElev = pcr.scalar(0.0) + weirCoef = pcr.scalar(1.0) + weirFormula = ( + 1.7 * weirCoef * pcr.max(0, waterHeight - sillElev) ** 1.5 + ) * weirWidth # m3/s + return weirFormula - def getLakeOutflow(self,\ - avgChannelDischarge,length_of_time_step = vos.secondsPerDay()): + def getLakeOutflow( + self, avgChannelDischarge, length_of_time_step=vos.secondsPerDay() + ): # waterHeight (m): temporary variable, a function of storage: - minWaterHeight = 0.001 # (m) Rens used 0.001 m as the limit # this is to make sure there is always lake outflow, - # but it will be still limited by available self.waterBodyStorage + minWaterHeight = ( + 0.001 + ) # (m) Rens used 0.001 m as the limit # this is to make sure there is always lake outflow, + # but it will be still limited by available self.waterBodyStorage waterHeight = pcr.cover( - pcr.max(minWaterHeight, \ - (self.waterBodyStorage - \ - pcr.cover(self.waterBodyCap, 0.0))/\ - self.waterBodyArea),0.) + pcr.max( + minWaterHeight, + (self.waterBodyStorage - pcr.cover(self.waterBodyCap, 0.0)) + / self.waterBodyArea, + ), + 0., + ) - # weirWidth (m) : + # weirWidth (m) : # - estimated from avgOutflow (m3/s) using the bankfull discharge formula - # + # avgOutflow = self.avgOutflow - avgOutflow = pcr.ifthenelse(\ - avgOutflow > 0.,\ - avgOutflow, - pcr.max(avgChannelDischarge,self.avgInflow,0.001)) # This is needed when new lakes/reservoirs introduced (its avgOutflow is still zero). - avgOutflow = pcr.areamaximum(avgOutflow,self.waterBodyIds) + avgOutflow = pcr.ifthenelse( + avgOutflow > 0., + avgOutflow, + pcr.max(avgChannelDischarge, self.avgInflow, 0.001), + ) # This is needed when new lakes/reservoirs introduced (its avgOutflow is still zero). + avgOutflow = pcr.areamaximum(avgOutflow, self.waterBodyIds) # - bankfullWidth = pcr.cover(\ - pcr.scalar(4.8) * \ - ((avgOutflow)**(0.5)),0.) + bankfullWidth = pcr.cover(pcr.scalar(4.8) * ((avgOutflow) ** (0.5)), 0.) weirWidthUsed = bankfullWidth - weirWidthUsed = pcr.max(weirWidthUsed,self.minWeirWidth) # TODO: minWeirWidth based on the GRanD database + weirWidthUsed = pcr.max( + weirWidthUsed, self.minWeirWidth + ) # TODO: minWeirWidth based on the GRanD database weirWidthUsed = pcr.cover( - pcr.ifthen(\ - pcr.scalar(self.waterBodyIds) > 0.,\ - weirWidthUsed),0.0) + pcr.ifthen(pcr.scalar(self.waterBodyIds) > 0., weirWidthUsed), 0.0 + ) # avgInflow <= lakeOutflow (weirFormula) <= waterBodyStorage - lakeOutflowInM3PerSec = pcr.max(\ - self.weirFormula(waterHeight,weirWidthUsed),\ - self.avgInflow) # unit: m3/s - + lakeOutflowInM3PerSec = pcr.max( + self.weirFormula(waterHeight, weirWidthUsed), self.avgInflow + ) # unit: m3/s + # estimate volume of water relased by lakes - lakeOutflow = lakeOutflowInM3PerSec * length_of_time_step # unit: m3 + lakeOutflow = lakeOutflowInM3PerSec * length_of_time_step # unit: m3 lakeOutflow = pcr.min(self.waterBodyStorage, lakeOutflow) # lakeOutflow = pcr.ifthen(pcr.scalar(self.waterBodyIds) > 0., lakeOutflow) lakeOutflow = pcr.ifthen(pcr.scalar(self.waterBodyTyp) == 1, lakeOutflow) - + # TODO: Consider endorheic lake/basin. No outflow for endorheic lake/basin! - return (lakeOutflow) + return lakeOutflow - def getReservoirOutflow(self,\ - avgChannelDischarge,length_of_time_step,downstreamDemand): + def getReservoirOutflow( + self, avgChannelDischarge, length_of_time_step, downstreamDemand + ): # avgOutflow (m3/s) avgOutflow = self.avgOutflow # The following is needed when new lakes/reservoirs introduced (its avgOutflow is still zero). - #~ # - alternative 1 - #~ avgOutflow = pcr.ifthenelse(\ - #~ avgOutflow > 0.,\ - #~ avgOutflow, - #~ pcr.max(avgChannelDischarge, self.avgInflow, 0.001)) + # ~ # - alternative 1 + # ~ avgOutflow = pcr.ifthenelse(\ + # ~ avgOutflow > 0.,\ + # ~ avgOutflow, + # ~ pcr.max(avgChannelDischarge, self.avgInflow, 0.001)) # - alternative 2 - avgOutflow = pcr.ifthenelse(\ - avgOutflow > 0.,\ - avgOutflow, - pcr.max(avgChannelDischarge, self.avgInflow)) - avgOutflow = pcr.ifthenelse(\ - avgOutflow > 0.,\ - avgOutflow, pcr.downstream(self.lddMap, avgOutflow)) - avgOutflow = pcr.areamaximum(avgOutflow,self.waterBodyIds) + avgOutflow = pcr.ifthenelse( + avgOutflow > 0., avgOutflow, pcr.max(avgChannelDischarge, self.avgInflow) + ) + avgOutflow = pcr.ifthenelse( + avgOutflow > 0., avgOutflow, pcr.downstream(self.lddMap, avgOutflow) + ) + avgOutflow = pcr.areamaximum(avgOutflow, self.waterBodyIds) - # calculate resvOutflow (m2/s) (based on reservoir storage and avgDischarge): + # calculate resvOutflow (m2/s) (based on reservoir storage and avgDischarge): # - using reductionFactor in such a way that: # - if relativeCapacity < minResvrFrac : release is terminated # - if relativeCapacity > maxResvrFrac : longterm average - reductionFactor = \ - pcr.cover(\ - pcr.min(1., - pcr.max(0., \ - self.waterBodyStorage - self.minResvrFrac*self.waterBodyCap)/\ - (self.maxResvrFrac - self.minResvrFrac)*self.waterBodyCap),0.0) + reductionFactor = pcr.cover( + pcr.min( + 1., + pcr.max( + 0., self.waterBodyStorage - self.minResvrFrac * self.waterBodyCap + ) + / (self.maxResvrFrac - self.minResvrFrac) + * self.waterBodyCap, + ), + 0.0, + ) # - resvOutflow = reductionFactor * avgOutflow * length_of_time_step # unit: m3 + resvOutflow = reductionFactor * avgOutflow * length_of_time_step # unit: m3 # maximum release <= average inflow (especially during dry condition) - resvOutflow = pcr.max(0, pcr.min(resvOutflow, self.avgInflow * length_of_time_step)) # unit: m3 + resvOutflow = pcr.max( + 0, pcr.min(resvOutflow, self.avgInflow * length_of_time_step) + ) # unit: m3 # downstream demand (m3/s) # reduce demand if storage < lower limit - reductionFactor = vos.getValDivZero(downstreamDemand, self.minResvrFrac*self.waterBodyCap, vos.smallNumber) - reductionFactor = pcr.cover(reductionFactor, 0.0) - downstreamDemand = pcr.min( - downstreamDemand, - downstreamDemand*reductionFactor) + reductionFactor = vos.getValDivZero( + downstreamDemand, self.minResvrFrac * self.waterBodyCap, vos.smallNumber + ) + reductionFactor = pcr.cover(reductionFactor, 0.0) + downstreamDemand = pcr.min(downstreamDemand, downstreamDemand * reductionFactor) # resvOutflow > downstreamDemand - resvOutflow = pcr.max(resvOutflow, downstreamDemand * length_of_time_step) # unit: m3 + resvOutflow = pcr.max( + resvOutflow, downstreamDemand * length_of_time_step + ) # unit: m3 # floodOutflow: additional release if storage > upper limit ratioQBankfull = 2.3 - estmStorage = pcr.max(0.,self.waterBodyStorage - resvOutflow) - floodOutflow = \ - pcr.max(0.0, estmStorage - self.waterBodyCap) +\ - pcr.cover(\ - pcr.max(0.0, estmStorage - self.maxResvrFrac*\ - self.waterBodyCap)/\ - ((1.-self.maxResvrFrac)*self.waterBodyCap),0.0)*\ - pcr.max(0.0,ratioQBankfull*avgOutflow* vos.secondsPerDay()-\ - resvOutflow) - floodOutflow = pcr.max(0.0, - pcr.min(floodOutflow,\ - estmStorage - self.maxResvrFrac*\ - self.waterBodyCap*0.75)) # maximum limit of floodOutflow: bring the reservoir storages only to 3/4 of upper limit capacities - + estmStorage = pcr.max(0., self.waterBodyStorage - resvOutflow) + floodOutflow = pcr.max(0.0, estmStorage - self.waterBodyCap) + pcr.cover( + pcr.max(0.0, estmStorage - self.maxResvrFrac * self.waterBodyCap) + / ((1. - self.maxResvrFrac) * self.waterBodyCap), + 0.0, + ) * pcr.max( + 0.0, ratioQBankfull * avgOutflow * vos.secondsPerDay() - resvOutflow + ) + floodOutflow = pcr.max( + 0.0, + pcr.min( + floodOutflow, estmStorage - self.maxResvrFrac * self.waterBodyCap * 0.75 + ), + ) # maximum limit of floodOutflow: bring the reservoir storages only to 3/4 of upper limit capacities + # update resvOutflow after floodOutflow - resvOutflow = pcr.cover(resvOutflow , 0.0) +\ - pcr.cover(floodOutflow, 0.0) + resvOutflow = pcr.cover(resvOutflow, 0.0) + pcr.cover(floodOutflow, 0.0) # maximum release if storage > upper limit : bring the reservoir storages only to 3/4 of upper limit capacities - resvOutflow = pcr.ifthenelse(self.waterBodyStorage > - self.maxResvrFrac*self.waterBodyCap,\ - pcr.min(resvOutflow,\ - pcr.max(0,self.waterBodyStorage - \ - self.maxResvrFrac*self.waterBodyCap*0.75)), - resvOutflow) + resvOutflow = pcr.ifthenelse( + self.waterBodyStorage > self.maxResvrFrac * self.waterBodyCap, + pcr.min( + resvOutflow, + pcr.max( + 0, + self.waterBodyStorage + - self.maxResvrFrac * self.waterBodyCap * 0.75, + ), + ), + resvOutflow, + ) # if storage > upper limit : resvOutflow > avgInflow - resvOutflow = pcr.ifthenelse(self.waterBodyStorage > - self.maxResvrFrac*self.waterBodyCap,\ - pcr.max(0.0, resvOutflow, self.avgInflow), - resvOutflow) - + resvOutflow = pcr.ifthenelse( + self.waterBodyStorage > self.maxResvrFrac * self.waterBodyCap, + pcr.max(0.0, resvOutflow, self.avgInflow), + resvOutflow, + ) + # resvOutflow < waterBodyStorage resvOutflow = pcr.min(self.waterBodyStorage, resvOutflow) - + resvOutflow = pcr.ifthen(pcr.scalar(self.waterBodyIds) > 0., resvOutflow) resvOutflow = pcr.ifthen(pcr.scalar(self.waterBodyTyp) == 2, resvOutflow) - return (resvOutflow) # unit: m3 + return resvOutflow # unit: m3 Index: wflow-py/wflow/reservoir_Sa.py =================================================================== diff -u -ra70af6fb5d306fffe3f818867365fe27ea19e27e -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/reservoir_Sa.py (.../reservoir_Sa.py) (revision a70af6fb5d306fffe3f818867365fe27ea19e27e) +++ wflow-py/wflow/reservoir_Sa.py (.../reservoir_Sa.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -19,45 +19,47 @@ from copy import copy as copylist try: - from wflow.wf_DynamicFramework import * + from wflow.wf_DynamicFramework import * except ImportError: - from wf_DynamicFramework import * + from wf_DynamicFramework import * import scipy import JarvisCoefficients + def selectSaR(i): """ not all functions are still in this file, the older functions can be found (with the same numbering) in h:\My Documents\memo's\python scripts\wflow\ """ if i == 1: - name = 'agriZone_Jarvis' + name = "agriZone_Jarvis" elif i == 2: - name = 'agriZone_Ep' + name = "agriZone_Ep" elif i == 3: - name = 'agriZone_Ep_Sa' + name = "agriZone_Ep_Sa" elif i == 4: - name = 'agriZone_Ep_Sa_cropG' + name = "agriZone_Ep_Sa_cropG" elif i == 5: - name = 'agriZone_Ep_Sa_cropG_beta' - elif i == 6: - name = 'agriZone_Ep_Sa_beta' + name = "agriZone_Ep_Sa_cropG_beta" + elif i == 6: + name = "agriZone_Ep_Sa_beta" elif i == 7: - name = 'agriZone_Ep_Sa_beta_frost' + name = "agriZone_Ep_Sa_beta_frost" elif i == 8: - name = 'agriZone_Ep_Sa_beta_Fvar' + name = "agriZone_Ep_Sa_beta_Fvar" elif i == 9: - name = 'agriZone_hourlyEp_Sa_beta_Fvar' + name = "agriZone_hourlyEp_Sa_beta_Fvar" elif i == 10: - name = 'agriZone_hourlyEp_Sa_beta_frost' + name = "agriZone_hourlyEp_Sa_beta_frost" elif i == 11: - name = 'agriZone_hourlyEp_Sa_beta_frostSamax' + name = "agriZone_hourlyEp_Sa_beta_frostSamax" elif i == 12: - name = 'agriZone_Ep_Sa_beta_frostSamax' + name = "agriZone_Ep_Sa_beta_frostSamax" elif i == 13: - name = 'agriZone_Ep_Sa_beta_frostSamax_surfTemp' + name = "agriZone_Ep_Sa_beta_frostSamax_surfTemp" return name + def agriZone_no_reservoir(self, k): """ This function is used when no unsaturated zone reservoir is used and only @@ -72,10 +74,17 @@ self.Ea_[k] = 0. self.Sa[k] = 0. self.Fa_[k] = max(self.Pe_[k], 0) - self.wbSa_[k] = self.Pe_[k] - self.Ea_[k] - self.Qa_[k] - self.Fa_[k] - self.Sa[k] + self.Sa_t[k] + self.wbSa_[k] = ( + self.Pe_[k] + - self.Ea_[k] + - self.Qa_[k] + - self.Fa_[k] + - self.Sa[k] + + self.Sa_t[k] + ) -def agriZone_Jarvis(self,k): +def agriZone_Jarvis(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on Jarvis stress functions @@ -85,32 +94,44 @@ - Qa u is determined from overflow from Sa - Code for ini-file: 1 """ - self.Qa = max(self.Pe - (self.samax[k] - self.Sa_t[k]),0) + self.Qa = max(self.Pe - (self.samax[k] - self.Sa_t[k]), 0) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) self.SaN = min(self.Sa[k] / self.samax2, 1) self.SuN = self.Su[k] / self.sumax[k] - - JarvisCoefficients.calcEu(self,k,1) #calculation of Ea based on Jarvis stress functions + + JarvisCoefficients.calcEu( + self, k, 1 + ) # calculation of Ea based on Jarvis stress functions self.Ea1 = self.Eu - - self.Fa1 = self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * self.SuN) + + self.Fa1 = self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** ( + -self.decF[k] * self.SuN + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 > 0 , self.Fa1 + self.Ea1 , 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 > 0 , self.Fa1 + self.Ea1 , 1)) * self.Sa_diff - self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) - self.Ea - self.Fa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Fa = ( + self.Fa1 + + (self.Fa1 / ifthenelse(self.Fa1 + self.Ea1 > 0, self.Fa1 + self.Ea1, 1)) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + (self.Ea1 / ifthenelse(self.Fa1 + self.Ea1 > 0, self.Fa1 + self.Ea1, 1)) + * self.Sa_diff + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) - self.Ea - self.Fa + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa self.Fa_[k] = self.Fa - -def agriZone_Ep(self,k): + +def agriZone_Ep(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -120,33 +141,46 @@ - Qa u is determined from overflow from Sa - Code for ini-file: 2 """ - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - - self.Qa = max(self.Pe - (self.samax[k] - self.Sa_t[k]),0) + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.Qa = max(self.Pe - (self.samax[k] - self.Sa_t[k]), 0) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) self.SaN = min(self.Sa[k] / self.samax2, 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax[k] * self.LP[k]),1) - - self.Fa1 = self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * self.SuN) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax[k] * self.LP[k]), 1 + ) + + self.Fa1 = self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** ( + -self.decF[k] * self.SuN + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 > 0 , self.Fa1 + self.Ea1 , 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 > 0 , self.Fa1 + self.Ea1 , 1)) * self.Sa_diff - self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) - self.Ea - self.Fa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Fa = ( + self.Fa1 + + (self.Fa1 / ifthenelse(self.Fa1 + self.Ea1 > 0, self.Fa1 + self.Ea1, 1)) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + (self.Ea1 / ifthenelse(self.Fa1 + self.Ea1 > 0, self.Fa1 + self.Ea1, 1)) + * self.Sa_diff + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) - self.Ea - self.Fa + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa self.Fa_[k] = self.Fa -def agriZone_Ep_Sa(self,k): + +def agriZone_Ep_Sa(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -157,34 +191,49 @@ - Fa is based on storage in Sa - Code for ini-file: 3 """ - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - - self.Qa = max(self.Pe - (self.samax[k] - self.Sa_t[k]),0) + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.Qa = max(self.Pe - (self.samax[k] - self.Sa_t[k]), 0) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) self.SaN = min(self.Sa[k] / self.samax2, 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax[k] * self.LP[k]),1) - - self.Fa1 = ifthenelse(self.SaN > 0,self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)),0) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax[k] * self.LP[k]), 1 + ) + + self.Fa1 = ifthenelse( + self.SaN > 0, + self.Fmin[k] + + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)), + 0, + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 > 0 , self.Fa1 + self.Ea1 , 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 > 0 , self.Fa1 + self.Ea1 , 1)) * self.Sa_diff - self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) - self.Ea - self.Fa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Fa = ( + self.Fa1 + + (self.Fa1 / ifthenelse(self.Fa1 + self.Ea1 > 0, self.Fa1 + self.Ea1, 1)) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + (self.Ea1 / ifthenelse(self.Fa1 + self.Ea1 > 0, self.Fa1 + self.Ea1, 1)) + * self.Sa_diff + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) - self.Ea - self.Fa + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa self.Fa_[k] = self.Fa - - -def agriZone_Ep_Sa_cropG(self,k): + + +def agriZone_Ep_Sa_cropG(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -195,36 +244,52 @@ - Fa is based on storage in Sa - Code for ini-file: 4 """ - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - - self.samax2 = self.samax[k] * self.cropG - self.Qaadd = max(self.Sa_t[k] - self.samax2,0) - - self.Qa = max(self.Pe - (self.samax2 - self.Sa_t[k]),0) + self.Qaadd + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.samax2 = self.samax[k] * self.cropG + self.Qaadd = max(self.Sa_t[k] - self.samax2, 0) + + self.Qa = max(self.Pe - (self.samax2 - self.Sa_t[k]), 0) + self.Qaadd self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) self.SaN = min(self.Sa[k] / self.samax2, 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax2 * self.LP[k]),1) - - self.Fa1 = ifthenelse(self.SaN > 0,self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)),0) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax2 * self.LP[k]), 1 + ) + + self.Fa1 = ifthenelse( + self.SaN > 0, + self.Fmin[k] + + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)), + 0, + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 > 0 , self.Fa1 + self.Ea1 , 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 > 0 , self.Fa1 + self.Ea1 , 1)) * self.Sa_diff - self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) - self.Ea - self.Fa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Fa = ( + self.Fa1 + + (self.Fa1 / ifthenelse(self.Fa1 + self.Ea1 > 0, self.Fa1 + self.Ea1, 1)) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + (self.Ea1 / ifthenelse(self.Fa1 + self.Ea1 > 0, self.Fa1 + self.Ea1, 1)) + * self.Sa_diff + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qa) - self.Ea - self.Fa + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa self.Fa_[k] = self.Fa - -def agriZone_Ep_Sa_cropG_beta(self,k): + + +def agriZone_Ep_Sa_cropG_beta(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -236,37 +301,73 @@ - Code for ini-file: 5 """ - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - - self.samax2 = self.samax[k] * self.cropG - self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2,0) - + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.samax2 = self.samax[k] * self.cropG + self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2, 0) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) self.SaN = min(self.Sa[k] / self.samax2, 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax2 * self.LP[k]),1) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax2 * self.LP[k]), 1 + ) self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - self.Fa1 = ifthenelse(self.SaN > 0,self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)),0) + self.Fa1 = ifthenelse( + self.SaN > 0, + self.Fmin[k] + + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)), + 0, + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff + self.Qa = ( + self.Qa1 + + ( + self.Qa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Fa = ( + self.Fa1 + + ( + self.Fa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + ( + self.Ea1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Fa - self.Qa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.wbSa_[k] = ( + self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] + ) + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa + self.Qaadd self.Fa_[k] = self.Fa - - -def agriZone_Ep_Sa_beta(self,k): + + +def agriZone_Ep_Sa_beta(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -278,36 +379,73 @@ - Code for ini-file: 6 """ - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + self.samax2 = self.samax[k] * scalar(self.catchArea) - self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2,0) - + self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2, 0) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) self.SaN = min(max(self.Sa[k] / self.samax2, 0), 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax2 * self.LP[k]),1) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax2 * self.LP[k]), 1 + ) self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - self.Fa1 = ifthenelse(self.SaN > 0,self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)),0) + self.Fa1 = ifthenelse( + self.SaN > 0, + self.Fmin[k] + + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)), + 0, + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff + self.Qa = ( + self.Qa1 + + ( + self.Qa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Fa = ( + self.Fa1 + + ( + self.Fa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + ( + self.Ea1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Fa - self.Qa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.wbSa_[k] = ( + self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] + ) + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa + self.Qaadd self.Fa_[k] = self.Fa -def agriZone_hourlyEp_Sa_beta(self,k): + +def agriZone_hourlyEp_Sa_beta(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -319,36 +457,73 @@ - Code for ini-file: """ - #JarvisCoefficients.calcEp(self,k) - #self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - + # JarvisCoefficients.calcEp(self,k) + # self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) + self.samax2 = self.samax[k] * scalar(self.catchArea) - self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2,0) - + self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2, 0) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) self.SaN = min(max(self.Sa[k] / self.samax2, 0), 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax2 * self.LP[k]),1) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax2 * self.LP[k]), 1 + ) self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - self.Fa1 = ifthenelse(self.SaN > 0,self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)),0) + self.Fa1 = ifthenelse( + self.SaN > 0, + self.Fmin[k] + + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)), + 0, + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff + self.Qa = ( + self.Qa1 + + ( + self.Qa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Fa = ( + self.Fa1 + + ( + self.Fa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + ( + self.Ea1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Fa - self.Qa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.wbSa_[k] = ( + self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] + ) + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa + self.Qaadd self.Fa_[k] = self.Fa - -def agriZone_Ep_Sa_beta_frost(self,k): + + +def agriZone_Ep_Sa_beta_frost(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -361,40 +536,88 @@ - Code for ini-file: 7 """ - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = self.EpHour - + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = self.EpHour + self.samax2 = self.samax[k] * scalar(self.catchArea) - self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2,0) - self.FrDur[k] = min(self.FrDur[k] + (self.Tmean - 273.15) / 86400 * self.timestepsecs * self.dayDeg[k], 0) - + self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2, 0) + self.FrDur[k] = min( + self.FrDur[k] + + (self.Tmean - 273.15) / 86400 * self.timestepsecs * self.dayDeg[k], + 0, + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) self.SaN = min(self.Sa[k] / self.samax2, 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax2 * self.LP[k]),1) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax2 * self.LP[k]), 1 + ) self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - self.Ft = min(max(self.FrDur[k] / (self.FrDur1[k] - self.FrDur0[k]) - self.FrDur0[k] / (self.FrDur1[k] - self.FrDur0[k]), 0), 1) - self.Fa1 = self.Ft * ifthenelse(self.SaN > 0,self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)),0) - + self.Ft = min( + max( + self.FrDur[k] / (self.FrDur1[k] - self.FrDur0[k]) + - self.FrDur0[k] / (self.FrDur1[k] - self.FrDur0[k]), + 0, + ), + 1, + ) + self.Fa1 = self.Ft * ifthenelse( + self.SaN > 0, + self.Fmin[k] + + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)), + 0, + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff + self.Qa = ( + self.Qa1 + + ( + self.Qa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Fa = ( + self.Fa1 + + ( + self.Fa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + ( + self.Ea1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Fa - self.Qa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.wbSa_[k] = ( + self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] + ) + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa + self.Qaadd self.Fa_[k] = self.Fa self.Ft_[k] = self.Ft - -def agriZone_hourlyEp_Sa_beta_frost(self,k): + + +def agriZone_hourlyEp_Sa_beta_frost(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -407,40 +630,87 @@ - Code for ini-file: 10 """ - #JarvisCoefficients.calcEp(self,k) - #self.PotEvaporation = self.EpHour - + # JarvisCoefficients.calcEp(self,k) + # self.PotEvaporation = self.EpHour + self.samax2 = self.samax[k] * scalar(self.catchArea) - self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2,0) - self.FrDur[k] = min(self.FrDur[k] + (self.Temperature) / 86400 * self.timestepsecs * self.dayDeg[k], 0) - + self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2, 0) + self.FrDur[k] = min( + self.FrDur[k] + (self.Temperature) / 86400 * self.timestepsecs * self.dayDeg[k], + 0, + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) self.SaN = min(self.Sa[k] / self.samax2, 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax2 * self.LP[k]),1) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax2 * self.LP[k]), 1 + ) self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - self.Ft = min(max(self.FrDur[k] / (self.FrDur1[k] - self.FrDur0[k]) - self.FrDur0[k] / (self.FrDur1[k] - self.FrDur0[k]), 0), 1) - self.Fa1 = self.Ft * ifthenelse(self.SaN > 0,self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)),0) - + self.Ft = min( + max( + self.FrDur[k] / (self.FrDur1[k] - self.FrDur0[k]) + - self.FrDur0[k] / (self.FrDur1[k] - self.FrDur0[k]), + 0, + ), + 1, + ) + self.Fa1 = self.Ft * ifthenelse( + self.SaN > 0, + self.Fmin[k] + + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)), + 0, + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff + self.Qa = ( + self.Qa1 + + ( + self.Qa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Fa = ( + self.Fa1 + + ( + self.Fa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + ( + self.Ea1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Fa - self.Qa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.wbSa_[k] = ( + self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] + ) + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa + self.Qaadd self.Fa_[k] = self.Fa self.Ft_[k] = self.Ft -def agriZone_hourlyEp_Sa_beta_frostSamax(self,k): + +def agriZone_hourlyEp_Sa_beta_frostSamax(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -453,42 +723,85 @@ - Code for ini-file: 11 """ - #JarvisCoefficients.calcEp(self,k) - #self.PotEvaporation = self.EpHour - - self.FrDur[k] = min(self.FrDur[k] + (self.Temperature) * self.dayDeg[k], 0) - self.Ft = min(max(self.FrDur[k] / (self.FrDur1[k] - self.FrDur0[k]) - self.FrDur0[k] / (self.FrDur1[k] - self.FrDur0[k]), 0.1), 1) - - + # JarvisCoefficients.calcEp(self,k) + # self.PotEvaporation = self.EpHour + + self.FrDur[k] = min(self.FrDur[k] + (self.Temperature) * self.dayDeg[k], 0) + self.Ft = min( + max( + self.FrDur[k] / (self.FrDur1[k] - self.FrDur0[k]) + - self.FrDur0[k] / (self.FrDur1[k] - self.FrDur0[k]), + 0.1, + ), + 1, + ) + self.samax2 = self.samax[k] * scalar(self.catchArea) * self.Ft - self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2,0) - + self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2, 0) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) self.SaN = min(self.Sa[k] / self.samax2, 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax2 * self.LP[k]),1) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax2 * self.LP[k]), 1 + ) self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - self.Fa1 = ifthenelse(self.SaN > 0,self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)),0) - + self.Fa1 = ifthenelse( + self.SaN > 0, + self.Fmin[k] + + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)), + 0, + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff + self.Qa = ( + self.Qa1 + + ( + self.Qa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Fa = ( + self.Fa1 + + ( + self.Fa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + ( + self.Ea1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Fa - self.Qa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.wbSa_[k] = ( + self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] + ) + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa + self.Qaadd self.Fa_[k] = self.Fa self.Ft_[k] = self.Ft - -def agriZone_Ep_Sa_beta_frostSamax(self,k): + + +def agriZone_Ep_Sa_beta_frostSamax(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -501,42 +814,93 @@ - Code for ini-file: 12 """ - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - - self.FrDur[k] = min(self.FrDur[k] + ifthenelse(self.Temperature > 0, self.ratFT[k] * self.Temperature, self.Temperature) * self.dayDeg[k], 0) - self.Ft = min(max(self.FrDur[k] / (self.FrDur1[k] - self.FrDur0[k]) - self.FrDur0[k] / (self.FrDur1[k] - self.FrDur0[k]), self.samin[k]), 1) - + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.FrDur[k] = min( + self.FrDur[k] + + ifthenelse( + self.Temperature > 0, self.ratFT[k] * self.Temperature, self.Temperature + ) + * self.dayDeg[k], + 0, + ) + self.Ft = min( + max( + self.FrDur[k] / (self.FrDur1[k] - self.FrDur0[k]) + - self.FrDur0[k] / (self.FrDur1[k] - self.FrDur0[k]), + self.samin[k], + ), + 1, + ) + self.samax2 = self.samax[k] * scalar(self.catchArea) * self.Ft - self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2,0) - + self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2, 0) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) self.SaN = min(self.Sa[k] / self.samax2, 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax2 * self.LP[k]),1) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax2 * self.LP[k]), 1 + ) self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - - self.Fa1 = ifthenelse(self.SaN > 0,self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)),0) - + + self.Fa1 = ifthenelse( + self.SaN > 0, + self.Fmin[k] + + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)), + 0, + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff + self.Qa = ( + self.Qa1 + + ( + self.Qa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Fa = ( + self.Fa1 + + ( + self.Fa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + ( + self.Ea1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Fa - self.Qa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.wbSa_[k] = ( + self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] + ) + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa + self.Qaadd self.Fa_[k] = self.Fa self.Ft_[k] = self.Ft -def agriZone_Ep_Sa_beta_frostSamax_surfTemp(self,k): + +def agriZone_Ep_Sa_beta_frostSamax_surfTemp(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -549,42 +913,91 @@ - Code for ini-file: 13 """ - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = self.EpHour - - self.FrDur[k] = min(self.FrDur[k] + ifthenelse(self.TempSurf > 0, self.ratFT[k] * self.TempSurf, self.TempSurf) * self.dayDeg[k], 0) - self.Ft = min(max(self.FrDur[k] / (self.FrDur1[k] - self.FrDur0[k]) - self.FrDur0[k] / (self.FrDur1[k] - self.FrDur0[k]), self.samin[k]), 1) - + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = self.EpHour + + self.FrDur[k] = min( + self.FrDur[k] + + ifthenelse(self.TempSurf > 0, self.ratFT[k] * self.TempSurf, self.TempSurf) + * self.dayDeg[k], + 0, + ) + self.Ft = min( + max( + self.FrDur[k] / (self.FrDur1[k] - self.FrDur0[k]) + - self.FrDur0[k] / (self.FrDur1[k] - self.FrDur0[k]), + self.samin[k], + ), + 1, + ) + self.samax2 = self.samax[k] * scalar(self.catchArea) * self.Ft - self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2,0) - + self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2, 0) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) self.SaN = min(self.Sa[k] / self.samax2, 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax2 * self.LP[k]),1) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax2 * self.LP[k]), 1 + ) self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - - self.Fa1 = ifthenelse(self.SaN > 0,self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)),0) - + + self.Fa1 = ifthenelse( + self.SaN > 0, + self.Fmin[k] + + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)), + 0, + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1)) * self.Sa_diff + self.Qa = ( + self.Qa1 + + ( + self.Qa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Fa = ( + self.Fa1 + + ( + self.Fa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + ( + self.Ea1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Fa - self.Qa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.wbSa_[k] = ( + self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] + ) + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa + self.Qaadd self.Fa_[k] = self.Fa self.Ft_[k] = self.Ft -def agriZone_Ep_Sa_beta_Fvar(self,k): + +def agriZone_Ep_Sa_beta_Fvar(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -596,36 +1009,73 @@ - Code for ini-file: 8 """ - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = self.EpHour - + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = self.EpHour + self.samax2 = self.samax[k] * scalar(self.catchArea) - self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2,0) - + self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2, 0) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) self.SaN = min(self.Sa[k] / self.samax2, 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax2 * self.LP[k]),1) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax2 * self.LP[k]), 1 + ) self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - self.Fa1 = self.cropG * ifthenelse(self.SaN > 0,self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)),0) + self.Fa1 = self.cropG * ifthenelse( + self.SaN > 0, + self.Fmin[k] + + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)), + 0, + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff + self.Qa = ( + self.Qa1 + + ( + self.Qa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Fa = ( + self.Fa1 + + ( + self.Fa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + ( + self.Ea1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Fa - self.Qa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.wbSa_[k] = ( + self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] + ) + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa + self.Qaadd self.Fa_[k] = self.Fa - -def agriZone_hourlyEp_Sa_beta_Fvar(self,k): + + +def agriZone_hourlyEp_Sa_beta_Fvar(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on LP @@ -637,31 +1087,67 @@ - Code for ini-file: 9 """ -# JarvisCoefficients.calcEp(self,k) -# self.PotEvaporation = self.EpHour - + # JarvisCoefficients.calcEp(self,k) + # self.PotEvaporation = self.EpHour + self.samax2 = self.samax[k] * scalar(self.catchArea) - self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2,0) - + self.Qaadd = max(self.Sa_t[k] + self.Pe - self.samax2, 0) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) self.SaN = min(self.Sa[k] / self.samax2, 1) self.SuN = self.Su[k] / self.sumax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax2 * self.LP[k]),1) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax2 * self.LP[k]), 1 + ) self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - self.Fa1 = self.cropG * ifthenelse(self.SaN > 0,self.Fmin[k] + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)),0) + self.Fa1 = self.cropG * ifthenelse( + self.SaN > 0, + self.Fmin[k] + + (self.Fmax[k] - self.Fmin[k]) * e ** (-self.decF[k] * (1 - self.SaN)), + 0, + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Fa1 - self.Ea1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff - self.Fa = self.Fa1 + (self.Fa1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff - self.Ea = self.Ea1 + (self.Ea1/ifthenelse(self.Fa1 + self.Ea1 + self.Qa1 > 0 , self.Fa1 + self.Ea1 + self.Qa1 , 1)) * self.Sa_diff + self.Qa = ( + self.Qa1 + + ( + self.Qa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Fa = ( + self.Fa1 + + ( + self.Fa1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) + self.Ea = ( + self.Ea1 + + ( + self.Ea1 + / ifthenelse( + self.Fa1 + self.Ea1 + self.Qa1 > 0, self.Fa1 + self.Ea1 + self.Qa1, 1 + ) + ) + * self.Sa_diff + ) self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Fa - self.Qa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] - + self.wbSa_[k] = ( + self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa - self.Sa[k] + self.Sa_t[k] + ) + self.Ea_[k] = self.Ea self.Qa_[k] = self.Qa + self.Qaadd - self.Fa_[k] = self.Fa \ No newline at end of file + self.Fa_[k] = self.Fa Index: wflow-py/wflow/reservoir_Sf.py =================================================================== diff -u -r7b48705d1cccb33e056124b90d698a474c3e656e -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/reservoir_Sf.py (.../reservoir_Sf.py) (revision 7b48705d1cccb33e056124b90d698a474c3e656e) +++ wflow-py/wflow/reservoir_Sf.py (.../reservoir_Sf.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -12,22 +12,24 @@ from copy import copy as copylist try: - from wflow.wf_DynamicFramework import * + from wflow.wf_DynamicFramework import * except ImportError: - from wf_DynamicFramework import * + from wf_DynamicFramework import * import scipy + def selectSfR(i): """ not all functions are still in this file, the older functions can be found (with the same numbering) in h:\My Documents\memo's\python scripts\wflow\ """ if i == 1: - name = 'fastRunoff_lag' + name = "fastRunoff_lag" if i == 2: - name = 'fastRunoff_lag2' + name = "fastRunoff_lag2" return name + def fastRunoff_no_reservoir(self, k): """ This function is used when no unsaturated zone reservoir is used and only @@ -39,7 +41,8 @@ self.Qf_[k] = self.Qfin_[k] self.Sf_[k] = 0. self.wbSf_[k] = self.Qfin_[k] - self.Qf_[k] - self.Sf[k] + self.Sf_t[k] - + + def fastAgriRunoff_no_reservoir(self, k): """ This function is used when no unsaturated zone reservoir is used and only @@ -50,9 +53,17 @@ self.Qfa_[k] = self.Qa_[k] self.Sfa[k] = 0. - self.wbSfa_[k] = self.Qfa_[k] - self.Qfa_[k] - self.Sfa[k] + self.Sfa_t[k] - sum(self.convQa[k]) + sum(self.convQa_t[k]) + self.wbSfa_[k] = ( + self.Qfa_[k] + - self.Qfa_[k] + - self.Sfa[k] + + self.Sfa_t[k] + - sum(self.convQa[k]) + + sum(self.convQa_t[k]) + ) -#@profile + +# @profile def fastRunoff_lag2(self, k): """ - Lag is applied before inflow into the fast reservoir @@ -64,45 +75,64 @@ """ if self.FR_L: - self.Qu = areatotal(self.Qu_[k] * self.percentArea ,nominal(self.TopoId)) + self.Qu = areatotal(self.Qu_[k] * self.percentArea, nominal(self.TopoId)) else: self.Qu = self.Qu_[k] - + self.Qfin = (1 - self.D[k]) * self.Qu - - if self.D[k] < 1.00: + + if self.D[k] < 1.00: if self.convQu[k]: self.QfinLag = self.convQu[k][-1] - self.Qf = self.Sf[k] * self.Kf[k] + self.Qf = self.Sf[k] * self.Kf[k] self.Sf[k] = self.Sf[k] + self.QfinLag - self.Qf - - self.convQu[k].insert(0, 0 * scalar(self.catchArea)) #convolution Qu for following time steps + + self.convQu[k].insert( + 0, 0 * scalar(self.catchArea) + ) # convolution Qu for following time steps self.Tfmap = self.Tf[k] * scalar(self.catchArea) del self.convQu[k][-1] - temp = [self.convQu[k][i] + (2/self.Tfmap-2/(self.Tfmap*(self.Tfmap+1))*(self.Tfmap-i))*self.Qfin for i in range(len(self.convQu[k]))] + temp = [ + self.convQu[k][i] + + ( + 2 / self.Tfmap + - 2 / (self.Tfmap * (self.Tfmap + 1)) * (self.Tfmap - i) + ) + * self.Qfin + for i in range(len(self.convQu[k])) + ] self.convQu[k] = temp - -# self.Qfin_[k] = self.Qfin -# self.Qfinput_[k] = self.QfinLag - + + # self.Qfin_[k] = self.Qfin + # self.Qfinput_[k] = self.QfinLag + else: - self.Qf = self.Sf[k] * self.Kf[k] + self.Qf = self.Sf[k] * self.Kf[k] self.Sf[k] = self.Sf[k] + self.Qfin - self.Qf - -# self.Qfin_[k] = self.Qfin -# self.Qfinput_[k] = self.Qfin + + # self.Qfin_[k] = self.Qfin + # self.Qfinput_[k] = self.Qfin else: self.Qf = self.ZeroMap self.Qfinput_[k] = self.ZeroMap self.Qfin_[k] = self.ZeroMap - self.wbSf_[k] = self.Qfin - self.Qf - self.Sf[k] + self.Sf_t[k] - sum(self.convQu[k]) + sum(self.convQu_t[k]) - + self.wbSf_[k] = ( + self.Qfin + - self.Qf + - self.Sf[k] + + self.Sf_t[k] + - sum(self.convQu[k]) + + sum(self.convQu_t[k]) + ) + self.Qf_[k] = self.Qf + + # self.QuA_[k] = self.Qu -def fastRunoff_lag_forAgri_combined(self,k): +def fastRunoff_lag_forAgri_combined(self, k): """ - Lag is applied before inflow into the fast reservoir - Lag formula is derived from Fenicia (2011) @@ -114,43 +144,58 @@ """ if self.FR_L: - self.Qu = areatotal(self.Qu_[k] * self.percentArea ,nominal(self.TopoId)) - self.Qa = areatotal(self.Qa_[k] * self.percentArea ,nominal(self.TopoId)) + self.Qu = areatotal(self.Qu_[k] * self.percentArea, nominal(self.TopoId)) + self.Qa = areatotal(self.Qa_[k] * self.percentArea, nominal(self.TopoId)) else: self.Qu = self.Qu_[k] self.Qa = self.Qa_[k] - + self.Qfin = (1 - self.D[k]) * self.Qu + self.Qa - - if self.D[k] < 1.00: + if self.D[k] < 1.00: if self.convQu[k]: self.QfinLag = self.convQu[k][-1] - self.Qf = self.Sf[k] * self.Kf[k] + self.Qf = self.Sf[k] * self.Kf[k] self.Sf[k] = self.Sf[k] + self.QfinLag - self.Qf - - self.convQu[k].insert(0, 0 * scalar(self.catchArea)) #convolution Qu for following time steps + + self.convQu[k].insert( + 0, 0 * scalar(self.catchArea) + ) # convolution Qu for following time steps self.Tfmap = self.Tf[k] * scalar(self.catchArea) del self.convQu[k][-1] - temp = [self.convQu[k][i] + (2/self.Tfmap-2/(self.Tfmap*(self.Tfmap+1))*(self.Tfmap-i))*self.Qfin for i in range(len(self.convQu[k]))] + temp = [ + self.convQu[k][i] + + ( + 2 / self.Tfmap + - 2 / (self.Tfmap * (self.Tfmap + 1)) * (self.Tfmap - i) + ) + * self.Qfin + for i in range(len(self.convQu[k])) + ] self.convQu[k] = temp - - + else: - self.Qf = self.Sf[k] * self.Kf[k] + self.Qf = self.Sf[k] * self.Kf[k] self.Sf[k] = self.Sf[k] + self.Qfin - self.Qf - - else: + else: self.Qf = self.ZeroMap self.Qfinput_[k] = self.ZeroMap self.Qfin_[k] = self.ZeroMap - self.wbSf_[k] = self.Qfin - self.Qf - self.Sf[k] + self.Sf_t[k] - sum(self.convQu[k]) + sum(self.convQu_t[k]) - + self.wbSf_[k] = ( + self.Qfin + - self.Qf + - self.Sf[k] + + self.Sf_t[k] + - sum(self.convQu[k]) + + sum(self.convQu_t[k]) + ) + self.Qf_[k] = self.Qf - -def fastRunoff_lag_agriDitch(self,k): + + +def fastRunoff_lag_agriDitch(self, k): """ - Lag is applied before inflow into the fast reservoir - Lag formula is derived from Fenicia (2011) @@ -162,40 +207,54 @@ """ if self.FR_L: - self.Qa = areatotal(self.Qa_[k] * self.percentArea ,nominal(self.TopoId)) + self.Qa = areatotal(self.Qa_[k] * self.percentArea, nominal(self.TopoId)) else: self.Qa = self.Qa_[k] - + self.Qfain = self.Qa -# commented on 4 August 2015, as the output of this reservoir should not depent on the value of D -# if self.D[k] < 1.00: + # commented on 4 August 2015, as the output of this reservoir should not depent on the value of D + # if self.D[k] < 1.00: if self.convQa[k]: self.QfainLag = self.convQa[k][-1] - self.Qfa = self.Sfa[k] * self.Kfa[k] + self.Qfa = self.Sfa[k] * self.Kfa[k] self.Sfa[k] = self.Sfa[k] + self.QfainLag - self.Qfa - - self.convQa[k].insert(0, 0 * scalar(self.catchArea)) #convolution Qu for following time steps + + self.convQa[k].insert( + 0, 0 * scalar(self.catchArea) + ) # convolution Qu for following time steps self.Tfmap = self.Tfa[k] * scalar(self.catchArea) del self.convQa[k][-1] - temp = [self.convQa[k][i] + (2/self.Tfmap-2/(self.Tfmap*(self.Tfmap+1))*(self.Tfmap-i))*self.Qfain for i in range(len(self.convQa[k]))] + temp = [ + self.convQa[k][i] + + (2 / self.Tfmap - 2 / (self.Tfmap * (self.Tfmap + 1)) * (self.Tfmap - i)) + * self.Qfain + for i in range(len(self.convQa[k])) + ] self.convQa[k] = temp - - + else: - self.Qfa = self.Sfa[k] * self.Kfa[k] + self.Qfa = self.Sfa[k] * self.Kfa[k] self.Sfa[k] = self.Sfa[k] + self.Qfain - self.Qfa - -# commented on 4 August 2015, as the output of this reservoir should not depent on the value of D -# else: -# self.Qfa = self.ZeroMap -# self.Qfain_[k] = self.ZeroMap - self.wbSfa_[k] = self.Qfain - self.Qfa - self.Sfa[k] + self.Sfa_t[k] - sum(self.convQa[k]) + sum(self.convQa_t[k]) - + # commented on 4 August 2015, as the output of this reservoir should not depent on the value of D + # else: + # self.Qfa = self.ZeroMap + # self.Qfain_[k] = self.ZeroMap + + self.wbSfa_[k] = ( + self.Qfain + - self.Qfa + - self.Sfa[k] + + self.Sfa_t[k] + - sum(self.convQa[k]) + + sum(self.convQa_t[k]) + ) + self.Qfa_[k] = self.Qfa - -def fastRunoff_lag_agriDitch_reInfilt(self,k): + + +def fastRunoff_lag_agriDitch_reInfilt(self, k): """ - Lag is applied before inflow into the fast reservoir - Lag formula is derived from Fenicia (2011) @@ -207,83 +266,129 @@ """ if self.FR_L: - self.Qa = areatotal(self.Qa_[k] * self.percentArea ,nominal(self.TopoId)) + self.Qa = areatotal(self.Qa_[k] * self.percentArea, nominal(self.TopoId)) else: self.Qa = self.Qa_[k] - + self.Qfain = self.Qa - + if self.convQa[k]: self.QfainLag = self.convQa[k][-1] - self.Qfa = self.Sfa[k] * self.Kfa[k] + self.Qfa = self.Sfa[k] * self.Kfa[k] self.Percfa = ifthenelse(self.Ft_[k] == 1, self.Sfa[k] * self.perc[k] * 200, 0) self.Sfa[k] = self.Sfa[k] + self.QfainLag - self.Qfa - self.Percfa - - self.convQa[k].insert(0, 0 * scalar(self.catchArea)) #convolution Qu for following time steps + + self.convQa[k].insert( + 0, 0 * scalar(self.catchArea) + ) # convolution Qu for following time steps self.Tfmap = self.Tfa[k] * scalar(self.catchArea) del self.convQa[k][-1] - temp = [self.convQa[k][i] + (2/self.Tfmap-2/(self.Tfmap*(self.Tfmap+1))*(self.Tfmap-i))*self.Qfain for i in range(len(self.convQa[k]))] + temp = [ + self.convQa[k][i] + + (2 / self.Tfmap - 2 / (self.Tfmap * (self.Tfmap + 1)) * (self.Tfmap - i)) + * self.Qfain + for i in range(len(self.convQa[k])) + ] self.convQa[k] = temp - - + else: - self.Qfa = self.Sfa[k] * self.Kfa[k] - self.Percfa = ifthenelse(self.Ft_[k] == 1, self.Sfa[k] * self.perc[k] * 200, 0) + self.Qfa = self.Sfa[k] * self.Kfa[k] + self.Percfa = ifthenelse(self.Ft_[k] == 1, self.Sfa[k] * self.perc[k] * 200, 0) self.Sfa[k] = self.Sfa[k] + self.Qfain - self.Qfa - self.Percfa - - self.wbSfa_[k] = self.Qfain - self.Qfa - self.Sfa[k] + self.Sfa_t[k] - sum(self.convQa[k]) + sum(self.convQa_t[k]) - self.Percfa - + + self.wbSfa_[k] = ( + self.Qfain + - self.Qfa + - self.Sfa[k] + + self.Sfa_t[k] + - sum(self.convQa[k]) + + sum(self.convQa_t[k]) + - self.Percfa + ) + self.Qfa_[k] = self.Qfa self.Percfa_[k] = self.Percfa - -def routingQf_combined(self): + + +def routingQf_combined(self): """ - Routing of fluxes from fast reservoir - Qf is devided over the reservoir numbers for the timesteps matching with the average travel time for a calcultation cell """ - - if nansum(pcr2numpy(self.Transit,NaN)) > 0: + + if nansum(pcr2numpy(self.Transit, NaN)) > 0: self.Qflag = self.trackQ[0] # first bucket is transferred to outlet - self.trackQ.append(0 * scalar(self.catchArea)) # add new bucket for present time step + self.trackQ.append( + 0 * scalar(self.catchArea) + ) # add new bucket for present time step del self.trackQ[0] # remove first bucket (transferred to outlet) - temp = [self.trackQ[i] + ifthenelse(rounddown(self.Transit) == i*scalar(self.catchArea), - (self.Transit - i*scalar(self.catchArea)) * self.Qftotal / 1000 * self.surfaceArea, - ifthenelse(roundup(self.Transit) == i*scalar(self.catchArea), - (i*scalar(self.catchArea) - self.Transit) * self.Qftotal / 1000 * self.surfaceArea, 0)) for i in range(len(self.trackQ))] - self.trackQ = temp - + temp = [ + self.trackQ[i] + + ifthenelse( + rounddown(self.Transit) == i * scalar(self.catchArea), + (self.Transit - i * scalar(self.catchArea)) + * self.Qftotal + / 1000 + * self.surfaceArea, + ifthenelse( + roundup(self.Transit) == i * scalar(self.catchArea), + (i * scalar(self.catchArea) - self.Transit) + * self.Qftotal + / 1000 + * self.surfaceArea, + 0, + ), + ) + for i in range(len(self.trackQ)) + ] + self.trackQ = temp + else: self.Qflag = self.Qftotal - - self.wbSfrout = self.Qftotal - self.Qflag - sum(self.trackQ) + sum (self.trackQ_t) - + + self.wbSfrout = self.Qftotal - self.Qflag - sum(self.trackQ) + sum(self.trackQ_t) + self.Qflag_ = self.Qflag - - self.Qtlag = self.Qflag_ / self.timestepsecs + self.Qs_ / 1000 * self.surfaceArea / self.timestepsecs - self.QLagTot = areatotal(self.Qtlag, nominal(self.TopoId)) # catchment total runoff with looptijd - + self.Qtlag = ( + self.Qflag_ / self.timestepsecs + + self.Qs_ / 1000 * self.surfaceArea / self.timestepsecs + ) + self.QLagTot = areatotal( + self.Qtlag, nominal(self.TopoId) + ) # catchment total runoff with looptijd + + def routingQf_Qs_grid(self): """ - Routing of both Qf and Qs - based on a velocity map """ self.Qtot = self.Qftotal + self.Qs_ # total local discharge in mm/hour - self.Qtotal = self.Qtot / 1000 * self.surfaceArea / self.timestepsecs # total local discharge in m3/s + self.Qtotal = ( + self.Qtot / 1000 * self.surfaceArea / self.timestepsecs + ) # total local discharge in m3/s self.QtotNoRout = accuflux(self.TopoLdd, self.Qtotal) self.Qstate_t = self.Qstate self.Qtest = self.Qstate + self.Qtotal - self.Qrout = accutraveltimeflux(self.TopoLdd, self.Qstate + self.Qtotal, self.velocity) - self.Qstate = accutraveltimestate(self.TopoLdd, self.Qstate + self.Qtotal, self.velocity) - + self.Qrout = accutraveltimeflux( + self.TopoLdd, self.Qstate + self.Qtotal, self.velocity + ) + self.Qstate = accutraveltimestate( + self.TopoLdd, self.Qstate + self.Qtotal, self.velocity + ) + self.Qtlag = self.Qrout self.QLagTot = self.Qrout - + # water balance of flux routing - self.dSdt = self.Qstate-self.Qstate_t - self.WB_rout = (accuflux(self.TopoLdd, self.Qtotal - self.dSdt)-self.Qrout)/accuflux(self.TopoLdd, self.Qtotal) - + self.dSdt = self.Qstate - self.Qstate_t + self.WB_rout = ( + accuflux(self.TopoLdd, self.Qtotal - self.dSdt) - self.Qrout + ) / accuflux(self.TopoLdd, self.Qtotal) + + def routingQf_Qs_grid_mm(self): """ - Routing of both Qf and Qs @@ -294,38 +399,62 @@ self.QtotNoRout = accuflux(self.TopoLdd, self.Qtotal) self.Qstate_t = self.Qstate self.Qtest = self.Qstate + self.Qtotal - self.Qrout = accutraveltimeflux(self.TopoLdd, self.Qstate + self.Qtotal, self.velocity) - self.Qstate = accutraveltimestate(self.TopoLdd, self.Qstate + self.Qtotal, self.velocity) - + self.Qrout = accutraveltimeflux( + self.TopoLdd, self.Qstate + self.Qtotal, self.velocity + ) + self.Qstate = accutraveltimestate( + self.TopoLdd, self.Qstate + self.Qtotal, self.velocity + ) + self.Qtlag = self.Qrout self.QLagTot = self.Qrout - + # water balance of flux routing - self.dSdt = self.Qstate-self.Qstate_t - self.WB_rout = (accuflux(self.TopoLdd, self.Qtotal - self.dSdt)-self.Qrout)/accuflux(self.TopoLdd, self.Qtotal) - + self.dSdt = self.Qstate - self.Qstate_t + self.WB_rout = ( + accuflux(self.TopoLdd, self.Qtotal - self.dSdt) - self.Qrout + ) / accuflux(self.TopoLdd, self.Qtotal) + + def kinematic_wave_routing(self): self.Qtot = self.Qftotal + self.Qs_ # total local discharge in mm/hour - self.Qtotal = self.Qtot / 1000 * self.surfaceArea / self.timestepsecs # total local discharge in m3/s + self.Qtotal = ( + self.Qtot / 1000 * self.surfaceArea / self.timestepsecs + ) # total local discharge in m3/s # self.Qstate_t = self.Qstate - self.Qtotal = max(0, self.Qtotal) # no neg kin wave -- check ! TODO - q=self.Qtotal/self.DCL - self.OldSurfaceRunoff=self.Qstate + self.Qtotal = max(0, self.Qtotal) # no neg kin wave -- check ! TODO + q = self.Qtotal / self.DCL + self.OldSurfaceRunoff = self.Qstate - self.Qstate = kinematic(self.TopoLdd, self.Qstate,q,self.Alpha, self.Beta,self.Tslice,self.timestepsecs,self.DCL) # m3/s + self.Qstate = kinematic( + self.TopoLdd, + self.Qstate, + q, + self.Alpha, + self.Beta, + self.Tslice, + self.timestepsecs, + self.DCL, + ) # m3/s - self.SurfaceRunoffMM=self.Qstate*self.QMMConv # SurfaceRunoffMM (mm) from SurfaceRunoff (m3/s) + self.SurfaceRunoffMM = ( + self.Qstate * self.QMMConv + ) # SurfaceRunoffMM (mm) from SurfaceRunoff (m3/s) self.QLagTot = self.Qstate self.Qtlag = self.Qstate self.updateRunOff() - InflowKinWaveCell=upstream(self.TopoLdd,self.Qstate) - self.MassBalKinWave = (self.KinWaveVolume - self.OldKinWaveVolume)/self.timestepsecs + InflowKinWaveCell + self.Qtotal - self.Qstate + InflowKinWaveCell = upstream(self.TopoLdd, self.Qstate) + self.MassBalKinWave = ( + (self.KinWaveVolume - self.OldKinWaveVolume) / self.timestepsecs + + InflowKinWaveCell + + self.Qtotal + - self.Qstate + ) - self.Qstate_t = self.OldKinWaveVolume /self.timestepsecs + self.Qstate_t = self.OldKinWaveVolume / self.timestepsecs self.Qstate_new = self.KinWaveVolume / self.timestepsecs - Runoff=self.Qstate - + Runoff = self.Qstate Index: wflow-py/wflow/reservoir_Si.py =================================================================== diff -u -rad5e049f1419c25bc30c20d2d0e1bcc56dcb4381 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/reservoir_Si.py (.../reservoir_Si.py) (revision ad5e049f1419c25bc30c20d2d0e1bcc56dcb4381) +++ wflow-py/wflow/reservoir_Si.py (.../reservoir_Si.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -11,9 +11,9 @@ from copy import copy as copylist try: - from wflow.wf_DynamicFramework import * + from wflow.wf_DynamicFramework import * except ImportError: - from wf_DynamicFramework import * + from wf_DynamicFramework import * import JarvisCoefficients @@ -23,13 +23,14 @@ (with the same numbering) in h:\My Documents\memo's\python scripts\wflow\ """ if i == 1: - name = 'interception_overflow' + name = "interception_overflow" if i == 2: - name = 'interception_overflow2' + name = "interception_overflow2" if i == 3: - name = 'interception_overflow_Ep' + name = "interception_overflow_Ep" return name + def interception_no_reservoir(self, k): """ Effective rainfall = rainfall @@ -39,63 +40,84 @@ self.Pe_[k] = max(self.Precipitation, 0) self.Ei_[k] = 0. self.Si_[k] = 0. - self.wbSi_[k] = self.Precipitation - self.Ei_[k] - self.Pe_[k] - self.Si[k] + self.Si_t[k] + self.wbSi_[k] = ( + self.Precipitation - self.Ei_[k] - self.Pe_[k] - self.Si[k] + self.Si_t[k] + ) + def interception_overflow2(self, k): """ - Effective rainfall is all that does not fit into the interception reservoir - Outgoing fluxes are determined separately - Code for ini-file: 2 """ - - self.Pe = max(self.Precipitation - (self.imax[k] - self.Si_t[k]),0) + + self.Pe = max(self.Precipitation - (self.imax[k] - self.Si_t[k]), 0) self.Si[k] = self.Si_t[k] + (self.Precipitation - self.Pe) - self.Ei = ifthenelse(self.Sw[k] == 0, min(self.PotEvaporation, self.Si[k]), 0) #ifstatement added on 3-11-2015 for snow module - self.Si[k] = self.Si[k] - self.Ei - - self.wbSi_[k] = self.Precipitation - self.Ei - self.Pe - self.Si[k] + self.Si_t[k] - - self.Pe = self.Pe + self.Qw_[k] #added on 3-11-2015 for snow module - self.Ei = self.Ei + (self.Ew_[k] / self.lamda * self.lamdaS) #lambda added on 31-3-2016 - - self.Ei_[k]=self.Ei - self.Pe_[k]=self.Pe - self.PotEvaporation_ = self.PotEvaporation - + self.Ei = ifthenelse( + self.Sw[k] == 0, min(self.PotEvaporation, self.Si[k]), 0 + ) # ifstatement added on 3-11-2015 for snow module + self.Si[k] = self.Si[k] - self.Ei + + self.wbSi_[k] = self.Precipitation - self.Ei - self.Pe - self.Si[k] + self.Si_t[k] + + self.Pe = self.Pe + self.Qw_[k] # added on 3-11-2015 for snow module + self.Ei = self.Ei + ( + self.Ew_[k] / self.lamda * self.lamdaS + ) # lambda added on 31-3-2016 + + self.Ei_[k] = self.Ei + self.Pe_[k] = self.Pe + self.PotEvaporation_ = self.PotEvaporation + if self.URFR_L: - self.Ei = areatotal(self.Ei * self.percentArea, nominal(self.TopoId)) - self.Pe = areatotal(self.Pe * self.percentArea, nominal(self.TopoId)) - self.PotEvaporation = areatotal(self.PotEvaporation * self.percentArea, nominal(self.TopoId)) - self.Si[k] = areatotal(self.Si[k] * self.percentArea, nominal(self.TopoId)) + self.Ei = areatotal(self.Ei * self.percentArea, nominal(self.TopoId)) + self.Pe = areatotal(self.Pe * self.percentArea, nominal(self.TopoId)) + self.PotEvaporation = areatotal( + self.PotEvaporation * self.percentArea, nominal(self.TopoId) + ) + self.Si[k] = areatotal(self.Si[k] * self.percentArea, nominal(self.TopoId)) -def interception_overflow_Ep(self,k): +def interception_overflow_Ep(self, k): """ - Effective rainfall is all that does not fit into the interception reservoir - Outgoing fluxes are determined separately - this version cannot be run with Su averaged (for the current code) - Code for ini-file: 3 """ - JarvisCoefficients.calcEp(self,k) #this line indicates that hourly profiles are made out of daily pot evap data based on start day (DS.tss) and day end (DE) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - - self.Pe = max(self.Precipitation - (self.imax[k] - self.Si_t[k]),0) + JarvisCoefficients.calcEp( + self, k + ) # this line indicates that hourly profiles are made out of daily pot evap data based on start day (DS.tss) and day end (DE) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.Pe = max(self.Precipitation - (self.imax[k] - self.Si_t[k]), 0) self.Si[k] = self.Si_t[k] + (self.Precipitation - self.Pe) - self.Ei = ifthenelse(self.Sw[k] == 0, min((self.PotEvaporation - (self.Ew_[k] / self.lamda * self.lamdaS)), self.Si[k]), 0) #ifstatement added on 3-11-2015 for snow module, '-self.Ew_[k]' added on 17-2-2016 - self.Si[k] = self.Si[k] - self.Ei - - self.wbSi_[k] = self.Precipitation - self.Ei - self.Pe - self.Si[k] + self.Si_t[k] - - self.Pe = self.Pe + self.Qw_[k] #added on 3-11-2015 for snow module - self.Ei = self.Ei + (self.Ew_[k] / self.lamda * self.lamdaS) #lambda added on 17-2-2016 - - self.Ei_[k]=self.Ei - self.Pe_[k]=self.Pe - self.Ep_[k]=self.EpHour - + self.Ei = ifthenelse( + self.Sw[k] == 0, + min( + (self.PotEvaporation - (self.Ew_[k] / self.lamda * self.lamdaS)), self.Si[k] + ), + 0, + ) # ifstatement added on 3-11-2015 for snow module, '-self.Ew_[k]' added on 17-2-2016 + self.Si[k] = self.Si[k] - self.Ei + + self.wbSi_[k] = self.Precipitation - self.Ei - self.Pe - self.Si[k] + self.Si_t[k] + + self.Pe = self.Pe + self.Qw_[k] # added on 3-11-2015 for snow module + self.Ei = self.Ei + ( + self.Ew_[k] / self.lamda * self.lamdaS + ) # lambda added on 17-2-2016 + + self.Ei_[k] = self.Ei + self.Pe_[k] = self.Pe + self.Ep_[k] = self.EpHour + if self.URFR_L: - self.Ei = areatotal(self.Ei * self.percentArea, nominal(self.TopoId)) - self.Pe = areatotal(self.Pe * self.percentArea, nominal(self.TopoId)) - self.PotEvaporation = areatotal(self.PotEvaporation * self.percentArea, nominal(self.TopoId)) - self.Si[k] = areatotal(self.Si[k] * self.percentArea, nominal(self.TopoId)) \ No newline at end of file + self.Ei = areatotal(self.Ei * self.percentArea, nominal(self.TopoId)) + self.Pe = areatotal(self.Pe * self.percentArea, nominal(self.TopoId)) + self.PotEvaporation = areatotal( + self.PotEvaporation * self.percentArea, nominal(self.TopoId) + ) + self.Si[k] = areatotal(self.Si[k] * self.percentArea, nominal(self.TopoId)) Index: wflow-py/wflow/reservoir_Ss.py =================================================================== diff -u -r9aacf70d29eac315b5782685f8b1ec1bbc91c984 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/reservoir_Ss.py (.../reservoir_Ss.py) (revision 9aacf70d29eac315b5782685f8b1ec1bbc91c984) +++ wflow-py/wflow/reservoir_Ss.py (.../reservoir_Ss.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -15,11 +15,12 @@ from copy import copy as copylist try: - from wflow.wf_DynamicFramework import * + from wflow.wf_DynamicFramework import * except ImportError: - from wf_DynamicFramework import * + from wf_DynamicFramework import * import scipy + def groundWater_no_reservoir(self): """ Recharge = Qu * D (per class) @@ -28,41 +29,55 @@ """ - self.Recharge = [x*y for x,y in zip(self.Qu_, self.D)] - self.QsinClass = [a+b-c for a,b,c in zip(self.Recharge, self.Perc_, self.Cap_)] # all fluxes are summed per class - self.QsinTemp = sum([a*b for a,b in zip(self.QsinClass ,self.percent)]) #fluxes are summed per cell according to percentage of class - self.Qsin = areatotal(self.QsinTemp * self.percentArea ,nominal(self.TopoId)) #areatotal is taken, according to area percentage of cell - + self.Recharge = [x * y for x, y in zip(self.Qu_, self.D)] + self.QsinClass = [ + a + b - c for a, b, c in zip(self.Recharge, self.Perc_, self.Cap_) + ] # all fluxes are summed per class + self.QsinTemp = sum( + [a * b for a, b in zip(self.QsinClass, self.percent)] + ) # fluxes are summed per cell according to percentage of class + self.Qsin = areatotal( + self.QsinTemp * self.percentArea, nominal(self.TopoId) + ) # areatotal is taken, according to area percentage of cell + self.Qs = self.Qsin self.Ss = 0. self.wbSs = self.Qsin - self.Qs - self.Ss + self.Ss_t - + + def groundWaterCombined3(self): """ - When using this option, the declaration of Ss and Qs should not be divided into separate classes - Stocks are lumped for the entire catchment - Differences with 'groundWaterCombined' are the order of calculations to try to decrease the numerical error --> turns out there is no difference - cannot be used combined with Sus for wetland areas """ - - self.Recharge = [x*y for x,y in zip(self.Qu_, self.D)] - self.QsinClass = [a+b-c for a,b,c in zip(self.Recharge, self.Perc_, self.Cap_)] # all fluxes are summed per class - self.QsinTemp = sum([a*b for a,b in zip(self.QsinClass ,self.percent)]) #fluxes are summed per cell according to percentage of class - self.Qsin = areatotal(self.QsinTemp * self.percentArea ,nominal(self.TopoId)) #areatotal is taken, according to area percentage of cell - - self.Qs = self.Ss * self.Ks[0] + + self.Recharge = [x * y for x, y in zip(self.Qu_, self.D)] + self.QsinClass = [ + a + b - c for a, b, c in zip(self.Recharge, self.Perc_, self.Cap_) + ] # all fluxes are summed per class + self.QsinTemp = sum( + [a * b for a, b in zip(self.QsinClass, self.percent)] + ) # fluxes are summed per cell according to percentage of class + self.Qsin = areatotal( + self.QsinTemp * self.percentArea, nominal(self.TopoId) + ) # areatotal is taken, according to area percentage of cell + + self.Qs = self.Ss * self.Ks[0] # self.Ss = self.Ss * exp(-self.Ks[0]) + self.Qsin # add a gain/lossterm based on constant value - self.Gain = ifthenelse(self.Closure < 0.0 , - min(self.Ss, -self.Closure) , self.Closure) # if negative, limited by storage in Ss + self.Gain = ifthenelse( + self.Closure < 0.0, -min(self.Ss, -self.Closure), self.Closure + ) # if negative, limited by storage in Ss self.Ss = self.Ss * exp(-self.Ks[0]) + self.Qsin + self.Gain - + self.wbSs = self.Qsin - self.Qs - self.Ss + self.Ss_t + self.Gain - + self.Qs_ = self.Qs self.Recharge_ = self.Recharge self.QsinClass_ = self.QsinClass self.QsinTemp_ = self.QsinTemp self.Qsin_ = self.Qsin self.Gain_ = self.Gain - Index: wflow-py/wflow/reservoir_Su.py =================================================================== diff -u -rb0a0649fbc4d5ed289c09f5beffbd40a711e95ca -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/reservoir_Su.py (.../reservoir_Su.py) (revision b0a0649fbc4d5ed289c09f5beffbd40a711e95ca) +++ wflow-py/wflow/reservoir_Su.py (.../reservoir_Su.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -12,59 +12,61 @@ from copy import copy as copylist try: - from wflow.wf_DynamicFramework import * + from wflow.wf_DynamicFramework import * except ImportError: - from wf_DynamicFramework import * + from wf_DynamicFramework import * import scipy import JarvisCoefficients + def selectSuR(i): """ not all functions are still in this file, the older functions can be found (with the same numbering) in h:\My Documents\memo's\python scripts\wflow\ """ if i == 1: - name = 'unsatZone_LP_beta' + name = "unsatZone_LP_beta" elif i == 2: - name = 'unsatZone_LP' + name = "unsatZone_LP" elif i == 3: - name = 'unsatZone_SF' + name = "unsatZone_SF" elif i == 4: - name = 'unsatZone_EisEp' + name = "unsatZone_EisEp" elif i == 5: - name = 'unsatZone_drain' + name = "unsatZone_drain" elif i == 6: - name = 'unsatZone_drain_split' + name = "unsatZone_drain_split" elif i == 7: - name = 'unsatZone_drain_Sumin' - elif i == 8: - name = 'unsatZone_drain_DZ' - elif i == 9: - name = 'unsatZone_drain_split_DZ' - elif i == 10: - name = 'unsatZone_withAgri' - elif i == 11: - name = 'unsatZone_withAgri_oldBeta' + name = "unsatZone_drain_Sumin" + elif i == 8: + name = "unsatZone_drain_DZ" + elif i == 9: + name = "unsatZone_drain_split_DZ" + elif i == 10: + name = "unsatZone_withAgri" + elif i == 11: + name = "unsatZone_withAgri_oldBeta" elif i == 12: - name = 'unsatZone_LP_beta_Jarvis' - elif i == 13: - name = 'unsatZone_LP_beta_Ep' + name = "unsatZone_LP_beta_Jarvis" + elif i == 13: + name = "unsatZone_LP_beta_Ep" elif i == 14: - name = 'unsatZone_withAgri_Ep' + name = "unsatZone_withAgri_Ep" elif i == 15: - name = 'unsatZone_withAgri_Jarvis' + name = "unsatZone_withAgri_Jarvis" elif i == 16: - name = 'unsatZone_forAgri_Jarvis' + name = "unsatZone_forAgri_Jarvis" elif i == 17: - name = 'unsatZone_forAgri_Ep' + name = "unsatZone_forAgri_Ep" elif i == 18: - name = 'unsatZone_forAgri_Jarvis_cropG' + name = "unsatZone_forAgri_Jarvis_cropG" elif i == 19: - name = 'unsatZone_forAgri_Ep_cropG' - elif i == 20: - name = 'unsatZone_LP_beta_Ep_cropG' + name = "unsatZone_forAgri_Ep_cropG" + elif i == 20: + name = "unsatZone_LP_beta_Ep_cropG" return name + def unsatZone_no_reservoir(self, k): """ This function is used when no unsaturated zone reservoir is used and only @@ -80,9 +82,12 @@ self.Perc_[k] = 0. self.Su[k] = 0. self.Cap_[k] = 0. - self.wbSu_[k] = self.Pe - self.Eu - self.Qu - self.Perc + self.Cap - self.Su[k] + self.Su_t[k] + self.wbSu_[k] = ( + self.Pe - self.Eu - self.Qu - self.Perc + self.Cap - self.Su[k] + self.Su_t[k] + ) -def unsatZone_LP_beta(self,k): + +def unsatZone_LP_beta(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation linear until LP, from than with potential rate @@ -91,39 +96,95 @@ - Qu is determined with a beta function (same as in HBV?) - Code for ini-file: 1 """ - self.Su[k] = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe) - self.Quadd = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.Su_t[k] + self.Pe - self.sumax[k], 0) + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], + self.Su_t[k] + self.Pe - self.sumax[k], + 0, + ) self.SuN = self.Su[k] / self.sumax[k] - self.SiN = self.Si[k] / self.imax[k] - - self.Eu1 = max((self.PotEvaporation - self.Ei),0) * min(self.Su[k] / (self.sumax[k] * self.LP[k]),1) - + self.SiN = self.Si[k] / self.imax[k] + + self.Eu1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Su[k] / (self.sumax[k] * self.LP[k]), 1 + ) + self.Qu1 = (self.Pe - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + self.Su[k] = ( + self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + ) self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 +self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Pe - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Pe + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc + + # self.Su_diff_[k] = self.Su_diff # self.Quadd_[k] = self.Quadd - - -def unsatZone_LP_beta_Jarvis(self,k): + + +def unsatZone_LP_beta_Jarvis(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on Jarvis stress functions @@ -133,38 +194,67 @@ - Qu is determined with a beta function (same as in HBV?) - Code for ini-file: 12 """ - self.Su[k] = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe) - self.Quadd = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.Su_t[k] + self.Pe - self.sumax[k], 0) + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], + self.Su_t[k] + self.Pe - self.sumax[k], + 0, + ) self.SuN = self.Su[k] / self.sumax[k] - self.SiN = self.Si[k] / self.imax[k] - - JarvisCoefficients.calcEu(self,k,1) #calculation of Eu based on Jarvis stress functions - + self.SiN = self.Si[k] / self.imax[k] + + JarvisCoefficients.calcEu( + self, k, 1 + ) # calculation of Eu based on Jarvis stress functions + self.Qu1 = (self.Pe - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu - self.Perc1 self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Qu = self.Qu1 + (self.Qu1/ifthenelse(self.Qu1 + self.Perc1 > 0 , self.Qu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1/ifthenelse(self.Qu1 + self.Perc1 > 0 , self.Qu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Qu = ( + self.Qu1 + + (self.Qu1 / ifthenelse(self.Qu1 + self.Perc1 > 0, self.Qu1 + self.Perc1, 1)) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + (self.Perc1 / ifthenelse(self.Qu1 + self.Perc1 > 0, self.Qu1 + self.Perc1, 1)) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Pe - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Pe + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc + + # self.Su_diff_[k] = self.Su_diff # self.Quadd_[k] = self.Quadd - - -def unsatZone_LP_beta_Ep(self,k): + + +def unsatZone_LP_beta_Ep(self, k): """ - Potential evaporation is calculated with formula in 'JarvisCoefficients', but without using the Jarvis stress functions @@ -175,44 +265,99 @@ - Qu is determined with a beta function (same as in HBV?) - Code for ini-file: 13 """ - - #pdb.set_trace() - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - - self.Su[k] = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe) - self.Quadd = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.Su_t[k] + self.Pe - self.sumax[k], 0) + + # pdb.set_trace() + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], + self.Su_t[k] + self.Pe - self.sumax[k], + 0, + ) self.SuN = self.Su[k] / self.sumax[k] - self.SiN = self.Si[k] / self.imax[k] - - self.Eu1 = max((self.PotEvaporation - self.Ei),0) * min(self.Su[k] / (self.sumax[k] * self.LP[k]),1) - + self.SiN = self.Si[k] / self.imax[k] + + self.Eu1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Su[k] / (self.sumax[k] * self.LP[k]), 1 + ) + self.Qu1 = (self.Pe - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + self.Su[k] = ( + self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + ) self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 +self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Pe - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Pe + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc -# self.Su_diff_[k] = self.Su_diff -# self.Quadd_[k] = self.Quadd + # self.Su_diff_[k] = self.Su_diff + # self.Quadd_[k] = self.Quadd self.Epot_[k] = self.PotEvaporation -def unsatZone_LP_beta_Ep_Ei(self,k): + +def unsatZone_LP_beta_Ep_Ei(self, k): """ - Potential evaporation is calculated with formula in 'JarvisCoefficients', but without using the Jarvis stress functions @@ -223,45 +368,103 @@ - Qu is determined with a beta function (same as in HBV?) - Code for ini-file: 13 """ - - #pdb.set_trace() - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - - self.Su[k] = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe) - self.Quadd = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.Su_t[k] + self.Pe - self.sumax[k], 0) + + # pdb.set_trace() + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], + self.Su_t[k] + self.Pe - self.sumax[k], + 0, + ) self.SuN = self.Su[k] / self.sumax[k] - self.SiN = self.Si[k] / self.imax[k] - - self.Eu1 = ifthenelse(self.SiN == 1, 0, max((self.PotEvaporation),0) * min(self.Su[k] / (self.sumax[k] * self.LP[k]),1)) -# self.Eu1 = max((self.PotEvaporation),0) * min(self.Su[k] / (self.sumax[k] * self.LP[k]),1) - + self.SiN = self.Si[k] / self.imax[k] + + self.Eu1 = ifthenelse( + self.SiN == 1, + 0, + max((self.PotEvaporation), 0) + * min(self.Su[k] / (self.sumax[k] * self.LP[k]), 1), + ) + # self.Eu1 = max((self.PotEvaporation),0) * min(self.Su[k] / (self.sumax[k] * self.LP[k]),1) + self.Qu1 = (self.Pe - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + self.Su[k] = ( + self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + ) self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 +self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Pe - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Pe + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc -# self.Su_diff_[k] = self.Su_diff -# self.Quadd_[k] = self.Quadd + # self.Su_diff_[k] = self.Su_diff + # self.Quadd_[k] = self.Quadd self.Epot_[k] = self.PotEvaporation -def unsatZone_LP_beta_Ep_percD(self,k): + +def unsatZone_LP_beta_Ep_percD(self, k): """ - Potential evaporation is calculated with formula in 'JarvisCoefficients', but without using the Jarvis stress functions @@ -272,42 +475,97 @@ - Qu is determined with a beta function (same as in HBV?) - Code for ini-file: 13 """ - - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - self.Su[k] = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe) - self.Quadd = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.Su_t[k] + self.Pe - self.sumax[k], 0) + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], + self.Su_t[k] + self.Pe - self.sumax[k], + 0, + ) self.SuN = self.Su[k] / self.sumax[k] - self.SiN = self.Si[k] / self.imax[k] - - self.Eu1 = max((self.PotEvaporation - self.Ei),0) * min(self.Su[k] / (self.sumax[k] * self.LP[k]),1) - + self.SiN = self.Si[k] / self.imax[k] + + self.Eu1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Su[k] / (self.sumax[k] * self.LP[k]), 1 + ) + self.percDeep = self.percD[-1] self.Qu1 = (self.Pe - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN + self.percDeep - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + self.Su[k] = ( + self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + ) self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 +self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Pe - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Pe + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc self.Epot_[k] = self.PotEvaporation - -def unsatZone_LP_beta_Ep_percD(self,k): + + +def unsatZone_LP_beta_Ep_percD(self, k): """ - Potential evaporation is calculated with formula in 'JarvisCoefficients', but without using the Jarvis stress functions @@ -318,43 +576,97 @@ - Qu is determined with a beta function (same as in HBV?) - Code for ini-file: 13 """ - - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - self.Su[k] = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe) - self.Quadd = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.Su_t[k] + self.Pe - self.sumax[k], 0) + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], + self.Su_t[k] + self.Pe - self.sumax[k], + 0, + ) self.SuN = self.Su[k] / self.sumax[k] - self.SiN = self.Si[k] / self.imax[k] - - self.Eu1 = max((self.PotEvaporation - self.Ei),0) * min(self.Su[k] / (self.sumax[k] * self.LP[k]),1) - + self.SiN = self.Si[k] / self.imax[k] + + self.Eu1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Su[k] / (self.sumax[k] * self.LP[k]), 1 + ) + self.percDeep = self.percD[-1] self.Qu1 = (self.Pe - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN + self.percDeep - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + self.Su[k] = ( + self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + ) self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 +self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Pe - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Pe + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc self.Epot_[k] = self.PotEvaporation -def unsatZone_LP_beta_Ep_percDvar(self,k): +def unsatZone_LP_beta_Ep_percDvar(self, k): """ - Potential evaporation is calculated with formula in 'JarvisCoefficients', but without using the Jarvis stress functions @@ -365,47 +677,120 @@ - Qu is determined with a beta function (same as in HBV?) - Code for ini-file: 13 """ - - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - - self.Su[k] = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe) - self.Quadd = ifthenelse(self.Su_t[k] + self.Pe > self.sumax[k], self.Su_t[k] + self.Pe - self.sumax[k], 0) + + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Pe + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax[k], + self.Su_t[k] + self.Pe - self.sumax[k], + 0, + ) self.SuN = self.Su[k] / self.sumax[k] - self.SiN = self.Si[k] / self.imax[k] + self.SiN = self.Si[k] / self.imax[k] - self.drought = ifthenelse(self.SuN < self.LP[k], self.TopoId, ifthenelse(pcrand(self.SuN < 0.8, self.drought), self.TopoId, boolean(scalar(self.TopoId) * 0))) - self.stijg = max(min(scalar(ifthenelse(self.drought == 1, self.stijg + self.Su_t[k] - self.Su_t2[k], 0)), self.sumax[k] * 100), 0) - - self.Eu1 = max((self.PotEvaporation - self.Ei),0) * min(self.Su[k] / (self.sumax[k] * self.LP[k]),1) - + self.drought = ifthenelse( + self.SuN < self.LP[k], + self.TopoId, + ifthenelse( + pcrand(self.SuN < 0.8, self.drought), + self.TopoId, + boolean(scalar(self.TopoId) * 0), + ), + ) + self.stijg = max( + min( + scalar( + ifthenelse( + self.drought == 1, self.stijg + self.Su_t[k] - self.Su_t2[k], 0 + ) + ), + self.sumax[k] * 100, + ), + 0, + ) + + self.Eu1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Su[k] / (self.sumax[k] * self.LP[k]), 1 + ) + self.Qu1 = (self.Pe - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) -# self.percDeep = max(10 * (1 - self.Ss / 30) * self.perc[k], 0) + # self.percDeep = max(10 * (1 - self.Ss / 30) * self.perc[k], 0) self.percDeep = 0.8 * self.stijg * self.perc[k] self.Perc1 = self.perc[k] * self.SuN + self.percDeep - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + self.Su[k] = ( + self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + ) self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 +self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Pe - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Pe + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc self.Epot_[k] = self.PotEvaporation self.percDeep_[k] = self.percDeep -def unsatZone_LP_beta_Ep_cropG(self,k): + +def unsatZone_LP_beta_Ep_cropG(self, k): """ - Potential evaporation is calculated with formula in 'JarvisCoefficients', but without using the Jarvis stress functions @@ -417,50 +802,107 @@ - root zone storage for crop land is decreased in autumn and winter - Code for ini-file: 20 """ - - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - self.cropG_scal = pcr2numpy(self.cropG,NaN) + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.cropG_scal = pcr2numpy(self.cropG, NaN) if any(self.cropG_scal == 1): self.sumax2 = self.sumax[k] - elif any(self.cropG_scal > 0): - self.sumax2 = self.sumax[k] * (1 - numpy.max(self.cropG_scal[self.cropG_scal >= 0]) * (1-self.redsu[k])) + elif any(self.cropG_scal > 0): + self.sumax2 = self.sumax[k] * ( + 1 - numpy.max(self.cropG_scal[self.cropG_scal >= 0]) * (1 - self.redsu[k]) + ) else: self.sumax2 = self.sumax[k] * self.redsu[k] - - self.Su[k] = ifthenelse(self.Su_t[k] + self.Pe > self.sumax2, self.sumax2, self.Su_t[k] + self.Pe) - self.Quadd = ifthenelse(self.Su_t[k] + self.Pe > self.sumax2, self.Su_t[k] + self.Pe - self.sumax2, 0) + + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax2, self.sumax2, self.Su_t[k] + self.Pe + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Pe > self.sumax2, self.Su_t[k] + self.Pe - self.sumax2, 0 + ) self.SuN = self.Su[k] / self.sumax2 - self.SiN = self.Si[k] / self.imax[k] - - self.Eu1 = max((self.PotEvaporation - self.Ei),0) * min(self.Su[k] / (self.sumax2 * self.LP[k]),1) - + self.SiN = self.Si[k] / self.imax[k] + + self.Eu1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Su[k] / (self.sumax2 * self.LP[k]), 1 + ) + self.Qu1 = (self.Pe - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + self.Su[k] = ( + self.Su_t[k] + (self.Pe - self.Quadd) - self.Qu1 - self.Eu1 - self.Perc1 + ) self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 +self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1/ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Pe - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax2), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Pe - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax2), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Pe + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc + + # self.Su_diff_[k] = self.Su_diff # self.Quadd_[k] = self.Quadd -def unsatZone_forAgri_Jarvis(self,k): + +def unsatZone_forAgri_Jarvis(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on Jarvis stress functions @@ -471,37 +913,90 @@ - inflow is infiltration from agriculture reservoir - Code for ini-file: 16 """ - self.Su[k] = ifthenelse(self.Su_t[k] + self.Fa > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Fa) - self.Quadd = ifthenelse(self.Su_t[k] + self.Fa > self.sumax[k], self.Su_t[k] + self.Fa - self.sumax[k], 0) + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Fa + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax[k], + self.Su_t[k] + self.Fa - self.sumax[k], + 0, + ) self.SuN = self.Su[k] / self.sumax[k] - self.SiN = self.Si[k] / self.imax[k] - - JarvisCoefficients.calcEu(self,k,2) #calculation of Eu based on Jarvis stress functions + self.SiN = self.Si[k] / self.imax[k] + + JarvisCoefficients.calcEu( + self, k, 2 + ) # calculation of Eu based on Jarvis stress functions self.Eu1 = self.Eu - + self.Qu1 = (self.Fa - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Qu1 - self.Eu - self.Perc1 self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Fa - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Fa + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc -def unsatZone_forAgri_Ep(self,k): + +def unsatZone_forAgri_Ep(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on beta/LP @@ -512,40 +1007,96 @@ - inflow is infiltration from agriculture reservoir - Code for ini-file: 17 """ - - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - self.Su[k] = ifthenelse(self.Su_t[k] + self.Fa > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Fa) - self.Quadd = ifthenelse(self.Su_t[k] + self.Fa > self.sumax[k], self.Su_t[k] + self.Fa - self.sumax[k], 0) + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Fa + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax[k], + self.Su_t[k] + self.Fa - self.sumax[k], + 0, + ) self.SuN = self.Su[k] / self.sumax[k] - self.SiN = self.Si[k] / self.imax[k] - - self.Eu1 = ifthenelse(self.Ft_[k] == 1, max((self.PotEvaporation - self.Ei - self.Ea),0) * min(self.Su[k] / (self.sumax[k] * self.LP[k]),1), 0) # no transpiration in case of frozen soil. Added on 22 feb 2016 - + self.SiN = self.Si[k] / self.imax[k] + + self.Eu1 = ifthenelse( + self.Ft_[k] == 1, + max((self.PotEvaporation - self.Ei - self.Ea), 0) + * min(self.Su[k] / (self.sumax[k] * self.LP[k]), 1), + 0, + ) # no transpiration in case of frozen soil. Added on 22 feb 2016 + self.Qu1 = (self.Fa - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Qu1 - self.Eu - self.Perc1 self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Fa - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Fa + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc -def unsatZone_forAgri_Ep_percD(self,k): + +def unsatZone_forAgri_Ep_percD(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on beta/LP @@ -556,41 +1107,97 @@ - inflow is infiltration from agriculture reservoir - Code for ini-file: 17 """ - - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - self.Su[k] = ifthenelse(self.Su_t[k] + self.Fa > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Fa) - self.Quadd = ifthenelse(self.Su_t[k] + self.Fa > self.sumax[k], self.Su_t[k] + self.Fa - self.sumax[k], 0) + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Fa + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax[k], + self.Su_t[k] + self.Fa - self.sumax[k], + 0, + ) self.SuN = self.Su[k] / self.sumax[k] - self.SiN = self.Si[k] / self.imax[k] - - self.Eu1 = ifthenelse(self.Ft_[k] == 1, max((self.PotEvaporation - self.Ei - self.Ea),0) * min(self.Su[k] / (self.sumax[k] * self.LP[k]),1), 0) # no transpiration in case of frozen soil. Added on 22 feb 2016 - + self.SiN = self.Si[k] / self.imax[k] + + self.Eu1 = ifthenelse( + self.Ft_[k] == 1, + max((self.PotEvaporation - self.Ei - self.Ea), 0) + * min(self.Su[k] / (self.sumax[k] * self.LP[k]), 1), + 0, + ) # no transpiration in case of frozen soil. Added on 22 feb 2016 + self.percDeep = self.percD[-1] self.Qu1 = (self.Fa - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN + self.percDeep self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Qu1 - self.Eu - self.Perc1 self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Fa - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Fa + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc -def unsatZone_forAgri_Ep_percDvar(self,k): + +def unsatZone_forAgri_Ep_percDvar(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on beta/LP @@ -601,45 +1208,119 @@ - inflow is infiltration from agriculture reservoir - Code for ini-file: 17 """ - - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - self.Su[k] = ifthenelse(self.Su_t[k] + self.Fa > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Fa) - self.Quadd = ifthenelse(self.Su_t[k] + self.Fa > self.sumax[k], self.Su_t[k] + self.Fa - self.sumax[k], 0) + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Fa + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax[k], + self.Su_t[k] + self.Fa - self.sumax[k], + 0, + ) self.SuN = self.Su[k] / self.sumax[k] - self.SiN = self.Si[k] / self.imax[k] - - self.drought = ifthenelse(self.SuN < self.LP[k], self.TopoId, ifthenelse(pcrand(self.SuN < 0.8, self.drought), self.TopoId, boolean(scalar(self.TopoId) * 0))) - self.stijg = max(min(scalar(ifthenelse(self.drought == 1, self.stijg + self.Su_t[k] - self.Su_t2[k], 0)), self.sumax[k] * 100), 0) -# self.stijg = max(self.Su_t[k] - self.Su_t2[k], 0) - - self.Eu1 = ifthenelse(self.Ft_[k] == 1, max((self.PotEvaporation - self.Ei - self.Ea),0) * min(self.Su[k] / (self.sumax[k] * self.LP[k]),1), 0) # no transpiration in case of frozen soil. Added on 22 feb 2016 - + self.SiN = self.Si[k] / self.imax[k] + + self.drought = ifthenelse( + self.SuN < self.LP[k], + self.TopoId, + ifthenelse( + pcrand(self.SuN < 0.8, self.drought), + self.TopoId, + boolean(scalar(self.TopoId) * 0), + ), + ) + self.stijg = max( + min( + scalar( + ifthenelse( + self.drought == 1, self.stijg + self.Su_t[k] - self.Su_t2[k], 0 + ) + ), + self.sumax[k] * 100, + ), + 0, + ) + # self.stijg = max(self.Su_t[k] - self.Su_t2[k], 0) + + self.Eu1 = ifthenelse( + self.Ft_[k] == 1, + max((self.PotEvaporation - self.Ei - self.Ea), 0) + * min(self.Su[k] / (self.sumax[k] * self.LP[k]), 1), + 0, + ) # no transpiration in case of frozen soil. Added on 22 feb 2016 + self.percDeep = 0.8 * self.stijg * self.perc[k] self.Qu1 = (self.Fa - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN + self.percDeep self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Qu1 - self.Eu - self.Perc1 self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Fa - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Fa + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc -def unsatZone_forAgri_hourlyEp(self,k): + +def unsatZone_forAgri_hourlyEp(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on beta/LP @@ -650,38 +1331,93 @@ - inflow is infiltration from agriculture reservoir - Code for ini-file: 25 """ - - self.Su[k] = ifthenelse(self.Su_t[k] + self.Fa > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Fa) - self.Quadd = ifthenelse(self.Su_t[k] + self.Fa > self.sumax[k], self.Su_t[k] + self.Fa - self.sumax[k], 0) + + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax[k], self.sumax[k], self.Su_t[k] + self.Fa + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax[k], + self.Su_t[k] + self.Fa - self.sumax[k], + 0, + ) self.SuN = self.Su[k] / self.sumax[k] - self.SiN = self.Si[k] / self.imax[k] - - self.Eu1 = ifthenelse(self.Ft_[k] == 1, max((self.PotEvaporation - self.Ei - self.Ea),0) * min(self.Su[k] / (self.sumax[k] * self.LP[k]),1), 0) # no transpiration in case of frozen soil. Added on 31 mrt 2016 - + self.SiN = self.Si[k] / self.imax[k] + + self.Eu1 = ifthenelse( + self.Ft_[k] == 1, + max((self.PotEvaporation - self.Ei - self.Ea), 0) + * min(self.Su[k] / (self.sumax[k] * self.LP[k]), 1), + 0, + ) # no transpiration in case of frozen soil. Added on 31 mrt 2016 + self.Qu1 = (self.Fa - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Qu1 - self.Eu - self.Perc1 self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Fa - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax[k]), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Fa + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc -def unsatZone_forAgri_Jarvis_cropG(self,k): +def unsatZone_forAgri_Jarvis_cropG(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on Jarvis stress functions @@ -692,43 +1428,94 @@ - inflow is infiltration from agriculture reservoir - Code for ini-file: 18 """ - self.cropG_scal = pcr2numpy(self.cropG,NaN) + self.cropG_scal = pcr2numpy(self.cropG, NaN) if any(self.cropG_scal == 1): self.sumax2 = self.sumax[k] else: self.sumax2 = self.sumax[k] * self.redsu[k] - - self.Su[k] = ifthenelse(self.Su_t[k] + self.Fa > self.sumax2, self.sumax2, self.Su_t[k] + self.Fa) - self.Quadd = ifthenelse(self.Su_t[k] + self.Fa > self.sumax2, self.Su_t[k] + self.Fa - self.sumax2, 0) + + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax2, self.sumax2, self.Su_t[k] + self.Fa + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax2, self.Su_t[k] + self.Fa - self.sumax2, 0 + ) self.SuN = self.Su[k] / self.sumax2 - self.SiN = self.Si[k] / self.imax[k] - - JarvisCoefficients.calcEu(self,k,2) #calculation of Eu based on Jarvis stress functions + self.SiN = self.Si[k] / self.imax[k] + + JarvisCoefficients.calcEu( + self, k, 2 + ) # calculation of Eu based on Jarvis stress functions self.Eu1 = self.Eu - + self.Qu1 = (self.Fa - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Qu1 - self.Eu - self.Perc1 self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax2), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Fa - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax2), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Fa + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc -def unsatZone_forAgri_Ep_cropG(self,k): + +def unsatZone_forAgri_Ep_cropG(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation based on beta/LP @@ -739,46 +1526,97 @@ - inflow is infiltration from agriculture reservoir - Code for ini-file: 19 """ - - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) - - self.cropG_scal = pcr2numpy(self.cropG,NaN) + + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) + + self.cropG_scal = pcr2numpy(self.cropG, NaN) if any(self.cropG_scal == 1): self.sumax2 = self.sumax[k] else: self.sumax2 = self.sumax[k] * self.redsu[k] - - self.Su[k] = ifthenelse(self.Su_t[k] + self.Fa > self.sumax2, self.sumax2, self.Su_t[k] + self.Fa) - self.Quadd = ifthenelse(self.Su_t[k] + self.Fa > self.sumax2, self.Su_t[k] + self.Fa - self.sumax2, 0) + + self.Su[k] = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax2, self.sumax2, self.Su_t[k] + self.Fa + ) + self.Quadd = ifthenelse( + self.Su_t[k] + self.Fa > self.sumax2, self.Su_t[k] + self.Fa - self.sumax2, 0 + ) self.SuN = self.Su[k] / self.sumax2 - self.SiN = self.Si[k] / self.imax[k] - - self.Eu1 = max((self.PotEvaporation - self.Ei),0) * min(self.Su[k] / (self.sumax2 * self.LP[k]),1) - + self.SiN = self.Si[k] / self.imax[k] + + self.Eu1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Su[k] / (self.sumax2 * self.LP[k]), 1 + ) + self.Qu1 = (self.Fa - self.Quadd) * (1 - (1 - self.SuN) ** self.beta[k]) self.Perc1 = self.perc[k] * self.SuN self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Qu1 - self.Eu - self.Perc1 self.Su_diff = ifthenelse(self.Su[k] < 0, self.Su[k], 0) - self.Eu = self.Eu1 + (self.Eu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Qu = self.Qu1 + (self.Qu1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff - self.Perc = ifthenelse (self.Perc1 > 0, self.Perc1 + (self.Perc1 / ifthenelse(self.Qu1 + self.Eu1 + self.Perc1 > 0 , self.Qu1 + self.Eu1 + self.Perc1 , 1)) * self.Su_diff, self.Perc1) - self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc - self.Su[k] = ifthenelse(self.Su[k] < 0, 0 , self.Su[k]) - self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) + self.Eu = ( + self.Eu1 + + ( + self.Eu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Qu = ( + self.Qu1 + + ( + self.Qu1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff + ) + self.Perc = ifthenelse( + self.Perc1 > 0, + self.Perc1 + + ( + self.Perc1 + / ifthenelse( + self.Qu1 + self.Eu1 + self.Perc1 > 0, + self.Qu1 + self.Eu1 + self.Perc1, + 1, + ) + ) + * self.Su_diff, + self.Perc1, + ) + self.Su[k] = self.Su_t[k] + (self.Fa - self.Quadd) - self.Eu - self.Qu - self.Perc + self.Su[k] = ifthenelse(self.Su[k] < 0, 0, self.Su[k]) + self.Su_diff2 = ifthen(self.Su[k] < 0, self.Su[k]) - self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax2), self.Ss) - self.Su[k] = self.Su[k] + self.Cap - - self.wbSu_[k] = self.Fa - self.Eu - self.Qu - self.Quadd - self.Perc + self. Cap - self.Su[k] + self.Su_t[k] - + self.Cap = min(self.cap[k] * (1 - self.Su[k] / self.sumax2), self.Ss) + self.Su[k] = self.Su[k] + self.Cap + + self.wbSu_[k] = ( + self.Fa + - self.Eu + - self.Qu + - self.Quadd + - self.Perc + + self.Cap + - self.Su[k] + + self.Su_t[k] + ) + self.Eu_[k] = self.Eu self.Qu_[k] = self.Qu + self.Quadd self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc -def unsatZone_withAgri(self,k): + +def unsatZone_withAgri(self, k): """ - Potential evaporation is decreased by energy used for interception evaporation - Formula for evaporation linear until LP, from than with potential rate @@ -787,44 +1625,92 @@ - Qu is determined with a beta function (same as in HBV?) - Code for ini-file: 10 """ - self.Sa[k] = ifthenelse(self.Sa_t[k] + self.Pe > self.samax[k], self.samax[k], self.Sa_t[k] + self.Pe) - self.Qaadd = ifthenelse(self.Sa_t[k] + self.Pe > self.samax[k], self.Sa_t[k] + self.Pe - self.samax[k], 0) + self.Sa[k] = ifthenelse( + self.Sa_t[k] + self.Pe > self.samax[k], self.samax[k], self.Sa_t[k] + self.Pe + ) + self.Qaadd = ifthenelse( + self.Sa_t[k] + self.Pe > self.samax[k], + self.Sa_t[k] + self.Pe - self.samax[k], + 0, + ) self.SaN = self.Sa[k] / self.samax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax[k] * self.LP[k]),1) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax[k] * self.LP[k]), 1 + ) self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - self.Fa1 = self.famax[k] * (self.sumax[k] - self.Su[k]) / self.sumax[k] - + self.Fa1 = self.famax[k] * (self.sumax[k] - self.Su[k]) / self.sumax[k] + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Ea1 - self.Fa1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Ea = self.Ea1 + (self.Ea1 / ifthenelse(self.Qa1 + self.Ea1 +self.Fa1 > 0 , self.Qa1 + self.Ea1 + self.Fa1 , 1)) * self.Sa_diff - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Qa1 + self.Ea1 + self.Fa1 > 0 , self.Qa1 + self.Ea1 + self.Fa1 , 1)) * self.Sa_diff - self.Fa = ifthenelse (self.Fa1 > 0, self.Fa1 + (self.Fa1/ifthenelse(self.Qa1 + self.Ea1 + self.Fa1 > 0 , self.Qa1 + self.Ea1 + self.Fa1 , 1)) * self.Sa_diff, self.Fa1) - self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Qa - self.Fa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Ea = ( + self.Ea1 + + ( + self.Ea1 + / ifthenelse( + self.Qa1 + self.Ea1 + self.Fa1 > 0, self.Qa1 + self.Ea1 + self.Fa1, 1 + ) + ) + * self.Sa_diff + ) + self.Qa = ( + self.Qa1 + + ( + self.Qa1 + / ifthenelse( + self.Qa1 + self.Ea1 + self.Fa1 > 0, self.Qa1 + self.Ea1 + self.Fa1, 1 + ) + ) + * self.Sa_diff + ) + self.Fa = ifthenelse( + self.Fa1 > 0, + self.Fa1 + + ( + self.Fa1 + / ifthenelse( + self.Qa1 + self.Ea1 + self.Fa1 > 0, self.Qa1 + self.Ea1 + self.Fa1, 1 + ) + ) + * self.Sa_diff, + self.Fa1, + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Qa - self.Fa + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) self.Capa = min(self.cap[k] * (1 - self.Sa[k] / self.samax[k]), self.Su[k]) - self.Sa[k] = self.Sa[k] + self.Capa - - self.Su[k] = self.Su_t[k] + self.Fa - self.Capa + self.Sa[k] = self.Sa[k] + self.Capa + + self.Su[k] = self.Su_t[k] + self.Fa - self.Capa self.Perc = self.perc[k] * (self.Su[k] / self.sumax[k]) self.Su[k] = self.Su[k] - self.Perc - - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa + self. Capa - self.Sa[k] + self.Sa_t[k] - self.wbSu_[k] = self.Fa - self.Perc - self. Capa - self.Su[k] + self.Su_t[k] - + + self.wbSa_[k] = ( + self.Pe + - self.Ea + - self.Qa + - self.Qaadd + - self.Fa + + self.Capa + - self.Sa[k] + + self.Sa_t[k] + ) + self.wbSu_[k] = self.Fa - self.Perc - self.Capa - self.Su[k] + self.Su_t[k] + self.Eu_[k] = self.Ea self.Qu_[k] = self.Qa + self.Qaadd self.Fa_[k] = self.Fa self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc + + # self.Su_diff_[k] = self.Su_diff # self.Quadd_[k] = self.Qaadd - - -def unsatZone_withAgri_Ep(self,k): + + +def unsatZone_withAgri_Ep(self, k): """ - Potential evaporation is calculated with formula in 'JarvisCoefficients', but without using the Jarvis stress functions @@ -836,46 +1722,95 @@ - Code for ini-file: 14 """ - JarvisCoefficients.calcEp(self,k) - self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0),0) + JarvisCoefficients.calcEp(self, k) + self.PotEvaporation = cover(ifthenelse(self.EpHour >= 0, self.EpHour, 0), 0) - self.Sa[k] = ifthenelse(self.Sa_t[k] + self.Pe > self.samax[k], self.samax[k], self.Sa_t[k] + self.Pe) - self.Qaadd = ifthenelse(self.Sa_t[k] + self.Pe > self.samax[k], self.Sa_t[k] + self.Pe - self.samax[k], 0) + self.Sa[k] = ifthenelse( + self.Sa_t[k] + self.Pe > self.samax[k], self.samax[k], self.Sa_t[k] + self.Pe + ) + self.Qaadd = ifthenelse( + self.Sa_t[k] + self.Pe > self.samax[k], + self.Sa_t[k] + self.Pe - self.samax[k], + 0, + ) self.SaN = self.Sa[k] / self.samax[k] - - self.Ea1 = max((self.PotEvaporation - self.Ei),0) * min(self.Sa[k] / (self.samax[k] * self.LP[k]),1) + + self.Ea1 = max((self.PotEvaporation - self.Ei), 0) * min( + self.Sa[k] / (self.samax[k] * self.LP[k]), 1 + ) self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - self.Fa1 = self.famax[k] * (self.sumax[k] - self.Su[k]) / self.sumax[k] - + self.Fa1 = self.famax[k] * (self.sumax[k] - self.Su[k]) / self.sumax[k] + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Ea1 - self.Fa1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Ea = self.Ea1 + (self.Ea1 / ifthenelse(self.Qa1 + self.Ea1 +self.Fa1 > 0 , self.Qa1 + self.Ea1 + self.Fa1 , 1)) * self.Sa_diff - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Qa1 + self.Ea1 + self.Fa1 > 0 , self.Qa1 + self.Ea1 + self.Fa1 , 1)) * self.Sa_diff - self.Fa = ifthenelse (self.Fa1 > 0, self.Fa1 + (self.Fa1/ifthenelse(self.Qa1 + self.Ea1 + self.Fa1 > 0 , self.Qa1 + self.Ea1 + self.Fa1 , 1)) * self.Sa_diff, self.Fa1) - self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Qa - self.Fa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Ea = ( + self.Ea1 + + ( + self.Ea1 + / ifthenelse( + self.Qa1 + self.Ea1 + self.Fa1 > 0, self.Qa1 + self.Ea1 + self.Fa1, 1 + ) + ) + * self.Sa_diff + ) + self.Qa = ( + self.Qa1 + + ( + self.Qa1 + / ifthenelse( + self.Qa1 + self.Ea1 + self.Fa1 > 0, self.Qa1 + self.Ea1 + self.Fa1, 1 + ) + ) + * self.Sa_diff + ) + self.Fa = ifthenelse( + self.Fa1 > 0, + self.Fa1 + + ( + self.Fa1 + / ifthenelse( + self.Qa1 + self.Ea1 + self.Fa1 > 0, self.Qa1 + self.Ea1 + self.Fa1, 1 + ) + ) + * self.Sa_diff, + self.Fa1, + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Qa - self.Fa + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) self.Capa = min(self.cap[k] * (1 - self.Sa[k] / self.samax[k]), self.Su[k]) - self.Sa[k] = self.Sa[k] + self.Capa - - self.Su[k] = self.Su_t[k] + self.Fa - self.Capa + self.Sa[k] = self.Sa[k] + self.Capa + + self.Su[k] = self.Su_t[k] + self.Fa - self.Capa self.Perc = self.perc[k] * (self.Su[k] / self.sumax[k]) self.Su[k] = self.Su[k] - self.Perc - - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa + self. Capa - self.Sa[k] + self.Sa_t[k] - self.wbSu_[k] = self.Fa - self.Perc - self. Capa - self.Su[k] + self.Su_t[k] - + + self.wbSa_[k] = ( + self.Pe + - self.Ea + - self.Qa + - self.Qaadd + - self.Fa + + self.Capa + - self.Sa[k] + + self.Sa_t[k] + ) + self.wbSu_[k] = self.Fa - self.Perc - self.Capa - self.Su[k] + self.Su_t[k] + self.Eu_[k] = self.Ea self.Qu_[k] = self.Qa + self.Qaadd self.Fa_[k] = self.Fa self.Cap_[k] = self.Cap self.Perc_[k] = self.Perc + + # self.Su_diff_[k] = self.Su_diff # self.Quadd_[k] = self.Qaadd - -def unsatZone_withAgri_Jarvis(self,k): + + +def unsatZone_withAgri_Jarvis(self, k): """ - Potential evaporation is calculated with formula in 'JarvisCoefficients', but without using the Jarvis stress functions @@ -887,37 +1822,64 @@ - Code for ini-file: 15 """ - self.Sa[k] = ifthenelse(self.Sa_t[k] + self.Pe > self.samax[k], self.samax[k], self.Sa_t[k] + self.Pe) - self.Qaadd = ifthenelse(self.Sa_t[k] + self.Pe > self.samax[k], self.Sa_t[k] + self.Pe - self.samax[k], 0) + self.Sa[k] = ifthenelse( + self.Sa_t[k] + self.Pe > self.samax[k], self.samax[k], self.Sa_t[k] + self.Pe + ) + self.Qaadd = ifthenelse( + self.Sa_t[k] + self.Pe > self.samax[k], + self.Sa_t[k] + self.Pe - self.samax[k], + 0, + ) self.SaN = self.Sa[k] / self.samax[k] - - JarvisCoefficients.calcEu(self,k,1) #calculation of Eu based on Jarvis stress functions - self.Ea = self.Eu - + + JarvisCoefficients.calcEu( + self, k, 1 + ) # calculation of Eu based on Jarvis stress functions + self.Ea = self.Eu + self.Qa1 = (self.Pe - self.Qaadd) * (1 - (1 - self.SaN) ** self.beta[k]) - self.Fa1 = self.famax[k] * (self.sumax[k] - self.Su[k]) / self.sumax[k] - + self.Fa1 = self.famax[k] * (self.sumax[k] - self.Su[k]) / self.sumax[k] + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Qa1 - self.Ea - self.Fa1 self.Sa_diff = ifthenelse(self.Sa[k] < 0, self.Sa[k], 0) - self.Qa = self.Qa1 + (self.Qa1/ifthenelse(self.Qa1 + self.Fa1 > 0 , self.Qa1 + self.Fa1 , 1)) * self.Sa_diff - self.Fa = ifthenelse (self.Fa1 > 0, self.Fa1 + (self.Fa1/ifthenelse(self.Qa1 + self.Fa1 > 0 , self.Qa1 + self.Fa1 , 1)) * self.Sa_diff, self.Fa1) - self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Qa - self.Fa - self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0 , self.Sa[k]) - self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) + self.Qa = ( + self.Qa1 + + (self.Qa1 / ifthenelse(self.Qa1 + self.Fa1 > 0, self.Qa1 + self.Fa1, 1)) + * self.Sa_diff + ) + self.Fa = ifthenelse( + self.Fa1 > 0, + self.Fa1 + + (self.Fa1 / ifthenelse(self.Qa1 + self.Fa1 > 0, self.Qa1 + self.Fa1, 1)) + * self.Sa_diff, + self.Fa1, + ) + self.Sa[k] = self.Sa_t[k] + (self.Pe - self.Qaadd) - self.Ea - self.Qa - self.Fa + self.Sa[k] = ifthenelse(self.Sa[k] < 0, 0, self.Sa[k]) + self.Sa_diff2 = ifthen(self.Sa[k] < 0, self.Sa[k]) self.Capa = min(self.cap[k] * (1 - self.Sa[k] / self.samax[k]), self.Su[k]) - self.Sa[k] = self.Sa[k] + self.Capa - - self.Su[k] = self.Su_t[k] + self.Fa - self.Capa + self.Sa[k] = self.Sa[k] + self.Capa + + self.Su[k] = self.Su_t[k] + self.Fa - self.Capa self.Perc = self.perc[k] * (self.Su[k] / self.sumax[k]) self.Su[k] = self.Su[k] - self.Perc - - self.wbSa_[k] = self.Pe - self.Ea - self.Qa - self.Qaadd - self.Fa + self. Capa - self.Sa[k] + self.Sa_t[k] - self.wbSu_[k] = self.Fa - self.Perc - self. Capa - self.Su[k] + self.Su_t[k] - + + self.wbSa_[k] = ( + self.Pe + - self.Ea + - self.Qa + - self.Qaadd + - self.Fa + + self.Capa + - self.Sa[k] + + self.Sa_t[k] + ) + self.wbSu_[k] = self.Fa - self.Perc - self.Capa - self.Su[k] + self.Su_t[k] + self.Eu_[k] = self.Ea self.Qu_[k] = self.Qa + self.Qaadd self.Fa_[k] = self.Fa self.Cap_[k] = self.Cap - self.Perc_[k] = self.Perc \ No newline at end of file + self.Perc_[k] = self.Perc Index: wflow-py/wflow/rtc_wflow_bmi.py =================================================================== diff -u -rc8e2fba98b7e0b0d9062e2dba1cba046ce931bab -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/rtc_wflow_bmi.py (.../rtc_wflow_bmi.py) (revision c8e2fba98b7e0b0d9062e2dba1cba046ce931bab) +++ wflow-py/wflow/rtc_wflow_bmi.py (.../rtc_wflow_bmi.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -2,9 +2,6 @@ from wflow.wrappers.rtc.wrapperExtended import BMIWrapperExtended - class rtcbmi_csdms(BMIWrapperExtended): - - def initialize_model(self): - self.initialize('..') + self.initialize("..") Index: wflow-py/wflow/sphy/ET.py =================================================================== diff -u -re59169d4b535e077a267eba3d2ba75f73803fbc8 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/sphy/ET.py (.../ET.py) (revision e59169d4b535e077a267eba3d2ba75f73803fbc8) +++ wflow-py/wflow/sphy/ET.py (.../ET.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,15 +1,13 @@ -#-Function to calculate the potential evapotranspiration +# -Function to calculate the potential evapotranspiration def ETpot(etr, kc): etpot = etr * kc return etpot -#-Function to calculate the actual evapotranspiration + +# -Function to calculate the actual evapotranspiration def ETact(pcr, etpot, rootwater, rootsat, etreddry, rainfrac): etredwet = pcr.ifthenelse(rootwater >= rootsat, pcr.scalar(0), 1) - etact = pcr.ifthenelse(rainfrac > 0, pcr.min(etpot * etreddry * etredwet, rootwater), 0) + etact = pcr.ifthenelse( + rainfrac > 0, pcr.min(etpot * etreddry * etredwet, rootwater), 0 + ) return etact - - - - - Index: wflow-py/wflow/sphy/hargreaves.py =================================================================== diff -u -re59169d4b535e077a267eba3d2ba75f73803fbc8 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/sphy/hargreaves.py (.../hargreaves.py) (revision e59169d4b535e077a267eba3d2ba75f73803fbc8) +++ wflow-py/wflow/sphy/hargreaves.py (.../hargreaves.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,15 +1,25 @@ -#-Extraterrestrial radiation +# -Extraterrestrial radiation def extrarad(self, pcr): - DayNo = self.wf_supplyJulianDOY() # timecalc.julian(self)[0] + DayNo = self.wf_supplyJulianDOY() # timecalc.julian(self)[0] LatRad = self.Lat * (self.pi / 180) - dr = 1 + 0.033 * pcr.cos((2 * self.pi * DayNo) / 365) + dr = 1 + 0.033 * pcr.cos((2 * self.pi * DayNo) / 365) delta = 0.409 * pcr.sin(((2 * self.pi * DayNo) / 365) - 1.39) omegas = pcr.acos(-1 * pcr.tan(LatRad) * pcr.tan(delta)) - Ra = ((24 * 60) / self.pi) * self.Gsc * dr * (pcr.scalar(omegas) * pcr.sin(LatRad) * pcr.sin(delta) +\ - pcr.cos(LatRad) * pcr.cos(delta) * pcr.sin(omegas)) - return Ra + Ra = ( + ((24 * 60) / self.pi) + * self.Gsc + * dr + * ( + pcr.scalar(omegas) * pcr.sin(LatRad) * pcr.sin(delta) + + pcr.cos(LatRad) * pcr.cos(delta) * pcr.sin(omegas) + ) + ) + return Ra -#-Modified Hargreaves for calculation of ETref + +# -Modified Hargreaves for calculation of ETref def Hargreaves(pcr, ra, temp, tempmax, tempmin): - ETref = pcr.max(0.0023 * 0.408 * ra * (temp + 17.8) * (pcr.max(tempmax - tempmin, 0))**0.5, 0) - return ETref \ No newline at end of file + ETref = pcr.max( + 0.0023 * 0.408 * ra * (temp + 17.8) * (pcr.max(tempmax - tempmin, 0)) ** 0.5, 0 + ) + return ETref Index: wflow-py/wflow/sphy/reporting.py =================================================================== diff -u -re59169d4b535e077a267eba3d2ba75f73803fbc8 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/sphy/reporting.py (.../reporting.py) (revision e59169d4b535e077a267eba3d2ba75f73803fbc8) +++ wflow-py/wflow/sphy/reporting.py (.../reporting.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,25 +1,25 @@ -#-Function to report the output +# -Function to report the output def REPM(self, pcr, tot, var, fname, outops, TSS=False, MAP=False): - if outops == 'Day': + if outops == "Day": if TSS: TSS.sample(var) if MAP: self.report(var, self.outpath + fname) tot = 0 - elif outops == 'Month': + elif outops == "Month": dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if self.calendar.isleap(self.curdate.year): dim[1] = 29 else: dim[1] = 28 tot = tot + var - if self.curdate.day == dim[self.curdate.month-1]: + if self.curdate.day == dim[self.curdate.month - 1]: if TSS: TSS.sample(tot) if MAP: - self.report(tot, self.outpath + fname + 'M') + self.report(tot, self.outpath + fname + "M") tot = 0 - elif outops == 'Year': + elif outops == "Year": if self.calendar.isleap(self.curdate.year): ydays = 366 else: @@ -29,29 +29,67 @@ if TSS: TSS.sample(tot) if MAP: - self.report(tot, self.outpath + fname + 'Y') + self.report(tot, self.outpath + fname + "Y") tot = 0 else: tot = tot + var if self.curdate == self.enddate: - pcr.report(tot, self.outpath + fname + '.map') + pcr.report(tot, self.outpath + fname + ".map") tot = 0 return tot - -#-Function to initialise the reporting + + +# -Function to initialise the reporting def reporting(self, pcr, tot, var): - for outops in ['Day','Month','Year','Final']: + for outops in ["Day", "Month", "Year", "Final"]: try: - TSS = eval('self.' + tot + '_' + outops + 'TS') + TSS = eval("self." + tot + "_" + outops + "TS") try: - MAP = eval('self.' + tot + '_' + outops + '_map') - setattr(self, tot + '_'+outops, REPM(self, pcr, eval('self.'+tot+'_'+outops), var, eval('self.'+tot+'_fname'), outops, TSS, MAP)) + MAP = eval("self." + tot + "_" + outops + "_map") + setattr( + self, + tot + "_" + outops, + REPM( + self, + pcr, + eval("self." + tot + "_" + outops), + var, + eval("self." + tot + "_fname"), + outops, + TSS, + MAP, + ), + ) except: - setattr(self, tot + '_'+outops, REPM(self, pcr, eval('self.'+tot+'_'+outops), var, eval('self.'+tot+'_fname'), outops, TSS)) + setattr( + self, + tot + "_" + outops, + REPM( + self, + pcr, + eval("self." + tot + "_" + outops), + var, + eval("self." + tot + "_fname"), + outops, + TSS, + ), + ) except: try: - MAP = eval('self.' + tot + '_' + outops + '_map') - setattr(self, tot + '_'+outops, REPM(self, pcr, eval('self.'+tot+'_'+outops), var, eval('self.'+tot+'_fname'), outops, False, MAP)) + MAP = eval("self." + tot + "_" + outops + "_map") + setattr( + self, + tot + "_" + outops, + REPM( + self, + pcr, + eval("self." + tot + "_" + outops), + var, + eval("self." + tot + "_fname"), + outops, + False, + MAP, + ), + ) except: - pass - + pass Index: wflow-py/wflow/sphy/rootzone.py =================================================================== diff -u -re59169d4b535e077a267eba3d2ba75f73803fbc8 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/sphy/rootzone.py (.../rootzone.py) (revision e59169d4b535e077a267eba3d2ba75f73803fbc8) +++ wflow-py/wflow/sphy/rootzone.py (.../rootzone.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,20 +1,30 @@ -#-Function to calculate rootzone runoff +# -Function to calculate rootzone runoff def RootRunoff(pcr, rainfrac, rootwater, rootsat): rootrunoff = pcr.ifthenelse(rainfrac > 0, pcr.max(rootwater - rootsat, 0), 0) return rootrunoff -#-Function to calculate rootzone drainage + +# -Function to calculate rootzone drainage def RootDrainage(pcr, rootwater, rootdrain, rootfield, rootsat, drainvel, rootTT): rootexcess = pcr.max(rootwater - rootfield, 0) rootexcessfrac = rootexcess / (rootsat - rootfield) rootlat = rootexcessfrac * drainvel - rootdrainage = pcr.max(pcr.min(rootwater, rootlat * (1-pcr.exp(-1/rootTT)) + rootdrain * pcr.exp(-1/rootTT)), 0) + rootdrainage = pcr.max( + pcr.min( + rootwater, + rootlat * (1 - pcr.exp(-1 / rootTT)) + rootdrain * pcr.exp(-1 / rootTT), + ), + 0, + ) return rootdrainage -#-Function to calculate rootzone percolation + +# -Function to calculate rootzone percolation def RootPercolation(pcr, rootwater, subwater, rootfield, rootTT, subsat): rootexcess = pcr.max(rootwater - rootfield, 0) rootperc = rootexcess * (1 - pcr.exp(-1 / rootTT)) - rootperc = pcr.ifthenelse(subwater >= subsat, 0, pcr.min(subsat - subwater, rootperc)) + rootperc = pcr.ifthenelse( + subwater >= subsat, 0, pcr.min(subsat - subwater, rootperc) + ) rootperc = pcr.max(pcr.min(rootperc, rootwater), 0) return rootperc Index: wflow-py/wflow/sphy/subzone.py =================================================================== diff -u -re59169d4b535e077a267eba3d2ba75f73803fbc8 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/sphy/subzone.py (.../subzone.py) (revision e59169d4b535e077a267eba3d2ba75f73803fbc8) +++ wflow-py/wflow/sphy/subzone.py (.../subzone.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,21 +1,29 @@ -#-Function to calculate capillary rise +# -Function to calculate capillary rise def CapilRise(pcr, subfield, subwater, capmax, rootwater, rootsat, rootfield): subrelwat = pcr.max(pcr.min((subwater / subfield), 1), 0) rootrelwat = pcr.max(pcr.min((rootwater / rootfield), 1), 0) caprise = pcr.min(subwater, capmax * (1 - rootrelwat) * subrelwat) - caprise = pcr.min(caprise, rootsat - rootwater) # adding caprise can not exceed saturated rootwater content + caprise = pcr.min( + caprise, rootsat - rootwater + ) # adding caprise can not exceed saturated rootwater content return caprise -#-Function to calculate percolation from subsoil (only if groundwater module is used) + +# -Function to calculate percolation from subsoil (only if groundwater module is used) def SubPercolation(pcr, subwater, subfield, subTT, gw, gwsat): - subperc = pcr.ifthenelse((gw < gwsat) & ((subwater - subfield) > 0), (subwater - subfield) * (1 - pcr.exp(-1 / subTT)), 0) + subperc = pcr.ifthenelse( + (gw < gwsat) & ((subwater - subfield) > 0), + (subwater - subfield) * (1 - pcr.exp(-1 / subTT)), + 0, + ) return subperc -#-Function to calculate drainage from subsoil (only if groundwater module is NOT used) + +# -Function to calculate drainage from subsoil (only if groundwater module is NOT used) def SubDrainage(pcr, subwater, subfield, subsat, drainvel, subdrainage, subTT): subexcess = pcr.max(subwater - subfield, 0) subexcessfrac = subexcess / (subsat - subfield) sublateral = subexcessfrac * drainvel subdrainage = (sublateral + subdrainage) * (1 - pcr.exp(-1 / subTT)) subdrainage = pcr.max(pcr.min(subdrainage, subwater), 0) - return subdrainage \ No newline at end of file + return subdrainage Index: wflow-py/wflow/wf_netcdfio.py =================================================================== diff -u -r1d7c6ea8e5b499f3b79bc4495eebaa42612dc599 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/wf_netcdfio.py (.../wf_netcdfio.py) (revision 1d7c6ea8e5b499f3b79bc4495eebaa42612dc599) +++ wflow-py/wflow/wf_netcdfio.py (.../wf_netcdfio.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -16,8 +16,6 @@ import os - - # the two below are needed fpr bbfreeze try: @@ -34,15 +32,14 @@ import wflow.pcrut as _pcrut globmetadata = {} -globmetadata['title'] = 'wflow output mapstack' -globmetadata['institution'] = 'Deltares' -globmetadata['source'] = 'wflow' -globmetadata['history'] = time.ctime() -globmetadata['references'] = 'https://github.com/openstreams/wflow' -globmetadata['Conventions'] = 'CF-1.4' +globmetadata["title"] = "wflow output mapstack" +globmetadata["institution"] = "Deltares" +globmetadata["source"] = "wflow" +globmetadata["history"] = time.ctime() +globmetadata["references"] = "https://github.com/openstreams/wflow" +globmetadata["Conventions"] = "CF-1.4" - def convertCoord(proj_src, proj_trg, x, y): """ Convert a list of x,y pairs in a certain projection to another projection @@ -55,129 +52,173 @@ X: NumPy array, vector or 2D array of x-coordinates (target) Y: NumPy array, vector or 2D array of y-coordinates (target) """ - srs1 = pyproj.Proj(proj_src) # OPT['proj4_params']) - srs2 = pyproj.Proj(proj_trg) # wgs84 - X,Y = pyproj.transform(srs1, srs2, x,y) # Do add 0. to avoid trunc issues. - return X,Y + srs1 = pyproj.Proj(proj_src) # OPT['proj4_params']) + srs2 = pyproj.Proj(proj_trg) # wgs84 + X, Y = pyproj.transform(srs1, srs2, x, y) # Do add 0. to avoid trunc issues. + return X, Y -def prepare_nc(trgFile, timeList, x, y, metadata, logger, EPSG="EPSG:4326", units=None, - calendar='gregorian', Format="NETCDF4", complevel=9, zlib=True, least_significant_digit=None,FillValue=1E31): +def prepare_nc( + trgFile, + timeList, + x, + y, + metadata, + logger, + EPSG="EPSG:4326", + units=None, + calendar="gregorian", + Format="NETCDF4", + complevel=9, + zlib=True, + least_significant_digit=None, + FillValue=1E31, +): """ This function prepares a NetCDF file with given metadata, for a certain year, daily basis data The function assumes a gregorian calendar and a time unit 'Days since 1900-01-01 00:00:00' """ import datetime as dt - logger.info('Setting up netcdf output: ' + trgFile) + logger.info("Setting up netcdf output: " + trgFile) - if units == None: # Use start of the run + if units == None: # Use start of the run epoch = timeList[0] - units = 'seconds since %04d-%02d-%02d %02d:%02d:%02d.0 00:00' % ( - epoch.year, epoch.month, epoch.day, epoch.hour, epoch.minute, epoch.second) + units = "seconds since %04d-%02d-%02d %02d:%02d:%02d.0 00:00" % ( + epoch.year, + epoch.month, + epoch.day, + epoch.hour, + epoch.minute, + epoch.second, + ) - startDayNr = netCDF4.date2num(timeList[0].replace(tzinfo=None), units=units, calendar=calendar) - endDayNr = netCDF4.date2num(timeList[-1].replace(tzinfo=None), units=units, calendar=calendar) + startDayNr = netCDF4.date2num( + timeList[0].replace(tzinfo=None), units=units, calendar=calendar + ) + endDayNr = netCDF4.date2num( + timeList[-1].replace(tzinfo=None), units=units, calendar=calendar + ) timeAR = linspace(startDayNr, endDayNr, num=len(timeList)) if os.path.exists(trgFile): - os.remove(trgFile) + os.remove(trgFile) - #nc_trg = netCDF4.Dataset(trgFile, 'a', format=Format, zlib=zlib, complevel=complevel) + # nc_trg = netCDF4.Dataset(trgFile, 'a', format=Format, zlib=zlib, complevel=complevel) - nc_trg = netCDF4.Dataset(trgFile, 'w', format=Format, zlib=zlib, complevel=complevel) + nc_trg = netCDF4.Dataset( + trgFile, "w", format=Format, zlib=zlib, complevel=complevel + ) logger.info( - 'Setting up dimensions and attributes. Steps: ' + str(len(timeList)) + ' lat: ' + str(len(y)) + " lon: " + str( - len(x))) + "Setting up dimensions and attributes. Steps: " + + str(len(timeList)) + + " lat: " + + str(len(y)) + + " lon: " + + str(len(x)) + ) if len(timeAR) == 1: - nc_trg.createDimension('time', 1) + nc_trg.createDimension("time", 1) else: - nc_trg.createDimension('time', 0) # NrOfDays*8 + nc_trg.createDimension("time", 0) # NrOfDays*8 - DateHour = nc_trg.createVariable('time', 'f8', ('time',), fill_value=FillValue, zlib=zlib, complevel=complevel) + DateHour = nc_trg.createVariable( + "time", "f8", ("time",), fill_value=FillValue, zlib=zlib, complevel=complevel + ) DateHour.units = units DateHour.calendar = calendar - DateHour.standard_name = 'time' - DateHour.long_name = 'time' - DateHour.axis = 'T' + DateHour.standard_name = "time" + DateHour.long_name = "time" + DateHour.axis = "T" DateHour[:] = timeAR # make a proj4 string srs = osgeo.osr.SpatialReference() res = srs.ImportFromEPSG(int(EPSG[5:])) if res != 0: - logger.error("EPGS not converted correctly: " + EPSG + ". Is the GDAL_DATA environment variable set correctly?") + logger.error( + "EPGS not converted correctly: " + + EPSG + + ". Is the GDAL_DATA environment variable set correctly?" + ) sys.exit(1) projStr = srs.ExportToProj4() - proj_src = '+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs' + proj_src = "+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs" - - if srs.IsProjected() == 0: # ONly lat lon needed - nc_trg.createDimension('lat', len(y)) - nc_trg.createDimension('lon', len(x)) - y_var = nc_trg.createVariable('lat', 'f4', ('lat',), fill_value=FillValue, zlib=zlib, complevel=complevel) - y_var.standard_name = 'latitude' - y_var.long_name = 'latitude' - y_var.units = 'degrees_north' - y_var.axis = 'Y' - x_var = nc_trg.createVariable('lon', 'f4', ('lon',), fill_value=FillValue, zlib=zlib, complevel=complevel) - x_var.standard_name = 'longitude' - x_var.long_name = 'longitude' - x_var.units = 'degrees_east' - x_var.axis = 'X' + if srs.IsProjected() == 0: # ONly lat lon needed + nc_trg.createDimension("lat", len(y)) + nc_trg.createDimension("lon", len(x)) + y_var = nc_trg.createVariable( + "lat", "f4", ("lat",), fill_value=FillValue, zlib=zlib, complevel=complevel + ) + y_var.standard_name = "latitude" + y_var.long_name = "latitude" + y_var.units = "degrees_north" + y_var.axis = "Y" + x_var = nc_trg.createVariable( + "lon", "f4", ("lon",), fill_value=FillValue, zlib=zlib, complevel=complevel + ) + x_var.standard_name = "longitude" + x_var.long_name = "longitude" + x_var.units = "degrees_east" + x_var.axis = "X" y_var[:] = y x_var[:] = x - crs = nc_trg.createVariable('crs', 'c') - crs.long_name = 'wgs84' - crs.proj4_params = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' - crs.grid_mapping_name = 'latitude_longitude' + crs = nc_trg.createVariable("crs", "c") + crs.long_name = "wgs84" + crs.proj4_params = "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs" + crs.grid_mapping_name = "latitude_longitude" else: # Assume regular grid in m - nc_trg.createDimension('y', len(y)) - nc_trg.createDimension('x', len(x)) - y_var = nc_trg.createVariable('y', 'f4', ('y',), fill_value=FillValue, zlib=zlib, complevel=complevel) - y_var.standard_name = 'projection_y_coordinate' - y_var.long_name = 'y-coordinate in Cartesian system' - y_var.units = 'm' - y_var.axis = 'Y' - x_var = nc_trg.createVariable('x', 'f4', ('x',), fill_value=FillValue, zlib=zlib, complevel=complevel) - x_var.standard_name = 'projection_x_coordinate' - x_var.long_name = 'x-coordinate in Cartesian system' - x_var.units = 'm' - x_var.axis = 'X' + nc_trg.createDimension("y", len(y)) + nc_trg.createDimension("x", len(x)) + y_var = nc_trg.createVariable( + "y", "f4", ("y",), fill_value=FillValue, zlib=zlib, complevel=complevel + ) + y_var.standard_name = "projection_y_coordinate" + y_var.long_name = "y-coordinate in Cartesian system" + y_var.units = "m" + y_var.axis = "Y" + x_var = nc_trg.createVariable( + "x", "f4", ("x",), fill_value=FillValue, zlib=zlib, complevel=complevel + ) + x_var.standard_name = "projection_x_coordinate" + x_var.long_name = "x-coordinate in Cartesian system" + x_var.units = "m" + x_var.axis = "X" y_var[:] = y x_var[:] = x - crs = nc_trg.createVariable('crs', 'c') + crs = nc_trg.createVariable("crs", "c") crs.long_name = EPSG - crs.grid_mapping_name = 'universal_transverse_mercator' + crs.grid_mapping_name = "universal_transverse_mercator" crs.utm_zone_number = srs.GetUTMZone() crs.semi_major_axis = srs.GetSemiMajor() crs.inverse_flattening = srs.GetInvFlattening() crs._CoordinateTransformType = "Projection" crs._CoordinateAxisTypes = "y x" crs.proj4_params = projStr # Also write lat lon fields - XI,YI = meshgrid(x,y) - lon_vals,lat_vals = convertCoord(projStr, proj_src, XI, YI) + XI, YI = meshgrid(x, y) + lon_vals, lat_vals = convertCoord(projStr, proj_src, XI, YI) # Need to create lat-lon fields - lat = nc_trg.createVariable('lat','f4',('y','x',)) - lat.standard_name = 'latitude' - lat.long_name = 'latitude coordinate' - lat.units = 'degrees_north' - lat.coordinates = 'lat lon' - lat.grid_mapping = 'wgs84' - #lat._CoordinateAxisType = "Lat" - lat[:,:] = lat_vals - lon = nc_trg.createVariable('lon','f4',('y','x',)) - lon.standard_name = 'longitude' - lon.long_name = 'longitude coordinate' - lon.units = 'degrees_east' - lon.coordinates = 'lat lon' - lon.grid_mapping = 'wgs84' - #lon._CoordinateAxisType = "Lon" - lon[:,:] = lon_vals + lat = nc_trg.createVariable("lat", "f4", ("y", "x")) + lat.standard_name = "latitude" + lat.long_name = "latitude coordinate" + lat.units = "degrees_north" + lat.coordinates = "lat lon" + lat.grid_mapping = "wgs84" + # lat._CoordinateAxisType = "Lat" + lat[:, :] = lat_vals + lon = nc_trg.createVariable("lon", "f4", ("y", "x")) + lon.standard_name = "longitude" + lon.long_name = "longitude coordinate" + lon.units = "degrees_east" + lon.coordinates = "lat lon" + lon.grid_mapping = "wgs84" + # lon._CoordinateAxisType = "Lon" + lon[:, :] = lon_vals crs.EPSG_code = EPSG @@ -188,10 +229,21 @@ nc_trg.close() -class netcdfoutput(): - def __init__(self, netcdffile, logger, starttime, timesteps, EPSG="EPSG:4326", timestepsecs=86400, - metadata={}, zlib=True, Format="NETCDF4", - maxbuf=25, least_significant_digit=None): +class netcdfoutput: + def __init__( + self, + netcdffile, + logger, + starttime, + timesteps, + EPSG="EPSG:4326", + timestepsecs=86400, + metadata={}, + zlib=True, + Format="NETCDF4", + maxbuf=25, + least_significant_digit=None, + ): """ Under construction """ @@ -202,8 +254,11 @@ self.least_significant_digit = least_significant_digit def date_range(start, end, timestepsecs): - r = int((end + dt.timedelta(seconds=timestepsecs) - start).total_seconds()/timestepsecs) - return [start + dt.timedelta(seconds=(timestepsecs * i)) for i in range(r)] + r = int( + (end + dt.timedelta(seconds=timestepsecs) - start).total_seconds() + / timestepsecs + ) + return [start + dt.timedelta(seconds=(timestepsecs * i)) for i in range(r)] self.logger = logger # Do not allow a max buffer larger than the number of timesteps @@ -215,12 +270,16 @@ cellsize = pcraster._pcraster.clone().cellSize() yupper = pcraster._pcraster.clone().north() xupper = pcraster._pcraster.clone().west() - x = _pcrut.pcr2numpy(_pcrut.xcoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN)[0, :] - y = _pcrut.pcr2numpy(_pcrut.ycoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN)[:, 0] + x = _pcrut.pcr2numpy( + _pcrut.xcoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN + )[0, :] + y = _pcrut.pcr2numpy( + _pcrut.ycoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN + )[:, 0] # Shift one timestep as we output at the end - #starttime = starttime + dt.timedelta(seconds=timestepsecs) - end = starttime + dt.timedelta(seconds=timestepsecs * (self.timesteps -1)) + # starttime = starttime + dt.timedelta(seconds=timestepsecs) + end = starttime + dt.timedelta(seconds=timestepsecs * (self.timesteps - 1)) timeList = date_range(starttime, end, timestepsecs) self.timestepbuffer = zeros((self.maxbuf, len(y), len(x))) @@ -229,12 +288,30 @@ globmetadata.update(metadata) - prepare_nc(self.ncfile, timeList, x, y, globmetadata, logger, Format=self.Format, EPSG=EPSG,zlib=self.zlib, - least_significant_digit=self.least_significant_digit) + prepare_nc( + self.ncfile, + timeList, + x, + y, + globmetadata, + logger, + Format=self.Format, + EPSG=EPSG, + zlib=self.zlib, + least_significant_digit=self.least_significant_digit, + ) self.nc_trg = None - def savetimestep(self, timestep, pcrdata, unit="mm", var='P', name="Precipitation",flushonly=False): + def savetimestep( + self, + timestep, + pcrdata, + unit="mm", + var="P", + name="Precipitation", + flushonly=False, + ): """ save a single timestep for a variable @@ -248,7 +325,9 @@ # Open target netCDF file var = os.path.basename(var) if not self.nc_trg: - self.nc_trg = netCDF4.Dataset(self.ncfile, 'a', format=self.Format, zlib=self.zlib, complevel=9) + self.nc_trg = netCDF4.Dataset( + self.ncfile, "a", format=self.Format, zlib=self.zlib, complevel=9 + ) self.nc_trg.set_fill_off() # read time axis and convert to time objects # TODO: use this to append time @@ -263,14 +342,30 @@ try: nc_var = self.nc_trg.variables[var] except: - self.logger.debug("Creating variable " + var + " in netcdf file. Format: " + self.Format) + self.logger.debug( + "Creating variable " + var + " in netcdf file. Format: " + self.Format + ) if self.EPSG.lower() == "epsg:4326": - nc_var = self.nc_trg.createVariable(var, 'f4', ('time', 'lat', 'lon',), fill_value=-9999.0, zlib=self.zlib, - complevel=9, least_significant_digit=self.least_significant_digit) + nc_var = self.nc_trg.createVariable( + var, + "f4", + ("time", "lat", "lon"), + fill_value=-9999.0, + zlib=self.zlib, + complevel=9, + least_significant_digit=self.least_significant_digit, + ) nc_var.coordinates = "lat lon" else: - nc_var = self.nc_trg.createVariable(var, 'f4', ('time', 'y', 'x',), fill_value=-9999.0, zlib=self.zlib, - complevel=9, least_significant_digit=self.least_significant_digit) + nc_var = self.nc_trg.createVariable( + var, + "f4", + ("time", "y", "x"), + fill_value=-9999.0, + zlib=self.zlib, + complevel=9, + least_significant_digit=self.least_significant_digit, + ) nc_var.coordinates = "lat lon" nc_var.grid_mapping = "crs" @@ -293,12 +388,18 @@ if buffreset == 0 or idx == self.maxbuf - 1 or self.timesteps <= timestep: spos = idx - bufpos self.logger.debug( - "Writing buffer for " + var + " to file at: " + str(spos) + " " + str(int(bufpos) + 1) + " timesteps") - nc_var[spos:idx + 1, :, :] = self.bufflst[var][0:bufpos + 1, :, :] + "Writing buffer for " + + var + + " to file at: " + + str(spos) + + " " + + str(int(bufpos) + 1) + + " timesteps" + ) + nc_var[spos : idx + 1, :, :] = self.bufflst[var][0 : bufpos + 1, :, :] self.bufferdirty = False self.nc_trg.sync() - def finish(self): """ Flushes and closes the netcdf file @@ -307,15 +408,28 @@ """ if hasattr(self, "nc_trg"): if self.bufferdirty: - self.logger.warn("Finishing before expected run-length exceeded. Buffer not flushed") + self.logger.warn( + "Finishing before expected run-length exceeded. Buffer not flushed" + ) self.nc_trg.sync() self.nc_trg.close() -class netcdfoutputstatic(): - def __init__(self, netcdffile, logger, starttime, timesteps, EPSG="EPSG:4326", timestepsecs=86400, - metadata={}, zlib=True, Format="NETCDF4", - maxbuf=25, least_significant_digit=None): +class netcdfoutputstatic: + def __init__( + self, + netcdffile, + logger, + starttime, + timesteps, + EPSG="EPSG:4326", + timestepsecs=86400, + metadata={}, + zlib=True, + Format="NETCDF4", + maxbuf=25, + least_significant_digit=None, + ): """ Under construction """ @@ -326,8 +440,11 @@ self.least_significant_digit = least_significant_digit def date_range(start, end, timestepsecs): - r = int((end + dt.timedelta(seconds=timestepsecs) - start).total_seconds()/timestepsecs) - return [start + dt.timedelta(seconds=(timestepsecs * i)) for i in range(r)] + r = int( + (end + dt.timedelta(seconds=timestepsecs) - start).total_seconds() + / timestepsecs + ) + return [start + dt.timedelta(seconds=(timestepsecs * i)) for i in range(r)] self.logger = logger # Do not allow a max buffer larger than the number of timesteps @@ -339,12 +456,16 @@ cellsize = pcraster._pcraster.clone().cellSize() yupper = pcraster._pcraster.clone().north() xupper = pcraster._pcraster.clone().west() - x = _pcrut.pcr2numpy(_pcrut.xcoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN)[0, :] - y = _pcrut.pcr2numpy(_pcrut.ycoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN)[:, 0] + x = _pcrut.pcr2numpy( + _pcrut.xcoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN + )[0, :] + y = _pcrut.pcr2numpy( + _pcrut.ycoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN + )[:, 0] # Shift one timestep as we output at the end - #starttime = starttime + dt.timedelta(seconds=timestepsecs) - end = starttime + dt.timedelta(seconds=timestepsecs * (self.timesteps -1)) + # starttime = starttime + dt.timedelta(seconds=timestepsecs) + end = starttime + dt.timedelta(seconds=timestepsecs * (self.timesteps - 1)) timeList = date_range(starttime, end, timestepsecs) self.timestepbuffer = zeros((self.maxbuf, len(y), len(x))) @@ -353,11 +474,20 @@ globmetadata.update(metadata) - prepare_nc(self.ncfile, timeList, x, y, globmetadata, logger, Format=self.Format, EPSG=EPSG,zlib=self.zlib, - least_significant_digit=self.least_significant_digit) + prepare_nc( + self.ncfile, + timeList, + x, + y, + globmetadata, + logger, + Format=self.Format, + EPSG=EPSG, + zlib=self.zlib, + least_significant_digit=self.least_significant_digit, + ) - - def savetimestep(self, timestep, pcrdata, unit="mm", var='P', name="Precipitation"): + def savetimestep(self, timestep, pcrdata, unit="mm", var="P", name="Precipitation"): """ save a single timestep for a variable @@ -370,7 +500,9 @@ """ # Open target netCDF file var = os.path.basename(var) - self.nc_trg = netCDF4.Dataset(self.ncfile, 'a', format=self.Format, zlib=self.zlib, complevel=9) + self.nc_trg = netCDF4.Dataset( + self.ncfile, "a", format=self.Format, zlib=self.zlib, complevel=9 + ) self.nc_trg.set_fill_off() # read time axis and convert to time objects # TODO: use this to append time @@ -385,14 +517,30 @@ try: nc_var = self.nc_trg.variables[var] except: - self.logger.debug("Creating variable " + var + " in netcdf file. Format: " + self.Format) + self.logger.debug( + "Creating variable " + var + " in netcdf file. Format: " + self.Format + ) if self.EPSG.lower() == "epsg:4326": - nc_var = self.nc_trg.createVariable(var, 'f4', ('time', 'lat', 'lon',), fill_value=-9999.0, zlib=self.zlib, - complevel=9, least_significant_digit=self.least_significant_digit) + nc_var = self.nc_trg.createVariable( + var, + "f4", + ("time", "lat", "lon"), + fill_value=-9999.0, + zlib=self.zlib, + complevel=9, + least_significant_digit=self.least_significant_digit, + ) nc_var.coordinates = "lat lon" else: - nc_var = self.nc_trg.createVariable(var, 'f4', ('time', 'y', 'x',), fill_value=-9999.0, zlib=self.zlib, - complevel=9, least_significant_digit=self.least_significant_digit) + nc_var = self.nc_trg.createVariable( + var, + "f4", + ("time", "y", "x"), + fill_value=-9999.0, + zlib=self.zlib, + complevel=9, + least_significant_digit=self.least_significant_digit, + ) nc_var.coordinates = "lat lon" nc_var.grid_mapping = "crs" @@ -416,8 +564,15 @@ if buffreset == 0 or idx == self.maxbuf - 1 or self.timesteps <= timestep: spos = idx - bufpos self.logger.debug( - "Writing buffer for " + var + " to file at: " + str(spos) + " " + str(int(bufpos) + 1) + " timesteps") - nc_var[spos:idx + 1, :, :] = self.bufflst[var][0:bufpos + 1, :, :] + "Writing buffer for " + + var + + " to file at: " + + str(spos) + + " " + + str(int(bufpos) + 1) + + " timesteps" + ) + nc_var[spos : idx + 1, :, :] = self.bufflst[var][0 : bufpos + 1, :, :] self.nc_trg.sync() self.buffdirty = False @@ -431,10 +586,10 @@ self.nc_trg.sync() self.nc_trg.close() if self.buffdirty: - self.logger.error('Finishing with dirty netcdf write buffer...!') + self.logger.error("Finishing with dirty netcdf write buffer...!") -class netcdfinput(): +class netcdfinput: def __init__(self, netcdffile, logging, vars=[]): """ First try to setup a class read netcdf files @@ -446,7 +601,7 @@ """ if os.path.exists(netcdffile): - self.dataset = netCDF4.Dataset(netcdffile, mode='r') + self.dataset = netCDF4.Dataset(netcdffile, mode="r") else: msg = os.path.abspath(netcdffile) + " not found!" logging.error(msg) @@ -459,85 +614,116 @@ floatspermb = 1048576 / 4 maxmb = 40 - self.maxlentime = len(self.dataset.variables['time']) - self.maxsteps = minimum(maxmb * len(a) / floatspermb + 1,self.maxlentime - 1) + self.maxlentime = len(self.dataset.variables["time"]) + self.maxsteps = minimum(maxmb * len(a) / floatspermb + 1, self.maxlentime - 1) self.fstep = 0 self.lstep = self.fstep + self.maxsteps self.offset = 0 - self.datetime = self.dataset.variables['time'][:] - if hasattr(self.dataset.variables['time'],'units'): - self.timeunits=self.dataset.variables['time'].units + self.datetime = self.dataset.variables["time"][:] + if hasattr(self.dataset.variables["time"], "units"): + self.timeunits = self.dataset.variables["time"].units else: - self.timeunits ='Seconds since 1970-01-01 00:00:00' - if hasattr(self.dataset.variables['time'], 'calendar'): - self.calendar= self.dataset.variables['time'].calendar + self.timeunits = "Seconds since 1970-01-01 00:00:00" + if hasattr(self.dataset.variables["time"], "calendar"): + self.calendar = self.dataset.variables["time"].calendar else: - self.calendar ='gregorian' - self.datetimelist=netCDF4.num2date(self.datetime,self.timeunits, calendar=self.calendar) + self.calendar = "gregorian" + self.datetimelist = netCDF4.num2date( + self.datetime, self.timeunits, calendar=self.calendar + ) try: - self.x = self.dataset.variables['x'][:] + self.x = self.dataset.variables["x"][:] except: - self.x = self.dataset.variables['lon'][:] + self.x = self.dataset.variables["lon"][:] # Now check Y values to see if we must flip the data try: - self.y = self.dataset.variables['y'][:] + self.y = self.dataset.variables["y"][:] except: - self.y = self.dataset.variables['lat'][:] + self.y = self.dataset.variables["lat"][:] # test if 1D or 2D array if len(self.y.shape) == 1: if self.y[0] > self.y[-1]: self.flip = False else: self.flip = True - else: # not sure if this works + else: # not sure if this works self.y = self.y[:][0] if self.y[0] > self.y[-1]: self.flip = False else: self.flip = True + x = _pcrut.pcr2numpy( + _pcrut.xcoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN + )[0, :] + y = _pcrut.pcr2numpy( + _pcrut.ycoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN + )[:, 0] - x = _pcrut.pcr2numpy(_pcrut.xcoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN)[0, :] - y = _pcrut.pcr2numpy(_pcrut.ycoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN)[:, 0] - - #Get average cell size - acc = diff(x).mean() * 0.25 # non-exact match needed becuase of possible rounding problems + # Get average cell size + acc = ( + diff(x).mean() * 0.25 + ) # non-exact match needed becuase of possible rounding problems if self.flip: - (self.latidx,) = logical_and(self.y[::-1] +acc >= y.min(), self.y[::-1] <= y.max() + acc).nonzero() - (self.lonidx,) = logical_and(self.x + acc >= x.min(), self.x <= x.max() + acc).nonzero() + (self.latidx,) = logical_and( + self.y[::-1] + acc >= y.min(), self.y[::-1] <= y.max() + acc + ).nonzero() + (self.lonidx,) = logical_and( + self.x + acc >= x.min(), self.x <= x.max() + acc + ).nonzero() else: - (self.latidx,) = logical_and(self.y +acc >= y.min(), self.y <= y.max() + acc).nonzero() - (self.lonidx,) = logical_and(self.x +acc >= x.min(), self.x <= x.max() + acc).nonzero() + (self.latidx,) = logical_and( + self.y + acc >= y.min(), self.y <= y.max() + acc + ).nonzero() + (self.lonidx,) = logical_and( + self.x + acc >= x.min(), self.x <= x.max() + acc + ).nonzero() if len(self.lonidx) != len(x): logging.error("error in determining X coordinates in netcdf...") logging.error("model expects: " + str(x.min()) + " to " + str(x.max())) - logging.error("got coordinates netcdf: " + str(self.x.min()) + " to " + str(self.x.max())) - logging.error("got len from netcdf x: " + str(len(x)) + " expected " + str(len(self.lonidx))) + logging.error( + "got coordinates netcdf: " + + str(self.x.min()) + + " to " + + str(self.x.max()) + ) + logging.error( + "got len from netcdf x: " + + str(len(x)) + + " expected " + + str(len(self.lonidx)) + ) raise ValueError("X coordinates in netcdf do not match model") if len(self.latidx) != len(y): logging.error("error in determining Y coordinates in netcdf...") logging.error("model expects: " + str(y.min()) + " to " + str(y.max())) - logging.error("got from netcdf: " + str(self.y.min()) + " to " + str(self.y.max())) - logging.error("got len from netcdf y: " + str(len(y)) + " expected " + str(len(self.latidx))) + logging.error( + "got from netcdf: " + str(self.y.min()) + " to " + str(self.y.max()) + ) + logging.error( + "got len from netcdf y: " + + str(len(y)) + + " expected " + + str(len(self.latidx)) + ) raise ValueError("Y coordinates in netcdf do not match model") - for var in vars: try: - #self.alldat[var] = self.dataset.variables[var][self.fstep:self.maxsteps] + # self.alldat[var] = self.dataset.variables[var][self.fstep:self.maxsteps] self.alldat[var] = self.dataset.variables[var] except: self.alldat.pop(var, None) - logging.warn("Variable " + var + " not found in netcdf file: " + netcdffile) + logging.warn( + "Variable " + var + " not found in netcdf file: " + netcdffile + ) - - - def gettimestep(self, timestep, logging, tsdatetime=None, var='P', shifttime=False): + def gettimestep(self, timestep, logging, tsdatetime=None, var="P", shifttime=False): """ Gets a map for a single timestep. reads data in blocks assuming sequential access @@ -558,52 +744,76 @@ else: ncindex = timestep - 1 - ncindex = ncindex + self.offset if self.datetimelist.size < ncindex + 1: - ncindex = self.datetimelist.size -1 + ncindex = self.datetimelist.size - 1 if tsdatetime != None: - if tsdatetime.replace(tzinfo=None) != self.datetimelist[ncindex].replace(tzinfo=None): - logging.warn("Date/time does not match. Wanted " + str(tsdatetime) + " got " + str(self.datetimelist[ncindex])) + if tsdatetime.replace(tzinfo=None) != self.datetimelist[ncindex].replace( + tzinfo=None + ): + logging.warn( + "Date/time does not match. Wanted " + + str(tsdatetime) + + " got " + + str(self.datetimelist[ncindex]) + ) import bisect - pos = bisect.bisect_left(self.datetimelist,tsdatetime.replace(tzinfo=None)) + + pos = bisect.bisect_left( + self.datetimelist, tsdatetime.replace(tzinfo=None) + ) if pos >= self.datetimelist.size: - pos = self.datetimelist.size -1 - logging.warn("No matching date/time found using last date/time again...") + pos = self.datetimelist.size - 1 + logging.warn( + "No matching date/time found using last date/time again..." + ) self.offset = pos - ncindex - logging.warn("Adjusting to the date/time at index and setting offset: " + str(pos) + ":" + str(self.offset) + ":" + str(self.datetimelist[pos])) + logging.warn( + "Adjusting to the date/time at index and setting offset: " + + str(pos) + + ":" + + str(self.offset) + + ":" + + str(self.datetimelist[pos]) + ) ncindex = pos - if self.alldat.has_key(var): - #if ncindex == self.lstep: # Read new block of data in mem + # if ncindex == self.lstep: # Read new block of data in mem # logging.debug("reading new netcdf data block starting at: " + str(ncindex)) # for vars in self.alldat: # self.alldat[vars] = self.dataset.variables[vars][ncindex:ncindex + self.maxsteps] # - #self.fstep = ncindex - #self.lstep = ncindex + self.maxsteps - + # self.fstep = ncindex + # self.lstep = ncindex + self.maxsteps + if len(self.alldat[var].dimensions) == 3: - np_step = self.alldat[var][ncindex - self.fstep,self.latidx.min():self.latidx.max()+1, - self.lonidx.min():self.lonidx.max()+1] + np_step = self.alldat[var][ + ncindex - self.fstep, + self.latidx.min() : self.latidx.max() + 1, + self.lonidx.min() : self.lonidx.max() + 1, + ] if len(self.alldat[var].dimensions) == 4: - np_step = self.alldat[var][ncindex - self.fstep,0,self.latidx.min():self.latidx.max()+1, - self.lonidx.min():self.lonidx.max()+1] + np_step = self.alldat[var][ + ncindex - self.fstep, + 0, + self.latidx.min() : self.latidx.max() + 1, + self.lonidx.min() : self.lonidx.max() + 1, + ] miss = float(self.dataset.variables[var]._FillValue) if self.flip: return numpy2pcr(Scalar, flipud(np_step).copy(), miss), True else: return numpy2pcr(Scalar, np_step, miss), True else: - #logging.debug("Var (" + var + ") not found returning 0") + # logging.debug("Var (" + var + ") not found returning 0") return cover(scalar(0.0)), False -class netcdfinputstates(): +class netcdfinputstates: def __init__(self, netcdffile, logging, vars=[]): """ First try to setup a class read netcdf files @@ -616,7 +826,7 @@ self.fname = netcdffile if os.path.exists(netcdffile): - self.dataset = netCDF4.Dataset(netcdffile, mode='r') + self.dataset = netCDF4.Dataset(netcdffile, mode="r") else: msg = os.path.abspath(netcdffile) + " not found!" logging.error(msg) @@ -632,76 +842,112 @@ self.fstep = 0 self.lstep = self.fstep + self.maxsteps - self.datetime = self.dataset.variables['time'][:] - if hasattr(self.dataset.variables['time'],'units'): - self.timeunits=self.dataset.variables['time'].units + self.datetime = self.dataset.variables["time"][:] + if hasattr(self.dataset.variables["time"], "units"): + self.timeunits = self.dataset.variables["time"].units else: - self.timeunits ='Seconds since 1970-01-01 00:00:00' - if hasattr(self.dataset.variables['time'], 'calendar'): - self.calendar= self.dataset.variables['time'].calendar + self.timeunits = "Seconds since 1970-01-01 00:00:00" + if hasattr(self.dataset.variables["time"], "calendar"): + self.calendar = self.dataset.variables["time"].calendar else: - self.calendar ='gregorian' - self.datetimelist=netCDF4.num2date(self.datetime,self.timeunits, calendar=self.calendar) + self.calendar = "gregorian" + self.datetimelist = netCDF4.num2date( + self.datetime, self.timeunits, calendar=self.calendar + ) try: - self.x = self.dataset.variables['x'][:] + self.x = self.dataset.variables["x"][:] except: - self.x = self.dataset.variables['lon'][:] + self.x = self.dataset.variables["lon"][:] # Now check Y values to see if we must flip the data try: - self.y = self.dataset.variables['y'][:] + self.y = self.dataset.variables["y"][:] except: - self.y = self.dataset.variables['lat'][:] + self.y = self.dataset.variables["lat"][:] # test if 1D or 2D array if len(self.y.shape) == 1: if self.y[0] > self.y[-1]: self.flip = False else: self.flip = True - else: # not sure if this works + else: # not sure if this works self.y = self.y[:][0] if self.y[0] > self.y[-1]: self.flip = False else: self.flip = True + x = _pcrut.pcr2numpy( + _pcrut.xcoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN + )[0, :] + y = _pcrut.pcr2numpy( + _pcrut.ycoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN + )[:, 0] - x = _pcrut.pcr2numpy(_pcrut.xcoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN)[0, :] - y = _pcrut.pcr2numpy(_pcrut.ycoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN)[:, 0] - - #Get average cell size - acc = diff(x).mean() * 0.25 # non-exact match needed becuase of possible rounding problems + # Get average cell size + acc = ( + diff(x).mean() * 0.25 + ) # non-exact match needed becuase of possible rounding problems if self.flip: - (self.latidx,) = logical_and(self.y[::-1] +acc >= y.min(), self.y[::-1] <= y.max() + acc).nonzero() - (self.lonidx,) = logical_and(self.x + acc >= x.min(), self.x <= x.max() + acc).nonzero() + (self.latidx,) = logical_and( + self.y[::-1] + acc >= y.min(), self.y[::-1] <= y.max() + acc + ).nonzero() + (self.lonidx,) = logical_and( + self.x + acc >= x.min(), self.x <= x.max() + acc + ).nonzero() else: - (self.latidx,) = logical_and(self.y +acc >= y.min(), self.y <= y.max() + acc).nonzero() - (self.lonidx,) = logical_and(self.x +acc >= x.min(), self.x <= x.max() + acc).nonzero() + (self.latidx,) = logical_and( + self.y + acc >= y.min(), self.y <= y.max() + acc + ).nonzero() + (self.lonidx,) = logical_and( + self.x + acc >= x.min(), self.x <= x.max() + acc + ).nonzero() if len(self.lonidx) != len(x): logging.error("error in determining X coordinates in netcdf...") logging.error("model expects: " + str(x.min()) + " to " + str(x.max())) - logging.error("got coordinates netcdf: " + str(self.x.min()) + " to " + str(self.x.max())) - logging.error("got len from netcdf x: " + str(len(x)) + " expected " + str(len(self.lonidx))) + logging.error( + "got coordinates netcdf: " + + str(self.x.min()) + + " to " + + str(self.x.max()) + ) + logging.error( + "got len from netcdf x: " + + str(len(x)) + + " expected " + + str(len(self.lonidx)) + ) raise ValueError("X coordinates in netcdf do not match model") if len(self.latidx) != len(y): logging.error("error in determining Y coordinates in netcdf...") logging.error("model expects: " + str(y.min()) + " to " + str(y.max())) - logging.error("got from netcdf: " + str(self.y.min()) + " to " + str(self.y.max())) - logging.error("got len from netcdf y: " + str(len(y)) + " expected " + str(len(self.latidx))) + logging.error( + "got from netcdf: " + str(self.y.min()) + " to " + str(self.y.max()) + ) + logging.error( + "got len from netcdf y: " + + str(len(y)) + + " expected " + + str(len(self.latidx)) + ) raise ValueError("Y coordinates in netcdf do not match model") for var in vars: try: - self.alldat[var] = self.dataset.variables[var][self.fstep:self.maxsteps] + self.alldat[var] = self.dataset.variables[var][ + self.fstep : self.maxsteps + ] except: self.alldat.pop(var, None) - logging.warn("Variable " + var + " not found in netcdf file: " + netcdffile) + logging.warn( + "Variable " + var + " not found in netcdf file: " + netcdffile + ) - def gettimestep(self, timestep, logging, var='P', tsdatetime=None): + def gettimestep(self, timestep, logging, var="P", tsdatetime=None): """ Gets a map for a single timestep. reads data in blocks assuming sequential access @@ -713,20 +959,34 @@ if var in self.dataset.variables: if tsdatetime != None: - if tsdatetime.replace(tzinfo=None) != self.datetimelist[ncindex].replace(tzinfo=None): - logging.warn("Date/time of state (" + var + " in " + self.fname + ")does not match. Wanted " + str(tsdatetime) + " got " + str(self.datetimelist[ncindex])) + if tsdatetime.replace(tzinfo=None) != self.datetimelist[ + ncindex + ].replace(tzinfo=None): + logging.warn( + "Date/time of state (" + + var + + " in " + + self.fname + + ")does not match. Wanted " + + str(tsdatetime) + + " got " + + str(self.datetimelist[ncindex]) + ) - np_step = self.dataset.variables[var][ncindex, self.latidx.min():self.latidx.max() + 1, - self.lonidx.min():self.lonidx.max() + 1] + np_step = self.dataset.variables[var][ + ncindex, + self.latidx.min() : self.latidx.max() + 1, + self.lonidx.min() : self.lonidx.max() + 1, + ] miss = float(self.dataset.variables[var]._FillValue) return numpy2pcr(Scalar, np_step, miss), True else: - #logging.debug("Var (" + var + ") not found returning map with 0.0") + # logging.debug("Var (" + var + ") not found returning map with 0.0") return cover(scalar(0.0)), False -class netcdfinputstatic(): +class netcdfinputstatic: def __init__(self, netcdffile, logging): """ First try to setup a class read netcdf files @@ -738,35 +998,35 @@ """ if os.path.exists(netcdffile): - self.dataset = netCDF4.Dataset(netcdffile, mode='r') + self.dataset = netCDF4.Dataset(netcdffile, mode="r") else: msg = os.path.abspath(netcdffile) + " not found!" logging.error(msg) raise ValueError(msg) - try: - self.x = self.dataset.variables['x'][:] + self.x = self.dataset.variables["x"][:] except: - self.x = self.dataset.variables['lon'][:] + self.x = self.dataset.variables["lon"][:] # Now check Y values to see if we must flip the data try: - self.y = self.dataset.variables['y'][:] + self.y = self.dataset.variables["y"][:] except: - self.y = self.dataset.variables['lat'][:] + self.y = self.dataset.variables["lat"][:] - x = _pcrut.pcr2numpy(_pcrut.xcoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN)[0, :] - y = _pcrut.pcr2numpy(_pcrut.ycoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN)[:, 0] + x = _pcrut.pcr2numpy( + _pcrut.xcoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN + )[0, :] + y = _pcrut.pcr2numpy( + _pcrut.ycoordinate(_pcrut.boolean(_pcrut.cover(1.0))), NaN + )[:, 0] (self.latidx,) = logical_and(self.x >= x.min(), self.x < x.max()).nonzero() (self.lonidx,) = logical_and(self.y >= x.min(), self.y < y.max()).nonzero() - logging.info("Reading static input from netCDF file: " + netcdffile) - - - def gettimestep(self, timestep, logging, var='P'): + def gettimestep(self, timestep, logging, var="P"): """ Gets a map for a single timestep. reads data in blocks assuming sequential access @@ -776,8 +1036,11 @@ """ if self.dataset.variables.has_key(var): - np_step = self.alldat[var][timestep-1, self.latidx.min():self.latidx.max() + 1, - self.lonidx.min():self.lonidx.max() + 1] + np_step = self.alldat[var][ + timestep - 1, + self.latidx.min() : self.latidx.max() + 1, + self.lonidx.min() : self.lonidx.max() + 1, + ] miss = float(self.dataset.variables[var]._FillValue) return numpy2pcr(Scalar, np_step, miss), True else: Index: wflow-py/wflow/wflow_bmi_combined_mp.py =================================================================== diff -u -rb792e0bc51c202acca25ff6186fb52816664a7df -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/wflow_bmi_combined_mp.py (.../wflow_bmi_combined_mp.py) (revision b792e0bc51c202acca25ff6186fb52816664a7df) +++ wflow-py/wflow/wflow_bmi_combined_mp.py (.../wflow_bmi_combined_mp.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -10,6 +10,7 @@ from pcraster import * import multiprocessing + def iniFileSetUp(configfile): """ Reads .ini file and returns a config object. @@ -22,7 +23,7 @@ return config -def configsection(config,section): +def configsection(config, section): """ gets the list of lesy in a section @@ -40,6 +41,7 @@ return ret + class wflowbmi_csdms(bmi.Bmi): """ csdms BMI implementation runner for combined pcraster/python models @@ -64,28 +66,30 @@ self.exchanges = [] self.comp_sep = "@" self.wrtodisk = False - if os.getenv("wflow_bmi_combined_writetodisk",'False') in 'True': + if os.getenv("wflow_bmi_combined_writetodisk", "False") in "True": self.wrtodisk = True self.loggingmode = logging.ERROR - logstr = os.getenv('wflow_bmi_loglevel', 'ERROR') - if logstr in 'ERROR': + logstr = os.getenv("wflow_bmi_loglevel", "ERROR") + if logstr in "ERROR": self.loggingmode = logging.ERROR - if logstr in 'WARNING': + if logstr in "WARNING": self.loggingmode = logging.WARNING - if logstr in 'INFO': + if logstr in "INFO": self.loggingmode = logging.INFO - if logstr in 'DEBUG': + if logstr in "DEBUG": self.loggingmode = logging.DEBUG - self.bmilogger = setlogger('wflow_bmi_combined.log','wflow_bmi_combined_logging',thelevel=self.loggingmode) + self.bmilogger = setlogger( + "wflow_bmi_combined.log", + "wflow_bmi_combined_logging", + thelevel=self.loggingmode, + ) self.bmilogger.info("__init__: wflow_bmi_combined object initialised.") if self.wrtodisk: - self.bmilogger.warn('Will write all bmi set- and get- grids to disk!...') + self.bmilogger.warn("Will write all bmi set- and get- grids to disk!...") - - - def __getmodulenamefromvar__(self,long_var_name): + def __getmodulenamefromvar__(self, long_var_name): """ :param long_var_name: @@ -111,19 +115,17 @@ self.datadir = os.path.dirname(fullpathname) inifile = os.path.basename(filename) - self.models = configsection(self.config,'models') - self.exchanges= configsection(self.config,'exchanges') + self.models = configsection(self.config, "models") + self.exchanges = configsection(self.config, "exchanges") for mod in self.models: self.bmimodels[mod] = wfbmi.wflowbmi_csdms() # Initialize all bmi model objects for key, value in self.bmimodels.iteritems(): - modconf = os.path.join(self.datadir,self.config.get('models',key)) - self.bmimodels[key].initialize_config(modconf,loglevel=loglevel) + modconf = os.path.join(self.datadir, self.config.get("models", key)) + self.bmimodels[key].initialize_config(modconf, loglevel=loglevel) - - def initialize_model(self): """ *Extended functionality*, see https://github.com/eWaterCycle/bmi/blob/master/src/main/python/bmi.py @@ -145,13 +147,11 @@ supplymodel = self.__getmodulenamefromvar__(item) if curmodel == supplymodel: outofmodel = self.get_value(item).copy() - tomodel = self.config.get('exchanges',item) - self.set_value(tomodel,outofmodel) + tomodel = self.config.get("exchanges", item) + self.set_value(tomodel, outofmodel) self.bmilogger.info(self.bmimodels) - - def set_start_time(self, start_time): """ Sets the start time for all bmi models @@ -172,8 +172,6 @@ for key, value in self.bmimodels.iteritems(): self.bmimodels[key].set_end_time(end_time) - - def get_attribute_names(self): """ Get the attributes of the model return in the form of model_name@section_name:attribute_name @@ -183,7 +181,10 @@ names = [] for key, value in self.bmimodels.iteritems(): names.append(self.bmimodels[key].get_attribute_names()) - names[-1] = [self.bmimodels[key].get_component_name() + self.comp_sep + s for s in names[-1]] + names[-1] = [ + self.bmimodels[key].get_component_name() + self.comp_sep + s + for s in names[-1] + ] ret = [item for sublist in names for item in sublist] return ret @@ -199,29 +200,25 @@ cname = attribute_name.split(self.comp_sep) return self.bmimodels[cname[0]].get_attribute_value(cname[1]) - def set_attribute_value(self, attribute_name, attribute_value): """ :param attribute_name: name using the model_name@section:option notation :param attribute_value: string value of the option :return: """ cname = attribute_name.split(self.comp_sep) - self.bmimodels[cname[0]].set_attribute_value(cname[1],attribute_value) + self.bmimodels[cname[0]].set_attribute_value(cname[1], attribute_value) - - def initialize(self, filename,loglevel=logging.DEBUG): + def initialize(self, filename, loglevel=logging.DEBUG): """ Initialise the model. Should be called before any other method. :var filename: full path to the combined model ini file """ - self.initialize_config(filename,loglevel=loglevel) + self.initialize_config(filename, loglevel=loglevel) self.initialize_model() - - def update(self): """ Propagate the model to the next model timestep @@ -237,8 +234,8 @@ supplymodel = self.__getmodulenamefromvar__(item) if curmodel == supplymodel: outofmodel = self.get_value(item) - tomodel = self.config.get('exchanges',item) - self.set_value(tomodel,outofmodel) + tomodel = self.config.get("exchanges", item) + self.set_value(tomodel, outofmodel) self.currenttimestep = self.currenttimestep + 1 @@ -253,27 +250,27 @@ """ curtime = self.get_current_time() - if abs(time - curtime)% self.get_time_step() != 0: + if abs(time - curtime) % self.get_time_step() != 0: raise ValueError("Update in time not a multiple of timestep") if curtime > time: timespan = curtime - time - nrstepsback = int(timespan/self.get_time_step()) + nrstepsback = int(timespan / self.get_time_step()) if nrstepsback > 1: raise ValueError("Time more than one timestep before current time.") for key, value in self.bmimodels.iteritems(): self.bmimodels[key].dynModel.wf_QuickResume() else: timespan = time - curtime - nrsteps = int(timespan/self.get_time_step()) + nrsteps = int(timespan / self.get_time_step()) - #self.dynModel._runDynamic(self.currenttimestep, self.currenttimestep + nrsteps -1) - for st in range(0,nrsteps): - #for key, value in self.bmimodels.iteritems(): + # self.dynModel._runDynamic(self.currenttimestep, self.currenttimestep + nrsteps -1) + for st in range(0, nrsteps): + # for key, value in self.bmimodels.iteritems(): self.update() - #self.currenttimestep = self.currenttimestep + nrsteps + # self.currenttimestep = self.currenttimestep + nrsteps def update_frac(self, time_frac): """ @@ -292,7 +289,6 @@ for key, value in self.bmimodels.iteritems(): self.bmimodels[key].save_state(destination_directory) - def load_state(self, source_directory): """ Ask the model to load its complete internal current state from one or more @@ -324,7 +320,6 @@ return ",".join(names) - def get_input_var_names(self): """ @@ -333,7 +328,10 @@ names = [] for key, value in self.bmimodels.iteritems(): names.append(self.bmimodels[key].get_input_var_names()) - names[-1] = [self.bmimodels[key].get_component_name() + self.comp_sep + s for s in names[-1]] + names[-1] = [ + self.bmimodels[key].get_component_name() + self.comp_sep + s + for s in names[-1] + ] ret = [item for sublist in names for item in sublist] return ret @@ -347,7 +345,10 @@ names = [] for key, value in self.bmimodels.iteritems(): names.append(self.bmimodels[key].get_output_var_names()) - names[-1] = [self.bmimodels[key].get_component_name() + self.comp_sep + s for s in names[-1]] + names[-1] = [ + self.bmimodels[key].get_component_name() + self.comp_sep + s + for s in names[-1] + ] ret = [item for sublist in names for item in sublist] @@ -385,7 +386,6 @@ return ret - def get_var_size(self, long_var_name): """ Gets the number of elements in a variable (rows * cols) @@ -480,8 +480,6 @@ return st[-1] - - def get_value(self, long_var_name): """ Get the value(s) of a variable as a numpy array @@ -490,18 +488,20 @@ :return: a np array of long_var_name """ # first part should be the component name - self.bmilogger.debug('get_value: ' + long_var_name) + self.bmilogger.debug("get_value: " + long_var_name) cname = long_var_name.split(self.comp_sep) if self.bmimodels.has_key(cname[0]): tmp = self.bmimodels[cname[0]].get_value(cname[1]) if self.wrtodisk: - report(numpy2pcr(Scalar,tmp, -999),long_var_name + "_get_" + str(self.get_current_time()) + '.map') + report( + numpy2pcr(Scalar, tmp, -999), + long_var_name + "_get_" + str(self.get_current_time()) + ".map", + ) return tmp else: - self.bmilogger.error('get_value: ' + long_var_name + ' returning None!!!!') + self.bmilogger.error("get_value: " + long_var_name + " returning None!!!!") return None - def get_value_at_indices(self, long_var_name, inds): """ Get a numpy array of the values at the given indices @@ -514,11 +514,10 @@ cname = long_var_name.split(self.comp_sep) if self.bmimodels.has_key(cname[0]): - return self.bmimodels[cname[0]].get_value_at_indices(cname[1],inds) + return self.bmimodels[cname[0]].get_value_at_indices(cname[1], inds) else: return None - def set_value_at_indices(self, long_var_name, inds, src): """ Set the values in a variable using a numpy array of the values given indices @@ -531,9 +530,8 @@ """ cname = long_var_name.split(self.comp_sep) if self.bmimodels.has_key(cname[0]): - self.bmimodels[cname[0]].set_value_at_indices(cname[1], inds,src) + self.bmimodels[cname[0]].set_value_at_indices(cname[1], inds, src) - def get_grid_type(self, long_var_name): """ Get the grid type according to the enumeration in BmiGridType @@ -564,7 +562,6 @@ else: return None - def get_grid_spacing(self, long_var_name): """ Only return something for variables with a uniform grid. Otherwise raise ValueError. @@ -580,7 +577,6 @@ else: return None - def get_grid_origin(self, long_var_name): """ gets the origin of the model grid. @@ -596,7 +592,6 @@ else: return None - def get_grid_x(self, long_var_name): """ Give X coordinates of point in the model grid @@ -613,7 +608,6 @@ else: return None - def get_grid_y(self, long_var_name): """ Give Y coordinates of point in the model grid @@ -646,7 +640,6 @@ else: return None - def get_var_units(self, long_var_name): """ Supply units as defined in the API section of the ini file @@ -673,16 +666,16 @@ is present a uniform map will be set in the wflow model. """ # first part should be the component name - self.bmilogger.debug('set_value: ' + long_var_name) + self.bmilogger.debug("set_value: " + long_var_name) cname = long_var_name.split(self.comp_sep) if self.bmimodels.has_key(cname[0]): - self.bmimodels[cname[0]].set_value(cname[1],src) + self.bmimodels[cname[0]].set_value(cname[1], src) if self.wrtodisk: - report(numpy2pcr(Scalar,src, -999),long_var_name + "_set_" + str(self.get_current_time()) + '.map') + report( + numpy2pcr(Scalar, src, -999), + long_var_name + "_set_" + str(self.get_current_time()) + ".map", + ) - - - def get_grid_connectivity(self, long_var_name): """ Not applicable, raises NotImplementedError Index: wflow-py/wflow/wflow_funcs.py =================================================================== diff -u -re14061eac25a80485dc43ebab91c0f5b07649a78 -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/wflow_funcs.py (.../wflow_funcs.py) (revision e14061eac25a80485dc43ebab91c0f5b07649a78) +++ wflow-py/wflow/wflow_funcs.py (.../wflow_funcs.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -33,68 +33,89 @@ from pcraster import * from pcraster.framework import * - -#import scipy +# import scipy -def rainfall_interception_hbv(Rainfall,PotEvaporation,Cmax,InterceptionStorage): + +def rainfall_interception_hbv(Rainfall, PotEvaporation, Cmax, InterceptionStorage): """ Returns: TF, Interception, IntEvap,InterceptionStorage """ - Interception=min(Rainfall,Cmax-InterceptionStorage)#: Interception in mm/timestep - - InterceptionStorage=InterceptionStorage+Interception #: Current interception storage - TF=Rainfall-Interception - IntEvap=min(InterceptionStorage,PotEvaporation) #: Evaporation from interception storage - InterceptionStorage=InterceptionStorage-IntEvap - - return TF,Interception,IntEvap,InterceptionStorage + Interception = min( + Rainfall, Cmax - InterceptionStorage + ) #: Interception in mm/timestep + InterceptionStorage = ( + InterceptionStorage + Interception + ) #: Current interception storage + TF = Rainfall - Interception + IntEvap = min( + InterceptionStorage, PotEvaporation + ) #: Evaporation from interception storage + InterceptionStorage = InterceptionStorage - IntEvap -def rainfall_interception_gash(Cmax,EoverR,CanopyGapFraction, Precipitation, CanopyStorage,maxevap=9999): + return TF, Interception, IntEvap, InterceptionStorage + + +def rainfall_interception_gash( + Cmax, EoverR, CanopyGapFraction, Precipitation, CanopyStorage, maxevap=9999 +): """ Interception according to the Gash model (For daily timesteps). """ - #TODO: add other rainfall interception method (lui) - #TODO: Include subdaily Gash model - #TODO: add LAI variation in year + # TODO: add other rainfall interception method (lui) + # TODO: Include subdaily Gash model + # TODO: add LAI variation in year # Hack for stemflow - + pt = 0.1 * CanopyGapFraction - - P_sat = max(scalar(0.0),cover((-Cmax / EoverR) * ln (1.0 - (EoverR/(1.0 - CanopyGapFraction - pt))),scalar(0.0))) - + + P_sat = max( + scalar(0.0), + cover( + (-Cmax / EoverR) * ln(1.0 - (EoverR / (1.0 - CanopyGapFraction - pt))), + scalar(0.0), + ), + ) + # large storms P > P_sat largestorms = Precipitation > P_sat - - Iwet = ifthenelse(largestorms, ((1 - CanopyGapFraction - pt) * P_sat) - Cmax, Precipitation * (1 - CanopyGapFraction - pt)) - Isat = ifthenelse(largestorms ,(EoverR) * (Precipitation - P_sat), 0.0) - Idry = ifthenelse (largestorms, Cmax, 0.0) + + Iwet = ifthenelse( + largestorms, + ((1 - CanopyGapFraction - pt) * P_sat) - Cmax, + Precipitation * (1 - CanopyGapFraction - pt), + ) + Isat = ifthenelse(largestorms, (EoverR) * (Precipitation - P_sat), 0.0) + Idry = ifthenelse(largestorms, Cmax, 0.0) Itrunc = 0 - - StemFlow=pt * Precipitation - - ThroughFall = Precipitation- Iwet - Idry- Isat - Itrunc - StemFlow + + StemFlow = pt * Precipitation + + ThroughFall = Precipitation - Iwet - Idry - Isat - Itrunc - StemFlow Interception = Iwet + Idry + Isat + Itrunc - + # Non corect for area without any Interception (say open water Cmax -- zero) CmaxZero = Cmax <= 0.0 - ThroughFall=ifthenelse(CmaxZero, Precipitation,ThroughFall) - Interception=ifthenelse(CmaxZero, scalar(0.0),Interception) - StemFlow=ifthenelse(CmaxZero, scalar(0.0),StemFlow) + ThroughFall = ifthenelse(CmaxZero, Precipitation, ThroughFall) + Interception = ifthenelse(CmaxZero, scalar(0.0), Interception) + StemFlow = ifthenelse(CmaxZero, scalar(0.0), StemFlow) # Now corect for maximum potential evap - OverEstimate = ifthenelse(Interception > maxevap,Interception - maxevap,scalar(0.0)) - Interception = min(Interception,maxevap) + OverEstimate = ifthenelse( + Interception > maxevap, Interception - maxevap, scalar(0.0) + ) + Interception = min(Interception, maxevap) # Add surpluss to the thoughdfall ThroughFall = ThroughFall + OverEstimate - + return ThroughFall, Interception, StemFlow, CanopyStorage - - -def rainfall_interception_modrut(Precipitation,PotEvap,CanopyStorage,CanopyGapFraction,Cmax): + +def rainfall_interception_modrut( + Precipitation, PotEvap, CanopyStorage, CanopyGapFraction, Cmax +): """ Interception according to a modified Rutter model. The model is solved explicitly and there is no drainage below Cmax. @@ -108,7 +129,7 @@ - CanopyStorage: Canopy storage at the end of the timestep """ - + ########################################################################## # Interception according to a modified Rutter model with hourly timesteps# ########################################################################## @@ -117,10 +138,10 @@ pt = 0.1 * p # Amount of P that falls on the canopy - Pfrac = (1 - p -pt) * Precipitation + Pfrac = (1 - p - pt) * Precipitation # S cannot be larger than Cmax, no gravity drainage below that - DD = ifthenelse (CanopyStorage > Cmax , CanopyStorage - Cmax , 0.0) + DD = ifthenelse(CanopyStorage > Cmax, CanopyStorage - Cmax, 0.0) CanopyStorage = CanopyStorage - DD # Add the precipitation that falls on the canopy to the store @@ -129,57 +150,56 @@ # Now do the Evap, make sure the store does not get negative dC = -1 * min(CanopyStorage, PotEvap) CanopyStorage = CanopyStorage + dC - - LeftOver = PotEvap +dC; # Amount of evap not used + LeftOver = PotEvap + dC + # Amount of evap not used # Now drain the canopy storage again if needed... - D = ifthenelse (CanopyStorage > Cmax , CanopyStorage - Cmax , 0.0) + D = ifthenelse(CanopyStorage > Cmax, CanopyStorage - Cmax, 0.0) CanopyStorage = CanopyStorage - D - + # Calculate throughfall ThroughFall = DD + D + p * Precipitation StemFlow = Precipitation * pt - + # Calculate interception, this is NET Interception NetInterception = Precipitation - ThroughFall - StemFlow Interception = -dC - + return NetInterception, ThroughFall, StemFlow, LeftOver, Interception, CanopyStorage - # baseflow seperation methods # see http://mssanz.org.au/MODSIM97/Vol%201/Chapman.pdf + def bf_oneparam(discharge, k): - bf = range(0,len(discharge)) - for i in range(1,len(discharge)): - bf[i] = (k*bf[i-1]/(2.0-k)) + ((1.0-k)*discharge[i]/(2.0-k)) + bf = range(0, len(discharge)) + for i in range(1, len(discharge)): + bf[i] = (k * bf[i - 1] / (2.0 - k)) + ((1.0 - k) * discharge[i] / (2.0 - k)) if bf[i] > discharge[i]: bf[i] = discharge[i] - + return bf -def bf_twoparam(discharge, k,C): - bf = range(0,len(discharge)) - for i in range(1,len(discharge)): - bf[i] = (k*bf[i-1]/(1.0+C)) + ((C)*discharge[i]/(1.0+C)) +def bf_twoparam(discharge, k, C): + bf = range(0, len(discharge)) + for i in range(1, len(discharge)): + bf[i] = (k * bf[i - 1] / (1.0 + C)) + ((C) * discharge[i] / (1.0 + C)) if bf[i] > discharge[i]: bf[i] = discharge[i] - + return bf -def bf_threeparam(discharge, k,C,a): - bf = range(0,len(discharge)) - for i in range(1,len(discharge)): - bf[i] = (k*bf[i-1]/(1.0+C)) + ((C)*discharge[i] + a*discharge[i-1]/(1.0+C)) +def bf_threeparam(discharge, k, C, a): + bf = range(0, len(discharge)) + for i in range(1, len(discharge)): + bf[i] = (k * bf[i - 1] / (1.0 + C)) + ( + (C) * discharge[i] + a * discharge[i - 1] / (1.0 + C) + ) if bf[i] > discharge[i]: bf[i] = discharge[i] - - return bf - - + return bf Index: wflow-py/wflow/wflow_obsolete.py =================================================================== diff -u -rac75d5eab1a097f62294f4e9116f6f8724005cca -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/wflow_obsolete.py (.../wflow_obsolete.py) (revision ac75d5eab1a097f62294f4e9116f6f8724005cca) +++ wflow-py/wflow/wflow_obsolete.py (.../wflow_obsolete.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,17 +1,17 @@ from wflow_hbv import * -class wflow_model(): - + +class wflow_model: def initialize(self, timeStepsToRun, timeStepInSeconds, dataDirectory, iniFile): self.currentTime = 1 runId = "run_default" - configfile=iniFile - wflow_cloneMap = 'wflow_subcatch.map' - # Initializes the model class - myModel = WflowModel(wflow_cloneMap, dataDirectory, runId,configfile) + configfile = iniFile + wflow_cloneMap = "wflow_subcatch.map" + # Initializes the model class + myModel = WflowModel(wflow_cloneMap, dataDirectory, runId, configfile) myModel.timestepsecs = timeStepInSeconds - self.dynModelFw = wf_DynamicFramework(myModel, timeStepsToRun, firstTimestep = 1) - self.dynModelFw.createRunId(NoOverWrite=0) + self.dynModelFw = wf_DynamicFramework(myModel, timeStepsToRun, firstTimestep=1) + self.dynModelFw.createRunId(NoOverWrite=0) self.dynModelFw._runInitial() self.dynModelFw._runResume() @@ -23,7 +23,6 @@ self.currentTime = self.currentTime - 1 self.dynModelFw._runDynamic(self.currentTime, self.currentTime) self.currentTime = self.currentTime + 1 - def get_grid_parameters(self): """ @@ -46,13 +45,11 @@ return self.dynModelFw.wf_supplyVariableUnits() def set_variable_values(self, name, values): - self.dynModelFw.wf_setValues(name,values) + self.dynModelFw.wf_setValues(name, values) def run_time_step(self): self.dynModelFw._runDynamic(self.currentTime, self.currentTime) self.currentTime = self.currentTime + 1 - + def finalize(self): self.dynModelFw._runSuspend() - - Index: wflow-py/wflow/wrappers/rtc/wrapperExtended.py =================================================================== diff -u -rc8e2fba98b7e0b0d9062e2dba1cba046ce931bab -r1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8 --- wflow-py/wflow/wrappers/rtc/wrapperExtended.py (.../wrapperExtended.py) (revision c8e2fba98b7e0b0d9062e2dba1cba046ce931bab) +++ wflow-py/wflow/wrappers/rtc/wrapperExtended.py (.../wrapperExtended.py) (revision 1ca4c471672b8dacc36d3c9d0f38ccc39422c1f8) @@ -1,37 +1,36 @@ import bmi import bmi.wrapper + class BMIWrapperExtended(bmi.wrapper.BMIWrapper): - + # base def update_until(self, time): - + t = self.get_current_time() tEnd = self.get_end_time() - while (t < time): + while t < time: self.update() t = self.get_current_time() - + # getter / setter def get_value(self, var_name): - return self.get_var(var_name) - + return self.get_var(var_name) + def set_value(self, var_name, src): self.set_var(var_name, src) - + # info def get_component_name(self): return "RTC-Tools" - + # time def get_time_units(self): return "s" - + # vars def get_var_itemsize(self, var_name): return 8 - + def get_var_nbytes(self, var_name): return 8 - - \ No newline at end of file