Skip to content

[FEAT] Add process_dist to BootstrapODPSample and draw process variance in MethodBase - #1736

Open
scks1 wants to merge 4 commits into
casact:mainfrom
scks1:bootstrap-process-dist-1703
Open

scks1 wants to merge 4 commits into
casact:mainfrom
scks1:bootstrap-process-dist-1703

Conversation

@scks1

@scks1 scks1 commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Closes #1703. This is the first of the three steps agreed on #1703. #1706 and #1705 follow.

BootstrapODPSample takes a new process_dist parameter. The default "gamma" keeps today's results. None leaves process variance out, so a method fit on the sample gives parameter risk only and process_variance_ comes back None. scale_ stays as fitted either way.

transform sets process_dist on the sample next to scale_ and the seed and no longer binds _get_process_variance to it. MethodBase._include_process_variance now draws the gamma noise itself from those three attributes and from the values of the triangle the method was fit on. The draws for an unchanged sample match main, so the existing seeded tests and docstring outputs still pass.

Because the draw now reads the fitted triangle and not the original sample, a slice of simulations fits on its own rows. On main Chainladder().fit(sims.iloc[:5]).ultimate_ comes back with every simulation. With this change it has 5. Simulation 3 of the slice no longer matches simulation 3 of the full fit, which we agreed on #1703 is fine for now.

The second commit changes an existing test. predict on a subset of simulations used to warn and fall back to point estimates. The subset now draws its own process variance, so the shape check can no longer fail. The commit removes that warning branch and updates test_predict_subset_of_simulations_keeps_shape to expect process variance on the subset.

New tests in test_bootstrap.py check the attributes on the sample, process_dist=None for Chainladder, MackChainladder, Benktander and BornhuetterFerguson, the rejection of an unknown process_dist, and fits on a copy and a slice.

MackChainladder.predict fails on a bootstrap sample on main with "Index data must be 1-dimensional", with or without process variance. The new test skips the Mack predict check for that reason. I can open a separate issue for it.

The RandomStateMixin move onto Triangle and the random_state merge stay out of this PR, as agreed.

I used Árbol, an AI assistant running on Muse, under my direction to write the change, the tests and this description.

scks1 added 2 commits December 1, 2026 19:34
…ce in MethodBase

BootstrapODPSample takes process_dist, "gamma" by default or None, and sets it on the sample next to scale_ and the seed. transform no longer binds _get_process_variance to the sample. MethodBase._include_process_variance draws the noise from the fitted triangle's own values with those three attributes, so a copy or a slice of the sample no longer draws from the original sample (casact#1703).

Developed with an AI assistant (Árbol, running Muse).
A subset of simulations now draws its process variance over its own rows, so predict no longer needs the warning and point-estimate fallback for a shape mismatch. Remove that branch and update test_predict_subset_of_simulations_keeps_shape (casact#1703).

Developed with an AI assistant (Árbol, running Muse).
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Pyright Type Completeness

View the full pyright --verifytypes output for this commit

Project (full chainladder package, at this PR's head): 17.3% of exported symbols fully typed (314 / 1814)

Known Ambiguous Unknown Total
Project (head) 314 103 1397 1814

Other symbols referenced but not exported by chainladder: 24

Known Ambiguous Unknown Total
Other (head) 11 1 12 24

Symbols without documentation:

  • Functions without docstring: 343
  • Functions without default param: 0
  • Classes without docstring: 10

Patch (exported symbols added or changed by this PR): 0.0% fully typed (0 / 6)

Known Ambiguous Unknown Total
Patch 0 1 5 6
Patch symbol details
Symbol Status Change
chainladder.adjustments.bootstrap.BootstrapODPSample.process_dist ⚠️ ambiguous new
chainladder.adjustments.tests.test_bootstrap.test_fit_on_a_copy_or_slice_uses_its_own_values ❌ unknown new
chainladder.adjustments.tests.test_bootstrap.test_methods_reject_unknown_process_dist_on_the_sample ❌ unknown new
chainladder.adjustments.tests.test_bootstrap.test_process_dist_none_gives_parameter_risk_only ❌ unknown new
chainladder.adjustments.tests.test_bootstrap.test_process_dist_rejects_unknown_values ❌ unknown new
chainladder.adjustments.tests.test_bootstrap.test_sample_carries_process_settings_as_values ❌ unknown new

@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.42%. Comparing base (6824da8) to head (7118a15).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1736      +/-   ##
==========================================
+ Coverage   95.38%   95.42%   +0.03%     
==========================================
  Files         101      101              
  Lines        6810     6865      +55     
  Branches      855      861       +6     
==========================================
+ Hits         6496     6551      +55     
  Misses        199      199              
  Partials      115      115              
Flag Coverage Δ
unittests 95.42% <100.00%> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Add a test where a sample's process_dist changes after sampling to a value the methods cannot draw, so Chainladder.fit raises (casact#1703).

Developed with an AI assistant (Árbol, running Muse).

@staticmethod
def _has_process_variance(X):
"""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you please add type hinting?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pushed 7118a15, which adds type hints to _has_process_variance and to _draw_process_variance next to it. They follow the style of validate_ldf in the same file, with X: Triangle and a return type.

(This comment was written with Árbol, an AI assistant, under my direction.)

assert np.allclose(
plain.full_triangle_.values[..., -1:], plain.ultimate_.values, equal_nan=True
)
if estimator is cl.MackChainladder:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this can be removed after #1738 is fixed?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. The branch is there only for #1738. MackChainladder.predict raises "Index data must be 1-dimensional" on a bootstrap sample, with or without process variance. With a #1738-style fix patched in for a local check, the Mack case passes both predict checks in this test. Once #1738 is fixed, the branch and its comment can go.

Snippet and output on this PR's head 47a645c
import warnings
import numpy as np
import pandas as pd
import chainladder as cl
from chainladder.methods.mack import MackChainladder

warnings.simplefilter("ignore")
raa = cl.load_sample("raa")
without = cl.BootstrapODPSample(
    n_sims=50, random_state=42, process_dist=None
).fit_transform(raa)
plain = cl.MackChainladder().fit(without)
try:
    plain.predict(without)
    print("head: predict ok")
except ValueError as e:
    print("head: predict ValueError", e)


def patched(self, obj):
    obj = obj.total_process_risk_**2 + obj.total_parameter_risk_**2
    out = obj.sqrt().values[..., 0, -1]
    index = obj.index.iloc[:, 0] if len(obj.key_labels) == 1 else obj.index
    return pd.DataFrame(out, index=index, columns=obj.columns)


MackChainladder._get_total_mack_std_err_ = patched
pred = plain.predict(without)
print("patched: process_variance_ is None", pred.process_variance_ is None)
print(
    "patched: ultimate matches",
    np.allclose(pred.ultimate_.values, plain.ultimate_.values, equal_nan=True),
)
head: predict ValueError Index data must be 1-dimensional
patched: process_variance_ is None True
patched: ultimate matches True

(This comment was written with Árbol, an AI assistant, under my direction.)

equal_nan=True,
)
part = cl.Chainladder().fit(sims.iloc[:5])
assert part.ultimate_.shape == (5, 1, 10, 1)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we know if part.ultimate_ is the same as fit(sims).ultimate_[:5]?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or is this same as a previous situation where integer seed makes them the same but Generator doesn't

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it is the same situation as the RandomState case on #1703. With an integer seed each draw builds a fresh RandomState(seed + 1) at base.py line 200, and gamma fills the array with the simulations on the first axis. So fit(sims.iloc[:5]) gets the same first draws as fit(sims) and matches fit(sims).ultimate_[:5] exactly. sims.iloc[5:] starts the stream over and differs. A RandomState instance moves forward on every fit, so even iloc[:5] differs, and two fits on the same sims differ too. With process_dist=None every slice matches for both. A numpy Generator from np.random.default_rng raises in BootstrapODPSample because the seed handling only accepts an integer, a RandomState or None.

Snippet and output on this PR's head 7118a15
import warnings
import numpy as np
import chainladder as cl

warnings.filterwarnings("ignore")
raa = cl.load_sample("raa")
for name in ["int", "RandomState"]:
    for dist in ["gamma", None]:
        rs = 42 if name == "int" else np.random.RandomState(42)
        sims = cl.BootstrapODPSample(n_sims=10, random_state=rs, process_dist=dist).fit_transform(raa)
        whole = cl.Chainladder().fit(sims).ultimate_.values
        out = []
        for a, b in [(0, 5), (5, 10)]:
            part = cl.Chainladder().fit(sims.iloc[a:b]).ultimate_.values
            same = np.array_equal(part, whole[a:b], equal_nan=True)
            out.append(f"iloc[{a}:{b}] {same}")
        print(f"{name:>11} {str(dist):>5}", *out)
        int gamma iloc[0:5] True iloc[5:10] False
        int  None iloc[0:5] True iloc[5:10] True
RandomState gamma iloc[0:5] False iloc[5:10] False
RandomState  None iloc[0:5] True iloc[5:10] True

(This comment was written with Árbol, an AI assistant, under my direction.)

X_new = self.resampled_triangles_
X_new.scale_ = self.scale_
X_new.random_state = self.random_state_
X_new._get_process_variance = types.MethodType(_get_process_variance, X_new)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in hindsight, i don't think i fully understood why X._get_process_variance wasn't impacted by slicing. after sub = sims.iloc[:5], why would the self in _get_process_variance still refer to sims?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On main, transform stores a bound method on the sample at bootstrap.py line 380. types.MethodType fixes its self to that sample when it runs. iloc builds the slice by calling Triangle.copy at slice.py line 61, and copy runs X.__dict__.update(vars(self)) at triangle.py line 2267. That puts the same bound method object on the slice.

Python binds self only when it finds a plain function on the class. A bound method that sits in the instance dict comes back as it is. So sub._get_process_variance.__self__ is still sims, and the draw reads sims.cum_to_incr() and returns all ten simulations.

Snippet and output on main at ebde49b
import chainladder as cl

raa = cl.load_sample("raa")
sims = cl.BootstrapODPSample(n_sims=10, random_state=42).fit_transform(raa)
sub = sims.iloc[:5]
print("bound method in vars(sub):", "_get_process_variance" in vars(sub))
print("same object as on sims:", vars(sub)["_get_process_variance"] is vars(sims)["_get_process_variance"])
print("__self__ is sims:", sub._get_process_variance.__self__ is sims)
print("sub.shape:", sub.shape)
print("fit(sub).ultimate_.shape:", cl.Chainladder().fit(sub).ultimate_.shape)
bound method in vars(sub): True
same object as on sims: True
__self__ is sims: True
sub.shape: (5, 1, 10, 10)
fit(sub).ultimate_.shape: (10, 1, 10, 1)

(This comment was written with Árbol, an AI assistant, under my direction.)

Developed with an AI assistant (Árbol, running Muse).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEAT] Add a BootstrapODPSample parameter to keep or leave out process variance

2 participants