pyEDAA.Reports.RiskManagement

pyEDAA/Reports/RiskManagement/__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
# ==================================================================================================================== #
#              _____ ____    _        _      ____                       _                                              #
#  _ __  _   _| ____|  _ \  / \      / \    |  _ \ ___ _ __   ___  _ __| |_ ___                                        #
# | '_ \| | | |  _| | | | |/ _ \    / _ \   | |_) / _ \ '_ \ / _ \| '__| __/ __|                                       #
# | |_) | |_| | |___| |_| / ___ \  / ___ \ _|  _ <  __/ |_) | (_) | |  | |_\__ \                                       #
# | .__/ \__, |_____|____/_/   \_\/_/   \_(_)_| \_\___| .__/ \___/|_|   \__|___/                                       #
# |_|    |___/                                        |_|                                                              #
# ==================================================================================================================== #
# Authors:                                                                                                             #
#   Patrick Lehmann                                                                                                    #
#                                                                                                                      #
# License:                                                                                                             #
# ==================================================================================================================== #
# Copyright 2026-2026 Electronic Design Automation Abstraction (EDA²)                                                  #
#                                                                                                                      #
# Licensed under the Apache License, Version 2.0 (the "License");                                                      #
# you may not use this file except in compliance with the License.                                                     #
# You may obtain a copy of the License at                                                                              #
#                                                                                                                      #
#   http://www.apache.org/licenses/LICENSE-2.0                                                                         #
#                                                                                                                      #
# Unless required by applicable law or agreed to in writing, software                                                  #
# distributed under the License is distributed on an "AS IS" BASIS,                                                    #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                             #
# See the License for the specific language governing permissions and                                                  #
# limitations under the License.                                                                                       #
#                                                                                                                      #
# SPDX-License-Identifier: Apache-2.0                                                                                  #
# ==================================================================================================================== #
#
"""
Abstract data model of risk management: a risk register of risks, their implications and the mitigations against
them.

The root, :class:`RiskManagement`, holds every :class:`Risk`, :class:`Implication` and :class:`Mitigation` by ID. A risk
references its implications - what happens, if it occurs - and its mitigations - what reduces it. Implications and
mitigations are elements of their own, so several risks can share one, e.g. a mitigation reducing two risks.

The implications form a chain: an implication can have implications of its own, and a mitigation can have
implications too: its side effects. Both are the second-order implications of a risk. An implication can be mitigated
like a risk.

Risks of a register relate to each other by a :class:`Link`: from a source risk to a destination risk, of a
:class:`LinkKind`, e.g. one risk causing another. A link has no parent: its risks and the register list it.

A risk's :attr:`~Risk.Score` - the rank of its probability times the rank of its impact - classifies it by a
:class:`RiskLevel`. A risk names its owner - a :class:`~pyEDAA.Reports.Person` the register refers to - and the date of
its next review; a mitigation states its :class:`MitigationKind` and its :class:`MitigationState`.

Every element has key-value pairs (:class:`~pyTooling.DataModel.KeyValuePairsMixin`) for data the model doesn't name.
"""
from __future__            import annotations

from datetime              import datetime
from enum                  import Enum
from typing                import Any, Callable, ClassVar, Generator, Hashable, Iterable, Mapping, Optional as Nullable

from pyTooling.Common      import getFullyQualifiedName
from pyTooling.DataModel   import KeyValuePairsMixin
from pyTooling.Decorators  import export, readonly
from pyTooling.Exceptions  import AlreadyInHierarchyError, DuplicateElementError, NotInSameHierarchyError
from pyTooling.MetaClasses import ExtendedType
from pyTooling.Versioning  import SemanticVersion

from pyEDAA.Reports        import Person, ReportException


@export
class RiskManagementError(ReportException):
	"""Base-exception of the risk management model."""


@export
class NotInSameRiskRegisterError(RiskManagementError, NotInSameHierarchyError):
	"""
	The exception is raised when an element is used together with an element or a person of another risk register.

	The element or person itself is valid, only its ownership is wrong: add it to the risk register first. E.g. a risk
	referencing a mitigation, which isn't part of the risk's register.
	"""


@export
class AlreadyInRiskRegisterError(RiskManagementError, AlreadyInHierarchyError):
	"""The exception is raised when an element is added to a risk register, but it's already part of a risk register."""


@export
class DuplicateRiskError(RiskManagementError, DuplicateElementError):
	"""The exception is raised when a risk register already contains a risk of the same ID."""


@export
class DuplicateImplicationError(RiskManagementError, DuplicateElementError):
	"""The exception is raised when a risk register or an element already contains an implication of the same ID."""


@export
class DuplicateMitigationError(RiskManagementError, DuplicateElementError):
	"""The exception is raised when a risk register or an element already contains a mitigation of the same ID."""


@export
class DuplicatePersonError(RiskManagementError, DuplicateElementError):
	"""The exception is raised when a risk register already contains a person of the same user ID."""


@export
class DuplicateLinkError(RiskManagementError, DuplicateElementError):
	"""The exception is raised when a risk already has a link of the same kind to the same destination."""


@export
class Probability(Enum):
	"""
	The probability of a risk to occur.
	"""

	Low =      1  #: Identified, but sleeping.
	Medium =   2  #: Likely to occur soon.
	High =     3  #: Very likely to occur.
	Occurred = 4  #: Occurred: the risk is active and causes heavy effects.

	__RANKS: ClassVar[dict[int, int]] = {
		Low:      1,
		Medium:   2,
		High:     3,
		Occurred: 4,
	}  #: The rank of each probability, by the probability's value.

	@readonly
	def Rank(self) -> int:
		"""
		Read-only property to return the probability's rank on its ordinal scale.

		:returns: The rank in range 1..4; ``1`` is the lowest probability.
		"""
		return self.__RANKS[self.value]


@export
class Impact(Enum):
	"""
	The impact of a risk, if it occurs, as the delay it causes.
	"""

	Low =      1  #: A delay of a few days.
	Medium =   2  #: A delay of multiple days.
	High =     3  #: A delay of a few weeks.
	Critical = 4  #: A delay of multiple weeks.

	__RANKS: ClassVar[dict[int, int]] = {
		Low:      1,
		Medium:   2,
		High:     3,
		Critical: 4,
	}  #: The rank of each impact, by the impact's value.

	@readonly
	def Rank(self) -> int:
		"""
		Read-only property to return the impact's rank on its ordinal scale.

		:returns: The rank in range 1..4; ``1`` is the lowest impact.
		"""
		return self.__RANKS[self.value]


@export
class RiskLevel(Enum):
	"""
	The level of a risk, classified by its score: the rank of its probability times the rank of its impact.

	.. code-block:: text

	                         Impact:  low  medium  high  critical
	   Probability: low                 1       2     3         4
	                medium              2       4     6         8
	                high                3       6     9        12
	                occurred            4       8    12        16
	"""

	Low =      1  #: A score of 1 to 3.
	Medium =   2  #: A score of 4 to 6.
	High =     3  #: A score of 8 or 9.
	Critical = 4  #: A score of 12 to 16.


@export
class RiskState(Enum):
	"""
	The state of a risk in its life cycle.

	A risk ends either *solved* - its mitigations removed it - or *closed* - it isn't tracked anymore, without being
	solved.
	"""

	Open =    1     #: Identified and tracked.
	OnHold =  2     #: Tracking is paused, e.g. until a decision is made.
	Closed =  3     #: Not tracked anymore, without being solved, e.g. accepted, obsolete or its time has passed.
	Solved =  4     #: Removed by its mitigations: it can't occur anymore.

	DEFAULT = Open  #: The state of a newly identified risk.


@export
class LinkKind(Enum):
	"""
	The relationship a :class:`Link` states from its source risk to its destination risk.
	"""

	Causes =     1        #: The source, if it occurs, causes the destination to occur.
	Amplifies =  2        #: The source, if it occurs, raises the probability or the impact of the destination.
	DependsOn =  3        #: The source can only occur, if the destination occurred.
	Duplicates = 4        #: The source describes the same risk as the destination.
	Related =    5        #: The source relates to the destination in another way.

	DEFAULT =    Related  #: The relationship of a link, which states no other.


@export
class MitigationKind(Enum):
	"""
	The way a mitigation reduces a risk or an implication.
	"""

	Avoid =       1        #: Removes the cause, so the risk can't occur.
	Prevent =     2        #: Reduces the probability the risk occurs.
	Contingency = 3        #: Reduces the impact: a plan applied, when the risk occurs.
	Transfer =    4        #: Moves the impact to a third party, e.g. by a contract or an insurance.

	DEFAULT =     Prevent  #: The way of a mitigation, which states no other.


@export
class MitigationState(Enum):
	"""
	The state of a mitigation: whether it is applied.

	A mitigation *on hold* waits to be planned; a new mitigation is *planned*.
	"""

	OnHold =    1        #: Proposed, but waiting to be planned, e.g. for a decision or a budget.
	Planned =   2        #: Decided, but not started.
	Active =    3        #: Being applied.
	Done =      4        #: Applied completely.
	Abandoned = 5        #: Not applied anymore, e.g. too expensive or without effect.

	DEFAULT =   Planned  #: The state of a newly decided mitigation.


@export
class Base(KeyValuePairsMixin, metaclass=ExtendedType, slots=True):
	"""
	Base-class of every element of the risk management model: key-value pairs, a reference to the risk register
	containing the element, and to the register's root.
	"""

	_parent: Nullable[RiskManagement]  #: The risk register containing this element, or ``None``.
	_root:   Nullable[RiskManagement]  #: The risk register's root, or ``None`` while the element isn't part of one.

	def __init__(
		self,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None,
		*,
		parent: Nullable[RiskManagement] = None
	) -> None:
		"""
		Initializes an element with its key-value pairs, its parent and the parent's root.

		The parent doesn't list the element yet: the class setting the fields the parent checks - an ID and the referenced
		elements - adds it with ``parent._AddElement(self)``.

		:param keyValuePairs: Optional, the key-value pairs. Default: ``None``.
		:param parent:        Optional, the risk register containing this element. Default: ``None``.
		:raises TypeError:    If parameter ``keyValuePairs`` isn't a mapping.
		:raises TypeError:    If parameter ``parent`` isn't of type :class:`RiskManagement`.
		"""
		super().__init__(keyValuePairs)

		if parent is None:
			self._parent = None
			self._root =   None
		elif not isinstance(parent, RiskManagement):
			ex = TypeError("Parameter 'parent' is not of type 'RiskManagement'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
			raise ex
		else:
			self._parent = parent
			self._root =   parent._root

	@property
	def Parent(self) -> Nullable[RiskManagement]:
		"""
		Property to access the risk register containing this element (:attr:`_parent`).

		Assigning a risk register adds this element to it, and sets the register's root as the root of this element.

		:returns:                           The parent, or ``None``.
		:raises ValueError:                 If ``None`` is assigned.
		:raises TypeError:                  If the assigned parent isn't of type :class:`RiskManagement`.
		:raises TypeError:                  If a parent is assigned to a :class:`RiskManagement`, which has no parent.
		:raises AlreadyInRiskRegisterError: If the element is already part of a risk register.
		:raises DuplicateRiskError:         If the element is a risk, and the risk register already contains a risk of its
		                                    ID.
		:raises DuplicateImplicationError:  If the element is an implication, and the risk register already contains an
		                                    implication of its ID.
		:raises DuplicateMitigationError:   If the element is a mitigation, and the risk register already contains a
		                                    mitigation of its ID.
		:raises NotInSameRiskRegisterError: If the element references an element, which isn't part of the risk register.
		                                    |br|
		                                    Add the referenced elements to the risk register first.
		"""
		return self._parent

	@Parent.setter
	def Parent(self, parent: RiskManagement) -> None:
		if parent is None:
			raise ValueError("Parameter 'parent' is None.")
		elif not isinstance(parent, RiskManagement):
			ex = TypeError("Parameter 'parent' is not of type 'RiskManagement'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
			raise ex
		elif self._parent is not None:
			ex = AlreadyInRiskRegisterError("Element is already part of a risk register.")
			ex.add_note(f"Got element '{self!r}'.")
			raise ex

		parent._AddElement(self)
		self._parent = parent
		self._root =   parent._root

	@readonly
	def Root(self) -> Nullable[RiskManagement]:
		"""
		Read-only property to access the risk register's root (:attr:`_root`).

		The root is maintained by :attr:`Parent`: assigning a parent sets it.

		:returns: The root, or ``None`` while the element isn't part of a risk register.
		"""
		return self._root


@export
class RiskManagement(Base):
	"""
	The risk register: every risk, implication and mitigation, each by its ID, the links between the risks, the persons
	it refers to, the register's version and its optional name.

	It is its own root, and has no parent. An element joins it by naming it as its parent, in the element's constructor
	or by :attr:`~Base.Parent`.
	"""

	_version:      SemanticVersion         #: The version of the risk register.
	_name:         Nullable[str]           #: The name of the risk register, if given.
	_risks:        dict[str, Risk]         #: The risks, by ID.
	_implications: dict[str, Implication]  #: The implications, by ID.
	_mitigations:  dict[str, Mitigation]   #: The mitigations, by ID.
	_links:        list[Link]              #: The links between the risks, in the order they were added.
	_persons:      dict[str, Person]       #: The persons the register refers to, e.g. as risk owners, by user ID.

	def __init__(
		self,
		version: SemanticVersion,
		name: Nullable[str] = None,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None
	) -> None:
		"""
		Initializes an empty risk register of a version.

		:param version:       The version of the risk register.
		:param name:          Optional, the name of the risk register, e.g. the project's name. Default: ``None``.
		:param keyValuePairs: Optional, the key-value pairs. Default: ``None``.
		:raises TypeError:    If parameter ``keyValuePairs`` isn't a mapping.
		:raises ValueError:   If parameter ``version`` is ``None``.
		:raises TypeError:    If parameter ``version`` isn't of type :class:`~pyTooling.Versioning.SemanticVersion`.
		:raises TypeError:    If parameter ``name`` isn't of type :class:`str`.
		:raises ValueError:   If parameter ``name`` is empty.
		"""
		super().__init__(keyValuePairs)

		if version is None:
			raise ValueError("Parameter 'version' is None.")
		elif not isinstance(version, SemanticVersion):
			ex = TypeError("Parameter 'version' is not of type 'SemanticVersion'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(version)}'.")
			raise ex

		if name is not None:
			if not isinstance(name, str):
				ex = TypeError("Parameter 'name' is not of type 'str'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(name)}'.")
				raise ex
			elif name == "":
				raise ValueError("Parameter 'name' is empty.")

		self._root =         self
		self._version =      version
		self._name =         name
		self._risks =        {}
		self._implications = {}
		self._mitigations =  {}
		self._links =        []
		self._persons =      {}

	@Base.Parent.setter
	def Parent(self, parent: None) -> None:
		ex = TypeError(f"A '{getFullyQualifiedName(self)}' has no parent.")
		ex.add_note(f"Got type '{getFullyQualifiedName(parent)}'.")
		raise ex

	def _AddElement(self, element: BaseWithID) -> None:
		"""
		Add a risk, an implication or a mitigation, which names the risk register as its parent.

		:param element:                     The risk, implication or mitigation.
		:raises DuplicateRiskError:         If the risk register already contains a risk of the element's ID.
		:raises DuplicateImplicationError:  If the risk register already contains an implication of the element's ID.
		:raises DuplicateMitigationError:   If the risk register already contains a mitigation of the element's ID.
		:raises NotInSameRiskRegisterError: If the element references an implication or a mitigation, which isn't part of
		                                    the
		                                    risk register. |br|
		                                    Add the referenced elements to the risk register first.
		:raises NotInSameRiskRegisterError: If the element is a risk, whose owner isn't a person of the risk register. |br|
		                                    Add the person to the risk register first.
		"""
		if isinstance(element, Risk):
			kind =      "Risk"
			elements =  self._risks
			exception = DuplicateRiskError
		elif isinstance(element, Implication):
			kind =      "Implication"
			elements =  self._implications
			exception = DuplicateImplicationError
		else:
			kind =      "Mitigation"
			elements =  self._mitigations
			exception = DuplicateMitigationError

		if element._id in elements:
			raise exception(f"{kind} '{element._id}' already exists in the risk register.")

		for implication in element._implications.values():
			if implication._root is not self:
				ex = NotInSameRiskRegisterError(f"{kind} '{element._id}' references an implication outside the risk register.")
				ex.add_note(f"Got implication '{implication._id}'.")
				ex.add_note("Add the implication to the risk register first.")
				raise ex

		if isinstance(element, MitigationsMixin):
			for mitigation in element._mitigations.values():
				if mitigation._root is not self:
					ex = NotInSameRiskRegisterError(f"{kind} '{element._id}' references a mitigation outside the risk register.")
					ex.add_note(f"Got mitigation '{mitigation._id}'.")
					ex.add_note("Add the mitigation to the risk register first.")
					raise ex

		if isinstance(element, Risk) and element._owner is not None:
			if self._persons.get(element._owner._userID) is not element._owner:
				ex = NotInSameRiskRegisterError(f"Risk '{element._id}' has an owner outside the risk register.")
				ex.add_note(f"Got person '{element._owner._userID}'.")
				ex.add_note("Add the person to the risk register first.")
				raise ex

		elements[element._id] = element

	@readonly
	def Version(self) -> SemanticVersion:
		"""
		Read-only property to access the version of the risk register (:attr:`_version`).

		:returns: The version.
		"""
		return self._version

	@readonly
	def Name(self) -> Nullable[str]:
		"""
		Read-only property to access the name of the risk register (:attr:`_name`).

		:returns: The name, or ``None`` if none is given.
		"""
		return self._name

	@readonly
	def Risks(self) -> dict[str, Risk]:
		"""
		Read-only property to access the risks (:attr:`_risks`).

		:returns: The risks, by ID.
		"""
		return self._risks

	@readonly
	def Implications(self) -> dict[str, Implication]:
		"""
		Read-only property to access the implications (:attr:`_implications`).

		:returns: The implications, by ID.
		"""
		return self._implications

	@readonly
	def Mitigations(self) -> dict[str, Mitigation]:
		"""
		Read-only property to access the mitigations (:attr:`_mitigations`).

		:returns: The mitigations, by ID.
		"""
		return self._mitigations

	@readonly
	def Links(self) -> list[Link]:
		"""
		Read-only property to access the links between the risks (:attr:`_links`).

		:returns: The links, in the order they were added.
		"""
		return self._links

	@readonly
	def Persons(self) -> dict[str, Person]:
		"""
		Read-only property to access the persons the risk register refers to (:attr:`_persons`).

		A risk's owner is one of them.

		:returns: The persons, by user ID.
		"""
		return self._persons

	def AddPerson(self, person: Person) -> None:
		"""
		Add a person the risk register refers to.

		A risk's owner must be added first. The same person may be added to several risk registers.

		:param person:                The person.
		:raises ValueError:           If parameter ``person`` is ``None``.
		:raises TypeError:            If parameter ``person`` isn't of type :class:`~pyEDAA.Reports.Person`.
		:raises DuplicatePersonError: If the risk register already contains a person of the same user ID.
		"""
		if person is None:
			raise ValueError("Parameter 'person' is None.")
		elif not isinstance(person, Person):
			ex = TypeError("Parameter 'person' is not of type 'Person'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(person)}'.")
			raise ex
		elif person._userID in self._persons:
			raise DuplicatePersonError(f"Person '{person._userID}' already exists in the risk register.")

		self._persons[person._userID] = person

	def IterateRisks(self, predicate: Nullable[Callable[[Risk], bool]] = None) -> Generator[Risk, None, None]:
		"""
		Iterate all or selected risks.

		If parameter ``predicate`` is not None, the given filter function is used to skip risks in the generator.

		:param predicate: Optional, filter function accepting any risk and returning a boolean.
		:returns:         A generator of the risks, in the order they were added.
		"""
		if predicate is None:
			yield from self._risks.values()
		else:
			for risk in self._risks.values():
				if predicate(risk):
					yield risk

	def IterateImplications(
		self,
		predicate: Nullable[Callable[[Implication], bool]] = None
	) -> Generator[Implication, None, None]:
		"""
		Iterate all or selected implications.

		If parameter ``predicate`` is not None, the given filter function is used to skip implications in the generator.

		:param predicate: Optional, filter function accepting any implication and returning a boolean.
		:returns:         A generator of the implications, in the order they were added.
		"""
		if predicate is None:
			yield from self._implications.values()
		else:
			for implication in self._implications.values():
				if predicate(implication):
					yield implication

	def IterateMitigations(
		self,
		predicate: Nullable[Callable[[Mitigation], bool]] = None
	) -> Generator[Mitigation, None, None]:
		"""
		Iterate all or selected mitigations.

		If parameter ``predicate`` is not None, the given filter function is used to skip mitigations in the generator.

		:param predicate: Optional, filter function accepting any mitigation and returning a boolean.
		:returns:         A generator of the mitigations, in the order they were added.
		"""
		if predicate is None:
			yield from self._mitigations.values()
		else:
			for mitigation in self._mitigations.values():
				if predicate(mitigation):
					yield mitigation

	def IterateLinks(self, predicate: Nullable[Callable[[Link], bool]] = None) -> Generator[Link, None, None]:
		"""
		Iterate all or selected links between the risks.

		If parameter ``predicate`` is not None, the given filter function is used to skip links in the generator.

		:param predicate: Optional, filter function accepting any link and returning a boolean.
		:returns:         A generator of the links, in the order they were added.
		"""
		if predicate is None:
			yield from self._links
		else:
			for link in self._links:
				if predicate(link):
					yield link

	def __repr__(self) -> str:
		"""
		Return a representation of the risk register for debugging.

		A register of version 1.0.0 with 3 risks, 4 implications and 2 mitigations reads
		``<RiskManagement 1.0.0: 3 risks, 4 implications, 2 mitigations>``.

		:returns: The register's version and its numbers of risks, implications and mitigations.
		"""
		return (
			f"<RiskManagement {self._version}: {len(self._risks)} risks, {len(self._implications)} implications, "
			f"{len(self._mitigations)} mitigations>"
		)


@export
class BaseWithID(Base):
	"""
	Base-class of the elements a risk register holds by ID - risks, implications and mitigations -: an ID and a
	description.
	"""

	_id:          str  #: The element's ID, unique among the elements of its kind in a risk register.
	_description: str  #: The element's description.

	def __init__(
		self,
		identifier: str,
		description: str,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None,
		*,
		parent: Nullable[RiskManagement] = None
	) -> None:
		"""
		Initializes an element with its ID, its description, its key-value pairs and its parent.

		:param identifier:    The element's ID, unique among the elements of its kind in a risk register.
		:param description:   The element's description.
		:param keyValuePairs: Optional, the key-value pairs. Default: ``None``.
		:param parent:        Optional, the risk register containing this element. Default: ``None``.
		:raises TypeError:    If parameter ``keyValuePairs`` isn't a mapping.
		:raises TypeError:    If parameter ``parent`` isn't of type :class:`RiskManagement`.
		:raises ValueError:   If parameter ``identifier`` is ``None``.
		:raises TypeError:    If parameter ``identifier`` isn't of type :class:`str`.
		:raises ValueError:   If parameter ``identifier`` is empty.
		:raises ValueError:   If parameter ``description`` is ``None``.
		:raises TypeError:    If parameter ``description`` isn't of type :class:`str`.
		:raises ValueError:   If parameter ``description`` is empty.
		"""
		super().__init__(keyValuePairs, parent=parent)

		if identifier is None:
			raise ValueError("Parameter 'identifier' is None.")
		elif not isinstance(identifier, str):
			ex = TypeError("Parameter 'identifier' is not of type 'str'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(identifier)}'.")
			raise ex
		elif identifier == "":
			raise ValueError("Parameter 'identifier' is empty.")

		if description is None:
			raise ValueError("Parameter 'description' is None.")
		elif not isinstance(description, str):
			ex = TypeError("Parameter 'description' is not of type 'str'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(description)}'.")
			raise ex
		elif description == "":
			raise ValueError("Parameter 'description' is empty.")

		self._id =          identifier
		self._description = description

	@readonly
	def ID(self) -> str:
		"""
		Read-only property to access the element's ID (:attr:`_id`).

		:returns: The ID.
		"""
		return self._id

	@readonly
	def Description(self) -> str:
		"""
		Read-only property to access the element's description (:attr:`_description`).

		:returns: The description.
		"""
		return self._description


@export
class ImplicationsMixin(metaclass=ExtendedType, mixin=True):
	"""
	A mixin-class adding implications to an element: the consequences the element has.

	The implications of a risk are what happens, if it occurs; those of a mitigation are its side effects. An element of
	a risk register references only implications of the same register.
	"""

	_implications: dict[str, Implication]  #: The implications, by ID.

	def __init__(self, implications: Nullable[Iterable[Implication]] = None) -> None:
		"""
		Initializes the implications.

		:param implications:                Optional, the implications. Default: ``None``.
		:raises TypeError:                  If parameter ``implications`` isn't iterable.
		:raises TypeError:                  If parameter ``implications`` is a single element, not an iterable.
		:raises TypeError:                  If parameter ``implications`` contains an element not of type
		                                    :class:`Implication`.
		:raises DuplicateImplicationError:  If parameter ``implications`` contains two implications of the same ID.
		:raises NotInSameRiskRegisterError: If parameter ``implications`` contains an implication, which isn't part of the
		                                    element's risk register. |br|
		                                    Add the implication to the risk register first.
		"""
		self._implications = {}

		if implications is None:
			return
		elif not isinstance(implications, Iterable):
			ex = TypeError("Parameter 'implications' is not iterable.")
			ex.add_note(f"Got type '{getFullyQualifiedName(implications)}'.")
			raise ex
		elif isinstance(implications, KeyValuePairsMixin):
			ex = TypeError("Parameter 'implications' is a single element, not an iterable of elements.")
			ex.add_note(f"Got type '{getFullyQualifiedName(implications)}'.")
			raise ex

		for implication in implications:
			if not isinstance(implication, Implication):
				ex = TypeError("Parameter 'implications' contains an element not of type 'Implication'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(implication)}'.")
				raise ex
			elif implication._id in self._implications:
				raise DuplicateImplicationError(f"Parameter 'implications' contains implication '{implication._id}' twice.")
			elif self._root is not None and implication._root is not self._root:
				ex = NotInSameRiskRegisterError(
					"Parameter 'implications' contains an implication outside the element's risk register."
				)
				ex.add_note(f"Got implication '{implication._id}'.")
				ex.add_note("Add the implication to the risk register first.")
				raise ex

			self._implications[implication._id] = implication

	@readonly
	def Implications(self) -> dict[str, Implication]:
		"""
		Read-only property to access the implications (:attr:`_implications`).

		:returns: The implications, by ID.
		"""
		return self._implications

	def AddImplication(self, implication: Implication) -> None:
		"""
		Add an implication.

		:param implication:                 The implication.
		:raises ValueError:                 If parameter ``implication`` is ``None``.
		:raises TypeError:                  If parameter ``implication`` isn't of type :class:`Implication`.
		:raises DuplicateImplicationError:  If the element already has an implication of the same ID.
		:raises NotInSameRiskRegisterError: If the implication isn't part of the element's risk register. |br|
		                                    Add the implication to the risk register first.
		"""
		if implication is None:
			raise ValueError("Parameter 'implication' is None.")
		elif not isinstance(implication, Implication):
			ex = TypeError("Parameter 'implication' is not of type 'Implication'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(implication)}'.")
			raise ex
		elif implication._id in self._implications:
			raise DuplicateImplicationError(f"Element already has implication '{implication._id}'.")
		elif self._root is not None and implication._root is not self._root:
			ex = NotInSameRiskRegisterError("Parameter 'implication' is outside the element's risk register.")
			ex.add_note(f"Got implication '{implication._id}'.")
			ex.add_note("Add the implication to the risk register first.")
			raise ex

		self._implications[implication._id] = implication


@export
class MitigationsMixin(metaclass=ExtendedType, mixin=True):
	"""
	A mixin-class adding mitigations to an element: the measures reducing the element's probability or impact.

	An element of a risk register references only mitigations of the same register.
	"""

	_mitigations: dict[str, Mitigation]  #: The mitigations, by ID.

	def __init__(self, mitigations: Nullable[Iterable[Mitigation]] = None) -> None:
		"""
		Initializes the mitigations.

		:param mitigations:                 Optional, the mitigations. Default: ``None``.
		:raises TypeError:                  If parameter ``mitigations`` isn't iterable.
		:raises TypeError:                  If parameter ``mitigations`` is a single element, not an iterable.
		:raises TypeError:                  If parameter ``mitigations`` contains an element not of type
		                                    :class:`Mitigation`.
		:raises DuplicateMitigationError:   If parameter ``mitigations`` contains two mitigations of the same ID.
		:raises NotInSameRiskRegisterError: If parameter ``mitigations`` contains a mitigation, which isn't part of the
		                                    element's risk register. |br|
		                                    Add the mitigation to the risk register first.
		"""
		self._mitigations = {}

		if mitigations is None:
			return
		elif not isinstance(mitigations, Iterable):
			ex = TypeError("Parameter 'mitigations' is not iterable.")
			ex.add_note(f"Got type '{getFullyQualifiedName(mitigations)}'.")
			raise ex
		elif isinstance(mitigations, KeyValuePairsMixin):
			ex = TypeError("Parameter 'mitigations' is a single element, not an iterable of elements.")
			ex.add_note(f"Got type '{getFullyQualifiedName(mitigations)}'.")
			raise ex

		for mitigation in mitigations:
			if not isinstance(mitigation, Mitigation):
				ex = TypeError("Parameter 'mitigations' contains an element not of type 'Mitigation'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(mitigation)}'.")
				raise ex
			elif mitigation._id in self._mitigations:
				raise DuplicateMitigationError(f"Parameter 'mitigations' contains mitigation '{mitigation._id}' twice.")
			elif self._root is not None and mitigation._root is not self._root:
				ex = NotInSameRiskRegisterError(
					"Parameter 'mitigations' contains a mitigation outside the element's risk register."
				)
				ex.add_note(f"Got mitigation '{mitigation._id}'.")
				ex.add_note("Add the mitigation to the risk register first.")
				raise ex

			self._mitigations[mitigation._id] = mitigation

	@readonly
	def Mitigations(self) -> dict[str, Mitigation]:
		"""
		Read-only property to access the mitigations (:attr:`_mitigations`).

		:returns: The mitigations, by ID.
		"""
		return self._mitigations

	def AddMitigation(self, mitigation: Mitigation) -> None:
		"""
		Add a mitigation.

		:param mitigation:                  The mitigation.
		:raises ValueError:                 If parameter ``mitigation`` is ``None``.
		:raises TypeError:                  If parameter ``mitigation`` isn't of type :class:`Mitigation`.
		:raises DuplicateMitigationError:   If the element already has a mitigation of the same ID.
		:raises NotInSameRiskRegisterError: If the mitigation isn't part of the element's risk register. |br|
		                                    Add the mitigation to the risk register first.
		"""
		if mitigation is None:
			raise ValueError("Parameter 'mitigation' is None.")
		elif not isinstance(mitigation, Mitigation):
			ex = TypeError("Parameter 'mitigation' is not of type 'Mitigation'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(mitigation)}'.")
			raise ex
		elif mitigation._id in self._mitigations:
			raise DuplicateMitigationError(f"Element already has mitigation '{mitigation._id}'.")
		elif self._root is not None and mitigation._root is not self._root:
			ex = NotInSameRiskRegisterError("Parameter 'mitigation' is outside the element's risk register.")
			ex.add_note(f"Got mitigation '{mitigation._id}'.")
			ex.add_note("Add the mitigation to the risk register first.")
			raise ex

		self._mitigations[mitigation._id] = mitigation


@export
class Implication(BaseWithID, ImplicationsMixin, MitigationsMixin):
	"""
	An implication: a consequence of a risk, if it occurs, of another implication, or of a mitigation, if applied.

	An implication is shared by every element naming it, e.g. two risks delaying the same milestone. It has implications
	of its own - the next order of consequences -, and it can be mitigated like a risk.
	"""

	def __init__(
		self,
		identifier: str,
		description: str,
		implications: Nullable[Iterable[Implication]] = None,
		mitigations: Nullable[Iterable[Mitigation]] = None,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None,
		*,
		parent: Nullable[RiskManagement] = None
	) -> None:
		"""
		Initializes an implication, and adds it to its risk register.

		:param identifier:                  The implication's ID, unique among the implications of a risk register.
		:param description:                 The implication's description.
		:param implications:                Optional, the implications of this implication. Default: ``None``.
		:param mitigations:                 Optional, the mitigations of this implication. Default: ``None``.
		:param keyValuePairs:               Optional, the key-value pairs. Default: ``None``.
		:param parent:                      Optional, the risk register containing the implication. Default: ``None``.
		:raises TypeError:                  If parameter ``keyValuePairs`` isn't a mapping.
		:raises TypeError:                  If parameter ``parent`` isn't of type :class:`RiskManagement`.
		:raises ValueError:                 If parameter ``identifier`` is ``None``.
		:raises TypeError:                  If parameter ``identifier`` isn't of type :class:`str`.
		:raises ValueError:                 If parameter ``identifier`` is empty.
		:raises ValueError:                 If parameter ``description`` is ``None``.
		:raises TypeError:                  If parameter ``description`` isn't of type :class:`str`.
		:raises ValueError:                 If parameter ``description`` is empty.
		:raises TypeError:                  If parameter ``implications`` isn't iterable.
		:raises TypeError:                  If parameter ``implications`` is a single element, not an iterable.
		:raises TypeError:                  If parameter ``implications`` contains an element not of type
		                                    :class:`Implication`.
		:raises DuplicateImplicationError:  If parameter ``implications`` contains two implications of the same ID.
		:raises NotInSameRiskRegisterError: If parameter ``implications`` contains an implication, which isn't part of the
		                                    risk register. |br|
		                                    Add the implication to the risk register first.
		:raises TypeError:                  If parameter ``mitigations`` isn't iterable.
		:raises TypeError:                  If parameter ``mitigations`` is a single element, not an iterable.
		:raises TypeError:                  If parameter ``mitigations`` contains an element not of type
		                                    :class:`Mitigation`.
		:raises DuplicateMitigationError:   If parameter ``mitigations`` contains two mitigations of the same ID.
		:raises NotInSameRiskRegisterError: If parameter ``mitigations`` contains a mitigation, which isn't part of the risk
		                                    register. |br|
		                                    Add the mitigation to the risk register first.
		:raises DuplicateImplicationError:  If the risk register already contains an implication of this ID.
		"""
		super().__init__(identifier, description, keyValuePairs, parent=parent)
		ImplicationsMixin.__init__(self, implications)
		MitigationsMixin.__init__(self, mitigations)

		if parent is not None:
			parent._AddElement(self)

	def __repr__(self) -> str:
		"""
		Return a representation of the implication for debugging.

		An implication ``I1`` with 2 implications and 1 mitigation reads ``<Implication I1: 2 implications,
		1 mitigations>``.

		:returns: The implication's ID and its numbers of implications and mitigations.
		"""
		return f"<Implication {self._id}: {len(self._implications)} implications, {len(self._mitigations)} mitigations>"


@export
class Mitigation(BaseWithID, ImplicationsMixin):
	"""
	A mitigation: a measure reducing the probability or the impact of a risk or of an implication.

	A mitigation is shared by every element naming it, e.g. a second supplier reducing two risks. Its implications are
	its side effects: the consequences of applying it.
	"""

	_kind:  MitigationKind   #: The way the mitigation reduces a risk or an implication.
	_state: MitigationState  #: Whether the mitigation is applied.

	def __init__(
		self,
		identifier: str,
		description: str,
		implications: Nullable[Iterable[Implication]] = None,
		kind: MitigationKind = MitigationKind.Prevent,
		state: MitigationState = MitigationState.Planned,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None,
		*,
		parent: Nullable[RiskManagement] = None
	) -> None:
		"""
		Initializes a mitigation, and adds it to its risk register.

		:param identifier:                  The mitigation's ID, unique among the mitigations of a risk register.
		:param description:                 The mitigation's description.
		:param implications:                Optional, the side effects of applying the mitigation. Default: ``None``.
		:param kind:                        Optional, the way the mitigation reduces a risk or an implication. Default:
		                                    ``MitigationKind.Prevent``.
		:param state:                       Optional, whether the mitigation is applied. Default:
		                                    ``MitigationState.Planned``.
		:param keyValuePairs:               Optional, the key-value pairs. Default: ``None``.
		:param parent:                      Optional, the risk register containing the mitigation. Default: ``None``.
		:raises TypeError:                  If parameter ``keyValuePairs`` isn't a mapping.
		:raises TypeError:                  If parameter ``parent`` isn't of type :class:`RiskManagement`.
		:raises ValueError:                 If parameter ``identifier`` is ``None``.
		:raises TypeError:                  If parameter ``identifier`` isn't of type :class:`str`.
		:raises ValueError:                 If parameter ``identifier`` is empty.
		:raises ValueError:                 If parameter ``description`` is ``None``.
		:raises TypeError:                  If parameter ``description`` isn't of type :class:`str`.
		:raises ValueError:                 If parameter ``description`` is empty.
		:raises TypeError:                  If parameter ``implications`` isn't iterable.
		:raises TypeError:                  If parameter ``implications`` is a single element, not an iterable.
		:raises TypeError:                  If parameter ``implications`` contains an element not of type
		                                    :class:`Implication`.
		:raises DuplicateImplicationError:  If parameter ``implications`` contains two implications of the same ID.
		:raises NotInSameRiskRegisterError: If parameter ``implications`` contains an implication, which isn't part of the
		                                    risk register. |br|
		                                    Add the implication to the risk register first.
		:raises ValueError:                 If parameter ``kind`` is ``None``.
		:raises TypeError:                  If parameter ``kind`` isn't of type :class:`MitigationKind`.
		:raises ValueError:                 If parameter ``state`` is ``None``.
		:raises TypeError:                  If parameter ``state`` isn't of type :class:`MitigationState`.
		:raises DuplicateMitigationError:   If the risk register already contains a mitigation of this ID.
		"""
		super().__init__(identifier, description, keyValuePairs, parent=parent)
		ImplicationsMixin.__init__(self, implications)

		if kind is None:
			raise ValueError("Parameter 'kind' is None.")
		elif not isinstance(kind, MitigationKind):
			ex = TypeError("Parameter 'kind' is not of type 'MitigationKind'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(kind)}'.")
			raise ex

		if state is None:
			raise ValueError("Parameter 'state' is None.")
		elif not isinstance(state, MitigationState):
			ex = TypeError("Parameter 'state' is not of type 'MitigationState'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(state)}'.")
			raise ex

		self._kind =  kind
		self._state = state

		if parent is not None:
			parent._AddElement(self)

	@readonly
	def Kind(self) -> MitigationKind:
		"""
		Read-only property to access the way the mitigation reduces a risk or an implication (:attr:`_kind`).

		:returns: The mitigation's kind.
		"""
		return self._kind

	@property
	def State(self) -> MitigationState:
		"""
		Property to access whether the mitigation is applied (:attr:`_state`).

		:returns:           The mitigation's state.
		:raises ValueError: If ``None`` is assigned.
		:raises TypeError:  If the assigned value isn't of type :class:`MitigationState`.
		"""
		return self._state

	@State.setter
	def State(self, value: MitigationState) -> None:
		if value is None:
			raise ValueError("Parameter 'value' is None.")
		elif not isinstance(value, MitigationState):
			ex = TypeError("Parameter 'value' is not of type 'MitigationState'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
			raise ex

		self._state = value

	def __repr__(self) -> str:
		"""
		Return a representation of the mitigation for debugging.

		A planned, preventing mitigation ``M1`` with 1 side effect reads ``<Mitigation M1: Prevent, Planned,
		1 implications>``.

		:returns: The mitigation's ID, kind, state and number of implications.
		"""
		return f"<Mitigation {self._id}: {self._kind.name}, {self._state.name}, {len(self._implications)} implications>"


# A class with a property named like a class - ``Probability``, ``Impact`` - can't name that class in the annotation of
# a field: the class body's namespace, where annotations are evaluated, binds the name to the property.
_Probability = Probability
_Impact =      Impact


@export
class Risk(BaseWithID, ImplicationsMixin, MitigationsMixin):
	"""
	A risk: its title and description, the probability it occurs, its impact, its state, its owner, the date of its next
	review, the implications and mitigations it references, and its links to other risks.

	The implications of a risk are its first-order implications. Their implications and the side effects of the risk's
	mitigations are its second-order implications (:attr:`SecondOrderImplications`).
	"""

	_title:         str                 #: The risk's title.
	_probability:   _Probability        #: The probability the risk occurs.
	_impact:        _Impact             #: The impact of the risk, if it occurs.
	_state:         RiskState           #: The state of the risk in its life cycle.
	_owner:         Nullable[Person]    #: The person responsible for the risk, if named.
	_nextReview:    Nullable[datetime]  #: The date of the risk's next review, if scheduled.
	_outboundLinks: list[Link]          #: The links from this risk to other risks, in the order they were added.
	_inboundLinks:  list[Link]          #: The links from other risks to this risk, in the order they were added.

	def __init__(
		self,
		identifier: str,
		title: str,
		description: str,
		probability: Probability,
		impact: Impact,
		state: RiskState = RiskState.Open,
		implications: Nullable[Iterable[Implication]] = None,
		mitigations: Nullable[Iterable[Mitigation]] = None,
		owner: Nullable[Person] = None,
		nextReview: Nullable[datetime] = None,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None,
		*,
		parent: Nullable[RiskManagement] = None
	) -> None:
		"""
		Initializes a risk, and adds it to its risk register.

		:param identifier:                  The risk's ID, unique among the risks of a risk register.
		:param title:                       The risk's title.
		:param description:                 The risk's description.
		:param probability:                 The probability the risk occurs.
		:param impact:                      The impact of the risk, if it occurs.
		:param state:                       Optional, the state of the risk. Default: ``RiskState.Open``.
		:param implications:                Optional, the first-order implications of the risk. Default: ``None``.
		:param mitigations:                 Optional, the mitigations of the risk. Default: ``None``.
		:param owner:                       Optional, the person responsible for the risk; a person of the risk register.
		                                    Default: ``None``.
		:param nextReview:                  Optional, the date of the risk's next review; without a time zone, it is a local
		                                    time. Default: ``None``.
		:param keyValuePairs:               Optional, the key-value pairs. Default: ``None``.
		:param parent:                      Optional, the risk register containing the risk. Default: ``None``.
		:raises TypeError:                  If parameter ``keyValuePairs`` isn't a mapping.
		:raises TypeError:                  If parameter ``parent`` isn't of type :class:`RiskManagement`.
		:raises ValueError:                 If parameter ``identifier`` is ``None``.
		:raises TypeError:                  If parameter ``identifier`` isn't of type :class:`str`.
		:raises ValueError:                 If parameter ``identifier`` is empty.
		:raises ValueError:                 If parameter ``description`` is ``None``.
		:raises TypeError:                  If parameter ``description`` isn't of type :class:`str`.
		:raises ValueError:                 If parameter ``description`` is empty.
		:raises TypeError:                  If parameter ``implications`` isn't iterable.
		:raises TypeError:                  If parameter ``implications`` is a single element, not an iterable.
		:raises TypeError:                  If parameter ``implications`` contains an element not of type
		                                    :class:`Implication`.
		:raises DuplicateImplicationError:  If parameter ``implications`` contains two implications of the same ID.
		:raises NotInSameRiskRegisterError: If parameter ``implications`` contains an implication, which isn't part of the
		                                    risk register. |br|
		                                    Add the implication to the risk register first.
		:raises TypeError:                  If parameter ``mitigations`` isn't iterable.
		:raises TypeError:                  If parameter ``mitigations`` is a single element, not an iterable.
		:raises TypeError:                  If parameter ``mitigations`` contains an element not of type
		                                    :class:`Mitigation`.
		:raises DuplicateMitigationError:   If parameter ``mitigations`` contains two mitigations of the same ID.
		:raises NotInSameRiskRegisterError: If parameter ``mitigations`` contains a mitigation, which isn't part of the risk
		                                    register. |br|
		                                    Add the mitigation to the risk register first.
		:raises ValueError:                 If parameter ``title`` is ``None``.
		:raises TypeError:                  If parameter ``title`` isn't of type :class:`str`.
		:raises ValueError:                 If parameter ``title`` is empty.
		:raises ValueError:                 If parameter ``probability`` is ``None``.
		:raises TypeError:                  If parameter ``probability`` isn't of type :class:`Probability`.
		:raises ValueError:                 If parameter ``impact`` is ``None``.
		:raises TypeError:                  If parameter ``impact`` isn't of type :class:`Impact`.
		:raises ValueError:                 If parameter ``state`` is ``None``.
		:raises TypeError:                  If parameter ``state`` isn't of type :class:`RiskState`.
		:raises TypeError:                  If parameter ``owner`` isn't of type :class:`~pyEDAA.Reports.Person`.
		:raises NotInSameRiskRegisterError: If parameter ``owner`` isn't a person of the risk register. |br|
		                                    Add the person to the risk register first.
		:raises TypeError:                  If parameter ``nextReview`` isn't of type :class:`~datetime.datetime`.
		:raises DuplicateRiskError:         If the risk register already contains a risk of this ID.
		"""
		super().__init__(identifier, description, keyValuePairs, parent=parent)
		ImplicationsMixin.__init__(self, implications)
		MitigationsMixin.__init__(self, mitigations)

		if title is None:
			raise ValueError("Parameter 'title' is None.")
		elif not isinstance(title, str):
			ex = TypeError("Parameter 'title' is not of type 'str'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(title)}'.")
			raise ex
		elif title == "":
			raise ValueError("Parameter 'title' is empty.")

		if probability is None:
			raise ValueError("Parameter 'probability' is None.")
		elif not isinstance(probability, Probability):
			ex = TypeError("Parameter 'probability' is not of type 'Probability'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(probability)}'.")
			raise ex

		if impact is None:
			raise ValueError("Parameter 'impact' is None.")
		elif not isinstance(impact, Impact):
			ex = TypeError("Parameter 'impact' is not of type 'Impact'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(impact)}'.")
			raise ex

		if state is None:
			raise ValueError("Parameter 'state' is None.")
		elif not isinstance(state, RiskState):
			ex = TypeError("Parameter 'state' is not of type 'RiskState'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(state)}'.")
			raise ex

		if owner is not None:
			if not isinstance(owner, Person):
				ex = TypeError("Parameter 'owner' is not of type 'Person'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(owner)}'.")
				raise ex
			elif self._root is not None and self._root._persons.get(owner._userID) is not owner:
				ex = NotInSameRiskRegisterError("Parameter 'owner' isn't a person of the risk register.")
				ex.add_note(f"Got person '{owner._userID}'.")
				ex.add_note("Add the person to the risk register first.")
				raise ex

		if nextReview is not None and not isinstance(nextReview, datetime):
			ex = TypeError("Parameter 'nextReview' is not of type 'datetime'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(nextReview)}'.")
			raise ex

		self._title =         title
		self._probability =   probability
		self._impact =        impact
		self._state =         state
		self._owner =         owner
		self._nextReview =    nextReview
		self._outboundLinks = []
		self._inboundLinks =  []

		if parent is not None:
			parent._AddElement(self)

	@readonly
	def Title(self) -> str:
		"""
		Read-only property to access the risk's title (:attr:`_title`).

		:returns: The title.
		"""
		return self._title

	@property
	def Probability(self) -> Probability:
		"""
		Property to access the probability the risk occurs (:attr:`_probability`).

		:returns:           The probability.
		:raises ValueError: If ``None`` is assigned.
		:raises TypeError:  If the assigned value isn't of type :class:`Probability`.
		"""
		return self._probability

	@Probability.setter
	def Probability(self, value: Probability) -> None:
		if value is None:
			raise ValueError("Parameter 'value' is None.")
		elif not isinstance(value, Probability):
			ex = TypeError("Parameter 'value' is not of type 'Probability'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
			raise ex

		self._probability = value

	@property
	def Impact(self) -> Impact:
		"""
		Property to access the impact of the risk, if it occurs (:attr:`_impact`).

		:returns:           The impact.
		:raises ValueError: If ``None`` is assigned.
		:raises TypeError:  If the assigned value isn't of type :class:`Impact`.
		"""
		return self._impact

	@Impact.setter
	def Impact(self, value: Impact) -> None:
		if value is None:
			raise ValueError("Parameter 'value' is None.")
		elif not isinstance(value, Impact):
			ex = TypeError("Parameter 'value' is not of type 'Impact'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
			raise ex

		self._impact = value

	@property
	def State(self) -> RiskState:
		"""
		Property to access the state of the risk in its life cycle (:attr:`_state`).

		:returns:           The state.
		:raises ValueError: If ``None`` is assigned.
		:raises TypeError:  If the assigned value isn't of type :class:`RiskState`.
		"""
		return self._state

	@State.setter
	def State(self, value: RiskState) -> None:
		if value is None:
			raise ValueError("Parameter 'value' is None.")
		elif not isinstance(value, RiskState):
			ex = TypeError("Parameter 'value' is not of type 'RiskState'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
			raise ex

		self._state = value

	@property
	def Owner(self) -> Nullable[Person]:
		"""
		Property to access the person responsible for the risk (:attr:`_owner`).

		The owner of a risk in a risk register is a person of that register (:attr:`RiskManagement.Persons`).

		:returns:                           The owner, or ``None`` if none is named.
		:raises TypeError:                  If the assigned value isn't of type :class:`~pyEDAA.Reports.Person`.
		:raises NotInSameRiskRegisterError: If the assigned value isn't a person of the risk register. |br|
		                                    Add the person to the risk register first.
		"""
		return self._owner

	@Owner.setter
	def Owner(self, value: Nullable[Person]) -> None:
		if value is not None:
			if not isinstance(value, Person):
				ex = TypeError("Parameter 'value' is not of type 'Person'.")
				ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
				raise ex
			elif self._root is not None and self._root._persons.get(value._userID) is not value:
				ex = NotInSameRiskRegisterError("Parameter 'value' isn't a person of the risk register.")
				ex.add_note(f"Got person '{value._userID}'.")
				ex.add_note("Add the person to the risk register first.")
				raise ex

		self._owner = value

	@property
	def NextReview(self) -> Nullable[datetime]:
		"""
		Property to access the date of the risk's next review (:attr:`_nextReview`).

		:returns:          The date, or ``None`` if no review is scheduled; without a time zone, it is a local time.
		:raises TypeError: If the assigned value isn't of type :class:`~datetime.datetime`.
		"""
		return self._nextReview

	@NextReview.setter
	def NextReview(self, value: Nullable[datetime]) -> None:
		if value is not None and not isinstance(value, datetime):
			ex = TypeError("Parameter 'value' is not of type 'datetime'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(value)}'.")
			raise ex

		self._nextReview = value

	@readonly
	def Score(self) -> int:
		"""
		Read-only property to return the risk's score: the rank of its probability times the rank of its impact.

		:returns: The score in range 1..16.
		"""
		return self._probability.Rank * self._impact.Rank

	@readonly
	def Level(self) -> RiskLevel:
		"""
		Read-only property to return the risk's level, classified by its :attr:`Score` (see :class:`RiskLevel`).

		:returns: The risk's level.
		"""
		score = self.Score
		if score >= 12:
			return RiskLevel.Critical
		elif score >= 8:
			return RiskLevel.High
		elif score >= 4:
			return RiskLevel.Medium

		return RiskLevel.Low

	@readonly
	def SecondOrderImplications(self) -> dict[str, Implication]:
		"""
		Read-only property to return the second-order implications: the implications of the risk's implications and of its
		mitigations.

		The implications of a mitigation are its side effects. An implication reached several times is returned once.

		:returns: The second-order implications, by ID.
		"""
		implications = {}
		for element in (*self._implications.values(), *self._mitigations.values()):
			implications.update(element._implications)

		return implications

	@readonly
	def OutboundLinks(self) -> list[Link]:
		"""
		Read-only property to access the links from this risk to other risks (:attr:`_outboundLinks`).

		:returns: The links, in the order they were added.
		"""
		return self._outboundLinks

	@readonly
	def InboundLinks(self) -> list[Link]:
		"""
		Read-only property to access the links from other risks to this risk (:attr:`_inboundLinks`).

		:returns: The links, in the order they were added.
		"""
		return self._inboundLinks

	def LinkTo(self, destination: Risk, kind: LinkKind, keyValuePairs: Nullable[Mapping[Hashable, Any]] = None) -> Link:
		"""
		Create an outbound link from this risk to the given risk.

		:param destination:                 The risk the link ends at.
		:param kind:                        The relationship the link states.
		:param keyValuePairs:               Optional, the key-value pairs of the link. Default: ``None``.
		:returns:                           The link from this risk to the destination.
		:raises TypeError:                  If parameter ``keyValuePairs`` isn't a mapping.
		:raises NotInSameRiskRegisterError: If this risk isn't part of a risk register.
		:raises ValueError:                 If parameter ``destination`` is ``None``.
		:raises TypeError:                  If parameter ``destination`` isn't of type :class:`Risk`.
		:raises ValueError:                 If parameter ``destination`` is this risk.
		:raises NotInSameRiskRegisterError: If parameter ``destination`` isn't part of this risk's risk register.
		:raises ValueError:                 If parameter ``kind`` is ``None``.
		:raises TypeError:                  If parameter ``kind`` isn't of type :class:`LinkKind`.
		:raises DuplicateLinkError:         If this risk already has a link of this kind to the destination.

		.. seealso::

		   :meth:`LinkFrom`
		      |rarr| Create an inbound link from the given risk to this risk.
		"""
		return Link(self, destination, kind, keyValuePairs)

	def LinkFrom(self, source: Risk, kind: LinkKind, keyValuePairs: Nullable[Mapping[Hashable, Any]] = None) -> Link:
		"""
		Create an inbound link from the given risk to this risk.

		:param source:                      The risk the link starts at.
		:param kind:                        The relationship the link states.
		:param keyValuePairs:               Optional, the key-value pairs of the link. Default: ``None``.
		:returns:                           The link from the source to this risk.
		:raises ValueError:                 If parameter ``source`` is this risk.
		:raises TypeError:                  If parameter ``keyValuePairs`` isn't a mapping.
		:raises ValueError:                 If parameter ``source`` is ``None``.
		:raises TypeError:                  If parameter ``source`` isn't of type :class:`Risk`.
		:raises NotInSameRiskRegisterError: If parameter ``source`` isn't part of a risk register.
		:raises NotInSameRiskRegisterError: If this risk isn't part of the source's risk register.
		:raises ValueError:                 If parameter ``kind`` is ``None``.
		:raises TypeError:                  If parameter ``kind`` isn't of type :class:`LinkKind`.
		:raises DuplicateLinkError:         If the source already has a link of this kind to this risk.

		.. seealso::

		   :meth:`LinkTo`
		      |rarr| Create an outbound link from this risk to the given risk.
		"""
		if source is self:
			ex = ValueError("Parameter 'source' is this risk.")
			ex.add_note(f"Got risk '{source._id}'.")
			raise ex

		return Link(source, self, kind, keyValuePairs)

	def __repr__(self) -> str:
		"""
		Return a representation of the risk for debugging.

		An open risk ``R1`` of medium probability and high impact reads ``<Risk R1: Open, probability Medium,
		impact High, level Medium>``.

		:returns: The risk's ID, state, probability, impact and level.
		"""
		return (
			f"<Risk {self._id}: {self._state.name}, probability {self._probability.name}, impact {self._impact.name}, "
			f"level {self.Level.name}>"
		)


@export
class Link(KeyValuePairsMixin, metaclass=ExtendedType, slots=True):
	"""
	A link from a source risk to a destination risk of the same risk register, and the relationship it states.

	A link connects two risks; it is no element of the risk register and has no parent. The source lists it in
	:attr:`~Risk.OutboundLinks`, the destination in :attr:`~Risk.InboundLinks`, the risk register in
	:attr:`~RiskManagement.Links`.
	"""

	_source:      Risk      #: The risk the link starts at.
	_destination: Risk      #: The risk the link ends at.
	_kind:        LinkKind  #: The relationship the link states.

	def __init__(
		self,
		source: Risk,
		destination: Risk,
		kind: LinkKind,
		keyValuePairs: Nullable[Mapping[Hashable, Any]] = None
	) -> None:
		"""
		Initializes a link, and adds it to its source, its destination and their risk register.

		:param source:                      The risk the link starts at.
		:param destination:                 The risk the link ends at.
		:param kind:                        The relationship the link states.
		:param keyValuePairs:               Optional, the key-value pairs. Default: ``None``.
		:raises TypeError:                  If parameter ``keyValuePairs`` isn't a mapping.
		:raises ValueError:                 If parameter ``source`` is ``None``.
		:raises TypeError:                  If parameter ``source`` isn't of type :class:`Risk`.
		:raises NotInSameRiskRegisterError: If parameter ``source`` isn't part of a risk register.
		:raises ValueError:                 If parameter ``destination`` is ``None``.
		:raises TypeError:                  If parameter ``destination`` isn't of type :class:`Risk`.
		:raises ValueError:                 If parameter ``destination`` is the source.
		:raises NotInSameRiskRegisterError: If parameter ``destination`` isn't part of the source's risk register.
		:raises ValueError:                 If parameter ``kind`` is ``None``.
		:raises TypeError:                  If parameter ``kind`` isn't of type :class:`LinkKind`.
		:raises DuplicateLinkError:         If the source already has a link of this kind to the destination.
		"""
		super().__init__(keyValuePairs)

		if source is None:
			raise ValueError("Parameter 'source' is None.")
		elif not isinstance(source, Risk):
			ex = TypeError("Parameter 'source' is not of type 'Risk'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(source)}'.")
			raise ex
		elif source._root is None:
			ex = NotInSameRiskRegisterError("Parameter 'source' isn't part of a risk register.")
			ex.add_note(f"Got risk '{source._id}'.")
			raise ex

		if destination is None:
			raise ValueError("Parameter 'destination' is None.")
		elif not isinstance(destination, Risk):
			ex = TypeError("Parameter 'destination' is not of type 'Risk'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(destination)}'.")
			raise ex
		elif destination is source:
			ex = ValueError("Parameter 'destination' is the source.")
			ex.add_note(f"Got risk '{destination._id}'.")
			raise ex
		elif destination._root is not source._root:
			ex = NotInSameRiskRegisterError("Parameter 'destination' isn't part of the source's risk register.")
			ex.add_note(f"Got risk '{destination._id}'.")
			raise ex

		if kind is None:
			raise ValueError("Parameter 'kind' is None.")
		elif not isinstance(kind, LinkKind):
			ex = TypeError("Parameter 'kind' is not of type 'LinkKind'.")
			ex.add_note(f"Got type '{getFullyQualifiedName(kind)}'.")
			raise ex

		for link in source._outboundLinks:
			if link._destination is destination and link._kind is kind:
				raise DuplicateLinkError(f"Risk '{source._id}' already has a '{kind.name}' link to risk '{destination._id}'.")

		self._source =      source
		self._destination = destination
		self._kind =        kind

		source._outboundLinks.append(self)
		destination._inboundLinks.append(self)
		source._root._links.append(self)


	@readonly
	def Source(self) -> Risk:
		"""
		Read-only property to access the risk the link starts at (:attr:`_source`).

		:returns: The source risk.
		"""
		return self._source

	@readonly
	def Destination(self) -> Risk:
		"""
		Read-only property to access the risk the link ends at (:attr:`_destination`).

		:returns: The destination risk.
		"""
		return self._destination

	@readonly
	def Kind(self) -> LinkKind:
		"""
		Read-only property to access the relationship the link states (:attr:`_kind`).

		:returns: The link's kind.
		"""
		return self._kind

	def __repr__(self) -> str:
		"""
		Return a representation of the link for debugging.

		A link stating risk ``R1`` causes risk ``R2`` reads ``<Link R1 Causes R2>``.

		:returns: The IDs of the source and the destination, and the link's kind.
		"""
		return f"<Link {self._source._id} {self._kind.name} {self._destination._id}>"