API reference¶
Explainer and results¶
Counterfactual explainer for a tree-ensemble model.
Parses the model, compiles the constraints, and fits the distance
normalizers once at construction, so repeated explain/explain_batch/
explain_coalitions calls reuse that work.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
object
|
A native model object (XGBoost/LightGBM/CatBoost/sklearn
ensemble), a JSON dump file path or dict, or an already-parsed
|
required |
background
|
FloatArray | None
|
Sample used to fit the per-feature distance normalizers
( |
None
|
constraints
|
Sequence[Constraint]
|
Constraint objects ( |
()
|
weights
|
dict[str, float] | None
|
Per-feature multiplier on distance cost, |
None
|
normalizers
|
FloatArray | dict[str, float] | None
|
Per-feature distance scale |
None
|
value_policy
|
dict[str, ValuePolicy] | None
|
Per-feature snapping rule, |
None
|
plausibility
|
Plausibility | None
|
Optional hard isolation-forest bound keeping every
returned counterfactual inside the data manifold (see
|
None
|
Raises:
| Type | Description |
|---|---|
TreecfError
|
If neither |
ConstraintValidationError
|
If |
Source code in src/treecf/api.py
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 | |
certificate(x, result, target, *, band=None, seed=None, node_budget=None, gap=None, time_budget_s=None, warm_start=None)
¶
Issue an audit certificate for a stored result (post-hoc, like
recourse_region).
A certificate is a reproducibility record plus a fresh verification —
it binds the result to a model fingerprint, a constraint fingerprint,
and the solve parameters, and re-verifies the returned plan at issue
time; it does not cryptographically prove that a search ran or that a
proof="optimal" claim is true — re-running with the recorded seed
and budgets on a fingerprint-matching model is how a validator checks
that. See
Certification — audit certificates
for the schema.
The certificate is a plain dict ("schema_version": 1) that
serializes with json.dumps(cert, allow_nan=False, sort_keys=True);
non-finite floats are encoded as the strings "NaN"/"Infinity"/
"-Infinity". Accepts a Counterfactual or an Infeasible —
the certified "no" is exactly the case a validator cares most about.
The verification block is computed fresh here, never copied from the
solve: the plan's score, target membership, and constraint check are
recomputed (plus the plausibility bound when configured, and a sampled
set of region points when the result carries a region). A certificate
whose fresh verification fails is still returned, with the failing
booleans recorded — but a TreecfWarning names the failed check.
seed/node_budget/gap/time_budget_s/warm_start are
recorded under solve.declared when given: the result object does
not carry them, so they are caller-supplied, and the block's name
makes that provenance explicit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
FloatArray
|
The factual instance the result was solved from. |
required |
result
|
Counterfactual | Infeasible
|
The |
required |
target
|
Target
|
The target the result was solved against. |
required |
band
|
str | None
|
For a |
None
|
seed
|
int | None
|
The seed the solve ran with, if the caller wants it recorded. |
None
|
node_budget
|
int | None
|
The node budget the solve ran with, likewise. |
None
|
gap
|
float | None
|
The relative gap the solve ran with, likewise. |
None
|
time_budget_s
|
float | None
|
The time budget the solve ran with, likewise. |
None
|
warm_start
|
bool | None
|
The warm-start setting the solve ran with, likewise. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, object]
|
The certificate as a strict-JSON-serializable |
Raises:
| Type | Description |
|---|---|
TreecfError
|
If |
Source code in src/treecf/api.py
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 | |
check_certificate(cert, *, calibrator=None)
¶
Validate a stored certificate against this explainer.
Recomputes both fingerprints (model and constraints) against this
explainer and re-runs the certificate's verification block from its
stored factual/plan, so a tampered x_cf, a swapped model, or a
changed constraint set each flips the corresponding boolean. This
method reports — it never raises on a mismatch.
Without calibrator=, a calibrated-target certificate is still
fully verifiable in plan geometry: the resolved raw_interval
is stored, so this proves the plan reaches the stored interval — it
does not prove which calibrator produced that interval. Passing
calibrator= adds exactly that: the duck-typed fingerprint()
is compared with the stored one, and the certificate's calibrated
lo/hi are re-inverted through the supplied calibrator and
compared with the stored interval (rtol 1e-9, infinities by
identity). Neither mode requires treecf to import a calibration
library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cert
|
dict[str, object]
|
A certificate produced by |
required |
calibrator
|
object | None
|
Optional duck-typed calibrator (the object handed to
|
None
|
Returns:
| Type | Description |
|---|---|
dict[str, object]
|
``{"model_match": bool, "constraints_match": bool, |
dict[str, object]
|
"verification_ok": bool, "mismatches": [...]}`` with one |
dict[str, object]
|
human-readable string per mismatch, plus ``"calibrator_match": |
dict[str, object]
|
bool |
Source code in src/treecf/api.py
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 | |
explain(x, target, backend='genetic', time_budget_s=10.0, sparsity_weight=0.0, seed=None, warm_start=None, node_budget=None, gap=None, region=False)
¶
Search for a counterfactual (or one per band for Target.bands).
x is the factual instance (one row, aligned to the model's feature
order); target bounds the model output the counterfactual must
reach. time_budget_s caps wall time per solve (per band, when
target is a Target.bands ladder); math.inf is accepted
and removes the time cut, letting an exact search run until it
proves its answer (Ctrl-C still aborts promptly). sparsity_weight makes
the search minimize distance + sparsity_weight * n_changed
instead of plain distance, trading a cheaper plan that touches
more features against a sparser one that costs more per feature; the
returned Counterfactual.distance itself always excludes the
sparsity term. 0.0 (the default) does not penalize sparsity at
all. seed fixes the genetic search's (and, on the
exact backend, the warm start's) randomness for reproducibility;
None draws a fresh one each call.
backend="genetic" runs the bundled Rust engine (default);
backend="python" runs the reference numpy implementation of the
same algorithm; backend="exact" runs a branch-and-bound search
over the same candidate grid that proves optimality when it finds a
counterfactual and proves infeasibility when it does not, at the cost
of a potentially longer solve. Every result is float-verified before
being returned.
warm_start (default True), node_budget (default
2_000_000), and gap (default 0.0) configure the exact
backend only; passing a non-default value together with another
backend raises ValueError — deliberately not the usual
TreecfError, since this rejects a Python-level argument
combination rather than a modeling error. warm_start=True runs a
short genetic pass first (about a quarter of time_budget_s,
capped at 2 seconds) and, if it lands a verified counterfactual, feeds
it to the exact search as a starting incumbent; the exact search
still gets the full time_budget_s afterwards, so warm start is
additive rather than deducted from the budget. gap lets the exact
search settle for a counterfactual within that relative fraction of
the true optimum, reported through proof="optimal_within_gap".
An exact search can return a feasible row with proof="heuristic"
without exhausting node_budget or time_budget_s: conservative
repair of some constraint shapes can withdraw the optimality
certificate honestly rather than claim a cheapest row it did not
prove — the row itself is still real and verified, only the
"cheapest possible" claim is dropped. Whenever the exact search
returns any result with solver_stats["completed"] is False — for
that reason or because the budget genuinely ran out — a
TreecfWarning names which of the two happened, never the
other one. Target.bands, explain_coalitions, and
explain_batch collapse this into one aggregate warning per call
instead of one per solve.
If the factual itself violates a constraint, a TreecfWarning
is emitted: the returned plan will include changes made solely to
satisfy the constraint set.
region=True widens every successful Counterfactual into a
certified RecourseRegion (cf.region) —
works with any backend, genetic included. Costs one oracle call per
attempted per-feature, per-direction expansion; see
Explainer.recourse_region.
Returns:
| Type | Description |
|---|---|
Counterfactual | Infeasible | dict[str, object]
|
A single |
Counterfactual | Infeasible | dict[str, object]
|
plain interval ( |
Counterfactual | Infeasible | dict[str, object]
|
|
Counterfactual | Infeasible | dict[str, object]
|
band in solved order, when |
Counterfactual | Infeasible | dict[str, object]
|
ladder. |
Counterfactual | Infeasible | dict[str, object]
|
counterfactual — see |
Counterfactual | Infeasible | dict[str, object]
|
certified impossibility or just an unsuccessful search. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TreecfError
|
If |
ConstraintValidationError
|
If |
Source code in src/treecf/api.py
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 | |
explain_batch(X, target, n_per_example=1, diversity='seeds', ids=None, backend='genetic', time_budget_s=10.0, sparsity_weight=0.0, seed=0, coalitions=None, include_full=False, warm_start=None, node_budget=None, gap=None, region=False, allow_exact_batch=False)
¶
Mass-produce counterfactuals for a dataset; see treecf.batch.
X is the factual dataset (one row per instance, aligned to the
model's feature order); ids labels each row (defaults to its
integer index) and must have one entry per row of X.
n_per_example alternatives per row via diversity="seeds" (distinct
change-sets from different seeds, best-effort) or "lever-blocking"
(freeze each plan's biggest lever; also records essential levers).
diversity="coalitions" instead produces one plan per named feature
group in coalitions per row (n_per_example unused; see
explain_coalitions for coalitions/include_full semantics,
which are only valid in this mode). The returned BatchResult supports
save/load/for_id/to_frame. time_budget_s, sparsity_weight, and
seed carry the same meaning as in Explainer.explain, applied
per solve (seed is combined with each row's index to derive a
distinct per-row seed).
Solves run in parallel inside the Rust engine; time_budget_s is
per solve, so a solve that hits its wall-clock budget while sharing
cores may stop earlier than it would sequentially (results are
otherwise identical to solving row by row).
backend="exact" has no vectorized population to parallelize, so
this loops the single-instance exact solve per row (and per plan, for
lever-blocking) sequentially — expect roughly linear-in-rows wall
time rather than the Rust engine's parallel wave scheduling, and each
row still gets the full, undiminished time_budget_s. Because that
wall time is easy to underestimate, backend="exact" here is
opt-in: without allow_exact_batch=True this raises ValueError
naming an estimate (rows × plans × time_budget_s, hours-formatted)
instead of silently running -- a floor, not a ceiling, since
diversity="seeds" can retry each plan up to 3x on a seed
collision; passing it through with any other backend also raises
ValueError. Opting in additionally
replaces warm_start's N sequential per-row (or, in seeds mode,
per-attempt) genetic warm passes with a single vectorized one across
every row — see treecf.batch.explain_batch for exactly which
modes it covers and which keep 0.2.0's per-solve behavior.
node_budget/gap thread through to every solve unchanged; see
Explainer.explain. A KeyboardInterrupt during any batch solve
discards whatever the batch has not yet finished — there is no
partial BatchResult. region=True attaches a certified
RecourseRegion (BatchRecord.region) to every feasible record,
at the same one-oracle-call-per-expansion cost.
Returns:
| Type | Description |
|---|---|
Any
|
A |
Any
|
— infeasible rows/plans get a record with |
Any
|
no |
Raises:
| Type | Description |
|---|---|
TreecfError
|
If |
ValueError
|
If |
Source code in src/treecf/api.py
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 | |
explain_coalitions(x, target, coalitions, include_full=False, backend='genetic', time_budget_s=10.0, sparsity_weight=0.0, seed=None, warm_start=None, node_budget=None, gap=None, region=False)
¶
One counterfactual per named feature coalition (opt-in mode).
x/target/backend/time_budget_s/sparsity_weight/
seed carry the same meaning as in Explainer.explain, applied
once per coalition. coalitions maps a group name to the features
it may change; each coalition is solved with every feature outside
it frozen, so a plan only ever asks for changes within one group —
grouped recourse instead of one plan that mixes unrelated levers.
Coalitions may overlap; features in no coalition are never modified;
an Infeasible for a coalition means that group alone cannot reach
the target. include_full=True prepends an unrestricted baseline
under the reserved key "(all levers)". One solve per coalition
(milliseconds each); this mode is optional and never the default.
warm_start/node_budget/gap/region thread through to every
coalition's solve; see Explainer.explain. A degraded exact result
(solver_stats["completed"] is False) in any coalition's solve is
collapsed into one aggregate TreecfWarning for the whole call,
rather than one per coalition.
Returns:
| Type | Description |
|---|---|
dict[str, Counterfactual | Infeasible]
|
|
dict[str, Counterfactual | Infeasible]
|
key of |
dict[str, Counterfactual | Infeasible]
|
|
Raises:
| Type | Description |
|---|---|
TreecfError
|
If |
ValueError
|
If |
Source code in src/treecf/api.py
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 | |
recourse_region(x, x_cf, target)
¶
Certify a per-feature box around an already-verified counterfactual.
x is the original factual and x_cf the counterfactual to widen
(typically Counterfactual.x_cf from a prior explain call);
target is the single interval x_cf was solved against. x_cf
must independently pass the same float-space re-check
explain runs on its own results; a row that fails it raises
TreecfError naming the reason, since there is nothing sound to
widen. Works for a counterfactual from any backend. Costs one oracle
call — a full interval-tree walk of every ensemble tree — per
attempted per-feature, per-direction expansion; see
RecourseRegion. The returned region is certified
but neither maximal nor monotone in target: a strictly narrower
target can still grow a strictly wider region on some feature. See
Certification.
Returns:
| Type | Description |
|---|---|
RecourseRegion
|
The certified |
Raises:
| Type | Description |
|---|---|
TreecfError
|
If |
Source code in src/treecf/api.py
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 | |
One verified counterfactual: the changed row, its cost, and how strong a claim the search makes about it being the cheapest one.
proof is always one of exactly three values:
{"heuristic", "optimal", "optimal_within_gap"}. The genetic and
python backends always report "heuristic" — they never claim
optimality. The exact backend reports "optimal" when it proved no
cheaper row exists, "optimal_within_gap" when gap > 0 and it only
proved none exists more than that relative fraction cheaper, and — more
rarely — "heuristic" for a row it is not claiming is cheapest: see
Explainer.explain for when that happens. See
Certification for the full proof taxonomy.
Attributes:
| Name | Type | Description |
|---|---|---|
x_cf |
FloatArray
|
The full counterfactual feature vector, same order and length as the factual; unchanged features keep the factual's own value. |
changes |
dict[str, tuple[float, float]]
|
|
distance |
float
|
The weighted, normalized sum of per-feature changes
( |
n_changed |
int
|
|
score_raw |
float
|
The model's raw score at |
score_prob |
float | None
|
|
proof |
str
|
The optimality claim this result makes; see above. |
solver_stats |
dict[str, object]
|
Backend-specific diagnostics. Populated by the exact
backend ( |
snapped |
dict[str, bool]
|
|
region |
RecourseRegion | None
|
The certified box around |
score_calibrated |
float | None
|
The calibrator's probability at |
Source code in src/treecf/api.py
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |
No counterfactual returned — the search made no claim, or proved none exists.
proof is always one of exactly two values:
{"search_exhausted", "certified"}. "search_exhausted" (the
default) means the search ran out of budget, hit a heuristic dead end, or
gave up an optimality certificate along the way — nothing is proven about
whether a counterfactual exists at all. "certified" is exact-backend
only: every assignment the searched grid allows was tried and none was
feasible, so reason names the node count behind that proof. See
Certification for the full proof taxonomy.
Attributes:
| Name | Type | Description |
|---|---|---|
reason |
str
|
Human-readable explanation of why no counterfactual was
returned; names the node count behind a |
proof |
str
|
The claim this non-result makes; see above. |
solver_stats |
dict[str, object]
|
Backend-specific diagnostics, populated the same way as
|
Source code in src/treecf/api.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
Batch production¶
Counterfactuals for a whole dataset, addressable by row id.
Returned by Explainer.explain_batch; supports len(), iteration
over its records, id lookup (for_id), a JSON round trip
(save/load), and a pandas view (to_frame).
Attributes:
| Name | Type | Description |
|---|---|---|
feature_names |
tuple[str, ...]
|
The model's feature names, in the order |
diversity |
str
|
The |
records |
tuple[BatchRecord, ...]
|
Every |
essential_levers |
dict[object, list[str]]
|
|
Source code in src/treecf/batch.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | |
for_id(row_id)
¶
Every record (all alternatives/coalitions) for one dataset row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row_id
|
object
|
A value from |
required |
Returns:
| Type | Description |
|---|---|
list[BatchRecord]
|
The matching records, in their original order; |
list[BatchRecord]
|
|
Source code in src/treecf/batch.py
162 163 164 165 166 167 168 169 170 171 172 173 | |
load(path)
classmethod
¶
Read a BatchResult previously written by save.
A file saved without region=True, or by a version of treecf
before regions existed, loads with every record's region set to
None; a file saved before coalition support loads with every
record's coalition set to None; a file saved before per-record
proofs existed loads with proof defaulted by feasibility
("heuristic"/"search_exhausted") and empty solver_stats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Path to a file written by |
required |
Returns:
| Type | Description |
|---|---|
BatchResult
|
The reconstructed |
Source code in src/treecf/batch.py
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 | |
save(path)
¶
Write this result to a portable JSON file, reloadable with load.
Every field is encoded explicitly (NaN/Infinity-safe floats via
encode_floats), including region when set, so a round trip
through save/load is lossless.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Destination file path; overwritten if it already exists. |
required |
Source code in src/treecf/batch.py
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | |
to_frame()
¶
One row per (id, k), wide cf_<feature> columns (pandas, lazy import).
Every BatchRecord field except x_cf/changes/region/
solver_stats becomes its own column (solver_stats stays
record-only — read it off the BatchRecord directly); x_cf is
spread into one cf_<feature> column per model feature (NaN for
an infeasible record, or an unchanged feature's factual-equal value);
changes is summarized as a changed_features column (sorted
feature names).
Returns:
| Type | Description |
|---|---|
Any
|
A pandas |
Raises:
| Type | Description |
|---|---|
TreecfError
|
If pandas is not installed. |
Source code in src/treecf/batch.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | |
One counterfactual (or the infeasibility marker) for one dataset row.
Fields mirror Counterfactual (x_cf, changes, distance,
n_changed, score_raw, score_prob, proof, solver_stats,
region), plus batch bookkeeping: id and k place the record in
the dataset, and feasible distinguishes a real plan from the
infeasibility marker.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
object
|
The row identifier this record belongs to (an element of
|
k |
int
|
Rank of this plan among the row's feasible alternatives,
|
feasible |
bool
|
|
x_cf |
FloatArray | None
|
The full counterfactual feature vector, or |
changes |
dict[str, tuple[float, float]]
|
|
distance |
float | None
|
The weighted, normalized sum of per-feature changes,
excluding the sparsity term (see |
n_changed |
int | None
|
|
score_raw |
float | None
|
The model's raw score at |
score_prob |
float | None
|
|
seed |
int | None
|
The seed that produced this plan, set only for
|
blocked_lever |
str | None
|
The feature frozen to produce this plan, set only for
|
coalition |
str | None
|
The coalition name this plan belongs to, set only for
|
region |
RecourseRegion | None
|
The certified box around |
proof |
str
|
The claim this record makes, mirroring the single-instance
result that produced it: |
solver_stats |
dict[str, object]
|
Exact-backend diagnostics for the solve behind this
record, same keys as |
calibrator_fingerprint |
str | None
|
The duck-typed |
score_calibrated |
float | None
|
The calibrator's probability at |
Source code in src/treecf/batch.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
Targets¶
Closed interval target, expressed in raw-score, probability, or calibrated space.
Construct through one of the classmethods (raw, probability,
calibrated, bands) rather than the constructor directly — they
validate their space's bounds and normalize the range/op/value
shorthand into lo/hi. Target.bands builds a named ladder of
intervals (rating grades); Explainer.explain then returns one result
per band instead of a single Counterfactual/Infeasible. See
Targets and, for calibrated,
Calibration.
Attributes:
| Name | Type | Description |
|---|---|---|
space |
str
|
|
lo |
float
|
Lower bound of the target interval, in |
hi |
float
|
Upper bound of the target interval, in |
bands_spec |
tuple[tuple[str, float, float], ...] | None
|
|
calibrator |
_SupportsIntervalInverse | None
|
The fitted calibrator, set only by |
buffer_logit |
float
|
Logit-space shrinkage applied before inverting a
calibrated interval; |
Source code in src/treecf/targets.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | |
band_intervals(link)
¶
Resolve every band of a Target.bands ladder to a raw-score interval.
Applies raw_interval band by band, in bands_spec's order,
each against a copy of this target's own space/calibrator/
buffer_logit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
Link
|
The model's link function ( |
required |
Returns:
| Type | Description |
|---|---|
dict[str, tuple[float, float]]
|
|
Raises:
| Type | Description |
|---|---|
TargetError
|
Under the same conditions as |
Source code in src/treecf/targets.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | |
bands(bands, space='probability', *, calibrator=None, buffer_logit=0.0)
classmethod
¶
A named ladder of intervals — rating grades solved in one explain call.
Explainer.explain(x, target=Target.bands(...)) returns a
{band_name: Counterfactual | Infeasible} dict instead of a single
result, one entry per band in bands' insertion order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bands
|
dict[str, tuple[float, float]]
|
|
required |
space
|
str
|
|
'probability'
|
calibrator
|
_SupportsIntervalInverse | None
|
Required when |
None
|
buffer_logit
|
float
|
Logit-space shrinkage applied to every band when
|
0.0
|
Returns:
| Type | Description |
|---|---|
Target
|
A |
Target
|
band; |
Target
|
that only look at the plain-interval fields. |
Raises:
| Type | Description |
|---|---|
TargetError
|
If |
Source code in src/treecf/targets.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
calibrated(calibrator, range=None, op=None, value=None, *, buffer_logit=0.0)
classmethod
¶
Target on the calibrated probability g(model probability).
The interval is inverted through the calibrator's generalized inverse
lazily, at raw_interval time; the calibrator is held by reference,
so refitting it between construction and explain is the caller's
responsibility. buffer_logit shrinks the calibrated interval in
logit space before inversion, making the counterfactual robust to
future recalibration or central-tendency drift of that magnitude.
Specify exactly one of range=(lo, hi) or op=/value=, as in
Target.raw. See Calibration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
calibrator
|
_SupportsIntervalInverse
|
Object exposing |
required |
range
|
tuple[float, float] | None
|
Explicit |
None
|
op
|
str | None
|
|
None
|
value
|
float | None
|
The threshold paired with |
None
|
buffer_logit
|
float
|
Logit-space shrinkage applied before inversion;
must be |
0.0
|
Returns:
| Type | Description |
|---|---|
Target
|
A |
Raises:
| Type | Description |
|---|---|
TargetError
|
If |
Source code in src/treecf/targets.py
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
probability(range=None, op=None, value=None)
classmethod
¶
Target on the model's own probability output.
If model outputs are post-hoc calibrated downstream, this constructor
targets the uncalibrated model probability; use Target.calibrated
with your calibrator instead. Requires a SIGMOID-link model — resolved
lazily, at raw_interval time, not here. Specify exactly one of
range=(lo, hi) or op=/value=, as in Target.raw.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
range
|
tuple[float, float] | None
|
Explicit |
None
|
op
|
str | None
|
|
None
|
value
|
float | None
|
The threshold paired with |
None
|
Returns:
| Type | Description |
|---|---|
Target
|
A |
Raises:
| Type | Description |
|---|---|
TargetError
|
If neither or both of |
Source code in src/treecf/targets.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | |
raw(range=None, op=None, value=None)
classmethod
¶
Target on the model's raw output (pre-link margin for a sigmoid model).
Specify exactly one of range=(lo, hi) or op=/value=
(op="<=" or op=">=" with value, giving a half-open bound
against -inf/+inf).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
range
|
tuple[float, float] | None
|
Explicit |
None
|
op
|
str | None
|
|
None
|
value
|
float | None
|
The threshold paired with |
None
|
Returns:
| Type | Description |
|---|---|
Target
|
A |
Raises:
| Type | Description |
|---|---|
TargetError
|
If neither or both of |
Source code in src/treecf/targets.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
raw_interval(link)
¶
Resolve this target to an [L, U] interval on the model's raw score.
A space="raw" target returns (lo, hi) unchanged. A
space="probability" target inverts through the logistic function.
A space="calibrated" target inverts through calibrator's own
generalized inverse in logit space, shrunk by buffer_logit first.
Both non-raw spaces require link to be Link.SIGMOID — this is
where that requirement is actually enforced, not at construction time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link
|
Link
|
The model's link function ( |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
|
Raises:
| Type | Description |
|---|---|
TargetError
|
If |
Source code in src/treecf/targets.py
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | |
Constraints¶
Parse "2*a - b <= 3"-style sugar into a canonical Linear object.
Only linear expressions over +/-/* and one of <=/>=/
== are accepted; anything richer (nonlinear terms, multiple
comparisons) must be written as constraint objects directly. Terms on
both sides are folded into coefficients/rhs on the left-hand
side's convention, so "a <= b" and "a - b <= 0" produce the same
Linear. See Constraints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
The constraint string, e.g. |
required |
feature_names
|
Sequence[str] | None
|
When given, every identifier in |
None
|
Returns:
| Type | Description |
|---|---|
Linear
|
The parsed |
Raises:
| Type | Description |
|---|---|
ConstraintParseError
|
If |
Source code in src/treecf/constraints/parser.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | |
Canonical constraint objects. Frozen dataclasses; validation at compile time.
Pass these (or a constraint() string) to Explainer(..., constraints=[...]).
See Constraints for what each one compiles to and
how they compose.
AllowMissing
dataclass
¶
NaN is a feasible counterfactual value for this feature.
delta_miss prices the value<->NaN transition; pass delta_from_miss
for an asymmetric NaN->value cost (defaults to delta_miss). See
Missing values.
Attributes:
| Name | Type | Description |
|---|---|---|
feature |
str
|
The feature name NaN is allowed on. |
delta_miss |
float
|
Distance cost of a value-to-NaN change on this feature. |
delta_from_miss |
float | None
|
Distance cost of a NaN-to-value change on this
feature; defaults to |
Source code in src/treecf/constraints/objects.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
Equals
dataclass
¶
Binary-feature equality (used standalone or inside Implies).
Attributes:
| Name | Type | Description |
|---|---|---|
feature |
str
|
The feature name to compare. |
value |
float
|
The value |
Source code in src/treecf/constraints/objects.py
84 85 86 87 88 89 90 91 92 93 94 95 | |
Freeze
dataclass
¶
The feature is immutable: the counterfactual keeps the factual value.
Attributes:
| Name | Type | Description |
|---|---|---|
feature |
str
|
The feature name to freeze. |
Source code in src/treecf/constraints/objects.py
13 14 15 16 17 18 19 20 21 | |
Implies
dataclass
¶
If condition holds then consequence must hold; binary features only.
Attributes:
| Name | Type | Description |
|---|---|---|
condition |
Equals
|
The antecedent equality. |
consequence |
Equals
|
The equality |
Source code in src/treecf/constraints/objects.py
98 99 100 101 102 103 104 105 106 107 108 | |
Linear
dataclass
¶
Linear inter-feature constraint: sum(coef * feature) op rhs.
missing_policy resolves the constraint when a referenced feature is NaN
in the counterfactual: "satisfied" (vacuously true, the default),
"violated"/"forbid_missing" (the counterfactual may not use NaN there).
The exact backend supports single-feature and the canonical two-feature
order-pair shape exactly; any other multi-feature shape raises
ConstraintValidationError naming backend="genetic" as the
fallback — see
Certification.
Attributes:
| Name | Type | Description |
|---|---|---|
coefficients |
dict[str, float]
|
|
op |
str
|
|
rhs |
float
|
The right-hand-side constant. |
missing_policy |
str
|
|
Source code in src/treecf/constraints/objects.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | |
Monotone
dataclass
¶
The feature may only move in one direction from the factual value.
Attributes:
| Name | Type | Description |
|---|---|---|
feature |
str
|
The feature name to constrain. |
direction |
str
|
|
Source code in src/treecf/constraints/objects.py
24 25 26 27 28 29 30 31 32 33 34 35 | |
OneHot
dataclass
¶
The listed binary columns sum to exactly one.
Attributes:
| Name | Type | Description |
|---|---|---|
features |
tuple[str, ...]
|
The mutually exclusive binary feature names; at least two. |
Source code in src/treecf/constraints/objects.py
111 112 113 114 115 116 117 118 119 | |
Range
dataclass
¶
Hard domain bounds for the counterfactual value (inclusive).
Attributes:
| Name | Type | Description |
|---|---|---|
feature |
str
|
The feature name to bound. |
lo |
float
|
Lower bound, inclusive. |
hi |
float
|
Upper bound, inclusive. |
Source code in src/treecf/constraints/objects.py
38 39 40 41 42 43 44 45 46 47 48 49 50 | |
Mining¶
Mine candidate invariants from a background sample, for human review.
Scans X for pairwise orders and equalities, binary implications
(a=1 => b=1), one-hot groups, missingness links (miss(a) =>
miss(b)), and integer-valuedness; optionally also observed 1st/99th
percentile ranges. Mined constraints are sample invariants, not domain
truths — min_support=1.0 on a finite sample can be coincidence — so
nothing here is ever auto-applied; inspect result[i].as_code() and
pass the ones you accept to Explainer(..., constraints=[...])
yourself. See
Constraints — mining candidates from
data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
FloatArray
|
Background sample, one row per instance, aligned to
|
required |
feature_names
|
Sequence[str] | None
|
Column names for |
None
|
min_support
|
float
|
Minimum fraction of co-present rows a pairwise order
must hold on to be suggested ( |
1.0
|
top_k
|
int
|
Maximum number of suggestions to return, after ranking by support and rationale strength; findings are not subject to this limit. |
50
|
report_threshold
|
float
|
Minimum support for a near-invariant (one below
|
0.999
|
include_ranges
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
SuggestionSet
|
A |
SuggestionSet
|
ranked and trimmed to |
SuggestionSet
|
that fell short of |
Source code in src/treecf/mining.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | |
One candidate invariant mined from a background sample, for human review.
suggest_constraints never applies a suggestion itself; the workflow is
to inspect as_code()/rationale/evidence, decide which
suggestions are real domain rules, and pass their constraint objects
to Explainer(..., constraints=[...]) explicitly. See
Constraints — mining candidates from
data.
Attributes:
| Name | Type | Description |
|---|---|---|
constraint |
Constraint | None
|
The compiled constraint object this suggestion proposes,
or |
kind |
str
|
|
support |
float
|
Fraction of checked rows the invariant held on, in
|
n_rows_checked |
int
|
Number of rows the check was evaluated over; what
counts as checkable depends on |
n_violations |
int
|
Number of those rows that violated the invariant;
|
evidence |
list[dict[str, object]]
|
Up to 5 violating rows, |
rationale |
str
|
Human-readable justification: shared name tokens for
|
Source code in src/treecf/mining.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | |
as_code()
¶
This suggestion rendered as a copy-pasteable Python snippet.
Returns:
| Type | Description |
|---|---|
str
|
A |
str
|
for kinds with no direct constraint form, a |
str
|
description) followed by a |
Source code in src/treecf/mining.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | |
A near-invariant that fell short of min_support — likely an ETL defect.
Reported separately from SuggestedConstraint because support in
[report_threshold, min_support) usually means a rule that should be
universal is being violated by a small number of dirty rows, not that the
rule is genuinely conditional — worth fixing upstream rather than
encoding the exception as a constraint.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
Always |
description |
str
|
Human-readable summary, e.g. |
support |
float
|
Fraction of checked rows the near-invariant held on, in
|
n_rows_checked |
int
|
Number of rows where both referenced features were present. |
n_violations |
int
|
Number of those rows that violated the near-invariant. |
evidence |
list[dict[str, object]]
|
Up to 5 violating rows, |
Source code in src/treecf/mining.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
Plausibility¶
A hard isolation-forest bound keeping counterfactuals inside the data manifold.
Construct through Plausibility.isolation_forest rather than the
constructor directly. Pass the result as Explainer(...,
plausibility=...); every returned counterfactual then also satisfies
anomaly_score(x_cf) <= max_anomaly_score, enforced as a hard
constraint by every backend. Cannot be combined with AllowMissing or a
NaN-containing factual (isolation forests define no NaN routing). See
Plausibility.
Attributes:
| Name | Type | Description |
|---|---|---|
if_ir |
EnsembleIR
|
The isolation forest, parsed through the same tree IR the model uses. |
max_anomaly_score |
float
|
The upper bound on |
Source code in src/treecf/plausibility.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
min_total_path
property
¶
The feasibility bound compiled into every backend's plausibility check.
Equivalent to max_anomaly_score re-expressed as a lower bound on
the summed depth-adjusted path length across every tree: a
counterfactual is plausible iff its total path length is at least
this value.
normalizer
property
¶
The average path length c(n) for the forest's subsample size n.
Standard isolation-forest normalizer, derived from if_ir's
max_samples metadata; used to turn a raw total path length into
the [0, 1] anomaly score.
anomaly_score(x)
¶
The isolation-forest anomaly score at x, in [0, 1].
2 ** (-mean_path / normalizer): close to 1 for a point the
forest isolates in very few splits (anomalous), close to 0 for
one that takes many (typical). A point is plausible under this bound
iff its score is <= max_anomaly_score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
FloatArray
|
A feature vector, aligned to the forest's feature order. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The anomaly score at |
Source code in src/treecf/plausibility.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
isolation_forest(model_or_ir, max_anomaly_score=0.55)
classmethod
¶
Build a Plausibility bound from a fitted isolation forest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_or_ir
|
object
|
A native isolation-forest model (currently
sklearn's |
required |
max_anomaly_score
|
float
|
Upper bound on the isolation-forest anomaly
score, in |
0.55
|
Returns:
| Type | Description |
|---|---|
Plausibility
|
A |
Raises:
| Type | Description |
|---|---|
TreecfError
|
If |
Source code in src/treecf/plausibility.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | |
Regions¶
A certified box around one verified counterfactual.
Every point z with lo <= z <= hi coordinate-wise (z_j = x_cf_j
at a degenerate or NaN coordinate) is provably in-target, plausible when
plausibility is configured, and feasible against every compiled
constraint -- the same guarantees the counterfactual itself carries, not
a heuristic neighbourhood around it.
lo/hi cover every feature (degenerate coordinates included, as a
single point); feature_intervals keys only the non-degenerate ones by
name, for display. Regions are certified but neither maximal (a larger
sound box may exist) nor monotone in the target interval (a strictly
narrower target can still produce a strictly wider region on some
feature: growth is greedy and order-dependent, so a feature that is
forced to stop early frees room a later feature grows into). See
Certification.
Attributes:
| Name | Type | Description |
|---|---|---|
lo |
FloatArray
|
Lower bound per feature, same order as the model's features;
equal to |
hi |
FloatArray
|
Upper bound per feature, same order as the model's features. |
feature_intervals |
dict[str, tuple[float, float]]
|
|
certified |
bool
|
Always |
Source code in src/treecf/regions.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
contains(x)
¶
Whether x lies inside the region, coordinate by coordinate.
A degenerate coordinate (lo == hi, including NaN) requires x
to match it exactly; every other coordinate requires
lo <= x[j] <= hi[j].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
FloatArray
|
A feature vector, same order and length as the region. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
bound. |
Source code in src/treecf/regions.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | |
describe()
¶
One human-readable phrase per non-degenerate feature.
One-sided ("<= v"/">= v") when the other endpoint is
infinite, two-sided ("in [lo, hi]") otherwise, and
"unconstrained" when both endpoints are infinite; values
formatted "{:.3g}".
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
|
Source code in src/treecf/regions.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
Audit¶
SHA-256 fingerprint of an ensemble over a canonical byte encoding.
The encoding is positional bytes — the link name, the base score, the tree count, then every node of every tree in index order with fixed-width little-endian fields and fixed sentinel bytes where a field does not apply to the node kind — so the fingerprint is stable across Python versions, platforms, and dict ordering, and changes when any structural or numeric detail of the ensemble changes (a one-ulp leaf perturbation included).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ir
|
EnsembleIR
|
The parsed ensemble to fingerprint ( |
required |
Returns:
| Type | Description |
|---|---|
str
|
A 64-character SHA-256 hex digest. |
Source code in src/treecf/audit.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
SHA-256 fingerprint of an explainer's effective objective and constraints.
Covers the compiled constraint set (type tags, resolved feature indices,
parameters), the distance normalizers sigma, the per-feature
weights, and every value-policy entry, all as canonical little-endian
bytes. A callable value policy has no canonical encoding: it is hashed as
a fixed unhashable_custom tag, and any certificate built from the
explainer records "reproducible": false with a reason.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
explainer
|
Explainer
|
The explainer whose constraint set to fingerprint. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A 64-character SHA-256 hex digest. |
Source code in src/treecf/audit.py
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
Visualization¶
Counterfactual visualizations. matplotlib lives behind the [viz] extra.
plot_alternatives(results, explainer=None, ax=None)
¶
Overlaid dumbbells: every alternative plan's changes for one instance.
Accepts a sequence of Counterfactual objects or feasible
BatchRecord entries, or a mapping of outcomes as returned by
explain_coalitions (keys become legend labels; Infeasible values
are skipped). Each plan keeps one color across all its changes — meant
for a handful of alternatives for the same row (at most 10). With
explainer, changes are plotted as standardized deltas from the
factual (Δ/σ), so features of different scales share one axis; without,
raw values are shown with gray factual dots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
Any
|
The plans to overlay — a sequence, or a mapping keyed by plan name; see above for accepted element types. |
required |
explainer
|
Any
|
When given, changes are standardized by its per-feature
|
None
|
ax
|
Any
|
Existing axes to draw on; a new figure is created if omitted. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The axes the chart was drawn on. |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
If matplotlib is not installed. |
TreecfError
|
If |
Source code in src/treecf/viz.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | |
plot_changes(cf, ax=None)
¶
Dumbbell chart of per-feature changes (from -> to); NaN transitions annotated.
One row per changed feature, a gray dot at the factual value and a blue
dot at the counterfactual value joined by a line; a feature that
transitions to or from NaN is drawn as a single gray dot annotated
"-> NaN"/"NaN ->" instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cf
|
Counterfactual
|
The counterfactual to plot. |
required |
ax
|
Any
|
Existing axes to draw on; a new figure is created if omitted. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The axes the chart was drawn on. |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
If matplotlib is not installed. |
Source code in src/treecf/viz.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |
plot_counterfactuals(results, ax=None)
¶
Changed-feature matrix comparing diverse counterfactuals.
One row per result, one column per feature changed by any of them; a
filled cell marks that the row's plan changed that column's feature.
Rows are labeled by rank and distance (#1 (J=...), ...), in the order
results is given.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
Sequence[Counterfactual]
|
The counterfactuals to compare (e.g. the |
required |
ax
|
Any
|
Existing axes to draw on; a new figure is created if omitted. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The axes the matrix was drawn on. |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
If matplotlib is not installed. |
Source code in src/treecf/viz.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
plot_effort(explainer, cf, ax=None)
¶
Cost-space companion: how the distance J splits across the changes.
One horizontal bar per changed feature, its length the feature's own
contribution w * |delta| / sigma to cf.distance (a NaN transition
priced via AllowMissing's delta_miss/delta_from_miss),
descending. Unlike plot_waterfall's exact score deltas, this
decomposes the recourse cost, not the model score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
explainer
|
Any
|
Explainer wrapping the model; supplies the distance weights and normalizers each contribution is computed from. |
required |
cf
|
Counterfactual
|
The counterfactual to decompose. |
required |
ax
|
Any
|
Existing axes to draw on; a new figure is created if omitted. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The axes the chart was drawn on. |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
If matplotlib is not installed. |
Source code in src/treecf/viz.py
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 | |
plot_ladder(bands_result, ax=None)
¶
Cost of reaching each rating band (Target.bands): the price of every grade.
One bar per band, named and ordered like bands_result; a
Counterfactual bar is its distance, an Infeasible band is
drawn at zero height and labeled "infeasible".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bands_result
|
Mapping[str, object]
|
The dict returned by |
required |
ax
|
Any
|
Existing axes to draw on; a new figure is created if omitted. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The axes the chart was drawn on. |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
If matplotlib is not installed. |
Source code in src/treecf/viz.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
plot_recourse_map(explainer, x, results, target, *, ax=None, space='auto', annotate=True, max_changes_per_label=3, fmt='{:.3g}', schematic=False, region_labels=('Reject', 'Accept'), show_factual_label=True)
¶
Recourse diagram: what each plan costs and where it lands relative to the target.
Plots one point per feasible plan in results at (model output, recourse
cost J), with the factual instance drawn as a red dot at cost 0 and an
arrow from the factual to each plan. A green band marks the target
interval on the model-output axis; the axis flips automatically so that
"improving" always reads as a move toward the band. Model output is shown
as a probability for sigmoid-link models (or when space="probability")
and as the raw score otherwise (space="raw"; space="auto" picks
based on the model's link function).
In the default quantitative view, each plan is labeled with one line —
its name (or "plan {i}", ascending by distance, when unnamed) and its
cost — when annotate is set; the map's job here is the overview, not
a change list. Infeasible entries in results are drawn as grey
markers above the plans, labeled by name ("infeasible" alone when
unlabeled, with a (certified) suffix when the entry carries a
certified proof) regardless of annotate.
schematic=True swaps the quantitative axes and target band for a
slide-friendly rendering: a wavy decision-boundary line instead of a
band, no ticks or axis labels, and "If ..." phrased plan labels (using
each plan's changed features, largest-effort first, truncated to
max_changes_per_label and formatted with fmt). annotate also
gates show_factual_label there — an anchored corner box on the
factual's screen side listing the features any plan changed, at their
original values (schematic mode only; the quantitative view never draws
it). region_labels names the two sides of the boundary in
schematic mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
explainer
|
Any
|
Explainer wrapping the model; supplies the link function and the counterfactual distance weights used to order each plan's changes. |
required |
x
|
Any
|
Factual feature vector. |
required |
results
|
Any
|
Counterfactual outcomes for |
required |
target
|
Any
|
The target interval the plans were solved against; also drawn as the band (or boundary, in schematic mode). |
required |
ax
|
Any
|
Existing axes to draw on; a new figure is created if omitted. |
None
|
space
|
str
|
|
'auto'
|
annotate
|
bool
|
Draw a text label at each plan's point; in |
True
|
max_changes_per_label
|
int
|
Schematic mode only. Number of changed features shown per label before truncating to "(+k more)". |
3
|
fmt
|
str
|
Schematic mode only. Format string for changed feature values in labels. |
'{:.3g}'
|
schematic
|
bool
|
Render the slide-friendly boundary view instead of the quantitative axes. |
False
|
region_labels
|
tuple[str, str]
|
The (reject-side, accept-side) names drawn next to the boundary in schematic mode. |
('Reject', 'Accept')
|
show_factual_label
|
bool
|
Schematic mode only. Draw an anchored corner box, on the factual's screen side, listing the features any plan changed. |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
The axes the recourse map was drawn on. |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
If matplotlib is not installed. |
TreecfError
|
If |
Source code in src/treecf/viz.py
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 | |
plot_tradeoff(results, target=None, ax=None)
¶
Cost vs achieved score for alternative plans of one instance.
One dot per plan: x = distance J, y = the achieved probability (sigmoid
models) or raw score. target draws the interval bounds the plans had
to reach. Accepts a sequence of Counterfactual objects or feasible
BatchRecord entries, or a mapping as returned by
explain_coalitions (keys label the dots; Infeasible skipped).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
Any
|
The plans to plot; see above for accepted shapes. |
required |
target
|
Any
|
When given, draws the target interval's finite bounds (mapped into the same probability/raw space as the plans) as horizontal reference lines. |
None
|
ax
|
Any
|
Existing axes to draw on; a new figure is created if omitted. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The axes the chart was drawn on. |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
If matplotlib is not installed. |
TreecfError
|
If |
Source code in src/treecf/viz.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
plot_waterfall(explainer, cf, target=None, ax=None)
¶
SHAP-style waterfall: exact score deltas of the counterfactual's changes.
Starts at the factual score, applies the changes one at a time (largest single effect first), each bar being the EXACT score delta from that change (recomputed through the IR — endpoints are exact; per-bar attribution is sequential and therefore order-dependent, like any sequential decomposition). Sigmoid-link models are plotted in probability space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
explainer
|
Any
|
Explainer wrapping the model; supplies the IR the score deltas are recomputed through and the link function. |
required |
cf
|
Counterfactual
|
The counterfactual to decompose. |
required |
target
|
Any
|
When given, draws the target interval's finite bounds (in the same display space) as vertical reference lines. |
None
|
ax
|
Any
|
Existing axes to draw on; a new figure is created if omitted. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The axes the waterfall was drawn on. |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
If matplotlib is not installed. |
Source code in src/treecf/viz.py
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 | |
Batch-level counterfactual visualizations. matplotlib lives behind the [viz] extra.
Every function consumes a BatchResult. k=0 (the default) keeps each
row's best plan; k=None keeps every feasible plan, so shares are per plan,
not per row.
plot_batch_deltas(batch, explainer=None, k=0, top_n=10, ax=None)
¶
Strip plot of actual deltas (to − from) per feature, top-N most-changed.
One jittered dot per plan, a median tick per feature; NaN transitions are
counted in a per-feature annotation instead of plotted. With explainer,
deltas are divided by the per-feature normalizer sigma so features of
different scales share one axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
BatchResult
|
The batch result to visualize. |
required |
explainer
|
Any
|
When given, standardizes deltas by its per-feature
|
None
|
k
|
int | None
|
Which plan(s) to include per row — |
0
|
top_n
|
int
|
Maximum number of features to show, most-changed first. |
10
|
ax
|
Any
|
Existing axes to draw on; a new figure is created if omitted. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The axes the strip plot was drawn on. |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
If matplotlib is not installed. |
TreecfError
|
If |
Source code in src/treecf/viz_batch.py
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | |
plot_batch_levers(batch, k=0, normalize=True, top_n=20, show_essential=True, ax=None)
¶
Horizontal stacked bars: share of plans changing each feature, by direction.
Increases, decreases, and NaN transitions stack per feature, ordered by how
often the feature is used. For diversity="lever-blocking" results,
features recorded as essential levers are annotated with their count.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
BatchResult
|
The batch result to summarize. |
required |
k
|
int | None
|
Which plan(s) to include per row — |
0
|
normalize
|
bool
|
When |
True
|
top_n
|
int
|
Maximum number of features to show, most-used first. |
20
|
show_essential
|
bool
|
When |
True
|
ax
|
Any
|
Existing axes to draw on; a new figure is created if omitted. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The axes the chart was drawn on. |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
If matplotlib is not installed. |
TreecfError
|
If |
Source code in src/treecf/viz_batch.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
plot_batch_matrix(batch, explainer=None, k=0, sort_rows=True, max_row_labels=30, ax=None)
¶
Plans × features heatmap: binary changes, or effort-shaded with an explainer.
With explainer, each cell shows the change's effort w·|Δ|/σ (NaN
legs priced via AllowMissing); without, cells mark changed features
like plot_counterfactuals. Rows sort by distance; columns by how often
the feature is changed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
BatchResult
|
The batch result to visualize. |
required |
explainer
|
Any
|
When given, shades cells by change effort instead of a
flat binary mark; must describe the same feature space as
|
None
|
k
|
int | None
|
Which plan(s) to include per row — |
0
|
sort_rows
|
bool
|
When |
True
|
max_row_labels
|
int
|
Row id labels are drawn only when the selected plan count is at or below this limit; beyond it, the y-axis is left unlabeled with a plan-count caption instead. |
30
|
ax
|
Any
|
Existing axes to draw on; a new figure is created if omitted. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The axes the heatmap was drawn on. |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
If matplotlib is not installed. |
TreecfError
|
If |
Source code in src/treecf/viz_batch.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
plot_batch_summary(batch, k=0, axs=None)
¶
Three-panel batch overview: plan cost, sparsity, and feasibility.
Creates its own figure when axs is None and returns the array of three
axes (unlike the single-axes functions, which return one ax). Panels:
a histogram of distance over the selected plans, a bar chart of
n_changed counts, and a feasible-vs-infeasible bar over every row
(independent of k — every row counts once).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
BatchResult
|
The batch result to summarize. |
required |
k
|
int | None
|
Which plan(s) feed the cost/sparsity panels — |
0
|
axs
|
Any
|
Existing array of 3 axes to draw on; a new figure is created if omitted. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The array of 3 axes (cost, sparsity, feasibility) the panels were |
Any
|
drawn on. |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
If matplotlib is not installed. |
TreecfError
|
If |
Source code in src/treecf/viz_batch.py
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |