mcdakit 0.2.0__py3-none-any.whl
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.
- mcdakit/__init__.py +180 -0
- mcdakit/ahp.py +372 -0
- mcdakit/ai.py +802 -0
- mcdakit/ai_providers.py +438 -0
- mcdakit/explain.py +346 -0
- mcdakit/group.py +296 -0
- mcdakit/methods/__init__.py +157 -0
- mcdakit/methods/_common.py +25 -0
- mcdakit/methods/aras.py +63 -0
- mcdakit/methods/base.py +305 -0
- mcdakit/methods/cocoso.py +80 -0
- mcdakit/methods/codas.py +71 -0
- mcdakit/methods/copras.py +100 -0
- mcdakit/methods/edas.py +66 -0
- mcdakit/methods/electre.py +83 -0
- mcdakit/methods/mabac.py +54 -0
- mcdakit/methods/marcos.py +71 -0
- mcdakit/methods/promethee.py +162 -0
- mcdakit/methods/registry.py +218 -0
- mcdakit/methods/scoring.py +97 -0
- mcdakit/methods/spotis.py +164 -0
- mcdakit/methods/topsis.py +69 -0
- mcdakit/methods/vikor.py +68 -0
- mcdakit/methods/waspas.py +133 -0
- mcdakit/normalization.py +240 -0
- mcdakit/orientation.py +47 -0
- mcdakit/py.typed +0 -0
- mcdakit/ranking.py +289 -0
- mcdakit/sensitivity.py +231 -0
- mcdakit/testing.py +444 -0
- mcdakit/types.py +394 -0
- mcdakit/weighting.py +341 -0
- mcdakit-0.2.0.dist-info/METADATA +627 -0
- mcdakit-0.2.0.dist-info/RECORD +36 -0
- mcdakit-0.2.0.dist-info/WHEEL +4 -0
- mcdakit-0.2.0.dist-info/licenses/LICENSE +202 -0
mcdakit/__init__.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
"""mcdakit — multi-criteria decision analysis whose rankings hold.
|
|
2
|
+
|
|
3
|
+
Most MCDA libraries answer "what is the ranking?". This one also answers
|
|
4
|
+
"would the ranking survive someone disagreeing with my inputs?", through two
|
|
5
|
+
features:
|
|
6
|
+
|
|
7
|
+
* :func:`~mcdakit.ranking.rank` with ``method="spotis"`` — a ranking that
|
|
8
|
+
cannot change when an option nobody chose is removed from the shortlist.
|
|
9
|
+
* :func:`~mcdakit.sensitivity.sensitivity` — how far each weight can move
|
|
10
|
+
before the winner changes, as a tolerance and a fragile/moderate/robust band.
|
|
11
|
+
|
|
12
|
+
Quick start
|
|
13
|
+
-----------
|
|
14
|
+
|
|
15
|
+
>>> from mcdakit import Criterion, rank, sensitivity
|
|
16
|
+
>>> criteria = [
|
|
17
|
+
... Criterion("Price", weight=0.6, direction="cost", bounds=(2.0, 4.0)),
|
|
18
|
+
... Criterion("Quality", weight=0.4, direction="benefit", bounds=(0, 10)),
|
|
19
|
+
... ]
|
|
20
|
+
>>> result = rank([[3.0, 8], [2.0, 6]], criteria,
|
|
21
|
+
... method="spotis", labels=["Alpha", "Beta"])
|
|
22
|
+
>>> result.winner
|
|
23
|
+
'Beta'
|
|
24
|
+
>>> result.reversal_free
|
|
25
|
+
True
|
|
26
|
+
|
|
27
|
+
numpy is the only runtime dependency.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from .ahp import (
|
|
31
|
+
CONSISTENCY_LIMIT,
|
|
32
|
+
RANDOM_INDEX,
|
|
33
|
+
SAATY_SCALE,
|
|
34
|
+
AhpResult,
|
|
35
|
+
ahp_rank,
|
|
36
|
+
ahp_weights,
|
|
37
|
+
comparison_matrix,
|
|
38
|
+
consistency_ratio,
|
|
39
|
+
priorities,
|
|
40
|
+
)
|
|
41
|
+
from .explain import Explanation, Margin, compare, explain
|
|
42
|
+
from .group import (
|
|
43
|
+
Participant,
|
|
44
|
+
aggregate_rankings,
|
|
45
|
+
aggregate_scores,
|
|
46
|
+
disagreement,
|
|
47
|
+
group_rank,
|
|
48
|
+
)
|
|
49
|
+
from .methods import (
|
|
50
|
+
BUILTIN_METHODS,
|
|
51
|
+
BoundsWarning,
|
|
52
|
+
DuplicateMethodError,
|
|
53
|
+
Method,
|
|
54
|
+
MethodResult,
|
|
55
|
+
PluginLoadError,
|
|
56
|
+
ScoringContext,
|
|
57
|
+
Wants,
|
|
58
|
+
available,
|
|
59
|
+
register,
|
|
60
|
+
unregister,
|
|
61
|
+
)
|
|
62
|
+
from .methods import get as get_method
|
|
63
|
+
from .methods import has as has_method
|
|
64
|
+
from .methods import names as method_names
|
|
65
|
+
from .normalization import (
|
|
66
|
+
NORMALIZATIONS,
|
|
67
|
+
available_normalizations,
|
|
68
|
+
get_normalization,
|
|
69
|
+
max_normalization,
|
|
70
|
+
minmax_normalization,
|
|
71
|
+
register_normalization,
|
|
72
|
+
sum_normalization,
|
|
73
|
+
vector_normalization,
|
|
74
|
+
)
|
|
75
|
+
from .orientation import orient
|
|
76
|
+
from .ranking import (
|
|
77
|
+
METHODS,
|
|
78
|
+
agreement,
|
|
79
|
+
compare_methods,
|
|
80
|
+
rank,
|
|
81
|
+
reversal_check,
|
|
82
|
+
score,
|
|
83
|
+
)
|
|
84
|
+
from .sensitivity import (
|
|
85
|
+
FRAGILE_THRESHOLD,
|
|
86
|
+
ROBUST_THRESHOLD,
|
|
87
|
+
sensitivity,
|
|
88
|
+
)
|
|
89
|
+
from .types import Criterion, Decision, McdaError, Result
|
|
90
|
+
from .weighting import (
|
|
91
|
+
WEIGHTINGS,
|
|
92
|
+
available_weightings,
|
|
93
|
+
critic_weights,
|
|
94
|
+
derive_weights,
|
|
95
|
+
entropy_weights,
|
|
96
|
+
equal_weights,
|
|
97
|
+
get_weighting,
|
|
98
|
+
register_weighting,
|
|
99
|
+
std_weights,
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
# `testing` is imported lazily by users (`from mcdakit.testing import ...`);
|
|
103
|
+
# it is not pulled in here so `import mcdakit` stays free of test scaffolding.
|
|
104
|
+
|
|
105
|
+
#: Language-model assistance is deliberately **not** re-exported here. It is
|
|
106
|
+
#: reached as ``from mcdakit.ai import propose_criteria``, so that using it is
|
|
107
|
+
#: a visible choice in the importing module rather than something available by
|
|
108
|
+
#: default. MCDA results are often used to justify a decision to somebody, and
|
|
109
|
+
#: whether a model contributed to the inputs should be legible in the source.
|
|
110
|
+
#: The module costs nothing to have installed: it imports only the standard
|
|
111
|
+
#: library and NumPy, and the model provider is injected by the caller.
|
|
112
|
+
|
|
113
|
+
__version__ = "0.2.0"
|
|
114
|
+
|
|
115
|
+
__all__ = [
|
|
116
|
+
"BUILTIN_METHODS",
|
|
117
|
+
"CONSISTENCY_LIMIT",
|
|
118
|
+
"FRAGILE_THRESHOLD",
|
|
119
|
+
"METHODS",
|
|
120
|
+
"NORMALIZATIONS",
|
|
121
|
+
"RANDOM_INDEX",
|
|
122
|
+
"ROBUST_THRESHOLD",
|
|
123
|
+
"SAATY_SCALE",
|
|
124
|
+
"WEIGHTINGS",
|
|
125
|
+
"AhpResult",
|
|
126
|
+
"BoundsWarning",
|
|
127
|
+
"Criterion",
|
|
128
|
+
"Decision",
|
|
129
|
+
"DuplicateMethodError",
|
|
130
|
+
"Explanation",
|
|
131
|
+
"Margin",
|
|
132
|
+
"McdaError",
|
|
133
|
+
"Method",
|
|
134
|
+
"MethodResult",
|
|
135
|
+
"Participant",
|
|
136
|
+
"PluginLoadError",
|
|
137
|
+
"Result",
|
|
138
|
+
"ScoringContext",
|
|
139
|
+
"Wants",
|
|
140
|
+
"__version__",
|
|
141
|
+
"aggregate_rankings",
|
|
142
|
+
"aggregate_scores",
|
|
143
|
+
"agreement",
|
|
144
|
+
"ahp_rank",
|
|
145
|
+
"ahp_weights",
|
|
146
|
+
"available",
|
|
147
|
+
"available_normalizations",
|
|
148
|
+
"available_weightings",
|
|
149
|
+
"compare",
|
|
150
|
+
"compare_methods",
|
|
151
|
+
"comparison_matrix",
|
|
152
|
+
"consistency_ratio",
|
|
153
|
+
"critic_weights",
|
|
154
|
+
"derive_weights",
|
|
155
|
+
"disagreement",
|
|
156
|
+
"entropy_weights",
|
|
157
|
+
"equal_weights",
|
|
158
|
+
"explain",
|
|
159
|
+
"get_method",
|
|
160
|
+
"get_normalization",
|
|
161
|
+
"get_weighting",
|
|
162
|
+
"group_rank",
|
|
163
|
+
"has_method",
|
|
164
|
+
"max_normalization",
|
|
165
|
+
"method_names",
|
|
166
|
+
"minmax_normalization",
|
|
167
|
+
"orient",
|
|
168
|
+
"priorities",
|
|
169
|
+
"rank",
|
|
170
|
+
"register",
|
|
171
|
+
"register_normalization",
|
|
172
|
+
"register_weighting",
|
|
173
|
+
"reversal_check",
|
|
174
|
+
"score",
|
|
175
|
+
"sensitivity",
|
|
176
|
+
"std_weights",
|
|
177
|
+
"sum_normalization",
|
|
178
|
+
"unregister",
|
|
179
|
+
"vector_normalization",
|
|
180
|
+
]
|
mcdakit/ahp.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
"""AHP — deriving weights from pairwise comparisons.
|
|
2
|
+
|
|
3
|
+
Saaty, *The Analytic Hierarchy Process*, McGraw-Hill, 1980.
|
|
4
|
+
|
|
5
|
+
Weights are the softest input in any MCDA model, and typing them directly is
|
|
6
|
+
the worst way to produce them: people cannot reliably say a criterion is worth
|
|
7
|
+
0.35 rather than 0.40, but they can say price matters somewhat more than
|
|
8
|
+
quality. AHP turns those judgements into weights and — the part that makes it
|
|
9
|
+
worth the extra questions — measures whether the judgements contradict each
|
|
10
|
+
other.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from .types import McdaError
|
|
21
|
+
|
|
22
|
+
#: Saaty's fundamental scale, as ratio and meaning.
|
|
23
|
+
SAATY_SCALE = {
|
|
24
|
+
1 / 9: "Extremely less important",
|
|
25
|
+
1 / 7: "Very strongly less important",
|
|
26
|
+
1 / 5: "Strongly less important",
|
|
27
|
+
1 / 3: "Moderately less important",
|
|
28
|
+
1.0: "Equally important",
|
|
29
|
+
3.0: "Moderately more important",
|
|
30
|
+
5.0: "Strongly more important",
|
|
31
|
+
7.0: "Very strongly more important",
|
|
32
|
+
9.0: "Extremely more important",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
#: Saaty's random consistency index by matrix order: the average consistency
|
|
36
|
+
#: index of a randomly filled n x n reciprocal matrix. The consistency ratio is
|
|
37
|
+
#: CI / RI, which is what makes it comparable across problem sizes.
|
|
38
|
+
RANDOM_INDEX = {
|
|
39
|
+
1: 0.00,
|
|
40
|
+
2: 0.00,
|
|
41
|
+
3: 0.58,
|
|
42
|
+
4: 0.90,
|
|
43
|
+
5: 1.12,
|
|
44
|
+
6: 1.24,
|
|
45
|
+
7: 1.32,
|
|
46
|
+
8: 1.41,
|
|
47
|
+
9: 1.45,
|
|
48
|
+
10: 1.49,
|
|
49
|
+
11: 1.51,
|
|
50
|
+
12: 1.48,
|
|
51
|
+
13: 1.56,
|
|
52
|
+
14: 1.57,
|
|
53
|
+
15: 1.59,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
#: Saaty's rule of thumb: above this, at least one judgement contradicts the
|
|
57
|
+
#: others badly enough that the derived weights should not be relied on.
|
|
58
|
+
CONSISTENCY_LIMIT = 0.10
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def comparison_matrix(n: int, judgements: dict) -> np.ndarray:
|
|
62
|
+
"""Build a reciprocal matrix from ``{(i, j): ratio}`` judgements.
|
|
63
|
+
|
|
64
|
+
Only the upper triangle need be given: setting ``(i, j)`` to 3 sets
|
|
65
|
+
``(j, i)`` to 1/3 automatically, which is what makes the matrix reciprocal
|
|
66
|
+
and the exercise tractable — n(n-1)/2 questions rather than n².
|
|
67
|
+
Unjudged pairs default to 1 (equally important).
|
|
68
|
+
"""
|
|
69
|
+
matrix = np.ones((n, n), dtype=float)
|
|
70
|
+
for (i, j), value in judgements.items():
|
|
71
|
+
if not (0 <= i < n and 0 <= j < n):
|
|
72
|
+
raise McdaError(f"Judgement ({i}, {j}) is out of range for {n} criteria.")
|
|
73
|
+
if i == j:
|
|
74
|
+
raise McdaError("A criterion cannot be compared with itself.")
|
|
75
|
+
value = float(value)
|
|
76
|
+
if value <= 0:
|
|
77
|
+
raise McdaError(
|
|
78
|
+
f"Judgement ({i}, {j}) must be a positive ratio, got {value}."
|
|
79
|
+
)
|
|
80
|
+
matrix[i, j] = value
|
|
81
|
+
matrix[j, i] = 1.0 / value
|
|
82
|
+
return matrix
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def priorities(matrix: np.ndarray) -> np.ndarray:
|
|
86
|
+
"""Principal eigenvector by row geometric mean, normalised to sum to one.
|
|
87
|
+
|
|
88
|
+
The geometric mean is Saaty's standard approximation and — unlike an
|
|
89
|
+
iterative eigensolver — always returns something sensible for the small,
|
|
90
|
+
well-formed matrices this is used on. It also keeps the numpy-only rule:
|
|
91
|
+
no scipy needed.
|
|
92
|
+
"""
|
|
93
|
+
matrix = np.asarray(matrix, dtype=float)
|
|
94
|
+
if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1]:
|
|
95
|
+
raise McdaError(
|
|
96
|
+
f"A comparison matrix must be square, got shape {matrix.shape}."
|
|
97
|
+
)
|
|
98
|
+
geometric = np.prod(matrix, axis=1) ** (1.0 / matrix.shape[0])
|
|
99
|
+
total = geometric.sum()
|
|
100
|
+
if total == 0:
|
|
101
|
+
return np.full(matrix.shape[0], 1.0 / matrix.shape[0])
|
|
102
|
+
return geometric / total
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def consistency_ratio(matrix: np.ndarray, weights: np.ndarray | None = None) -> float:
|
|
106
|
+
"""Saaty's consistency ratio, ``CI / RI``.
|
|
107
|
+
|
|
108
|
+
Zero for a perfectly consistent set of judgements — one where saying price
|
|
109
|
+
is 3x quality and quality is 3x delivery is matched by saying price is 9x
|
|
110
|
+
delivery. Returns 0.0 for orders below three, where a single judgement has
|
|
111
|
+
nothing to contradict.
|
|
112
|
+
"""
|
|
113
|
+
matrix = np.asarray(matrix, dtype=float)
|
|
114
|
+
size = matrix.shape[0]
|
|
115
|
+
if size < 3:
|
|
116
|
+
return 0.0
|
|
117
|
+
if weights is None:
|
|
118
|
+
weights = priorities(matrix)
|
|
119
|
+
|
|
120
|
+
weighted_sum = matrix @ weights
|
|
121
|
+
lambda_max = float(np.mean(weighted_sum / weights))
|
|
122
|
+
consistency_index = (lambda_max - size) / (size - 1)
|
|
123
|
+
random_index = RANDOM_INDEX.get(size, 1.60)
|
|
124
|
+
return consistency_index / random_index if random_index else 0.0
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def ahp_weights(judgements, names: Sequence[str] | None = None) -> dict:
|
|
128
|
+
"""Weights from pairwise comparisons, with their consistency ratio.
|
|
129
|
+
|
|
130
|
+
``judgements`` is either a full reciprocal matrix, or a ``{(i, j): ratio}``
|
|
131
|
+
mapping of the upper triangle — in which case ``names`` (or an explicit
|
|
132
|
+
``n``) is needed to size it.
|
|
133
|
+
|
|
134
|
+
Returns ``{"weights", "consistency_ratio", "consistent", "names"}``.
|
|
135
|
+
|
|
136
|
+
The consistency ratio is **reported, never enforced**. An inconsistent
|
|
137
|
+
matrix is a signal to revisit the judgements, not an error: sometimes the
|
|
138
|
+
inconsistency is real and the analyst wants to proceed anyway, and taking
|
|
139
|
+
that decision away from them would be presumptuous.
|
|
140
|
+
|
|
141
|
+
Examples
|
|
142
|
+
--------
|
|
143
|
+
>>> from mcdakit import ahp_weights
|
|
144
|
+
>>> out = ahp_weights({(0, 1): 3, (0, 2): 9, (1, 2): 3},
|
|
145
|
+
... names=["Price", "Quality", "Delivery"])
|
|
146
|
+
>>> round(out["consistency_ratio"], 6)
|
|
147
|
+
0.0
|
|
148
|
+
>>> [round(float(w), 4) for w in out["weights"]]
|
|
149
|
+
[0.6923, 0.2308, 0.0769]
|
|
150
|
+
"""
|
|
151
|
+
if isinstance(judgements, dict):
|
|
152
|
+
if names is None:
|
|
153
|
+
raise McdaError(
|
|
154
|
+
"names are required when judgements are given as pairs, so "
|
|
155
|
+
"the matrix size is known."
|
|
156
|
+
)
|
|
157
|
+
matrix = comparison_matrix(len(names), judgements)
|
|
158
|
+
else:
|
|
159
|
+
matrix = np.asarray(judgements, dtype=float)
|
|
160
|
+
if names is None:
|
|
161
|
+
names = [f"Criterion {i + 1}" for i in range(matrix.shape[0])]
|
|
162
|
+
|
|
163
|
+
if matrix.shape[0] < 2:
|
|
164
|
+
raise McdaError(
|
|
165
|
+
"Pairwise comparison needs at least two criteria; with one there "
|
|
166
|
+
"is nothing to compare."
|
|
167
|
+
)
|
|
168
|
+
if len(names) != matrix.shape[0]:
|
|
169
|
+
raise McdaError(
|
|
170
|
+
f"Got {len(names)} names for a {matrix.shape[0]}x"
|
|
171
|
+
f"{matrix.shape[1]} comparison matrix."
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
weights = priorities(matrix)
|
|
175
|
+
ratio = consistency_ratio(matrix, weights)
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
"weights": weights,
|
|
179
|
+
"consistency_ratio": ratio,
|
|
180
|
+
"consistent": ratio <= CONSISTENCY_LIMIT,
|
|
181
|
+
"names": list(names),
|
|
182
|
+
"matrix": matrix,
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@dataclass(frozen=True)
|
|
187
|
+
class AhpResult:
|
|
188
|
+
"""A full AHP hierarchy, and how coherent the judgements behind it were.
|
|
189
|
+
|
|
190
|
+
Attributes
|
|
191
|
+
----------
|
|
192
|
+
scores:
|
|
193
|
+
One priority per alternative, summing to one. Higher is better.
|
|
194
|
+
weights:
|
|
195
|
+
The criterion weights derived from the criteria comparison matrix.
|
|
196
|
+
local_priorities:
|
|
197
|
+
Alternatives by criteria: each column is the alternatives' priorities
|
|
198
|
+
under one criterion.
|
|
199
|
+
consistency:
|
|
200
|
+
``{"criteria": ratio, criterion_name: ratio, ...}``. Reported for
|
|
201
|
+
every matrix separately, because a hierarchy is only as sound as its
|
|
202
|
+
least coherent judgement set and an average would hide exactly that.
|
|
203
|
+
inconsistent:
|
|
204
|
+
Names of the matrices exceeding :data:`CONSISTENCY_LIMIT`. Empty when
|
|
205
|
+
every judgement set holds together.
|
|
206
|
+
"""
|
|
207
|
+
|
|
208
|
+
scores: np.ndarray
|
|
209
|
+
weights: np.ndarray
|
|
210
|
+
local_priorities: np.ndarray
|
|
211
|
+
names: tuple
|
|
212
|
+
labels: tuple
|
|
213
|
+
consistency: dict
|
|
214
|
+
inconsistent: tuple
|
|
215
|
+
|
|
216
|
+
@property
|
|
217
|
+
def ranking(self) -> list:
|
|
218
|
+
"""``[(label, score), ...]`` best first."""
|
|
219
|
+
order = sorted(range(len(self.scores)), key=lambda i: -self.scores[i])
|
|
220
|
+
return [(self.labels[i], float(self.scores[i])) for i in order]
|
|
221
|
+
|
|
222
|
+
@property
|
|
223
|
+
def winner(self) -> str:
|
|
224
|
+
return self.ranking[0][0]
|
|
225
|
+
|
|
226
|
+
def __str__(self) -> str:
|
|
227
|
+
lines = ["AHP ranking:"]
|
|
228
|
+
label_width = max((len(label) for label, _ in self.ranking), default=0) + 2
|
|
229
|
+
for position, (label, score) in enumerate(self.ranking, start=1):
|
|
230
|
+
lines.append(f" {position}. {label:<{label_width}}{score:.4f}")
|
|
231
|
+
lines.append(" consistency ratios:")
|
|
232
|
+
name_width = max((len(n) for n in self.consistency), default=0) + 2
|
|
233
|
+
for name, ratio in self.consistency.items():
|
|
234
|
+
flag = " EXCEEDS 0.10" if ratio > CONSISTENCY_LIMIT else ""
|
|
235
|
+
lines.append(f" {name:<{name_width}}{ratio:.4f}{flag}")
|
|
236
|
+
if self.inconsistent:
|
|
237
|
+
verb = "contradicts" if len(self.inconsistent) == 1 else "contradict"
|
|
238
|
+
lines.append(
|
|
239
|
+
f" ! {', '.join(self.inconsistent)} {verb} itself; revisit "
|
|
240
|
+
f"those judgements before relying on the ranking"
|
|
241
|
+
if len(self.inconsistent) == 1
|
|
242
|
+
else f" ! {', '.join(self.inconsistent)} {verb} themselves; "
|
|
243
|
+
f"revisit those judgements before relying on the ranking"
|
|
244
|
+
)
|
|
245
|
+
return "\n".join(lines)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def ahp_rank(
|
|
249
|
+
criteria_comparisons,
|
|
250
|
+
alternative_comparisons: Sequence,
|
|
251
|
+
names: Sequence[str] | None = None,
|
|
252
|
+
labels: Sequence[str] | None = None,
|
|
253
|
+
) -> AhpResult:
|
|
254
|
+
"""Rank alternatives by pairwise comparison throughout the hierarchy.
|
|
255
|
+
|
|
256
|
+
This is AHP as Saaty defined it, and it differs from every other method in
|
|
257
|
+
this package in what it asks for. There is no decision matrix: instead the
|
|
258
|
+
alternatives are compared against each other, pair by pair, separately
|
|
259
|
+
under each criterion. That is what makes the method usable on criteria
|
|
260
|
+
nobody can measure --- a supplier's reputation, the quality of a design ---
|
|
261
|
+
where asking *is A better than B on this, and by how much* is answerable
|
|
262
|
+
and asking for a number is not.
|
|
263
|
+
|
|
264
|
+
The price is quadratic: :math:`n(n-1)/2` judgements per criterion, plus
|
|
265
|
+
the criteria themselves. The compensation is that the judgements can be
|
|
266
|
+
checked. A person who says A is three times B, B three times C, and then
|
|
267
|
+
A twice C has contradicted themselves, and the consistency ratio detects
|
|
268
|
+
it without anyone knowing what the right answer was.
|
|
269
|
+
|
|
270
|
+
Parameters
|
|
271
|
+
----------
|
|
272
|
+
criteria_comparisons:
|
|
273
|
+
A reciprocal matrix comparing the criteria, or a ``{(i, j): ratio}``
|
|
274
|
+
mapping of its upper triangle.
|
|
275
|
+
alternative_comparisons:
|
|
276
|
+
One comparison matrix per criterion, in the same order as the
|
|
277
|
+
criteria, each comparing the alternatives under that criterion.
|
|
278
|
+
names, labels:
|
|
279
|
+
Criterion and alternative names, for the report.
|
|
280
|
+
|
|
281
|
+
Returns
|
|
282
|
+
-------
|
|
283
|
+
AhpResult
|
|
284
|
+
With the ranking, the weights, and a consistency ratio for every
|
|
285
|
+
matrix. Inconsistency is reported and never enforced: whether a
|
|
286
|
+
contradiction is fatal is the analyst's judgement, not the library's.
|
|
287
|
+
|
|
288
|
+
Examples
|
|
289
|
+
--------
|
|
290
|
+
>>> import numpy as np
|
|
291
|
+
>>> from mcdakit import ahp_rank
|
|
292
|
+
>>> criteria = np.array([[1.0, 3.0], [1 / 3, 1.0]])
|
|
293
|
+
>>> per_criterion = [
|
|
294
|
+
... np.array([[1.0, 5.0], [1 / 5, 1.0]]),
|
|
295
|
+
... np.array([[1.0, 1 / 3], [3.0, 1.0]]),
|
|
296
|
+
... ]
|
|
297
|
+
>>> result = ahp_rank(criteria, per_criterion, labels=["A", "B"])
|
|
298
|
+
>>> result.winner
|
|
299
|
+
'A'
|
|
300
|
+
"""
|
|
301
|
+
alternative_comparisons = list(alternative_comparisons)
|
|
302
|
+
if not alternative_comparisons:
|
|
303
|
+
raise McdaError(
|
|
304
|
+
"ahp_rank needs one comparison matrix per criterion; none were given."
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
n_criteria = len(alternative_comparisons)
|
|
308
|
+
if names is None:
|
|
309
|
+
names = [f"Criterion {j + 1}" for j in range(n_criteria)]
|
|
310
|
+
names = tuple(str(n) for n in names)
|
|
311
|
+
if len(names) != n_criteria:
|
|
312
|
+
raise McdaError(
|
|
313
|
+
f"Got {len(names)} criterion names for {n_criteria} comparison matrices."
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
if isinstance(criteria_comparisons, dict):
|
|
317
|
+
criteria_matrix = comparison_matrix(n_criteria, criteria_comparisons)
|
|
318
|
+
else:
|
|
319
|
+
criteria_matrix = np.asarray(criteria_comparisons, dtype=float)
|
|
320
|
+
if criteria_matrix.shape != (n_criteria, n_criteria):
|
|
321
|
+
raise McdaError(
|
|
322
|
+
f"The criteria comparison matrix is {criteria_matrix.shape}, but "
|
|
323
|
+
f"{n_criteria} comparison matrices were given, one per criterion."
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
weights = priorities(criteria_matrix)
|
|
327
|
+
consistency = {"criteria": float(consistency_ratio(criteria_matrix, weights))}
|
|
328
|
+
|
|
329
|
+
columns, n_alternatives = [], None
|
|
330
|
+
for name, comparisons in zip(names, alternative_comparisons):
|
|
331
|
+
matrix = np.asarray(comparisons, dtype=float)
|
|
332
|
+
if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1]:
|
|
333
|
+
raise McdaError(
|
|
334
|
+
f"The comparison matrix for {name!r} must be square, got "
|
|
335
|
+
f"shape {matrix.shape}."
|
|
336
|
+
)
|
|
337
|
+
if n_alternatives is None:
|
|
338
|
+
n_alternatives = matrix.shape[0]
|
|
339
|
+
elif matrix.shape[0] != n_alternatives:
|
|
340
|
+
raise McdaError(
|
|
341
|
+
f"The comparison matrix for {name!r} compares "
|
|
342
|
+
f"{matrix.shape[0]} alternatives, but earlier matrices "
|
|
343
|
+
f"compared {n_alternatives}. Every criterion must rank the "
|
|
344
|
+
f"same alternatives."
|
|
345
|
+
)
|
|
346
|
+
local = priorities(matrix)
|
|
347
|
+
columns.append(local)
|
|
348
|
+
consistency[name] = float(consistency_ratio(matrix, local))
|
|
349
|
+
|
|
350
|
+
if labels is None:
|
|
351
|
+
labels = [f"Option {i + 1}" for i in range(n_alternatives or 0)]
|
|
352
|
+
labels = tuple(str(label) for label in labels)
|
|
353
|
+
if len(labels) != n_alternatives:
|
|
354
|
+
raise McdaError(
|
|
355
|
+
f"Got {len(labels)} alternative labels for {n_alternatives} alternatives."
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
local_priorities = np.column_stack(columns)
|
|
359
|
+
scores = local_priorities @ weights
|
|
360
|
+
|
|
361
|
+
inconsistent = tuple(
|
|
362
|
+
name for name, ratio in consistency.items() if ratio > CONSISTENCY_LIMIT
|
|
363
|
+
)
|
|
364
|
+
return AhpResult(
|
|
365
|
+
scores=scores.astype(float),
|
|
366
|
+
weights=weights,
|
|
367
|
+
local_priorities=local_priorities,
|
|
368
|
+
names=names,
|
|
369
|
+
labels=labels,
|
|
370
|
+
consistency=consistency,
|
|
371
|
+
inconsistent=inconsistent,
|
|
372
|
+
)
|