Skip to content

Commit fd9cdef

Browse files
committed
Try to fix more tests
1 parent 14aac79 commit fd9cdef

7 files changed

Lines changed: 75 additions & 80 deletions

File tree

docs/source/notebooks/ops.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@
217217
# [Pint](https://pint.readthedocs.io) and some other work, this operation
218218
# is also unit aware.
219219
#
220-
# There are two methods of integration available, `cumtrapz` and `cumsum`.
220+
# There are two methods of integration available, `cumulative_trapezoid` and `cumsum`.
221221
# The method that should be used depends on the data you are integrating,
222222
# specifically whether the data are piecewise linear or piecewise constant.
223223
#
@@ -226,18 +226,18 @@
226226
#
227227
# Other output such as effective radiative forcing, concentrations or decadal
228228
# timeseries of emissions, represent a point estimate or an average over a period.
229-
# These timeseries are therefore piecewise linear and should use the `cumtrapz`
229+
# These timeseries are therefore piecewise linear and should use the `cumulative_trapezoid`
230230
# method.
231231

232232
# %%
233233
with warnings.catch_warnings():
234234
# Ignore warning about nans in the historical timeseries
235235
warnings.filterwarnings("ignore", module="scmdata.ops")
236236

237-
# Radiative Forcings are piecewise-linear so `cumtrapz` should be used
237+
# Radiative Forcings are piecewise-linear so `cumulative_trapezoid` should be used
238238
erf_integral = (
239239
db_forcing.filter(variable="Effective Radiative Forcing")
240-
.cumtrapz()
240+
.cumulative_trapezoid()
241241
.convert_unit("TJ / m^2")
242242
)
243243

@@ -416,13 +416,7 @@
416416
)
417417
erf_total_for_shift_rel_to_ref_period_shifted[
418418
"label"
419-
] = "rel. to {} - {} (median of {} - {} mean adjusted to {})".format(
420-
ref_period[0],
421-
ref_period[-1],
422-
evaluation_period[0],
423-
evaluation_period[-1],
424-
target,
425-
)
419+
] = f"rel. to {ref_period[0]} - {ref_period[-1]} (median of {evaluation_period[0]} - {evaluation_period[-1]} mean adjusted to {target})" # noqa: E501
426420

427421
# %%
428422
pdf = run_append(

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,7 @@ authorized_licenses = [
267267
"mit",
268268
"mit license",
269269
"Mozilla Public License 2.0 (MPL 2.0)",
270+
"psf-2.0",
270271
"python software foundation",
271272
"python software foundation license",
272273
"zpl 2.1",

src/scmdata/ops.py

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
`Pint's Pandas interface <https://pint.readthedocs.io/en/0.13/pint-pandas.html>`_
66
to handle unit conversions automatically
77
"""
8+
89
import warnings
910

1011
import numpy as np
@@ -113,10 +114,9 @@ def _perform_op(base, other, op, use_pint_units=True):
113114
elif op == "subtract":
114115
out.append(base[col] - other[col])
115116

116-
except KeyError:
117-
raise KeyError( # noqa: TRY200
118-
f"No equivalent in `other` for {list(zip(col_names, col))}"
119-
)
117+
except KeyError as exc:
118+
msg = f"No equivalent in `other` for {list(zip(col_names, col))}"
119+
raise KeyError(msg) from exc
120120

121121
elif op == "multiply":
122122
out.append(base[col] * other[col])
@@ -227,17 +227,17 @@ def subtract(self, other, op_cols, **kwargs):
227227
>>> fos_minus_afolu.head()
228228
time 2010-01-01 2020-01-01
229229
model region scenario unit variable
230-
idealised World|NH idealised gigatC / a Emissions|CO2|Fossil - AFOLU -0.001 3.995
231-
World|SH idealised gigatC / a Emissions|CO2|Fossil - AFOLU 1.997 5.993
230+
idealised World|NH idealised gigatC / yr Emissions|CO2|Fossil - AFOLU -0.001 3.995
231+
World|SH idealised gigatC / yr Emissions|CO2|Fossil - AFOLU 1.997 5.993
232232
233233
>>> nh = start.filter(region="World|NH")
234234
>>> sh = start.filter(region="World|SH")
235235
>>> nh_minus_sh = nh.subtract(sh, op_cols={"region": "World|NH - SH"})
236236
>>> nh_minus_sh.head()
237237
time 2010-01-01 2020-01-01
238238
model region scenario unit variable
239-
idealised World|NH - SH idealised gigatC / a Emissions|CO2|Fossil -2.0 -2.0
240-
megatC / a Emissions|CO2|AFOLU -2.0 -2.0
239+
idealised World|NH - SH idealised gigatC / yr Emissions|CO2|Fossil -2.0 -2.0
240+
megatC / yr Emissions|CO2|AFOLU -2.0 -2.0
241241
"""
242242
out = _perform_op(
243243
prep_for_op(self, op_cols, self.meta.columns, **kwargs),
@@ -336,17 +336,17 @@ def add(self, other, op_cols, **kwargs):
336336
>>> fos_plus_afolu.head()
337337
time 2010-01-01 2020-01-01
338338
model region scenario unit variable
339-
idealised World|NH idealised gigatC / a Emissions|CO2|Fossil + AFOLU 0.001 4.005
340-
World|SH idealised gigatC / a Emissions|CO2|Fossil + AFOLU 2.003 6.007
339+
idealised World|NH idealised gigatC / yr Emissions|CO2|Fossil + AFOLU 0.001 4.005
340+
World|SH idealised gigatC / yr Emissions|CO2|Fossil + AFOLU 2.003 6.007
341341
342342
>>> nh = start.filter(region="World|NH")
343343
>>> sh = start.filter(region="World|SH")
344344
>>> nh_plus_sh = nh.add(sh, op_cols={"region": "World|NH + SH"})
345345
>>> nh_plus_sh.head()
346346
time 2010-01-01 2020-01-01
347347
model region scenario unit variable
348-
idealised World|NH + SH idealised gigatC / a Emissions|CO2|Fossil 2.0 10.0
349-
megatC / a Emissions|CO2|AFOLU 4.0 12.0
348+
idealised World|NH + SH idealised gigatC / yr Emissions|CO2|Fossil 2.0 10.0
349+
megatC / yr Emissions|CO2|AFOLU 4.0 12.0
350350
"""
351351
out = _perform_op(
352352
prep_for_op(self, op_cols, self.meta.columns, **kwargs),
@@ -544,14 +544,14 @@ def divide(self, other, op_cols, **kwargs):
544544
World|SH idealised MtC / yr Emissions|CO2|AFOLU 3.0 7.0
545545
546546
>>> fos_divide_afolu = fos.divide(
547-
... afolu, op_cols={"variable": "Emissions|CO2|Fossil / AFOLU"}
547+
... afolu, op_cols={"variable": "Emissions|CO2|Fossil / yrFOLU"}
548548
... )
549549
>>> # The rows align and the units are handled automatically
550550
>>> fos_divide_afolu.convert_unit("dimensionless").head()
551551
time 2010-01-01 2020-01-01
552552
model region scenario unit variable
553-
idealised World|NH idealised dimensionless Emissions|CO2|Fossil / AFOLU 0.000000 800.000000
554-
World|SH idealised dimensionless Emissions|CO2|Fossil / AFOLU 666.666667 857.142857
553+
idealised World|NH idealised dimensionless Emissions|CO2|Fossil / yrFOLU 0.000000 800.000000
554+
World|SH idealised dimensionless Emissions|CO2|Fossil / yrFOLU 666.666667 857.142857
555555
556556
>>> nh = start.filter(region="World|NH")
557557
>>> sh = start.filter(region="World|SH")
@@ -597,7 +597,7 @@ def cumsum(self, out_var=None, check_annual=True):
597597
arbitrary day/month of the year has not been implemented, if that would be
598598
useful raise an issue on GitHub.
599599
600-
If the timeseries are piecewise-linear, :meth:`cumtrapz` should be used instead.
600+
If the timeseries are piecewise-linear, :meth:`cumulative_trapezoid` should be used instead.
601601
602602
Parameters
603603
----------
@@ -618,7 +618,7 @@ def cumsum(self, out_var=None, check_annual=True):
618618
619619
See Also
620620
--------
621-
:func:`cumtrapz`
621+
:func:`cumulative_trapezoid`
622622
623623
Raises
624624
------
@@ -677,7 +677,7 @@ def cumsum(self, out_var=None, check_annual=True):
677677
return out
678678

679679

680-
def cumtrapz(self, out_var=None):
680+
def cumulative_trapezoid(self, out_var=None):
681681
"""
682682
Integrate with respect to time using the trapezoid rule
683683
@@ -743,7 +743,9 @@ def cumtrapz(self, out_var=None):
743743
# some thinking about unit handling
744744
_initial = 0.0
745745
out = pd.DataFrame(
746-
scipy.integrate.cumtrapz(y=ts, x=times_in_s, axis=1, initial=_initial)
746+
scipy.integrate.cumulative_trapezoid(
747+
y=ts, x=times_in_s, axis=1, initial=_initial
748+
)
747749
)
748750
out.index = ts.index
749751
out.columns = ts.columns
@@ -790,7 +792,7 @@ def integrate(self, out_var=None):
790792
See Also
791793
--------
792794
:meth:`cumsum`
793-
:meth:`cumtrapz`
795+
:meth:`cumulative_trapezoid`
794796
795797
Raises
796798
------
@@ -805,14 +807,14 @@ def integrate(self, out_var=None):
805807
data will also contain nans.
806808
DeprecationWarning
807809
This function has been deprecated in preference to :meth:`cumsum` and
808-
:meth:`cumtrapz`.
810+
:meth:`cumulative_trapezoid`.
809811
"""
810812
warnings.warn(
811-
"integrate has been deprecated in preference of cumsum and cumtrapz",
813+
"integrate has been deprecated in preference of cumsum and cumulative_trapezoid",
812814
DeprecationWarning,
813815
)
814816

815-
return cumtrapz(self, out_var)
817+
return cumulative_trapezoid(self, out_var)
816818

817819

818820
def delta_per_delta_time(self, out_var=None):
@@ -1144,7 +1146,7 @@ def inject_ops_methods(cls):
11441146
("divide", divide),
11451147
("integrate", integrate),
11461148
("cumsum", cumsum),
1147-
("cumtrapz", cumtrapz),
1149+
("cumulative_trapezoid", cumulative_trapezoid),
11481150
("delta_per_delta_time", delta_per_delta_time),
11491151
("linear_regression", linear_regression),
11501152
("linear_regression_gradient", linear_regression_gradient),

tests/unit/test_ops.py

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ def test_no_scipy(scm_run):
9999
with pytest.raises(
100100
ImportError, match="scipy is not installed. Run 'pip install scipy'"
101101
):
102-
scm_run.cumtrapz()
102+
scm_run.cumulative_trapezoid()
103103

104104

105105
@OPS_MARK
@@ -113,10 +113,10 @@ def test_single_timeseries(op, base_single_scmrun, other_single_scmrun):
113113
exp_ts["variable"] = "Emissions|CO2|AFOLU"
114114

115115
if op in ["add", "subtract"]:
116-
exp_ts["unit"] = "gigatC / a"
116+
exp_ts["unit"] = "gigatC / yr"
117117

118118
elif op == "multiply":
119-
exp_ts["unit"] = "gigatC ** 2 / a ** 2"
119+
exp_ts["unit"] = "gigatC ** 2 / yr ** 2"
120120

121121
elif op == "divide":
122122
exp_ts["unit"] = "dimensionless"
@@ -170,7 +170,7 @@ def test_different_unit_error():
170170

171171
error_msg = re.escape(
172172
"Cannot convert from 'kelvin' ([temperature]) to "
173-
"'gigatC' ([carbon] * [mass])"
173+
"'gigatC' ([mass] * [carbon])"
174174
)
175175
with pytest.raises(DimensionalityError, match=error_msg):
176176
base.add(other, op_cols={"variable": "Warming plus Cumulative emissions CO2"})
@@ -262,10 +262,10 @@ def test_scalar_ops_pint(op):
262262
exp = ScmRun(exp_ts)
263263

264264
if op in ["add", "subtract"]:
265-
exp["unit"] = "gigatC / a"
265+
exp["unit"] = "gigatC / yr"
266266

267267
elif op == "multiply":
268-
exp["unit"] = "gigatC * megatC / a ** 2"
268+
exp["unit"] = "gigatC * megatC / yr ** 2"
269269

270270
elif op == "divide":
271271
exp["unit"] = "gigatC / megatC"
@@ -315,7 +315,7 @@ def test_scalar_multiply_pint_by_run():
315315
exp_ts = perform_pint_op(start, scalar, "multiply_inverse")
316316
exp = ScmRun(exp_ts)
317317

318-
exp["unit"] = "megatC * gigatC / a**2"
318+
exp["unit"] = "megatC * gigatC / yr**2"
319319

320320
res = scalar * start
321321

@@ -330,8 +330,8 @@ def test_scalar_ops_pint_wrong_unit(op):
330330
)
331331

332332
error_msg = re.escape(
333-
"Cannot convert from 'gigatC / a' ([carbon] * [mass] / [time]) "
334-
"to 'CH4 * megametric_ton / a' ([mass] * [methane] / [time])"
333+
"Cannot convert from 'gigatC / yr' ([mass] * [carbon] / [time]) "
334+
"to 'megametric_ton * CH4 / yr' ([mass] * [methane] / [time])"
335335
)
336336
with pytest.raises(DimensionalityError, match=error_msg):
337337
if op == "add":
@@ -356,10 +356,10 @@ def test_vector_ops_pint(op):
356356
exp = ScmRun(exp_ts)
357357

358358
if op in ["add", "subtract"]:
359-
exp["unit"] = "gigatC / a"
359+
exp["unit"] = "gigatC / yr"
360360

361361
elif op == "multiply":
362-
exp["unit"] = "gigatC * megatC / a ** 2"
362+
exp["unit"] = "gigatC * megatC / yr ** 2"
363363

364364
elif op == "divide":
365365
exp["unit"] = "gigatC / megatC"
@@ -391,8 +391,8 @@ def test_vector_ops_pint_wrong_unit(op, start_unit):
391391
)
392392

393393
error_msg = re.escape(
394-
"Cannot convert from 'gigatC / a' ([carbon] * [mass] / [time]) "
395-
"to 'CH4 * megametric_ton / a' ([mass] * [methane] / [time])"
394+
"Cannot convert from 'gigatC / yr' ([mass] * [carbon] / [time]) "
395+
"to 'megametric_ton * CH4 / yr' ([mass] * [methane] / [time])"
396396
)
397397
with pytest.raises(DimensionalityError, match=error_msg):
398398
if op == "add":
@@ -549,11 +549,11 @@ def test_wrong_length_ops(op):
549549
# We can add initial back if use case arises. At the moment I can't see an easy
550550
# way to make the units behave.
551551
# @pytest.mark.parametrize("initial", (None, 0, 1, -1.345))
552-
def test_cumtrapz(out_var):
552+
def test_cumulative_trapezoid(out_var):
553553
dat = [1, 2, 3]
554554
start = get_single_ts(data=dat, index=[1, 2, 3], unit="GtC / yr")
555555

556-
res = start.cumtrapz(out_var=out_var)
556+
res = start.cumulative_trapezoid(out_var=out_var)
557557

558558
if out_var is None:
559559
exp_var = ("Cumulative " + start["variable"]).values
@@ -570,10 +570,10 @@ def test_cumtrapz(out_var):
570570
)
571571

572572

573-
def test_cumtrapz_time_handling_big_jumps():
573+
def test_cumulative_trapezoid_time_handling_big_jumps():
574574
start = get_single_ts(data=[1, 2, 3], index=[10, 20, 50], unit="GtC / yr")
575575

576-
res = start.cumtrapz()
576+
res = start.cumulative_trapezoid()
577577

578578
npt.assert_allclose(
579579
res.values.squeeze(),
@@ -582,12 +582,12 @@ def test_cumtrapz_time_handling_big_jumps():
582582
)
583583

584584

585-
def test_cumtrapz_time_handling_all_over_jumps():
585+
def test_cumulative_trapezoid_time_handling_all_over_jumps():
586586
start = get_single_ts(
587587
data=[1, 2, 3, 3, 1.8], index=[10, 10.1, 11, 20, 50], unit="GtC / yr"
588588
)
589589

590-
res = start.cumtrapz()
590+
res = start.cumulative_trapezoid()
591591

592592
first = 0
593593
second = first + 1.5 * 0.1
@@ -603,7 +603,7 @@ def test_cumtrapz_time_handling_all_over_jumps():
603603
"method,exp",
604604
[
605605
("cumsum", [1, 3, 6, np.nan, np.nan, np.nan, np.nan, np.nan]),
606-
("cumtrapz", [0, 1.5, 4, np.nan, np.nan, np.nan, np.nan, np.nan]),
606+
("cumulative_trapezoid", [0, 1.5, 4, np.nan, np.nan, np.nan, np.nan, np.nan]),
607607
],
608608
)
609609
def test_integration_nan_handling(method, exp):
@@ -633,7 +633,7 @@ def test_integration_nan_handling(method, exp):
633633
@pytest.mark.xfail(
634634
_check_pandas_less_110(), reason="pandas<=1.1.0 does not have rtol argument"
635635
)
636-
def test_cumtrapz_multiple_ts():
636+
def test_cumulative_trapezoid_multiple_ts():
637637
variables = ["Emissions|CO2", "Heat Uptake", "Temperature"]
638638
start = get_multiple_ts(
639639
data=np.array([[1, 2, 3], [-1, -2, -3], [0, 5, 10]]).T,
@@ -642,7 +642,7 @@ def test_cumtrapz_multiple_ts():
642642
unit=["Mt CO2 / yr", "W / m^2", "K"],
643643
)
644644

645-
res = start.cumtrapz()
645+
res = start.cumulative_trapezoid()
646646

647647
exp = get_single_ts(
648648
data=np.array([[0, 7.5, 45], [0, -7.5, -45], [0, 12.5, 125]]).T,
@@ -730,7 +730,9 @@ def test_integrate_deprecated():
730730
dat = [1, 2, 3]
731731
start = get_single_ts(data=dat, index=[2020, 2021, 2024], unit="GtC / yr")
732732

733-
match = "integrate has been deprecated in preference of cumsum and cumtrapz"
733+
match = (
734+
"integrate has been deprecated in preference of cumsum and cumulative_trapezoid"
735+
)
734736
with pytest.warns(DeprecationWarning, match=match):
735737
start.integrate()
736738

tests/unit/test_pyam_compat.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,7 @@ def test_to_int_value_error(test_iam_df):
1919
)
2020

2121
else:
22-
error_msg = re.escape(
23-
f'time data "{bad_val}" '
24-
"doesn't match format "
25-
'"%Y/%m/%d", at position 4. You might want to try:'
26-
)
22+
error_msg = re.escape(f"Invalid time domain: {bad_val}")
2723

2824
with pytest.raises(ValueError, match=error_msg):
2925
LongDatetimeIamDataFrame(idf)

0 commit comments

Comments
 (0)