SearchLibrium 0.0.271__tar.gz → 0.0.273__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. {searchlibrium-0.0.271/src/SearchLibrium.egg-info → searchlibrium-0.0.273}/PKG-INFO +1 -1
  2. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/pyproject.toml +1 -1
  3. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/__init__.py +2 -2
  4. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/larch_compat.py +147 -1
  5. searchlibrium-0.0.273/src/SearchLibrium/version.txt +1 -0
  6. {searchlibrium-0.0.271 → searchlibrium-0.0.273/src/SearchLibrium.egg-info}/PKG-INFO +1 -1
  7. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium.egg-info/SOURCES.txt +1 -0
  8. searchlibrium-0.0.273/tests/test_larch_compat.py +158 -0
  9. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/tests/test_larch_integration.py +2 -1
  10. searchlibrium-0.0.271/src/SearchLibrium/version.txt +0 -1
  11. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/LICENSE +0 -0
  12. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/MANIFEST.in +0 -0
  13. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/README.md +0 -0
  14. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/setup.cfg +0 -0
  15. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/BEHier.py +0 -0
  16. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/Halton.py +0 -0
  17. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/MixedLogit.py +0 -0
  18. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/MixedLogitGSE.py +0 -0
  19. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/Mode_Activity_Nested.py +0 -0
  20. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/RandomP.py +0 -0
  21. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/SEARCH_SM_MARIO.py +0 -0
  22. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/Two_Level_Nest.py +0 -0
  23. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/__main__.py +0 -0
  24. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/_choice_model.py +0 -0
  25. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/_device.py +0 -0
  26. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/abm.py +0 -0
  27. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/accessibility.py +0 -0
  28. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/banditsa.py +0 -0
  29. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/boxcox_functions.py +0 -0
  30. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/call_meta.py +0 -0
  31. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/constraints_builder.py +0 -0
  32. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/coupled_solver.py +0 -0
  33. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/data/Swissmetro_final.csv +0 -0
  34. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/data/TravelMode.csv +0 -0
  35. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/data/electricity.csv +0 -0
  36. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/destination_distances.py +0 -0
  37. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/harmony.py +0 -0
  38. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/hspbil.py +0 -0
  39. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/jax_utils.py +0 -0
  40. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/larch_models.py +0 -0
  41. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/latent_class.py +0 -0
  42. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/latent_spec.py +0 -0
  43. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/lc_rail_guard.py +0 -0
  44. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/logistic_regression.py +0 -0
  45. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/main.py +0 -0
  46. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/main_debug.py +0 -0
  47. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/mdcev.py +0 -0
  48. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/mh_choice_estimator.py +0 -0
  49. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/misc.py +0 -0
  50. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/mixed_logit.py +0 -0
  51. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/mixed_nested.py +0 -0
  52. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/mixedrrm.py +0 -0
  53. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/multinomial_logit.py +0 -0
  54. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/multinomial_nested.py +0 -0
  55. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/multinomial_probit.py +0 -0
  56. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/numba_engine.py +0 -0
  57. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/numba_mxl.py +0 -0
  58. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/numba_rrm.py +0 -0
  59. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/ordered_logit.py +0 -0
  60. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/ordered_logit_mixed.py +0 -0
  61. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/predict.py +0 -0
  62. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/regularization.py +0 -0
  63. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/rrm.py +0 -0
  64. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/sample_data.py +0 -0
  65. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/sapbil.py +0 -0
  66. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/search.py +0 -0
  67. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/selection_models.py +0 -0
  68. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/setup.py +0 -0
  69. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/siman.py +0 -0
  70. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/skims.py +0 -0
  71. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/sparseea_agds.py +0 -0
  72. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/test_lc_de.py +0 -0
  73. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/test_mario_searches.py +0 -0
  74. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/test_sapbil_vs_banditsa.py +0 -0
  75. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/threshold.py +0 -0
  76. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium/zero_inflated_ordered_probit.py +0 -0
  77. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium.egg-info/dependency_links.txt +0 -0
  78. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium.egg-info/entry_points.txt +0 -0
  79. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium.egg-info/requires.txt +0 -0
  80. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/src/SearchLibrium.egg-info/top_level.txt +0 -0
  81. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/tests/test_destination_distances.py +0 -0
  82. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/tests/test_jax_mask_equivalence.py +0 -0
  83. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/tests/test_lc_smart_init.py +0 -0
  84. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/tests/test_mh_choice_estimator.py +0 -0
  85. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/tests/test_mxl_random_starts.py +0 -0
  86. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/tests/test_per_alternative_random.py +0 -0
  87. {searchlibrium-0.0.271 → searchlibrium-0.0.273}/tests/test_zero_inflated_ordered_probit.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: SearchLibrium
3
- Version: 0.0.271
3
+ Version: 0.0.273
4
4
  Summary: Automated specification search for discrete choice models (logit, mixed logit, nested logit, RRM and more) using metaheuristic optimisation
5
5
  Author: Zeke Ahern, Mario Fernando Taco Morales, Alexander Paz, Prithvi Beeramole, Robert Burdett
6
6
  Maintainer-email: Zeke Ahern <z.ahern@qut.edu.au>
@@ -132,7 +132,7 @@ Documentation = "https://pypi.org/project/SearchLibrium/"
132
132
  realpython = "SearchLibrium.__main__:main"
133
133
 
134
134
  [tool.bumpver]
135
- current_version = "0.0.271"
135
+ current_version = "0.0.273"
136
136
  version_pattern = "MAJOR.MINOR.PATCH"
137
137
  commit_message = "[skip ci] Bump version {old_version} -> {new_version}"
138
138
  commit = true
@@ -195,7 +195,7 @@ _IMPORT_GROUPS = [
195
195
  'estimate_row_guard', 'check_gradient_health']),
196
196
  ('larch_compat', ['apply_larch_patches']),
197
197
  ('larch_models', ['LarchMNL', 'LarchNestedLogit', 'LarchMixedLogit',
198
- 'build_latent_class']),
198
+ 'LarchLatentClass', 'build_latent_class']),
199
199
  ('skims', ['omx_to_dataframe', 'read_omx_skims', 'prepare_skims_from_omx',
200
200
  'merge_skim_component']),
201
201
  ('destination_distances', ['haversine_km', 'pick_skim_matrices',
@@ -254,7 +254,7 @@ __all__ = [
254
254
  "elasticnet_objective", "elasticnet_penalty_and_grad", "nl_identification_priors",
255
255
  "ensure_jax_environment", "is_large_model", "estimate_row_guard", "check_gradient_health",
256
256
  "apply_larch_patches", "LarchMNL", "LarchNestedLogit", "LarchMixedLogit",
257
- "build_latent_class",
257
+ "LarchLatentClass", "build_latent_class",
258
258
  "omx_to_dataframe", "read_omx_skims", "prepare_skims_from_omx", "merge_skim_component",
259
259
  "haversine_km", "pick_skim_matrices", "load_skim_matrices",
260
260
  "build_case_alt_distances", "summarize_distance_sources",
@@ -25,9 +25,30 @@ What it fixes (see original module docstring for the full story):
25
25
  4. **``pf`` inference sync** — writes ridge-aware ``std_err`` / ``t_stat``
26
26
  (``value / se``, not the inverted historic form) / ``p_value`` into the
27
27
  parameter frame, served through a ``pf`` property shim.
28
+ 5. **Numba engine graph-None rebuild guards** (promoted 2026-11-11;
29
+ HPC-validated in probe jobs ``lc_graphfix_probe`` / ``lc_classdt_probe``).
30
+ Larch 6.0.x rebuilds fixed/work arrays from graph slots on every
31
+ unmangle/reflow; a graph-less (datatreeless) sub-model — e.g. the class
32
+ membership model whenever upstream wiring skips it — died with
33
+ ``AttributeError "'NoneType' object has no attribute
34
+ 'node_slot_arrays'"`` the moment anyone reassigns or reads its dataset.
35
+ Both rebuilds now no-op when ``graph is None``.
36
+ 6. **LatentClass membership datatree wiring for tree inputs** (promoted
37
+ 2026-11-11; same probe lineage). Stock larch auto-wires the class
38
+ membership model's datatree/graph ONLY when ``datatree`` is a Dataset;
39
+ every tree-shaped input (exactly what the production Stage-5 pipeline
40
+ passes) took no branch, so the membership model stayed datatreeless and
41
+ the first ``loglike()`` died inside ``LatentClass.jax_probability``.
42
+ The patch mirrors the Dataset-branch wiring for non-Dataset inputs by
43
+ handing the membership model a minimal flat class dataset (case × K
44
+ altids). Canary-gated: deactivates itself once upstream larch wires
45
+ membership for DataTree inputs natively.
28
46
 
29
47
  Idempotent and a safe no-op when larch is not installed or its internals
30
- differ (every patch site is guarded by ``hasattr``).
48
+ differ (every patch site is guarded by ``hasattr``). Patches 5 and 6 share
49
+ the marker attributes ``_graph_none_guard`` / ``_qut_membership_wiring``
50
+ with the tour pipeline's own ``larch_patches.py``, so applying either copy
51
+ first makes the other a no-op (no double wrapping).
31
52
  """
32
53
 
33
54
  from __future__ import annotations
@@ -272,6 +293,131 @@ def apply_larch_patches() -> bool:
272
293
  if _cls is not None:
273
294
  _install_pf_shim(_cls)
274
295
 
296
+ # ── numba engine: graph-None rebuild guards ──────────────────────
297
+ # Larch 6.0.x rebuilds fixed/work arrays from graph slots on every
298
+ # unmangle/reflow; a graph-less (datatreeless) sub-model therefore dies
299
+ # with AttributeError "'NoneType' object has no attribute
300
+ # 'node_slot_arrays'" the moment anyone reassigns or reads its dataset
301
+ # (first surfaced as the stage-5 LCCM arm's anonymous -1e9 GA sentinel).
302
+ # Guard both rebuilds to a no-op when graph is None: a graphless model has
303
+ # no slots to rebuild FROM, and its evaluation path (flow folds) does not
304
+ # take them from there. Idempotent via the _graph_none_guard marker,
305
+ # shared with the tour pipeline's larch_patches.py.
306
+ try:
307
+ from larch.model import numbamodel as _nbm_g
308
+ except Exception as _e_g: # noqa: BLE001
309
+ _nbm_g = None
310
+ logger.debug("larch_compat: numbamodel unavailable (%s)", _e_g)
311
+ if _nbm_g is not None:
312
+ for _gname in ("_rebuild_fixed_arrays", "_rebuild_work_arrays"):
313
+ _gorig = getattr(_nbm_g.NumbaModel, _gname, None)
314
+ if _gorig is None or getattr(_gorig, "_graph_none_guard", False):
315
+ continue
316
+
317
+ def _graph_guarded(orig, _nm):
318
+ # Forward *args/**kwargs: larch calls
319
+ # _rebuild_work_arrays(on_missing_data=...), and dropping that
320
+ # keyword raises TypeError before the graph guard is reached.
321
+ def _impl(self, *args, **kwargs):
322
+ if getattr(self, "graph", None) is None:
323
+ logger.debug(
324
+ "larch_compat: %s skipped for graphless %s",
325
+ _nm, type(self).__name__)
326
+ return
327
+ return orig(self, *args, **kwargs)
328
+ _impl._graph_none_guard = True
329
+ return _impl
330
+
331
+ setattr(_nbm_g.NumbaModel, _gname, _graph_guarded(_gorig, _gname))
332
+ logger.info("larch_compat: NumbaModel.%s → graph-None guard", _gname)
333
+
334
+ # ── LatentClass: membership-model datatree wiring for tree inputs ──
335
+ # Larch 6.0.x LatentClass.__init__ auto-wires the class-membership
336
+ # model's datatree/graph ONLY when ``datatree`` is a Dataset (the
337
+ # no-groupid ``set_altids`` branch). Every tree-shaped input — exactly
338
+ # what the production Stage-5 pipeline passes — takes NO branch, so the
339
+ # membership model stays datatreeless: graph None, _data_arrays None,
340
+ # and the first loglike() dies inside LatentClass.jax_probability with
341
+ # "'NoneType' object has no attribute 'av'" (pre-guard form:
342
+ # 'node_slot_arrays'; validated 2026-11-10 via HPC probes
343
+ # lc_graphfix_probe / lc_classdt_probe). Reference arms converge only
344
+ # because they pass a flat Dataset.
345
+ #
346
+ # The patch mirrors the no-groupid wiring for non-Dataset inputs by
347
+ # handing the membership model a minimal flat class dataset
348
+ # (case × K altids) — the intercept-only membership used by the
349
+ # pipeline needs nothing more, larch builds the membership graph from
350
+ # these altids, and reflow overwrites classmodel.dataset with the
351
+ # derived class data anyway. Covariate plumbing stays the caller's
352
+ # business, as in stock larch. Canary-gated: deactivates itself once
353
+ # upstream larch wires membership for DataTree inputs natively.
354
+ def _lc_membership_needs_wiring():
355
+ import pandas as _pd_lc
356
+ from larch.dataset import DataTree as _DT, Dataset as _DS
357
+ try:
358
+ _d = _pd_lc.DataFrame(
359
+ {"case": ["a", "a", "b", "b"], "alt": [1, 2, 1, 2],
360
+ "ch": [1.0, 0.0, 0.0, 1.0]}
361
+ ).set_index(["case", "alt"])
362
+ dto = _DS.construct.from_idca(_d, fill_missing=0.0)
363
+ _cm = larch.Model() # membership model
364
+ _ch = larch.Model() # single class
365
+ _ch.utility_co[2] = larch.P("g") * 1.0
366
+ _lc = larch.LatentClass(_cm, {1: _ch}, datatree=_DT(main=dto))
367
+ return getattr(_lc.class_membership_model, "datatree",
368
+ None) is None
369
+ except Exception as _e_c: # noqa: BLE001
370
+ logger.debug("larch_compat: LC membership canary failed (%r) "
371
+ "— assuming wiring needed", _e_c)
372
+ return True
373
+
374
+ if _lc_membership_needs_wiring():
375
+ from larch.dataset import DataTree as _DT_w, Dataset as _DS_w
376
+ _LC_cls = larch.LatentClass
377
+ _lc_orig_init = _LC_cls.__init__
378
+ if not getattr(_lc_orig_init, "_qut_membership_wiring", False):
379
+
380
+ def _lc_wired_init(self, classmodel, choicemodels,
381
+ datatree=None, **kw):
382
+ try:
383
+ if (classmodel.datatree is None and datatree is not None
384
+ and not isinstance(datatree, _DS_w)):
385
+ _keys = sorted(choicemodels.keys())
386
+ _rid = datatree.root_dataset
387
+ _dims = list(_rid.sizes)
388
+ _cdim = next(
389
+ (d for d in _dims
390
+ if "caseid" in str(d).lower()
391
+ or str(d).startswith("_case")),
392
+ None)
393
+ if _cdim is None:
394
+ _cdim = max(_dims,
395
+ key=lambda d: int(_rid.sizes[d]))
396
+ _nc = int(_rid.sizes[_cdim])
397
+ import pandas as _pd_lc2
398
+ _ca = _pd_lc2.DataFrame({
399
+ "case_id": np.repeat(np.arange(_nc), len(_keys)),
400
+ "_altid_": np.tile(
401
+ np.asarray(_keys, dtype=np.int64), _nc),
402
+ }).set_index(["case_id", "_altid_"])
403
+ classmodel.datatree = _DS_w.construct.from_idca(
404
+ _ca, fill_missing=0.0)
405
+ logger.info(
406
+ "larch_compat: LatentClass membership datatree "
407
+ "wired for %s input (%d classes)",
408
+ type(datatree).__name__, len(_keys))
409
+ except Exception as _e_mw: # noqa: BLE001
410
+ logger.debug(
411
+ "larch_compat: membership wiring skipped (%r)",
412
+ _e_mw)
413
+ return _lc_orig_init(self, classmodel, choicemodels,
414
+ datatree=datatree, **kw)
415
+
416
+ _lc_wired_init._qut_membership_wiring = True
417
+ _LC_cls.__init__ = _lc_wired_init
418
+ logger.info("larch_compat: LatentClass.__init__ → membership "
419
+ "datatree wiring for tree inputs")
420
+
275
421
  logger.info("larch_compat: applied")
276
422
  return True
277
423
 
@@ -0,0 +1 @@
1
+ 0.0.273
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: SearchLibrium
3
- Version: 0.0.271
3
+ Version: 0.0.273
4
4
  Summary: Automated specification search for discrete choice models (logit, mixed logit, nested logit, RRM and more) using metaheuristic optimisation
5
5
  Author: Zeke Ahern, Mario Fernando Taco Morales, Alexander Paz, Prithvi Beeramole, Robert Burdett
6
6
  Maintainer-email: Zeke Ahern <z.ahern@qut.edu.au>
@@ -75,6 +75,7 @@ src/SearchLibrium/data/TravelMode.csv
75
75
  src/SearchLibrium/data/electricity.csv
76
76
  tests/test_destination_distances.py
77
77
  tests/test_jax_mask_equivalence.py
78
+ tests/test_larch_compat.py
78
79
  tests/test_larch_integration.py
79
80
  tests/test_lc_smart_init.py
80
81
  tests/test_mh_choice_estimator.py
@@ -0,0 +1,158 @@
1
+ """Regression tests for the promoted larch compatibility patches.
2
+
3
+ Covers the two LCCM fixes tracked in GitHub issue #1:
4
+
5
+ 1. graph-None guards on ``NumbaModel._rebuild_fixed_arrays`` /
6
+ ``_rebuild_work_arrays``;
7
+ 2. ``LatentClass.__init__`` membership datatree wiring for ``DataTree``
8
+ inputs, including the cross-copy marker contract with the tour
9
+ pipeline's ``larch_patches.py`` (stand-in: a second copy of this module).
10
+ """
11
+ import importlib.util
12
+ import os
13
+ import subprocess
14
+ import sys
15
+ import textwrap
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+ import pytest
21
+
22
+
23
+ def _larch_importable():
24
+ return importlib.util.find_spec("larch") is not None
25
+
26
+
27
+ pytestmark = pytest.mark.skipif(
28
+ not _larch_importable(), reason="larch not installed")
29
+
30
+
31
+ def _apply():
32
+ from SearchLibrium.larch_compat import apply_larch_patches
33
+ assert apply_larch_patches() is True
34
+
35
+
36
+ def _toy_datatree(n=80, alts=(1, 2), seed=0):
37
+ """Return an idca Dataset wrapped in a single-node DataTree."""
38
+ import larch as lx
39
+
40
+ rng = np.random.default_rng(seed)
41
+ rows = []
42
+ for i in range(n):
43
+ x = rng.normal(size=len(alts))
44
+ chosen = int(np.argmax(x + rng.gumbel(size=len(alts))))
45
+ for j, alt in enumerate(alts):
46
+ rows.append((i, alt, x[j], 1 if j == chosen else 0))
47
+ frame = pd.DataFrame(
48
+ rows, columns=["case", "alt", "x", "ch"]
49
+ ).set_index(["case", "alt"])
50
+ ds = lx.Dataset.construct.from_idca(frame)
51
+ return lx.DataTree(main=ds), ds
52
+
53
+
54
+ def test_larch_latent_class_is_public():
55
+ """The first-class LCCM wrapper is exported at package level."""
56
+ from SearchLibrium import LarchLatentClass
57
+ from SearchLibrium.larch_models import LarchLatentClass as Direct
58
+
59
+ assert LarchLatentClass is Direct
60
+
61
+
62
+ def test_graph_none_rebuild_guards_installed():
63
+ _apply()
64
+ from larch.model.numbamodel import NumbaModel
65
+
66
+ for name in ("_rebuild_fixed_arrays", "_rebuild_work_arrays"):
67
+ assert getattr(getattr(NumbaModel, name), "_graph_none_guard", False)
68
+ # A graphless model must survive a rebuild call instead of raising
69
+ # "'NoneType' object has no attribute 'node_slot_arrays'".
70
+ import larch as lx
71
+
72
+ model = lx.Model()
73
+ assert getattr(model, "graph", None) is None
74
+ model._rebuild_fixed_arrays()
75
+ # larch calls this with on_missing_data=...; the guard must forward the
76
+ # keyword instead of raising TypeError (smoke_s5b regression, 2026-11-11).
77
+ model._rebuild_work_arrays(on_missing_data="silent")
78
+ model._rebuild_work_arrays(on_missing_data="raise")
79
+
80
+
81
+ def test_latent_class_membership_wired_for_datatree_input():
82
+ """Issue #1 acceptance test (a) + (b)."""
83
+ _apply()
84
+ import larch as lx
85
+ from larch import P
86
+
87
+ tree, ds = _toy_datatree()
88
+ class_models = {}
89
+ for k, name in ((1, "c1"), (2, "c2")):
90
+ cm = lx.Model(ds)
91
+ cm.choice_ca_var = "ch"
92
+ cm.utility_co[2] = P(name)
93
+ class_models[k] = cm
94
+ membership = lx.Model()
95
+ membership.utility_co[2] = P("g")
96
+
97
+ latent = lx.LatentClass(
98
+ membership, class_models, datatree=tree)
99
+
100
+ assert latent.class_membership_model.datatree is not None
101
+ ll0 = float(latent.loglike())
102
+ assert np.isfinite(ll0)
103
+
104
+ # Parameters must actually move the likelihood (no frozen/datatreeless
105
+ # membership path).
106
+ latent.pvals = np.asarray(latent.pvals, dtype=float) + 0.3
107
+ ll1 = float(latent.loglike())
108
+ assert np.isfinite(ll1)
109
+ assert abs(ll1 - ll0) > 1e-6
110
+
111
+
112
+ def test_apply_is_idempotent_for_latent_class_init():
113
+ _apply()
114
+ import larch as lx
115
+
116
+ init_before = lx.LatentClass.__init__
117
+ _apply()
118
+ assert lx.LatentClass.__init__ is init_before
119
+
120
+
121
+ def test_marker_contract_with_second_patch_copy():
122
+ """Issue #1 acceptance test (c): a second copy must not double-wrap.
123
+
124
+ The tour pipeline's ``larch_patches.py`` shares the
125
+ ``_graph_none_guard`` / ``_qut_membership_wiring`` markers. A second
126
+ copy of this module is a faithful stand-in: load it under the
127
+ SearchLibrium package so its relative imports resolve, apply it, then
128
+ apply the package copy in the same fresh interpreter.
129
+ """
130
+ repo = Path(__file__).resolve().parents[1]
131
+ src = str(repo / "src")
132
+ code = textwrap.dedent(
133
+ """
134
+ import importlib.util
135
+ import larch as lx
136
+ from SearchLibrium import larch_compat as slc
137
+
138
+ spec = importlib.util.spec_from_file_location(
139
+ "SearchLibrium._larch_compat_second_copy", slc.__file__)
140
+ second = importlib.util.module_from_spec(spec)
141
+ spec.loader.exec_module(second)
142
+ assert second.apply_larch_patches() is True
143
+
144
+ init_before = lx.LatentClass.__init__
145
+ assert slc.apply_larch_patches() is True
146
+ print("REVERSE_OK" if lx.LatentClass.__init__ is init_before
147
+ else "REVERSE_BAD")
148
+ """
149
+ )
150
+ env = os.environ.copy()
151
+ env["JAX_PLATFORMS"] = "cpu"
152
+ env["PYTHONPATH"] = os.pathsep.join(
153
+ [src] + ([env["PYTHONPATH"]] if env.get("PYTHONPATH") else []))
154
+ proc = subprocess.run(
155
+ [sys.executable, "-c", code], capture_output=True, text=True,
156
+ env=env, timeout=300)
157
+ assert "REVERSE_OK" in proc.stdout, (
158
+ f"stdout={proc.stdout!r} stderr={proc.stderr[-2000:]!r}")
@@ -218,7 +218,8 @@ def test_stage_configs():
218
218
  def test_registry_lists_larch_models():
219
219
  from SearchLibrium.search import ModelRegistry
220
220
  models = ModelRegistry().get_models()
221
- assert {"larch_mnl", "larch_nested", "larch_mixed"} <= set(models)
221
+ assert {"larch_mnl", "larch_nested", "larch_mixed",
222
+ "larch_latent_class"} <= set(models)
222
223
 
223
224
 
224
225
  def test_parameters_accepts_larch_opts_quietly(capsys):
@@ -1 +0,0 @@
1
- 0.0.271
File without changes