From 9a43d58cf6f5b079518b15369c34e68ab5e66f2b Mon Sep 17 00:00:00 2001 From: "henrydingliu@gmail.com" Date: Sun, 4 Oct 2026 08:08:34 +0000 Subject: [PATCH 01/12] fix _pattern breaking read_pickle --- .gitignore | 2 + chainladder/core/tests/test_io.py | 261 ++++++++++++++++++++++ chainladder/core/triangle.py | 2 +- chainladder/utils/data/raa_0_10_0.pkl | Bin 0 -> 2045 bytes chainladder/utils/data/raa_0_8_24.pkl | Bin 0 -> 2068 bytes chainladder/utils/data/raa_0_9_1.pkl | Bin 0 -> 2047 bytes chainladder/utils/tests/test_utilities.py | 143 ------------ 7 files changed, 264 insertions(+), 144 deletions(-) create mode 100644 chainladder/core/tests/test_io.py create mode 100644 chainladder/utils/data/raa_0_10_0.pkl create mode 100644 chainladder/utils/data/raa_0_8_24.pkl create mode 100644 chainladder/utils/data/raa_0_9_1.pkl diff --git a/.gitignore b/.gitignore index 7808b45c4..f459162f0 100644 --- a/.gitignore +++ b/.gitignore @@ -117,6 +117,8 @@ settings.json *.pkl +!chainladder/utils/data/*.pkl + # macOS related files *.DS_Store *Icon? diff --git a/chainladder/core/tests/test_io.py b/chainladder/core/tests/test_io.py new file mode 100644 index 000000000..159f2e9e7 --- /dev/null +++ b/chainladder/core/tests/test_io.py @@ -0,0 +1,261 @@ +from __future__ import annotations + +import numpy as np +import chainladder as cl +import dill +import pytest + +from pathlib import Path + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from chainladder import Triangle + + +class TestJSON: + """Test JSON IO""" + + def test_triangle_json_io(self, clrd: Triangle) -> None: + """ + test JSON round trip for Triangle + + Parameters + ---------- + clrd: Triangle + The CLRD sample data set fixture + + Returns + ------- + None + """ + clrd2 = cl.read_json(clrd.to_json(), array_backend=clrd.array_backend) + assert clrd == clrd2 + assert np.all(clrd.kdims == clrd2.kdims) + assert np.all(clrd.vdims == clrd2.vdims) + assert np.all(clrd.odims == clrd2.odims) + assert np.all(clrd.ddims == clrd2.ddims) + assert np.all(clrd.valuation == clrd2.valuation) + + def test_json_for_val(self, raa: Triangle) -> None: + """ + test JSON round trip for val Triangle + + Parameters + ---------- + raa: Triangle + The CLRD sample data set fixture + + Returns + ------- + None + """ + x = raa.dev_to_val().to_json() + assert cl.read_json(x) == raa.dev_to_val() + + + def test_estimator_json_io(self) -> None: + """ + test JSON round trip for Development estimator + + Returns + ------- + None + """ + assert ( + cl.read_json(cl.Development().to_json()).get_params() + == cl.Development().get_params() + ) + + + def test_pipeline_json_io(self) -> None: + """ + test JSON round trip for an estimator pipeline + + Returns + ------- + None + """ + pipe = cl.Pipeline( + steps=[("dev", cl.Development()), ("model", cl.BornhuetterFerguson())] + ) + pipe2 = cl.read_json(pipe.to_json()) + assert {item[0]: item[1].get_params() for item in pipe.get_params()["steps"]} == { + item[0]: item[1].get_params() for item in pipe2.get_params()["steps"] + } + + + def test_json_subtri(self, raa: Triangle, atol: float) -> None: + """ + test JSON round trip preserves sub-Triangles + + Parameters + ---------- + raa: Triangle + The CLRD sample data set fixture + + atol: float + the absolute tolerance for this test + + Returns + ------- + None + """ + a = cl.read_json(cl.Chainladder().fit_predict(raa).to_json()).full_triangle_ + b = cl.Chainladder().fit_predict(raa).full_triangle_ + # since a and b are meant to be identical, (a - b) should be 0 everywhere + # 0's are turned to NaN's in Triangle arithmetic, resulting in an All-NaN + # warning when aggregating + with pytest.warns(RuntimeWarning, match="All-NaN"): + assert abs(a - b).max().max() < atol + + + def test_json_df(self, atol: float) -> None: + """ + test JSON round trip preserves sub-Triangles from Munich Adjustment + + Parameters + ---------- + atol: float + the absolute tolerance for this test + + Returns + ------- + None + """ + x = cl.MunichAdjustment(paid_to_incurred=("paid", "incurred")).fit_transform( + cl.load_sample("mcl") + ) + assert abs(cl.read_json(x.to_json()).lambda_ - x.lambda_).sum() < atol + + +class TestPickle: + """Test JSON IO""" + + def test_to_pickle_read_pickle(self, raa: Triangle) -> None: + """ + test JSON round trip for val Triangle + + Parameters + ---------- + raa: Triangle + The CLRD sample data set fixture + + Returns + ------- + None + """ + import tempfile + import os + + dev = cl.Development(average="simple", n_periods=4).fit(raa) + fd, path = tempfile.mkstemp(suffix=".pkl") + os.close(fd) + try: + dev.to_pickle(path) + restored = cl.read_pickle(path) + assert restored.average == dev.average + assert restored.n_periods == dev.n_periods + np.testing.assert_array_almost_equal(restored.ldf_.values, dev.ldf_.values) + finally: + os.remove(path) + + def test_read_pickle_triangle(self, raa: Triangle, tmp_path: Path) -> None: + """ + Create a triangle, dump a pickle of it, and then read it back in. The ingested pickle should result + in an equal copy of the triangle that was dumped. + + Parameters + ---------- + raa: Triangle + The raa sample data set. + tmp_path: Path + The builtin pytest tmp_path fixture, provides a temporary path to dump the pickle to. + + Returns + ------- + None + + """ + pkl_path = tmp_path / "triangle.pkl" + with open(pkl_path, "wb") as f: + dill.dump(raa, f) + assert cl.read_pickle(str(pkl_path)) == raa + + + def test_triangle_to_pickle(self, raa: Triangle, clrd: Triangle, tmp_path: Path) -> None: + """ + Dump a pickle of a triangle and read it back in. The read-in triangle should + equal the one that was dumped. + + Parameters + ---------- + raa: Triangle + The raa sample data set Triangle. + clrd: Triangle + The clrd sample data set Triangle. + tmp_path: Path + The builtin pytest tmp_path fixture, provides a temporary path to dump the pickle to. + + Returns + ------- + None + + """ + # Single-dimension case. + raa_path = tmp_path / "raa.pkl" + raa.to_pickle(str(raa_path)) + assert raa_path.is_file() + assert cl.read_pickle(str(raa_path)) == raa + + # Multidimensional case. + clrd_path = tmp_path / "clrd.pkl" + clrd.to_pickle(str(clrd_path)) + assert clrd_path.is_file() + assert cl.read_pickle(str(clrd_path)) == clrd + + def test_read_pickle_estimator(self, raa: Triangle, tmp_path: Path) -> None: + """ + Create an estimator, dump a pickle of it, and then read it back in. The ingested pickle should result + produce the same LDFs that the original estimator does. + + Parameters + ---------- + raa: Triangle + The raa sample data set. + tmp_path: Path + The builtin pytest tmp_path fixture, provides a temporary path to dump the pickle to. + + Returns + ------- + None + + """ + + pkl_path = tmp_path / "estimator.pkl" + dev = cl.Development().fit(raa) + with open(pkl_path, "wb") as f: + dill.dump(dev, f) + assert dev.ldf_ == cl.read_pickle(str(pkl_path)).ldf_ + + def test_pickle_backward_compatibility(self, raa: Triangle) -> None: + """ + Tests backward compatibility with pickles from older versions + + Parameters + ---------- + raa: Triangle + The raa sample data set fixture + + Returns + ------- + None + """ + data_dir: Path = Path(__file__).parent.parent / "data" + raa_pickles = list(data_dir.glob("raa*.pkl")) + + for raa_pickle in raa_pickles: + test = cl.read_pickle(raa_pickle) + assert test == raa + assert repr(test) == repr(raa) + assert cl.Development().fit(test).ldf_ == cl.Development().fit(raa).ldf_ diff --git a/chainladder/core/triangle.py b/chainladder/core/triangle.py index 27c2888da..a5af46e86 100644 --- a/chainladder/core/triangle.py +++ b/chainladder/core/triangle.py @@ -1103,7 +1103,7 @@ def is_pattern(self) -> bool: True """ - return self._pattern + return getattr(self, "_pattern", False) @is_pattern.setter def is_pattern(self, pattern: bool): diff --git a/chainladder/utils/data/raa_0_10_0.pkl b/chainladder/utils/data/raa_0_10_0.pkl new file mode 100644 index 0000000000000000000000000000000000000000..a355ec318aca5c8a4c73fa550bde75ca51cdfcb7 GIT binary patch literal 2045 zcmbW2Ux*t;9LFdBdbxPHwzRfa(5fhMq6R4<9u&Nqinj4$X-|6<$~xJd-mcl~rn|H0 zU9p%x^xBhoFx*r@d=NZDebAnwAR@%lR%=mPu^#G+ebhohAH=uwxBHtUnll8PF!}7v z@Av!8Z+CvPTTh<;V}L|WY|%|>IW{#6=H+zPV>#|w)S0%K6zR#<<$}EDxI89D#gOY+ z)0U&zw8U(AP>MA;A!*w*?SY^au>(@9H&~6?ZneT3uHn2nC~mSGgUxg#Qj;#HHYlXZ zhE?&U$QYJw=d|!&imax4jB=(?&!e+)0g~9{1eNM+PK(m51U9$OCWbVR>8|5*FVH!- zid5t&#eie9!VBbt%*RUdq#P~8!rz=UZx$(o&sJF&5`XGpIe+S;+za-Eh`k_-#p3Q2 zXwhHc5iU#f2c?;%ToyTaiBv7h+FUW-}#c_Xg==v67QAEIgo`__YiX9oy+^L zBnfFOze#tb2zfAdq`U-N-nKiqV+|n}e_#5#0km&Bu^fYPSvxUx?J)3zqxW9F23#Cl z$nQ-P^7!cWwnm?9txmRyRoP;4LvZ_H8$pn}6dzFBuK0xFq~ddm;iC-O45ITW zGi5f5h389iNDSAg9Z+t$j%GlKNwKv`p;G*uW?Lmc$9;rVVLqpoDwO61EpV!qUbdOW zThn1pzLZ{B`BjeX-!=%Fn~CZoYx$ZUKzYIfH6~AqwKdD*0kxrS?VtjCA~vl$e6XSp zc?>^;u6gCzK7Z-<=`<5!pe1xn1|^Z!s+4o)IdZ;z7IoY8K`ycLu{<2r@NOC0_^L|9 zlaL7$4-58Cza4t?_C)K+emEXp)$eX1C(a{>zd#=T3i;Z%5yxM-5|P~Z9nOy_8c0%q z7VV#%L2mpAdG#Ffy3#xH4UTsr>k{?Jp368-{(6ywZSh?kzx;W``p6~Z9Qrp4YW=0F z(R_2?4`}}lNm@EBZvGhUjSCUUCAI#!@1ybfFBsRH`7s(douAOJ72nNujmTbq?=1S= zK)vy|R6bLvLmGgC^W{^;ANvq9BKKmUIAt#ACl`}z;v_8T!9eR{MK)yvE=!mmxz zvRz%8Q(|xzTtqJ*c!@-xSdnl`&r37mmqbE2rJwBbF$1()@C^cy#4ex;SEe{x;ybzw HK`Hk)^EhSj literal 0 HcmV?d00001 diff --git a/chainladder/utils/data/raa_0_8_24.pkl b/chainladder/utils/data/raa_0_8_24.pkl new file mode 100644 index 0000000000000000000000000000000000000000..f400a0b322fda50e4a19fec39b6d0efad49ab523 GIT binary patch literal 2068 zcmbW2U1%It6vyv=HJde?R9f0qO06goQ5P*D1`4KbMcXy8)M%?x#=A4OnQ>=lwljA& zNwK(nXxhkqaLKKL_#hZWeNdw)hzM(`AGN5hScCdvAGJ{MMSP2A=G@(l8Sk^4zniGi@^|(o?O|MS1%Pd0dW)tnS)D z#ql+pmY6LMOR=Fw?ST1`iXqptrY&cU2^ZFwraed|MeHdlt~XeX*>1JM9IoNIIV7&L z9D~hvBvMl@r#2|0%7#_(rN|hTZRfS{Uy7`zdyI0XQO~1uauEvL;sllITwaSVr4rcO zLYo-UJf^#j&%HqB;3`s)rxXK@(F!k;ld=#i$y0K)7z=;%(#(mJ!RM+h42eH>zg#$d zN*(}vLd2ezlarJCR$)Yc#Rs@7EgY8SM#|+R2QQJTMOB-dN6oF~jiJ1`O^L(l4iSIi zzO{n8LcwCLm@KA4sY0#>4~fEI!x6y2;PBy)?F4SG1Q|>)(Wy9T-t+Hz$>eAu?)Va~ zmCJdMg{=Dtx%T$OgO`$oG*;fAyHkYRo0=&v16OwL3vS*($oW5)zij~Rn@+C81_&9M zICSMG@PlJ_T)hHZ8e1$JfEIgr`pCrDbf;RQPqkL3+QhnQvA7|){BYzDuF_Mb`2)J%ILv1T`j4i;$WB5sQEhx|S-b}Z5u9*-6EurHwD2WW@t5VLH=g5WjM%8WC2f@Ui zhYHdhSl^_$2{K{LVXq$P_i!HEk!ao2568o^`fW|*#23inuaHN-LB9HZ#POFeMI?9r zfa_z529ngDM*C;)BR7A9ynGIMRq4%qhx0wixBQC4da@#KS%SX^9%a5;=8%A z5!vhSo<+ZFs5kzms^<{ukcMJ+eD{3m71X)w6XdU0XT5M9=YOgD)*aVtZl1t6^F1WR z=S#9*tY*KyF&%d92`|JPjy8c7A{W8o(UmdMP z^)hpe@I#ZdY*&}&Gh%QroJ8*)cz;A+UXgH1&q*`kmqbE2r629`F=x86a*3fJKye`B$_h>oG|(9 z%zN)UZ+G78)|03I7$8v-TXd6Jj!g}Nc{$znSdM!Zb*615MS8MzxghU3E|1AkG30vI zwB=|vEiqdjlwu7|NZK|{dmt!9?0^*O4OU~eTdgpMYdCKXikmFQU^5+w)TGO)4GO8U zVO4x7GKOW_IW7E`BCF{hqnv5f^XRNxfFw3KL8UsI)1q`Mfz2(ni6PBny6gDd3v>>y zA{BW`G2j@j@B%p@^RbdVDMt&j@HZ#Tn?=gtvsD&`#GiUt&YwCd_kukkVlT*IvABB$ zTJ%?Vgv-+WL1|_wmqiX z@_W;SJU)GB;%vH;t>tTE3dR|YhHP_&tJNII?aR_XbByYK}lp_y(;CLd5)ZKpGMtweGp9Sd@K)#HN0O2x4x=Y z@hoJ*)WecJ)NhX-y*<%-wjYj%SM|G_$cgjF;V+Pfze2wDZN%|cu0$mFeTVa7iUyL@ zpGEs;XOJ5|LS8+Gysq?)e1qei$ht&*vgb0+lfPahVOx9`$1i^#u|9GMIfwquf?9v+ zYBb;6_XFC0Lz0$Gi<>`2d*ebxa!IX!?)zvw{tL!6XMT*vP3I@{YsGhST_dvB-#d$b zH&AcX3$FcYODF@m18h{}bfTm}fnI5yyY3=hhw9Yiu6JIP-lZ#r-AOFLB%} zuGjo6r!nr%Pm!;yyn6Zfn?L$C>TFPT($Bx2ed` None: assert result == expected -def test_read_pickle_triangle(raa: Triangle, tmp_path: Path) -> None: - """ - Create a triangle, dump a pickle of it, and then read it back in. The ingested pickle should result - in an equal copy of the triangle that was dumped. - - Parameters - ---------- - raa: Triangle - The raa sample data set. - tmp_path: Path - The builtin pytest tmp_path fixture, provides a temporary path to dump the pickle to. - - Returns - ------- - None - - """ - pkl_path = tmp_path / "triangle.pkl" - with open(pkl_path, "wb") as f: - dill.dump(raa, f) - assert cl.read_pickle(str(pkl_path)) == raa - - -def test_triangle_to_pickle(raa: Triangle, clrd: Triangle, tmp_path: Path) -> None: - """ - Dump a pickle of a triangle and read it back in. The read-in triangle should - equal the one that was dumped. - - Parameters - ---------- - raa: Triangle - The raa sample data set Triangle. - clrd: Triangle - The clrd sample data set Triangle. - tmp_path: Path - The builtin pytest tmp_path fixture, provides a temporary path to dump the pickle to. - - Returns - ------- - None - - """ - # Single-dimension case. - raa_path = tmp_path / "raa.pkl" - raa.to_pickle(str(raa_path)) - assert raa_path.is_file() - assert cl.read_pickle(str(raa_path)) == raa - - # Multidimensional case. - clrd_path = tmp_path / "clrd.pkl" - clrd.to_pickle(str(clrd_path)) - assert clrd_path.is_file() - assert cl.read_pickle(str(clrd_path)) == clrd - - -def test_read_pickle_estimator(raa: Triangle, tmp_path: Path) -> None: - """ - Create an estimator, dump a pickle of it, and then read it back in. The ingested pickle should result - produce the same LDFs that the original estimator does. - - Parameters - ---------- - raa: Triangle - The raa sample data set. - tmp_path: Path - The builtin pytest tmp_path fixture, provides a temporary path to dump the pickle to. - - Returns - ------- - None - - """ - - pkl_path = tmp_path / "estimator.pkl" - dev = cl.Development().fit(raa) - with open(pkl_path, "wb") as f: - dill.dump(dev, f) - assert dev.ldf_ == cl.read_pickle(str(pkl_path)).ldf_ - - def test_concat_type_error() -> None: """ Supply a string to cl.concat() and raise a TypeError. Concat expects a list or tuple, so supplying a string From b07e740e504decfa671e657c9b4ab41c58fb7b4c Mon Sep 17 00:00:00 2001 From: "henrydingliu@gmail.com" Date: Sun, 4 Oct 2026 08:13:17 +0000 Subject: [PATCH 02/12] ruff fix --- chainladder/core/tests/test_io.py | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/chainladder/core/tests/test_io.py b/chainladder/core/tests/test_io.py index 159f2e9e7..107ef8c93 100644 --- a/chainladder/core/tests/test_io.py +++ b/chainladder/core/tests/test_io.py @@ -53,7 +53,6 @@ def test_json_for_val(self, raa: Triangle) -> None: x = raa.dev_to_val().to_json() assert cl.read_json(x) == raa.dev_to_val() - def test_estimator_json_io(self) -> None: """ test JSON round trip for Development estimator @@ -67,7 +66,6 @@ def test_estimator_json_io(self) -> None: == cl.Development().get_params() ) - def test_pipeline_json_io(self) -> None: """ test JSON round trip for an estimator pipeline @@ -80,10 +78,9 @@ def test_pipeline_json_io(self) -> None: steps=[("dev", cl.Development()), ("model", cl.BornhuetterFerguson())] ) pipe2 = cl.read_json(pipe.to_json()) - assert {item[0]: item[1].get_params() for item in pipe.get_params()["steps"]} == { - item[0]: item[1].get_params() for item in pipe2.get_params()["steps"] - } - + assert { + item[0]: item[1].get_params() for item in pipe.get_params()["steps"] + } == {item[0]: item[1].get_params() for item in pipe2.get_params()["steps"]} def test_json_subtri(self, raa: Triangle, atol: float) -> None: """ @@ -109,7 +106,6 @@ def test_json_subtri(self, raa: Triangle, atol: float) -> None: with pytest.warns(RuntimeWarning, match="All-NaN"): assert abs(a - b).max().max() < atol - def test_json_df(self, atol: float) -> None: """ test JSON round trip preserves sub-Triangles from Munich Adjustment @@ -182,8 +178,9 @@ def test_read_pickle_triangle(self, raa: Triangle, tmp_path: Path) -> None: dill.dump(raa, f) assert cl.read_pickle(str(pkl_path)) == raa - - def test_triangle_to_pickle(self, raa: Triangle, clrd: Triangle, tmp_path: Path) -> None: + def test_triangle_to_pickle( + self, raa: Triangle, clrd: Triangle, tmp_path: Path + ) -> None: """ Dump a pickle of a triangle and read it back in. The read-in triangle should equal the one that was dumped. From f0dcf7304485f22cec52c2bb58f453993244e069 Mon Sep 17 00:00:00 2001 From: "henrydingliu@gmail.com" Date: Sun, 4 Oct 2026 08:33:42 +0000 Subject: [PATCH 03/12] update folder --- chainladder/core/tests/test_io.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chainladder/core/tests/test_io.py b/chainladder/core/tests/test_io.py index 107ef8c93..042a31815 100644 --- a/chainladder/core/tests/test_io.py +++ b/chainladder/core/tests/test_io.py @@ -248,7 +248,7 @@ def test_pickle_backward_compatibility(self, raa: Triangle) -> None: ------- None """ - data_dir: Path = Path(__file__).parent.parent / "data" + data_dir: Path = Path(__file__).parent.parent.parent / "utils" / "data" raa_pickles = list(data_dir.glob("raa*.pkl")) for raa_pickle in raa_pickles: From 8e053d48d8f5b467cf01ae2f10755583e7359b64 Mon Sep 17 00:00:00 2001 From: "henrydingliu@gmail.com" Date: Mon, 19 Oct 2026 03:03:01 +0000 Subject: [PATCH 04/12] merge conflict fix --- chainladder/core/tests/test_io.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chainladder/core/tests/test_io.py b/chainladder/core/tests/test_io.py index 042a31815..debe44d24 100644 --- a/chainladder/core/tests/test_io.py +++ b/chainladder/core/tests/test_io.py @@ -31,8 +31,8 @@ def test_triangle_json_io(self, clrd: Triangle) -> None: """ clrd2 = cl.read_json(clrd.to_json(), array_backend=clrd.array_backend) assert clrd == clrd2 - assert np.all(clrd.kdims == clrd2.kdims) - assert np.all(clrd.vdims == clrd2.vdims) + assert clrd.index.equals(clrd2.index) + assert np.all(clrd.columns == clrd2.columns) assert np.all(clrd.odims == clrd2.odims) assert np.all(clrd.ddims == clrd2.ddims) assert np.all(clrd.valuation == clrd2.valuation) From 26f461ee94762595114fc0a9e37456fcbbd61acb Mon Sep 17 00:00:00 2001 From: "henrydingliu@gmail.com" Date: Thu, 5 Nov 2026 18:11:11 +0000 Subject: [PATCH 05/12] equals and ruff --- chainladder/core/tests/test_io.py | 28 +++++++++++------------ chainladder/utils/tests/test_utilities.py | 1 - 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/chainladder/core/tests/test_io.py b/chainladder/core/tests/test_io.py index debe44d24..ae6e17cc9 100644 --- a/chainladder/core/tests/test_io.py +++ b/chainladder/core/tests/test_io.py @@ -1,13 +1,13 @@ from __future__ import annotations -import numpy as np -import chainladder as cl +from pathlib import Path +from typing import TYPE_CHECKING + import dill +import numpy as np import pytest -from pathlib import Path - -from typing import TYPE_CHECKING +import chainladder as cl if TYPE_CHECKING: from chainladder import Triangle @@ -30,7 +30,7 @@ def test_triangle_json_io(self, clrd: Triangle) -> None: None """ clrd2 = cl.read_json(clrd.to_json(), array_backend=clrd.array_backend) - assert clrd == clrd2 + assert clrd.equals clrd2 assert clrd.index.equals(clrd2.index) assert np.all(clrd.columns == clrd2.columns) assert np.all(clrd.odims == clrd2.odims) @@ -51,7 +51,7 @@ def test_json_for_val(self, raa: Triangle) -> None: None """ x = raa.dev_to_val().to_json() - assert cl.read_json(x) == raa.dev_to_val() + assert cl.read_json(x).equals(raa.dev_to_val()) def test_estimator_json_io(self) -> None: """ @@ -141,8 +141,8 @@ def test_to_pickle_read_pickle(self, raa: Triangle) -> None: ------- None """ - import tempfile import os + import tempfile dev = cl.Development(average="simple", n_periods=4).fit(raa) fd, path = tempfile.mkstemp(suffix=".pkl") @@ -176,7 +176,7 @@ def test_read_pickle_triangle(self, raa: Triangle, tmp_path: Path) -> None: pkl_path = tmp_path / "triangle.pkl" with open(pkl_path, "wb") as f: dill.dump(raa, f) - assert cl.read_pickle(str(pkl_path)) == raa + assert cl.read_pickle(str(pkl_path)).equals(raa) def test_triangle_to_pickle( self, raa: Triangle, clrd: Triangle, tmp_path: Path @@ -203,13 +203,13 @@ def test_triangle_to_pickle( raa_path = tmp_path / "raa.pkl" raa.to_pickle(str(raa_path)) assert raa_path.is_file() - assert cl.read_pickle(str(raa_path)) == raa + assert cl.read_pickle(str(raa_path)).equals(raa) # Multidimensional case. clrd_path = tmp_path / "clrd.pkl" clrd.to_pickle(str(clrd_path)) assert clrd_path.is_file() - assert cl.read_pickle(str(clrd_path)) == clrd + assert cl.read_pickle(str(clrd_path)).equals(clrd) def test_read_pickle_estimator(self, raa: Triangle, tmp_path: Path) -> None: """ @@ -233,7 +233,7 @@ def test_read_pickle_estimator(self, raa: Triangle, tmp_path: Path) -> None: dev = cl.Development().fit(raa) with open(pkl_path, "wb") as f: dill.dump(dev, f) - assert dev.ldf_ == cl.read_pickle(str(pkl_path)).ldf_ + assert dev.ldf_.equals(cl.read_pickle(str(pkl_path)).ldf_) def test_pickle_backward_compatibility(self, raa: Triangle) -> None: """ @@ -253,6 +253,6 @@ def test_pickle_backward_compatibility(self, raa: Triangle) -> None: for raa_pickle in raa_pickles: test = cl.read_pickle(raa_pickle) - assert test == raa + assert test.equals(raa) assert repr(test) == repr(raa) - assert cl.Development().fit(test).ldf_ == cl.Development().fit(raa).ldf_ + assert cl.Development().fit(test).ldf_.equals(cl.Development().fit(raa).ldf_) diff --git a/chainladder/utils/tests/test_utilities.py b/chainladder/utils/tests/test_utilities.py index 283509497..1ceb97110 100644 --- a/chainladder/utils/tests/test_utilities.py +++ b/chainladder/utils/tests/test_utilities.py @@ -6,7 +6,6 @@ from pathlib import Path from typing import TYPE_CHECKING -import dill import numpy as np import pandas as pd import pytest From 01cf266939a29aed84536b55562c02ff46a0532d Mon Sep 17 00:00:00 2001 From: "henrydingliu@gmail.com" Date: Thu, 5 Nov 2026 18:12:53 +0000 Subject: [PATCH 06/12] typo --- chainladder/core/tests/test_io.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chainladder/core/tests/test_io.py b/chainladder/core/tests/test_io.py index ae6e17cc9..70801f7ea 100644 --- a/chainladder/core/tests/test_io.py +++ b/chainladder/core/tests/test_io.py @@ -30,7 +30,7 @@ def test_triangle_json_io(self, clrd: Triangle) -> None: None """ clrd2 = cl.read_json(clrd.to_json(), array_backend=clrd.array_backend) - assert clrd.equals clrd2 + assert clrd.equals(clrd2) assert clrd.index.equals(clrd2.index) assert np.all(clrd.columns == clrd2.columns) assert np.all(clrd.odims == clrd2.odims) From 869d6b21eb79fc14b419afdd6db0a7cb43e6fe4b Mon Sep 17 00:00:00 2001 From: "henrydingliu@gmail.com" Date: Thu, 5 Nov 2026 18:14:17 +0000 Subject: [PATCH 07/12] ruff fix --- chainladder/core/tests/test_io.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/chainladder/core/tests/test_io.py b/chainladder/core/tests/test_io.py index 70801f7ea..a1d993c2a 100644 --- a/chainladder/core/tests/test_io.py +++ b/chainladder/core/tests/test_io.py @@ -255,4 +255,6 @@ def test_pickle_backward_compatibility(self, raa: Triangle) -> None: test = cl.read_pickle(raa_pickle) assert test.equals(raa) assert repr(test) == repr(raa) - assert cl.Development().fit(test).ldf_.equals(cl.Development().fit(raa).ldf_) + assert ( + cl.Development().fit(test).ldf_.equals(cl.Development().fit(raa).ldf_) + ) From abe0205587019a9ad4e31564f9baf3c603acea1c Mon Sep 17 00:00:00 2001 From: "henrydingliu@gmail.com" Date: Thu, 5 Nov 2026 18:30:57 +0000 Subject: [PATCH 08/12] ruff fixes --- chainladder/core/tests/test_io.py | 17 +++--- chainladder/core/triangle.py | 53 ++++++++++-------- chainladder/utils/tests/test_utilities.py | 67 ++++++++++++++--------- 3 files changed, 81 insertions(+), 56 deletions(-) diff --git a/chainladder/core/tests/test_io.py b/chainladder/core/tests/test_io.py index a1d993c2a..b9b56d6e6 100644 --- a/chainladder/core/tests/test_io.py +++ b/chainladder/core/tests/test_io.py @@ -158,15 +158,16 @@ def test_to_pickle_read_pickle(self, raa: Triangle) -> None: def test_read_pickle_triangle(self, raa: Triangle, tmp_path: Path) -> None: """ - Create a triangle, dump a pickle of it, and then read it back in. The ingested pickle should result - in an equal copy of the triangle that was dumped. + Create a triangle, dump a pickle of it, and then read it back in. The ingested + pickle should result in an equal copy of the triangle that was dumped. Parameters ---------- raa: Triangle The raa sample data set. tmp_path: Path - The builtin pytest tmp_path fixture, provides a temporary path to dump the pickle to. + The builtin pytest tmp_path fixture, provides a temporary path to dump the + pickle to. Returns ------- @@ -192,7 +193,8 @@ def test_triangle_to_pickle( clrd: Triangle The clrd sample data set Triangle. tmp_path: Path - The builtin pytest tmp_path fixture, provides a temporary path to dump the pickle to. + The builtin pytest tmp_path fixture, provides a temporary path to dump the + pickle to. Returns ------- @@ -213,15 +215,16 @@ def test_triangle_to_pickle( def test_read_pickle_estimator(self, raa: Triangle, tmp_path: Path) -> None: """ - Create an estimator, dump a pickle of it, and then read it back in. The ingested pickle should result - produce the same LDFs that the original estimator does. + Create an estimator, dump a pickle of it, and then read it back in. The ingested + pickle should result produce the same LDFs that the original estimator does. Parameters ---------- raa: Triangle The raa sample data set. tmp_path: Path - The builtin pytest tmp_path fixture, provides a temporary path to dump the pickle to. + The builtin pytest tmp_path fixture, provides a temporary path to dump the + pickle to. Returns ------- diff --git a/chainladder/core/triangle.py b/chainladder/core/triangle.py index 649f3d76a..740495a39 100644 --- a/chainladder/core/triangle.py +++ b/chainladder/core/triangle.py @@ -7,24 +7,24 @@ # file, You can obtain one at https://mozilla.org/MPL/2.0/. from __future__ import annotations -import pandas as pd -import numpy as np import warnings + +import numpy as np +import pandas as pd + +from chainladder import options, _warn_dask_parallel_deprecated, __dt64_dtype__ +from chainladder._config.deprecation import _deprecated_rename_argument +from chainladder.core.axis import _set_columns, _set_index, TriangleAxis from chainladder.core.base import TriangleBase -from chainladder.core.axis import TriangleAxis -from chainladder.core.axis import _set_columns -from chainladder.core.axis import _set_index -from chainladder.utils.sparse import sp -from chainladder.core.slice import VirtualColumns from chainladder.core.correlation import DevelopmentCorrelation, ValuationCorrelation +from chainladder.core.slice import VirtualColumns +from chainladder.utils.sparse import sp from chainladder.utils.utility_functions import ( concat, num_to_nan, num_to_value, to_period, ) -from chainladder import options, _warn_dask_parallel_deprecated, __dt64_dtype__ -from chainladder._config.deprecation import _deprecated_rename_argument try: import dask.bag as db @@ -33,20 +33,21 @@ from typing import ( Any, - cast, Optional, - TYPE_CHECKING, Self, + TYPE_CHECKING, + cast, ) if TYPE_CHECKING: - from pandas import DataFrame, Series - from chainladder.core.style import Styler - from chainladder.core.typing import BackendArray from numpy.typing import ArrayLike + from pandas import DataFrame, Series from pandas._libs.tslibs.timestamps import Timestamp # noqa from pandas.core.interchange.dataframe_protocol import DataFrame as DataFrameXchg + from chainladder.core.style import Styler + from chainladder.core.typing import BackendArray + class Triangle(TriangleBase): """ @@ -128,11 +129,13 @@ class Triangle(TriangleBase): development_grain: str The grain of the development vector ('Y', 'S', 'Q', 'M') shape: tuple - The 4D shape of the triangle instance with axes corresponding to (index, columns, origin, development) + The 4D shape of the triangle instance with axes corresponding to + (index, columns, origin, development) link_ratio, age_to_age: Triangle Displays age-to-age ratios for the triangle. disposal_rate_tri: Triangle - Displays actual disposal rates by origin and development; must have ``ultimate_`` + Displays actual disposal rates by origin and development; must have + ``ultimate_`` valuation_date : date The latest valuation date of the data latest_diagonal: Triangle @@ -656,8 +659,9 @@ def __init__( if cumulative is None: warnings.warn( - "The cumulative property of your triangle is not set. This may result in " - "undesirable behavior. In a future release this will result in an error." + "The cumulative property of your triangle is not set. " + "This may result in undesirable behavior. In a future " + "release this will result in an error." ) self.is_cumulative: bool = cumulative @@ -1142,7 +1146,8 @@ def is_pattern(self, pattern: bool): @property def is_disposal_rate(self) -> bool: """ - Indicates whether the Triangle holds disposal rates (additive ratios going from head to tail) + Indicates whether the Triangle holds disposal rates (additive ratios + going from head to tail) """ if hasattr(self, "_is_disposal_rate"): return self._is_disposal_rate @@ -1156,7 +1161,8 @@ def align_pattern( self, X: Triangle, sample_weight: Triangle | None = None ) -> Triangle: """ - Vertically align a selected pattern to origin period latest diagonal. Triangle must be a selected pattern. + Vertically align a selected pattern to origin period latest diagonal. + Triangle must be a selected pattern. Parameters ---------- @@ -1291,9 +1297,10 @@ def latest_diagonal(self) -> Triangle: @property def link_ratio(self) -> Triangle: """ - Displays age-to-age ratios for the triangle. If the calling Triangle object already has the - self.is_pattern set to true (i.e., it is already a set of link ratios or development patterns), - this property simply returns itself. + Displays age-to-age ratios for the triangle. If the calling Triangle + object already has the self.is_pattern set to true (i.e., it is already + a set of link ratios or development patterns), this property simply + returns itself. Returns ------- diff --git a/chainladder/utils/tests/test_utilities.py b/chainladder/utils/tests/test_utilities.py index 1ceb97110..dda1b3d70 100644 --- a/chainladder/utils/tests/test_utilities.py +++ b/chainladder/utils/tests/test_utilities.py @@ -391,7 +391,8 @@ def test_load_sample_clrd2025() -> None: def test_date_delta_adjustment() -> None: """ - Tests the date adjustment depending on Pandas default precision, nanosecond for Pandas 2, microsecond for Pandas 3. + Tests the date adjustment depending on Pandas default precision, + nanosecond for Pandas 2, microsecond for Pandas 3. """ result = date_delta_adjustment("2025-11-01") @@ -405,8 +406,8 @@ def test_date_delta_adjustment() -> None: def test_concat_type_error() -> None: """ - Supply a string to cl.concat() and raise a TypeError. Concat expects a list or tuple, so supplying a string - will raise the error. + Supply a string to cl.concat() and raise a TypeError. Concat expects + a list or tuple, so supplying a string will raise the error. Returns ------- @@ -419,9 +420,12 @@ def test_concat_type_error() -> None: def test_concat_empty_error() -> None: """ - Supply an empty list to cl.concat(). Trigger a ValueError since the length of the list must be greater than 0. + Supply an empty list to cl.concat(). Trigger a ValueError since the + length of the list must be greater than 0. + Returns ------- + None """ with pytest.raises(ValueError): @@ -430,8 +434,9 @@ def test_concat_empty_error() -> None: def test_concat_mismatched_columns(clrd: Triangle) -> None: """ - Concatenate two triangles where each has a column that the other does not have. This creates new columns - for each triangle which then get filled with xp.nan. + Concatenate two triangles where each has a column that the other does + not have. This creates new columns for each triangle which then get + filled with xp.nan. Parameters ---------- @@ -460,8 +465,8 @@ def test_concat_mismatched_columns(clrd: Triangle) -> None: def test_concat_sort(clrd: Triangle) -> None: """ - Concat two triangles with indexes in reverse alphabetical order then sort the index. Check to see - that the index gets sorted alphabetically. + Concat two triangles with indexes in reverse alphabetical order then + sort the index. Check to see that the index gets sorted alphabetically. Parameters ---------- @@ -501,8 +506,8 @@ def test_concat_axis1(raa: Triangle) -> None: def test_concat_axis1_duplicate_columns(raa: Triangle) -> None: """ - Concat two triangles along the column axis with the same column names. Raise an assertion error since - columns must be unique. + Concat two triangles along the column axis with the same column names. + Raise an assertion error since columns must be unique. Parameters ---------- @@ -542,7 +547,10 @@ def test_concat_ignore_index_axes(raa: Triangle) -> None: def test_concat_axis_1_index_dtype_relaxed(raa: Triangle) -> None: - """Verify concat on axis 1 succeeds when index values match but row index labels differ.""" + """ + Verify concat on axis 1 succeeds when index values match but + row index labels differ. + """ t1 = copy.deepcopy(raa).rename("columns", ["A"]) t2 = copy.deepcopy(raa).rename("columns", ["B"]) t2.index = pd.DataFrame(t2.index.values, columns=t2.index.columns, index=[10]) @@ -563,7 +571,8 @@ def test_concat_axis_1_index_nan_preserved(raa: Triangle) -> None: def test_maximum_2(raa: Triangle) -> None: """ - Run cl.maximum(raa, 5000) and check if each element in the resulting triangle is at least 5000. + Run cl.maximum(raa, 5000) and check if each element in the resulting + triangle is at least 5000. Parameters ---------- @@ -582,7 +591,8 @@ def test_maximum_2(raa: Triangle) -> None: def test_minimum_2(raa): """ - Run cl.minimum(raa, 5000) and check if each element in the resulting triangle is at most 5000. + Run cl.minimum(raa, 5000) and check if each element in the resulting + triangle is at most 5000. Parameters ---------- @@ -601,7 +611,8 @@ def test_minimum_2(raa): def test_reset_option() -> None: """ - Change some of the options and then reset them. Values after reset should match the original values. + Change some of the options and then reset them. Values after reset should + match the original values. Returns ------- @@ -633,7 +644,8 @@ def test_reset_option() -> None: def test_options_defaults() -> None: """ - When initialized, default options should be correct and accessible from the options variable. + When initialized, default options should be correct and accessible from + the options variable. Returns ------- @@ -664,7 +676,8 @@ def test_get_option() -> None: def test_set_option_consistency() -> None: """ - When set_option changes an option value, get_option should return the new option value. + When set_option changes an option value, get_option should return the + new option value. Returns ------- @@ -1048,8 +1061,8 @@ def test_dask_parallel_numpy_groupby_no_warning( def test_describe_option(capsys: CaptureFixture[str]) -> None: """ - Supply an option to cl.options.describe_option(). Attribute name, type, default/current - settings should be captured in the output. + Supply an option to cl.options.describe_option(). Attribute name, type, + default/current settings should be captured in the output. Parameters ---------- @@ -1070,8 +1083,8 @@ def test_describe_option(capsys: CaptureFixture[str]) -> None: def test_describe_option_multi(capsys) -> None: """ - Supply two options to cl.options.describe_option(). Attribute names, types, default/current - settings should be captured in the output. + Supply two options to cl.options.describe_option(). Attribute names, types, + default/current settings should be captured in the output. Parameters ---------- @@ -1117,8 +1130,8 @@ def test_describe_option_all(capsys) -> None: def test_describe_option_return_string() -> None: """ - Execute cl.options.desribe_option() with _print_desc=False. Should return a string. Check - if attribute info is in the string. + Execute cl.options.desribe_option() with _print_desc=False. Should return a + string. Check if attribute info is in the string. Returns ------- @@ -1169,8 +1182,8 @@ def test_get_option_missing_pat_raises() -> None: def test_describe_option_no_docstring_match(monkeypatch: MonkeyPatch) -> None: """ - When the class docstring has no entry for an option, describe_option should fall back - to 'No description available.' rather than raising an error. + When the class docstring has no entry for an option, describe_option should + fall back to 'No description available.' rather than raising an error. Parameters ---------- @@ -1188,7 +1201,8 @@ def test_describe_option_no_docstring_match(monkeypatch: MonkeyPatch) -> None: def test_describe_option_invalid() -> None: """ - Execute cl.options.desribe_option() with an invalid argument. Should raise a ValueError. + Execute cl.options.desribe_option() with an invalid argument. Should raise + a ValueError. Returns ------- @@ -1201,7 +1215,8 @@ def test_describe_option_invalid() -> None: def test_both_pat_and_option_raises() -> None: """ - Passing both pat and option to get_option, set_option, or reset_option should raise TypeError. + Passing both pat and option to get_option, set_option, or reset_option should + raise TypeError. """ with pytest.raises(TypeError, match="Cannot specify both"): cl.options.get_option(pat="ARRAY_BACKEND", option="ARRAY_BACKEND") From 329c99086cf162150abd61076be9e81d1ae6032b Mon Sep 17 00:00:00 2001 From: "henrydingliu@gmail.com" Date: Thu, 5 Nov 2026 18:34:11 +0000 Subject: [PATCH 09/12] more ruff --- chainladder/core/triangle.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chainladder/core/triangle.py b/chainladder/core/triangle.py index 740495a39..21e8b8f14 100644 --- a/chainladder/core/triangle.py +++ b/chainladder/core/triangle.py @@ -12,9 +12,9 @@ import numpy as np import pandas as pd -from chainladder import options, _warn_dask_parallel_deprecated, __dt64_dtype__ +from chainladder import __dt64_dtype__, _warn_dask_parallel_deprecated, options from chainladder._config.deprecation import _deprecated_rename_argument -from chainladder.core.axis import _set_columns, _set_index, TriangleAxis +from chainladder.core.axis import TriangleAxis, _set_columns, _set_index from chainladder.core.base import TriangleBase from chainladder.core.correlation import DevelopmentCorrelation, ValuationCorrelation from chainladder.core.slice import VirtualColumns @@ -32,10 +32,10 @@ db = None from typing import ( + TYPE_CHECKING, Any, Optional, Self, - TYPE_CHECKING, cast, ) From 1e01be8bb41ec1ba9989b841ebf1b9bcaadaa620 Mon Sep 17 00:00:00 2001 From: "henrydingliu@gmail.com" Date: Wed, 18 Nov 2026 16:29:18 +0000 Subject: [PATCH 10/12] bugbot fix --- chainladder/core/triangle.py | 2 +- chainladder/utils/utility_functions.py | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/chainladder/core/triangle.py b/chainladder/core/triangle.py index ff72b5855..6d523c9f3 100644 --- a/chainladder/core/triangle.py +++ b/chainladder/core/triangle.py @@ -1195,7 +1195,7 @@ def align_pattern( Triangle of selected pattern across origin periods """ - if not self._pattern: + if not self.pattern: raise ValueError( "Triangle is not a selected pattern, such as .ldf_ or .cdf_" ) diff --git a/chainladder/utils/utility_functions.py b/chainladder/utils/utility_functions.py index e581face7..ac8c44efa 100644 --- a/chainladder/utils/utility_functions.py +++ b/chainladder/utils/utility_functions.py @@ -253,7 +253,10 @@ def read_pickle(path): """ with open(path, "rb") as pkl: - return dill.load(pkl) + obj = dill.load(pkl) + if "is_pattern" in obj.__dict__ and "_is_pattern" not in obj.__dict__: + obj.__dict__["_is_pattern"] = obj.__dict__.pop("is_pattern") + return obj @_deprecated_rename_argument("development", "valuation", remove_in_version="v2.0") From 888dd812930dad82c8c876c5352dc016b6acb55d Mon Sep 17 00:00:00 2001 From: "henrydingliu@gmail.com" Date: Wed, 18 Nov 2026 16:34:38 +0000 Subject: [PATCH 11/12] typo --- chainladder/core/triangle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chainladder/core/triangle.py b/chainladder/core/triangle.py index 6d523c9f3..32f3f0463 100644 --- a/chainladder/core/triangle.py +++ b/chainladder/core/triangle.py @@ -1195,7 +1195,7 @@ def align_pattern( Triangle of selected pattern across origin periods """ - if not self.pattern: + if not self.is_pattern: raise ValueError( "Triangle is not a selected pattern, such as .ldf_ or .cdf_" ) From 99f4cc465acad0c7d32b780107cb743fd2176e6b Mon Sep 17 00:00:00 2001 From: "henrydingliu@gmail.com" Date: Wed, 18 Nov 2026 16:36:55 +0000 Subject: [PATCH 12/12] more bugbot --- chainladder/utils/utility_functions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chainladder/utils/utility_functions.py b/chainladder/utils/utility_functions.py index ac8c44efa..566ba67dc 100644 --- a/chainladder/utils/utility_functions.py +++ b/chainladder/utils/utility_functions.py @@ -254,8 +254,8 @@ def read_pickle(path): """ with open(path, "rb") as pkl: obj = dill.load(pkl) - if "is_pattern" in obj.__dict__ and "_is_pattern" not in obj.__dict__: - obj.__dict__["_is_pattern"] = obj.__dict__.pop("is_pattern") + if "is_pattern" in obj.__dict__ and "_pattern" not in obj.__dict__: + obj.__dict__["_pattern"] = obj.__dict__.pop("is_pattern") return obj