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/ai.py ADDED
@@ -0,0 +1,802 @@
1
+ """Language-model assistance, with every suggestion checked before it counts.
2
+
3
+ An LLM is useful in MCDA for the part that is genuinely hard to automate:
4
+ turning a described problem into a structured one. Naming plausible criteria,
5
+ proposing a direction for each, and drafting a first set of weights are tasks
6
+ where a model's breadth helps and where a wrong answer is cheap to spot.
7
+
8
+ It is *not* useful as an authority. A model that returns weights returns them
9
+ with the same confidence whether they are considered or invented, and nothing
10
+ in the output distinguishes the two. A package whose stated purpose is to
11
+ refuse answers it cannot stand behind must not make an exception here.
12
+
13
+ So this module inverts the usual arrangement. The model **proposes**; the
14
+ package **verifies**, and reports what the proposal is worth:
15
+
16
+ * every suggestion is parsed into the package's own validated types, so a
17
+ malformed or out-of-range answer is rejected rather than absorbed;
18
+ * proposed weights are run through :func:`~mcdakit.sensitivity`, so the
19
+ caller is told whether the recommendation would even survive the model
20
+ being somewhat wrong;
21
+ * the same question is asked more than once and the answers compared, so a
22
+ model that is guessing can be distinguished from one that is consistent;
23
+ * nothing is applied automatically. Every function returns a *proposal* the
24
+ caller must choose to accept.
25
+
26
+ The provider is injected rather than imported. ``mcdakit`` acquires no LLM
27
+ dependency: the caller supplies any callable mapping a prompt to a string,
28
+ which may wrap any vendor's client, a local model, or a fixture in a test.
29
+
30
+ >>> from mcdakit.ai import propose_criteria
31
+ >>> reply = '''[{"name": "Price", "direction": "cost", "weight": 0.6},
32
+ ... {"name": "Quality", "direction": "benefit", "weight": 0.4}]'''
33
+ >>> proposal = propose_criteria("choosing a supplier", ask=lambda p: reply)
34
+ >>> [c.name for c in proposal.criteria]
35
+ ['Price', 'Quality']
36
+ >>> proposal.accepted
37
+ False
38
+
39
+ Because the model is injected, this module is deterministic under test and
40
+ adds no network dependency to the package.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import json
46
+ import re
47
+ from collections.abc import Sequence
48
+ from dataclasses import dataclass, field
49
+ from typing import Callable
50
+
51
+ import numpy as np
52
+
53
+ from .types import Criterion, McdaError
54
+
55
+ __all__ = [
56
+ "AiError",
57
+ "AiProposal",
58
+ "ComparisonProposal",
59
+ "PanelProposal",
60
+ "WeightProposal",
61
+ "critique_weights",
62
+ "narrate",
63
+ "propose_comparisons",
64
+ "propose_criteria",
65
+ "propose_weights",
66
+ "simulate_panel",
67
+ ]
68
+
69
+ #: A provider is any callable taking a prompt and returning the model's reply.
70
+ Ask = Callable[[str], str]
71
+
72
+
73
+ class AiError(McdaError):
74
+ """A model's reply could not be turned into a valid proposal."""
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class AiProposal:
79
+ """Criteria a model suggested, and what the package makes of them.
80
+
81
+ Attributes
82
+ ----------
83
+ criteria:
84
+ Validated :class:`~mcdakit.types.Criterion` objects. A suggestion that
85
+ failed validation never reaches this list.
86
+ rejected:
87
+ Suggestions that were discarded, each with the reason. Reported rather
88
+ than dropped: a model that proposed six criteria of which two were
89
+ malformed is a different signal from one that proposed four.
90
+ agreement:
91
+ When the model was asked more than once, the share of criteria names
92
+ common to every reply. Low agreement indicates the model is
93
+ improvising, and is worth more than any single answer.
94
+ accepted:
95
+ Always ``False``. A proposal is a suggestion; applying it is the
96
+ caller's decision, made by constructing a
97
+ :class:`~mcdakit.types.Decision` from it.
98
+ """
99
+
100
+ criteria: tuple
101
+ rejected: tuple = ()
102
+ agreement: float | None = None
103
+ raw: tuple = ()
104
+ accepted: bool = False
105
+
106
+ def __str__(self) -> str:
107
+ lines = [f"{len(self.criteria)} criteria proposed:"]
108
+ for criterion in self.criteria:
109
+ lines.append(
110
+ f" {criterion.name} ({criterion.direction}, "
111
+ f"weight {criterion.weight:.2f})"
112
+ )
113
+ for name, why in self.rejected:
114
+ lines.append(f" ! discarded {name!r}: {why}")
115
+ if self.agreement is not None:
116
+ lines.append(f" agreement across replies: {self.agreement:.0%}")
117
+ lines.append(" not applied — construct a Decision to accept")
118
+ return "\n".join(lines)
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class WeightProposal:
123
+ """Weights a model suggested, checked against the data.
124
+
125
+ Attributes
126
+ ----------
127
+ weights:
128
+ Normalised to sum to one.
129
+ stability:
130
+ The :func:`~mcdakit.sensitivity` report obtained *using* these weights.
131
+ This is the point of the exercise: a model's weights may be plausible
132
+ and still produce a recommendation that a small correction overturns,
133
+ and the caller should know that before relying on them.
134
+ disagrees_with:
135
+ Objective schemes whose weights order the criteria differently. A
136
+ model that ranks importance unlike every data-driven scheme is not
137
+ necessarily wrong, but the divergence is worth surfacing.
138
+ """
139
+
140
+ weights: np.ndarray
141
+ criteria: tuple
142
+ stability: dict = field(default_factory=dict)
143
+ disagrees_with: tuple = ()
144
+ agreement: float | None = None
145
+ accepted: bool = False
146
+
147
+
148
+ def _extract_json(reply: str):
149
+ """Pull the first JSON array or object out of a model's reply.
150
+
151
+ Models wrap JSON in prose and code fences however they were prompted not
152
+ to, so the reply is searched rather than parsed whole.
153
+ """
154
+ fenced = re.search(r"```(?:json)?\s*(.+?)```", reply, re.S)
155
+ if fenced:
156
+ reply = fenced.group(1)
157
+ match = re.search(r"[\[{].*[\]}]", reply, re.S)
158
+ if not match:
159
+ raise AiError(
160
+ f"The model's reply contained no JSON. Reply began: {reply.strip()[:120]!r}"
161
+ )
162
+ try:
163
+ return json.loads(match.group(0))
164
+ except json.JSONDecodeError as exc:
165
+ raise AiError(f"The model's reply was not valid JSON: {exc}") from exc
166
+
167
+
168
+ CRITERIA_PROMPT = """You are helping set up a multi-criteria decision analysis.
169
+
170
+ Problem: {problem}
171
+
172
+ List the {n} most important criteria for this decision. Reply with JSON only,
173
+ as a list of objects with these keys:
174
+ "name": a short label
175
+ "direction": "cost" if a smaller value is better, "benefit" if larger is
176
+ "weight": relative importance, a positive number
177
+ "bounds": [low, high] plausible range, or null if unknown
178
+
179
+ Reply with the JSON array and nothing else."""
180
+
181
+
182
+ def _parse_criteria(payload) -> tuple:
183
+ """Turn a model's list into validated criteria, keeping the failures."""
184
+ if not isinstance(payload, list):
185
+ raise AiError(
186
+ f"Expected a JSON list of criteria, got {type(payload).__name__}."
187
+ )
188
+
189
+ kept, rejected = [], []
190
+ for entry in payload:
191
+ name = (entry or {}).get("name") if isinstance(entry, dict) else None
192
+ try:
193
+ bounds = entry.get("bounds")
194
+ if bounds is not None:
195
+ bounds = tuple(bounds)
196
+ kept.append(
197
+ Criterion(
198
+ name=entry["name"],
199
+ weight=float(entry.get("weight", 1.0)),
200
+ direction=entry.get("direction", "benefit"),
201
+ bounds=bounds,
202
+ )
203
+ )
204
+ except (McdaError, KeyError, TypeError, ValueError) as exc:
205
+ rejected.append((name or "<unnamed>", str(exc)))
206
+
207
+ if not kept:
208
+ raise AiError(
209
+ "No criterion in the model's reply was valid. Rejected: "
210
+ + "; ".join(f"{n}: {w}" for n, w in rejected)
211
+ )
212
+ return tuple(kept), tuple(rejected)
213
+
214
+
215
+ def propose_criteria(
216
+ problem: str,
217
+ ask: Ask,
218
+ n: int = 5,
219
+ samples: int = 1,
220
+ ) -> AiProposal:
221
+ """Ask a model to suggest criteria for a described problem.
222
+
223
+ Parameters
224
+ ----------
225
+ problem:
226
+ A description in plain language.
227
+ ask:
228
+ Any callable mapping a prompt to the model's reply. The package
229
+ imposes no vendor and acquires no dependency.
230
+ samples:
231
+ How many times to ask. Above one, the replies are compared and the
232
+ share of criteria common to all is reported as ``agreement``. Asking
233
+ twice costs twice as much and is usually worth it: a model that names
234
+ different criteria each time is improvising, which no single reply
235
+ would reveal.
236
+
237
+ Returns
238
+ -------
239
+ AiProposal
240
+ Validated criteria, the suggestions that failed validation and why,
241
+ and the agreement across replies. Nothing is applied.
242
+ """
243
+ if samples < 1:
244
+ raise McdaError("samples must be at least 1.")
245
+
246
+ prompt = CRITERIA_PROMPT.format(problem=problem, n=n)
247
+ replies = [ask(prompt) for _ in range(samples)]
248
+
249
+ parsed = [_parse_criteria(_extract_json(reply)) for reply in replies]
250
+ criteria, rejected = parsed[0]
251
+
252
+ agreement = None
253
+ if samples > 1:
254
+ name_sets = [{c.name.strip().lower() for c in kept} for kept, _ in parsed]
255
+ shared = set.intersection(*name_sets)
256
+ union = set.union(*name_sets)
257
+ agreement = len(shared) / len(union) if union else 0.0
258
+
259
+ return AiProposal(
260
+ criteria=criteria,
261
+ rejected=rejected,
262
+ agreement=agreement,
263
+ raw=tuple(replies),
264
+ )
265
+
266
+
267
+ WEIGHTS_PROMPT = """You are helping set up a multi-criteria decision analysis.
268
+
269
+ Problem: {problem}
270
+
271
+ Criteria, in order: {names}
272
+
273
+ Give each criterion a relative importance weight. Reply with JSON only: a
274
+ single object mapping each criterion name to a positive number.
275
+
276
+ Reply with the JSON object and nothing else."""
277
+
278
+
279
+ def propose_weights(
280
+ problem: str,
281
+ criteria: Sequence[Criterion],
282
+ ask: Ask,
283
+ matrix=None,
284
+ samples: int = 1,
285
+ ) -> WeightProposal:
286
+ """Ask a model to weight known criteria, and check the answer.
287
+
288
+ Where ``matrix`` is supplied, the proposed weights are used to rank the
289
+ problem and the result is passed through
290
+ :func:`~mcdakit.sensitivity`, so the caller learns not only what the model
291
+ suggested but whether the resulting recommendation is fragile. The
292
+ weights are additionally compared against the objective schemes of
293
+ :mod:`mcdakit.weighting`; any that order the criteria differently are
294
+ named in ``disagrees_with``.
295
+ """
296
+ if samples < 1:
297
+ raise McdaError("samples must be at least 1.")
298
+ criteria = tuple(criteria)
299
+ names = ", ".join(c.name for c in criteria)
300
+
301
+ prompt = WEIGHTS_PROMPT.format(problem=problem, names=names)
302
+ replies = [ask(prompt) for _ in range(samples)]
303
+
304
+ vectors = []
305
+ for reply in replies:
306
+ payload = _extract_json(reply)
307
+ if not isinstance(payload, dict):
308
+ raise AiError(
309
+ f"Expected a JSON object of weights, got {type(payload).__name__}."
310
+ )
311
+ try:
312
+ vector = np.array([float(payload[c.name]) for c in criteria], dtype=float)
313
+ except KeyError as exc:
314
+ raise AiError(
315
+ f"The model omitted a weight for {exc.args[0]!r}. It replied "
316
+ f"with: {sorted(payload)}"
317
+ ) from exc
318
+ except (TypeError, ValueError) as exc:
319
+ raise AiError(f"A weight was not a number: {exc}") from exc
320
+
321
+ if np.any(vector < 0) or not np.all(np.isfinite(vector)):
322
+ raise AiError(
323
+ "The model proposed a negative or non-finite weight; a "
324
+ "criterion cannot count against itself."
325
+ )
326
+ if vector.sum() <= 0:
327
+ raise AiError("The model proposed weights summing to zero.")
328
+ vectors.append(vector / vector.sum())
329
+
330
+ weights = vectors[0]
331
+
332
+ agreement = None
333
+ if samples > 1:
334
+ # Mean pairwise cosine similarity: how consistently the model weights
335
+ # the same problem. Reported rather than acted upon.
336
+ sims = [
337
+ float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
338
+ for i, a in enumerate(vectors)
339
+ for b in vectors[i + 1 :]
340
+ ]
341
+ agreement = float(np.mean(sims)) if sims else None
342
+
343
+ stability, disagrees = {}, ()
344
+ if matrix is not None:
345
+ stability, disagrees = _check_against_data(matrix, criteria, weights)
346
+
347
+ return WeightProposal(
348
+ weights=weights,
349
+ criteria=criteria,
350
+ stability=stability,
351
+ disagrees_with=disagrees,
352
+ agreement=agreement,
353
+ )
354
+
355
+
356
+ def _check_against_data(matrix, criteria: Sequence[Criterion], weights):
357
+ """Rank with the proposed weights, and compare them to objective schemes."""
358
+ from .ranking import rank
359
+ from .sensitivity import sensitivity
360
+ from .types import Decision
361
+ from .weighting import derive_weights
362
+
363
+ weighted = [
364
+ Criterion(c.name, float(w), c.direction, c.bounds)
365
+ for c, w in zip(criteria, weights)
366
+ ]
367
+ decision = Decision(matrix, weighted)
368
+ report = sensitivity(rank(decision))
369
+
370
+ proposed_order = tuple(np.argsort(-weights))
371
+ disagrees = []
372
+ for scheme in ("entropy", "critic", "std"):
373
+ try:
374
+ objective = derive_weights(matrix, scheme, [c.direction for c in criteria])
375
+ except McdaError: # pragma: no cover - defensive
376
+ continue
377
+ if tuple(np.argsort(-objective)) != proposed_order:
378
+ disagrees.append(scheme)
379
+
380
+ return report, tuple(disagrees)
381
+
382
+
383
+ def critique_weights(
384
+ weights: Sequence[float],
385
+ criteria: Sequence[Criterion],
386
+ matrix,
387
+ ) -> dict:
388
+ """Assess weights from any source against the data.
389
+
390
+ Separated from :func:`propose_weights` so that weights elicited from a
391
+ person, taken from a previous study, or produced by a model this package
392
+ never saw can be held to the same standard. Returns the sensitivity report
393
+ and the objective schemes that order the criteria differently.
394
+ """
395
+ vector = np.asarray(weights, dtype=float)
396
+ criteria = tuple(criteria)
397
+ if vector.shape != (len(criteria),):
398
+ raise McdaError(f"Got {vector.shape} weights for {len(criteria)} criteria.")
399
+ if np.any(vector < 0) or vector.sum() <= 0:
400
+ raise McdaError("Weights must be non-negative and not all zero.")
401
+
402
+ vector = vector / vector.sum()
403
+ report, disagrees = _check_against_data(matrix, criteria, vector)
404
+ return {
405
+ "weights": vector,
406
+ "stability": report,
407
+ "disagrees_with": disagrees,
408
+ }
409
+
410
+
411
+ # --------------------------------------------------------------------------
412
+ # Pairwise comparison, checked for self-contradiction
413
+ # --------------------------------------------------------------------------
414
+
415
+ COMPARISON_PROMPT = """You are helping set up a multi-criteria decision analysis.
416
+
417
+ Problem: {problem}
418
+
419
+ Criteria, numbered from 0: {names}
420
+
421
+ For each pair, say how much more important the first is than the second, on
422
+ Saaty's scale: 9 extremely more, 7 very strongly, 5 strongly, 3 moderately,
423
+ 1 equally, and 1/3, 1/5, 1/7, 1/9 for the reverse.
424
+
425
+ Reply with JSON only: a list of objects with keys "i", "j" and "ratio",
426
+ covering every pair with i < j. Reply with the JSON array and nothing else."""
427
+
428
+
429
+ @dataclass(frozen=True)
430
+ class ComparisonProposal:
431
+ """Pairwise judgements a model made, and whether they cohere.
432
+
433
+ The value of routing an LLM through pairwise comparison rather than asking
434
+ for weights directly is that the answer is checkable. Saying price matters
435
+ three times quality, quality three times delivery, and price twice
436
+ delivery is a contradiction, and Saaty's consistency ratio detects it
437
+ without anyone knowing what the right weights were.
438
+
439
+ Attributes
440
+ ----------
441
+ consistency_ratio:
442
+ Saaty's CI/RI. At or below :data:`~mcdakit.CONSISTENCY_LIMIT` (0.10)
443
+ the judgements hold together.
444
+ consistent:
445
+ Whether that threshold was met. Reported, never enforced: an
446
+ inconsistent panel of judgements is a reason to ask again, and the
447
+ caller decides.
448
+ """
449
+
450
+ judgements: dict
451
+ weights: np.ndarray
452
+ criteria: tuple
453
+ consistency_ratio: float
454
+ consistent: bool
455
+ agreement: float | None = None
456
+ accepted: bool = False
457
+
458
+ def __str__(self) -> str:
459
+ lines = [
460
+ f"{len(self.judgements)} pairwise judgements, "
461
+ f"consistency ratio {self.consistency_ratio:.3f} "
462
+ f"({'consistent' if self.consistent else 'INCONSISTENT'})"
463
+ ]
464
+ width = max((len(c.name) for c in self.criteria), default=0) + 2
465
+ for criterion, weight in zip(self.criteria, self.weights):
466
+ lines.append(f" {criterion.name:<{width}}{weight:.4f}")
467
+ if not self.consistent:
468
+ lines.append(
469
+ " ! the judgements contradict each other; ask again or "
470
+ "revise them by hand"
471
+ )
472
+ lines.append(" not applied — construct a Decision to accept")
473
+ return "\n".join(lines)
474
+
475
+
476
+ def propose_comparisons(
477
+ problem: str,
478
+ criteria: Sequence[Criterion],
479
+ ask: Ask,
480
+ samples: int = 1,
481
+ ) -> ComparisonProposal:
482
+ """Ask a model to compare criteria pairwise, and check it contradicts
483
+ itself no more than Saaty allows.
484
+
485
+ Asking for pairwise judgements rather than for weights directly is the
486
+ point: *is price more important than quality, and by how much* is a
487
+ question with a checkable answer, whereas a weight vector is not. The
488
+ model's replies are assembled into a reciprocal matrix and put through
489
+ :func:`~mcdakit.ahp_weights`, so a model that answers inconsistently is
490
+ detected by arithmetic rather than by inspection.
491
+ """
492
+ if samples < 1:
493
+ raise McdaError("samples must be at least 1.")
494
+ criteria = tuple(criteria)
495
+ if len(criteria) < 2:
496
+ raise McdaError(
497
+ "Pairwise comparison needs at least two criteria; with one there "
498
+ "is nothing to compare."
499
+ )
500
+
501
+ names = ", ".join(f"{i}: {c.name}" for i, c in enumerate(criteria))
502
+ prompt = COMPARISON_PROMPT.format(problem=problem, names=names)
503
+ replies = [ask(prompt) for _ in range(samples)]
504
+
505
+ parsed = [_parse_comparisons(_extract_json(r), len(criteria)) for r in replies]
506
+ judgements = parsed[0]
507
+
508
+ from .ahp import ahp_weights
509
+
510
+ outcome = ahp_weights(judgements, names=[c.name for c in criteria])
511
+
512
+ agreement = None
513
+ if samples > 1:
514
+ # How consistently the model judges the same pairs, measured as the
515
+ # mean absolute difference in log-ratio — the natural scale for a
516
+ # multiplicative comparison, where 3 and 1/3 are equally far from 1.
517
+ gaps = []
518
+ for i, first in enumerate(parsed):
519
+ for second in parsed[i + 1 :]:
520
+ shared = set(first) & set(second)
521
+ if shared:
522
+ gaps.append(
523
+ float(
524
+ np.mean(
525
+ [
526
+ abs(np.log(first[k]) - np.log(second[k]))
527
+ for k in shared
528
+ ]
529
+ )
530
+ )
531
+ )
532
+ if gaps:
533
+ # Map a mean log gap to [0, 1]: identical judgements score 1.
534
+ agreement = float(np.exp(-np.mean(gaps)))
535
+
536
+ return ComparisonProposal(
537
+ judgements=judgements,
538
+ weights=outcome["weights"],
539
+ criteria=criteria,
540
+ consistency_ratio=float(outcome["consistency_ratio"]),
541
+ consistent=bool(outcome["consistent"]),
542
+ agreement=agreement,
543
+ )
544
+
545
+
546
+ def _parse_comparisons(payload, n_criteria: int) -> dict:
547
+ """Turn a model's pair list into ``{(i, j): ratio}``."""
548
+ if not isinstance(payload, list):
549
+ raise AiError(
550
+ f"Expected a JSON list of comparisons, got {type(payload).__name__}."
551
+ )
552
+ judgements = {}
553
+ for entry in payload:
554
+ try:
555
+ i, j = int(entry["i"]), int(entry["j"])
556
+ ratio = float(entry["ratio"])
557
+ except (KeyError, TypeError, ValueError) as exc:
558
+ raise AiError(
559
+ f"A comparison was malformed; each needs i, j and ratio: {exc}"
560
+ ) from exc
561
+ if not (0 <= i < n_criteria and 0 <= j < n_criteria):
562
+ raise AiError(
563
+ f"Comparison ({i}, {j}) is out of range for {n_criteria} criteria."
564
+ )
565
+ if i == j:
566
+ raise AiError("A criterion cannot be compared with itself.")
567
+ if ratio <= 0 or not np.isfinite(ratio):
568
+ raise AiError(
569
+ f"Comparison ({i}, {j}) needs a positive finite ratio, got {ratio}."
570
+ )
571
+ judgements[(i, j)] = ratio
572
+ if not judgements:
573
+ raise AiError("The model returned no comparisons.")
574
+ return judgements
575
+
576
+
577
+ # --------------------------------------------------------------------------
578
+ # Simulated expert panel
579
+ # --------------------------------------------------------------------------
580
+
581
+ PANEL_PROMPT = """You are participating in a decision panel as: {persona}
582
+
583
+ Problem: {problem}
584
+
585
+ Score each option on each criterion, from the perspective of your role.
586
+ Options, in order: {options}
587
+ Criteria, in order: {names}
588
+
589
+ Reply with JSON only: a list of rows, one per option, each a list of numbers
590
+ one per criterion, in the orders given. Reply with the JSON array and nothing
591
+ else."""
592
+
593
+
594
+ @dataclass(frozen=True)
595
+ class PanelProposal:
596
+ """A panel of simulated experts, and how far apart they were.
597
+
598
+ Human expert panels are expensive to convene, hard to assemble across
599
+ disciplines, and — because the same panel cannot be run twice — not
600
+ reproducible. A simulated panel is reproducible by construction and costs
601
+ a prompt, at the price of being a model's impression of an expert rather
602
+ than an expert.
603
+
604
+ That trade is only acceptable if the output is scrutinised, so the
605
+ participants returned here are ordinary
606
+ :class:`~mcdakit.group.Participant` objects and go through the same
607
+ :func:`~mcdakit.group.group_rank` and
608
+ :func:`~mcdakit.group.disagreement` machinery as a real panel. A
609
+ simulated panel that agrees suspiciously closely is itself a finding, and
610
+ ``spread`` is what shows it.
611
+
612
+ Attributes
613
+ ----------
614
+ participants:
615
+ One per persona, ready for :func:`~mcdakit.group.group_rank`.
616
+ spread:
617
+ Mean standard deviation of the scores across personas. Near zero means
618
+ the personas did not actually differ, and the panel added nothing over
619
+ asking once.
620
+ """
621
+
622
+ participants: tuple
623
+ personas: tuple
624
+ criteria: tuple
625
+ labels: tuple
626
+ spread: float
627
+ rejected: tuple = ()
628
+ accepted: bool = False
629
+
630
+ def __str__(self) -> str:
631
+ lines = [f"{len(self.participants)} simulated participants:"]
632
+ for participant in self.participants:
633
+ lines.append(f" {participant.name}")
634
+ for persona, why in self.rejected:
635
+ lines.append(f" ! discarded {persona!r}: {why}")
636
+ lines.append(f" spread across personas: {self.spread:.3f}")
637
+ if self.spread < 1e-9:
638
+ lines.append(
639
+ " ! the personas produced identical scores; the panel adds "
640
+ "nothing over a single opinion"
641
+ )
642
+ lines.append(" not applied — pass to group_rank() to combine")
643
+ return "\n".join(lines)
644
+
645
+
646
+ def simulate_panel(
647
+ problem: str,
648
+ criteria: Sequence[Criterion],
649
+ personas: Sequence[str],
650
+ labels: Sequence[str],
651
+ ask: Ask,
652
+ ):
653
+ """Ask a model to score the problem once per expert persona.
654
+
655
+ Each persona is prompted separately and scores every option on every
656
+ criterion, producing a :class:`~mcdakit.group.Participant`. The result is
657
+ an ordinary panel: combine it with
658
+ :func:`~mcdakit.group.group_rank`, which reports both aggregations and
659
+ where the personas disagreed.
660
+
661
+ A persona whose reply is malformed or the wrong shape is discarded with
662
+ its reason rather than silently dropped, since a panel of three that
663
+ became a panel of two is a different panel.
664
+
665
+ Parameters
666
+ ----------
667
+ personas:
668
+ Short role descriptions, for example ``"cost analyst"`` or
669
+ ``"sustainability officer"``. Distinct roles are the point; identical
670
+ ones produce identical scores and a spread of zero, which the result
671
+ flags.
672
+ """
673
+ from .group import Participant
674
+
675
+ criteria = tuple(criteria)
676
+ labels = tuple(labels)
677
+ personas = tuple(personas)
678
+
679
+ if len(personas) < 2:
680
+ raise McdaError(
681
+ "A panel needs at least two personas; with one there is nothing "
682
+ "to compare. Use propose_weights() instead."
683
+ )
684
+
685
+ names = ", ".join(c.name for c in criteria)
686
+ options = ", ".join(labels)
687
+
688
+ participants, rejected = [], []
689
+ for persona in personas:
690
+ prompt = PANEL_PROMPT.format(
691
+ persona=persona, problem=problem, options=options, names=names
692
+ )
693
+ try:
694
+ payload = _extract_json(ask(prompt))
695
+ matrix = np.asarray(payload, dtype=float)
696
+ if matrix.shape != (len(labels), len(criteria)):
697
+ raise AiError(
698
+ f"expected a {len(labels)}x{len(criteria)} matrix, got "
699
+ f"{matrix.shape}"
700
+ )
701
+ if not np.all(np.isfinite(matrix)):
702
+ raise AiError("the scores contain NaN or infinity")
703
+ participants.append(Participant(persona, matrix))
704
+ except (AiError, McdaError, TypeError, ValueError) as exc:
705
+ rejected.append((persona, str(exc)))
706
+
707
+ if len(participants) < 2:
708
+ raise AiError(
709
+ "Fewer than two personas produced a usable panel. Rejected: "
710
+ + "; ".join(f"{p}: {w}" for p, w in rejected)
711
+ )
712
+
713
+ stacked = np.stack([p.matrix for p in participants])
714
+ spread = float(stacked.std(axis=0).mean())
715
+
716
+ return PanelProposal(
717
+ participants=tuple(participants),
718
+ personas=personas,
719
+ criteria=criteria,
720
+ labels=labels,
721
+ spread=spread,
722
+ rejected=tuple(rejected),
723
+ )
724
+
725
+
726
+ # --------------------------------------------------------------------------
727
+ # Narration
728
+ # --------------------------------------------------------------------------
729
+
730
+ NARRATE_PROMPT = """Write a short paragraph for a decision report, using only
731
+ the figures below. Do not introduce numbers that do not appear here, and do
732
+ not round them differently.
733
+
734
+ {facts}
735
+
736
+ Reply with the paragraph and nothing else."""
737
+
738
+
739
+ def narrate(result, ask: Ask, sensitivity_report: dict | None = None) -> dict:
740
+ """Turn a result into a paragraph, and check the model kept to the figures.
741
+
742
+ The model is given the computed facts and asked to write them up. It is
743
+ not asked to analyse anything: everything in the prompt has already been
744
+ calculated, so the only failure available to it is misstating a number —
745
+ and that is checkable.
746
+
747
+ Every numeric literal in the reply is therefore compared against the
748
+ figures supplied. Any that does not appear is listed in
749
+ ``unsupported_numbers``, which is the thing worth reading before pasting
750
+ the text into a report.
751
+
752
+ Returns
753
+ -------
754
+ dict
755
+ ``text`` the paragraph, ``facts`` what the model was given,
756
+ ``unsupported_numbers`` any figure in the text that was not among
757
+ them, and ``faithful`` whether that list is empty.
758
+ """
759
+ from .types import Result
760
+
761
+ if not isinstance(result, Result):
762
+ raise McdaError(
763
+ f"narrate() takes a Result from rank(), got {type(result).__name__}."
764
+ )
765
+
766
+ lines = [
767
+ f"Method: {result.method}",
768
+ f"Recommended: {result.winner}",
769
+ "Ranking:",
770
+ ]
771
+ supported = set()
772
+ for label, score in result.ranking:
773
+ lines.append(f" {label}: {score:.4f}")
774
+ supported.add(f"{score:.4f}")
775
+
776
+ if sensitivity_report:
777
+ level = sensitivity_report.get("level")
778
+ overall = sensitivity_report.get("overall")
779
+ lines.append(f"Stability: {level}")
780
+ if overall is not None:
781
+ percent = f"{overall * 100:.1f}"
782
+ lines.append(
783
+ f" the winner changes if {sensitivity_report.get('weakest')} "
784
+ f"moves by {percent}%"
785
+ )
786
+ supported.add(percent)
787
+
788
+ facts = "\n".join(lines)
789
+ text = ask(NARRATE_PROMPT.format(facts=facts))
790
+
791
+ # Any number in the reply that was not given to the model is one it
792
+ # invented, which is the only way this call can go wrong.
793
+ written = set(re.findall(r"\d+(?:\.\d+)?", text))
794
+ given = set(re.findall(r"\d+(?:\.\d+)?", facts))
795
+ unsupported = tuple(sorted(written - given))
796
+
797
+ return {
798
+ "text": text.strip(),
799
+ "facts": facts,
800
+ "unsupported_numbers": unsupported,
801
+ "faithful": not unsupported,
802
+ }