conceptflow 0.3.0__tar.gz → 0.3.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 (111) hide show
  1. {conceptflow-0.3.0/src/conceptflow.egg-info → conceptflow-0.3.1}/PKG-INFO +20 -14
  2. {conceptflow-0.3.0 → conceptflow-0.3.1}/README.md +18 -13
  3. {conceptflow-0.3.0 → conceptflow-0.3.1}/pyproject.toml +1 -0
  4. conceptflow-0.3.1/src/conceptflow/_version.py +1 -0
  5. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/algorithms/_registry.py +1 -1
  6. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/algorithms/implications.py +10 -3
  7. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/core/context.py +31 -4
  8. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/core/incomplete_context.py +12 -3
  9. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/core/lattice.py +15 -0
  10. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/core/many_valued_context.py +13 -0
  11. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/decomposition/ordinal_factorization.py +75 -102
  12. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/feature_extraction/concept_encoder.py +2 -0
  13. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/io/cxt.py +24 -1
  14. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/io/formats.py +14 -5
  15. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/metrics/measures.py +1 -1
  16. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/metrics/rules.py +11 -4
  17. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/preprocessing/conceptual_scaler.py +13 -0
  18. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/preprocessing/scales.py +21 -18
  19. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/rules/implication_basis.py +15 -2
  20. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/validation/input.py +16 -1
  21. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/visualization/d3_backend.py +26 -13
  22. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/visualization/dimflux_layout.py +8 -1
  23. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/visualization/graph_data.py +31 -0
  24. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/visualization/graphviz.py +8 -31
  25. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/visualization/html_figure.py +9 -0
  26. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/visualization/nested.py +15 -9
  27. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/visualization/static.py +15 -2
  28. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/visualization/tikz.py +10 -3
  29. {conceptflow-0.3.0 → conceptflow-0.3.1/src/conceptflow.egg-info}/PKG-INFO +20 -14
  30. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow.egg-info/SOURCES.txt +1 -0
  31. conceptflow-0.3.1/tests/test_patch_0_3_1.py +287 -0
  32. conceptflow-0.3.0/src/conceptflow/_version.py +0 -1
  33. {conceptflow-0.3.0 → conceptflow-0.3.1}/LICENSE +0 -0
  34. {conceptflow-0.3.0 → conceptflow-0.3.1}/setup.cfg +0 -0
  35. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/__init__.py +0 -0
  36. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/algorithms/__init__.py +0 -0
  37. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/algorithms/_bitset.py +0 -0
  38. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/algorithms/_membership.py +0 -0
  39. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/algorithms/derivation.py +0 -0
  40. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/algorithms/enumeration.py +0 -0
  41. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/algorithms/generators.py +0 -0
  42. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/algorithms/hasse.py +0 -0
  43. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/algorithms/order.py +0 -0
  44. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/algorithms/reduction.py +0 -0
  45. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/cluster/__init__.py +0 -0
  46. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/cluster/concept_lattice.py +0 -0
  47. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/core/__init__.py +0 -0
  48. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/core/concept.py +0 -0
  49. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/core/operations.py +0 -0
  50. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/decomposition/__init__.py +0 -0
  51. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/exploration/__init__.py +0 -0
  52. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/exploration/builder.py +0 -0
  53. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/exploration/combinations.py +0 -0
  54. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/exploration/view.py +0 -0
  55. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/feature_extraction/__init__.py +0 -0
  56. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/io/__init__.py +0 -0
  57. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/metrics/__init__.py +0 -0
  58. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/model_selection/__init__.py +0 -0
  59. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/preprocessing/__init__.py +0 -0
  60. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/quality.py +0 -0
  61. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/rules/__init__.py +0 -0
  62. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/rules/outlier_detector.py +0 -0
  63. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/validation/__init__.py +0 -0
  64. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/visualization/__init__.py +0 -0
  65. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/visualization/lattice_plot.py +0 -0
  66. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow/visualization/layered_layout.py +0 -0
  67. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow.egg-info/dependency_links.txt +0 -0
  68. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow.egg-info/requires.txt +0 -0
  69. {conceptflow-0.3.0 → conceptflow-0.3.1}/src/conceptflow.egg-info/top_level.txt +0 -0
  70. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_algorithm_registry.py +0 -0
  71. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_audit_regressions.py +0 -0
  72. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_check_estimator.py +0 -0
  73. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_cluster_estimator.py +0 -0
  74. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_concept.py +0 -0
  75. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_concept_encoder.py +0 -0
  76. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_conceptual_scaler.py +0 -0
  77. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_context_handling.py +0 -0
  78. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_context_operations.py +0 -0
  79. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_cxt_io.py +0 -0
  80. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_d3_backend.py +0 -0
  81. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_derivation.py +0 -0
  82. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_dimflux_layout.py +0 -0
  83. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_docs_examples.py +0 -0
  84. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_enumeration.py +0 -0
  85. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_exploration.py +0 -0
  86. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_formal_context.py +0 -0
  87. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_generators.py +0 -0
  88. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_graph_data.py +0 -0
  89. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_hasse.py +0 -0
  90. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_html_figure.py +0 -0
  91. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_implication_basis_estimator.py +0 -0
  92. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_implications.py +0 -0
  93. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_incomplete_context.py +0 -0
  94. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_lattice.py +0 -0
  95. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_lattice_navigation.py +0 -0
  96. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_layout_and_graphviz.py +0 -0
  97. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_many_valued_context.py +0 -0
  98. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_measures.py +0 -0
  99. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_metrics.py +0 -0
  100. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_nested_combinations.py +0 -0
  101. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_nested_visualization.py +0 -0
  102. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_ordinal_factorization.py +0 -0
  103. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_public_api.py +0 -0
  104. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_quality.py +0 -0
  105. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_reduction.py +0 -0
  106. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_review_fixes.py +0 -0
  107. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_scales.py +0 -0
  108. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_sklearn_compatibility.py +0 -0
  109. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_static_figures.py +0 -0
  110. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_tikz.py +0 -0
  111. {conceptflow-0.3.0 → conceptflow-0.3.1}/tests/test_validation_input.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: conceptflow
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Summary: A scikit-learn compatible Formal Concept Analysis framework.
5
5
  Author-email: Anurag Sharma <sharma@cs.uni-kassel.de>
6
6
  License: BSD 3-Clause License
@@ -33,6 +33,7 @@ License: BSD 3-Clause License
33
33
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34
34
 
35
35
  Project-URL: Homepage, https://github.com/anuragxorma/conceptflow
36
+ Project-URL: Documentation, https://conceptflow.readthedocs.io
36
37
  Project-URL: Repository, https://github.com/anuragxorma/conceptflow
37
38
  Project-URL: Issues, https://github.com/anuragxorma/conceptflow/issues
38
39
  Keywords: formal-concept-analysis,fca,scikit-learn,concept-lattice,conceptual-scaling
@@ -68,6 +69,7 @@ Dynamic: license-file
68
69
 
69
70
  ![Python](https://img.shields.io/badge/python-3.12%2B-blue)
70
71
  ![License](https://img.shields.io/badge/license-BSD--3--Clause-green)
72
+ [![Documentation](https://readthedocs.org/projects/conceptflow/badge/?version=latest)](https://conceptflow.readthedocs.io)
71
73
  ![Status](https://img.shields.io/badge/status-experimental-orange)
72
74
 
73
75
  ConceptFlow is a Python library for **Formal Concept Analysis (FCA)** that
@@ -131,19 +133,23 @@ cf.plot_lattice(lattice, backend="tikz", layout="layered").write("lattice.pdf")
131
133
 
132
134
  ## Documentation
133
135
 
134
- The documentation lives in [`docs/`](https://github.com/anuragxorma/conceptflow/blob/main/docs/index.md):
135
-
136
- - [Getting started](https://github.com/anuragxorma/conceptflow/blob/main/docs/getting-started.md)
137
- - User guide: [contexts](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/contexts.md),
138
- [lattices](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/lattices.md),
139
- [implications](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/rules.md),
140
- [measures](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/measures.md),
141
- [scaling](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/scaling.md),
142
- [scikit-learn](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/sklearn.md),
143
- [visualization](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/visualization.md),
144
- [nested diagrams](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/nested.md),
145
- [data quality](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/quality.md)
146
- - [Changelog](https://github.com/anuragxorma/conceptflow/blob/main/CHANGELOG.md)
136
+ The documentation is at **[conceptflow.readthedocs.io](https://conceptflow.readthedocs.io)**:
137
+
138
+ - [Getting started](https://conceptflow.readthedocs.io/en/latest/getting-started/)
139
+ - User guide: [contexts](https://conceptflow.readthedocs.io/en/latest/guide/contexts/),
140
+ [lattices](https://conceptflow.readthedocs.io/en/latest/guide/lattices/),
141
+ [implications](https://conceptflow.readthedocs.io/en/latest/guide/rules/),
142
+ [measures](https://conceptflow.readthedocs.io/en/latest/guide/measures/),
143
+ [scaling](https://conceptflow.readthedocs.io/en/latest/guide/scaling/),
144
+ [scikit-learn](https://conceptflow.readthedocs.io/en/latest/guide/sklearn/),
145
+ [visualization](https://conceptflow.readthedocs.io/en/latest/guide/visualization/),
146
+ [nested diagrams](https://conceptflow.readthedocs.io/en/latest/guide/nested/),
147
+ [data quality](https://conceptflow.readthedocs.io/en/latest/guide/quality/),
148
+ [ordinal factorization](https://conceptflow.readthedocs.io/en/latest/guide/decomposition/)
149
+ - [API reference](https://conceptflow.readthedocs.io/en/latest/api/core/)
150
+ - [Changelog](https://conceptflow.readthedocs.io/en/latest/changelog/)
151
+
152
+ The sources are in [`docs/`](https://github.com/anuragxorma/conceptflow/tree/main/docs).
147
153
 
148
154
  To build the documentation site locally (with the API reference):
149
155
 
@@ -2,6 +2,7 @@
2
2
 
3
3
  ![Python](https://img.shields.io/badge/python-3.12%2B-blue)
4
4
  ![License](https://img.shields.io/badge/license-BSD--3--Clause-green)
5
+ [![Documentation](https://readthedocs.org/projects/conceptflow/badge/?version=latest)](https://conceptflow.readthedocs.io)
5
6
  ![Status](https://img.shields.io/badge/status-experimental-orange)
6
7
 
7
8
  ConceptFlow is a Python library for **Formal Concept Analysis (FCA)** that
@@ -65,19 +66,23 @@ cf.plot_lattice(lattice, backend="tikz", layout="layered").write("lattice.pdf")
65
66
 
66
67
  ## Documentation
67
68
 
68
- The documentation lives in [`docs/`](https://github.com/anuragxorma/conceptflow/blob/main/docs/index.md):
69
-
70
- - [Getting started](https://github.com/anuragxorma/conceptflow/blob/main/docs/getting-started.md)
71
- - User guide: [contexts](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/contexts.md),
72
- [lattices](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/lattices.md),
73
- [implications](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/rules.md),
74
- [measures](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/measures.md),
75
- [scaling](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/scaling.md),
76
- [scikit-learn](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/sklearn.md),
77
- [visualization](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/visualization.md),
78
- [nested diagrams](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/nested.md),
79
- [data quality](https://github.com/anuragxorma/conceptflow/blob/main/docs/guide/quality.md)
80
- - [Changelog](https://github.com/anuragxorma/conceptflow/blob/main/CHANGELOG.md)
69
+ The documentation is at **[conceptflow.readthedocs.io](https://conceptflow.readthedocs.io)**:
70
+
71
+ - [Getting started](https://conceptflow.readthedocs.io/en/latest/getting-started/)
72
+ - User guide: [contexts](https://conceptflow.readthedocs.io/en/latest/guide/contexts/),
73
+ [lattices](https://conceptflow.readthedocs.io/en/latest/guide/lattices/),
74
+ [implications](https://conceptflow.readthedocs.io/en/latest/guide/rules/),
75
+ [measures](https://conceptflow.readthedocs.io/en/latest/guide/measures/),
76
+ [scaling](https://conceptflow.readthedocs.io/en/latest/guide/scaling/),
77
+ [scikit-learn](https://conceptflow.readthedocs.io/en/latest/guide/sklearn/),
78
+ [visualization](https://conceptflow.readthedocs.io/en/latest/guide/visualization/),
79
+ [nested diagrams](https://conceptflow.readthedocs.io/en/latest/guide/nested/),
80
+ [data quality](https://conceptflow.readthedocs.io/en/latest/guide/quality/),
81
+ [ordinal factorization](https://conceptflow.readthedocs.io/en/latest/guide/decomposition/)
82
+ - [API reference](https://conceptflow.readthedocs.io/en/latest/api/core/)
83
+ - [Changelog](https://conceptflow.readthedocs.io/en/latest/changelog/)
84
+
85
+ The sources are in [`docs/`](https://github.com/anuragxorma/conceptflow/tree/main/docs).
81
86
 
82
87
  To build the documentation site locally (with the API reference):
83
88
 
@@ -56,6 +56,7 @@ dev = [
56
56
 
57
57
  [project.urls]
58
58
  Homepage = "https://github.com/anuragxorma/conceptflow"
59
+ Documentation = "https://conceptflow.readthedocs.io"
59
60
  Repository = "https://github.com/anuragxorma/conceptflow"
60
61
  Issues = "https://github.com/anuragxorma/conceptflow/issues"
61
62
 
@@ -0,0 +1 @@
1
+ __version__ = "0.3.1"
@@ -46,7 +46,7 @@ def normalize_enumeration_algorithm(name: str) -> str:
46
46
  ValueError
47
47
  If the algorithm is unknown.
48
48
  """
49
- normalized = name.lower().strip().replace(" ", "_")
49
+ normalized = name.lower().strip().replace(" ", "_") if isinstance(name, str) else None
50
50
 
51
51
  if normalized not in ENUMERATION_ALGORITHM_ALIASES:
52
52
  supported = ", ".join(sorted(SUPPORTED_ENUMERATION_ALGORITHMS))
@@ -429,7 +429,10 @@ def _resolve_min_support(min_support: int | float, n_objects: int) -> int:
429
429
  if not isinstance(min_support, numbers.Integral):
430
430
  # str() gives the shortest decimal for NumPy floats too, so
431
431
  # np.float32(0.1) counts as 0.1 rather than 0.10000000149.
432
- min_support = float(str(min_support))
432
+ try:
433
+ min_support = float(str(min_support))
434
+ except ValueError: # e.g. Fraction(1, 2), whose str() is "1/2"
435
+ min_support = float(min_support)
433
436
  if not 0.0 <= min_support <= 1.0:
434
437
  raise ValueError("A fractional min_support must lie in [0, 1].")
435
438
  # Rounding keeps e.g. 0.1 * 30 == 3.0000000000000004 from rounding up to 4.
@@ -486,8 +489,12 @@ def compute_luxenburger_basis(
486
489
  from conceptflow.algorithms._bitset import from_indices
487
490
  from conceptflow.algorithms.enumeration import _closebyone_bitsets, _intent_of
488
491
 
489
- if not 0.0 <= min_confidence <= 1.0:
490
- raise ValueError("min_confidence must lie in [0, 1].")
492
+ if (
493
+ isinstance(min_confidence, bool)
494
+ or not isinstance(min_confidence, numbers.Real)
495
+ or not 0.0 <= min_confidence <= 1.0
496
+ ):
497
+ raise ValueError("min_confidence must be a number in [0, 1].")
491
498
 
492
499
  support_threshold = _resolve_min_support(min_support, context.n_objects)
493
500
  bits = BitsetContext(context)
@@ -23,6 +23,7 @@ from typing import Iterable
23
23
 
24
24
  import numpy as np
25
25
  import pandas as pd
26
+ import scipy.sparse
26
27
 
27
28
 
28
29
  def _is_index(value) -> bool:
@@ -81,6 +82,8 @@ def _cross_table(data) -> np.ndarray:
81
82
  "no") raises instead of being guessed; "?" (unknown) points to
82
83
  IncompleteContext.
83
84
  """
85
+ if scipy.sparse.issparse(data):
86
+ data = data.toarray()
84
87
  raw = np.asarray(data)
85
88
 
86
89
  if raw.dtype == bool:
@@ -95,6 +98,22 @@ def _cross_table(data) -> np.ndarray:
95
98
  return np.array(cells, dtype=bool).reshape(raw.shape)
96
99
 
97
100
 
101
+ def _new_cells(data, shape: tuple[int, int], argument: str, kind: str) -> np.ndarray:
102
+ """Cross table for add_objects/add_attributes, which must have exactly ``shape``."""
103
+ cells = _cross_table(data)
104
+ if cells.size == 0 and 0 in shape:
105
+ return np.zeros(shape, dtype=bool)
106
+ if cells.ndim == 1 and cells.size == shape[0] * shape[1] and 1 in shape:
107
+ # A single new object (or attribute) may be given as a flat list.
108
+ cells = cells.reshape(shape)
109
+ if cells.shape != shape:
110
+ raise ValueError(
111
+ f"{argument} has shape {cells.shape}, but expected {shape} "
112
+ f"(one {'row per new object' if kind == 'object' else 'column per new attribute'})."
113
+ )
114
+ return cells
115
+
116
+
98
117
  @dataclass(frozen=True)
99
118
  class FormalContext:
100
119
  """
@@ -143,6 +162,9 @@ class FormalContext:
143
162
  f"{incidence.shape}, but expected {expected_shape}."
144
163
  )
145
164
 
165
+ # Read-only, so the context cannot change after creation (its hash
166
+ # and cached lookups depend on it).
167
+ incidence.flags.writeable = False
146
168
  object.__setattr__(self, "incidence", incidence)
147
169
 
148
170
  def __eq__(self, other: object) -> bool:
@@ -191,6 +213,8 @@ class FormalContext:
191
213
  """
192
214
  Create a formal context from an array-like binary matrix.
193
215
  """
216
+ if scipy.sparse.issparse(data):
217
+ data = data.toarray()
194
218
  array = np.asarray(data)
195
219
 
196
220
  if array.ndim != 2:
@@ -235,8 +259,11 @@ class FormalContext:
235
259
  Names -> indices; integers are positions and must be in range.
236
260
 
237
261
  Names are always strings (FormalContext converts them), so an integer
238
- is never mistaken for a name.
262
+ is never mistaken for a name. A single string is one name, not a
263
+ sequence of one-letter names.
239
264
  """
265
+ if isinstance(items, str):
266
+ items = [items]
240
267
  resolved: list[int] = []
241
268
  for item in items:
242
269
  if _is_index(item):
@@ -352,7 +379,7 @@ class FormalContext:
352
379
  ``rows`` has one row per new object and one column per attribute.
353
380
  """
354
381
  names = tuple(map(str, names))
355
- rows = _cross_table(rows).reshape(len(names), self.n_attributes)
382
+ rows = _new_cells(rows, (len(names), self.n_attributes), "rows", "object")
356
383
  return FormalContext(
357
384
  objects=self.objects + names,
358
385
  attributes=self.attributes,
@@ -366,7 +393,7 @@ class FormalContext:
366
393
  ``columns`` has one row per object and one column per new attribute.
367
394
  """
368
395
  names = tuple(map(str, names))
369
- columns = _cross_table(columns).reshape(self.n_objects, len(names))
396
+ columns = _new_cells(columns, (self.n_objects, len(names)), "columns", "attribute")
370
397
  return FormalContext(
371
398
  objects=self.objects,
372
399
  attributes=self.attributes + names,
@@ -398,7 +425,7 @@ class FormalContext:
398
425
  Convert the formal context to a pandas DataFrame.
399
426
  """
400
427
  return pd.DataFrame(
401
- self.incidence,
428
+ self.incidence.copy(),
402
429
  index=self.objects,
403
430
  columns=self.attributes,
404
431
  )
@@ -122,8 +122,9 @@ class IncompleteContext:
122
122
  if len(set(self.attributes)) != len(self.attributes):
123
123
  raise ValueError("Attribute names must be unique.")
124
124
 
125
- certain = np.asarray(self.certain, dtype=bool)
126
- unknown = np.asarray(self.unknown, dtype=bool)
125
+ # Copies, read-only: the context cannot change after creation.
126
+ certain = np.array(self.certain, dtype=bool)
127
+ unknown = np.array(self.unknown, dtype=bool)
127
128
  expected_shape = (len(self.objects), len(self.attributes))
128
129
 
129
130
  for name, matrix in (("certain", certain), ("unknown", unknown)):
@@ -136,6 +137,9 @@ class IncompleteContext:
136
137
  if (certain & unknown).any():
137
138
  raise ValueError("An entry cannot be both certain and unknown.")
138
139
 
140
+ certain.flags.writeable = False
141
+ unknown.flags.writeable = False
142
+
139
143
  object.__setattr__(self, "certain", certain)
140
144
  object.__setattr__(self, "unknown", unknown)
141
145
 
@@ -269,6 +273,8 @@ class IncompleteContext:
269
273
 
270
274
  @staticmethod
271
275
  def _resolve(items: Iterable[int | str], names: tuple[str, ...], kind: str) -> list[int]:
276
+ if isinstance(items, str):
277
+ items = [items]
272
278
  index_of = {name: i for i, name in enumerate(names)}
273
279
  resolved = []
274
280
  for item in items:
@@ -279,7 +285,10 @@ class IncompleteContext:
279
285
  )
280
286
  resolved.append(int(item))
281
287
  else:
282
- resolved.append(index_of[item])
288
+ try:
289
+ resolved.append(index_of[item])
290
+ except KeyError:
291
+ raise KeyError(f"Unknown {kind} {item!r}.") from None
283
292
  return resolved
284
293
 
285
294
  def _attribute_indices(self, attributes: Iterable[int | str]) -> list[int]:
@@ -48,6 +48,21 @@ class ConceptLattice:
48
48
  def __post_init__(self) -> None:
49
49
  object.__setattr__(self, "concepts", tuple(self.concepts))
50
50
 
51
+ def __eq__(self, other: object) -> bool:
52
+ # The same concepts make the same lattice, whichever order the
53
+ # algorithm produced them in.
54
+ if not isinstance(other, ConceptLattice):
55
+ return NotImplemented
56
+ return (
57
+ self.context == other.context
58
+ and self.min_support == other.min_support
59
+ and len(self.concepts) == len(other.concepts)
60
+ and set(self.concepts) == set(other.concepts)
61
+ )
62
+
63
+ def __hash__(self) -> int:
64
+ return hash((self.context, frozenset(self.concepts), self.min_support))
65
+
51
66
  @classmethod
52
67
  def from_context(
53
68
  cls,
@@ -108,6 +108,19 @@ class ManyValuedContext:
108
108
  object.__setattr__(self, "attributes", attributes)
109
109
  object.__setattr__(self, "data", data)
110
110
 
111
+ def __eq__(self, other: object) -> bool:
112
+ if not isinstance(other, ManyValuedContext):
113
+ return NotImplemented
114
+ return (
115
+ self.objects == other.objects
116
+ and self.attributes == other.attributes
117
+ and self.data.equals(other.data)
118
+ )
119
+
120
+ def __hash__(self) -> int:
121
+ # The values may be unhashable; equal contexts have equal names.
122
+ return hash((self.objects, self.attributes))
123
+
111
124
  @property
112
125
  def n_objects(self) -> int:
113
126
  """Number of objects."""
@@ -25,7 +25,6 @@ from __future__ import annotations
25
25
  from collections import deque
26
26
  from collections.abc import Iterable
27
27
  from dataclasses import dataclass
28
- from itertools import combinations
29
28
 
30
29
  import numpy as np
31
30
  from sklearn.base import BaseEstimator
@@ -181,73 +180,52 @@ def bipartite_coloring(
181
180
  return color
182
181
 
183
182
 
184
- def _concept_leq(
185
- lattice: ConceptLattice,
186
- left_index: int,
187
- right_index: int,
188
- ) -> bool:
189
- """
190
- Concept order using extent inclusion.
191
- """
192
- left = lattice.concepts[left_index]
193
- right = lattice.concepts[right_index]
194
- return left.extent.issubset(right.extent)
183
+ def _concept_order(lattice: ConceptLattice) -> np.ndarray:
184
+ """``leq[i, j]``: concept i lies below (or is) concept j, by extent inclusion."""
185
+ extents = np.zeros((lattice.n_concepts, lattice.context.n_objects), dtype=int)
186
+ for i, concept in enumerate(lattice.concepts):
187
+ extents[i, list(concept.extent)] = 1
188
+ # i <= j iff no object is in extent i but not in extent j.
189
+ return extents @ (1 - extents).T == 0
195
190
 
196
191
 
197
- def _poset_predecessors(
198
- lattice: ConceptLattice,
199
- ) -> dict[int, set[int]]:
200
- """
201
- Return predecessor sets for the concept poset.
192
+ def _transitive_orientation(adjacent: list[set[int]]) -> set[tuple[int, int]]:
202
193
  """
203
- n_concepts = lattice.n_concepts
204
- predecessors = {i: set() for i in range(n_concepts)}
194
+ A transitive orientation of an undirected graph (Golumbic's algorithm).
205
195
 
206
- for i, j in combinations(range(n_concepts), 2):
207
- if _concept_leq(lattice, i, j):
208
- predecessors[j].add(i)
209
- elif _concept_leq(lattice, j, i):
210
- predecessors[i].add(j)
211
-
212
- return predecessors
213
-
214
-
215
- def _linear_extensions(
216
- predecessors: dict[int, set[int]],
217
- ) -> list[tuple[int, ...]]:
196
+ Repeatedly orients one remaining edge and everything it forces (its
197
+ implication class: ab forces ac if bc is not an edge, and cb if ac is
198
+ not an edge), then removes those edges. Raises ValueError if the graph
199
+ has no transitive orientation.
218
200
  """
219
- Enumerate all linear extensions of a finite poset.
220
-
221
- This is intentionally simple and suitable only for small contexts.
222
- """
223
- elements = set(predecessors)
224
- result: list[tuple[int, ...]] = []
225
-
226
- def backtrack(
227
- current: list[int],
228
- remaining: set[int],
229
- ) -> None:
230
- if not remaining:
231
- result.append(tuple(current))
232
- return
233
-
234
- available = sorted(
235
- element
236
- for element in remaining
237
- if predecessors[element].issubset(current)
238
- )
239
-
240
- for element in available:
241
- current.append(element)
242
- remaining.remove(element)
243
-
244
- backtrack(current, remaining)
245
-
246
- remaining.add(element)
247
- current.pop()
248
-
249
- backtrack([], set(elements))
250
- return result
201
+ remaining = [set(neighbours) for neighbours in adjacent]
202
+ orientation: set[tuple[int, int]] = set()
203
+
204
+ for a in range(len(remaining)):
205
+ while remaining[a]:
206
+ start = (a, next(iter(remaining[a])))
207
+ implication_class = {start}
208
+ stack = [start]
209
+ while stack:
210
+ x, y = stack.pop()
211
+ forced = [(x, z) for z in remaining[x] if z != y and z not in remaining[y]]
212
+ forced += [(z, y) for z in remaining[y] if z != x and z not in remaining[x]]
213
+ for edge in forced:
214
+ if edge not in implication_class:
215
+ implication_class.add(edge)
216
+ stack.append(edge)
217
+
218
+ if any((y, x) in implication_class for x, y in implication_class):
219
+ raise ValueError(
220
+ "The complement concept lattice does not have order "
221
+ "dimension at most two."
222
+ )
223
+ orientation |= implication_class
224
+ for x, y in implication_class:
225
+ remaining[x].discard(y)
226
+ remaining[y].discard(x)
227
+
228
+ return orientation
251
229
 
252
230
 
253
231
  def _realizer_pair(
@@ -256,50 +234,45 @@ def _realizer_pair(
256
234
  """
257
235
  Find two linear extensions whose intersection is the concept order.
258
236
 
259
- For small contexts, this brute-force search is a clear way to obtain the
260
- two chain orders required by Algorithm 1 when the lattice has order
261
- dimension at most two.
237
+ A poset has order dimension at most two iff its incomparability graph
238
+ has a transitive orientation T (Dushnik and Miller); the two linear
239
+ extensions are then P + T and P + T^-1. Polynomial, unlike trying all
240
+ pairs of linear extensions.
262
241
  """
263
- predecessors = _poset_predecessors(lattice)
264
- extensions = _linear_extensions(predecessors)
265
-
266
- if not extensions:
267
- raise ValueError("Could not compute linear extensions.")
268
-
242
+ leq = _concept_order(lattice)
269
243
  n_concepts = lattice.n_concepts
244
+ incomparable = ~(leq | leq.T)
245
+ adjacent = [set(np.flatnonzero(row).tolist()) for row in incomparable]
246
+ orientation = _transitive_orientation(adjacent)
247
+
248
+ chains = []
249
+ for forward in (True, False):
250
+ before = leq.copy()
251
+ for x, y in orientation:
252
+ if forward:
253
+ before[x, y] = True
254
+ else:
255
+ before[y, x] = True
256
+ # In a linear order, the number of elements before x is x's position.
257
+ positions = before.sum(axis=0) - 1
258
+ if sorted(positions.tolist()) != list(range(n_concepts)):
259
+ raise ValueError(
260
+ "The complement concept lattice does not have order "
261
+ "dimension at most two."
262
+ )
263
+ chains.append(tuple(int(i) for i in np.argsort(positions)))
270
264
 
271
- poset_relation = {
272
- (i, j)
273
- for i in range(n_concepts)
274
- for j in range(n_concepts)
275
- if _concept_leq(lattice, i, j)
276
- }
277
-
278
- extension_positions = []
279
- for extension in extensions:
280
- extension_positions.append(
281
- {
282
- concept_index: position
283
- for position, concept_index in enumerate(extension)
284
- }
265
+ position_1 = np.argsort(chains[0])
266
+ position_2 = np.argsort(chains[1])
267
+ both = (position_1[:, None] <= position_1[None, :]) & (
268
+ position_2[:, None] <= position_2[None, :]
269
+ )
270
+ if not np.array_equal(both, leq):
271
+ raise ValueError(
272
+ "The complement concept lattice does not have order dimension at most two."
285
273
  )
286
274
 
287
- for ext_1, pos_1 in zip(extensions, extension_positions):
288
- for ext_2, pos_2 in zip(extensions, extension_positions):
289
- intersection_relation = {
290
- (i, j)
291
- for i in range(n_concepts)
292
- for j in range(n_concepts)
293
- if pos_1[i] <= pos_1[j] and pos_2[i] <= pos_2[j]
294
- }
295
-
296
- if intersection_relation == poset_relation:
297
- return ext_1, ext_2
298
-
299
- raise ValueError(
300
- "The complement concept lattice does not appear to have "
301
- "order dimension at most two."
302
- )
275
+ return chains[0], chains[1]
303
276
 
304
277
 
305
278
  def _factor_from_chain_order(
@@ -76,6 +76,8 @@ class ConceptMembershipEncoder(TransformerMixin, BaseEstimator):
76
76
  """
77
77
  encoder = cls(output=output)
78
78
  encoder._fit_from_lattice(lattice)
79
+ # Fitted on the lattice's context, as fit(lattice.context) would be.
80
+ encoder._fit_feature_names = lattice.context.attributes
79
81
  return encoder
80
82
 
81
83
  def fit(self, X, y=None):
@@ -24,7 +24,8 @@ def read_cxt(path: str | Path) -> FormalContext:
24
24
  """
25
25
  path = Path(path)
26
26
 
27
- with path.open("r", encoding="utf-8") as file:
27
+ # utf-8-sig also reads files that start with a byte-order mark.
28
+ with path.open("r", encoding="utf-8-sig") as file:
28
29
  lines = [line.rstrip("\n") for line in file]
29
30
 
30
31
  if not lines or lines[0] != "B":
@@ -47,6 +48,20 @@ def read_cxt(path: str | Path) -> FormalContext:
47
48
  expected_without_separator = 4 + n_objects + n_attributes + n_objects
48
49
  expected_with_separator = expected_without_separator + 1
49
50
 
51
+ # Blank lines after the cross table are not part of the context. (Rows
52
+ # of a context without attributes are blank too, so only lines beyond
53
+ # the expected count are dropped.)
54
+ while len(lines) > expected_with_separator and not lines[-1].strip():
55
+ lines.pop()
56
+ if (
57
+ len(lines) == expected_with_separator
58
+ and len(lines) > 4
59
+ and lines[4] != ""
60
+ and not lines[-1].strip()
61
+ and n_attributes > 0
62
+ ):
63
+ lines.pop() # no separator line, one trailing blank line
64
+
50
65
  if len(lines) == expected_with_separator:
51
66
  object_start = 5
52
67
  elif len(lines) == expected_without_separator:
@@ -109,6 +124,14 @@ def write_cxt(context: FormalContext, path: str | Path) -> None:
109
124
  """
110
125
  path = Path(path)
111
126
 
127
+ for kind, names in (("object", context.objects), ("attribute", context.attributes)):
128
+ for name in names:
129
+ if "\n" in name or "\r" in name:
130
+ raise ValueError(
131
+ f"The {kind} name {name!r} contains a line break, which the "
132
+ ".cxt format cannot store (one name per line)."
133
+ )
134
+
112
135
  lines: list[str] = [
113
136
  "B",
114
137
  "",
@@ -44,11 +44,16 @@ def context_from_json(text: str) -> FormalContext:
44
44
  data = json.loads(text)
45
45
 
46
46
  if isinstance(data, dict):
47
- return FormalContext(
48
- objects=data["objects"],
49
- attributes=data["attributes"],
50
- incidence=data["incidence"],
51
- )
47
+ try:
48
+ objects, attributes, incidence = (
49
+ data["objects"], data["attributes"], data["incidence"]
50
+ )
51
+ except KeyError as exc:
52
+ raise ValueError(
53
+ f"The JSON context has no {exc.args[0]!r} entry: expected the "
54
+ 'FCART/fcapy layout or {"objects", "attributes", "incidence"}.'
55
+ ) from None
56
+ return FormalContext(objects=objects, attributes=attributes, incidence=incidence)
52
57
 
53
58
  try:
54
59
  header, body = data
@@ -68,6 +73,10 @@ def context_from_json(text: str) -> FormalContext:
68
73
 
69
74
  incidence = np.zeros((len(objects), len(attributes)), dtype=bool)
70
75
  for i, indices in enumerate(rows):
76
+ if not isinstance(indices, list):
77
+ raise ValueError(
78
+ f"Object {objects[i]!r}: expected a list of attribute indices, got {indices!r}."
79
+ )
71
80
  for m in indices:
72
81
  if isinstance(m, bool) or not isinstance(m, int) or not 0 <= m < len(attributes):
73
82
  raise ValueError(
@@ -189,7 +189,7 @@ def _label_entropy(labels: np.ndarray) -> float:
189
189
  return 0.0
190
190
  _, counts = np.unique(labels, return_counts=True)
191
191
  p = counts / counts.sum()
192
- return float(-(p * np.log2(p)).sum())
192
+ return float(-(p * np.log2(p)).sum()) + 0.0 # + 0.0 turns -0.0 into 0.0
193
193
 
194
194
 
195
195
  def _check_labels(lattice: ConceptLattice, y) -> np.ndarray: