calibration_utils¶
Description of helper functions for calibration step implemented in the module bnn_for_14C_calibration.calibration_utils:
bnn_for_14C_calibration.calibration_utils
¶
compute_HPD_regions(alpha, density=None, nb_intervals=1000, support_bounds=(0, 1), subdivision_components=None)
¶
Compute the Highest Posterior Density (HPD) region for a univariate posterior distribution represented by a piecewise-constant density function on a regular subdivision.
Let \(f\) be a density of the posterior distribution. Then, the HPD region for credibility level (\(1 - \alpha\)) is the set: $$ \text{HPD} = \{ x : f(x) \ge k_{1-\alpha} \} $$ where \(k_{1-\alpha}\) is the smallest value such that the total posterior mass of the set \(\{ x : f(x) \ge k_{1-\alpha} \}\) is at least (\(1 - \alpha\)).
This function approximates the posterior density using midpoint densities on
nb_intervals sub-intervals. The HPD region may be disconnected; the function returns
all connected components of the HPD set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
float
|
Tail probability. The HPD region contains mass (1 - alpha). Must satisfy 0 <= alpha <= 1. |
required |
density
|
callable
|
A function |
None
|
nb_intervals
|
int
|
Number of equal-length subintervals of the support on which the density is
approximated as piecewise constant (based on midpoint evaluation). |
1000
|
support_bounds
|
tuple of float
|
Tuple |
(0, 1)
|
subdivision_components
|
tuple or list of three numpy.ndarray
|
Precomputed components for the density approximation: |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
{ |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
ValueError
|
If neither |
Notes
Piecewise-constant density approximation
When the user does not provide subdivision_components, the support is subdivided
into nb_intervals equal-length intervals of width:
$$
h = \dfrac{1 - 0}{\text{nb_intervals}}.
$$
The posterior density is then approximated as constant on each interval, equal to
the value at its midpoint. The normalisation is computed via the sum of these
midpoint densities, which is mathematically equivalent to a trapezoidal scheme
specialised to constant-per-interval densities.
Computation of the HPD region
Let \((f_i)_{1 \le i \le N}\) be the midpoint densities and let \((I_i)_{1 \le i \le N}\) be their associated intervals. Sorting the \(f_i\) in decreasing order produces a sequence of density levels ordered from the most probable to the least probable regions of the posterior.
Define the scaled cumulative sum: $$ S_k = \dfrac{f_{(1)} + \cdots + f_{(k)}}{\sum_{i=1}^N f_i}, $$ where \((j)\) denotes the ordering from largest to smallest. The index \(k\) such that: $$ S_k \ge 1 - \alpha $$ determines the HPD density threshold: $$ k_{1-\alpha} = \dfrac{f_{(k)}}{\sum_{i=1}^N f_i}. $$ All intervals whose midpoint density is equal or greater than \(k_{1-\alpha}\) belong to the HPD region. Adjacent selected intervals are merged into connected components.
The function returns:
- the HPD threshold \(k_{1-\alpha}\),
- the connected HPD components expressed in terms of scaled dates
(see minimax_scaling),
- the (scaled) posterior mode and its density.
Examples:
>>> f = lambda x: 2*(1 - x)
>>> res = compute_HPD_regions(alpha=0.1, density=f, nb_intervals=1000)
>>> "connexe_HPD_intervals" in res
True
Source code in src/bnn_for_14C_calibration/calibration_utils.py
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 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 | |
mono_cal_date_approx_cumulative_fct(density=None, nb_intervals=1000, support_bounds=(0, 1), subdivision_components=None)
¶
Approximate the posterior cumulative distribution function (CDF) for a single calibrated radiocarbon date.
This function builds a continuous CDF from either:
- a callable density function density, or
- precomputed subdivision components (interval bounds, middle points, densities at middle points).
The continuity of the resulting CDF is a direct mathematical consequence of the sampling strategy used for generating posterior samples: each interval is chosen with probability proportional to its middle-point density, and points within the interval are drawn uniformly. This results in a CDF that increases linearly within each interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
density
|
callable
|
A function |
None
|
nb_intervals
|
int
|
Number of subintervals to discretize the support for the density approximation.
Overrided internally if |
1000
|
support_bounds
|
tuple of float
|
Tuple |
(0, 1)
|
subdivision_components
|
tuple or list of three numpy.ndarray
|
Precomputed components for the density approximation: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
cumulative_density |
callable
|
A function |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
ValueError
|
If neither |
Notes
- Let the support \([a,b]\) be subdivided into N intervals \([x_j, x_{j+1}]\) with
middle points \(m_j = \frac{x_j + x_{j+1}}{2}\), and let \(f_j = density(m_j)\).
The approximate \(CDF\) at a point \(d \in [x_j, x_{j+1}]\) is:
$$
CDF(d) = \sum_{i=1}^{j-1} \dfrac{f_i}{\sum_{k=1}^N f_k} +
\dfrac{f_j}{\sum_{k=1}^N f_k} \dfrac{d - x_j}{x_{j+1} - x_j}
$$
where the first term sums contributions from previous intervals, and the second term accounts for the uniform distribution inside the current interval. - Continuity of the CDF arises naturally from the uniform distribution inside intervals.
- This approach provides a simple and fast approximation suitable for sampling posterior dates. For N → ∞, the discrete sum converges to the integral of the continuous piecewise density function.
Examples:
>>> density_fn = mono_cal_date_approx_density(
... mesure=0.954,
... lab_error=0.002,
... bnn_model=my_trained_bnn,
... nb_curves=200
... )
>>> cdf_fn = mono_cal_date_approx_cumulative_fct(density=density_fn, nb_intervals=1000)
>>> scaled_date = 0.25
>>> cdf_value = cdf_fn(scaled_date)
>>> isinstance(cdf_value, float)
True
Source code in src/bnn_for_14C_calibration/calibration_utils.py
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 | |
mono_cal_date_approx_density(mesure, lab_error, bnn_model, nb_curves=100, prior_density='default', batch_size=None)
¶
Approximate the posterior density function for a single radiocarbon date calibration.
This function computes an approximate posterior density for a given measured
radiocarbon date using a trained Bayesian Neural Network (BNN) model.
The approximation is done by sampling multiple stochastic realizations of
the BNN predictions and combining them with a likelihood term based on
the laboratory measurement error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mesure
|
float
|
The measured radiocarbon age (expressed in the F\(^{14}\)C domain). |
required |
lab_error
|
float
|
The measurement uncertainty (standard deviation) associated with the lab measurement (also in the F\(^{14}\)C domain). |
required |
bnn_model
|
object
|
The trained Bayesian Neural Network model used to estimate the predictive distribution. |
required |
nb_curves
|
int
|
Number of stochastic realizations (Monte Carlo samples) to use for
approximating the BNN predictive distribution. |
100
|
prior_density
|
(default, callable)
|
Prior probability density over the calendar dates' domain. |
"default"
|
batch_size
|
int
|
Batch size for model predictions, passed to the internal
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
density |
callable
|
A function |
Notes
- The posterior density is proportional to the product of the prior and the likelihood:
\( p(d|m) ∝ p(d) × E_{BNN}[ \exp(-(m - F^{14}C(d))^2 / (2σ^2)) ] \).
This expectation is approximated by averaging over multiple stochastic predictions of the BNN model. - The uniform prior currently assumes that the scaled ages' calibration domain is
[0, 1];
future implementations should allow to replace this with the actual domain limits or use other values to approximate these limits (e.g. training data domain bounds).
Another implementation improvement may be to make it possible to handle the use of acallablewhich gives a custom prior density function of the formf(dates) → np.ndarray. - The output density is not normalized; normalization must be handled externally if necessary (e.g., via numerical integration).
Examples:
>>> density_fn = mono_cal_date_approx_density(
... mesure=0.954,
... lab_error=0.002,
... bnn_model=my_trained_bnn,
... nb_curves=200
... )
>>> ages = np.linspace(0, 1, 500)
>>> posterior_vals = density_fn(ages)
>>> posterior_vals.shape
(500,)
Source code in src/bnn_for_14C_calibration/calibration_utils.py
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 | |
mono_cal_date_approx_density_sample(density=None, nb_intervals=1000, support_bounds=(0.0, 1.0), subdivision_components=None, sample_size=1)
¶
Draw samples from an univariate, unnormalized posterior density using a piecewise-constant approximation over a regular grid.
This function is typically used in Bayesian radiocarbon calibration to draw samples from the approximate posterior distribution of a single calibrated date, when the posterior density is only available up to a multiplicative constant or when direct numerical integration is not desirable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
density
|
callable or None
|
A function evaluating the unnormalized posterior density on an array
of points. Required unless |
None
|
nb_intervals
|
int
|
Number of subintervals defining the grid approximation of the density. |
1000
|
support_bounds
|
tuple of float
|
Lower and upper bounds of the support. Only (0, 1) is currently supported. |
(0.0, 1.0)
|
subdivision_components
|
tuple of numpy.ndarray or None
|
Optional tuple (interval_bounds, midpoints, midpoint_densities). If provided, these arrays are reused directly. |
None
|
sample_size
|
int
|
Number of posterior samples to generate. |
1
|
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple (d, unnorm_prob, norm_prob) with: |
Notes
1. Posterior density availability
The function assumes that the posterior density `p(d | m)` is only known
through an unnormalized function:
f(d) ∝ p(d | m)
This is the case when the density results from Monte Carlo averaging over a
Bayesian Neural Network (BNN), where:
f(d) = p(d) × E_BNN[ exp(-(m - F¹⁴C(d))² / (2σ²)) ] / (σ √(2π))
Since the density is unnormalized, classical continuous inversion sampling
is not possible. Instead, a piecewise-constant discretization is used.
2. Numerical approximation
The interval [0, 1] is subdivided into `nb_intervals` equal subintervals.
On each subinterval, the density is approximated by its midpoint value:
f(d) ≈ f(d_j*) for d in interval j
yielding discrete weights:
p_j = f(d_j*) / Σ_k f(d_k*)
which define a categorical distribution over the intervals.
3. Sampling algorithm
Sampling is performed as follows:
1. Compute (or reuse) midpoints `d_j*` and their unnormalized densities.
2. Normalize these densities to obtain probabilities over subintervals.
3. Draw an interval index J according to these probabilities.
4. Draw a uniform sample on the chosen interval:
d ~ Uniform(interval_bounds[J-1], interval_bounds[J])
This yields samples approximately distributed according to the target
posterior density.
4. Precomputed subdivision
If `subdivision_components = (bounds, midpoints, densities)` is supplied,
the function skips all density evaluations and directly reuses the
piecewise-constant representation.
This is useful when repeatedly sampling from the same density is needed,
e.g. inside an MCMC procedure.
5. Support and limitations
- Only the default support (0, 1) is currently implemented.
- The method is *univariate*.
Multivariate posterior sampling must instead rely on MCMC (e.g.
Metropolis–Hastings within Gibbs), since grid-based density approximation
in higher dimension is impractical due to the curse of dimensionality.
- The density is never normalized by continuous integration (on purpose),
this yields a converging approximation of f(d) when the number of subintervals,
`nb_intervals`, tends to infinity.
Examples:
>>> density = lambda x: np.exp(-(x-0.4)**2 / 0.01)
>>> d, f_unnorm, f_norm = mono_cal_date_approx_density_sample(
... density=density,
... sample_size=5
... )
Source code in src/bnn_for_14C_calibration/calibration_utils.py
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 | |
mono_cal_date_approx_vect_cumulative_fct(density=None, nb_intervals=1000, support_bounds=(0, 1), subdivision_components=None)
¶
Vectorized version of mono_cal_date_approx_cumulative_fct for approximation
of the posterior cumulative distribution function (CDF)
for a single calibrated radiocarbon date.
This function returns a vectorized CDF: it takes an array of scaled dates and returns an array of the same shape containing the corresponding cumulative probabilities.
The CDF is constructed from either:
- a callable density function density, or
- precomputed subdivision components (interval bounds, middle points,
densities at middle points).
As in the scalar version, the continuity of the CDF is a direct mathematical consequence of the sampling strategy: intervals are chosen with probability proportional to their middle–point density, and values inside each interval are drawn uniformly. This implies a linear increase of the CDF inside each interval.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
density
|
callable
|
A function |
None
|
nb_intervals
|
int
|
Number of subintervals to discretize the support for the density approximation.
Overrided internally if |
1000
|
support_bounds
|
tuple of float
|
Tuple |
(0, 1)
|
subdivision_components
|
tuple or list of three numpy.ndarray
|
Precomputed components for the density approximation: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
cumulative_density |
callable
|
A vectorized function:
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
ValueError
|
If neither |
Notes
Let the support \([a,b]\) be subdivided into N intervals \([x_j, x_{j+1}]\) with
middle points \(m_j = \frac{x_j + x_{j+1}}{2}\), and let \(f_j = density(m_j)\).
The approximate \(CDF\) at a point \(d \in [x_j, x_{j+1}]\) is:
$$
CDF(d) = \sum_{i=1}^{j-1} \dfrac{f_i}{\sum_{k=1}^N f_k} +
\dfrac{f_j}{\sum_{k=1}^N f_k} \dfrac{d - x_j}{x_{j+1} - x_j} \, ,
$$
where the first term sums contributions from previous intervals, and the second
term accounts for the uniform distribution inside the current interval.
The CDF is continuous because the sampling strategy draws uniformly inside the selected interval.
The vectorized function applies this formula simultaneously to an array of points.
Examples:
>>> density_fn = mono_cal_date_approx_density(
... mesure=0.954,
... lab_error=0.002,
... bnn_model=my_trained_bnn,
... nb_curves=200
... )
>>> cdf_fn = mono_cal_date_approx_vect_cumulative_fct(density=density_fn, nb_intervals=1000)
>>> scaled_dates = np.array([0.25, 0.5, 0.8])
>>> cdf_values = cdf_fn(scaled_dates)
>>> cdf_values.shape
(3,)
Source code in src/bnn_for_14C_calibration/calibration_utils.py
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 | |
mono_cal_date_discrete_approx_quantile_fct(density=None, nb_intervals=1000, support_bounds=(0, 1), subdivision_components=None)
¶
Approximate the posterior quantile function for a single calibrated radiocarbon date using a discrete grid derived from the posterior density approximation.
The quantile returned for a level alpha is the closest discrete realization
available on the grid, i.e. the first grid point whose discretized CDF is greater
than or equal to alpha. This is a purely discrete approximation, unlike the
continuous quantile obtainable via inversion of a continuous CDF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
density
|
callable
|
A function |
None
|
nb_intervals
|
int
|
Number of subintervals to discretize the support for the density approximation.
Ignored if |
1000
|
support_bounds
|
tuple of float
|
Tuple |
(0, 1)
|
subdivision_components
|
tuple or list of three numpy.ndarray
|
Precomputed components for the density approximation: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
discrete_alpha_quantile |
callable
|
A function |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
ValueError
|
If neither |
Notes
Approximation of the CDF.
Let the posterior density be approximated on nb_intervals subintervals
by evaluating it at middle points \(m_j\) with corresponding values \(f_j\).
The cumulative density assigned to a middle point is then written as:
$$
\forall j \in \{ 1, \cdots, N \} \,,
F(m_j)
= \dfrac{\frac{f_j}{2} + \sum_{i=1}^{j-1} f_i}{\sum_{k=1}^N f_k},
$$
where:
- \(\sum_{i<j} f_i\) represents the (unnormalized) cumulative probability mass of the intervals
preceding the j-th,
- \(f_j/2\) accounts for integrating half of the (piecewise) constant density over the current
interval up to its midpoint.
This expression arises directly from the integration of the piecewise constant density implicitly defined by the sampling strategy of the approximate posterior: selecting an interval proportionally to its density and drawing uniformly inside it.
Discrete quantile.
Extending the discretized CDF with values:
- \(F = 0\) at the lower bound,
- \(F = 1\) at the upper bound,
we obtain an ordered set of cumulative probabilities:
$$
0 = F_0 < F(m_1) < \dots < F(m_{N}) < F_{N+1} = 1.
$$
The discrete quantile is then defined as: $$ Q_{\text{disc}}(\alpha) = x_{k} \quad \text{where } k = \min\{ i : F_i \ge \alpha \}, $$ with \(x_k\) the corresponding support point (a midpoint, the lower bound, or the upper bound).
This approximation converges to the true quantile as the number of intervals increases, because the piecewise-constant density and its cumulative sum are standard Riemann approximations of the continuous density and CDF.
Examples:
>>> density_fn = mono_cal_date_approx_density(
... mesure=0.954,
... lab_error=0.002,
... bnn_model=my_trained_bnn,
... nb_curves=200
... )
>>> q_fn = mono_cal_date_discrete_approx_quantile_fct(density_fn, nb_intervals=2000)
>>> q25 = q_fn(0.25)
>>> isinstance(q25, float)
True
Source code in src/bnn_for_14C_calibration/calibration_utils.py
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 | |
mono_cal_date_exact_approx_quantile_fct(density=None, nb_intervals=1000, support_bounds=(0, 1), subdivision_components=None)
¶
Compute a continuous approximation of the posterior quantile function for a single calibrated radiocarbon date by analytically inverting the piecewise-linear CDF obtained from the piecewise-constant approximation of the posterior density.
This contrasts with the discrete quantile approximation, which selects
the closest grid point. Here, the quantile is obtained by solving an
affine equation inside the unique interval where the continuous CDF
crosses alpha.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
density
|
callable
|
A function |
None
|
nb_intervals
|
int
|
Number of subintervals to discretize the support for the density approximation.
Overrided internally if |
1000
|
support_bounds
|
tuple of float
|
Tuple |
(0, 1)
|
subdivision_components
|
tuple or list of three numpy.ndarray
|
Precomputed components for the density approximation: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
exact_alpha_quantile |
callable
|
A function |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If |
ValueError
|
If neither |
Notes
1. Approximate posterior density.
As in the discrete quantile version, the posterior density is approximated
by a piecewise-constant function:
$$
f(d) \approx f(m_j) := f_j \quad \text{for } d \in [x_j, x_{j+1}],
$$
where \(x_j\) are interval bounds and \(m_j = \frac{x_j+x_{j+1}}{2}\) are midpoints.
2. Approximate CDF at interval bounds.
The cumulative probability at the bounds is:
$$
F(x_j)
= \dfrac{\sum_{i=1}^{j} f_i}{\sum_{k=1}^{N} f_k}.
$$
These values form a strictly increasing sequence from 0 to 1.
3. Continuous quantile: inversion on each interval.
Inside the interval \([x_j, x_{j+1}]\), the density is constant, hence
the CDF is affine:
$$
F(d) = F(x_j) + \dfrac{f_j}{\sum_{k=1}^N f_k}\,\dfrac{d - x_j}{x_{j+1} - x_j}.
$$
To find the quantile of order \(\alpha\), determine the unique interval where:
$$
F(x_j) < \alpha \le F(x_{j+1}),
$$
and solve for d:
$$
d = x_j +
\frac{h}{f_j} \left( \alpha \sum_{k=1}^N f_k- \sum_{i=1}^{j} f_i \right)
:= Q(\alpha) \, ,
$$
where \(h = x_{j+1} - x_j \, , \quad \forall j \in \{ 1, \cdots, N \}\).
4. Difference with the discrete quantile.
- Discrete quantile selects the closest grid point.
- Continuous quantile solves a linear equation inside the interval.
- This yields a true continuous function of \(\alpha\) with no jumps.
- Both converge to the exact quantile as the grid is refined, but the
continuous version converges faster.
Examples:
>>> density_fn = mono_cal_date_approx_density(
... mesure=0.954,
... lab_error=0.002,
... bnn_model=my_trained_bnn,
... nb_curves=200
... )
>>> q_fn = mono_cal_date_exact_approx_quantile_fct(density_fn, nb_intervals=2000)
>>> q25 = q_fn(0.25)
>>> isinstance(q25, float)
True
Source code in src/bnn_for_14C_calibration/calibration_utils.py
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 | |
multi_cal_date_approx_density(mesures, lab_errors, bnn_model, nb_curves=100, prior_density='default', batch_size=None)
¶
Approximate the joint posterior density for multiple radiocarbon dates.
This function generalizes the single-date calibration approach to the case
where several radiocarbon dates are calibrated simultaneously.
It computes an approximate joint posterior density over the vector of
(scaled) calendar dates, using a trained Bayesian Neural Network (BNN) model
as an estimator of the calibration curve in the F¹⁴C domain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mesures
|
np.ndarray of shape (n_dates,)
|
The measured radiocarbon ages expressed in the F¹⁴C domain. |
required |
lab_errors
|
np.ndarray of shape (n_dates,)
|
The laboratory measurement uncertainties (standard deviations), also expressed in the F¹⁴C domain. |
required |
bnn_model
|
object
|
The trained Bayesian Neural Network model used to estimate the predictive distribution. |
required |
nb_curves
|
int
|
Number of stochastic realizations (Monte Carlo samples) to use for
approximating the BNN predictive distribution. |
100
|
prior_density
|
(default, callable)
|
Prior probability density over the vector of scaled calendar dates. |
"default"
|
batch_size
|
int
|
Batch size for model predictions, passed to the internal
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
density |
callable
|
A function |
Notes
- The posterior density is proportional to:
\( p(\mathbf{d}|\mathbf{m}) ∝ p(\mathbf{d}) × E_{BNN}[ \prod_i \exp(-(m_i - \hat{F}^{14}C(d_i))^2 / (2σ_i^2)) ] \).
The expectation over the BNN distribution is approximated by Monte Carlo averaging. - The
"default"prior corresponds to a uniform independent prior over each scaled date in[0, 1]. - The output density is not normalized; handling normalization here via numerical integration over a multi-dimensional grid is not a good idea because of the curse of dimensionality. In general, trying to do so will not be necessary because the outputs densities are expected to be used within a MCMC sampler (e.g. Metropolis-Hastings within Gibbs sampler).
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If a non-default prior density is provided (custom priors are not yet supported). |
Examples:
>>> mesures = np.array([0.954, 0.928])
>>> lab_errors = np.array([0.002, 0.003])
>>> density_fn = multi_cal_date_approx_density(
... mesures=mesures,
... lab_errors=lab_errors,
... bnn_model=my_trained_bnn,
... nb_curves=200
... )
>>> date_grid = np.random.rand(100, 2) # 100 candidate date vectors
>>> posterior_vals = density_fn(date_grid)
>>> posterior_vals.shape
(100,)
Source code in src/bnn_for_14C_calibration/calibration_utils.py
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 | |
optimise_credible_interval(quantile, alpha)
¶
Optimize the (1 - alpha)-credible interval for a single calibrated radiocarbon date by minimizing its length over all intervals of the form [Q(beta), Q(1 - alpha + beta)], where Q is a continuous posterior quantile function.
The optimization variable beta ∈ [0, alpha] determines the lower tail mass excluded from the interval. For a symmetric posterior, the optimal value is beta = alpha/2 (equal-tailed interval). For asymmetric posteriors, the optimal beta shifts to achieve the shortest interval of posterior mass (1 - alpha).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quantile
|
callable
|
A continuous quantile function Q(u) mapping u ∈ [0,1] to posterior dates.
Must satisfy: |
required |
alpha
|
float
|
Posterior tail probability. The credible interval contains mass (1 - alpha). Must satisfy 0 <= alpha <= 1. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
beta_opt |
object
|
The SciPy optimization result. The optimal value is:
beta_opt.x[0] |
Raises:
| Type | Description |
|---|---|
ValueError
|
If alpha is not between 0 and 1. |
Notes
Mathematical background.
For any beta ∈ [0, alpha], the interval I_beta = [Q(beta), Q(1 - alpha + beta)] has posterior probability (1 - alpha).
Its length is L(beta) = Q(1 - alpha + beta) - Q(beta).
The shortest credible interval is obtained by solving: beta* = argmin_{beta ∈ [0, alpha]} L(beta).
When the posterior is unimodal, this interval coincides with the HPD (Highest Posterior Density) region. When the posterior is multimodal, the HPD region may be disconnected, but this function returns the shortest connected interval of mass (1 - alpha).
The optimization is performed using the Nelder–Mead method. In recent versions of SciPy, the bounds provided are used to constrain the shape and updates of the simplex, ensuring that the iterates remain within the allowed domain [0, alpha].
Examples:
>>> Q = lambda u: u**2 # toy quantile function
>>> res = optimise_credible_interval(Q, alpha=0.2)
>>> float(res.x[0]) >= 0
True
Source code in src/bnn_for_14C_calibration/calibration_utils.py
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 | |