Skip to content

calib_plot_functions

Description of all functions implemented in the module bnn_for_14C_calibration.calib_plot_functions:

bnn_for_14C_calibration.calib_plot_functions

add_IntCal20_curve(ax=None, figsize=None, color='green', alpha=0.4, incertitude=True, sigma_length=1, Min_x=None, Max_x=None, Min_y=None, Max_y=None, invert_xaxis=True, domaine=['delta14c', 'c14', 'f14c'][0])

Add the IntCal20 radiocarbon calibration curve to a Matplotlib axis.

The IntCal20 curve is plotted in one of three possible domains:

  • 'c14': radiocarbon ages (BP)
  • 'f14c': Fraction Modern F¹⁴C
  • 'delta14c': Δ¹⁴C (per mil)

Optional uncertainty bands corresponding to sigma_length standard deviations may be added around the curve.

Parameters:

Name Type Description Default
ax Axes or None

Axis on which to draw the curve. If None, uses plt.gca().

None
figsize tuple or None

Figure size passed to pandas' DataFrame.plot method. Only used when ax is None.

None
color str

Main curve color (default: "green").

'green'
alpha float

Transparency of the uncertainty band (default: 0.4).

0.4
incertitude bool

If True, plot the ±σ uncertainty region around the curve.

True
sigma_length int

Number of standard deviations for the uncertainty band.

1
Min_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Max_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Min_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
Max_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
invert_xaxis bool

If True (default), invert the x-axis so that time decreases to the right, consistent with radiocarbon convention.

True
domaine (delta14c, c14, f14c)

Domain in which to plot the curve. Default is 'delta14c'.

'delta14c'

Returns:

Type Description
Axes

The axis containing the plotted calibration curve.

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
 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
def add_IntCal20_curve(
    ax: plt.Axes = None,
    figsize: tuple = None,
    color: str = "green",
    alpha: float = 0.4,
    incertitude: bool = True,
    sigma_length: int = 1,
    Min_x: float = None,
    Max_x: float = None,
    Min_y: float = None,
    Max_y: float = None,
    invert_xaxis: bool = True,
    domaine: str = ['delta14c', 'c14', 'f14c'][0]
) -> plt.Axes:
    """
    Add the IntCal20 radiocarbon calibration curve to a Matplotlib axis.

    The IntCal20 curve is plotted in one of three possible domains:

    - ``'c14'``: radiocarbon ages (BP)
    - ``'f14c'``: Fraction Modern F¹⁴C
    - ``'delta14c'``: Δ¹⁴C (per mil)

    Optional uncertainty bands corresponding to ``sigma_length`` standard
    deviations may be added around the curve.

    Parameters
    ----------
    ax : matplotlib.axes.Axes or None, optional
        Axis on which to draw the curve. If None, uses ``plt.gca()``.
    figsize : tuple or None, optional
        Figure size passed to pandas' ``DataFrame.plot`` method. Only used
        when ``ax`` is None.
    color : str, optional
        Main curve color (default: ``"green"``).
    alpha : float, optional
        Transparency of the uncertainty band (default: 0.4).
    incertitude : bool, optional
        If True, plot the ±σ uncertainty region around the curve.
    sigma_length : int, optional
        Number of standard deviations for the uncertainty band.
    Min_x, Max_x : float or None, optional
        Optional x-axis limits; when both provided the axis limits are set.
    Min_y, Max_y : float or None, optional
        Optional y-axis limits; when both provided the axis limits are set.
    invert_xaxis : bool, optional
        If True (default), invert the x-axis so that time decreases to the right,
        consistent with radiocarbon convention.
    domaine : {'delta14c', 'c14', 'f14c'}
        Domain in which to plot the curve. Default is ``'delta14c'``.

    Returns
    -------
    matplotlib.axes.Axes
        The axis containing the plotted calibration curve.

    """


    # courbe IntCal20
    IntCal20_file_path = IntCal20_dir / "IntCal20_completed.csv"
    IntCal20 = pd.read_csv(IntCal20_file_path, sep =",")

    # Création de l'axe si pas fourni
    if ax == None :
        ax = plt.gca()

    # choix du domaine
    if domaine == 'c14' :
        y_name = 'c14age'
        y = IntCal20.c14age.values
        y_sigma = IntCal20.c14sigma.values
    elif domaine == 'f14c' :
        y_name = 'c14age'
        y = c14_to_f14c(IntCal20.c14age.values)
        y_sigma = c14sig_to_f14csig(IntCal20.c14age.values, IntCal20.c14sigma.values)
        IntCal20['c14age'] = y
        IntCal20['c14sigma'] = y_sigma
    else : 
        #domaine = 'delta14c'
        y_name = 'd14c'
        y = IntCal20.d14c.values
        y_sigma = IntCal20.d14csigma.values

    # ajout de IntCal20 sur ax
    IntCal20.plot(
        x = 'calage',
        y = y_name,
        label = 'IntCal20',
        figsize = figsize,
        ax = ax,
        color = color
    )

    # Incertitude autour de la courbe
    if incertitude :
        ax.fill_between(
            IntCal20.calage.values, 
            y - sigma_length * y_sigma,
            y + sigma_length * y_sigma,
            label=f"IntCal20 $\pm$ {sigma_length} $\sigma$", 
            color= color, 
            alpha=alpha
        )

    # setup des axes
    if Min_y != None and Max_y != None :
        ax.set_ylim(Min_y, Max_y)
    if Min_x != None and Max_x != None :
        ax.set_xlim(Min_x, Max_x)
    if invert_xaxis :
        ax.invert_xaxis()

    return ax

add_bnn_calibration_curve(ax=None, figsize=None, color='cyan', alpha=0.4, incertitude=True, sigma_length=1, Min_x=None, Max_x=None, Min_y=None, Max_y=None, invert_xaxis=True, domaine=['delta14c', 'c14', 'f14c'][0], covariables=False, label_prefix='', label_suffix='', credible_interval=False, credible_interval_level=0.95, credible_color=None, credible_alpha=None)

Add the full BNN calibration curve (concatenated parts 1 and 2) to a given matplotlib axis.

This function:

  • loads precomputed BNN predictions from both sections of the calibration model, previously concatenated using concatenate_curves_parts;
  • rescales the middle points to calendar ages (BP);
  • converts predictions to the selected domain (Δ14C, 14C age, or F14C);
  • plots the mean BNN prediction curve;
  • optionally adds the ±σ uncertainty band;
  • optionally adds credible intervals obtained from the posterior predictive samples.

Parameters:

Name Type Description Default
ax Axes or None

Axis to draw on. If None, the current axis from matplotlib.pyplot.gca() is used. Default is None.

None
figsize tuple(int, int) or None

Size of the matplotlib figure used by the underlying DataFrame.plot call.

None
color str

Color used for plotting the curve and uncertainty bands.

'cyan'
alpha float

Transparency level for uncertainty shading and credible interval bands.

0.4
incertitude bool

Whether to add the ±σ uncertainty band around the mean curve.

True
sigma_length int

Width of the uncertainty band in standard deviations.

1
Min_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Max_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Min_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
Max_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
invert_xaxis bool

Whether to invert the x-axis (used for IntCal-style plots).

True
domaine (delta14c, c14, f14c)

Domain of radiocarbon quantities displayed.

'delta14c'
covariables bool

Whether to use BNN predictions trained with covariates.

False
label_prefix str

String prepended to the curve label.

''
label_suffix str

String appended to the curve label.

''
credible_interval bool

Whether to compute and display credible intervals for the BNN predictions.

False
credible_interval_level float

Credible interval level (e.g., 0.95 for 95% CI).

0.95
credible_color str or None

Color of the credible interval shading (defaults to color).

None
credible_alpha float or None

Transparency of the credible interval shading (defaults to alpha).

None

Returns:

Type Description
Axes

The axis containing the plotted BNN calibration curve.

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
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
def add_bnn_calibration_curve(
    ax: Optional[plt.Axes] = None,
    figsize: Optional[Tuple[int, int]] = None,
    color: str = 'cyan',
    alpha: float = .4,
    incertitude: bool = True,
    sigma_length: int = 1,
    Min_x: Optional[float] = None, Max_x: Optional[float] = None,
    Min_y: Optional[float] = None, Max_y: Optional[float] = None,
    invert_xaxis: bool = True,
    domaine: str = ['delta14c', 'c14', 'f14c'][0],
    covariables: bool = False,
    label_prefix: str = '',
    label_suffix: str = '',
    credible_interval: bool = False,
    credible_interval_level: float = 0.95,
    credible_color: Optional[str] = None,
    credible_alpha: Optional[float] = None
) -> plt.Axes:
    """
    Add the full BNN calibration curve (concatenated parts 1 and 2) to a given
    matplotlib axis.

    This function:

    - loads precomputed BNN predictions from both sections of the calibration model,
      previously concatenated using ``concatenate_curves_parts``;
    - rescales the middle points to calendar ages (BP);
    - converts predictions to the selected domain (Δ14C, 14C age, or F14C);
    - plots the mean BNN prediction curve;
    - optionally adds the ±σ uncertainty band;
    - optionally adds credible intervals obtained from the posterior predictive samples.

    Parameters
    ----------
    ax : matplotlib.axes.Axes or None, optional
        Axis to draw on. If ``None``, the current axis from ``matplotlib.pyplot.gca()``
        is used. Default is ``None``.
    figsize : tuple(int, int) or None, optional
        Size of the matplotlib figure used by the underlying ``DataFrame.plot`` call.
    color : str, optional
        Color used for plotting the curve and uncertainty bands.
    alpha : float, optional
        Transparency level for uncertainty shading and credible interval bands.
    incertitude : bool, optional
        Whether to add the ±σ uncertainty band around the mean curve.
    sigma_length : int, optional
        Width of the uncertainty band in standard deviations.
    Min_x, Max_x : float or None, optional
        Optional x-axis limits; when both provided the axis limits are set.
    Min_y, Max_y : float or None, optional
        Optional y-axis limits; when both provided the axis limits are set.
    invert_xaxis : bool, optional
        Whether to invert the x-axis (used for IntCal-style plots).
    domaine : {'delta14c', 'c14', 'f14c'}, optional
        Domain of radiocarbon quantities displayed.
    covariables : bool, optional
        Whether to use BNN predictions trained with covariates.
    label_prefix : str, optional
        String prepended to the curve label.
    label_suffix : str, optional
        String appended to the curve label.
    credible_interval : bool, optional
        Whether to compute and display credible intervals for the BNN predictions.
    credible_interval_level : float, optional
        Credible interval level (e.g., 0.95 for 95% CI).
    credible_color : str or None, optional
        Color of the credible interval shading (defaults to ``color``).
    credible_alpha : float or None, optional
        Transparency of the credible interval shading (defaults to ``alpha``).

    Returns
    -------
    matplotlib.axes.Axes
        The axis containing the plotted BNN calibration curve.
    """

    # résultats issus de la concatenation de deux parties de la courbe
    concatenated_results = concatenate_curves_parts(
        covariables = covariables
    )

    middle_points_predictions = concatenated_results['middle_points_predictions_in_F14C']
    middle_points = concatenated_results['middle_points_rescaled']
    intervals_bounds = concatenated_results['intervals_bounds_rescaled']
    nb_curves = concatenated_results['nb_curves']

    Max_part_1 = concatenated_results['Max_part_1']
    Min_part_1 = concatenated_results['Min_part_1']
    #max_horizon_x_part_1 = concatenated_results['max_horizon_x_part_1']
    #max_horizon_x_part_1_scaled = concatenated_results['max_horizon_x_part_1_scaled']
    #min_horizon_x_part_1 = concatenated_results['min_horizon_x_part_1']
    #min_horizon_x_part_1_scaled = concatenated_results['min_horizon_x_part_1_scaled']

    Max_part_2 = concatenated_results['Max_part_2']
    Min_part_2 = concatenated_results['Min_part_2']
    #max_horizon_x_part_2 = concatenated_results['max_horizon_x_part_2']
    #max_horizon_x_part_2_scaled = concatenated_results['max_horizon_x_part_2_scaled']
    min_horizon_x_part_2 = concatenated_results['min_horizon_x_part_2']
    #min_horizon_x_part_2_scaled = concatenated_results['min_horizon_x_part_2_scaled']

    # intervals_bounds est une liste contenant les bornes des intervalles de 2 parties de la courbe
    # avec  borne max part 1 = borne min part 2 repétée donc 2 fois. 
    # nb_intervals = nombre de bornes - 2 et pas -1
    nb_intervals = len(intervals_bounds) - 2 

    # dates calibrées en années BP
    calage = minimax_scaling_reciproque(
        x = middle_points,
        Max = Max_part_2,
        Min = Min_part_1
    )

    # Création de l'axe si pas fourni
    if ax == None :
        ax = plt.gca()

    # choix du domaine
    if domaine == 'c14' :
        middle_points_predictions = f14c_to_c14(
            f14c = middle_points_predictions
        )
        y_name = 'c14age'
    elif domaine =='f14c' :
        y_name = 'f14c'
    else : 
        #domaine = 'delta14c'
        middle_points_predictions = f14c_to_d14c(
            f14c = middle_points_predictions, 
            teta = calage.repeat(nb_curves).reshape((nb_intervals, nb_curves))
        )
        y_name = 'd14c'

    # calcul courbe moyenne et écart-type
    y = middle_points_predictions.mean(axis=1)
    y_sigma = middle_points_predictions.std(axis=1)

    # ajout courbe moyenne sur ax
    df = pd.DataFrame({
        'calage': calage,
        y_name: y
    })

    df.plot(
        x = 'calage',
        y = y_name,
        label = label_prefix + 'BNN curve' + label_suffix,
        figsize = figsize,
        ax = ax,
        color = color
    )

    # Incertitude autour de la courbe
    if incertitude :
        ax.fill_between(
            calage, 
            y - sigma_length * y_sigma,
            y + sigma_length * y_sigma,
            label=label_prefix + "BNN curve" + label_suffix + f"$\pm$ {sigma_length} $\sigma$", 
            color= color, 
            alpha=alpha
        )

    # Intervalle de crédibilité
    if credible_interval :
        if credible_alpha == None :
            credible_alpha = alpha
        if credible_color == None :
            credible_color = color
        # calcul intervalle de crédibilité de chaque prédiction
        credible_intervals, _ = compute_credible_intervals_bounds(
            1 - credible_interval_level, middle_points_predictions
        )
        ax.fill_between(
            calage, 
            credible_intervals[0], 
            credible_intervals[1], 
            label=f"{round(100*credible_interval_level)}% CI for BNN curve", 
            color=credible_color, 
            alpha=credible_alpha
        )



    # setup des axes
    if Min_y != None and Max_y != None :
        ax.set_ylim(Min_y, Max_y)
    if Min_x != None and Max_x != None :
        ax.set_xlim(Min_x, Max_x)
    if invert_xaxis :
        ax.invert_xaxis()

    return ax

add_c14age_density_plot(c14age, c14sig, ax=None, color='gray', support_size=5, sample_size=1000, plot_density=False, fill_density=True)

Plot the probability density function of a radiocarbon (14C) age measurement, modeled as a Gaussian distribution with mean c14age and standard deviation c14sig. The plot can display the curve itself, a filled area, or both.

Parameters:

Name Type Description Default
c14age float

The measured conventional radiocarbon age (in years BP).

required
c14sig float

The standard deviation (1σ) of the radiocarbon age measurement.

required
ax Axes or None

Axis on which the plot is drawn. If None, the current axis (plt.gca()) is used.

None
color str

Color used for drawing or filling the density.

'gray'
support_size float

Half-width (in units of standard deviations) of the interval over which the density is evaluated.

5
sample_size int

Number of sample points used for plotting the density curve.

1000
plot_density bool

If True, the density curve is drawn.

False
fill_density bool

If True, the area between the y-axis and the density curve is filled.

True

Returns:

Type Description
Axes

The axis on which the plot is added.

Note

The distribution is actually Gaussian when radiocarbon measurements are expressed in terms of F\(^{14}\)C values. Although conventional radiocarbon ages are no longer Gaussian, Gaussian density is still used solely for graphical representation purposes.

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
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
def add_c14age_density_plot(
    c14age: float,
    c14sig: float,
    ax: Optional[plt.Axes] = None,
    color: str = "gray",
    support_size: float = 5,
    sample_size: int = 1000,
    plot_density: bool = False,
    fill_density: bool = True
) -> plt.Axes:
    """
    Plot the probability density function of a radiocarbon (14C) age measurement,
    modeled as a Gaussian distribution with mean `c14age` and standard deviation
    `c14sig`. The plot can display the curve itself, a filled area, or both.

    Parameters
    ----------
    c14age : float
        The measured conventional radiocarbon age (in years BP).
    c14sig : float
        The standard deviation (1σ) of the radiocarbon age measurement.
    ax : matplotlib.axes.Axes or None, optional
        Axis on which the plot is drawn. If None, the current axis (`plt.gca()`) is used.
    color : str, optional
        Color used for drawing or filling the density.
    support_size : float, optional
        Half-width (in units of standard deviations) of the interval over which
        the density is evaluated.
    sample_size : int, optional
        Number of sample points used for plotting the density curve.
    plot_density : bool, optional
        If True, the density curve is drawn.
    fill_density : bool, optional
        If True, the area between the y-axis and the density curve is filled.

    Returns
    -------
    matplotlib.axes.Axes
        The axis on which the plot is added.

    Note
    ----
    The distribution is actually Gaussian when radiocarbon measurements are expressed 
    in terms of F$^{14}$C values. Although conventional radiocarbon ages are no longer 
    Gaussian, Gaussian density is still used solely for graphical representation purposes.
    """
    #if type(ax) == 'NoneType' :
    if ax == None :
        ax = plt.gca()


    # densité de la mesure d'âge c14
    mesure_density_fct = lambda m : np.exp(-(m - c14age)**2/(2*c14sig**2))/(c14sig*np.sqrt(2*np.pi))
    mesures = np.linspace(c14age - support_size*c14sig, c14age + support_size*c14sig, sample_size)
    mesures_density = mesure_density_fct(mesures)

    # plot de la distribution de la mesure de laboratoire
    label="distribution of $^{14}$C age" +f"\nof {int(c14age)} $\pm$ {round(c14sig, 2)} years BP"
    if plot_density :
        ax.plot(
            mesures_density/mesures_density.sum(), 
            mesures, 
            color=color,
            label=label
        )
    if fill_density :
        ax.fill_between(
            mesures_density/mesures_density.sum(), 
            c14age, 
            mesures, 
            label=label,
            color=color, 
            alpha=.3
        )


    ax.set_xlabel('Probability')
    ax.set_ylabel('$^{14}$C ages in years BP')

    return ax

add_cal_date_density_plot_and_HPD_region(calibration_results, ax=None, color='cyan', eps=10 ** -7, set_title=True, add_legend=True, plot_HPD_bounds=False, plot_HPD_threshold=False)

Plot the posterior density of a calibrated date together with its HPD (Highest Posterior Density) region. This function visualizes the posterior distribution computed from calibration results and highlights all HPD intervals by shading and optional bound/threshold markers.

Parameters:

Name Type Description Default
calibration_results Dict[str, Any]

Dictionary containing all outputs of the calibration process, including:

  • 'middle_points' : 1D array of time grid points.
  • 'middle_points_density' : posterior density evaluated at each grid point.
  • 'alpha' : tail probability used for HPD region computation (e.g. 0.05 for 95% HPD).
  • 'HPD_threshold' : density threshold defining the HPD region.
  • 'connexe_HPD_intervals_unscaled_round' : list of HPD intervals (tuples).
required
ax Axes or None

Axis on which to draw. If None, the current axis (plt.gca()) is used.

None
color str

Color used for curves and shaded HPD region.

'cyan'
eps float

Minimal normalized density threshold; values below this are considered zero for plotting purposes.

10 ** -7
set_title bool

Whether the figure title should be added.

True
add_legend bool

Whether to display the legend.

True
plot_HPD_bounds bool

Whether to plot vertical dashed lines at HPD interval bounds.

False
plot_HPD_threshold bool

Whether to plot the threshold line used to compute the HPD region.

False

Returns:

Type Description
Axes

The axis where the plot was added.

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
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
def add_cal_date_density_plot_and_HPD_region(
    calibration_results: Dict[str, Any],
    ax: Optional[plt.Axes] = None,
    color: str = "cyan",
    eps: float = 10**(-7),
    set_title: bool = True,
    add_legend: bool = True,
    plot_HPD_bounds: bool = False,
    plot_HPD_threshold: bool = False
) -> plt.Axes:
    """
    Plot the posterior density of a calibrated date together with its HPD (Highest 
    Posterior Density) region. This function visualizes the posterior distribution 
    computed from calibration results and highlights all HPD intervals by shading 
    and optional bound/threshold markers.

    Parameters
    ----------
    calibration_results : Dict[str, Any]
        Dictionary containing all outputs of the calibration process, including:

        - `'middle_points'` : 1D array of time grid points.
        - `'middle_points_density'` : posterior density evaluated at each grid point.
        - `'alpha'` : tail probability used for HPD region computation (e.g. 0.05 for 95% HPD).
        - `'HPD_threshold'` : density threshold defining the HPD region.
        - `'connexe_HPD_intervals_unscaled_round'` : list of HPD intervals (tuples).
    ax : matplotlib.axes.Axes or None, optional
        Axis on which to draw. If None, the current axis (`plt.gca()`) is used.
    color : str, optional
        Color used for curves and shaded HPD region.
    eps : float, optional
        Minimal normalized density threshold; values below this are considered zero 
        for plotting purposes.
    set_title : bool, optional
        Whether the figure title should be added.
    add_legend : bool, optional
        Whether to display the legend.
    plot_HPD_bounds : bool, optional
        Whether to plot vertical dashed lines at HPD interval bounds.
    plot_HPD_threshold : bool, optional
        Whether to plot the threshold line used to compute the HPD region.

    Returns
    -------
    matplotlib.axes.Axes
        The axis where the plot was added.
    """
    #if type(ax) == 'NoneType' :
    if ax == None :
        ax = plt.gca()

    middle_points = calibration_results['middle_points']
    middle_points_density = calibration_results['middle_points_density']

    ages_idx=np.where(middle_points_density/middle_points_density.sum()>eps)[0]
    Min_age = middle_points[ages_idx].min()
    Max_age = middle_points[ages_idx].max()

    # niveau des intervalles HPD
    alpha = calibration_results['alpha']

    #distribution a posteriori sur les dates (date calibrée)
    ax.plot(
        middle_points, 
        middle_points_density/middle_points_density.sum(), 
        label="posterior density of\nthe calibrated date",
        color=color
    )

    # intervales HPD

    HPD_threshold = calibration_results['HPD_threshold']
    if plot_HPD_threshold :
        ax.plot(
            middle_points, 
            [HPD_threshold]*len(middle_points), 
            '-.', 
            color='gray', 
            #label=f"Seuil utilisé pour déterminer les intervalles HPD de niveau {int((1-alpha)*100)}%")
            label=f"the threshold used to compute the {int((1-alpha)*100)}% HPD region")



    connexe_HPD_intervals = calibration_results['connexe_HPD_intervals_unscaled_round']
    nb_HPDI = len(connexe_HPD_intervals)

    for i in range(nb_HPDI-1) :
        # borne inf de l'intervalle i
        if plot_HPD_bounds :
            ax.plot(
                [connexe_HPD_intervals[i][0],connexe_HPD_intervals[i][0]],
                [0,HPD_threshold], 
                '--', 
                color='red'
            ) 

            # borne sup de l'intervalle i
            ax.plot(
                [connexe_HPD_intervals[i][1],connexe_HPD_intervals[i][1]],
                [0,HPD_threshold], 
                '--', 
                color='red'
            ) 

        idx_i = np.where(
            (middle_points >= connexe_HPD_intervals[i][0])*(middle_points <= connexe_HPD_intervals[i][1])
        )[0]
        ax.fill_between(
            middle_points[idx_i],
            0,
            middle_points_density[idx_i]/middle_points_density.sum(),
            color=color, 
            alpha=.3
        )

    # dernier intervalle traité à part pour mettre la légende (le label) une seule fois :

    if plot_HPD_bounds:
        # borne inf du dernier intervalle 
        ax.plot(
            [connexe_HPD_intervals[nb_HPDI-1][0],connexe_HPD_intervals[nb_HPDI-1][0]],
            [0,HPD_threshold], 
            '--', 
            color='red'
        )

        # borne sup du dernier intervalle
        ax.plot(
            [connexe_HPD_intervals[nb_HPDI-1][1],connexe_HPD_intervals[nb_HPDI-1][1]],
            [0,HPD_threshold], 
            '--', 
            color='red', 
            #label=f"Borne(s) des/d'intervalle(s) HPD de niveau {int((1-alpha)*100)}%"
            label="HPD region bounds"
        )

    idx_nb_HPDI = np.where(
        (middle_points >= connexe_HPD_intervals[nb_HPDI-1][0])*(middle_points <= connexe_HPD_intervals[nb_HPDI-1][1])
    )[0]
    ax.fill_between(
        middle_points[idx_nb_HPDI], 
        0, 
        middle_points_density[idx_nb_HPDI]/middle_points_density.sum(), 
        color=color, 
        alpha=.3, 
        #label=f"intervalle(s) HPD de niveau {int((1-alpha)*100)}%"
        label=f"{int((1-alpha)*100)}% HPD region"
    )


    if set_title :
        ax.set_title('HPD region and Posterior distribution\nof the calibrated age')
    ax.set_ylabel('Probability')
    ax.set_xlabel('calibrated dates (in years cal BP)')
    ax.set_xlim(Min_age, Max_age)
    ax.invert_xaxis()

    if add_legend :
        ax.legend(loc='lower center', fancybox=True, framealpha=0., bbox_to_anchor=(0.5,-.4))

    return ax

add_individual_calibration_curve_part_1(ax=None, figsize=None, color='cyan', alpha=0.4, incertitude=True, sigma_length=1, Min_x=None, Max_x=None, Min_y=None, Max_y=None, invert_xaxis=True, domaine=['delta14c', 'c14', 'f14c'][0], covariables=False, label_prefix='', label_suffix='', credible_interval=False, credible_interval_level=0.95, credible_color=None, credible_alpha=None)

Add the Bayesian Neural Network (BNN) calibration curve (part 1) to a Matplotlib axis.

This function loads precomputed BNN midpoint predictions for the part_1 curve (recent segment), optionally converts the predictions into the requested radiocarbon domain (delta14c, c14 or f14c), computes the pointwise mean and standard deviation across Monte-Carlo predictive draws and plots the mean curve. It can optionally display the ±σ band and a pointwise credible interval band (computed from predictive samples).

Parameters:

Name Type Description Default
ax Axes or None

Axis to draw on. If None, the current axis from matplotlib.pyplot.gca() is used. Default is None.

None
figsize tuple(int, int) or None

If provided, forwarded to the plotting call; default is None.

None
color str

Color used for the BNN mean curve and (by default) for the uncertainty band.

'cyan'
alpha float

Alpha transparency for the ±σ uncertainty band.

0.4
incertitude bool

If True, draw the ± sigma_length standard-deviation envelope around the mean.

True
sigma_length int

Number of standard deviations for the ± envelope (e.g. 1 for ±1σ).

1
Min_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Max_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Min_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
Max_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
invert_xaxis bool

If True, invert the x-axis (IntCal convention). Default True.

True
domaine (delta14c, c14, f14c)

Domain for the plotted predictions. Default is 'delta14c'.

'delta14c'
covariables bool

Whether to use BNN predictions trained with covariates.

False
label_prefix str

String prefix to prepend to plotted labels.

''
label_suffix str

String suffix to append to plotted labels.

''
credible_interval bool

If True, compute and plot pointwise credible intervals from predictive samples.

False
credible_interval_level float

Credible interval level (e.g. 0.95 for 95% credible interval). Default 0.95.

0.95
credible_color str or None

Color for the credible interval fill. If None the main color is used.

None
credible_alpha float or None

Alpha transparency for the credible interval fill. If None alpha is used.

None

Returns:

Type Description
Axes

The axis object containing the plotted BNN curve.

Note

Credible intervals are computed pointwise per grid location from the predictive samples (no smoothing or joint-region calculation here).

See Also

compute_credible_intervals_bounds : helper used to compute pointwise credible bands.

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
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
def add_individual_calibration_curve_part_1(
    ax: Optional[plt.Axes] = None,
    figsize: Optional[Tuple[int, int]] = None,
    color: str = 'cyan',
    alpha: float = .4,
    incertitude: bool = True,
    sigma_length: int = 1,
    Min_x: Optional[float] = None, Max_x: Optional[float] = None,
    Min_y: Optional[float] = None, Max_y: Optional[float] = None,
    invert_xaxis: bool = True,
    domaine: str = ['delta14c', 'c14', 'f14c'][0],
    covariables: bool = False,
    label_prefix: str = '',
    label_suffix: str = '',
    credible_interval: bool = False,
    credible_interval_level: float = 0.95,
    credible_color: Optional[str] = None,
    credible_alpha: Optional[float] = None
) -> plt.Axes:
    """
    Add the Bayesian Neural Network (BNN) calibration curve (part 1) to a Matplotlib axis.

    This function loads precomputed BNN midpoint predictions for the ``part_1`` curve
    (recent segment), optionally converts the predictions into the requested radiocarbon
    domain (`delta14c`, `c14` or `f14c`), computes the pointwise mean and standard
    deviation across Monte-Carlo predictive draws and plots the mean curve.  It can
    optionally display the ±σ band and a pointwise credible interval band (computed
    from predictive samples).

    Parameters
    ----------
    ax : matplotlib.axes.Axes or None, optional
        Axis to draw on. If ``None``, the current axis from ``matplotlib.pyplot.gca()``
        is used. Default is ``None``.
    figsize : tuple(int, int) or None, optional
        If provided, forwarded to the plotting call; default is ``None``.
    color : str, optional
        Color used for the BNN mean curve and (by default) for the uncertainty band.
    alpha : float, optional
        Alpha transparency for the ±σ uncertainty band.
    incertitude : bool, optional
        If True, draw the ± `sigma_length` standard-deviation envelope around the mean.
    sigma_length : int, optional
        Number of standard deviations for the ± envelope (e.g. 1 for ±1σ).
    Min_x, Max_x : float or None, optional
        Optional x-axis limits; when both provided the axis limits are set.
    Min_y, Max_y : float or None, optional
        Optional y-axis limits; when both provided the axis limits are set.
    invert_xaxis : bool, optional
        If True, invert the x-axis (IntCal convention). Default True.
    domaine : {'delta14c', 'c14', 'f14c'}, optional
        Domain for the plotted predictions. Default is `'delta14c'`.
    covariables : bool, optional
        Whether to use BNN predictions trained with covariates.
    label_prefix : str, optional
        String prefix to prepend to plotted labels.
    label_suffix : str, optional
        String suffix to append to plotted labels.
    credible_interval : bool, optional
        If True, compute and plot pointwise credible intervals from predictive samples.
    credible_interval_level : float, optional
        Credible interval level (e.g. 0.95 for 95% credible interval). Default 0.95.
    credible_color : str or None, optional
        Color for the credible interval fill. If ``None`` the main ``color`` is used.
    credible_alpha : float or None, optional
        Alpha transparency for the credible interval fill. If ``None`` ``alpha`` is used.

    Returns
    -------
    matplotlib.axes.Axes
        The axis object containing the plotted BNN curve.

    Note
    ----
    Credible intervals are computed pointwise per grid location from the predictive
    samples (no smoothing or joint-region calculation here).

    See Also
    --------
    `compute_credible_intervals_bounds` : helper used to compute pointwise credible bands.

    """

    # chargement des prédictions pré-sauvergardées

    if covariables :
        filename = "bnn_part_1_with_covariables_middle_points_predictions.csv"
    else :
        filename = "bnn_part_1_without_covariables_middle_points_predictions.csv"
    middle_points_predictions_part_2_filepath = bnn_predictions_dir /  filename

    middle_points_predictions_part_2, nb_intervals, nb_curves = bnn_load_predictions_(
        filepath = middle_points_predictions_part_2_filepath
    )

    # Paramétrages des bornes pour la partie ancienne de la courbe de calibration

    # Bornes des âges dans le dataset d'entraînement de la partie 2
    Max_part_2 = 12310
    Min_part_2 = -4

    # choix bornes sup et inf adaptées à la partie part_2 (courbe partie ancienne) et leur reduction dans [0,1], 
    max_horizon_x = 12310 # horizon temporel des ages calibrés limité à celui de IntCal20
    min_horizon_x_part_2 = -4 # fin de la période avec dates incertaines
    max_horizon_x_part_2_scaled = minimax_scaling(max_horizon_x, Max=Max_part_2, Min=Min_part_2)
    min_horizon_x_part_2_scaled = minimax_scaling(min_horizon_x_part_2, Max=Max_part_2, Min=Min_part_2)

    # Subdivision de l'intervalle de temps couvert par la courbe part_2 en sous intervalles 
    # pour intégration et simulation si nécessaire
    intervals_bounds_part_2 = np.linspace(min_horizon_x_part_2_scaled, max_horizon_x_part_2_scaled, nb_intervals + 1)
    middle_points_part_2 = (intervals_bounds_part_2[1:] + intervals_bounds_part_2[:-1])/2

    # dates calibrées en années BP
    calage = minimax_scaling_reciproque(
        x = middle_points_part_2,
        Max = Max_part_2,
        Min = Min_part_2
    )

    # Création de l'axe si pas fourni
    if ax == None :
        ax = plt.gca()

    # choix du domaine
    if domaine == 'c14' :
        middle_points_predictions_part_2 = d14c_to_c14(
            d14c = middle_points_predictions_part_2, 
            teta = calage.repeat(nb_curves).reshape((nb_intervals, nb_curves))
        )
        y_name = 'c14age'
    elif domaine =='f14c' :
        middle_points_predictions_part_2 = d14c_to_f14c(
            d14c = middle_points_predictions_part_2, 
            teta = calage.repeat(nb_curves).reshape((nb_intervals, nb_curves))
        )
        y_name = 'f14c'
    else : 
        #domaine = 'delta14c'
        y_name = 'd14c'

    # calcul courbe moyenne et écart-type
    y = middle_points_predictions_part_2.mean(axis=1)
    y_sigma = middle_points_predictions_part_2.std(axis=1)

    # ajout courbe moyenne sur ax
    df = pd.DataFrame({
        'calage': calage,
        y_name: y
    })

    df.plot(
        x = 'calage',
        y = y_name,
        label = label_prefix + 'BNN curve' + label_suffix,
        figsize = figsize,
        ax = ax,
        color = color
    )

    # Incertitude autour de la courbe
    if incertitude :
        ax.fill_between(
            calage, 
            y - sigma_length * y_sigma,
            y + sigma_length * y_sigma,
            label=label_prefix + "BNN curve" + label_suffix + f"$\pm$ {sigma_length} $\sigma$", 
            color= color, 
            alpha=alpha
        )

    # Intervalle de crédibilité
    if credible_interval :
        if credible_alpha == None :
            credible_alpha = alpha
        if credible_color == None :
            credible_color = color
        # calcul intervalle de crédibilité de chaque prédiction
        credible_intervals, _ = compute_credible_intervals_bounds(
            1 - credible_interval_level, middle_points_predictions_part_2
        )
        ax.fill_between(
            calage, 
            credible_intervals[0], 
            credible_intervals[1], 
            label=f"{round(100*credible_interval_level)}% CI for BNN curve", 
            color=credible_color, 
            alpha=credible_alpha
        )



    # setup des axes
    if Min_y != None and Max_y != None :
        ax.set_ylim(Min_y, Max_y)
    if Min_x != None and Max_x != None :
        ax.set_xlim(Min_x, Max_x)
    if invert_xaxis :
        ax.invert_xaxis()

    return ax

add_individual_calibration_curve_part_2(ax=None, figsize=None, color='cyan', alpha=0.4, incertitude=True, sigma_length=1, Min_x=None, Max_x=None, Min_y=None, Max_y=None, invert_xaxis=True, domaine=['delta14c', 'c14', 'f14c'][0], covariables=False, label_prefix='', label_suffix='', credible_interval=False, credible_interval_level=0.95, credible_color=None, credible_alpha=None)

Add the Bayesian Neural Network (BNN) calibration curve (part 2) to a Matplotlib axis.

This function loads precomputed BNN midpoint predictions for the part_2 curve (old segment), optionally converts the predictions into the requested radiocarbon domain (delta14c, c14 or f14c), computes the pointwise mean and standard deviation across Monte-Carlo predictive draws and plots the mean curve. It can optionally display the ±σ band and a pointwise credible interval band (computed from predictive samples).

Parameters:

Name Type Description Default
ax Axes or None

Axis to draw on. If None, the current axis from matplotlib.pyplot.gca() is used. Default is None.

None
figsize tuple(int, int) or None

If provided, forwarded to the plotting call; default is None.

None
color str

Color used for the BNN mean curve and (by default) for the uncertainty band.

'cyan'
alpha float

Alpha transparency for the ±σ uncertainty band.

0.4
incertitude bool

If True, draw the ± sigma_length standard-deviation envelope around the mean.

True
sigma_length int

Number of standard deviations for the ± envelope (e.g. 1 for ±1σ).

1
Min_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Max_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Min_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
Max_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
invert_xaxis bool

If True, invert the x-axis (IntCal convention). Default True.

True
domaine (delta14c, c14, f14c)

Domain for the plotted predictions. Default is 'delta14c'.

'delta14c'
covariables bool

Whether to use BNN predictions trained with covariates.

False
label_prefix str

String prefix to prepend to plotted labels.

''
label_suffix str

String suffix to append to plotted labels.

''
credible_interval bool

If True, compute and plot pointwise credible intervals from predictive samples.

False
credible_interval_level float

Credible interval level (e.g. 0.95 for 95% credible interval). Default 0.95.

0.95
credible_color str or None

Color for the credible interval fill. If None the main color is used.

None
credible_alpha float or None

Alpha transparency for the credible interval fill. If None alpha is used.

None

Returns:

Type Description
Axes

The axis object containing the plotted BNN curve.

Note

Credible intervals are computed pointwise per grid location from the predictive samples (no smoothing or joint-region calculation here).

See Also

compute_credible_intervals_bounds : helper used to compute pointwise credible bands.

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
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
def add_individual_calibration_curve_part_2(
    ax: Optional[plt.Axes] = None,
    figsize: Optional[Tuple[int, int]] = None,
    color: str = 'cyan',
    alpha: float = .4,
    incertitude: bool = True,
    sigma_length: int = 1,
    Min_x: Optional[float] = None, Max_x: Optional[float] = None,
    Min_y: Optional[float] = None, Max_y: Optional[float] = None,
    invert_xaxis: bool = True,
    domaine: str = ['delta14c', 'c14', 'f14c'][0],
    covariables: bool = False,
    label_prefix: str = '',
    label_suffix: str = '',
    credible_interval: bool = False,
    credible_interval_level: float = 0.95,
    credible_color: Optional[str] = None,
    credible_alpha: Optional[float] = None
) -> plt.Axes:
    """
    Add the Bayesian Neural Network (BNN) calibration curve (part 2) to a Matplotlib axis.

    This function loads precomputed BNN midpoint predictions for the ``part_2`` curve
    (old segment), optionally converts the predictions into the requested radiocarbon
    domain (`delta14c`, `c14` or `f14c`), computes the pointwise mean and standard
    deviation across Monte-Carlo predictive draws and plots the mean curve.  It can
    optionally display the ±σ band and a pointwise credible interval band (computed
    from predictive samples).

    Parameters
    ----------
    ax : matplotlib.axes.Axes or None, optional
        Axis to draw on. If ``None``, the current axis from ``matplotlib.pyplot.gca()``
        is used. Default is ``None``.
    figsize : tuple(int, int) or None, optional
        If provided, forwarded to the plotting call; default is ``None``.
    color : str, optional
        Color used for the BNN mean curve and (by default) for the uncertainty band.
    alpha : float, optional
        Alpha transparency for the ±σ uncertainty band.
    incertitude : bool, optional
        If True, draw the ± `sigma_length` standard-deviation envelope around the mean.
    sigma_length : int, optional
        Number of standard deviations for the ± envelope (e.g. 1 for ±1σ).
    Min_x, Max_x : float or None, optional
        Optional x-axis limits; when both provided the axis limits are set.
    Min_y, Max_y : float or None, optional
        Optional y-axis limits; when both provided the axis limits are set.
    invert_xaxis : bool, optional
        If True, invert the x-axis (IntCal convention). Default True.
    domaine : {'delta14c', 'c14', 'f14c'}, optional
        Domain for the plotted predictions. Default is `'delta14c'`.
    covariables : bool, optional
        Whether to use BNN predictions trained with covariates.
    label_prefix : str, optional
        String prefix to prepend to plotted labels.
    label_suffix : str, optional
        String suffix to append to plotted labels.
    credible_interval : bool, optional
        If True, compute and plot pointwise credible intervals from predictive samples.
    credible_interval_level : float, optional
        Credible interval level (e.g. 0.95 for 95% credible interval). Default 0.95.
    credible_color : str or None, optional
        Color for the credible interval fill. If ``None`` the main ``color`` is used.
    credible_alpha : float or None, optional
        Alpha transparency for the credible interval fill. If ``None`` ``alpha`` is used.

    Returns
    -------
    matplotlib.axes.Axes
        The axis object containing the plotted BNN curve.

    Note
    ----
    Credible intervals are computed pointwise per grid location from the predictive
    samples (no smoothing or joint-region calculation here).

    See Also
    --------
    `compute_credible_intervals_bounds` : helper used to compute pointwise credible bands.

    """

    # chargement des prédictions pré-sauvergardées

    if covariables :
        filename = "bnn_part_2_with_covariables_middle_points_predictions.csv"
    else :
        filename = "bnn_part_2_without_covariables_middle_points_predictions.csv"
    middle_points_predictions_part_2_filepath = bnn_predictions_dir /  filename

    middle_points_predictions_part_2, nb_intervals, nb_curves = bnn_load_predictions_(
        filepath = middle_points_predictions_part_2_filepath
    )

    # Paramétrages des bornes pour la partie ancienne de la courbe de calibration

    # Bornes des âges dans le dataset d'entraînement de la partie 2
    Max_part_2 = 63648
    Min_part_2 = 12283

    # choix bornes sup et inf adaptées à la partie part_2 (courbe partie ancienne) et leur reduction dans [0,1], 
    max_horizon_x = 55000 # horizon temporel des ages calibrés limité à celui de IntCal20
    min_horizon_x_part_2 = 12310 # fin de la période avec dates incertaines
    max_horizon_x_part_2_scaled = minimax_scaling(max_horizon_x, Max=Max_part_2, Min=Min_part_2)
    min_horizon_x_part_2_scaled = minimax_scaling(min_horizon_x_part_2, Max=Max_part_2, Min=Min_part_2)

    # Subdivision de l'intervalle de temps couvert par la courbe part_2 en sous intervalles 
    # pour intégration et simulation si nécessaire
    intervals_bounds_part_2 = np.linspace(min_horizon_x_part_2_scaled, max_horizon_x_part_2_scaled, nb_intervals + 1)
    middle_points_part_2 = (intervals_bounds_part_2[1:] + intervals_bounds_part_2[:-1])/2

    # dates calibrées en années BP
    calage = minimax_scaling_reciproque(
        x = middle_points_part_2,
        Max = Max_part_2,
        Min = Min_part_2
    )

    # Création de l'axe si pas fourni
    if ax == None :
        ax = plt.gca()

    # choix du domaine
    if domaine == 'c14' :
        middle_points_predictions_part_2 = d14c_to_c14(
            d14c = middle_points_predictions_part_2, 
            teta = calage.repeat(nb_curves).reshape((nb_intervals, nb_curves))
        )
        y_name = 'c14age'
    elif domaine =='f14c' :
        middle_points_predictions_part_2 = d14c_to_f14c(
            d14c = middle_points_predictions_part_2, 
            teta = calage.repeat(nb_curves).reshape((nb_intervals, nb_curves))
        )
        y_name = 'f14c'
    else : 
        #domaine = 'delta14c'
        y_name = 'd14c'

    # calcul courbe moyenne et écart-type
    y = middle_points_predictions_part_2.mean(axis=1)
    y_sigma = middle_points_predictions_part_2.std(axis=1)

    # ajout courbe moyenne sur ax
    df = pd.DataFrame({
        'calage': calage,
        y_name: y
    })

    df.plot(
        x = 'calage',
        y = y_name,
        label = label_prefix + 'BNN curve' + label_suffix,
        figsize = figsize,
        ax = ax,
        color = color
    )

    # Incertitude autour de la courbe
    if incertitude :
        ax.fill_between(
            calage, 
            y - sigma_length * y_sigma,
            y + sigma_length * y_sigma,
            label=label_prefix + "BNN curve" + label_suffix + f"$\pm$ {sigma_length} $\sigma$", 
            color= color, 
            alpha=alpha
        )

    # Intervalle de crédibilité
    if credible_interval :
        if credible_alpha == None :
            credible_alpha = alpha
        if credible_color == None :
            credible_color = color
        # calcul intervalle de crédibilité de chaque prédiction
        credible_intervals, _ = compute_credible_intervals_bounds(
            1 - credible_interval_level, middle_points_predictions_part_2
        )
        ax.fill_between(
            calage, 
            credible_intervals[0], 
            credible_intervals[1], 
            label=f"{round(100*credible_interval_level)}% CI for BNN curve", 
            color=credible_color, 
            alpha=credible_alpha
        )



    # setup des axes
    if Min_y != None and Max_y != None :
        ax.set_ylim(Min_y, Max_y)
    if Min_x != None and Max_x != None :
        ax.set_xlim(Min_x, Max_x)
    if invert_xaxis :
        ax.invert_xaxis()

    return ax

add_individual_calibration_curve_parts_1_and_2(ax=None, figsize=None, color='cyan', alpha=0.4, incertitude=True, sigma_length=1, Min_x=None, Max_x=None, Min_y=None, Max_y=None, invert_xaxis=True, domaine=['delta14c', 'c14', 'f14c'][0], covariables=False, credible_interval=False, credible_interval_level=0.95, credible_color=None, credible_alpha=None)

Add both parts (1 and 2) of the BNN calibration curve to the provided matplotlib axis.

This function successively calls:

  • add_individual_calibration_curve_part_1 for the recent period,
  • add_individual_calibration_curve_part_2 for the older period.

It manages:

  • axis inversion only once,
  • legend suffix depending on whether covariates are used,
  • forwarding of all visual and uncertainty options,
  • consistent handling of credible intervals.

Parameters:

Name Type Description Default
ax Axes or None

Axis on which to draw the curves. If None, the axis is taken from add_individual_calibration_curve_part_1.

None
figsize tuple(int, int) or None

Figure size used by the underlying plot calls.

None
color str

Color used for both BNN curve parts.

'cyan'
alpha float

Transparency for uncertainty or credible interval fills.

0.4
incertitude bool

Whether to draw the ±σ uncertainty band around the mean curve.

True
sigma_length int

Number of standard deviations for the uncertainty band.

1
Min_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Max_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Min_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
Max_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
invert_xaxis bool

If True, the x-axis is inverted (IntCal convention).

True
domaine (delta14c, c14, f14c)

Domain of radiocarbon quantities displayed.

'delta14c'
covariables bool

Whether to use BNN predictions trained with covariates. This affects the legend suffix.

False
credible_interval bool

If True, compute and plot pointwise credible intervals from predictive samples.

False
credible_interval_level float

Credible interval level (e.g. 0.95 for 95% credible interval). Default 0.95.

0.95
credible_color str or None

Color for the credible interval fill. If None the main color is used.

None
credible_alpha float or None

Alpha transparency for the credible interval fill. If None alpha is used.

None

Returns:

Type Description
Axes

The axis containing both parts of the BNN calibration curve.

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
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
def add_individual_calibration_curve_parts_1_and_2(
    ax: Optional[plt.Axes] = None,
    figsize: Optional[Tuple[int, int]] = None,
    color: str = 'cyan',
    alpha: float = .4,
    incertitude: bool = True,
    sigma_length: int = 1,
    Min_x: Optional[float] = None, Max_x: Optional[float] = None,
    Min_y: Optional[float] = None, Max_y: Optional[float] = None,
    invert_xaxis: bool = True,
    domaine: str = ['delta14c', 'c14', 'f14c'][0],
    covariables: bool = False,
    credible_interval: bool = False,
    credible_interval_level: float = 0.95,
    credible_color: Optional[str] = None,
    credible_alpha: Optional[float] = None
) -> plt.Axes:
    """
    Add both parts (1 and 2) of the BNN calibration curve to the
    provided matplotlib axis.

    This function successively calls:

    - ``add_individual_calibration_curve_part_1`` for the recent period,
    - ``add_individual_calibration_curve_part_2`` for the older period.

    It manages:

    - axis inversion only once,
    - legend suffix depending on whether covariates are used,
    - forwarding of all visual and uncertainty options,
    - consistent handling of credible intervals.

    Parameters
    ----------
    ax : matplotlib.axes.Axes or None, optional
        Axis on which to draw the curves. If ``None``, the axis is taken from
        ``add_individual_calibration_curve_part_1``.
    figsize : tuple(int, int) or None, optional
        Figure size used by the underlying plot calls.
    color : str, optional
        Color used for both BNN curve parts.
    alpha : float, optional
        Transparency for uncertainty or credible interval fills.
    incertitude : bool, optional
        Whether to draw the ±σ uncertainty band around the mean curve.
    sigma_length : int, optional
        Number of standard deviations for the uncertainty band.
    Min_x, Max_x : float or None, optional
        Optional x-axis limits; when both provided the axis limits are set.
    Min_y, Max_y : float or None, optional
        Optional y-axis limits; when both provided the axis limits are set.
    invert_xaxis : bool, optional
        If True, the x-axis is inverted (IntCal convention).
    domaine : {'delta14c', 'c14', 'f14c'}, optional
        Domain of radiocarbon quantities displayed.
    covariables : bool, optional
        Whether to use BNN predictions trained with covariates.
        This affects the legend suffix.
    credible_interval : bool, optional
        If True, compute and plot pointwise credible intervals from predictive samples.
    credible_interval_level : float, optional
        Credible interval level (e.g. 0.95 for 95% credible interval). Default 0.95.
    credible_color : str or None, optional
        Color for the credible interval fill. If ``None`` the main ``color`` is used.
    credible_alpha : float or None, optional
        Alpha transparency for the credible interval fill. If ``None`` ``alpha`` is used.

    Returns
    -------
    matplotlib.axes.Axes
        The axis containing both parts of the BNN calibration curve.
    """

    if not covariables :
        # à donner uniquement à un graphique (ici part_1) pour la légende en cas de covariables
        label_suffix = ' with covariates '
    else :
        label_suffix = ''


    # ajout partie de la courbe sans dates incertaines
    ax = add_individual_calibration_curve_part_1(
            ax = ax,
            figsize = figsize,
            color = color,
            alpha= alpha,
            incertitude = incertitude,
            sigma_length = sigma_length,
            Min_x = Min_x, Max_x = Max_x,
            Min_y = Min_y, Max_y = Max_y,
            invert_xaxis = invert_xaxis,
            domaine = domaine,
            covariables = covariables,
            label_prefix = '', # la légende apparaît
            label_suffix = label_suffix, # gestion de la présence ou non des covariables dans la légende
            credible_interval = credible_interval,
            credible_interval_level = credible_interval_level,
            credible_color = credible_color,
            credible_alpha = credible_alpha
    )

    if invert_xaxis :
        # on n'inverse plus l'axe une deuxième fois
        invert_xaxis = False

    ax = add_individual_calibration_curve_part_2(
            ax = ax,
            figsize = figsize,
            color = color,
            alpha= alpha,
            incertitude = incertitude,
            sigma_length = sigma_length,
            Min_x = Min_x, Max_x = Max_x,
            Min_y = Min_y, Max_y = Max_y,
            invert_xaxis = invert_xaxis,
            domaine = domaine,
            covariables = covariables,
            label_prefix = '_', # pour supprimer la double apparition dans la légende
            label_suffix = '',
            credible_interval = credible_interval,
            credible_interval_level = credible_interval_level,
            credible_color = credible_color,
            credible_alpha = credible_alpha
    )

    return ax

compute_credible_intervals_bounds(alpha, bnn_predictions, method='median_unbiased')

Compute pointwise (per-prediction) credible-interval bounds for a set of predictive samples produced by a Bayesian Neural Network.

For each prediction index i (row of bnn_predictions), the function:

  1. Computes the optimal quantile-shift parameter beta_opt using find_quantile_beta_opt to minimize the length of the asymmetric credible interval of level 1 - alpha.
  2. Extracts the lower and upper credible bounds using the empirical quantiles:
    • lower = Q_{beta_opt}
    • upper = Q_{1 - alpha + beta_opt}

Parameters:

Name Type Description Default
alpha float

Target tail probability (the interval has probability mass 1 - alpha).
Must satisfy 0 < alpha < 1.

required
bnn_predictions ndarray

Array of predictive samples, typically of shape (n_grid_points, n_samples) where each row corresponds to the distribution of predictions at a given calendar date.

required
method str

Method used by numpy.quantile. Default is 'median_unbiased'.

'median_unbiased'

Returns:

Type Description
(Tuple[ndarray, ndarray], ndarray)

A tuple (lower_bounds, upper_bounds) where both arrays have shape (n_grid_points,), and an array beta_opt_list of shape (n_grid_points,) containing the optimal beta for each point.

Note

This function is typically used to generate credible bands around reconstructed calibration curves.

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
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
def compute_credible_intervals_bounds(
    alpha: float,
    bnn_predictions: np.ndarray,
    method: str = 'median_unbiased'
):
    """
    Compute pointwise (per-prediction) credible-interval bounds for a set of
    predictive samples produced by a Bayesian Neural Network.  

    For each prediction index ``i`` (row of ``bnn_predictions``), the function: 

    1. Computes the optimal quantile-shift parameter ``beta_opt`` using
        `find_quantile_beta_opt` to minimize the length of the asymmetric
        credible interval of level ``1 - alpha``.  
    2. Extracts the lower and upper credible bounds using the empirical
        quantiles:  
        - lower = Q_{beta_opt}  
        - upper = Q_{1 - alpha + beta_opt}  

    Parameters
    ----------
    alpha : float
        Target tail probability (the interval has probability mass ``1 - alpha``).  
        Must satisfy ``0 < alpha < 1``.
    bnn_predictions : np.ndarray
        Array of predictive samples, typically of shape
        ``(n_grid_points, n_samples)`` where each row corresponds to the
        distribution of predictions at a given calendar date.
    method : str, optional
        Method used by ``numpy.quantile``. Default is 'median_unbiased'.

    Returns
    -------
    Tuple[np.ndarray, np.ndarray], np.ndarray
        A tuple ``(lower_bounds, upper_bounds)`` where both arrays have shape
        ``(n_grid_points,)``, and an array ``beta_opt_list`` of shape
        ``(n_grid_points,)`` containing the optimal beta for each point.

    Note
    -----
    This function is typically used to generate credible bands around 
    reconstructed calibration curves.
    """

    predictions_size = bnn_predictions.shape[0]
    CI_upper_bounds = []
    CI_lower_bounds = []
    beta_opt_list = []
    for i in range(predictions_size) :
        predictions = bnn_predictions[i,]
        beta_opt = find_quantile_beta_opt(alpha, predictions, method=method)
        upper = np.quantile(predictions, 1 - alpha + beta_opt, method=method)
        lower = np.quantile(predictions, beta_opt, method=method)
        CI_upper_bounds.append(upper)
        CI_lower_bounds.append(lower)
        beta_opt_list.append(beta_opt)
    return (np.array(CI_lower_bounds), np.array(CI_upper_bounds)), np.array(beta_opt_list)

find_quantile_beta_opt(alpha, predictions, method='median_unbiased')

Compute the optimal quantile-shift parameter beta that minimizes the length of an asymmetric prediction credible interval of level 1 - alpha.

The interval is defined as: $$ [ Q_{\beta} , Q_{1 - \alpha + \beta} ] $$ where \(Q_p\) denotes the empirical quantile of the predictive distribution. The optimal beta is obtained by numerical minimization of the interval length with respect to beta over the admissible domain [0, alpha].

Parameters:

Name Type Description Default
alpha float

Target tail probability. Must satisfy 0 < alpha < 1.

required
predictions ndarray

One-dimensional array of predictive samples from which empirical quantiles are computed.

required
method str

Quantile calculation method passed to numpy.quantile. Defaults to 'median_unbiased'.

'median_unbiased'

Returns:

Type Description
float

The optimal beta in the interval [0, alpha].

Raises:

Type Description
ValueError

If alpha is not in (0, 1), if predictions is not a one-dimensional numpy array, or if it contains NaNs.

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
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
def find_quantile_beta_opt(
    alpha: float,
    predictions: np.ndarray,
    method: str = 'median_unbiased'
) -> float:
    """
    Compute the optimal quantile-shift parameter ``beta`` that minimizes
    the length of an asymmetric prediction credible interval of 
    level ``1 - alpha``.

    The interval is defined as:
    $$
        [ Q_{\\beta} , Q_{1 - \\alpha + \\beta} ]
    $$
    where $Q_p$ denotes the empirical quantile of the predictive distribution.
    The optimal ``beta`` is obtained by numerical minimization of the
    interval length with respect to ``beta`` over the admissible domain
    [0, alpha].

    Parameters
    ----------
    alpha : float
        Target tail probability. Must satisfy ``0 < alpha < 1``.
    predictions : np.ndarray
        One-dimensional array of predictive samples from which
        empirical quantiles are computed.
    method : str, optional
        Quantile calculation method passed to ``numpy.quantile``.
        Defaults to 'median_unbiased'.

    Returns
    -------
    float
        The optimal ``beta`` in the interval [0, alpha].

    Raises
    ------
    ValueError
        If ``alpha`` is not in (0, 1), if ``predictions`` is not a
        one-dimensional numpy array, or if it contains NaNs.
    """

    # Vérifications d’entrées
    if not isinstance(alpha, (float, int)) or not (0 < float(alpha) < 1):
        raise ValueError("'alpha' must be a float strictly between 0 and 1.")

    if not isinstance(predictions, np.ndarray):
        raise ValueError("'predictions' must be a numpy.ndarray.")

    if predictions.ndim != 1:
        raise ValueError("'predictions' must be one-dimensional.")

    if np.isnan(predictions).any():
        raise ValueError("'predictions' contains NaN values, cannot compute quantiles.")

    interval_length = lambda beta : np.quantile(predictions, 1 - alpha + beta, method=method) - np.quantile(predictions, beta, method=method)
    beta_opt = minimize(fun = interval_length , x0 = np.array([alpha/2]), method = 'Nelder-Mead', bounds = [(0.,alpha)])
    return beta_opt.x[0]

plot_IntCal20_curve(xlabel='Calibrated dates (years BP)', ylabel='Radiocarbon ages (years BP)', add_grid=True, fontsize_legend='small', reset_margins=False, ax=None, figsize=None, color='green', alpha=0.4, incertitude=True, sigma_length=1, Min_x=None, Max_x=None, Min_y=None, Max_y=None, invert_xaxis=True, domaine='delta14c')

Plot the IntCal20 calibration curve in the chosen radiocarbon domain.

Parameters:

Name Type Description Default
xlabel str

X-axis label.

'Calibrated dates (years BP)'
ylabel str

Y-axis label. Adjusted automatically if domaine is "delta14c" or "f14c".

'Radiocarbon ages (years BP)'
add_grid bool

If True, draw a grid behind the plot.

True
fontsize_legend int or str

Font size passed to matplotlib’s legend.

'small'
reset_margins bool

If True, reset axis margins to zero.

False
ax Axes or None

Existing axis onto which the curve is drawn. If None, a new one is created.

None
figsize tuple(int, int)

Figure size passed to matplotlib.

None
color str

Color of the IntCal20 curve.

'green'
alpha float

Transparency for the uncertainty band.

0.4
incertitude bool

If True, display the ±σ IntCal20 uncertainty envelope.

True
sigma_length int

Number of sigma widths for the uncertainty envelope.

1
Min_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Max_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Min_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
Max_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
invert_xaxis bool

If True, invert X axis (IntCal standard orientation).

True
domaine (delta14c, c14, f14c)

Domain in which to express radiocarbon values.

'delta14c'

Returns:

Type Description
None
Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
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
def plot_IntCal20_curve(
    xlabel: str = "Calibrated dates (years BP)",
    ylabel: str = "Radiocarbon ages (years BP)",
    add_grid: bool = True,
    fontsize_legend: Union[int, str] = 'small',
    reset_margins: bool = False,

    ax: plt.Axes = None,
    figsize: Optional[Tuple[int, int]] = None,
    color: str = "green",
    alpha: float = 0.4,
    incertitude: bool = True,
    sigma_length: int = 1,
    Min_x: Optional[float] = None, 
    Max_x: Optional[float] = None,
    Min_y: Optional[float] = None, 
    Max_y: Optional[float] = None,
    invert_xaxis: bool = True,
    domaine: str = 'delta14c'
):
    """
    Plot the IntCal20 calibration curve in the chosen radiocarbon domain.

    Parameters
    ----------
    xlabel : str, optional
        X-axis label.
    ylabel : str, optional
        Y-axis label. Adjusted automatically if `domaine` is "delta14c" or "f14c".
    add_grid : bool, optional
        If True, draw a grid behind the plot.
    fontsize_legend : int or str, optional
        Font size passed to matplotlib’s legend.
    reset_margins : bool, optional
        If True, reset axis margins to zero.

    ax : matplotlib.axes.Axes or None
        Existing axis onto which the curve is drawn. If None, a new one is created.
    figsize : tuple(int, int), optional
        Figure size passed to matplotlib.
    color : str, optional
        Color of the IntCal20 curve.
    alpha : float, optional
        Transparency for the uncertainty band.
    incertitude : bool, optional
        If True, display the ±σ IntCal20 uncertainty envelope.
    sigma_length : int, optional
        Number of sigma widths for the uncertainty envelope.

    Min_x, Max_x : float or None, optional
        Optional x-axis limits; when both provided the axis limits are set.
    Min_y, Max_y : float or None, optional
        Optional y-axis limits; when both provided the axis limits are set.
    invert_xaxis : bool, optional
        If True, invert X axis (IntCal standard orientation).
    domaine : {'delta14c', 'c14', 'f14c'}
        Domain in which to express radiocarbon values.

    Returns
    -------
    None
    """

    ax = add_IntCal20_curve(
            ax = ax,
            figsize = figsize,
            color = color,
            alpha= alpha,
            incertitude = incertitude,
            sigma_length = sigma_length,
            Min_x = Min_x, Max_x = Max_x,
            Min_y = Min_y, Max_y = Max_y,
            invert_xaxis = True,
            domaine = domaine
    )

    if reset_margins:
        ax.margins(0)

    plt.xlabel(xlabel)
    if domaine == 'delta14c' :
        ylabel = "$\Delta^{14}$C"
    if domaine == 'f14c' :
        ylabel = "F$^{14}$C"
    plt.ylabel(ylabel)
    plt.grid(add_grid)
    #plt.gca().invert_xaxis()
    plt.legend(fontsize=fontsize_legend)
    plt.show()

plot_bnn_calibration_curve(xlabel='Calendar dates (in years BP)', ylabel='Radiocarbon ages (in years BP)', add_grid=True, fontsize_legend='small', reset_margins=False, ax=None, figsize=None, color='cyan', alpha=0.4, incertitude=True, sigma_length=1, Min_x=None, Max_x=None, Min_y=None, Max_y=None, invert_xaxis=True, domaine=['delta14c', 'c14', 'f14c'][0], covariables=False, credible_interval=False, credible_interval_level=0.95, credible_color=None, credible_alpha=None)

Plot the full BNN-based calibration curve, including optional uncertainty visualization, credible intervals, grid, labels, and legend. This function acts as a convenience wrapper around add_bnn_calibration_curve, and automatically configures axis labels, grid display, margins, and legend formatting.

Parameters:

Name Type Description Default
xlabel str

X-axis label.

'Calendar dates (in years BP)'
ylabel str

Y-axis label. Adjusted automatically if domaine is "delta14c" or "f14c".

'Radiocarbon ages (in years BP)'
add_grid bool

If True, draw a grid behind the plot.

True
fontsize_legend str

Legend font size (e.g., "small", "medium", "large").

'small'
reset_margins bool

Whether to remove extra margins around the plotted data.

False
ax Axes or None

Axis on which to draw the curves. If None, the axis is taken from add_bnn_calibration_curve.

None
figsize tuple or None

Figure size passed to underlying plotting functions.

None
color str

Color used for plotting the curve and uncertainty bands.

'cyan'
alpha float

Transparency level for uncertainty shading and credible interval bands.

0.4
incertitude bool

Whether to add the ±σ uncertainty band around the mean curve.

True
sigma_length float

Width of the uncertainty band in standard deviations.

1
Min_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Max_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Min_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
Max_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
invert_xaxis bool

Whether to invert the x-axis (used for IntCal-style plots).

True
domaine (delta14c, c14, f14c)

Domain of radiocarbon quantities displayed.

'delta14c'
covariables bool

Whether to use BNN predictions trained with covariates; influences legend content.

False
credible_interval bool

Whether to compute and display credible intervals for the BNN predictions.

False
credible_interval_level float

Credible interval level (e.g., 0.95 for 95% CI).

0.95
credible_color str or None

Color of the credible interval shading (defaults to color).

None
credible_alpha float or None

Transparency of the credible interval shading (defaults to alpha).

None

Returns:

Type Description
None

The function produces a plot.

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
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
def plot_bnn_calibration_curve(
    xlabel: str = "Calendar dates (in years BP)",
    ylabel: str = "Radiocarbon ages (in years BP)",
    add_grid: bool = True,
    fontsize_legend: str = 'small',
    reset_margins: bool = False,

    ax: Optional[plt.Axes] = None,
    figsize: Optional[Tuple[int, int]] = None,
    color: str = 'cyan',
    alpha: float = .4,
    incertitude: bool = True,
    sigma_length: float = 1,
    Min_x: Optional[float] = None, Max_x: Optional[float] = None,
    Min_y: Optional[float] = None, Max_y: Optional[float] = None,
    invert_xaxis: bool = True,
    domaine: str = ['delta14c', 'c14', 'f14c'][0],
    covariables: bool = False,
    credible_interval: bool = False,
    credible_interval_level: float = 0.95,
    credible_color: Optional[str] = None,
    credible_alpha: Optional[float] = None
) -> None:
    """
    Plot the full BNN-based calibration curve, including optional uncertainty
    visualization, credible intervals, grid, labels, and legend. This function
    acts as a convenience wrapper around `add_bnn_calibration_curve`, and 
    automatically configures axis labels, grid display, margins, and legend 
    formatting.

    Parameters
    ----------
    xlabel : str, optional
        X-axis label.
    ylabel : str, optional
        Y-axis label. Adjusted automatically if `domaine` is "delta14c" or "f14c".
    add_grid : bool, optional
        If True, draw a grid behind the plot.
    fontsize_legend : str, optional
        Legend font size (e.g., "small", "medium", "large").
    reset_margins : bool, optional
        Whether to remove extra margins around the plotted data.
    ax : matplotlib.axes.Axes or None, optional
        Axis on which to draw the curves. If ``None``, the axis is taken from
        `add_bnn_calibration_curve`.
    figsize : tuple or None
        Figure size passed to underlying plotting functions.
    color : str, optional
        Color used for plotting the curve and uncertainty bands.
    alpha : float, optional
        Transparency level for uncertainty shading and credible interval bands.
    incertitude : bool, optional
        Whether to add the ±σ uncertainty band around the mean curve.
    sigma_length : float, optional
        Width of the uncertainty band in standard deviations.
    Min_x, Max_x : float or None, optional
        Optional x-axis limits; when both provided the axis limits are set.
    Min_y, Max_y : float or None, optional
        Optional y-axis limits; when both provided the axis limits are set.
    invert_xaxis : bool, optional
        Whether to invert the x-axis (used for IntCal-style plots).
    domaine : {'delta14c', 'c14', 'f14c'}, optional
        Domain of radiocarbon quantities displayed.
    covariables : bool, optional
        Whether to use BNN predictions trained with covariates; 
        influences legend content.
    credible_interval : bool, optional
        Whether to compute and display credible intervals for the BNN predictions.
    credible_interval_level : float, optional
        Credible interval level (e.g., 0.95 for 95% CI).
    credible_color : str or None, optional
        Color of the credible interval shading (defaults to ``color``).
    credible_alpha : float or None, optional
        Transparency of the credible interval shading (defaults to ``alpha``).

    Returns
    -------
    None
        The function produces a plot.
    """
    ax = add_bnn_calibration_curve(
            ax = ax,
            figsize = figsize,
            color = color,
            alpha= alpha,
            incertitude = incertitude,
            sigma_length = sigma_length,
            Min_x = Min_x, Max_x = Max_x,
            Min_y = Min_y, Max_y = Max_y,
            invert_xaxis = True,
            domaine = domaine,
            covariables = covariables,
            credible_interval = credible_interval,
            credible_interval_level = credible_interval_level,
            credible_color = credible_color,
            credible_alpha = credible_alpha
    )

    if reset_margins:
        ax.margins(0)

    plt.xlabel(xlabel)
    if domaine == 'delta14c' :
        ylabel = "$\Delta^{14}$C"
    if domaine == 'f14c' :
        ylabel = "F$^{14}$C"
    plt.ylabel(ylabel)
    plt.grid(add_grid)
    plt.legend(fontsize=fontsize_legend)
    plt.show()

plot_calib_results(calibration_results, c14age=None, c14sig=None, plot_BNN=True, covariables=None, color_BNN='blue', parts_1_and_2=True, part_1=False, part_2=False, plot_IntCal20=False, color_IntCal20='green', figsize=None, fontsize_legend=['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'][2], fig=None, axs=None, add_grid=False, color_cal_date='cyan', eps=10 ** -7, plot_HPD_bounds=False, plot_HPD_threshold=False, color_c14age='gray', support_size=5, sample_size=1000, plot_density=False, fill_density=True)

Plot a full graphical summary of individual radiocarbon calibration results.

The figure combines:

  • the probability density of the radiocarbon measurement,
  • the calibration curve (BNN-based or IntCal20),
  • the posterior density of the calibrated date with its HPD region,
  • a blank panel for layout aesthetics.

Parameters:

Name Type Description Default
calibration_results Dict[str, Any]

A dictionary containing all required calibration outputs (c14age, c14sig, covariables, posterior density, HPD intervals, etc.).

required
c14age float

Preserved for backward compatibility; the radiocarbon age (will be overwritten by the value inside calibration_results).

None
c14sig float

Preserved for backward compatibility; the radiocarbon age uncertainty (will be overwritten by the value inside calibration_results).

None
plot_BNN bool

If True, plot the BNN calibration curve (unless covariables is None).

True
covariables bool or None

Preserved for backward compatibility; whether covariates were used for BNN calibration (will be overwritten by the value inside calibration_results).
If None, IntCal20 is used automatically.

None
color_BNN str

Color for the BNN calibration curve.

'blue'
parts_1_and_2 bool

Whether to plot the entire BNN curve (parts 1 and 2).

True
part_1 bool

If True, only plot part 1 of the BNN calibration curve.

False
part_2 bool

If True, only plot part 2 of the BNN calibration curve.

False
plot_IntCal20 bool

If True, plot the IntCal20 curve instead of a BNN model.

False
color_IntCal20 str

Color for the IntCal20 calibration curve.

'green'
figsize tuple or None

Size of the figure in inches. If None, a default size is chosen.

None
fontsize_legend str

Legend font size.

['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'][2]
fig Figure or None

A figure instance to reuse; if None, one is created.

None
axs array-like of Axes or None

A 2×2 array of axes. If None, axes are created.

None
add_grid bool

Whether to add grid lines to all plots.

False
color_cal_date str

Color used for plotting the posterior distribution of the calibrated date.

'cyan'
eps float

Density threshold below which points are considered negligible.
A negative value allows to display the posterior distribution of the calibrated date over all the entire range of the calibration curve.

10 ** -7
plot_HPD_bounds bool

If True, display vertical HPD interval bounds.

False
plot_HPD_threshold bool

If True, plot the HPD threshold line.

False
color_c14age str

Color for the radiocarbon measurement density plot.

'gray'
support_size float

Half-width of the range (in σ units) used to construct the c14age density.

5
sample_size int

Number of points in the discretized c14age density evaluation.

1000
plot_density bool

Whether to draw the c14age density curve.

False
fill_density bool

Whether to fill the area under the c14age density curve.

True

Returns:

Type Description
None

The function displays the figure directly using plt.show().

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
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
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
def plot_calib_results(
    calibration_results: Dict[str, Any],
    c14age: float = None,
    c14sig: float = None,

    plot_BNN: bool = True,
    covariables: bool = None,
    color_BNN: str = 'blue',
    parts_1_and_2: bool = True,
    part_1: bool = False,
    part_2: bool = False,

    plot_IntCal20: bool = False,
    color_IntCal20: str = 'green',

    figsize = None,
    fontsize_legend: str = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'][2],
    fig = None,
    axs = None,
    add_grid: bool = False,

    color_cal_date: str = "cyan",
    eps: float = 10**(-7),
    plot_HPD_bounds: bool = False,
    plot_HPD_threshold: bool = False,

    color_c14age: str = "gray",
    support_size: float = 5,
    sample_size: int = 1000,
    plot_density: bool = False,
    fill_density: bool = True
) -> None:
    """
    Plot a full graphical summary of individual radiocarbon calibration results.

    The figure combines:

    - the probability density of the radiocarbon measurement,
    - the calibration curve (BNN-based or IntCal20),
    - the posterior density of the calibrated date with its HPD region,
    - a blank panel for layout aesthetics.

    Parameters
    ----------
    calibration_results : Dict[str, Any]
        A dictionary containing all required calibration outputs
        (c14age, c14sig, covariables, posterior density, HPD intervals, etc.).
    c14age : float, optional
        Preserved for backward compatibility; the radiocarbon age (will be overwritten
        by the value inside `calibration_results`).
    c14sig : float, optional
        Preserved for backward compatibility; the radiocarbon age uncertainty (will be 
        overwritten by the value inside `calibration_results`).
    plot_BNN : bool, optional
        If True, plot the BNN calibration curve (unless covariables is None).
    covariables : bool or None, optional
        Preserved for backward compatibility; whether covariates were used for BNN 
        calibration (will be overwritten by the value inside `calibration_results`).  
        If None, IntCal20 is used automatically.
    color_BNN : str, optional
        Color for the BNN calibration curve.
    parts_1_and_2 : bool, optional
        Whether to plot the entire BNN curve (parts 1 and 2).
    part_1 : bool, optional
        If True, only plot part 1 of the BNN calibration curve.
    part_2 : bool, optional
        If True, only plot part 2 of the BNN calibration curve.
    plot_IntCal20 : bool, optional
        If True, plot the IntCal20 curve instead of a BNN model.
    color_IntCal20 : str, optional
        Color for the IntCal20 calibration curve.
    figsize : tuple or None, optional
        Size of the figure in inches. If None, a default size is chosen.
    fontsize_legend : str, optional
        Legend font size.
    fig : matplotlib.figure.Figure or None, optional
        A figure instance to reuse; if None, one is created.
    axs : array-like of Axes or None, optional
        A 2×2 array of axes. If None, axes are created.
    add_grid : bool, optional
        Whether to add grid lines to all plots.
    color_cal_date : str, optional
        Color used for plotting the posterior distribution of the calibrated date.
    eps : float, optional
        Density threshold below which points are considered negligible.  
        A negative value allows to display the posterior distribution of the 
        calibrated date over all the entire range of the calibration curve.
    plot_HPD_bounds : bool, optional
        If True, display vertical HPD interval bounds.
    plot_HPD_threshold : bool, optional
        If True, plot the HPD threshold line.
    color_c14age : str, optional
        Color for the radiocarbon measurement density plot.
    support_size : float, optional
        Half-width of the range (in σ units) used to construct the `c14age` density.
    sample_size : int, optional
        Number of points in the discretized `c14age` density evaluation.
    plot_density : bool, optional
        Whether to draw the `c14age` density curve.
    fill_density : bool, optional
        Whether to fill the area under the `c14age` density curve.

    Returns
    -------
    None
        The function displays the figure directly using `plt.show()`.
    """

    # récupération des paramètres d'entrées et choix automatique entre la courbe BNN et
    #  la courbe IntCal20 en fonction des résultats de calibration
    c14age = calibration_results['c14age']
    c14sig = calibration_results['c14sig']
    covariables = calibration_results['covariables']
    if covariables == None :
        plot_BNN = False
        plot_IntCal20 = True
    else :
        plot_BNN = True
        plot_IntCal20 = False

    if figsize == None :
        # choix des unités pour les axes afin de fixer la taille de la figure
        cm = 1/2.54  # centimètres en pouces
        #figsize=(29.7*cm, 29.7*cm)
        figsize=(13*cm, 10.5*cm)

    if fig == None and axs == None :
        # subdivision de la grille en 4 parties (2 lignes et 2 colonnes)
        fig, axs = plt.subplots(
            nrows=2, 
            ncols=2, 
            figsize=figsize,
            gridspec_kw={
                'width_ratios': [1, 3],
                'height_ratios': [3, 1]
            }
        )

    # plot 1 (axs[0,0]) : distribution de la mesure de laboratoire

    add_c14age_density_plot(
        c14age=c14age,
        c14sig=c14sig,
        ax=axs[0,0],
        color=color_c14age,
        support_size=support_size,
        sample_size =sample_size,
        plot_density=plot_density,
        fill_density=fill_density
    )

    # plot 2 (axs[0,1]) : Courbe de calibration et incertitude autour de la courbe

    ax = axs[0,1]
    if plot_BNN :
        if parts_1_and_2 :
            add_bnn_calibration_curve(
                ax = ax,
                figsize = None,
                color = color_BNN,
                alpha=.3,
                incertitude = True,
                sigma_length = 1,
                Min_x = None, Max_x = None,
                Min_y = None, Max_y = None,
                invert_xaxis = True,
                domaine = ['delta14c', 'c14', 'f14c'][1],
                covariables = covariables,
                credible_interval = False,
                credible_interval_level = 0.95,
                credible_color = None,
                credible_alpha = None
            )
            part_1 = False
            part_2 = False
        elif part_1 :
            add_individual_calibration_curve_part_1(
                ax = ax,
                figsize = None,
                color = color_BNN,
                alpha=.3,
                incertitude = True,
                sigma_length = 1,
                Min_x = None, Max_x = None,
                Min_y = None, Max_y = None,
                invert_xaxis = True,
                domaine = ['delta14c', 'c14', 'f14c'][1],
                covariables = covariables,
                credible_interval = False,
                credible_interval_level = 0.95,
                credible_color = None,
                credible_alpha = None
            )
        else :
            part_2 = True

        if part_2 :
            add_individual_calibration_curve_part_2(
                ax = ax,
                figsize = None,
                color = color_BNN,
                alpha=.3,
                incertitude = True,
                sigma_length = 1,
                Min_x = None, Max_x = None,
                Min_y = None, Max_y = None,
                invert_xaxis = True,
                domaine = ['delta14c', 'c14', 'f14c'][1],
                covariables = covariables,
                credible_interval = False,
                credible_interval_level = 0.95,
                credible_color = None,
                credible_alpha = None
            )
    else :
        plot_IntCal20 = True

    if plot_IntCal20 :
        add_IntCal20_curve(
            ax = ax,
            figsize = None,
            color = color_IntCal20,
            alpha=.3,
            incertitude = True,
            sigma_length = 1,
            Min_x = None, Max_x = None,
            Min_y = None, Max_y = None,
            invert_xaxis = True,
            domaine = ['delta14c', 'c14', 'f14c'][1]
        )

    # plot 3 (axs[1,0]) : Vide

    axs[1,0].spines[:].set_visible(False)
    axs[1,0].xaxis.set_ticks([])
    axs[1,0].yaxis.set_ticks([])

    # plot 4 (axs[1,1]) : distribution a posteriori sur les dates (date calibrée)

    add_cal_date_density_plot_and_HPD_region(
        calibration_results=calibration_results,
        ax=axs[1,1],
        color=color_cal_date,
        eps=eps,
        add_legend=False,
        set_title=False,
        plot_HPD_bounds=plot_HPD_bounds,
        plot_HPD_threshold=plot_HPD_threshold
    )

    # paramétrage limites plot 2 
    ax.set_xlim(
        axs[1,1].get_xlim()
    )
    ax.set_ylim(
        axs[0,0].get_ylim()
    )
    ax.set_xlabel('')

    # grille
    if add_grid :
        axs[0,0].grid()
        axs[0,1].grid() # == ax.grid() ici car ax = axs[0,1]
        axs[1,1].grid()

    # légende et figure

    fig.tight_layout()
    #fig.legend(loc="lower left")
    fig.legend(
        loc='lower left', 
        fontsize=fontsize_legend,
        fancybox=True, 
        framealpha=0., 
        bbox_to_anchor=(0., 0.05)
    )
    plt.show()

plot_individual_calibration_curve_part_1(xlabel='Calibrated dates (in years BP)', ylabel='Radiocarbon ages (in years BP)', add_grid=True, fontsize_legend='small', ax=None, figsize=None, color='cyan', alpha=0.4, incertitude=True, sigma_length=1, Min_x=None, Max_x=None, Min_y=None, Max_y=None, invert_xaxis=True, domaine=['delta14c', 'c14', 'f14c'][0], covariables=False, credible_interval=False, credible_interval_level=0.95, credible_color=None, credible_alpha=None)

Plot the BNN calibration curve (part 1) by calling add_individual_calibration_curve_part_1 and applying axis labels, grid, legend, and final display.

This function is a thin wrapper around add_individual_calibration_curve_part_1 and only handles visual elements such as xlabel, ylabel, grid and legend.

Parameters:

Name Type Description Default
xlabel str

Label for the x-axis.

'Calibrated dates (in years BP)'
ylabel str

Label for the y-axis. Adjusted automatically if domaine is "delta14c" or "f14c".

'Radiocarbon ages (in years BP)'
add_grid bool

Whether to display a grid on the plot.

True
fontsize_legend str

Font size for the legend.

'small'
ax Axes or None

Axis to draw on. If None, the axis internally created by add_individual_calibration_curve_part_1 is used.

None
figsize tuple(int, int) or None

Figure size forwarded to the plotting function.

None
color str

Color used for plotting the BNN mean curve.

'cyan'
alpha float

Transparency for uncertainty or credible interval fills.

0.4
incertitude bool

Whether to draw the ±σ uncertainty band around the mean curve.

True
sigma_length int

Number of standard deviations for the uncertainty band.

1
Min_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Max_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Min_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
Max_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
invert_xaxis bool

If True, the x-axis is inverted (IntCal convention).

True
domaine (delta14c, c14, f14c)

Domain of radiocarbon quantities displayed.

'delta14c'
covariables bool

Whether to use BNN predictions trained with covariates.

False
credible_interval bool

If True, compute and plot pointwise credible intervals from predictive samples.

False
credible_interval_level float

Credible interval level (e.g. 0.95 for 95% credible interval). Default 0.95.

0.95
credible_color str or None

Color for the credible interval fill. If None the main color is used.

None
credible_alpha float or None

Alpha transparency for the credible interval fill. If None alpha is used.

None

Returns:

Type Description
None

The function produces a plot.

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
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
def plot_individual_calibration_curve_part_1(
    xlabel: str = "Calibrated dates (in years BP)",
    ylabel: str = "Radiocarbon ages (in years BP)",
    add_grid: bool = True,
    fontsize_legend: str = 'small',
    ax: Optional[plt.Axes] = None,
    figsize: Optional[Tuple[int, int]] = None,
    color: str = 'cyan',
    alpha: float = .4,
    incertitude: bool = True,
    sigma_length: int = 1,
    Min_x: Optional[float] = None, Max_x: Optional[float] = None,
    Min_y: Optional[float] = None, Max_y: Optional[float] = None,
    invert_xaxis: bool = True,
    domaine: str = ['delta14c', 'c14', 'f14c'][0],
    covariables: bool = False,
    credible_interval: bool = False,
    credible_interval_level: float = 0.95,
    credible_color: Optional[str] = None,
    credible_alpha: Optional[float] = None
) -> None:
    """
    Plot the BNN calibration curve (part 1) by calling
    ``add_individual_calibration_curve_part_1`` and applying axis labels,
    grid, legend, and final display.

    This function is a thin wrapper around
    ``add_individual_calibration_curve_part_1`` and only handles visual
    elements such as xlabel, ylabel, grid and legend.

    Parameters
    ----------
    xlabel : str, optional
        Label for the x-axis.
    ylabel : str, optional
        Label for the y-axis. Adjusted automatically if `domaine` is `"delta14c"` or `"f14c"`.
    add_grid : bool, optional
        Whether to display a grid on the plot.
    fontsize_legend : str, optional
        Font size for the legend.
    ax : matplotlib.axes.Axes or None, optional
        Axis to draw on. If ``None``, the axis internally created by
        ``add_individual_calibration_curve_part_1`` is used.
    figsize : tuple(int, int) or None, optional
        Figure size forwarded to the plotting function.
    color : str, optional
        Color used for plotting the BNN mean curve.
    alpha : float, optional
        Transparency for uncertainty or credible interval fills.
    incertitude : bool, optional
        Whether to draw the ±σ uncertainty band around the mean curve.
    sigma_length : int, optional
        Number of standard deviations for the uncertainty band.
    Min_x, Max_x : float or None, optional
        Optional x-axis limits; when both provided the axis limits are set.
    Min_y, Max_y : float or None, optional
        Optional y-axis limits; when both provided the axis limits are set.
    invert_xaxis : bool, optional
        If True, the x-axis is inverted (IntCal convention).
    domaine : {'delta14c', 'c14', 'f14c'}, optional
        Domain of radiocarbon quantities displayed.
    covariables : bool, optional
        Whether to use BNN predictions trained with covariates.
    credible_interval : bool, optional
        If True, compute and plot pointwise credible intervals from predictive samples.
    credible_interval_level : float, optional
        Credible interval level (e.g. 0.95 for 95% credible interval). Default 0.95.
    credible_color : str or None, optional
        Color for the credible interval fill. If ``None`` the main ``color`` is used.
    credible_alpha : float or None, optional
        Alpha transparency for the credible interval fill. If ``None`` ``alpha`` is used.

    Returns
    -------
    None
        The function produces a plot.
    """
    ax = add_individual_calibration_curve_part_1(
            ax = ax,
            figsize = figsize,
            color = color,
            alpha= alpha,
            incertitude = incertitude,
            sigma_length = sigma_length,
            Min_x = Min_x, Max_x = Max_x,
            Min_y = Min_y, Max_y = Max_y,
            invert_xaxis = True,
            domaine = domaine,
            covariables = covariables,
            credible_interval = credible_interval,
            credible_interval_level = credible_interval_level,
            credible_color = credible_color,
            credible_alpha = credible_alpha
    )

    plt.xlabel(xlabel)
    if domaine == 'delta14c' :
        ylabel = "$\Delta^{14}$C"
    if domaine == 'f14c' :
        ylabel = "F$^{14}$C"
    plt.ylabel(ylabel)
    plt.grid(add_grid)
    plt.legend(fontsize=fontsize_legend)
    plt.show()

plot_individual_calibration_curve_part_2(xlabel='Calibrated dates (in years BP)', ylabel='Radiocarbon ages (in years BP)', add_grid=True, fontsize_legend='small', ax=None, figsize=None, color='cyan', alpha=0.4, incertitude=True, sigma_length=1, Min_x=None, Max_x=None, Min_y=None, Max_y=None, invert_xaxis=True, domaine=['delta14c', 'c14', 'f14c'][0], covariables=False, credible_interval=False, credible_interval_level=0.95, credible_color=None, credible_alpha=None)

Plot the BNN calibration curve (part 2) by calling add_individual_calibration_curve_part_2 and applying axis labels, grid, legend, and final display.

This function is a thin wrapper around add_individual_calibration_curve_part_2 and only handles visual elements such as xlabel, ylabel, grid and legend.

Parameters:

Name Type Description Default
xlabel str

Label for the x-axis.

'Calibrated dates (in years BP)'
ylabel str

Label for the y-axis. Adjusted automatically if domaine is "delta14c" or "f14c".

'Radiocarbon ages (in years BP)'
add_grid bool

Whether to display a grid on the plot.

True
fontsize_legend str

Font size for the legend.

'small'
ax Axes or None

Axis to draw on. If None, the axis internally created by add_individual_calibration_curve_part_2 is used.

None
figsize tuple(int, int) or None

Figure size forwarded to the plotting function.

None
color str

Color used for plotting the BNN mean curve.

'cyan'
alpha float

Transparency for uncertainty or credible interval fills.

0.4
incertitude bool

Whether to draw the ±σ uncertainty band around the mean curve.

True
sigma_length int

Number of standard deviations for the uncertainty band.

1
Min_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Max_x float or None

Optional x-axis limits; when both provided the axis limits are set.

None
Min_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
Max_y float or None

Optional y-axis limits; when both provided the axis limits are set.

None
invert_xaxis bool

If True, the x-axis is inverted (IntCal convention).

True
domaine (delta14c, c14, f14c)

Domain of radiocarbon quantities displayed.

'delta14c'
covariables bool

Whether to use BNN predictions trained with covariates.

False
credible_interval bool

If True, compute and plot pointwise credible intervals from predictive samples.

False
credible_interval_level float

Credible interval level (e.g. 0.95 for 95% credible interval). Default 0.95.

0.95
credible_color str or None

Color for the credible interval fill. If None the main color is used.

None
credible_alpha float or None

Alpha transparency for the credible interval fill. If None alpha is used.

None

Returns:

Type Description
None

The function produces a plot.

Source code in src/bnn_for_14C_calibration/calib_plot_functions.py
 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
def plot_individual_calibration_curve_part_2(
    xlabel: str = "Calibrated dates (in years BP)",
    ylabel: str = "Radiocarbon ages (in years BP)",
    add_grid: bool = True,
    fontsize_legend: str = 'small',
    ax: Optional[plt.Axes] = None,
    figsize: Optional[Tuple[int, int]] = None,
    color: str = 'cyan',
    alpha: float = .4,
    incertitude: bool = True,
    sigma_length: int = 1,
    Min_x: Optional[float] = None, Max_x: Optional[float] = None,
    Min_y: Optional[float] = None, Max_y: Optional[float] = None,
    invert_xaxis: bool = True,
    domaine: str = ['delta14c', 'c14', 'f14c'][0],
    covariables: bool = False,
    credible_interval: bool = False,
    credible_interval_level: float = 0.95,
    credible_color: Optional[str] = None,
    credible_alpha: Optional[float] = None
) -> None:
    """
    Plot the BNN calibration curve (part 2) by calling
    ``add_individual_calibration_curve_part_2`` and applying axis labels,
    grid, legend, and final display.

    This function is a thin wrapper around
    ``add_individual_calibration_curve_part_2`` and only handles visual
    elements such as xlabel, ylabel, grid and legend.

    Parameters
    ----------
    xlabel : str, optional
        Label for the x-axis.
    ylabel : str, optional
        Label for the y-axis. Adjusted automatically if `domaine` is `"delta14c"` or `"f14c"`.
    add_grid : bool, optional
        Whether to display a grid on the plot.
    fontsize_legend : str, optional
        Font size for the legend.
    ax : matplotlib.axes.Axes or None, optional
        Axis to draw on. If ``None``, the axis internally created by
        ``add_individual_calibration_curve_part_2`` is used.
    figsize : tuple(int, int) or None, optional
        Figure size forwarded to the plotting function.
    color : str, optional
        Color used for plotting the BNN mean curve.
    alpha : float, optional
        Transparency for uncertainty or credible interval fills.
    incertitude : bool, optional
        Whether to draw the ±σ uncertainty band around the mean curve.
    sigma_length : int, optional
        Number of standard deviations for the uncertainty band.
    Min_x, Max_x : float or None, optional
        Optional x-axis limits; when both provided the axis limits are set.
    Min_y, Max_y : float or None, optional
        Optional y-axis limits; when both provided the axis limits are set.
    invert_xaxis : bool, optional
        If True, the x-axis is inverted (IntCal convention).
    domaine : {'delta14c', 'c14', 'f14c'}, optional
        Domain of radiocarbon quantities displayed.
    covariables : bool, optional
        Whether to use BNN predictions trained with covariates.
    credible_interval : bool, optional
        If True, compute and plot pointwise credible intervals from predictive samples.
    credible_interval_level : float, optional
        Credible interval level (e.g. 0.95 for 95% credible interval). Default 0.95.
    credible_color : str or None, optional
        Color for the credible interval fill. If ``None`` the main ``color`` is used.
    credible_alpha : float or None, optional
        Alpha transparency for the credible interval fill. If ``None`` ``alpha`` is used.

    Returns
    -------
    None
        The function produces a plot.
    """
    ax = add_individual_calibration_curve_part_2(
            ax = ax,
            figsize = figsize,
            color = color,
            alpha= alpha,
            incertitude = incertitude,
            sigma_length = sigma_length,
            Min_x = Min_x, Max_x = Max_x,
            Min_y = Min_y, Max_y = Max_y,
            invert_xaxis = True,
            domaine = domaine,
            covariables = covariables,
            credible_interval = credible_interval,
            credible_interval_level = credible_interval_level,
            credible_color = credible_color,
            credible_alpha = credible_alpha
    )

    plt.xlabel(xlabel)
    if domaine == 'delta14c' :
        ylabel = "$\Delta^{14}$C"
    if domaine == 'f14c' :
        ylabel = "F$^{14}$C"
    plt.ylabel(ylabel)
    plt.grid(add_grid)
    plt.legend(fontsize=fontsize_legend)
    plt.show()