saiph 2.0.13__tar.gz → 3.0.1__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 (73) hide show
  1. {saiph-2.0.13 → saiph-3.0.1}/.github/workflows/prepare-release.yml +2 -2
  2. {saiph-2.0.13 → saiph-3.0.1}/.github/workflows/release.yml +2 -2
  3. {saiph-2.0.13 → saiph-3.0.1}/.github/workflows/saiph-ci.yml +2 -2
  4. {saiph-2.0.13 → saiph-3.0.1}/.gitignore +1 -0
  5. {saiph-2.0.13 → saiph-3.0.1}/PKG-INFO +2 -2
  6. saiph-3.0.1/docs/requirements.txt +2 -0
  7. {saiph-2.0.13 → saiph-3.0.1}/docs/source/reference.rst +8 -0
  8. {saiph-2.0.13 → saiph-3.0.1}/pyproject.toml +1 -1
  9. {saiph-2.0.13 → saiph-3.0.1}/saiph/__init__.py +11 -1
  10. {saiph-2.0.13 → saiph-3.0.1}/saiph/models.py +0 -2
  11. {saiph-2.0.13 → saiph-3.0.1}/saiph/projection.py +0 -28
  12. {saiph-2.0.13 → saiph-3.0.1}/saiph/projection_test.py +1 -22
  13. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/famd.py +22 -116
  14. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/famd_sparse_test.py +0 -2
  15. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/famd_test.py +64 -39
  16. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/mca.py +10 -65
  17. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/mca_test.py +10 -15
  18. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/pca.py +1 -56
  19. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/pca_test.py +0 -19
  20. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/utils/common.py +21 -2
  21. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/utils/common_test.py +30 -0
  22. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/utils/svd.py +8 -6
  23. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/utils/svd_test.py +13 -0
  24. {saiph-2.0.13 → saiph-3.0.1}/saiph/serializer.py +1 -1
  25. saiph-3.0.1/saiph/streaming.py +531 -0
  26. saiph-3.0.1/saiph/streaming_test.py +714 -0
  27. saiph-3.0.1/saiph/tests/benchmark_test.py +126 -0
  28. {saiph-2.0.13 → saiph-3.0.1}/uv.lock +218 -243
  29. saiph-2.0.13/docs/requirements.txt +0 -2
  30. saiph-2.0.13/saiph/tests/benchmark_test.py +0 -57
  31. {saiph-2.0.13 → saiph-3.0.1}/.github/dependabot.yml +0 -0
  32. {saiph-2.0.13 → saiph-3.0.1}/.github/workflows/pr-title.yml +0 -0
  33. {saiph-2.0.13 → saiph-3.0.1}/.pre-commit-config.yaml +0 -0
  34. {saiph-2.0.13 → saiph-3.0.1}/.readthedocs.yaml +0 -0
  35. {saiph-2.0.13 → saiph-3.0.1}/.tool-versions +0 -0
  36. {saiph-2.0.13 → saiph-3.0.1}/CONTRIBUTING.md +0 -0
  37. {saiph-2.0.13 → saiph-3.0.1}/LICENSE +0 -0
  38. {saiph-2.0.13 → saiph-3.0.1}/README.md +0 -0
  39. {saiph-2.0.13 → saiph-3.0.1}/bin/create_csv.py +0 -0
  40. {saiph-2.0.13 → saiph-3.0.1}/docs/conf.py +0 -0
  41. {saiph-2.0.13 → saiph-3.0.1}/docs/index.rst +0 -0
  42. {saiph-2.0.13 → saiph-3.0.1}/docs/source/example/README.rst +0 -0
  43. {saiph-2.0.13 → saiph-3.0.1}/docs/source/example/plot_example.py +0 -0
  44. {saiph-2.0.13 → saiph-3.0.1}/fixtures/iris.csv +0 -0
  45. {saiph-2.0.13 → saiph-3.0.1}/fixtures/wbcd.csv +0 -0
  46. {saiph-2.0.13 → saiph-3.0.1}/justfile +0 -0
  47. {saiph-2.0.13 → saiph-3.0.1}/release.py +0 -0
  48. {saiph-2.0.13 → saiph-3.0.1}/ruff.toml +0 -0
  49. {saiph-2.0.13 → saiph-3.0.1}/saiph/conftest.py +0 -0
  50. {saiph-2.0.13 → saiph-3.0.1}/saiph/contribution.py +0 -0
  51. {saiph-2.0.13 → saiph-3.0.1}/saiph/contribution_test.py +0 -0
  52. {saiph-2.0.13 → saiph-3.0.1}/saiph/exception.py +0 -0
  53. {saiph-2.0.13 → saiph-3.0.1}/saiph/inverse_transform.py +0 -0
  54. {saiph-2.0.13 → saiph-3.0.1}/saiph/inverse_transform_test.py +0 -0
  55. {saiph-2.0.13 → saiph-3.0.1}/saiph/lib/size.py +0 -0
  56. {saiph-2.0.13 → saiph-3.0.1}/saiph/py.typed +0 -0
  57. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/__init__.py +0 -0
  58. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/famd_sparse.py +0 -0
  59. {saiph-2.0.13 → saiph-3.0.1}/saiph/reduction/utils/__init__.py +0 -0
  60. {saiph-2.0.13 → saiph-3.0.1}/saiph/serializer_test.py +0 -0
  61. {saiph-2.0.13 → saiph-3.0.1}/saiph/tests/__init_.py +0 -0
  62. {saiph-2.0.13 → saiph-3.0.1}/saiph/tests/profile_cpu.py +0 -0
  63. {saiph-2.0.13 → saiph-3.0.1}/saiph/tests/profile_memory.py +0 -0
  64. {saiph-2.0.13 → saiph-3.0.1}/saiph/visualization.py +0 -0
  65. {saiph-2.0.13 → saiph-3.0.1}/setup.cfg +0 -0
  66. {saiph-2.0.13 → saiph-3.0.1}/tests/fixtures/breast_cancer_wisconsin.csv +0 -0
  67. {saiph-2.0.13 → saiph-3.0.1}/tests/fixtures/breast_cancer_wisconsin_supplemental.csv +0 -0
  68. {saiph-2.0.13 → saiph-3.0.1}/tests/fixtures/iris.csv +0 -0
  69. {saiph-2.0.13 → saiph-3.0.1}/tests/fixtures/iris_factomineR_contributions.csv +0 -0
  70. {saiph-2.0.13 → saiph-3.0.1}/tests/fixtures/iris_factomineR_cos2.csv +0 -0
  71. {saiph-2.0.13 → saiph-3.0.1}/tests/fixtures/wbcd_supplemental_coordinates_famd.csv +0 -0
  72. {saiph-2.0.13 → saiph-3.0.1}/tests/fixtures/wbcd_supplemental_coordinates_mca.csv +0 -0
  73. {saiph-2.0.13 → saiph-3.0.1}/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/
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: saiph
3
- Version: 2.0.13
3
+ Version: 3.0.1
4
4
  Summary: A projection package
5
5
  Author-email: Octopize <help@octopize.io>
6
6
  License: Apache-2.0
@@ -0,0 +1,2 @@
1
+ matplotlib==3.11.2
2
+ sphinx-gallery==0.22.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.13"
4
+ version = "3.0.1"
5
5
  description = "A projection package"
6
6
  authors = [
7
7
  {name = "Octopize", email = "help@octopize.io"}
@@ -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.13"
11
+ __version__ = "3.0.1"
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",
@@ -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
 
@@ -269,31 +269,3 @@ def get_variable_correlation(
269
269
  "coord",
270
270
  ]
271
271
  return cor
272
-
273
-
274
- def get_reconstructed_df_from_model(model: Model) -> pd.DataFrame:
275
- """Reconstruct the original DataFrame from the model.
276
-
277
- Note: if nf < df.shape[1], reconstructed df will not be exactly the same.
278
- The more nf < df.shape[1], the more the reconstructed df will differ.
279
- the degree of difference is linked to the unused explained variance.
280
-
281
- Parameters:
282
- model: Model computed by fit.
283
-
284
- Returns:
285
- df: The reconstructed DataFrame.
286
- """
287
- if not model.is_fitted:
288
- raise ValueError(
289
- "Model has not been fitted."
290
- "Call fit() to create a Model instance before calling transform()."
291
- )
292
-
293
- if len(model.original_categorical) == 0:
294
- return pca.reconstruct_df_from_model(model)
295
-
296
- if len(model.original_continuous) == 0:
297
- return mca.reconstruct_df_from_model(model)
298
-
299
- 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
@@ -515,26 +514,6 @@ def test_fit_mca_works_with_different_arguments_for_seed_and_stores_them_in_mode
515
514
  assert model.seed == stored_seed
516
515
 
517
516
 
518
- def test_get_reconstructed_df_from_model_calls_correct_subfunction(
519
- quanti_df: pd.DataFrame, quali_df: pd.DataFrame, mixed_df: pd.DataFrame
520
- ) -> None:
521
- """Verify that projection.get_reconstructed_df_from_model calls the correct subfunction."""
522
- # FAMD
523
- model = fit(mixed_df)
524
- expect(saiph.reduction.famd).reconstruct_df_from_model(model).once().and_return(None)
525
- projection.get_reconstructed_df_from_model(model)
526
-
527
- # MCA
528
- model = fit(quali_df)
529
- expect(saiph.reduction.mca).reconstruct_df_from_model(model).once().and_return(None)
530
- projection.get_reconstructed_df_from_model(model)
531
-
532
- # PCA
533
- model = fit(quanti_df)
534
- expect(saiph.reduction.pca).reconstruct_df_from_model(model).once().and_return(None)
535
- projection.get_reconstructed_df_from_model(model)
536
-
537
-
538
517
  @pytest.mark.parametrize(
539
518
  "df_to_fit,df_to_transform",
540
519
  [
@@ -2,7 +2,6 @@
2
2
 
3
3
  import sys
4
4
  from collections.abc import Callable
5
- from itertools import chain, repeat
6
5
  from typing import Any, cast
7
6
 
8
7
  import numpy as np
@@ -14,6 +13,7 @@ from saiph.models import Model
14
13
  from saiph.reduction import DUMMIES_SEPARATOR
15
14
  from saiph.reduction.utils.common import (
16
15
  column_multiplication,
16
+ expand_column_weights,
17
17
  get_dummies_mapping,
18
18
  get_explained_variance,
19
19
  get_grouped_modality_values,
@@ -111,6 +111,8 @@ def fit(
111
111
  # Select the categorical and continuous columns
112
112
  quanti = df.select_dtypes(include=["int", "float", "number"]).columns.to_list()
113
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.")
114
116
  dummy_categorical = pd.get_dummies(
115
117
  df[quali].astype("category"),
116
118
  prefix_sep=DUMMIES_SEPARATOR,
@@ -119,7 +121,9 @@ def fit(
119
121
  modalities_types = get_modalities_types(df[quali])
120
122
 
121
123
  row_w = get_uniform_row_weights(len(df))
122
- 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
+ )
123
127
 
124
128
  df_scaled, mean, std, prop, _modalities = center(df, quanti, quali)
125
129
 
@@ -127,19 +131,17 @@ def fit(
127
131
  Z = df_scaled.multiply(col_weights).T.multiply(row_w).T
128
132
 
129
133
  # Compute the svd
130
- _U, S, _Vt = (
134
+ _, S, _Vt = (
131
135
  get_svd(Z.todense(), nf=nf, random_gen=random_gen)
132
136
  if isinstance(Z, scipy.sparse.spmatrix)
133
137
  else get_svd(Z, nf=nf, random_gen=random_gen)
134
138
  )
135
139
 
136
- U = ((_U.T) / np.sqrt(row_w)).T
137
140
  Vt = _Vt / np.sqrt(col_weights)
138
141
 
139
142
  explained_var, explained_var_ratio = get_explained_variance(S, df.shape[0], nf)
140
143
 
141
144
  # Retain only the nf higher singular values
142
- U = U[:, :nf]
143
145
  S = S[:nf]
144
146
  Vt = Vt[:nf, :]
145
147
  # we use the random generator to generate a new seed for the model
@@ -149,7 +151,6 @@ def fit(
149
151
  original_categorical=quali,
150
152
  original_continuous=quanti,
151
153
  dummy_categorical=dummy_categorical,
152
- U=U,
153
154
  V=Vt,
154
155
  s=S,
155
156
  explained_var=explained_var,
@@ -197,33 +198,6 @@ def fit_transform(
197
198
  return coord, model
198
199
 
199
200
 
200
- def _col_weights_compute(
201
- df: pd.DataFrame, col_weights: NDArray[Any], quanti: list[int], quali: list[int]
202
- ) -> NDArray[Any]:
203
- """Calculate weights for columns given what weights the user gave."""
204
- # Set the columns and row weights
205
- weight_df = pd.DataFrame([col_weights], columns=df.columns)
206
- weight_quanti = weight_df[quanti]
207
- weight_quali = weight_df[quali]
208
-
209
- # Get the number of modality for each quali variable
210
- modality_numbers = []
211
- for column in weight_quali.columns:
212
- modality_numbers += [len(df[column].unique())]
213
-
214
- # Set weight vector for categorical columns
215
- weight_quali_rep = list(
216
- chain.from_iterable(
217
- repeat(i, j)
218
- for i, j in zip(list(weight_quali.iloc[0]), modality_numbers, strict=False)
219
- )
220
- )
221
-
222
- _col_weights: NDArray[Any] = np.array(list(weight_quanti.iloc[0]) + weight_quali_rep)
223
-
224
- return _col_weights
225
-
226
-
227
201
  def scaler(model: Model, df: pd.DataFrame) -> pd.DataFrame:
228
202
  """Scale data using mean, std, modalities and proportions of each categorical from model.
229
203
 
@@ -406,11 +380,7 @@ def compute_categorical_cos2(model: Model, df: pd.DataFrame, min_nf: int) -> pd.
406
380
  -------
407
381
  dataframe of categorical cos2
408
382
  """
409
- if model.U is not None and model.s is not None:
410
- model_coords = pd.DataFrame(
411
- model.U[:, :min_nf] * model.s[:min_nf],
412
- columns=get_projected_column_names(min_nf),
413
- )
383
+ model_coords = get_individual_coordinates(model, df, min_nf)
414
384
 
415
385
  mapping = get_dummies_mapping(model.original_categorical, model.dummy_categorical)
416
386
  dummy = pd.get_dummies(
@@ -441,6 +411,20 @@ def compute_categorical_cos2(model: Model, df: pd.DataFrame, min_nf: int) -> pd.
441
411
  return categorical_cos2
442
412
 
443
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
+
444
428
  def compute_continuous_cos2(
445
429
  model: Model,
446
430
  scaled_df: pd.DataFrame,
@@ -534,81 +518,3 @@ def _compute_cos2_single_category(
534
518
  )
535
519
  single_category_cos2: NDArray[np.float64] = np.array(cos2) / summed_weights_without_zeros
536
520
  return single_category_cos2
537
-
538
-
539
- def reconstruct_df_from_model(model: Model) -> pd.DataFrame:
540
- """Reconstruct a DataFrame from a fitted model.
541
-
542
- Note: if nf < df.shape[1], reconstructed df will not be exactly the same.
543
- The more nf < df.shape[1], the more the reconstructed df will differ.
544
- the degree of difference is linked to the unused explained variance.
545
-
546
- Parameters:
547
- model: Model computed by fit.
548
-
549
- Returns:
550
- df: The reconstructed DataFrame.
551
- """
552
- # Extract the necessary components from the model
553
- if model.s is None or model.mean is None or model.std is None or model.prop is None:
554
- raise ValueError("Model has not been fitted. Call fit() to create a Model instance.")
555
- U = model.U
556
- S = model.s
557
- V = model.V
558
- row_w = model.row_weights
559
- col_weights = model.column_weights
560
- mean = model.mean.values
561
- std = model.std.values
562
- prop = model.prop.values
563
- _modalities = model._modalities
564
- quanti = model.original_continuous
565
- quali = model.original_categorical
566
-
567
- # Construct the diagonal matrix of singular values
568
- Sigma = np.diag(S)
569
-
570
- # Reconstruct the weighted and scaled matrix Z
571
- Z = np.dot(U, np.dot(Sigma, V))
572
-
573
- # Undo the row and column weighting
574
- Z = Z / np.sqrt(row_w)[:, np.newaxis]
575
- Z = Z / np.sqrt(col_weights)
576
-
577
- # Split Z back into quantitative and qualitative parts
578
- n_quanti = len(quanti)
579
- df_quanti_scaled = Z[:, :n_quanti]
580
- df_quali_scaled = Z[:, n_quanti:]
581
-
582
- # Reverse the scaling for quantitative variables
583
- df_quanti = df_quanti_scaled * std + mean
584
-
585
- # Reverse the scaling for qualitative variables
586
- df_quali = df_quali_scaled * np.sqrt(prop) + prop
587
-
588
- # Combine quantitative and qualitative data
589
- df_quali = pd.DataFrame(df_quali, columns=_modalities)
590
- df_quanti = pd.DataFrame(df_quanti, columns=quanti)
591
- df_reconstructed = pd.concat([df_quanti, df_quali], axis=1)
592
-
593
- # Reverse the dummy encoding for categorical variables
594
- for var in quali:
595
- prefix = var + DUMMIES_SEPARATOR
596
- dummies = [col for col in df_reconstructed.columns if col.startswith(prefix)]
597
- df_reconstructed[var] = (
598
- df_reconstructed[dummies].idxmax(axis=1).apply(lambda x: x.split(DUMMIES_SEPARATOR)[1])
599
- )
600
- df_reconstructed.drop(columns=dummies, inplace=True)
601
-
602
- # Ensure the column order matches the original dataframe
603
- df_reconstructed = df_reconstructed[model.original_dtypes.index]
604
-
605
- # Identify the columns that need to be converted to integers
606
- int_columns = model.original_dtypes[model.original_dtypes == "int"].index.tolist()
607
-
608
- # Round the values before because astype(int) truncates the decimals
609
- df_reconstructed[int_columns] = df_reconstructed[int_columns].round()
610
-
611
- # Convert the data types to the original types
612
- df_reconstructed = df_reconstructed.astype(model.original_dtypes)
613
-
614
- 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)
@@ -15,8 +15,8 @@ from saiph.reduction.famd import (
15
15
  center,
16
16
  fit,
17
17
  fit_transform,
18
+ get_individual_coordinates,
18
19
  get_variable_contributions,
19
- reconstruct_df_from_model,
20
20
  scaler,
21
21
  transform,
22
22
  )
@@ -24,6 +24,7 @@ from saiph.reduction.pca import center as center_pca
24
24
  from saiph.reduction.pca import fit_transform as fit_pca
25
25
  from saiph.reduction.pca import scaler as scaler_pca
26
26
  from saiph.reduction.utils.common import get_projected_column_names
27
+ from saiph.reduction.utils.svd import get_svd
27
28
 
28
29
 
29
30
  def test_fit_mix(mixed_df2: pd.DataFrame) -> None:
@@ -47,14 +48,12 @@ def test_fit_mix(mixed_df2: pd.DataFrame) -> None:
47
48
  ]
48
49
  )
49
50
  expected_s: NDArray[np.float64] = np.array([1.224745e00, 0.0])
50
- expected_u: NDArray[np.float64] = np.array([[-1.0, 1.0], [1.0, 1.0]])
51
51
  expected_explained_var: NDArray[np.float64] = np.array([1.5, 0.0])
52
52
  expected_explained_var_ratio: NDArray[np.float64] = np.array([1.0, 0.0])
53
53
 
54
54
  assert_frame_equal(result, expected_result, check_exact=False, atol=0.01)
55
55
  assert_allclose(model.V, expected_v, atol=0.01)
56
56
  assert_allclose(model.s, expected_s, atol=0.01)
57
- assert_allclose(model.U, expected_u, atol=0.01)
58
57
  assert_allclose(model.explained_var, expected_explained_var, atol=0.01)
59
58
  (assert_allclose(model.explained_var_ratio, expected_explained_var_ratio, atol=0.01),)
60
59
  assert_allclose(model.variable_coord, model.V.T)
@@ -198,15 +197,20 @@ def test_get_variable_contributions(mixed_df: pd.DataFrame) -> None:
198
197
 
199
198
  expected_cos2 = pd.DataFrame.from_dict(
200
199
  data={
201
- "variable_1": [0.897214, 0.002786, 0],
202
- "tool": [0.897214, 0.002786, 0.25],
200
+ "variable_1": [0.897214, 0.002786],
201
+ "tool": [0.897214, 0.002786],
203
202
  },
204
203
  orient="index",
205
- columns=get_projected_column_names(3),
204
+ columns=get_projected_column_names(2),
206
205
  )
207
206
 
208
207
  assert_frame_equal(contributions, expected_contributions, check_exact=False, atol=0.0001)
209
- assert_frame_equal(cos2, expected_cos2, check_exact=False, atol=0.0001)
208
+ assert_frame_equal(cos2.iloc[:, :2], expected_cos2, check_exact=False, atol=0.0001)
209
+ # The third axis has a singular value of 2.7e-19, so every cos2 on it is built from
210
+ # floating-point dust. The continuous one has that value as a factor and stays
211
+ # negligible (1e-135); the categorical one divides one dust quadratic by another and
212
+ # lands anywhere in [0, 1], so there is nothing to assert about it.
213
+ assert cos2.loc["variable_1", "Dim. 3"] == pytest.approx(0, abs=1e-9)
210
214
 
211
215
 
212
216
  @pytest.mark.parametrize("col_weights", [[2.0, 3.0], None])
@@ -276,38 +280,6 @@ def test_get_variable_contributions_with_constant_variable() -> None:
276
280
  assert np.isfinite(contributions).all().all()
277
281
 
278
282
 
279
- def test_reconstructed_df_from_model_equals_df_minimal(mixed_df: pd.DataFrame) -> None:
280
- """Ensure that the reconstructed df from the model is equal to the original df."""
281
- df = mixed_df
282
- model = fit(df)
283
- reconstructed_df = reconstruct_df_from_model(model)
284
- # don't check dtypes, model don't know if numerical were int or float
285
- assert_frame_equal(df, reconstructed_df, check_dtype=False)
286
-
287
-
288
- def test_reconstructed_df_from_weighted_model_equals_df() -> None:
289
- """Ensure that the reconstructed df from the model is equal to the original df."""
290
- df = pd.read_csv("./fixtures/iris.csv")
291
- model = fit(df, col_weights=[3, 1, 1, 1, 1]) # type: ignore
292
- reconstructed_df = reconstruct_df_from_model(model)
293
- assert_frame_equal(df, reconstructed_df)
294
-
295
-
296
- # ---------------------------------------------------------------------------
297
- # Absent / novel modality tests
298
- # ---------------------------------------------------------------------------
299
- # These three tests collectively protect the behaviour of scaler() under the
300
- # conditions that actually occur in the avatar pipeline:
301
- #
302
- # • Privacy metrics fit on 50 % of rows, then transform the other 50 %
303
- # (→ holdout may be missing categories seen only in the training half).
304
- # • Avatar data is transformed with the original model after generation
305
- # (→ rare categories may be absent from the avatar batch).
306
- # • Cross-table linkage transforms a child table with a parent-table model
307
- # (→ child may have categories never seen in the parent).
308
- # ---------------------------------------------------------------------------
309
-
310
-
311
283
  def test_transform_famd_absent_categories_no_performance_warning() -> None:
312
284
  """FAMD (mixed continuous + categorical) must not emit PerformanceWarning
313
285
  when >100 categories are absent from the transform batch.
@@ -480,3 +452,56 @@ def test_scaler_encodes_bool_column_identically_to_str_column() -> None:
480
452
  unscale_dummies(model_bool, scaler(model_bool, df_bool)),
481
453
  unscale_dummies(model_str, scaler(model_str, df_str)),
482
454
  )
455
+
456
+
457
+ def test_fit_without_categorical_raises(quanti_df: pd.DataFrame) -> None:
458
+ with pytest.raises(ValueError, match="FAMD requires at least one categorical variable"):
459
+ fit(quanti_df)
460
+
461
+
462
+ def test_fit_with_null_categorical_value() -> None:
463
+ """A null takes no dummy column, so it must not lengthen the weight vector."""
464
+ df = pd.DataFrame(
465
+ {
466
+ "num": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
467
+ "cat": ["a", "b", "a", None, "b", "a"],
468
+ }
469
+ )
470
+ model = fit(df, nf=2, col_weights=np.array([2.0, 3.0]))
471
+
472
+ assert list(model.column_weights) == [2.0, 3.0, 3.0]
473
+ assert model.dummy_categorical == [f"cat{DUMMIES_SEPARATOR}a", f"cat{DUMMIES_SEPARATOR}b"]
474
+
475
+
476
+ def test_get_individual_coordinates_equals_the_left_singular_vectors() -> None:
477
+ """The rebuilt coordinates must be the ones the decomposition produced.
478
+
479
+ They are rebuilt from the scaled data rather than stored, because one row per
480
+ individual is the one part of a decomposition whose size grows with the table.
481
+ """
482
+ rng = np.random.default_rng(4)
483
+ n = 60
484
+ df = pd.DataFrame(
485
+ {
486
+ "num_1": rng.normal(size=n),
487
+ "num_2": rng.normal(size=n),
488
+ "tool": rng.choice(["a", "b", "c"], size=n),
489
+ "fruit": rng.choice(["x", "y"], size=n),
490
+ }
491
+ )
492
+ # nf below 0.8 * min(shape) would take the randomized path, whose U and V are
493
+ # an approximation and do not agree with each other to this tolerance.
494
+ nf = 7
495
+
496
+ for col_weights in (None, np.array([3.0, 1.0, 2.0, 1.0])):
497
+ model = fit(df, nf=nf, col_weights=col_weights)
498
+ assert model.s is not None
499
+
500
+ # What fit decomposes, and what it does to the left singular vectors after.
501
+ Z = (scaler(model, df) * model.column_weights).T.multiply(model.row_weights).T
502
+ U, S, _ = get_svd(Z, nf=nf)
503
+ expected = (U / np.sqrt(model.row_weights)[:, np.newaxis])[:, :nf] * S[:nf]
504
+
505
+ rebuilt = get_individual_coordinates(model, df, nf)
506
+
507
+ assert_allclose(rebuilt.to_numpy(), expected, atol=1e-14)