taxodist 0.3.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.
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: taxodist
3
+ Version: 0.3.0
4
+ Summary: Taxonomic Distance and Phylogenetic Lineage Computation
5
+ Author-email: Rodrigo Fonseca Villa <rodrigo03.villa@gmail.com>
6
+ License: GPL-3.0-or-later
7
+ Project-URL: Homepage, https://github.com/rodrigosqrt3/taxodist
8
+ Project-URL: Bug Tracker, https://github.com/rodrigosqrt3/taxodist/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ Requires-Dist: requests>=2.25.0
17
+ Requires-Dist: beautifulsoup4>=4.9.0
18
+ Requires-Dist: pandas>=1.2.0
19
+ Requires-Dist: numpy>=1.20.0
20
+ Requires-Dist: scipy>=1.6.0
21
+ Requires-Dist: matplotlib>=3.3.0
22
+ Requires-Dist: seaborn>=0.11.0
23
+ Requires-Dist: lxml>=4.9.0
24
+
25
+ # taxodist
26
+
27
+ [![PyPI version](https://badge.fury.io/py/taxodist.svg)](https://badge.fury.io/py/taxodist)
28
+ [![Python Tests](https://github.com/rodrigosqrt3/taxodist/actions/workflows/python-app.yml/badge.svg)](https://github.com/rodrigosqrt3/taxodist/actions/workflows/python-app.yml)
29
+ [![Coverage](https://app.codecov.io/gh/rodrigosqrt3/taxodist/branch/main/graph/badge.svg)](https://app.codecov.io/gh/rodrigosqrt3/taxodist)
30
+
31
+ **Taxonomic distance and phylogenetic lineage computation for any taxon on Earth.**
32
+
33
+ `taxodist` retrieves full hierarchical lineages from [The Taxonomicon](http://taxonomicon.taxonomy.nl) and computes a tree metric distance between any two taxa: a pair of dinosaurs, a dinosaur and a fungus, two species of fly, or an oak tree and a human.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install taxodist
39
+ ```
40
+ ```bash
41
+ pip install git+https://github.com/rodrigosqrt3/taxodist.git
42
+ ```
43
+
44
+ ## Basic usage
45
+
46
+ ```python
47
+ from taxodist import (
48
+ get_lineage, taxo_distance, mrca, distance_matrix,
49
+ filter_clade, taxo_path, save_cache, load_cache
50
+ )
51
+
52
+ # Get a full lineage
53
+ get_lineage("Tyrannosaurus")
54
+
55
+ # Distance between two taxa
56
+ taxo_distance("Tyrannosaurus", "Velociraptor")
57
+
58
+ # Most recent common ancestor
59
+ mrca("Tyrannosaurus", "Triceratops") # "Dinosauria"
60
+ mrca("Tyrannosaurus", "Homo") # "Amniota"
61
+
62
+ # Pairwise distance matrix
63
+ theropods = ["Tyrannosaurus", "Velociraptor", "Spinosaurus", "Allosaurus"]
64
+ distance_matrix(theropods)
65
+
66
+ # Filter taxa by clade
67
+ taxa =["Tyrannosaurus", "Triceratops", "Homo", "Quercus"]
68
+ filter_clade(taxa, "Dinosauria")
69
+
70
+ # Get the path between two taxa
71
+ taxo_path("Tyrannosaurus", "Velociraptor")
72
+
73
+ # Save and restore the lineage cache across sessions
74
+ save_cache("my_cache.pkl")
75
+ load_cache("my_cache.pkl")
76
+ ```
@@ -0,0 +1,52 @@
1
+ # taxodist
2
+
3
+ [![PyPI version](https://badge.fury.io/py/taxodist.svg)](https://badge.fury.io/py/taxodist)
4
+ [![Python Tests](https://github.com/rodrigosqrt3/taxodist/actions/workflows/python-app.yml/badge.svg)](https://github.com/rodrigosqrt3/taxodist/actions/workflows/python-app.yml)
5
+ [![Coverage](https://app.codecov.io/gh/rodrigosqrt3/taxodist/branch/main/graph/badge.svg)](https://app.codecov.io/gh/rodrigosqrt3/taxodist)
6
+
7
+ **Taxonomic distance and phylogenetic lineage computation for any taxon on Earth.**
8
+
9
+ `taxodist` retrieves full hierarchical lineages from [The Taxonomicon](http://taxonomicon.taxonomy.nl) and computes a tree metric distance between any two taxa: a pair of dinosaurs, a dinosaur and a fungus, two species of fly, or an oak tree and a human.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pip install taxodist
15
+ ```
16
+ ```bash
17
+ pip install git+https://github.com/rodrigosqrt3/taxodist.git
18
+ ```
19
+
20
+ ## Basic usage
21
+
22
+ ```python
23
+ from taxodist import (
24
+ get_lineage, taxo_distance, mrca, distance_matrix,
25
+ filter_clade, taxo_path, save_cache, load_cache
26
+ )
27
+
28
+ # Get a full lineage
29
+ get_lineage("Tyrannosaurus")
30
+
31
+ # Distance between two taxa
32
+ taxo_distance("Tyrannosaurus", "Velociraptor")
33
+
34
+ # Most recent common ancestor
35
+ mrca("Tyrannosaurus", "Triceratops") # "Dinosauria"
36
+ mrca("Tyrannosaurus", "Homo") # "Amniota"
37
+
38
+ # Pairwise distance matrix
39
+ theropods = ["Tyrannosaurus", "Velociraptor", "Spinosaurus", "Allosaurus"]
40
+ distance_matrix(theropods)
41
+
42
+ # Filter taxa by clade
43
+ taxa =["Tyrannosaurus", "Triceratops", "Homo", "Quercus"]
44
+ filter_clade(taxa, "Dinosauria")
45
+
46
+ # Get the path between two taxa
47
+ taxo_path("Tyrannosaurus", "Velociraptor")
48
+
49
+ # Save and restore the lineage cache across sessions
50
+ save_cache("my_cache.pkl")
51
+ load_cache("my_cache.pkl")
52
+ ```
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "taxodist"
7
+ version = "0.3.0"
8
+ authors =[
9
+ { name="Rodrigo Fonseca Villa", email="rodrigo03.villa@gmail.com" }
10
+ ]
11
+ description = "Taxonomic Distance and Phylogenetic Lineage Computation"
12
+ readme = "README.md"
13
+ requires-python = ">=3.8"
14
+ license = {text = "GPL-3.0-or-later"}
15
+ classifiers =[
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
18
+ "Operating System :: OS Independent",
19
+ "Intended Audience :: Science/Research",
20
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
21
+ ]
22
+ dependencies =[
23
+ "requests>=2.25.0",
24
+ "beautifulsoup4>=4.9.0",
25
+ "pandas>=1.2.0",
26
+ "numpy>=1.20.0",
27
+ "scipy>=1.6.0",
28
+ "matplotlib>=3.3.0",
29
+ "seaborn>=0.11.0",
30
+ "lxml>=4.9.0"
31
+ ]
32
+
33
+ [project.urls]
34
+ "Homepage" = "https://github.com/rodrigosqrt3/taxodist"
35
+ "Bug Tracker" = "https://github.com/rodrigosqrt3/taxodist/issues"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,66 @@
1
+ """
2
+ taxodist: Taxonomic Distance and Phylogenetic Lineage Computation
3
+
4
+ taxodist computes phylogenetic distances between any two taxa using
5
+ hierarchical lineage data retrieved from The Taxonomicon
6
+ (taxonomy.nl), a comprehensive curated classification of all life
7
+ based on Systema Naturae 2000.
8
+
9
+ Core functions
10
+ --------------
11
+ - get_lineage() — retrieve the full lineage of any taxon
12
+ - taxo_distance() — compute the tree metric distance between two taxa
13
+ - mrca() — find the most recent common ancestor
14
+ - distance_matrix() — compute all pairwise distances for a set of taxa
15
+ - closest_relative() — find the closest relative among candidates
16
+ - compare_lineages() — print a side-by-side lineage comparison
17
+ - shared_clades() — list clades shared between two taxa
18
+ - is_member() — test clade membership
19
+ - filter_clade() — filter taxa by clade membership
20
+ - check_coverage() — check Taxonomicon coverage for a list of taxa
21
+ - lineage_depth() — get the lineage depth of a taxon
22
+ - clear_cache() — clear the session lineage cache
23
+
24
+ Mathematical background
25
+ -----------------------
26
+ The distance metric is based on the depth of the most recent common
27
+ ancestor (MRCA):
28
+
29
+ d(A, B) = 1 / depth(MRCA(A, B))
30
+
31
+ The deeper the shared ancestor, the smaller the distance. This metric
32
+ ensures that taxa sharing the same MRCA are always equidistant from any
33
+ third taxon, regardless of lineage depth below the split — a key
34
+ biological correctness property absent from Jaccard-based approaches.
35
+
36
+ Data source
37
+ -----------
38
+ All lineage data is sourced from The Taxonomicon (taxonomy.nl), based on
39
+ Systema Naturae 2000 by S.J. Brands (1989 onwards). Please cite this
40
+ resource when using taxodist in published work.
41
+
42
+ References
43
+ ----------
44
+ Brands, S.J. (1989 onwards). Systema Naturae 2000. Amsterdam,
45
+ The Netherlands. Retrieved from The Taxonomicon,
46
+ http://taxonomicon.taxonomy.nl.
47
+ """
48
+
49
+ __version__ = "0.3.0"
50
+
51
+ from .fetch import (
52
+ clear_cache, save_cache, load_cache,
53
+ get_taxonomicon_id, get_lineage_by_id, get_lineage, taxo_search
54
+ )
55
+
56
+ from .distance import (
57
+ taxo_distance, mrca, distance_matrix, closest_relative,
58
+ lineage_depth, check_coverage, taxo_cluster, taxo_ordinate
59
+ )
60
+
61
+ from .utils import (
62
+ compare_lineages, shared_clades, is_member, filter_clade,
63
+ taxo_heatmap, taxo_path,
64
+ print_taxodist_result, plot_taxodist_cluster, plot_taxodist_ord,
65
+ summary_taxodist_ord, print_taxodist_path
66
+ )
@@ -0,0 +1,385 @@
1
+ import math
2
+ import warnings
3
+ import numpy as np
4
+ import pandas as pd
5
+ from scipy.cluster.hierarchy import linkage
6
+ from scipy.spatial.distance import squareform
7
+
8
+ from .fetch import get_lineage, get_taxonomicon_id
9
+
10
+ def _compute_distance(lin_a, lin_b, name_a="A", name_b="B"):
11
+ """
12
+ Internal helper to compute distance between two parsed lineages.
13
+ Equivalent to the hidden .compute_distance in R.
14
+ """
15
+ depth_a = len(lin_a)
16
+ depth_b = len(lin_b)
17
+
18
+ shared =[]
19
+ set_b = set(lin_b)
20
+ for x in lin_a:
21
+ if x in set_b and x not in shared:
22
+ shared.append(x)
23
+
24
+ if not shared:
25
+ return {
26
+ "distance": float('inf'),
27
+ "mrca": None,
28
+ "mrca_depth": 0,
29
+ "depth_a": depth_a,
30
+ "depth_b": depth_b,
31
+ "taxon_a": name_a,
32
+ "taxon_b": name_b
33
+ }
34
+
35
+ positions_in_a =[lin_a.index(x) + 1 for x in shared]
36
+ mrca_idx = positions_in_a.index(max(positions_in_a))
37
+ mrca_depth = positions_in_a[mrca_idx]
38
+
39
+ mrca_name = lin_a[mrca_depth - 1]
40
+
41
+ is_ancestral = (mrca_name == lin_a[-1]) or (mrca_name == lin_b[-1]) or (name_a in lin_b) or (name_b in lin_a)
42
+ distance = 0.0 if is_ancestral else 1.0 / mrca_depth
43
+
44
+ return {
45
+ "distance": distance,
46
+ "mrca": mrca_name,
47
+ "mrca_depth": mrca_depth,
48
+ "depth_a": depth_a,
49
+ "depth_b": depth_b,
50
+ "taxon_a": name_a,
51
+ "taxon_b": name_b
52
+ }
53
+
54
+
55
+ def taxo_distance(taxon_a, taxon_b, verbose=False):
56
+ """
57
+ Compute the phylogenetic distance between two taxa
58
+
59
+ Given two taxon names, retrieves their lineages from The Taxonomicon and
60
+ computes a taxonomic distance based on the depth of their most recent
61
+ common ancestor (MRCA):
62
+
63
+ d(A, B) = 1 / depth(MRCA(A, B))
64
+
65
+ The deeper the shared ancestor, the smaller (closer to zero) the distance.
66
+ This metric ensures that taxa diverging at the same node are always
67
+ equidistant from any third taxon, regardless of lineage depth differences
68
+ below the split.
69
+
70
+ Parameters
71
+ ----------
72
+ taxon_a : str
73
+ A character string giving the first taxon name.
74
+ taxon_b : str
75
+ A character string giving the second taxon name.
76
+ verbose : bool
77
+ Logical. If True, prints progress messages. Default False.
78
+
79
+ Returns
80
+ -------
81
+ dict or None
82
+ A dictionary with the following elements:
83
+ - distance: Numeric. The distance between the two taxa. Returns 0
84
+ if one taxon is an ancestor of the other.
85
+ - mrca: Character. The name of the most recent common ancestor.
86
+ - mrca_depth: Integer. The depth of the MRCA node.
87
+ - depth_a: Integer. The lineage depth of taxon A.
88
+ - depth_b: Integer. The lineage depth of taxon B.
89
+ - taxon_a: Character. Name of the first taxon.
90
+ - taxon_b: Character. Name of the second taxon.
91
+ Returns None if either taxon cannot be found.
92
+ """
93
+ lin_a = get_lineage(taxon_a, verbose=verbose)
94
+ lin_b = get_lineage(taxon_b, verbose=verbose)
95
+
96
+ if lin_a is None:
97
+ print(f"Error: Could not retrieve lineage for {taxon_a}")
98
+ return None
99
+ if lin_b is None:
100
+ print(f"Error: Could not retrieve lineage for {taxon_b}")
101
+ return None
102
+
103
+ return _compute_distance(lin_a, lin_b, taxon_a, taxon_b)
104
+
105
+
106
+ def mrca(taxon_a, taxon_b, verbose=False):
107
+ """
108
+ Compute the most recent common ancestor of two taxa
109
+
110
+ Retrieves the lineages of two taxa and returns the name of their most
111
+ recent common ancestor (MRCA) — the deepest node shared by both lineages.
112
+
113
+ Parameters
114
+ ----------
115
+ taxon_a : str
116
+ A character string giving the first taxon name.
117
+ taxon_b : str
118
+ A character string giving the second taxon name.
119
+ verbose : bool
120
+ Logical. If True, prints progress messages. Default False.
121
+
122
+ Returns
123
+ -------
124
+ str or None
125
+ A character string giving the name of the MRCA, or None if
126
+ either taxon cannot be found or no common ancestor exists.
127
+ """
128
+ result = taxo_distance(taxon_a, taxon_b, verbose=verbose)
129
+ if result is None:
130
+ return None
131
+ return result["mrca"]
132
+
133
+ def distance_matrix(taxa, verbose=False, progress=True):
134
+ """
135
+ Compute pairwise taxonomic distances for a set of taxa
136
+
137
+ Given a list of taxon names, computes all pairwise phylogenetic distances
138
+ and returns a symmetric distance matrix. Lineages are cached after first
139
+ retrieval to minimise redundant network requests.
140
+
141
+ Parameters
142
+ ----------
143
+ taxa : list of str
144
+ A list of taxon names.
145
+ verbose : bool
146
+ Logical. If True, prints progress for each pair. Default False.
147
+ progress : bool
148
+ Logical. If True, shows progress status. Default True.
149
+
150
+ Returns
151
+ -------
152
+ pandas.DataFrame
153
+ A symmetric numeric DataFrame containing pairwise distances.
154
+ Row and column names are set to the input taxon names.
155
+ Taxa that could not be found are included with NaN distances.
156
+ """
157
+ n = len(taxa)
158
+ mat = np.full((n, n), np.nan)
159
+ np.fill_diagonal(mat, 0.0)
160
+
161
+ if progress:
162
+ print(f"Fetching {n} lineages...")
163
+
164
+ lineages =[get_lineage(t, verbose=verbose) for t in taxa]
165
+
166
+ if progress:
167
+ print("Lineages fetched.")
168
+ total_pairs = int(n * (n - 1) / 2)
169
+ print(f"Computing distances for {total_pairs} pairs...")
170
+
171
+ for i in range(n - 1):
172
+ for j in range(i + 1, n):
173
+ if lineages[i] is not None and lineages[j] is not None:
174
+ result = _compute_distance(lineages[i], lineages[j], taxa[i], taxa[j])
175
+ mat[i, j] = result["distance"]
176
+ mat[j, i] = result["distance"]
177
+
178
+ if progress:
179
+ print("Done.")
180
+
181
+ return pd.DataFrame(mat, index=taxa, columns=taxa)
182
+
183
+
184
+ def closest_relative(taxon, candidates, verbose=False):
185
+ """
186
+ Find the closest relative of a taxon among a set of candidates
187
+
188
+ Given a query taxon and a list of candidate taxa, returns the candidate
189
+ with the smallest phylogenetic distance to the query.
190
+
191
+ Parameters
192
+ ----------
193
+ taxon : str
194
+ A character string giving the query taxon name.
195
+ candidates : list of str
196
+ A list of candidate taxon names to compare against.
197
+ verbose : bool
198
+ Logical. If True, prints progress messages. Default False.
199
+
200
+ Returns
201
+ -------
202
+ pandas.DataFrame or None
203
+ A DataFrame with columns 'taxon' (candidate name) and 'distance'
204
+ (tree metric distance), sorted by distance ascending. Returns None if
205
+ the query taxon cannot be found.
206
+ """
207
+ query_lin = get_lineage(taxon, verbose=verbose)
208
+ if query_lin is None:
209
+ print(f"Error: Could not retrieve lineage for {taxon}")
210
+ return None
211
+
212
+ results =[]
213
+ for cand in candidates:
214
+ cand_lin = get_lineage(cand, verbose=verbose)
215
+ if cand_lin is None:
216
+ results.append({"taxon": cand, "distance": float('nan')})
217
+ else:
218
+ dist_result = _compute_distance(query_lin, cand_lin, taxon, cand)
219
+ results.append({"taxon": cand, "distance": dist_result["distance"]})
220
+
221
+ df = pd.DataFrame(results)
222
+ return df.sort_values(by="distance", na_position='last').reset_index(drop=True)
223
+
224
+
225
+ def lineage_depth(taxon, verbose=False):
226
+ """
227
+ Get the lineage depth of a taxon
228
+
229
+ Returns the number of nodes in the lineage of a taxon, from root to tip.
230
+ This reflects how deeply nested the taxon is within the taxonomic hierarchy.
231
+
232
+ Parameters
233
+ ----------
234
+ taxon : str
235
+ A character string giving the taxon name.
236
+ verbose : bool
237
+ Logical. If True, prints progress messages. Default False.
238
+
239
+ Returns
240
+ -------
241
+ int or None
242
+ An integer giving the lineage depth, or None if the taxon cannot
243
+ be found.
244
+ """
245
+ lin = get_lineage(taxon, verbose=verbose)
246
+ if lin is None:
247
+ return None
248
+ return len(lin)
249
+
250
+ def check_coverage(taxa, verbose=False):
251
+ """
252
+ Check whether a taxon is covered by The Taxonomicon
253
+
254
+ Queries The Taxonomicon for a taxon name and returns a boolean Series indicating
255
+ whether the taxon was found. Useful for pre-screening a list of names
256
+ before running distance computations.
257
+
258
+ Parameters
259
+ ----------
260
+ taxa : list of str
261
+ A list of one or more taxon names.
262
+ verbose : bool
263
+ Logical. If True, prints progress messages. Default False.
264
+
265
+ Returns
266
+ -------
267
+ pandas.Series
268
+ A boolean Series indexed by taxon names. True indicates the taxon was found,
269
+ False indicates it was not.
270
+ """
271
+ result = {}
272
+ for t in taxa:
273
+ res = get_taxonomicon_id(t, verbose=verbose)
274
+ result[t] = res is not None
275
+
276
+ return pd.Series(result)
277
+
278
+
279
+ def taxo_cluster(taxa, method="average", **kwargs):
280
+ """
281
+ Cluster taxa by taxonomic distance
282
+
283
+ Computes pairwise taxonomic distances and performs hierarchical clustering.
284
+
285
+ Parameters
286
+ ----------
287
+ taxa : list of str or pandas.DataFrame
288
+ A list of taxon names, or a distance matrix DataFrame from distance_matrix().
289
+ method : str
290
+ Clustering method. Default "average" (UPGMA), which works well
291
+ with taxonomic distances.
292
+ verbose : bool
293
+ Logical. If True, prints progress messages. Default False.
294
+ progress : bool
295
+ Logical. If True, shows progress status. Default True.
296
+
297
+ Returns
298
+ -------
299
+ dict
300
+ A dictionary with:
301
+ - hclust: The hierarchical clustering linkage matrix (SciPy format).
302
+ - dist: The underlying distance matrix DataFrame.
303
+ """
304
+ if isinstance(taxa, pd.DataFrame):
305
+ d = taxa
306
+ else:
307
+ d = distance_matrix(taxa, **kwargs)
308
+
309
+ if np.isnan(d.values).any():
310
+ warnings.warn("Distance matrix contains NaN values (taxa not found or server offline). Clustering skipped.")
311
+ return {"hclust": None, "dist": d}
312
+
313
+ condensed_dist = squareform(d.values, checks=False)
314
+ hc = linkage(condensed_dist, method=method)
315
+
316
+ return {"hclust": hc, "dist": d}
317
+
318
+ def taxo_ordinate(taxa, k=2, **kwargs):
319
+ """
320
+ Ordinate taxa in taxonomic distance space
321
+
322
+ Computes pairwise taxonomic distances and applies classical multidimensional
323
+ scaling (PCoA) to project taxa into a low-dimensional space.
324
+
325
+ Parameters
326
+ ----------
327
+ taxa : list of str or pandas.DataFrame
328
+ A list of taxon names, or a distance matrix DataFrame from distance_matrix().
329
+ k : int
330
+ Number of dimensions. Default 2.
331
+ verbose : bool
332
+ Logical. If True, prints progress messages. Default False.
333
+ progress : bool
334
+ Logical. If True, shows progress status. Default True.
335
+
336
+ Returns
337
+ -------
338
+ dict
339
+ A dictionary with:
340
+ - points: A DataFrame of coordinates (taxa x k dimensions).
341
+ - dist: The underlying distance matrix DataFrame.
342
+ - GOF: Goodness-of-fit (matches R's cmdscale GOF).
343
+ - eig: The eigenvalues computed during PCoA.
344
+ """
345
+ if isinstance(taxa, pd.DataFrame):
346
+ d = taxa
347
+ else:
348
+ d = distance_matrix(taxa, **kwargs)
349
+
350
+ if np.isnan(d.values).any():
351
+ warnings.warn("Distance matrix contains NaN values. Ordination skipped.")
352
+ return {"points": None, "dist": d, "GOF": None, "eig": None}
353
+
354
+ mat = d.values
355
+ n = mat.shape[0]
356
+
357
+ A = -0.5 * (mat ** 2)
358
+ J = np.eye(n) - np.ones((n, n)) / n
359
+ B = J.dot(A).dot(J)
360
+
361
+ eigvals, eigvecs = np.linalg.eigh(B)
362
+
363
+ idx = np.argsort(eigvals)[::-1]
364
+ eigvals = eigvals[idx]
365
+ eigvecs = eigvecs[:, idx]
366
+
367
+ eigvals_k = np.maximum(eigvals[:k], 0)
368
+ points = eigvecs[:, :k] * np.sqrt(eigvals_k)
369
+
370
+ eig_pos = np.maximum(eigvals, 0)
371
+ gof_1 = np.sum(eigvals_k) / np.sum(eig_pos) if np.sum(eig_pos) > 0 else 0
372
+ gof_2 = np.sum(eigvals_k) / np.sum(np.abs(eigvals)) if np.sum(np.abs(eigvals)) > 0 else 0
373
+
374
+ points_df = pd.DataFrame(
375
+ points,
376
+ index=d.index,
377
+ columns=[f"PC{i+1}" for i in range(k)]
378
+ )
379
+
380
+ return {
381
+ "points": points_df,
382
+ "dist": d,
383
+ "GOF": [gof_1, gof_2],
384
+ "eig": eigvals
385
+ }