Skip to content

utils

Description of general helper functions implemented in the module bnn_for_14C_calibration.utils:

bnn_for_14C_calibration.utils

ajoute_segment_horizontal(y, x_min, x_max, ax=None, color='blue', linestyle='-', linewidth=2, label=None, ticks=True, tick_size=0.1)

Plot a horizontal segment from (x_min, y) to (x_max, y) with optional vertical ticks at ends.

Parameters:

Name Type Description Default
y float

Y-coordinate of the segment.

required
x_min float

Starting X-coordinate (left).

required
x_max float

Ending X-coordinate (right).

required
ax Axes

Axis to plot on. If None, uses current axis.

None
color str

Segment color (default 'blue').

'blue'
linestyle str

Line style (default '-').

'-'
linewidth float

Line width (default 2).

2
label str

Label for the segment.

None
ticks bool

If True, adds small vertical ticks at the segment ends (default True).

True
tick_size float

Length of vertical ticks (default 0.1).

0.1

Returns:

Type Description
Line2D

The main line object of the horizontal segment.

Source code in src/bnn_for_14C_calibration/utils.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
def ajoute_segment_horizontal(
    y: float,
    x_min: float,
    x_max: float,
    ax: plt.Axes = None,
    color: str = 'blue',
    linestyle: str = '-',
    linewidth: float = 2,
    label: str = None,
    ticks: bool = True,
    tick_size: float = 0.1
) -> plt.Line2D:
    """
    Plot a horizontal segment from (x_min, y) to (x_max, y) with optional vertical ticks at ends.

    Parameters
    ----------
    y : float
        Y-coordinate of the segment.
    x_min : float
        Starting X-coordinate (left).
    x_max : float
        Ending X-coordinate (right).
    ax : matplotlib.axes.Axes, optional
        Axis to plot on. If None, uses current axis.
    color : str, optional
        Segment color (default 'blue').
    linestyle : str, optional
        Line style (default '-').
    linewidth : float, optional
        Line width (default 2).
    label : str, optional
        Label for the segment.
    ticks : bool, optional
        If True, adds small vertical ticks at the segment ends (default True).
    tick_size : float, optional
        Length of vertical ticks (default 0.1).

    Returns
    -------
    matplotlib.lines.Line2D
        The main line object of the horizontal segment.
    """
    if ax is None:
        ax = plt.gca()

    line = ax.plot([x_min, x_max], [y, y], color=color, linestyle=linestyle,
                   linewidth=linewidth, label=label)[0]

    if ticks:
        ax.plot([x_min, x_min], [y - tick_size, y + tick_size], color=color, linewidth=linewidth)
        ax.plot([x_max, x_max], [y - tick_size, y + tick_size], color=color, linewidth=linewidth)

    return line

ajoute_segment_vertical(x, y_min, y_max, ax=None, color='red', linestyle='-', linewidth=2, label=None, ticks=True, tick_size=0.1)

Plot a vertical segment from (x, y_min) to (x, y_max) with optional horizontal ticks at ends.

Parameters:

Name Type Description Default
x float

X-coordinate of the segment.

required
y_min float

Starting Y-coordinate (bottom).

required
y_max float

Ending Y-coordinate (top).

required
ax Axes

Axis to plot on. If None, uses current axis.

None
color str

Segment color (default 'red').

'red'
linestyle str

Line style (default '-').

'-'
linewidth float

Line width (default 2).

2
label str

Label for the segment.

None
ticks bool

If True, adds small horizontal ticks at the segment ends (default True).

True
tick_size float

Length of horizontal ticks (default 0.1).

0.1

Returns:

Type Description
Line2D

The main line object of the vertical segment.

Source code in src/bnn_for_14C_calibration/utils.py
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
def ajoute_segment_vertical(
    x: float,
    y_min: float,
    y_max: float,
    ax: plt.Axes = None,
    color: str = 'red',
    linestyle: str = '-',
    linewidth: float = 2,
    label: str = None,
    ticks: bool = True,
    tick_size: float = 0.1
) -> plt.Line2D:
    """
    Plot a vertical segment from (x, y_min) to (x, y_max) with optional horizontal ticks at ends.

    Parameters
    ----------
    x : float
        X-coordinate of the segment.
    y_min : float
        Starting Y-coordinate (bottom).
    y_max : float
        Ending Y-coordinate (top).
    ax : matplotlib.axes.Axes, optional
        Axis to plot on. If None, uses current axis.
    color : str, optional
        Segment color (default 'red').
    linestyle : str, optional
        Line style (default '-').
    linewidth : float, optional
        Line width (default 2).
    label : str, optional
        Label for the segment.
    ticks : bool, optional
        If True, adds small horizontal ticks at the segment ends (default True).
    tick_size : float, optional
        Length of horizontal ticks (default 0.1).

    Returns
    -------
    matplotlib.lines.Line2D
        The main line object of the vertical segment.
    """
    if ax is None:
        ax = plt.gca()

    line = ax.plot([x, x], [y_min, y_max], color=color, linestyle=linestyle,
                   linewidth=linewidth, label=label)[0]

    if ticks:
        ax.plot([x - tick_size, x + tick_size], [y_min, y_min], color=color, linewidth=linewidth)
        ax.plot([x - tick_size, x + tick_size], [y_max, y_max], color=color, linewidth=linewidth)

    return line

bp_to_calendar(bp)

Converts BP (Before Present, ref. 1949) to calendar year BCE/CE.

Parameters:

Name Type Description Default
bp int or ndarray

Year(s) in BP (Before Present, reference year 1949).

required

Returns:

Type Description
Tuple[int, str] or ndarray
  • If single int: tuple (year, 'BCE' or 'CE')
  • If numpy array: structured array of (year, era) for each element
Notes
  • BP > 1949 corresponds to BCE, else CE.
  • Skips year 0: 1949 BP = 1 CE.
Source code in src/bnn_for_14C_calibration/utils.py
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
def bp_to_calendar(bp: Union[int, np.ndarray]) -> Union[Tuple[int, str], np.ndarray]:
    """
    Converts BP (Before Present, ref. 1949) to calendar year BCE/CE.

    Parameters
    ----------
    bp : int or np.ndarray
        Year(s) in BP (Before Present, reference year 1949).

    Returns
    -------
    Tuple[int, str] or np.ndarray
        - If single int: tuple (year, 'BCE' or 'CE')
        - If numpy array: structured array of (year, era) for each element

    Notes
    -----
    - BP > 1949 corresponds to BCE, else CE.
    - Skips year 0: 1949 BP = 1 CE.
    """
    if isinstance(bp, np.ndarray):
        years = np.where(bp > 1949, bp - 1949, 1950 - bp)
        eras = np.where(bp > 1949, 'BCE', 'CE')
        return np.array(list(zip(years, eras)), dtype=object)
    else:
        if bp > 1949:
            year = bp - 1949
            return (year, 'BCE')
        else:
            year = 1950 - bp  # on saute l’an 0 → donc 1949 BP = 1 CE
            return (year, 'CE')

c14_to_d14c(c14, teta)

Convert radiocarbon age (c14) to d14c domain.

Parameters:

Name Type Description Default
c14 float or ndarray

Radiocarbon age(s).

required
teta float or ndarray

Calendar age(s), same shape as c14.

required

Returns:

Type Description
float or ndarray

Corresponding d14c value(s).

Notes
  • Supports element-wise operations.
  • This function is computed as the composition of f14c_to_d14c and c14_to_f14c: d14c = f14c_to_d14c(c14_to_f14c(c14),teta).
Source code in src/bnn_for_14C_calibration/utils.py
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
def c14_to_d14c(c14: NumberOrArray, teta: NumberOrArray) -> NumberOrArray:
    """
    Convert radiocarbon age (c14) to d14c domain.

    Parameters
    ----------
    c14 : float or np.ndarray
        Radiocarbon age(s).
    teta : float or np.ndarray
        Calendar age(s), same shape as c14.

    Returns
    -------
    float or np.ndarray
        Corresponding d14c value(s).

    Notes
    -----
    - Supports element-wise operations.
    - This function is computed as the composition of `f14c_to_d14c` and `c14_to_f14c`:
        d14c = f14c_to_d14c(c14_to_f14c(c14),teta).
    """
    return f14c_to_d14c(c14_to_f14c(c14),teta)

c14_to_f14c(c14)

Convert radiocarbon age (\(^{14}\)C) to f14c domain.

Parameters:

Name Type Description Default
c14 float or ndarray

Radiocarbon age(s).

required

Returns:

Type Description
float or ndarray

Corresponding f14c value(s).

Notes
  • Supports element-wise operations.
  • As the inverse function of f14c_to_c14, it uses its formula's inverse for transformation: f14c = exp(-c14/8033)
Source code in src/bnn_for_14C_calibration/utils.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
def c14_to_f14c(c14: NumberOrArray) -> NumberOrArray:
    """
    Convert radiocarbon age ($^{14}$C) to f14c domain.

    Parameters
    ----------
    c14 : float or np.ndarray
        Radiocarbon age(s).

    Returns
    -------
    float or np.ndarray
        Corresponding f14c value(s).

    Notes
    -----
    - Supports element-wise operations.
    - As the inverse function of `f14c_to_c14`, it uses its formula's inverse for transformation:
        f14c = exp(-c14/8033)
    """
    f14c = np.exp(-c14/8033)
    return f14c

c14sig_to_d14csig(c14, c14sig, teta)

Convert \(^{14}\)C uncertainty to d14c uncertainty.

Parameters:

Name Type Description Default
c14 float or ndarray

Radiocarbon age(s).

required
c14sig float or ndarray

Uncertainty in c14.

required
teta float or ndarray

Calendar age(s), same shape as c14.

required

Returns:

Type Description
float or ndarray

Corresponding uncertainty in d14c.

Notes
  • Supports element-wise operations.
  • This function is computed as the composition of f14csig_to_d14csig and c14sig_to_f14csig: c14sig = f14csig_to_d14csig( c14sig_to_f14csig(c14,c14sig), teta ).
Source code in src/bnn_for_14C_calibration/utils.py
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
def c14sig_to_d14csig(
    c14: NumberOrArray, 
    c14sig: NumberOrArray, 
    teta: NumberOrArray
) -> NumberOrArray:
    """
    Convert $^{14}$C uncertainty to d14c uncertainty.

    Parameters
    ----------
    c14 : float or np.ndarray
        Radiocarbon age(s).
    c14sig : float or np.ndarray
        Uncertainty in c14.
    teta : float or np.ndarray
        Calendar age(s), same shape as c14.

    Returns
    -------
    float or np.ndarray
        Corresponding uncertainty in d14c.

    Notes
    -----
    - Supports element-wise operations.
    - This function is computed as the composition of `f14csig_to_d14csig` and `c14sig_to_f14csig`:
        c14sig = f14csig_to_d14csig(
            c14sig_to_f14csig(c14,c14sig),
            teta
        ).
    """
    return f14csig_to_d14csig(
        c14sig_to_f14csig(c14,c14sig),
        teta
    )

c14sig_to_f14csig(c14, c14sig)

Convert c14 uncertainty to f14c uncertainty using delta-method.

Parameters:

Name Type Description Default
c14 float or ndarray

Radiocarbon age(s).

required
c14sig float or ndarray

Uncertainty in c14, same shape as c14.

required

Returns:

Type Description
float or ndarray

Corresponding uncertainty in f14c.

Notes
  • Supports element-wise operations.
  • As the inverse function of f14csig_to_c14sig, it uses its formula's inverse for transformation: f14csig = c14sig * f14c/8033, where f14c is computed using the function c14_to_f14c.
Source code in src/bnn_for_14C_calibration/utils.py
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
def c14sig_to_f14csig(
    c14: NumberOrArray, 
    c14sig: NumberOrArray
) -> NumberOrArray:
    """
    Convert c14 uncertainty to f14c uncertainty using delta-method.

    Parameters
    ----------
    c14 : float or np.ndarray
        Radiocarbon age(s).
    c14sig : float or np.ndarray
        Uncertainty in c14, same shape as c14.

    Returns
    -------
    float or np.ndarray
        Corresponding uncertainty in f14c.

    Notes
    -----
    - Supports element-wise operations.
    - As the inverse function of `f14csig_to_c14sig`, it uses its formula's inverse for transformation:
        f14csig = c14sig * f14c/8033, 
        where f14c is computed using the function `c14_to_f14c`.
    """
    f14c = c14_to_f14c(c14 = c14)
    f14c_sig = c14sig*f14c/8033 # f14c > 0
    return f14c_sig

calendar_to_bp(year, era)

Converts calendar year(s) in BCE or CE to BP (Before Present, ref. 1949).

Parameters:

Name Type Description Default
year int or ndarray

Positive calendar year(s) in BCE or CE.

required
era str or ndarray

Era indicator(s): 'BCE' or 'CE'. If a NumPy array is provided, it must have the same shape as year.

required

Returns:

Type Description
int or ndarray

Corresponding year(s) in BP.

Raises:

Type Description
ValueError

If any element in era is not 'BCE' or 'CE', or if array shapes do not match.

Notes
  • Skips year 0: 1 CE = 1949 BP.
  • Supports both scalar and vectorized inputs.
  • When given a structured array as returned by bp_to_calendar, it will internally extract the year and era columns before computation.

Examples:

>>> calendar_to_bp(2500, 'BCE')
4449
>>> calendar_to_bp(2020, 'CE')
-70
>>> arr = np.array([[2500, 'BCE'], [2020, 'CE']], dtype=object)
>>> calendar_to_bp(arr[:, 0].astype(int), arr[:, 1])
array([4449.,  -70.])
>>> calendar_to_bp(arr[:, 0], arr[:, 1])
array([4449.,  -70.])
Source code in src/bnn_for_14C_calibration/utils.py
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
def calendar_to_bp(
    year: Union[int, np.ndarray],
    era: Union[str, np.ndarray]
) -> Union[int, np.ndarray]:
    """
    Converts calendar year(s) in BCE or CE to BP (Before Present, ref. 1949).

    Parameters
    ----------
    year : int or np.ndarray
        Positive calendar year(s) in BCE or CE.
    era : str or np.ndarray
        Era indicator(s): 'BCE' or 'CE'.
        If a NumPy array is provided, it must have the same shape as `year`.

    Returns
    -------
    int or np.ndarray
        Corresponding year(s) in BP.

    Raises
    ------
    ValueError
        If any element in `era` is not 'BCE' or 'CE', or if array shapes do not match.

    Notes
    -----
    - Skips year 0: 1 CE = 1949 BP.
    - Supports both scalar and vectorized inputs.
    - When given a structured array as returned by `bp_to_calendar`,
      it will internally extract the year and era columns before computation.

    Examples
    --------
    >>> calendar_to_bp(2500, 'BCE')
    4449

    >>> calendar_to_bp(2020, 'CE')
    -70

    >>> arr = np.array([[2500, 'BCE'], [2020, 'CE']], dtype=object)
    >>> calendar_to_bp(arr[:, 0].astype(int), arr[:, 1])
    array([4449.,  -70.])
    >>> calendar_to_bp(arr[:, 0], arr[:, 1])
    array([4449.,  -70.])
    """
    # Support structured array returned by bp_to_calendar
    if isinstance(year, np.ndarray) and year.dtype == object and year.ndim == 2 and year.shape[1] == 2:
        # form (year, era)
        year, era = year[:, 0].astype(int), year[:, 1]

    if isinstance(year, np.ndarray):
        if not isinstance(era, np.ndarray):
            raise ValueError("When 'year' is an array, 'era' must also be an array.")
        if year.shape != era.shape:
            raise ValueError("'year' and 'era' arrays must have the same shape.")

        bp = np.empty_like(year, dtype=float)
        mask_bce = era == 'BCE'
        mask_ce = era == 'CE'

        if not np.all(mask_bce | mask_ce):
            raise ValueError("All 'era' values must be either 'BCE' or 'CE'.")

        bp[mask_bce] = 1949 + year[mask_bce]
        bp[mask_ce] = 1950 - year[mask_ce]
        return bp
    else:
        if era == 'BCE':
            return 1949 + year
        elif era == 'CE':
            return 1950 - year  # on saute l’an 0
        else:
            raise ValueError("Era must be 'BCE' or 'CE'.")

d14c_to_c14(d14c, teta)

Convert d14c domain to radiocarbon age (\(^{14}\)C).

Parameters:

Name Type Description Default
d14c float or ndarray

d14c value(s).

required
teta float or ndarray

Calendar age(s), same shape as d14c.

required

Returns:

Type Description
float or ndarray

Corresponding c14 value(s).

Notes
  • Supports element-wise operations.
  • This function is computed as the composition of f14c_to_c14 and d14c_to_f14c: c14 = f14c_to_c14(d14c_to_f14c(d14c,teta)).
Source code in src/bnn_for_14C_calibration/utils.py
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
def d14c_to_c14(
    d14c: NumberOrArray, 
    teta: NumberOrArray
) -> NumberOrArray:
    """
    Convert d14c domain to radiocarbon age ($^{14}$C).

    Parameters
    ----------
    d14c : float or np.ndarray
        d14c value(s).
    teta : float or np.ndarray
        Calendar age(s), same shape as d14c.

    Returns
    -------
    float or np.ndarray
        Corresponding c14 value(s).

    Notes
    -----
    - Supports element-wise operations.
    - This function is computed as the composition of `f14c_to_c14` and `d14c_to_f14c`:
        c14 = f14c_to_c14(d14c_to_f14c(d14c,teta)).
    """
    return f14c_to_c14(d14c_to_f14c(d14c,teta))

d14c_to_f14c(d14c, teta)

Convert d14c domain to f14c domain.

Parameters:

Name Type Description Default
d14c float or ndarray

d14c value(s).

required
teta float or ndarray

Calendar age(s), must match the shape of d14c.

required

Returns:

Type Description
float or ndarray

Corresponding f14c value(s).

Notes
  • Supports element-wise operations.
  • Uses transformation formula: f14c = (1 + d14c/1000) * exp(-teta/8267)
Source code in src/bnn_for_14C_calibration/utils.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def d14c_to_f14c(
    d14c: NumberOrArray, 
    teta: NumberOrArray
) -> NumberOrArray:
    """
    Convert d14c domain to f14c domain.

    Parameters
    ----------
    d14c : float or np.ndarray
        d14c value(s).
    teta : float or np.ndarray
        Calendar age(s), must match the shape of d14c.

    Returns
    -------
    float or np.ndarray
        Corresponding f14c value(s).

    Notes
    -----
    - Supports element-wise operations.
    - Uses transformation formula: 
        f14c = (1 + d14c/1000) * exp(-teta/8267)
    """
    f14c = (1/1000*d14c + 1)*np.exp(-teta/8267)
    return f14c

d14csig_to_c14sig(d14c, d14csig, teta)

Convert d14c uncertainty to \(^{14}\)C uncertainty.

Parameters:

Name Type Description Default
d14c float or ndarray

d14c value(s).

required
d14csig float or ndarray

Uncertainty in d14c.

required
teta float or ndarray

Calendar age(s), same shape as d14c.

required

Returns:

Type Description
float or ndarray

Corresponding uncertainty in \(^{14}\)C.

Notes
  • Supports element-wise operations.
  • This function is computed as the composition of f14csig_to_c14sig, d14c_to_f14c and d14csig_to_f14csig: c14sig = f14csig_to_c14sig( d14c_to_f14c(d14c,teta), d14csig_to_f14csig(d14csig,teta) ).
Source code in src/bnn_for_14C_calibration/utils.py
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
def d14csig_to_c14sig(
    d14c: NumberOrArray, 
    d14csig: NumberOrArray, 
    teta: NumberOrArray
) -> NumberOrArray:
    """
    Convert d14c uncertainty to $^{14}$C uncertainty.

    Parameters
    ----------
    d14c : float or np.ndarray
        d14c value(s).
    d14csig : float or np.ndarray
        Uncertainty in d14c.
    teta : float or np.ndarray
        Calendar age(s), same shape as d14c.

    Returns
    -------
    float or np.ndarray
        Corresponding uncertainty in $^{14}$C.

    Notes
    -----
    - Supports element-wise operations.
    - This function is computed as the composition of `f14csig_to_c14sig`, 
        `d14c_to_f14c` and `d14csig_to_f14csig`:
        c14sig = f14csig_to_c14sig(
            d14c_to_f14c(d14c,teta),
            d14csig_to_f14csig(d14csig,teta)
        ).
    """
    return f14csig_to_c14sig(
        d14c_to_f14c(d14c,teta),
        d14csig_to_f14csig(d14csig,teta)
    )

d14csig_to_f14csig(d14csig, teta)

Convert d14c uncertainty to f14c uncertainty.

Parameters:

Name Type Description Default
d14csig float or ndarray

Uncertainty in d14c.

required
teta float or ndarray

Calendar age(s), same shape as d14csig.

required

Returns:

Type Description
float or ndarray

Corresponding uncertainty in f14c.

Notes
  • Supports element-wise operations.
  • Transformation formula can be derived directly or by using delta-method: f14csig = d14csig * exp(-teta/8267)/1000
Source code in src/bnn_for_14C_calibration/utils.py
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
def d14csig_to_f14csig(
    d14csig: NumberOrArray, 
    teta: NumberOrArray
) -> NumberOrArray:
    """
    Convert d14c uncertainty to f14c uncertainty.

    Parameters
    ----------
    d14csig : float or np.ndarray
        Uncertainty in d14c.
    teta : float or np.ndarray
        Calendar age(s), same shape as d14csig.

    Returns
    -------
    float or np.ndarray
        Corresponding uncertainty in f14c.

    Notes
    -----
    - Supports element-wise operations.
    - Transformation formula can be derived directly or by using delta-method: 
        f14csig = d14csig * exp(-teta/8267)/1000
    """
    f14csig = d14csig*np.exp(-teta/8267)/1000
    return f14csig

f14c_to_c14(f14c)

Convert f14c domain to radiocarbon age (\(^{14}\)C).

Parameters:

Name Type Description Default
f14c float or ndarray

f14c value(s).

required

Returns:

Type Description
float or ndarray

Radiocarbon age(s) \(^{14}\)C.

Notes
  • Supports element-wise operations.
  • Uses transformation formula: c14 = -8033 * log(f14c)
Source code in src/bnn_for_14C_calibration/utils.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
def f14c_to_c14(f14c: NumberOrArray) -> NumberOrArray:
    """
    Convert f14c domain to radiocarbon age ($^{14}$C).

    Parameters
    ----------
    f14c : float or np.ndarray
        f14c value(s).

    Returns
    -------
    float or np.ndarray
        Radiocarbon age(s) $^{14}$C.

    Notes
    -----
    - Supports element-wise operations.
    - Uses transformation formula: 
        c14 = -8033 * log(f14c)
    """
    c14 = -8033*np.log(f14c)
    return c14

f14c_to_d14c(f14c, teta)

Convert f14c to d14c.

Parameters:

Name Type Description Default
f14c float or ndarray

f14c value(s).

required
teta float or ndarray

Calendar age(s), same shape as f14c.

required

Returns:

Type Description
float or ndarray

Corresponding d14c value(s).

Notes
  • Supports element-wise operations.
  • As the inverse function of d14c_to_f14c, it uses its formula's inverse for transformation: d14c = 1000 * (-1 + f14c * exp(teta/8267))
Source code in src/bnn_for_14C_calibration/utils.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def f14c_to_d14c(
    f14c: NumberOrArray, 
    teta: NumberOrArray
) -> NumberOrArray:
    """
    Convert f14c to d14c.

    Parameters
    ----------
    f14c : float or np.ndarray
        f14c value(s).
    teta : float or np.ndarray
        Calendar age(s), same shape as f14c.

    Returns
    -------
    float or np.ndarray
        Corresponding d14c value(s).

    Notes
    -----
    - Supports element-wise operations.
    - As the inverse function of `d14c_to_f14c`, it uses its formula's inverse for transformation:
        d14c = 1000 * (-1 + f14c * exp(teta/8267))
    """
    d14c = 1000*(-1 + f14c*np.exp(teta/8267))
    return d14c

f14csig_to_c14sig(f14c, f14csig)

Convert f14c uncertainty to \(^{14}\)C uncertainty using delta-method.

Parameters:

Name Type Description Default
f14c float or ndarray

f14c value(s).

required
f14csig float or ndarray

Uncertainty in f14c, same shape as f14c.

required

Returns:

Type Description
float or ndarray

Corresponding uncertainty in \(^{14}\)C.

Notes
  • Supports element-wise operations.
  • Transformation formula cannot be derived directly but by using delta-method: c14sig = f14csig * 8033/f14c
Source code in src/bnn_for_14C_calibration/utils.py
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
def f14csig_to_c14sig(
    f14c: NumberOrArray, 
    f14csig: NumberOrArray
) -> NumberOrArray:
    """
    Convert f14c uncertainty to $^{14}$C uncertainty using delta-method.

    Parameters
    ----------
    f14c : float or np.ndarray
        f14c value(s).
    f14csig : float or np.ndarray
        Uncertainty in f14c, same shape as f14c.

    Returns
    -------
    float or np.ndarray
        Corresponding uncertainty in $^{14}$C.

    Notes
    -----
    - Supports element-wise operations.
    - Transformation formula cannot be derived directly but by using delta-method: 
        c14sig = f14csig * 8033/f14c
    """
    c14_sig = f14csig*8033/f14c # f14c > 0
    return c14_sig

f14csig_to_d14csig(f14csig, teta)

Convert f14c uncertainty to d14c uncertainty.

Parameters:

Name Type Description Default
f14csig float or ndarray

Uncertainty in f14c.

required
teta float or ndarray

Calendar age(s), same shape as f14csig.

required

Returns:

Type Description
float or ndarray

Corresponding uncertainty in d14c.

Notes
  • Supports element-wise operations.
  • As the inverse function of d14csig_to_f14csig, it uses its formula's inverse for transformation: d14csig = 1000 * f14csig * exp(teta/8267)
Source code in src/bnn_for_14C_calibration/utils.py
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
def f14csig_to_d14csig(
    f14csig: NumberOrArray, 
    teta: NumberOrArray
) -> NumberOrArray:
    """
    Convert f14c uncertainty to d14c uncertainty.

    Parameters
    ----------
    f14csig : float or np.ndarray
        Uncertainty in f14c.
    teta : float or np.ndarray
        Calendar age(s), same shape as f14csig.

    Returns
    -------
    float or np.ndarray
        Corresponding uncertainty in d14c.

    Notes
    -----
    - Supports element-wise operations.
    - As the inverse function of `d14csig_to_f14csig`, it uses its formula's inverse for transformation:
        d14csig = 1000 * f14csig * exp(teta/8267)
    """
    d14csig = 1000*f14csig*np.exp(teta/8267)
    return d14csig

get_lib_data_paths()

Generate paths to embedded package data or local cache data.

Returns:

Type Description
Dict[str, Path]

Dictionary containing paths to: - IntCal20 data - Exogenous variables - Bayesian neural network predictions and weights (from local cache if exists)

Notes
  • If the cache does not exist, it will automatically be created using download_cache_lib_data.
Source code in src/bnn_for_14C_calibration/utils.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def get_lib_data_paths() -> Dict[str, Path]:
    """
    Generate paths to embedded package data or local cache data.

    Returns
    -------
    Dict[str, Path]
        Dictionary containing paths to:
        - IntCal20 data
        - Exogenous variables
        - Bayesian neural network predictions and weights (from local cache if exists)

    Notes
    -----
    - If the cache does not exist, it will automatically be created using `download_cache_lib_data`.
    """

    # dossier contenant les scripts et données embarquées dans la librairie
    # c.a.d dir_path = "chemin_absolu_vers_src/bnn_for_14C_calibration_c14"
    dir_path = Path(__file__).resolve().parent 

    # ========================================================================
    # embedded package data in src/bnn_for_14C_calibration/data : 
    # ========================================================================

    ## TO DO : 
    ## manage embedded package data in src/bnn_for_14C_calibration/data with 
    ## import importlib.resources as pkg_resources
    ## and see how to modify paths generated here and their use in the package

    # dossier contenant les données IntCal20
    IntCal20_dir = dir_path / "data" / "IntCal20"

    # dossier contenant les variables exogènes 
    covariates_dir = dir_path / "data" / "exogenous_variables"

    # ========================================================================
    # package data (to be) stored in local cache 
    # ========================================================================

    # dossier contenant les prédictions pré-sauvegardées de différents réseaux de neurones bayésiens
    if not (CACHE_DIR.exists() and CACHE_DIR.is_dir()):
        # pour tester en local depuis le repo git avant construction de la librairie, utiliser le chemin suivant : 
        bnn_predictions_dir = dir_path.parents[1] / "models" / "predictions" / "last_version"
        bnn_weights_dir = dir_path.parents[1] / "models" / "weights"

        # si l'un des chemins locaux spécifié ci-dessus n'existe pas, 
        # on crée le cache local et on re-définit les chemins en utilisant le cache créé
        if not (
            (
                bnn_predictions_dir.exists() and bnn_predictions_dir.is_dir()
            ) or (
                bnn_weights_dir.exists() and bnn_weights_dir.is_dir()
            )
        ):
            download_cache_lib_data()
            bnn_predictions_dir = CACHE_DIR / "models" / "predictions" / "last_version"
            bnn_weights_dir = CACHE_DIR / "models" / "weights"
    else :
        # sinon, pour la librairie finale, on utilise les prédictions en cache
        bnn_predictions_dir = CACHE_DIR / "models" / "predictions" / "last_version"
        bnn_weights_dir = CACHE_DIR / "models" / "weights"

    paths_results_dict = {
        "IntCal20_dir" : IntCal20_dir,
        "covariates_dir" : covariates_dir,
        "bnn_predictions_dir" : bnn_predictions_dir,
        "bnn_weights_dir" : bnn_weights_dir
    }

    return paths_results_dict

load_data(path, sep=';')

Load a CSV file into a pandas DataFrame.

Parameters:

Name Type Description Default
path str or Path

Path to the CSV file.

required
sep str

Separator used in the CSV file (default ';').

';'

Returns:

Type Description
DataFrame

Loaded dataset.

Source code in src/bnn_for_14C_calibration/utils.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def load_data(
    path: Union[str, Path], 
    sep: str = ";"
) -> pd.DataFrame:
    """
    Load a CSV file into a pandas DataFrame.

    Parameters
    ----------
    path : str or Path
        Path to the CSV file.
    sep : str, optional
        Separator used in the CSV file (default ';').

    Returns
    -------
    pd.DataFrame
        Loaded dataset.
    """
    dataset = pd.read_csv(path, sep =sep)
    return dataset

minimax_scaling(x, Max, Min)

Apply manual min-max scaling to a single value or numpy array.

Parameters:

Name Type Description Default
x float or ndarray

Input value(s).

required
Max float

Maximum of the original range.

required
Min float

Minimum of the original range.

required

Returns:

Type Description
float or ndarray

Scaled value(s) (in [0,1] if Min <= x <= Max).

Notes
  • If x is a numpy array, the operation is applied element-wise.
Source code in src/bnn_for_14C_calibration/utils.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def minimax_scaling(
    x: NumberOrArray, 
    Max: float, 
    Min: float
) -> NumberOrArray:
    """
    Apply manual min-max scaling to a single value or numpy array.

    Parameters
    ----------
    x : float or np.ndarray
        Input value(s).
    Max : float
        Maximum of the original range.
    Min : float
        Minimum of the original range.

    Returns
    -------
    float or np.ndarray
        Scaled value(s) (in [0,1] if Min <= x <= Max).

    Notes
    -----
    - If x is a numpy array, the operation is applied element-wise.
    """
    return (x-Min)/(Max-Min)

minimax_scaling_reciproque(x, Max, Min)

Inverse min-max scaling for a value or numpy array.

Parameters:

Name Type Description Default
x float or ndarray

Scaled value(s).

required
Max float

Maximum of the original range.

required
Min float

Minimum of the original range.

required

Returns:

Type Description
float or ndarray

Original value(s) before scaling (in [Min,Max] if 0 <= x <= 1).

Notes
  • If x is a numpy array, the operation is applied element-wise.
Source code in src/bnn_for_14C_calibration/utils.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def minimax_scaling_reciproque(x: NumberOrArray, Max: float, Min: float) -> NumberOrArray:
    """
    Inverse min-max scaling for a value or numpy array.

    Parameters
    ----------
    x : float or np.ndarray
        Scaled value(s).
    Max : float
        Maximum of the original range.
    Min : float
        Minimum of the original range.

    Returns
    -------
    float or np.ndarray
        Original value(s) before scaling (in [Min,Max] if 0 <= x <= 1).

    Notes
    -----
    - If x is a numpy array, the operation is applied element-wise.
    """
    return (Max-Min)*x + Min

read_params_from_file(file_path)

Read parameters from a text file and convert them to proper Python types.

Parameters:

Name Type Description Default
file_path str or Path

Path to the file containing parameters in 'key : value' format.

required

Returns:

Type Description
Dict[str, Any]

Dictionary mapping parameter names to their values, converted to int, float, bool, or str depending on content.

Notes
  • Boolean values are recognized as "True" or "False".
  • Float values are recognized for keys ['alpha', 'beta', 'min_delta'].
  • Other values are attempted to convert to int, otherwise stored as str.
Source code in src/bnn_for_14C_calibration/utils.py
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
def read_params_from_file(file_path: Union[str, Path]) -> Dict[str, Any]:
    """
    Read parameters from a text file and convert them to proper Python types.

    Parameters
    ----------
    file_path : str or Path
        Path to the file containing parameters in 'key : value' format.

    Returns
    -------
    Dict[str, Any]
        Dictionary mapping parameter names to their values, converted to
        int, float, bool, or str depending on content.

    Notes
    -----
    - Boolean values are recognized as "True" or "False".
    - Float values are recognized for keys ['alpha', 'beta', 'min_delta'].
    - Other values are attempted to convert to int, otherwise stored as str.
    """
    keys: Dict[str, Any] = {}
    with open(file_path, 'r') as file :
        for line in file :
            key,value = line.strip().split(sep=" : ")

            # booléens
            if value == "True" :
                value = True
            elif value == "False" :
                value = False

            # floattants
            elif key in ['alpha', 'beta', 'min_delta'] :
                value = float(value)

            # entiers ou chaînes de caractères
            else :
                try :
                    # entiers
                    value = int(value)
                except ValueError as e :
                    # chaînes de caractère (ou erreurs non prévues)
                    #if __name__ == "__main__" :
                    print(f"""
                            Ignored error : {e} \n
                            If the parameter {key} is supposed to be a string, this error is normal and ignored. \n
                            Otherwise, this may be a non-handled case and the parameter will be stored as a string.
                    """)
                    pass

            keys[key] = value
    return keys