Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

REF: splines restructure #415

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
6638229
REF: splines restructure
attack68 Sep 24, 2024
cb742cf
REF: splines restructure
attack68 Sep 24, 2024
7dccbe9
calibrate method
attack68 Sep 25, 2024
ba8855a
try to calibrate
attack68 Sep 25, 2024
c54984a
Merge branch 'main' into refactor-splines
attack68 Oct 1, 2024
077715a
Merge branch 'main' into refactor-splines
attack68 Oct 2, 2024
d0db482
Merge branch 'main' into refactor-splines
attack68 Oct 18, 2024
f72e987
Merge branch 'refs/heads/main' into refactor-splines
attack68 Oct 26, 2024
b7d6bcb
Merge branch 'main' into refactor-splines
attack68 Nov 11, 2024
e543f6d
Merge branch 'main' into refactor-splines
attack68 Nov 25, 2024
57d7809
Merge branch 'main' into refactor-splines
attack68 Nov 29, 2024
1a03054
Merge branch 'main' into refactor-splines
attack68 Dec 8, 2024
201579b
Merge branch 'main' into refactor-splines
attack68 Dec 10, 2024
8634559
Merge branch 'main' into refactor-splines
attack68 Dec 16, 2024
5e07943
Merge branch 'main' into refactor-splines
attack68 Dec 17, 2024
5e74348
Merge branch 'main' into refactor-splines
attack68 Dec 19, 2024
dd2b311
Merge remote-tracking branch 'origin/main' into refactor-splines
attack68 Dec 26, 2024
9cea390
Merge branch 'main' into refactor-splines
attack68 Dec 27, 2024
201800d
Merge branch 'main' into refactor-splines
attack68 Dec 30, 2024
f49e315
Merge branch 'main' into refactor-splines
attack68 Jan 3, 2025
df80e88
Merge branch 'main' into refactor-splines
attack68 Jan 6, 2025
3e88975
Merge remote-tracking branch 'origin/main' into refactor-splines
attack68 Jan 13, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions rust/curves/curve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ pub trait CurveInterpolation {
// let timestamp = date.and_utc().timestamp();
index_left(&nodes.keys(), &date_timestamp, None)
}

/// Calibrate the interpolator to the Curve nodes if necessary
fn calibrate(&self, nodes: &NodesTimestamp) -> Result<(), PyErr> {
Ok(())
}
}

impl<T: CurveInterpolation, U: DateRoll> CurveDF<T, U> {
Expand Down
107 changes: 57 additions & 50 deletions rust/curves/interpolation/intp_log_cubic.rs
Original file line number Diff line number Diff line change
@@ -1,66 +1,72 @@
use crate::curves::interpolation::utils::log_linear_interp;
use crate::curves::nodes::NodesTimestamp;

Check warning on line 1 in rust/curves/interpolation/intp_log_cubic.rs

View workflow job for this annotation

GitHub Actions / build (3.13)

Diff in /home/runner/work/rateslib/rateslib/rust/curves/interpolation/intp_log_cubic.rs
use crate::curves::CurveInterpolation;
use crate::dual::DualsOrF64;
use bincode::{deserialize, serialize};
use crate::dual::{Number, ADOrder, NumberPPSpline, set_order_clone, Dual, Dual2};
use crate::splines::{PPSplineF64, PPSplineDual, PPSplineDual2};
use chrono::NaiveDateTime;
use pyo3::prelude::*;
use pyo3::types::{PyBytes, PyTuple};
use pyo3::{pyclass, pymethods, Bound, PyResult, Python};
use pyo3::{pyclass, pymethods};
use serde::{Deserialize, Serialize};
use std::cmp::PartialEq;

/// Define log-linear interpolation of nodes.
/// Define log-cubic interpolation of nodes.
#[pyclass(module = "rateslib.rs")]

Check warning on line 12 in rust/curves/interpolation/intp_log_cubic.rs

View workflow job for this annotation

GitHub Actions / build (3.13)

Diff in /home/runner/work/rateslib/rateslib/rust/curves/interpolation/intp_log_cubic.rs
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LogCubicInterpolator<T: NumberMapping> {
spline: T
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct LogCubicInterpolator {
spline: NumberPPSpline
}

#[pymethods]
impl<T> LogCubicInterpolator
where T: PartialOrd + Signed + Clone + Sum + Zero,
for<'a> &'a T: Sub<&'a T, Output = T>,
for<'a> &'a f64: Mul<&'a T, Output = T>,
{
impl LogCubicInterpolator {
#[new]
pub fn new(t: Vec<f64>, c: Option<Vec<T>>) -> Self {
let spline: PPSpline<T> = PPSpline.new(3_usize, t, c);
LogCubicInterpolator {
spline
pub fn new(t: Vec<f64>, ad: ADOrder, c: Option<Vec<Number>>) -> Self {

Check warning on line 21 in rust/curves/interpolation/intp_log_cubic.rs

View workflow job for this annotation

GitHub Actions / build (3.13)

Diff in /home/runner/work/rateslib/rateslib/rust/curves/interpolation/intp_log_cubic.rs
match (c, ad) {
(Some(v), ADOrder::Zero) => {
let c_: Vec<f64> = v.iter().map(|x| set_order_clone(&x, ADOrder::Zero, vec![])).map(f64::from).collect();
let spline = NumberPPSpline::F64(PPSplineF64::new(3, t, Some(c_)));
LogCubicInterpolator {spline}
}
(Some(v), ADOrder::One) => {
let c_: Vec<Dual> = v.iter().map(|x| set_order_clone(&x, ADOrder::One, vec![])).map(Dual::from).collect();
let spline = NumberPPSpline::Dual(PPSplineDual::new(3, t, Some(c_)));
LogCubicInterpolator {spline}
}
(Some(v), ADOrder::Two) => {
let c_: Vec<Dual2> = v.iter().map(|x| set_order_clone(&x, ADOrder::Zero, vec![])).map(Dual2::from).collect();
let spline = NumberPPSpline::Dual2(PPSplineDual2::new(3, t, Some(c_)));
LogCubicInterpolator {spline}
}
(None, ADOrder::Zero) => {LogCubicInterpolator {spline: NumberPPSpline::F64(PPSplineF64::new(3, t, None))}},
(None, ADOrder::One) => {LogCubicInterpolator {spline: NumberPPSpline::Dual(PPSplineDual::new(3, t, None))}},
(None, ADOrder::Two) => {LogCubicInterpolator {spline: NumberPPSpline::Dual2(PPSplineDual2::new(3, t, None))}},
}
}
//
// // Pickling
// pub fn __setstate__(&mut self, state: Bound<'_, PyBytes>) -> PyResult<()> {
// *self = deserialize(state.as_bytes()).unwrap();
// Ok(())
// }
// pub fn __getstate__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
// Ok(PyBytes::new_bound(py, &serialize(&self).unwrap()))
// }
// pub fn __getnewargs__<'py>(&self, py: Python<'py>) -> PyResult<(Vec<f64>, Option<Vec<T>>)> {
// Ok((self.t.clone(), ))
// }
}

// Pickling
pub fn __setstate__(&mut self, state: Bound<'_, PyBytes>) -> PyResult<()> {
*self = deserialize(state.as_bytes()).unwrap();
Ok(())
}
pub fn __getstate__<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
Ok(PyBytes::new_bound(py, &serialize(&self).unwrap()))
}
pub fn __getnewargs__<'py>(&self, py: Python<'py>) -> PyResult<(Vec<f64>, Option<Vec<T>>)> {
Ok((self.t.clone(), ))
impl CurveInterpolation for LogCubicInterpolator {
fn interpolated_value(&self, nodes: &NodesTimestamp, date: &NaiveDateTime) -> Number {
Number::F64(2.3)
}
}

impl CurveInterpolation for LogLinearInterpolator {
fn interpolated_value(&self, nodes: &NodesTimestamp, date: &NaiveDateTime) -> DualsOrF64 {
let x = date.and_utc().timestamp();
let index = self.node_index(nodes, x);
/// Calibrate the interpolator to the Curve nodes if necessary
fn calibrate(&self, nodes: &NodesTimestamp) -> Result<(), PyErr> {

Check warning on line 63 in rust/curves/interpolation/intp_log_cubic.rs

View workflow job for this annotation

GitHub Actions / build (3.13)

Diff in /home/runner/work/rateslib/rateslib/rust/curves/interpolation/intp_log_cubic.rs
// will call csolve on the spline with the appropriate data.
let t = self.spline.t().clone();
let t_min = t[0]; let t_max = t[t.len()-1];

macro_rules! interp {
($Variant: ident, $indexmap: expr) => {{
let (x1, y1) = $indexmap.get_index(index).unwrap();
let (x2, y2) = $indexmap.get_index(index + 1_usize).unwrap();
DualsOrF64::$Variant(log_linear_interp(*x1 as f64, y1, *x2 as f64, y2, x as f64))
}};
}
match nodes {
NodesTimestamp::F64(m) => interp!(F64, m),
NodesTimestamp::Dual(m) => interp!(Dual, m),
NodesTimestamp::Dual2(m) => interp!(Dual2, m),
}
let f = nodes.clone().iter().filter(|(k,v)| (k as f64) >= t_min && (k as f64) <= t_max);
Ok(())
}
}

Expand All @@ -81,11 +87,12 @@
}

#[test]
fn test_log_linear() {
fn test_log_cubic() {
let nts = nodes_timestamp_fixture();
let ll = LogLinearInterpolator::new();
let result = ll.interpolated_value(&nts, &ndt(2000, 7, 1));
// expected = exp(0 + (182 / 366) * (ln(0.99) - ln(1.0)) = 0.995015
assert_eq!(result, DualsOrF64::F64(0.9950147597711371));
let s = nts.get_index_as_f64(0).0;
let m = nts.get_index_as_f64(1).0;
let e = nts.get_index_as_f64(2).0;
let t = vec![s, s, s, s, m, e, e, e, e];
let ll = LogCubicInterpolator::new(t, ADOrder::Zero, None);
}
}
1 change: 1 addition & 0 deletions rust/curves/interpolation/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
pub(crate) mod interpolation_py;

pub(crate) mod intp_flat_backward;
pub(crate) mod intp_flat_forward;

Check warning on line 4 in rust/curves/interpolation/mod.rs

View workflow job for this annotation

GitHub Actions / build (3.13)

Diff in /home/runner/work/rateslib/rateslib/rust/curves/interpolation/mod.rs
pub(crate) mod intp_linear;
pub(crate) mod intp_linear_zero_rate;
pub(crate) mod intp_log_linear;
pub(crate) mod intp_log_cubic;
pub(crate) mod intp_null;

pub(crate) mod utils;
54 changes: 26 additions & 28 deletions rust/curves/nodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,6 @@
Dual2(IndexMap<i64, Dual2>),
}

impl NodesTimestamp {
pub fn first_key(&self) -> i64 {
match self {
NodesTimestamp::F64(m) => *m.first().unwrap().0,
NodesTimestamp::Dual(m) => *m.first().unwrap().0,
NodesTimestamp::Dual2(m) => *m.first().unwrap().0,
}
}
}

impl From<Nodes> for NodesTimestamp {
fn from(value: Nodes) -> Self {
match value {
Expand Down Expand Up @@ -76,6 +66,14 @@
// }
// }

pub fn first_key(&self) -> i64 {
match self {
NodesTimestamp::F64(m) => *m.first().unwrap().0,
NodesTimestamp::Dual(m) => *m.first().unwrap().0,
NodesTimestamp::Dual2(m) => *m.first().unwrap().0,
}
}

pub(crate) fn sort_keys(&mut self) {
match self {
NodesTimestamp::F64(m) => m.sort_keys(),
Expand All @@ -92,6 +90,24 @@
}
}

/// Refactors the `get_index` method of an IndexMap and type casts the return values.
pub(crate) fn get_index_as_f64(&self, index: usize) -> (f64, Number) {
match self {
NodesTimestamp::F64(m) => {

Check warning on line 96 in rust/curves/nodes.rs

View workflow job for this annotation

GitHub Actions / build (3.13)

Diff in /home/runner/work/rateslib/rateslib/rust/curves/nodes.rs
let (k, v) = m.get_index(index).unwrap();
(*k as f64, Number::F64(*v))
},
NodesTimestamp::Dual(m) => {
let (k, v) = m.get_index(index).unwrap();
(*k as f64, Number::Dual(v.clone()))
},

Check warning on line 103 in rust/curves/nodes.rs

View workflow job for this annotation

GitHub Actions / build (3.13)

Diff in /home/runner/work/rateslib/rateslib/rust/curves/nodes.rs
NodesTimestamp::Dual2(m) => {
let (k, v) = m.get_index(index).unwrap();
(*k as f64, Number::Dual2(v.clone()))
},

Check warning on line 107 in rust/curves/nodes.rs

View workflow job for this annotation

GitHub Actions / build (3.13)

Diff in /home/runner/work/rateslib/rateslib/rust/curves/nodes.rs
}
}

pub(crate) fn index_map(&self) -> IndexMap<NaiveDateTime, Number> {
macro_rules! create_map {
($map:ident, $Variant:ident) => {
Expand All @@ -111,21 +127,3 @@
}
}
}

// /// Refactors the `get_index` method of an IndexMap and type casts the return values.
// pub(crate) fn get_index_as_f64(&self, index: usize) -> (f64, Number) {
// match self {
// NodesTimestamp::F64(m) => {
// let (k, v) = m.get_index(index).unwrap();
// (*k as f64, Number::F64(*v))
// },
// NodesTimestamp::Dual(m) => {
// let (k, v) = m.get_index(index).unwrap();
// (*k as f64, Number::Dual(v.clone()))
// },
// NodesTimestamp::Dual2(m) => {
// let (k, v) = m.get_index(index).unwrap();
// (*k as f64, Number::Dual2(v.clone()))
// },
// }
// }
11 changes: 11 additions & 0 deletions rust/dual/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,17 @@ pub enum NumberPPSpline {
Dual2(PPSplineDual2),
}

impl NumberPPSpline {
/// Return a reference to the knot sequence of the inner pp-spline.
pub fn t(&self) -> &Vec<f64> {
match self {
NumberPPSpline::F64(s) => s.inner.t(),
NumberPPSpline::Dual(s) => s.inner.t(),
NumberPPSpline::Dual2(s) => s.inner.t(),
}
}
}

/// Generic trait indicating a function exists to map one [Number] to another.
///
/// An example of this trait is used by certain [PPSpline] indicating that an x-value as
Expand Down
37 changes: 20 additions & 17 deletions rust/splines/spline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,27 +398,30 @@
}
}
}

Check warning on line 401 in rust/splines/spline.rs

View workflow job for this annotation

GitHub Actions / build (3.13)

Diff in /home/runner/work/rateslib/rateslib/rust/splines/spline.rs
/// Definitive [f64] type variant of a [PPSpline].
#[pyclass(module = "rateslib.rs")]
#[derive(Clone, Deserialize, Serialize)]
pub struct PPSplineF64 {
pub(crate) inner: PPSpline<f64>,
}
macro_rules! define_specific_type_splines {
($name: ident, $type: ident) => {

#[doc = concat!("Definitive [", stringify!($type), "] type variant of a [PPSpline]")]
#[pyclass(module = "rateslib.rs")]
#[derive(Clone, Deserialize, Serialize)]
pub struct $name {
pub(crate) inner: PPSpline<$type>,
}

/// Definitive [Dual] type variant of a [PPSpline].
#[pyclass(module = "rateslib.rs")]
#[derive(Clone, Deserialize, Serialize)]
pub struct PPSplineDual {
pub(crate) inner: PPSpline<Dual>,
impl $name {
pub fn new(k: usize, t: Vec<f64>, c: Option<Vec<$type>>) -> Self {
Self {
inner: PPSpline::new(k, t, c),
}

Check warning on line 416 in rust/splines/spline.rs

View workflow job for this annotation

GitHub Actions / build (3.13)

Diff in /home/runner/work/rateslib/rateslib/rust/splines/spline.rs
}
}
}
}
define_specific_type_splines!(PPSplineF64, f64);
define_specific_type_splines!(PPSplineDual, Dual);
define_specific_type_splines!(PPSplineDual2, Dual2);

/// Definitive [Dual2] type variant of a [PPSpline].
#[pyclass(module = "rateslib.rs")]
#[derive(Clone, Deserialize, Serialize)]
pub struct PPSplineDual2 {
pub(crate) inner: PPSpline<Dual2>,
}

impl PartialEq for PPSplineF64 {
/// Equality of `PPSplineF64` if
Expand Down
2 changes: 1 addition & 1 deletion rust/splines/spline_py.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ macro_rules! create_interface {
impl $name {
#[new]
#[pyo3(signature = (k, t, c=None))]
fn new(k: usize, t: Vec<f64>, c: Option<Vec<$type>>) -> Self {
fn new_py(k: usize, t: Vec<f64>, c: Option<Vec<$type>>) -> Self {
Self {
inner: PPSpline::new(k, t, c),
}
Expand Down
Loading