Skip to content

Commit e72fc40

Browse files
Merge pull request #4 from btschwertfeger/dev
Removed forced 'time.month' grouping in `adjust_3d` when no group was specified
2 parents f21ae59 + ac138a6 commit e72fc40

File tree

4 files changed

+35
-58
lines changed

4 files changed

+35
-58
lines changed

.pylintrc

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -425,21 +425,22 @@ disable=raw-checker-failed,
425425
multiple-statements,
426426
line-too-long,
427427
import-error,
428-
consider-using-with
428+
consider-using-with,
429+
c-extension-no-member
429430

430431

431432
# Enable the message, report, category or checker with the given id(s). You can
432433
# either give multiple identifier separated by comma (,) or put this option
433434
# multiple time (only on the command line, not in the configuration file where
434435
# it should appear only once). See also the "--disable" option for examples.
435-
enable=c-extension-no-member
436+
enable=
436437

437438

438439
[METHOD_ARGS]
439440

440441
# List of qualified names (i.e., library.method) which require a timeout
441442
# parameter e.g. 'requests.api.get,requests.api.post'
442-
timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
443+
# timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
443444

444445

445446
[MISCELLANEOUS]

cmethods/CMethods.py

Lines changed: 20 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,7 @@ def adjust_3d(
136136
obs = obs[variable],
137137
simh = simh[variable],
138138
simp = simp[variable],
139-
n_quantiles = 100,
140-
group = 'time.month',
139+
n_quantiles = 250,
141140
n_jobs = 4
142141
)
143142
"""
@@ -146,9 +145,6 @@ def adjust_3d(
146145
simh = simh.transpose("lat", "lon", "time")
147146
simp = simp.transpose("lat", "lon", "time").load()
148147

149-
if group is None and method in cls.SCALING_METHODS:
150-
group = "time.month"
151-
152148
result = simp.copy(deep=True)
153149
len_lat, len_lon = len(simp.lat), len(simp.lon)
154150

@@ -170,6 +166,7 @@ def adjust_3d(
170166
try:
171167
pool = multiprocessing.Pool(processes=n_jobs)
172168
# with multiprocessing.Pool(processes=n_jobs) as pool:
169+
# conntext manager is not use because than the coverage does not work.
173170
params: List[dict] = [
174171
{
175172
"method": method,
@@ -334,8 +331,8 @@ def linear_scaling(
334331
kwargs.get("max_scaling_factor", cls.MAX_SCALING_FACTOR),
335332
)
336333
return np.array(simp) * adj_scaling_factor # Eq. 2
337-
raise ValueError(
338-
'Scaling type invalid. Valid options for param kind: "+" and "*"'
334+
raise NotImplementedError(
335+
f"{kind} not available for linear_scaling. Use '+' or '*' instead."
339336
)
340337

341338
# ? -----========= V A R I A N C E - S C A L I N G =========------
@@ -368,8 +365,7 @@ def variance_scaling(
368365
> simh = xarray.open_dataset('path/to/simulated/data.nc')
369366
> simp = xarray.open_dataset('path/to/predicted/data.nc')
370367
> variable = 'tas'
371-
372-
> result = CMethods().variance_scaling(obs=obs[variable], simh=simh[variable], simp=simp[variable] group='time.dayofyear')
368+
> result = CMethods().variance_scaling(obs=obs[variable], simh=simh[variable], simp=simp[variable] group='time.month')
373369
374370
------ E Q U A T I O N S -----
375371
@@ -413,7 +409,9 @@ def variance_scaling(
413409
VS_2_simp = VS_1_simp * adj_scaling_factor # Eq. 5
414410
return VS_2_simp + np.nanmean(LS_simp) # Eq. 6
415411

416-
raise ValueError(f'"{kind}" not available or variance scaling!')
412+
raise NotImplementedError(
413+
f"{kind} not available for variance_scaling. Use '+' instead."
414+
)
417415

418416
# ? -----========= D E L T A - M E T H O D =========------
419417
@classmethod
@@ -445,7 +443,6 @@ def delta_method(
445443
> simh = xarray.open_dataset('path/to/simulated/data.nc')
446444
> simp = xarray.open_dataset('path/to/predicted/data.nc')
447445
> variable = 'tas'
448-
449446
> result = CMethods().delta_method(obs=obs[variable], simh=simh[variable], group='time.month')
450447
451448
------ E Q U A T I O N S -----
@@ -481,7 +478,9 @@ def delta_method(
481478
kwargs.get("max_scaling_factor", cls.MAX_SCALING_FACTOR),
482479
)
483480
return np.array(obs) * adj_scaling_factor # Eq. 2
484-
raise ValueError(f'{kind} not implemented! Use "+" or "*" instead.')
481+
raise NotImplementedError(
482+
f"{kind} not available for delta_method. Use '+' or '*' instead."
483+
)
485484

486485
# ? -----========= Q U A N T I L E - M A P P I N G =========------
487486
@classmethod
@@ -503,7 +502,6 @@ def quantile_mapping(
503502
simh (xarray.core.dataarray.DataArray): simulated historical Data
504503
simp (xarray.core.dataarray.DataArray): future simulated Data
505504
n_quantiles (int): number of quantiles to use
506-
group (str): [optional] Group / Period (e.g.: 'time.month')
507505
kind (str): '+' or '*', default: '+'
508506
detrended (bool): [optional] detrend by shifting mean on long term basis
509507
@@ -535,20 +533,7 @@ def quantile_mapping(
535533
Alex J. Cannon and Stephen R. Sobie and Trevor Q. Murdock Bias Correction of GCM Precipitation by Quantile Mapping: How Well Do Methods Preserve Changes in Quantiles and Extremes?
536534
https://doi.org/10.1175/JCLI-D-14-00754.1)
537535
"""
538-
# distribution-based adjustment on a grouped basis lead to high deviations
539-
# in the monthly transitions, if group = "time.month". This is also when the group is
540-
# day of year and so on.
541-
# if group is not None:
542-
# return cls.grouped_correction(
543-
# method="quantile_mapping",
544-
# obs=obs,
545-
# simh=simh,
546-
# simp=simp,
547-
# group=group,
548-
# n_quantiles=n_quantiles,
549-
# kind=kind,
550-
# **kwargs,
551-
# )
536+
552537
res = simp.copy(deep=True)
553538
obs, simh, simp = np.array(obs), np.array(simh), np.array(simp)
554539

@@ -614,7 +599,9 @@ def quantile_mapping(
614599
res.values = cls.get_inverse_of_cdf(cdf_obs, epsilon, xbins) # Eq. 2
615600
return res
616601

617-
raise ValueError("Not implemented!")
602+
raise NotImplementedError(
603+
f"{kind} for quantile_mapping is not available. Use '+' or '*' instead."
604+
)
618605

619606
# ? -----========= E M P I R I C A L - Q U A N T I L E - M A P P I N G =========------
620607
@classmethod
@@ -628,8 +615,8 @@ def empirical_quantile_mapping(
628615
**kwargs,
629616
) -> xr.core.dataarray.DataArray:
630617
"""Method to adjust 1 dimensional climate data by empirical quantile mapping"""
631-
raise ValueError(
632-
"not implemented; please have a look at: https://svn.oss.deltares.nl/repos/openearthtools/trunk/python/applications/hydrotools/hydrotools/statistics/bias_correction.py "
618+
raise NotImplementedError(
619+
"Not implemented; please have a look at: https://svn.oss.deltares.nl/repos/openearthtools/trunk/python/applications/hydrotools/hydrotools/statistics/bias_correction.py "
633620
)
634621

635622
# ? -----========= Q U A N T I L E - D E L T A - M A P P I N G =========------
@@ -640,7 +627,6 @@ def quantile_delta_mapping(
640627
simh: xr.core.dataarray.DataArray,
641628
simp: xr.core.dataarray.DataArray,
642629
n_quantiles: int,
643-
# group: Union[str, None] = None,
644630
kind: str = "+",
645631
**kwargs,
646632
) -> xr.core.dataarray.DataArray:
@@ -652,7 +638,6 @@ def quantile_delta_mapping(
652638
simh (xarray.core.dataarray.DataArray): simulated historical Data
653639
simp (xarray.core.dataarray.DataArray): future simulated Data
654640
n_quantiles (int): number of quantiles to use
655-
group (str): [optional] Group / Period (e.g.: 'time.month')
656641
kind (str): '+' or '*', default: '+'
657642
global_min (float): this parameter can be set when kind == '*' to define a custom lower limit. Otherwise 0.0 is used.
658643
@@ -688,20 +673,6 @@ def quantile_delta_mapping(
688673
689674
"""
690675

691-
# distribution-based adjustment on a grouped basis lead to high deviations
692-
# in the monthly transitions, if group = "time.month". This is also when the group is
693-
# day of year and so on.
694-
# if group is not None:
695-
# return cls.grouped_correction(
696-
# method="quantile_delta_mapping",
697-
# obs=obs,
698-
# simh=simh,
699-
# simp=simp,
700-
# group=group,
701-
# n_quantiles=n_quantiles,
702-
# kind=kind,
703-
# **kwargs,
704-
# )
705676
if kind in cls.ADDITIVE:
706677
res = simp.copy(deep=True)
707678
obs, simh, simp = (
@@ -747,7 +718,9 @@ def quantile_delta_mapping(
747718

748719
res.values = QDM1 * delta # Eq. 2.4
749720
return res
750-
raise ValueError(f"Unknown kind {kind}!")
721+
raise NotImplementedError(
722+
f"{kind} not available for quantile_delta_mapping. Use '+' or '*' instead."
723+
)
751724

752725
# * -----========= G E N E R A L =========------
753726
@staticmethod

tests/requirements.txt

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
netCDF4>=1.6.1
12
numpy
3+
pytest
24
scikit-learn
3-
xarray
5+
tqdm
6+
xarray>=2022.11.0

tests/test_methods.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ def test_3d_sclaing_methods(self) -> None:
240240
simh=self.data[kind]["simh"],
241241
simp=self.data[kind]["simp"],
242242
kind=kind,
243-
goup="time.month", # default
243+
group="time.month", # default
244244
)
245245
assert isinstance(result, xr.core.dataarray.DataArray)
246246
for lat in range(len(self.data[kind]["obsh"].lat)):
@@ -339,7 +339,7 @@ def test_unknown_method(self) -> None:
339339

340340
def test_not_implemented_methods(self) -> None:
341341
kind = "+"
342-
with pytest.raises(ValueError):
342+
with pytest.raises(NotImplementedError):
343343
CMethods.empirical_quantile_mapping(
344344
self.data[kind]["obsh"],
345345
self.data[kind]["simh"],
@@ -349,36 +349,36 @@ def test_not_implemented_methods(self) -> None:
349349

350350
def test_invalid_adjustment_type(self) -> None:
351351
kind = "+"
352-
with pytest.raises(ValueError):
352+
with pytest.raises(NotImplementedError):
353353
CMethods.linear_scaling(
354354
self.data[kind]["obsh"],
355355
self.data[kind]["simh"],
356356
self.data[kind]["simp"],
357357
kind="/",
358358
)
359-
with pytest.raises(ValueError):
359+
with pytest.raises(NotImplementedError):
360360
CMethods.variance_scaling(
361361
self.data[kind]["obsh"],
362362
self.data[kind]["simh"],
363363
self.data[kind]["simp"],
364364
kind="*",
365365
)
366-
with pytest.raises(ValueError):
366+
with pytest.raises(NotImplementedError):
367367
CMethods.delta_method(
368368
self.data[kind]["obsh"],
369369
self.data[kind]["simh"],
370370
self.data[kind]["simp"],
371371
kind="/",
372372
)
373-
with pytest.raises(ValueError):
373+
with pytest.raises(NotImplementedError):
374374
CMethods.quantile_mapping(
375375
self.data[kind]["obsh"],
376376
self.data[kind]["simh"],
377377
self.data[kind]["simp"],
378378
kind="/",
379379
n_quantiles=10,
380380
)
381-
with pytest.raises(ValueError):
381+
with pytest.raises(NotImplementedError):
382382
CMethods.quantile_delta_mapping(
383383
self.data[kind]["obsh"],
384384
self.data[kind]["simh"],

0 commit comments

Comments
 (0)