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/explain.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
"""Why did this option win?
|
|
2
|
+
|
|
3
|
+
A ranking is a conclusion, and a conclusion nobody can interrogate is
|
|
4
|
+
difficult to act on or to defend. Transparency is increasingly treated in the
|
|
5
|
+
decision-analysis literature as a precondition for trusting a computed result
|
|
6
|
+
rather than as a presentational extra.
|
|
7
|
+
|
|
8
|
+
This module answers two questions about a ranking the package has already
|
|
9
|
+
produced:
|
|
10
|
+
|
|
11
|
+
* **Which criteria carried the result?** Each criterion's contribution to an
|
|
12
|
+
option's score, and how much of the score it accounts for.
|
|
13
|
+
* **Why did A beat B?** The margin between two options, decomposed by
|
|
14
|
+
criterion, showing which criteria favoured the winner, which worked against
|
|
15
|
+
it, and whether any single one was decisive.
|
|
16
|
+
|
|
17
|
+
Two ways of attributing a score are used, because only one of them is exact
|
|
18
|
+
and it does not apply everywhere:
|
|
19
|
+
|
|
20
|
+
``exact``
|
|
21
|
+
The method is a weighted sum of normalised values, so an option's score
|
|
22
|
+
*is* the sum of its per-criterion contributions. Nothing is approximated
|
|
23
|
+
and the parts add up to the whole. Applies to ``weighted_scoring``,
|
|
24
|
+
``saw``, ``simple_scoring`` and ``spotis``.
|
|
25
|
+
|
|
26
|
+
``leave_one_out``
|
|
27
|
+
The method is not additive --- TOPSIS is a ratio of distances, VIKOR
|
|
28
|
+
takes a maximum, ELECTRE and PROMETHEE compare options pairwise --- so no
|
|
29
|
+
exact decomposition exists. Each criterion's importance is instead
|
|
30
|
+
measured by removing it and re-scoring: the contribution is how much the
|
|
31
|
+
score changes in its absence. These values are attributions, not
|
|
32
|
+
components, and do not sum to the score.
|
|
33
|
+
|
|
34
|
+
Which was used is reported on every result, because presenting an
|
|
35
|
+
approximation as though it were a decomposition would be the same
|
|
36
|
+
overstatement the rest of this package exists to avoid.
|
|
37
|
+
|
|
38
|
+
>>> from mcdakit import Criterion, rank
|
|
39
|
+
>>> from mcdakit.explain import explain
|
|
40
|
+
>>> criteria = [Criterion("Price", 0.6, "cost"), Criterion("Quality", 0.4)]
|
|
41
|
+
>>> result = rank([[3.0, 8.0], [2.0, 6.0]], criteria, labels=["A", "B"])
|
|
42
|
+
>>> report = explain(result)
|
|
43
|
+
>>> report.basis
|
|
44
|
+
'exact'
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
from __future__ import annotations
|
|
48
|
+
|
|
49
|
+
from dataclasses import dataclass
|
|
50
|
+
|
|
51
|
+
import numpy as np
|
|
52
|
+
|
|
53
|
+
from .types import McdaError, Result
|
|
54
|
+
|
|
55
|
+
__all__ = ["Contribution", "Explanation", "Margin", "compare", "explain"]
|
|
56
|
+
|
|
57
|
+
#: Methods whose score is exactly the sum of per-criterion contributions.
|
|
58
|
+
ADDITIVE = frozenset({"simple_scoring", "weighted_scoring", "saw", "spotis"})
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class Contribution:
|
|
63
|
+
"""One criterion's part in one option's score."""
|
|
64
|
+
|
|
65
|
+
criterion: str
|
|
66
|
+
value: float
|
|
67
|
+
weight: float
|
|
68
|
+
contribution: float
|
|
69
|
+
share: float
|
|
70
|
+
|
|
71
|
+
def __str__(self) -> str: # pragma: no cover - formatting only
|
|
72
|
+
return (
|
|
73
|
+
f"{self.criterion}: {self.contribution:+.4f} "
|
|
74
|
+
f"({self.share:.0%} of the score)"
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class Explanation:
|
|
80
|
+
"""Why one option scored what it did.
|
|
81
|
+
|
|
82
|
+
Attributes
|
|
83
|
+
----------
|
|
84
|
+
basis:
|
|
85
|
+
``"exact"`` when the contributions sum to the score, or
|
|
86
|
+
``"leave_one_out"`` when they are attributions obtained by removing
|
|
87
|
+
each criterion in turn. The distinction is reported rather than
|
|
88
|
+
smoothed over: only the first is a decomposition.
|
|
89
|
+
dominant:
|
|
90
|
+
The criterion contributing most. For a close decision this is the one
|
|
91
|
+
worth checking first.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
option: str
|
|
95
|
+
method: str
|
|
96
|
+
score: float
|
|
97
|
+
basis: str
|
|
98
|
+
contributions: tuple
|
|
99
|
+
dominant: str
|
|
100
|
+
|
|
101
|
+
def __str__(self) -> str:
|
|
102
|
+
lines = [
|
|
103
|
+
f"{self.option} scored {self.score:.4f} under {self.method}",
|
|
104
|
+
f" attribution: {self.basis}",
|
|
105
|
+
]
|
|
106
|
+
width = max((len(c.criterion) for c in self.contributions), default=0) + 2
|
|
107
|
+
for c in self.contributions:
|
|
108
|
+
lines.append(
|
|
109
|
+
f" {c.criterion:<{width}}{c.contribution:+.4f} ({c.share:>5.0%})"
|
|
110
|
+
)
|
|
111
|
+
if self.basis == "leave_one_out":
|
|
112
|
+
lines.append(
|
|
113
|
+
" (attributions from removing each criterion; they do not "
|
|
114
|
+
"sum to the score)"
|
|
115
|
+
)
|
|
116
|
+
return "\n".join(lines)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@dataclass(frozen=True)
|
|
120
|
+
class Margin:
|
|
121
|
+
"""Why one option beat another, criterion by criterion."""
|
|
122
|
+
|
|
123
|
+
winner: str
|
|
124
|
+
loser: str
|
|
125
|
+
method: str
|
|
126
|
+
margin: float
|
|
127
|
+
basis: str
|
|
128
|
+
rows: tuple
|
|
129
|
+
decisive: str | None = None
|
|
130
|
+
|
|
131
|
+
def __str__(self) -> str:
|
|
132
|
+
lines = [
|
|
133
|
+
f"{self.winner} beats {self.loser} by {self.margin:.4f} "
|
|
134
|
+
f"under {self.method}",
|
|
135
|
+
f" attribution: {self.basis}",
|
|
136
|
+
]
|
|
137
|
+
width = max((len(name) for name, _ in self.rows), default=0) + 2
|
|
138
|
+
for criterion, delta in self.rows:
|
|
139
|
+
# A criterion the two options score alike separates them not at
|
|
140
|
+
# all; saying it "favours" either would misread a tie.
|
|
141
|
+
if delta == 0:
|
|
142
|
+
side = "no difference"
|
|
143
|
+
else:
|
|
144
|
+
side = "favours " + (self.winner if delta > 0 else self.loser)
|
|
145
|
+
lines.append(f" {criterion:<{width}}{delta:+.4f} {side}")
|
|
146
|
+
if self.decisive:
|
|
147
|
+
lines.append(
|
|
148
|
+
f" {self.decisive} is decisive: without it the result reverses"
|
|
149
|
+
)
|
|
150
|
+
return "\n".join(lines)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _oriented_normalised(result: Result):
|
|
154
|
+
"""The matrix as the method saw it, plus the weights it applied."""
|
|
155
|
+
from .methods import get as get_method
|
|
156
|
+
from .methods.base import Wants
|
|
157
|
+
from .normalization import normalize
|
|
158
|
+
from .orientation import orient
|
|
159
|
+
|
|
160
|
+
decision = result.decision
|
|
161
|
+
method = get_method(result.method)
|
|
162
|
+
|
|
163
|
+
if method.wants is Wants.RAW:
|
|
164
|
+
data = np.asarray(decision.matrix, dtype=float)
|
|
165
|
+
else:
|
|
166
|
+
data = orient(decision.matrix, decision.directions)
|
|
167
|
+
|
|
168
|
+
if method.normalization is not None:
|
|
169
|
+
data = normalize(data, method.normalization)
|
|
170
|
+
|
|
171
|
+
return data, decision.normalized_weights
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _exact_contributions(result: Result, index: int):
|
|
175
|
+
"""Per-criterion contributions for an additive method."""
|
|
176
|
+
data, weights = _oriented_normalised(result)
|
|
177
|
+
|
|
178
|
+
if result.method == "spotis":
|
|
179
|
+
# SPOTIS is additive in the distance, and the score is its negation:
|
|
180
|
+
# each criterion contributes -w * d, so the parts still sum to the
|
|
181
|
+
# score and a larger (less negative) part is a better one.
|
|
182
|
+
from .methods.spotis import spotis
|
|
183
|
+
|
|
184
|
+
decision = result.decision
|
|
185
|
+
bounds = [c.bounds for c in decision.criteria]
|
|
186
|
+
lo = np.array(
|
|
187
|
+
[
|
|
188
|
+
b[0] if b else float(np.min(decision.matrix[:, j]))
|
|
189
|
+
for j, b in enumerate(bounds)
|
|
190
|
+
]
|
|
191
|
+
)
|
|
192
|
+
hi = np.array(
|
|
193
|
+
[
|
|
194
|
+
b[1] if b else float(np.max(decision.matrix[:, j]))
|
|
195
|
+
for j, b in enumerate(bounds)
|
|
196
|
+
]
|
|
197
|
+
)
|
|
198
|
+
span = np.where(hi - lo == 0, 1.0, hi - lo)
|
|
199
|
+
ideal = np.where(np.asarray(decision.directions) == "cost", lo, hi)
|
|
200
|
+
del spotis
|
|
201
|
+
return -weights * np.abs(decision.matrix[index] - ideal) / span
|
|
202
|
+
|
|
203
|
+
if result.method == "simple_scoring":
|
|
204
|
+
# Ignores weights by design, so each criterion contributes its own
|
|
205
|
+
# oriented value.
|
|
206
|
+
return data[index]
|
|
207
|
+
|
|
208
|
+
return weights * data[index]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _leave_one_out_contributions(result: Result, index: int):
|
|
212
|
+
"""Attribution by removal, for a method that does not decompose.
|
|
213
|
+
|
|
214
|
+
A criterion's importance is how much the option's score changes when that
|
|
215
|
+
criterion is dropped and the problem re-scored. Dropping a criterion means
|
|
216
|
+
setting its weight to zero, which is what "this criterion did not matter"
|
|
217
|
+
means in the model, rather than deleting a column and changing the shape
|
|
218
|
+
of the problem.
|
|
219
|
+
"""
|
|
220
|
+
import dataclasses
|
|
221
|
+
|
|
222
|
+
from .ranking import score
|
|
223
|
+
from .types import Decision
|
|
224
|
+
|
|
225
|
+
decision = result.decision
|
|
226
|
+
baseline = float(result.scores[index])
|
|
227
|
+
weights = decision.weights
|
|
228
|
+
|
|
229
|
+
contributions = []
|
|
230
|
+
for j in range(decision.n_criteria):
|
|
231
|
+
muted = weights.astype(float).copy()
|
|
232
|
+
muted[j] = 0.0
|
|
233
|
+
if muted.sum() <= 0:
|
|
234
|
+
# A single-criterion problem: everything rests on it.
|
|
235
|
+
contributions.append(baseline)
|
|
236
|
+
continue
|
|
237
|
+
criteria = [
|
|
238
|
+
dataclasses.replace(c, weight=float(w))
|
|
239
|
+
for c, w in zip(decision.criteria, muted)
|
|
240
|
+
]
|
|
241
|
+
without = Decision(decision.matrix, criteria, decision.labels)
|
|
242
|
+
scores, _free, _messages = score(without, result.method)
|
|
243
|
+
contributions.append(baseline - float(scores[index]))
|
|
244
|
+
return np.array(contributions)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def explain(result: Result, option: str | None = None) -> Explanation:
|
|
248
|
+
"""Explain how one option's score arose.
|
|
249
|
+
|
|
250
|
+
Parameters
|
|
251
|
+
----------
|
|
252
|
+
result:
|
|
253
|
+
A :class:`~mcdakit.types.Result` from :func:`~mcdakit.rank`.
|
|
254
|
+
option:
|
|
255
|
+
Which option to explain. Defaults to the winner, since that is the one
|
|
256
|
+
a reader will question first.
|
|
257
|
+
|
|
258
|
+
Returns
|
|
259
|
+
-------
|
|
260
|
+
Explanation
|
|
261
|
+
Per-criterion contributions, and whether they are an exact
|
|
262
|
+
decomposition or attributions obtained by leaving each criterion out.
|
|
263
|
+
"""
|
|
264
|
+
if not isinstance(result, Result):
|
|
265
|
+
raise McdaError(
|
|
266
|
+
f"explain() takes a Result from rank(), got {type(result).__name__}."
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
decision = result.decision
|
|
270
|
+
label = option if option is not None else result.winner
|
|
271
|
+
try:
|
|
272
|
+
index = decision.labels.index(label)
|
|
273
|
+
except ValueError as exc:
|
|
274
|
+
raise McdaError(f"No option named {label!r}.") from exc
|
|
275
|
+
|
|
276
|
+
if result.method in ADDITIVE:
|
|
277
|
+
basis = "exact"
|
|
278
|
+
raw = _exact_contributions(result, index)
|
|
279
|
+
else:
|
|
280
|
+
basis = "leave_one_out"
|
|
281
|
+
raw = _leave_one_out_contributions(result, index)
|
|
282
|
+
|
|
283
|
+
total = float(np.sum(np.abs(raw))) or 1.0
|
|
284
|
+
contributions = tuple(
|
|
285
|
+
Contribution(
|
|
286
|
+
criterion=criterion.name,
|
|
287
|
+
value=float(decision.matrix[index, j]),
|
|
288
|
+
weight=float(criterion.weight),
|
|
289
|
+
contribution=float(raw[j]),
|
|
290
|
+
share=float(abs(raw[j]) / total),
|
|
291
|
+
)
|
|
292
|
+
for j, criterion in enumerate(decision.criteria)
|
|
293
|
+
)
|
|
294
|
+
ordered = tuple(sorted(contributions, key=lambda c: -abs(c.contribution)))
|
|
295
|
+
|
|
296
|
+
return Explanation(
|
|
297
|
+
option=label,
|
|
298
|
+
method=result.method,
|
|
299
|
+
score=float(result.scores[index]),
|
|
300
|
+
basis=basis,
|
|
301
|
+
contributions=ordered,
|
|
302
|
+
dominant=ordered[0].criterion,
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def compare(result: Result, winner: str, loser: str) -> Margin:
|
|
307
|
+
"""Explain why one option outranked another.
|
|
308
|
+
|
|
309
|
+
The margin between two options is decomposed by criterion, so a reader can
|
|
310
|
+
see which criteria favoured the winner and which worked against it. A
|
|
311
|
+
criterion is reported as *decisive* when reversing its contribution alone
|
|
312
|
+
would reverse the outcome --- the case where a single disputed judgement
|
|
313
|
+
determines the recommendation, and the one most worth knowing about.
|
|
314
|
+
"""
|
|
315
|
+
first = explain(result, winner)
|
|
316
|
+
second = explain(result, loser)
|
|
317
|
+
|
|
318
|
+
if first.score < second.score:
|
|
319
|
+
raise McdaError(
|
|
320
|
+
f"{winner!r} did not outrank {loser!r} ({first.score:.4f} vs "
|
|
321
|
+
f"{second.score:.4f}). Pass the higher-scoring option first."
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
by_name = {c.criterion: c.contribution for c in second.contributions}
|
|
325
|
+
rows = tuple(
|
|
326
|
+
(c.criterion, c.contribution - by_name[c.criterion])
|
|
327
|
+
for c in sorted(first.contributions, key=lambda c: c.criterion)
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
margin = first.score - second.score
|
|
331
|
+
decisive = None
|
|
332
|
+
for criterion, delta in rows:
|
|
333
|
+
# Removing this criterion's advantage would put the loser ahead.
|
|
334
|
+
if delta > 0 and delta > margin:
|
|
335
|
+
decisive = criterion
|
|
336
|
+
break
|
|
337
|
+
|
|
338
|
+
return Margin(
|
|
339
|
+
winner=winner,
|
|
340
|
+
loser=loser,
|
|
341
|
+
method=result.method,
|
|
342
|
+
margin=float(margin),
|
|
343
|
+
basis=first.basis,
|
|
344
|
+
rows=tuple(sorted(rows, key=lambda r: -abs(r[1]))),
|
|
345
|
+
decisive=decisive,
|
|
346
|
+
)
|
mcdakit/group.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
"""Decisions made by several people.
|
|
2
|
+
|
|
3
|
+
Two people scoring the same options rarely agree, and the interesting question
|
|
4
|
+
is not only "what did the group decide?" but "how much did they disagree, and
|
|
5
|
+
does the answer survive that disagreement?" A consensus ranking that hides a
|
|
6
|
+
6-2 split is the same failure as a point estimate that hides its error bars.
|
|
7
|
+
|
|
8
|
+
There are two honest ways to combine several stakeholders, and they answer
|
|
9
|
+
different questions:
|
|
10
|
+
|
|
11
|
+
**Aggregate the scores, then rank once** (:func:`aggregate_scores`). Treats the
|
|
12
|
+
group as one better-informed judge: average what each person thought each
|
|
13
|
+
option was worth, then run a method over the averages. Right when the
|
|
14
|
+
participants are measuring the same thing and their differences are noise.
|
|
15
|
+
|
|
16
|
+
**Rank separately, then combine the rankings** (:func:`aggregate_rankings`).
|
|
17
|
+
Treats each participant as a voter with their own legitimate view. Right when
|
|
18
|
+
the differences are real preferences rather than measurement error, and when
|
|
19
|
+
you do not want one person's outlying score to drag the average.
|
|
20
|
+
|
|
21
|
+
They can disagree, and when they do that is a finding about the group, not a
|
|
22
|
+
defect. :func:`group_rank` reports both by default.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from collections.abc import Sequence
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
|
|
31
|
+
from .ranking import rank
|
|
32
|
+
from .types import Criterion, Decision, McdaError
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"Participant",
|
|
36
|
+
"aggregate_rankings",
|
|
37
|
+
"aggregate_scores",
|
|
38
|
+
"disagreement",
|
|
39
|
+
"group_rank",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Participant:
|
|
44
|
+
"""One stakeholder's view of the same decision.
|
|
45
|
+
|
|
46
|
+
Parameters
|
|
47
|
+
----------
|
|
48
|
+
name:
|
|
49
|
+
Who this is. Used in the disagreement report.
|
|
50
|
+
matrix:
|
|
51
|
+
Their scores. Must cover the same options and criteria as everyone
|
|
52
|
+
else, in the same order — see :func:`group_rank` for why.
|
|
53
|
+
weight:
|
|
54
|
+
How much this participant counts. Equal by default. A chair with a
|
|
55
|
+
casting vote, or a domain expert weighted above a generalist, is
|
|
56
|
+
expressed here rather than by duplicating their row.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(self, name: str, matrix, weight: float = 1.0):
|
|
60
|
+
if not str(name).strip():
|
|
61
|
+
raise McdaError("Every participant needs a name.")
|
|
62
|
+
weight = float(weight)
|
|
63
|
+
if weight < 0 or not np.isfinite(weight):
|
|
64
|
+
raise McdaError(
|
|
65
|
+
f"Participant {name!r}: weight must be a non-negative finite "
|
|
66
|
+
f"number, got {weight}."
|
|
67
|
+
)
|
|
68
|
+
self.name = str(name)
|
|
69
|
+
self.matrix = np.asarray(matrix, dtype=float)
|
|
70
|
+
self.weight = weight
|
|
71
|
+
|
|
72
|
+
def __repr__(self) -> str: # pragma: no cover - debugging aid
|
|
73
|
+
return f"<Participant {self.name!r} weight={self.weight}>"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _check(participants: Sequence[Participant], criteria: Sequence[Criterion]):
|
|
77
|
+
"""Refuse a group whose members are not judging the same problem.
|
|
78
|
+
|
|
79
|
+
The mistake this prevents: participants scoring different option sets get
|
|
80
|
+
averaged over different numbers of people, so an option only one person
|
|
81
|
+
rated is compared against options everyone rated. The result looks
|
|
82
|
+
authoritative and is computed from uneven evidence.
|
|
83
|
+
"""
|
|
84
|
+
if not participants:
|
|
85
|
+
raise McdaError("A group decision needs at least one participant.")
|
|
86
|
+
if len(participants) < 2:
|
|
87
|
+
raise McdaError(
|
|
88
|
+
"A group decision needs at least two participants; with one there "
|
|
89
|
+
"is nothing to combine. Use rank() instead."
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
shapes = {p.matrix.shape for p in participants}
|
|
93
|
+
if len(shapes) > 1:
|
|
94
|
+
detail = ", ".join(f"{p.name} {p.matrix.shape}" for p in participants)
|
|
95
|
+
raise McdaError(
|
|
96
|
+
f"Participants are not scoring the same problem: {detail}. Every "
|
|
97
|
+
f"matrix must have the same options (rows) and criteria "
|
|
98
|
+
f"(columns), in the same order, or their scores would be averaged "
|
|
99
|
+
f"over different people."
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
rows, cols = participants[0].matrix.shape
|
|
103
|
+
if cols != len(criteria):
|
|
104
|
+
raise McdaError(
|
|
105
|
+
f"Each participant scored {cols} criteria but {len(criteria)} were given."
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
total = sum(p.weight for p in participants)
|
|
109
|
+
if total <= 0:
|
|
110
|
+
raise McdaError(
|
|
111
|
+
"Participant weights are all zero, so nobody influences the result."
|
|
112
|
+
)
|
|
113
|
+
return rows, cols
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _participant_weights(participants: Sequence[Participant]) -> np.ndarray:
|
|
117
|
+
weights = np.array([p.weight for p in participants], dtype=float)
|
|
118
|
+
return weights / weights.sum()
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def aggregate_scores(
|
|
122
|
+
participants: Sequence[Participant],
|
|
123
|
+
criteria: Sequence[Criterion],
|
|
124
|
+
labels: Sequence[str] | None = None,
|
|
125
|
+
) -> Decision:
|
|
126
|
+
"""Average the participants' scores into one decision matrix.
|
|
127
|
+
|
|
128
|
+
The weighted mean, cell by cell. Treats the group as a single
|
|
129
|
+
better-informed judge, which is the right model when the participants are
|
|
130
|
+
estimating the same underlying quantity and differ only by noise.
|
|
131
|
+
|
|
132
|
+
It is the wrong model when they hold genuinely different preferences: an
|
|
133
|
+
average of 9 and 2 is 5.5, a value neither person would recognise, and
|
|
134
|
+
nothing in the resulting ranking records that they disagreed. Pair it with
|
|
135
|
+
:func:`disagreement`, which is what :func:`group_rank` does.
|
|
136
|
+
"""
|
|
137
|
+
_check(participants, criteria)
|
|
138
|
+
shares = _participant_weights(participants)
|
|
139
|
+
stacked = np.stack([p.matrix for p in participants])
|
|
140
|
+
averaged = np.tensordot(shares, stacked, axes=(0, 0))
|
|
141
|
+
return Decision(averaged, criteria, labels)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def aggregate_rankings(
|
|
145
|
+
participants: Sequence[Participant],
|
|
146
|
+
criteria: Sequence[Criterion],
|
|
147
|
+
method: str = "weighted_scoring",
|
|
148
|
+
labels: Sequence[str] | None = None,
|
|
149
|
+
**kwargs,
|
|
150
|
+
) -> dict:
|
|
151
|
+
"""Rank for each participant separately, then combine the rankings.
|
|
152
|
+
|
|
153
|
+
Borda count over each participant's ordering: an option placed first by
|
|
154
|
+
someone earns ``n - 1`` points from them, second earns ``n - 2``, and so
|
|
155
|
+
on, weighted by that participant's weight. Ties share the average of the
|
|
156
|
+
positions they span, so a tie cannot invent a preference nobody expressed.
|
|
157
|
+
|
|
158
|
+
Unlike :func:`aggregate_scores` this is insensitive to *how far apart* the
|
|
159
|
+
scores were — only to the order each person put them in. That is a
|
|
160
|
+
weakness when the magnitudes are meaningful and a strength when one
|
|
161
|
+
participant's outlying score would otherwise drag the mean.
|
|
162
|
+
|
|
163
|
+
Returns ``{"scores", "order", "per_participant"}``, where
|
|
164
|
+
``per_participant`` maps each name to their own :class:`~mcdakit.Result`.
|
|
165
|
+
"""
|
|
166
|
+
n_options, _ = _check(participants, criteria)
|
|
167
|
+
shares = _participant_weights(participants)
|
|
168
|
+
|
|
169
|
+
points = np.zeros(n_options)
|
|
170
|
+
per_participant = {}
|
|
171
|
+
|
|
172
|
+
for participant, share in zip(participants, shares):
|
|
173
|
+
result = rank(
|
|
174
|
+
participant.matrix,
|
|
175
|
+
criteria,
|
|
176
|
+
method=method,
|
|
177
|
+
labels=labels,
|
|
178
|
+
**kwargs,
|
|
179
|
+
)
|
|
180
|
+
per_participant[participant.name] = result
|
|
181
|
+
# Borda points from competition ranks, so tied options score equally
|
|
182
|
+
# rather than being separated by the order they happen to be listed.
|
|
183
|
+
points += share * (n_options - result.ranks)
|
|
184
|
+
|
|
185
|
+
order = sorted(range(n_options), key=lambda i: -points[i])
|
|
186
|
+
names = tuple(
|
|
187
|
+
labels if labels is not None else [f"Option {i + 1}" for i in range(n_options)]
|
|
188
|
+
)
|
|
189
|
+
return {
|
|
190
|
+
"scores": points,
|
|
191
|
+
"order": [names[i] for i in order],
|
|
192
|
+
"per_participant": per_participant,
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def disagreement(
|
|
197
|
+
participants: Sequence[Participant],
|
|
198
|
+
criteria: Sequence[Criterion],
|
|
199
|
+
labels: Sequence[str] | None = None,
|
|
200
|
+
) -> dict:
|
|
201
|
+
"""How far apart the participants were, per option and per criterion.
|
|
202
|
+
|
|
203
|
+
Reported as the standard deviation of the scores each cell received,
|
|
204
|
+
unweighted — the question is how much the people differed, not how much
|
|
205
|
+
the chair's opinion outweighs the rest.
|
|
206
|
+
|
|
207
|
+
A mean of 5.5 that everybody agreed on and one that averages 9 and 2 are
|
|
208
|
+
the same number and completely different findings. This is what tells them
|
|
209
|
+
apart.
|
|
210
|
+
|
|
211
|
+
Returns ``overall``, ``by_option``, ``by_criterion``, and ``most_contested``
|
|
212
|
+
naming the option and criterion with the widest spread.
|
|
213
|
+
"""
|
|
214
|
+
_check(participants, criteria)
|
|
215
|
+
stacked = np.stack([p.matrix for p in participants])
|
|
216
|
+
spread = stacked.std(axis=0)
|
|
217
|
+
|
|
218
|
+
names = (
|
|
219
|
+
list(labels)
|
|
220
|
+
if labels is not None
|
|
221
|
+
else [f"Option {i + 1}" for i in range(spread.shape[0])]
|
|
222
|
+
)
|
|
223
|
+
criterion_names = [c.name for c in criteria]
|
|
224
|
+
|
|
225
|
+
by_option = dict(zip(names, spread.mean(axis=1)))
|
|
226
|
+
by_criterion = dict(zip(criterion_names, spread.mean(axis=0)))
|
|
227
|
+
|
|
228
|
+
return {
|
|
229
|
+
"overall": float(spread.mean()),
|
|
230
|
+
"by_option": {k: float(v) for k, v in by_option.items()},
|
|
231
|
+
"by_criterion": {k: float(v) for k, v in by_criterion.items()},
|
|
232
|
+
"most_contested_option": max(by_option, key=lambda k: by_option[k]),
|
|
233
|
+
"most_contested_criterion": max(by_criterion, key=lambda k: by_criterion[k]),
|
|
234
|
+
"spread": spread,
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def group_rank(
|
|
239
|
+
participants: Sequence[Participant],
|
|
240
|
+
criteria: Sequence[Criterion],
|
|
241
|
+
method: str = "weighted_scoring",
|
|
242
|
+
labels: Sequence[str] | None = None,
|
|
243
|
+
**kwargs,
|
|
244
|
+
) -> dict:
|
|
245
|
+
"""Rank a decision made by several people, and say how much they agreed.
|
|
246
|
+
|
|
247
|
+
Runs both aggregations — averaging the scores, and combining each
|
|
248
|
+
participant's ranking — because they answer different questions and can
|
|
249
|
+
disagree. When they do, that disagreement is a finding about the group:
|
|
250
|
+
it means the answer depends on whether you treat the participants as
|
|
251
|
+
co-estimators of one truth or as voters with distinct views.
|
|
252
|
+
|
|
253
|
+
Returns
|
|
254
|
+
-------
|
|
255
|
+
dict
|
|
256
|
+
``result``
|
|
257
|
+
A :class:`~mcdakit.Result` from ranking the averaged scores. The
|
|
258
|
+
headline answer.
|
|
259
|
+
``borda``
|
|
260
|
+
The rank-aggregated view, from :func:`aggregate_rankings`.
|
|
261
|
+
``agree``
|
|
262
|
+
Whether the two aggregations chose the same winner.
|
|
263
|
+
``disagreement``
|
|
264
|
+
The spread report from :func:`disagreement`.
|
|
265
|
+
``per_participant``
|
|
266
|
+
Each participant's own :class:`~mcdakit.Result`.
|
|
267
|
+
``unanimous``
|
|
268
|
+
Whether every participant, ranking alone, picked the same winner.
|
|
269
|
+
|
|
270
|
+
Examples
|
|
271
|
+
--------
|
|
272
|
+
>>> from mcdakit import Criterion
|
|
273
|
+
>>> from mcdakit.group import Participant, group_rank
|
|
274
|
+
>>> criteria = [Criterion("Price", 0.5, "cost"), Criterion("Quality", 0.5)]
|
|
275
|
+
>>> alice = Participant("Alice", [[2.0, 8.0], [3.0, 6.0]])
|
|
276
|
+
>>> bob = Participant("Bob", [[2.0, 5.0], [3.0, 9.0]])
|
|
277
|
+
>>> out = group_rank([alice, bob], criteria, labels=["A", "B"])
|
|
278
|
+
>>> out["agree"]
|
|
279
|
+
True
|
|
280
|
+
"""
|
|
281
|
+
decision = aggregate_scores(participants, criteria, labels)
|
|
282
|
+
result = rank(decision, method=method, **kwargs)
|
|
283
|
+
borda = aggregate_rankings(
|
|
284
|
+
participants, criteria, method=method, labels=labels, **kwargs
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
winners = {r.winner for r in borda["per_participant"].values()}
|
|
288
|
+
|
|
289
|
+
return {
|
|
290
|
+
"result": result,
|
|
291
|
+
"borda": borda,
|
|
292
|
+
"agree": result.winner == borda["order"][0],
|
|
293
|
+
"disagreement": disagreement(participants, criteria, labels),
|
|
294
|
+
"per_participant": borda["per_participant"],
|
|
295
|
+
"unanimous": len(winners) == 1,
|
|
296
|
+
}
|