saiph 2.0.12__tar.gz → 3.0.0__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 (72) hide show
  1. {saiph-2.0.12 → saiph-3.0.0}/.github/workflows/prepare-release.yml +2 -2
  2. {saiph-2.0.12 → saiph-3.0.0}/.github/workflows/release.yml +2 -2
  3. {saiph-2.0.12 → saiph-3.0.0}/.github/workflows/saiph-ci.yml +2 -2
  4. {saiph-2.0.12 → saiph-3.0.0}/.gitignore +2 -0
  5. {saiph-2.0.12 → saiph-3.0.0}/PKG-INFO +3 -3
  6. {saiph-2.0.12 → saiph-3.0.0}/docs/requirements.txt +1 -1
  7. {saiph-2.0.12 → saiph-3.0.0}/docs/source/reference.rst +8 -0
  8. {saiph-2.0.12 → saiph-3.0.0}/pyproject.toml +2 -2
  9. {saiph-2.0.12 → saiph-3.0.0}/saiph/__init__.py +11 -1
  10. {saiph-2.0.12 → saiph-3.0.0}/saiph/inverse_transform_test.py +32 -0
  11. {saiph-2.0.12 → saiph-3.0.0}/saiph/models.py +0 -2
  12. {saiph-2.0.12 → saiph-3.0.0}/saiph/projection.py +14 -28
  13. {saiph-2.0.12 → saiph-3.0.0}/saiph/projection_test.py +30 -22
  14. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/famd.py +39 -141
  15. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/famd_sparse_test.py +0 -2
  16. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/famd_test.py +146 -39
  17. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/mca.py +10 -65
  18. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/mca_test.py +10 -15
  19. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/pca.py +1 -56
  20. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/pca_test.py +0 -19
  21. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/utils/common.py +21 -2
  22. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/utils/common_test.py +30 -0
  23. {saiph-2.0.12 → saiph-3.0.0}/saiph/serializer.py +1 -1
  24. saiph-3.0.0/saiph/streaming.py +531 -0
  25. saiph-3.0.0/saiph/streaming_test.py +714 -0
  26. saiph-3.0.0/saiph/tests/benchmark_test.py +126 -0
  27. {saiph-2.0.12 → saiph-3.0.0}/uv.lock +205 -223
  28. saiph-2.0.12/saiph/tests/benchmark_test.py +0 -57
  29. {saiph-2.0.12 → saiph-3.0.0}/.github/dependabot.yml +0 -0
  30. {saiph-2.0.12 → saiph-3.0.0}/.github/workflows/pr-title.yml +0 -0
  31. {saiph-2.0.12 → saiph-3.0.0}/.pre-commit-config.yaml +0 -0
  32. {saiph-2.0.12 → saiph-3.0.0}/.readthedocs.yaml +0 -0
  33. {saiph-2.0.12 → saiph-3.0.0}/.tool-versions +0 -0
  34. {saiph-2.0.12 → saiph-3.0.0}/CONTRIBUTING.md +0 -0
  35. {saiph-2.0.12 → saiph-3.0.0}/LICENSE +0 -0
  36. {saiph-2.0.12 → saiph-3.0.0}/README.md +0 -0
  37. {saiph-2.0.12 → saiph-3.0.0}/bin/create_csv.py +0 -0
  38. {saiph-2.0.12 → saiph-3.0.0}/docs/conf.py +0 -0
  39. {saiph-2.0.12 → saiph-3.0.0}/docs/index.rst +0 -0
  40. {saiph-2.0.12 → saiph-3.0.0}/docs/source/example/README.rst +0 -0
  41. {saiph-2.0.12 → saiph-3.0.0}/docs/source/example/plot_example.py +0 -0
  42. {saiph-2.0.12 → saiph-3.0.0}/fixtures/iris.csv +0 -0
  43. {saiph-2.0.12 → saiph-3.0.0}/fixtures/wbcd.csv +0 -0
  44. {saiph-2.0.12 → saiph-3.0.0}/justfile +0 -0
  45. {saiph-2.0.12 → saiph-3.0.0}/release.py +0 -0
  46. {saiph-2.0.12 → saiph-3.0.0}/ruff.toml +0 -0
  47. {saiph-2.0.12 → saiph-3.0.0}/saiph/conftest.py +0 -0
  48. {saiph-2.0.12 → saiph-3.0.0}/saiph/contribution.py +0 -0
  49. {saiph-2.0.12 → saiph-3.0.0}/saiph/contribution_test.py +0 -0
  50. {saiph-2.0.12 → saiph-3.0.0}/saiph/exception.py +0 -0
  51. {saiph-2.0.12 → saiph-3.0.0}/saiph/inverse_transform.py +0 -0
  52. {saiph-2.0.12 → saiph-3.0.0}/saiph/lib/size.py +0 -0
  53. {saiph-2.0.12 → saiph-3.0.0}/saiph/py.typed +0 -0
  54. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/__init__.py +0 -0
  55. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/famd_sparse.py +0 -0
  56. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/utils/__init__.py +0 -0
  57. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/utils/svd.py +0 -0
  58. {saiph-2.0.12 → saiph-3.0.0}/saiph/reduction/utils/svd_test.py +0 -0
  59. {saiph-2.0.12 → saiph-3.0.0}/saiph/serializer_test.py +0 -0
  60. {saiph-2.0.12 → saiph-3.0.0}/saiph/tests/__init_.py +0 -0
  61. {saiph-2.0.12 → saiph-3.0.0}/saiph/tests/profile_cpu.py +0 -0
  62. {saiph-2.0.12 → saiph-3.0.0}/saiph/tests/profile_memory.py +0 -0
  63. {saiph-2.0.12 → saiph-3.0.0}/saiph/visualization.py +0 -0
  64. {saiph-2.0.12 → saiph-3.0.0}/setup.cfg +0 -0
  65. {saiph-2.0.12 → saiph-3.0.0}/tests/fixtures/breast_cancer_wisconsin.csv +0 -0
  66. {saiph-2.0.12 → saiph-3.0.0}/tests/fixtures/breast_cancer_wisconsin_supplemental.csv +0 -0
  67. {saiph-2.0.12 → saiph-3.0.0}/tests/fixtures/iris.csv +0 -0
  68. {saiph-2.0.12 → saiph-3.0.0}/tests/fixtures/iris_factomineR_contributions.csv +0 -0
  69. {saiph-2.0.12 → saiph-3.0.0}/tests/fixtures/iris_factomineR_cos2.csv +0 -0
  70. {saiph-2.0.12 → saiph-3.0.0}/tests/fixtures/wbcd_supplemental_coordinates_famd.csv +0 -0
  71. {saiph-2.0.12 → saiph-3.0.0}/tests/fixtures/wbcd_supplemental_coordinates_mca.csv +0 -0
  72. {saiph-2.0.12 → saiph-3.0.0}/tests/fixtures/wbcd_supplemental_coordinates_pca.csv +0 -0
@@ -34,14 +34,14 @@ jobs:
34
34
 
35
35
  steps:
36
36
  - name: Checkout code
37
- uses: actions/checkout@v6
37
+ uses: actions/checkout@v7
38
38
  with:
39
39
  ssh-key: ${{ secrets.OCTOBOT_SSH_PRIVATE_KEY }}
40
40
  fetch-depth: 0
41
41
  ref: refs/heads/main
42
42
 
43
43
  - name: Set up Python
44
- uses: actions/setup-python@v6
44
+ uses: actions/setup-python@v7
45
45
  with:
46
46
  python-version: "3.13"
47
47
 
@@ -11,10 +11,10 @@ jobs:
11
11
  runs-on: ubuntu-latest
12
12
  steps:
13
13
  - name: Checkout code
14
- uses: actions/checkout@v6
14
+ uses: actions/checkout@v7
15
15
 
16
16
  - name: Set up Python 3.12
17
- uses: actions/setup-python@v6
17
+ uses: actions/setup-python@v7
18
18
  with:
19
19
  python-version: "3.12"
20
20
 
@@ -16,9 +16,9 @@ jobs:
16
16
  ]
17
17
 
18
18
  steps:
19
- - uses: actions/checkout@v6
19
+ - uses: actions/checkout@v7
20
20
  - name: Set up Python ${{ matrix.python-version }}
21
- uses: actions/setup-python@v6
21
+ uses: actions/setup-python@v7
22
22
  with:
23
23
  python-version: ${{ matrix.python-version }}
24
24
 
@@ -69,6 +69,7 @@ instance/
69
69
 
70
70
  # Sphinx documentation
71
71
  docs/_build/
72
+ docs/sg_execution_times.rst
72
73
 
73
74
  # PyBuilder
74
75
  target/
@@ -138,3 +139,4 @@ tmp/
138
139
 
139
140
  # uv
140
141
  .venv/
142
+ .claude/settings.local.json
@@ -1,12 +1,12 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: saiph
3
- Version: 2.0.12
3
+ Version: 3.0.0
4
4
  Summary: A projection package
5
5
  Author-email: Octopize <help@octopize.io>
6
6
  License: Apache-2.0
7
7
  License-File: LICENSE
8
8
  Requires-Python: <3.14,>=3.11
9
- Requires-Dist: matplotlib>=3.10.9
9
+ Requires-Dist: matplotlib>=3.5.2
10
10
  Requires-Dist: msgspec>=0.19
11
11
  Requires-Dist: numpy>=1
12
12
  Requires-Dist: pandas>=2.2.2
@@ -1,2 +1,2 @@
1
- matplotlib==3.10.9
1
+ matplotlib==3.11.1
2
2
  sphinx-gallery==0.21.0
@@ -15,6 +15,14 @@ saiph.models
15
15
  :undoc-members:
16
16
  :show-inheritance:
17
17
 
18
+ saiph.streaming
19
+ ---------------
20
+
21
+ .. automodule:: saiph.streaming
22
+ :members:
23
+ :undoc-members:
24
+ :show-inheritance:
25
+
18
26
  saiph.famd
19
27
  ----------
20
28
 
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "saiph"
3
3
  # Also modify in saiph/__init__.py
4
- version = "2.0.12"
4
+ version = "3.0.0"
5
5
  description = "A projection package"
6
6
  authors = [
7
7
  {name = "Octopize", email = "help@octopize.io"}
@@ -16,7 +16,7 @@ dependencies = [
16
16
  "toolz>=1",
17
17
  "pydantic>=2",
18
18
  "msgspec>=0.19",
19
- "matplotlib>=3.10.9",
19
+ "matplotlib>=3.5.2",
20
20
  ]
21
21
 
22
22
  [project.optional-dependencies]
@@ -1,12 +1,22 @@
1
1
  from .inverse_transform import inverse_transform
2
2
  from .projection import fit, fit_transform, stats, transform
3
+ from .streaming import (
4
+ DecompositionAccumulator,
5
+ ScalingAccumulator,
6
+ ScalingParams,
7
+ fit_streaming,
8
+ )
3
9
 
4
10
  # Also modify in pyproject.toml
5
- __version__ = "2.0.12"
11
+ __version__ = "3.0.0"
6
12
 
7
13
  __all__ = [
14
+ "DecompositionAccumulator",
15
+ "ScalingAccumulator",
16
+ "ScalingParams",
8
17
  "__version__",
9
18
  "fit",
19
+ "fit_streaming",
10
20
  "fit_transform",
11
21
  "inverse_transform",
12
22
  "stats",
@@ -238,3 +238,35 @@ def test_inverse_from_coord_famd(
238
238
  assert_series_equal(wbcd_statistics.loc["50%"], reversed_statistics.loc["50%"])
239
239
  assert_allclose(wbcd_statistics.loc["75%"], reversed_statistics.loc["75%"], atol=1)
240
240
  assert_series_equal(wbcd_statistics.loc["max"], reversed_statistics.loc["max"], atol=1)
241
+
242
+
243
+ def test_inverse_transform_preserves_bool_modality_proportions() -> None:
244
+ """A round-trip must not collapse a bool column onto a single modality.
245
+
246
+ This is the user-visible consequence of scaler() failing to one-hot encode
247
+ non-string modalities: with every dummy zero, undummify() picks essentially
248
+ the same modality for every individual. saiph 2.0.10 to 2.0.12 turned a
249
+ balanced 50/50 bool column into a 98/2 split.
250
+
251
+ The 20 % tolerance is loose on purpose — the point is that both modalities
252
+ survive in roughly their original proportions, not that the round-trip is
253
+ exact.
254
+ """
255
+ n = 50
256
+ df = pd.DataFrame(
257
+ {
258
+ "flag": pd.array([True] * n + [False] * n, dtype=object),
259
+ # Well-separated per modality, so the projection carries enough
260
+ # signal for the round-trip to recover the right one.
261
+ "value": [float(x) for x in range(n)] + [float(x) for x in range(1000, 1000 + n)],
262
+ }
263
+ )
264
+ coord, model = fit_transform(df)
265
+
266
+ result = inverse_transform(coord, model)
267
+
268
+ counts = result["flag"].value_counts()
269
+ assert set(counts.index) == {True, False}
270
+ assert counts[True] == pytest.approx(n, rel=0.2)
271
+ assert counts[False] == pytest.approx(n, rel=0.2)
272
+ assert all(isinstance(value, bool) for value in result["flag"])
@@ -37,8 +37,6 @@ class Model:
37
37
  V: NDArray[np.float64]
38
38
  # Modality type of the first individuals
39
39
  modalities_types: dict[str, str]
40
- # Orthogonal matrix with left singular vectors as columns.
41
- U: NDArray[np.float64]
42
40
  # Singular values
43
41
  s: NDArray[np.float64] | None = None
44
42
 
@@ -59,6 +59,13 @@ def fit(
59
59
  _col_weights[df.columns.get_loc(col)] = col_weights[col]
60
60
 
61
61
  # Check column types
62
+ datetime_cols = df.select_dtypes(include=["datetime", "datetimetz"]).columns.tolist()
63
+ if datetime_cols:
64
+ raise ValueError(
65
+ f"DataFrame contains datetime column(s): {datetime_cols}. "
66
+ "Convert them to numeric (e.g. seconds since epoch) before fitting."
67
+ )
68
+
62
69
  quanti = df.select_dtypes(include=["int", "float", "number"]).columns.values
63
70
  quali = df.select_dtypes(exclude=["int", "float", "number"]).columns.values
64
71
 
@@ -199,6 +206,13 @@ def transform(df: pd.DataFrame, model: Model, *, sparse: bool = False) -> pd.Dat
199
206
  "Call fit() to create a Model instance before calling transform()."
200
207
  )
201
208
 
209
+ datetime_cols = df.select_dtypes(include=["datetime", "datetimetz"]).columns.tolist()
210
+ if datetime_cols:
211
+ raise ValueError(
212
+ f"DataFrame contains datetime column(s): {datetime_cols}. "
213
+ "Convert them to numeric (e.g. seconds since epoch) before transforming."
214
+ )
215
+
202
216
  # Check that all the columns of the df is in the model
203
217
  model_columns = model.original_continuous + model.original_categorical
204
218
  df_columns = df.columns.tolist()
@@ -255,31 +269,3 @@ def get_variable_correlation(
255
269
  "coord",
256
270
  ]
257
271
  return cor
258
-
259
-
260
- def get_reconstructed_df_from_model(model: Model) -> pd.DataFrame:
261
- """Reconstruct the original DataFrame from the model.
262
-
263
- Note: if nf < df.shape[1], reconstructed df will not be exactly the same.
264
- The more nf < df.shape[1], the more the reconstructed df will differ.
265
- the degree of difference is linked to the unused explained variance.
266
-
267
- Parameters:
268
- model: Model computed by fit.
269
-
270
- Returns:
271
- df: The reconstructed DataFrame.
272
- """
273
- if not model.is_fitted:
274
- raise ValueError(
275
- "Model has not been fitted."
276
- "Call fit() to create a Model instance before calling transform()."
277
- )
278
-
279
- if len(model.original_categorical) == 0:
280
- return pca.reconstruct_df_from_model(model)
281
-
282
- if len(model.original_continuous) == 0:
283
- return mca.reconstruct_df_from_model(model)
284
-
285
- return famd.reconstruct_df_from_model(model)
@@ -327,8 +327,7 @@ def test_get_variable_contribution_are_similar_with_reduced_nf() -> None:
327
327
  """Verify that get_variable_contributions returns similar contributions with reduced nf."""
328
328
  df = pd.read_csv("./fixtures/wbcd.csv")
329
329
  model_truncated = fit(df, nf=5) # nf = nf_max/2
330
- df_reconstructed = projection.get_reconstructed_df_from_model(model_truncated)
331
- truncated_contributions = get_variable_contributions(model_truncated, df_reconstructed)
330
+ truncated_contributions = get_variable_contributions(model_truncated, df)
332
331
  model_full = fit(df) # nf = nf_max
333
332
  full_contributions = get_variable_contributions(model_full, df)
334
333
  # We only look at the first two dimensions
@@ -438,6 +437,35 @@ def test_fit_checks_col_weights_parameter(
438
437
  fit(quali_df, col_weights=col_weights)
439
438
 
440
439
 
440
+ @pytest.mark.parametrize(
441
+ "df",
442
+ [
443
+ pd.DataFrame({"a": pd.to_datetime(["2021-01-01", "2021-01-02"]), "b": [1, 2]}),
444
+ pd.DataFrame({"a": pd.to_datetime(["2021-01-01", "2021-01-02"])}),
445
+ pd.DataFrame(
446
+ {
447
+ "a": pd.to_datetime(["2021-01-01", "2021-01-02"]),
448
+ "b": ["x", "y"],
449
+ }
450
+ ),
451
+ ],
452
+ )
453
+ def test_fit_rejects_datetime_columns(df: pd.DataFrame) -> None:
454
+ """Verify that fit raises ValueError when the DataFrame contains datetime columns."""
455
+ with pytest.raises(ValueError, match="datetime"):
456
+ fit(df)
457
+
458
+
459
+ def test_transform_rejects_datetime_columns() -> None:
460
+ """Verify that transform raises ValueError when the DataFrame contains datetime columns."""
461
+ model = fit(pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}))
462
+ df_with_datetime = pd.DataFrame(
463
+ {"a": pd.to_datetime(["2021-01-01", "2021-01-02", "2021-01-03"]), "b": [4, 5, 6]}
464
+ )
465
+ with pytest.raises(ValueError, match="datetime"):
466
+ transform(df_with_datetime, model)
467
+
468
+
441
469
  @pytest.mark.parametrize(
442
470
  "starting_seed, stored_seed",
443
471
  [
@@ -486,26 +514,6 @@ def test_fit_mca_works_with_different_arguments_for_seed_and_stores_them_in_mode
486
514
  assert model.seed == stored_seed
487
515
 
488
516
 
489
- def test_get_reconstructed_df_from_model_calls_correct_subfunction(
490
- quanti_df: pd.DataFrame, quali_df: pd.DataFrame, mixed_df: pd.DataFrame
491
- ) -> None:
492
- """Verify that projection.get_reconstructed_df_from_model calls the correct subfunction."""
493
- # FAMD
494
- model = fit(mixed_df)
495
- expect(saiph.reduction.famd).reconstruct_df_from_model(model).once().and_return(None)
496
- projection.get_reconstructed_df_from_model(model)
497
-
498
- # MCA
499
- model = fit(quali_df)
500
- expect(saiph.reduction.mca).reconstruct_df_from_model(model).once().and_return(None)
501
- projection.get_reconstructed_df_from_model(model)
502
-
503
- # PCA
504
- model = fit(quanti_df)
505
- expect(saiph.reduction.pca).reconstruct_df_from_model(model).once().and_return(None)
506
- projection.get_reconstructed_df_from_model(model)
507
-
508
-
509
517
  @pytest.mark.parametrize(
510
518
  "df_to_fit,df_to_transform",
511
519
  [
@@ -1,9 +1,7 @@
1
1
  """FAMD projection module."""
2
2
 
3
3
  import sys
4
- from collections import defaultdict
5
4
  from collections.abc import Callable
6
- from itertools import chain, repeat
7
5
  from typing import Any, cast
8
6
 
9
7
  import numpy as np
@@ -15,6 +13,7 @@ from saiph.models import Model
15
13
  from saiph.reduction import DUMMIES_SEPARATOR
16
14
  from saiph.reduction.utils.common import (
17
15
  column_multiplication,
16
+ expand_column_weights,
18
17
  get_dummies_mapping,
19
18
  get_explained_variance,
20
19
  get_grouped_modality_values,
@@ -112,6 +111,8 @@ def fit(
112
111
  # Select the categorical and continuous columns
113
112
  quanti = df.select_dtypes(include=["int", "float", "number"]).columns.to_list()
114
113
  quali = df.select_dtypes(exclude=["int", "float", "number"]).columns.to_list()
114
+ if not quali:
115
+ raise ValueError("FAMD requires at least one categorical variable. Use PCA instead.")
115
116
  dummy_categorical = pd.get_dummies(
116
117
  df[quali].astype("category"),
117
118
  prefix_sep=DUMMIES_SEPARATOR,
@@ -120,7 +121,9 @@ def fit(
120
121
  modalities_types = get_modalities_types(df[quali])
121
122
 
122
123
  row_w = get_uniform_row_weights(len(df))
123
- col_weights = _col_weights_compute(df, _col_weights, quanti, quali)
124
+ col_weights = expand_column_weights(
125
+ _col_weights, df.columns.to_list(), quanti, quali, dummy_categorical
126
+ )
124
127
 
125
128
  df_scaled, mean, std, prop, _modalities = center(df, quanti, quali)
126
129
 
@@ -128,19 +131,17 @@ def fit(
128
131
  Z = df_scaled.multiply(col_weights).T.multiply(row_w).T
129
132
 
130
133
  # Compute the svd
131
- _U, S, _Vt = (
134
+ _, S, _Vt = (
132
135
  get_svd(Z.todense(), nf=nf, random_gen=random_gen)
133
136
  if isinstance(Z, scipy.sparse.spmatrix)
134
137
  else get_svd(Z, nf=nf, random_gen=random_gen)
135
138
  )
136
139
 
137
- U = ((_U.T) / np.sqrt(row_w)).T
138
140
  Vt = _Vt / np.sqrt(col_weights)
139
141
 
140
142
  explained_var, explained_var_ratio = get_explained_variance(S, df.shape[0], nf)
141
143
 
142
144
  # Retain only the nf higher singular values
143
- U = U[:, :nf]
144
145
  S = S[:nf]
145
146
  Vt = Vt[:nf, :]
146
147
  # we use the random generator to generate a new seed for the model
@@ -150,7 +151,6 @@ def fit(
150
151
  original_categorical=quali,
151
152
  original_continuous=quanti,
152
153
  dummy_categorical=dummy_categorical,
153
- U=U,
154
154
  V=Vt,
155
155
  s=S,
156
156
  explained_var=explained_var,
@@ -198,33 +198,6 @@ def fit_transform(
198
198
  return coord, model
199
199
 
200
200
 
201
- def _col_weights_compute(
202
- df: pd.DataFrame, col_weights: NDArray[Any], quanti: list[int], quali: list[int]
203
- ) -> NDArray[Any]:
204
- """Calculate weights for columns given what weights the user gave."""
205
- # Set the columns and row weights
206
- weight_df = pd.DataFrame([col_weights], columns=df.columns)
207
- weight_quanti = weight_df[quanti]
208
- weight_quali = weight_df[quali]
209
-
210
- # Get the number of modality for each quali variable
211
- modality_numbers = []
212
- for column in weight_quali.columns:
213
- modality_numbers += [len(df[column].unique())]
214
-
215
- # Set weight vector for categorical columns
216
- weight_quali_rep = list(
217
- chain.from_iterable(
218
- repeat(i, j)
219
- for i, j in zip(list(weight_quali.iloc[0]), modality_numbers, strict=False)
220
- )
221
- )
222
-
223
- _col_weights: NDArray[Any] = np.array(list(weight_quanti.iloc[0]) + weight_quali_rep)
224
-
225
- return _col_weights
226
-
227
-
228
201
  def scaler(model: Model, df: pd.DataFrame) -> pd.DataFrame:
229
202
  """Scale data using mean, std, modalities and proportions of each categorical from model.
230
203
 
@@ -240,6 +213,11 @@ def scaler(model: Model, df: pd.DataFrame) -> pd.DataFrame:
240
213
  "Expected model to have mean and std attributes,",
241
214
  f"got {model.mean} and {model.std} instead.",
242
215
  )
216
+ if model._modalities is None:
217
+ raise ValueError(
218
+ "Expected model to have a _modalities attribute to align the dummies on, "
219
+ "got None instead. Call fit() to create a Model instance."
220
+ )
243
221
  model.prop = cast(pd.Series, model.prop)
244
222
 
245
223
  df_quanti = df[model.original_continuous]
@@ -251,31 +229,19 @@ def scaler(model: Model, df: pd.DataFrame) -> pd.DataFrame:
251
229
  df_quanti = (df_quanti - model.mean) / std_without_zeros
252
230
 
253
231
  # scale
254
- # Attach fit-time categories to each column so that pd.get_dummies emits a
255
- # column for every modality seen during fit — including those absent from
256
- # this transform batch (they become all-zero columns automatically).
257
- # This replaces a one-by-one loop that fragmented the DataFrame block
232
+ df_quali = pd.get_dummies(
233
+ df[model.original_categorical].astype("category"),
234
+ prefix_sep=DUMMIES_SEPARATOR,
235
+ dtype=np.uint8,
236
+ )
237
+ # Align on the fit-time modalities: a modality absent from this batch becomes
238
+ # an all-zero column, and a category unseen at fit is dropped.
239
+ # `reindex` builds the result in a single allocation, unlike the one-by-one
240
+ # `df_quali[mod] = 0` loop it replaces, which fragmented the DataFrame block
258
241
  # manager and emitted a PerformanceWarning after 100+ insertions.
259
- if model._modalities is not None:
260
- col_cats: dict[str, list[str]] = defaultdict(list)
261
- for mod in model._modalities:
262
- col, _, val = mod.partition(DUMMIES_SEPARATOR)
263
- col_cats[col].append(val)
264
-
265
- df_quali = pd.get_dummies(
266
- df[model.original_categorical].assign(
267
- **{col: pd.Categorical(df[col], categories=cats) for col, cats in col_cats.items()}
268
- ),
269
- prefix_sep=DUMMIES_SEPARATOR,
270
- dtype=np.uint8,
271
- )
272
- else:
273
- df_quali = pd.get_dummies(
274
- df[model.original_categorical].astype("category"),
275
- prefix_sep=DUMMIES_SEPARATOR,
276
- dtype=np.uint8,
277
- )
278
- df_quali = df_quali[model._modalities]
242
+ # `fill_value` must be a np.uint8 so that the filled columns keep the dtype
243
+ # asked of get_dummies instead of being upcast to int64.
244
+ df_quali = df_quali.reindex(columns=model._modalities, fill_value=np.uint8(0))
279
245
  df_quali = (df_quali - model.prop) / np.sqrt(model.prop)
280
246
 
281
247
  df_scaled = pd.concat([df_quanti, df_quali], axis=1)
@@ -414,11 +380,7 @@ def compute_categorical_cos2(model: Model, df: pd.DataFrame, min_nf: int) -> pd.
414
380
  -------
415
381
  dataframe of categorical cos2
416
382
  """
417
- if model.U is not None and model.s is not None:
418
- model_coords = pd.DataFrame(
419
- model.U[:, :min_nf] * model.s[:min_nf],
420
- columns=get_projected_column_names(min_nf),
421
- )
383
+ model_coords = get_individual_coordinates(model, df, min_nf)
422
384
 
423
385
  mapping = get_dummies_mapping(model.original_categorical, model.dummy_categorical)
424
386
  dummy = pd.get_dummies(
@@ -449,6 +411,20 @@ def compute_categorical_cos2(model: Model, df: pd.DataFrame, min_nf: int) -> pd.
449
411
  return categorical_cos2
450
412
 
451
413
 
414
+ def get_individual_coordinates(model: Model, df: pd.DataFrame, min_nf: int) -> pd.DataFrame:
415
+ """`U * s` for the individuals of `df`, rebuilt rather than stored on the model.
416
+
417
+ Not `transform(df, model)`: that divides the column weights out of the axes, so it
418
+ agrees only up to a uniform factor, and only when every weight is one.
419
+ """
420
+ scaled = scaler(model, df)
421
+ weighted = column_multiplication(scaled, model.column_weights**1.5)
422
+ coords = weighted @ model.V[:min_nf].T
423
+ coords = row_multiplication(coords, np.sqrt(model.row_weights))
424
+ coords.columns = get_projected_column_names(min_nf)
425
+ return pd.DataFrame(coords)
426
+
427
+
452
428
  def compute_continuous_cos2(
453
429
  model: Model,
454
430
  scaled_df: pd.DataFrame,
@@ -542,81 +518,3 @@ def _compute_cos2_single_category(
542
518
  )
543
519
  single_category_cos2: NDArray[np.float64] = np.array(cos2) / summed_weights_without_zeros
544
520
  return single_category_cos2
545
-
546
-
547
- def reconstruct_df_from_model(model: Model) -> pd.DataFrame:
548
- """Reconstruct a DataFrame from a fitted model.
549
-
550
- Note: if nf < df.shape[1], reconstructed df will not be exactly the same.
551
- The more nf < df.shape[1], the more the reconstructed df will differ.
552
- the degree of difference is linked to the unused explained variance.
553
-
554
- Parameters:
555
- model: Model computed by fit.
556
-
557
- Returns:
558
- df: The reconstructed DataFrame.
559
- """
560
- # Extract the necessary components from the model
561
- if model.s is None or model.mean is None or model.std is None or model.prop is None:
562
- raise ValueError("Model has not been fitted. Call fit() to create a Model instance.")
563
- U = model.U
564
- S = model.s
565
- V = model.V
566
- row_w = model.row_weights
567
- col_weights = model.column_weights
568
- mean = model.mean.values
569
- std = model.std.values
570
- prop = model.prop.values
571
- _modalities = model._modalities
572
- quanti = model.original_continuous
573
- quali = model.original_categorical
574
-
575
- # Construct the diagonal matrix of singular values
576
- Sigma = np.diag(S)
577
-
578
- # Reconstruct the weighted and scaled matrix Z
579
- Z = np.dot(U, np.dot(Sigma, V))
580
-
581
- # Undo the row and column weighting
582
- Z = Z / np.sqrt(row_w)[:, np.newaxis]
583
- Z = Z / np.sqrt(col_weights)
584
-
585
- # Split Z back into quantitative and qualitative parts
586
- n_quanti = len(quanti)
587
- df_quanti_scaled = Z[:, :n_quanti]
588
- df_quali_scaled = Z[:, n_quanti:]
589
-
590
- # Reverse the scaling for quantitative variables
591
- df_quanti = df_quanti_scaled * std + mean
592
-
593
- # Reverse the scaling for qualitative variables
594
- df_quali = df_quali_scaled * np.sqrt(prop) + prop
595
-
596
- # Combine quantitative and qualitative data
597
- df_quali = pd.DataFrame(df_quali, columns=_modalities)
598
- df_quanti = pd.DataFrame(df_quanti, columns=quanti)
599
- df_reconstructed = pd.concat([df_quanti, df_quali], axis=1)
600
-
601
- # Reverse the dummy encoding for categorical variables
602
- for var in quali:
603
- prefix = var + DUMMIES_SEPARATOR
604
- dummies = [col for col in df_reconstructed.columns if col.startswith(prefix)]
605
- df_reconstructed[var] = (
606
- df_reconstructed[dummies].idxmax(axis=1).apply(lambda x: x.split(DUMMIES_SEPARATOR)[1])
607
- )
608
- df_reconstructed.drop(columns=dummies, inplace=True)
609
-
610
- # Ensure the column order matches the original dataframe
611
- df_reconstructed = df_reconstructed[model.original_dtypes.index]
612
-
613
- # Identify the columns that need to be converted to integers
614
- int_columns = model.original_dtypes[model.original_dtypes == "int"].index.tolist()
615
-
616
- # Round the values before because astype(int) truncates the decimals
617
- df_reconstructed[int_columns] = df_reconstructed[int_columns].round()
618
-
619
- # Convert the data types to the original types
620
- df_reconstructed = df_reconstructed.astype(model.original_dtypes)
621
-
622
- return df_reconstructed
@@ -42,14 +42,12 @@ def test_fit_mix(mixed_df2: pd.DataFrame) -> None:
42
42
  ]
43
43
  )
44
44
  expected_s: NDArray[np.float64] = np.array([1.224745e00, 1])
45
- expected_u: NDArray[np.float64] = np.array([[1.0, 1.0], [-1.0, 1.0]])
46
45
  expected_explained_var: NDArray[np.float64] = np.array([1.5, 1.0])
47
46
  expected_explained_var_ratio: NDArray[np.float64] = np.array([0.6, 0.4])
48
47
 
49
48
  assert_frame_equal(abs(result), abs(expected_result), check_exact=False, atol=0.01)
50
49
  assert_allclose(np.abs(model.V), np.abs(expected_v), atol=0.01)
51
50
  assert_allclose(model.s, expected_s, atol=0.01)
52
- assert_allclose(np.abs(model.U), np.abs(expected_u), atol=0.01)
53
51
  assert_allclose(model.explained_var, expected_explained_var, atol=0.01)
54
52
  (assert_allclose(model.explained_var_ratio, expected_explained_var_ratio, atol=0.01),)
55
53
  assert_allclose(model.variable_coord, model.V.T)