Skip to main content

oa/data/
dataframe.rs

1//! Host columnar values adapted from `trade/include/oa/core/dataframe.h` and
2//! `trade/lib/oa/core/dataframe.cpp`. Rust ownership adaptation; checked lengths
3//! replace donor truncation. Slices borrow storage rather than copying it.
4
5use crate::{Error, Result};
6use std::ops::Range;
7
8/// Contiguous typed host column. Moving it into a frame does not copy its data.
9#[derive(Clone, Debug, PartialEq)]
10pub enum Series {
11	/// Exact signed integers, including Unix timestamps.
12	I64(Vec<i64>),
13	/// Single-precision numerical values.
14	F32(Vec<f32>),
15	/// Double-precision numerical values.
16	F64(Vec<f64>),
17}
18
19/// Borrowed contiguous column; independent of an Engine.
20#[derive(Clone, Copy, Debug)]
21pub enum SeriesView<'a> {
22	/// Signed integers.
23	I64(&'a [i64]),
24	/// Single-precision values.
25	F32(&'a [f32]),
26	/// Double-precision values.
27	F64(&'a [f64]),
28}
29
30/// Exclusively borrowed column storage for in-place edits without resizing.
31#[derive(Debug)]
32pub enum SeriesViewMut<'a> {
33	/// Signed integer storage.
34	I64(&'a mut [i64]),
35	/// Single-precision storage.
36	F32(&'a mut [f32]),
37	/// Double-precision storage.
38	F64(&'a mut [f64]),
39}
40
41impl Series {
42	/// Borrow the entire column without allocation.
43	pub fn view(&self) -> SeriesView<'_> {
44		match self {
45			Self::I64(v) => SeriesView::I64(v),
46			Self::F32(v) => SeriesView::F32(v),
47			Self::F64(v) => SeriesView::F64(v),
48		}
49	}
50
51	/// Exclusively borrow values for in-place edits without resizing the column.
52	pub fn view_mut(&mut self) -> SeriesViewMut<'_> {
53		match self {
54			Self::I64(v) => SeriesViewMut::I64(v),
55			Self::F32(v) => SeriesViewMut::F32(v),
56			Self::F64(v) => SeriesViewMut::F64(v),
57		}
58	}
59
60	/// Number of rows.
61	pub fn len(&self) -> usize {
62		self.view().len()
63	}
64
65	/// Whether this column has no rows.
66	pub fn is_empty(&self) -> bool {
67		self.len() == 0
68	}
69}
70
71impl<'a> SeriesView<'a> {
72	/// Number of rows.
73	pub fn len(self) -> usize {
74		match self {
75			Self::I64(v) => v.len(),
76			Self::F32(v) => v.len(),
77			Self::F64(v) => v.len(),
78		}
79	}
80
81	/// Whether the view is empty.
82	pub fn is_empty(self) -> bool {
83		self.len() == 0
84	}
85
86	/// Borrow a checked row range. No allocation or copy.
87	///
88	/// # Errors
89	/// Returns an error for reversed or out-of-bounds ranges.
90	pub fn slice(self, range: Range<usize>) -> Result<Self> {
91		if range.start > range.end || range.end > self.len() {
92			return Err(Error::out_of_range(
93				"series row range is outside the column",
94			));
95		}
96		Ok(match self {
97			Self::I64(v) => Self::I64(&v[range]),
98			Self::F32(v) => Self::F32(&v[range]),
99			Self::F64(v) => Self::F64(&v[range]),
100		})
101	}
102
103	pub(super) fn float_at(self, row: usize) -> Option<f64> {
104		match self {
105			Self::I64(_) => None,
106			Self::F32(v) => v.get(row).map(|&v| f64::from(v)),
107			Self::F64(v) => v.get(row).copied(),
108		}
109	}
110}
111
112/// Ordered named host columns with one checked row count.
113///
114/// ```
115/// let mut frame = oa::DataFrame::new();
116/// frame.set_column("timestamp", oa::Series::I64(vec![0, 1]))?;
117/// frame.set_column("close", oa::Series::F64(vec![10.0, 11.0]))?;
118/// let last = frame.slice(1..2)?;
119/// assert_eq!(last.len(), 1);
120/// # Ok::<(), oa::Error>(())
121/// ```
122///
123/// Unlike the donor, missing columns and unequal lengths are errors. Whole-column replacement
124/// is transactional; exclusive mutable slices cannot invalidate lengths.
125#[derive(Clone, Debug, Default)]
126pub struct DataFrame {
127	columns: Vec<(String, Series)>,
128	rows: usize,
129}
130
131impl DataFrame {
132	/// Create an empty frame.
133	pub fn new() -> Self {
134		Self::default()
135	}
136
137	/// Insert or replace a column, moving its buffer without copying.
138	///
139	/// # Errors
140	/// Rejects empty names and lengths differing from existing columns.
141	pub fn set_column(&mut self, name: impl Into<String>, series: Series) -> Result<()> {
142		let name = name.into();
143		if name.is_empty() || (!self.columns.is_empty() && series.len() != self.rows) {
144			return Err(Error::invalid_argument(
145				"frame columns require a name and equal row counts",
146			));
147		}
148		self.rows = series.len();
149		if let Some((_, column)) = self.columns.iter_mut().find(|(n, _)| *n == name) {
150			*column = series;
151		} else {
152			self.columns.push((name, series));
153		}
154		Ok(())
155	}
156
157	/// Borrow a named column.
158	///
159	/// # Errors
160	/// Returns an error when the column does not exist.
161	pub fn column(&self, name: &str) -> Result<SeriesView<'_>> {
162		self
163			.columns
164			.iter()
165			.find(|(n, _)| n == name)
166			.map(|(_, c)| c.view())
167			.ok_or_else(|| Error::invalid_argument(format!("missing frame column: {name}")))
168	}
169
170	/// Exclusively borrow column values for in-place edits. Length cannot change.
171	/// Existing immutable frame/OHLCV views prevent this borrow in safe Rust.
172	///
173	/// # Errors
174	/// Returns an error when the column does not exist.
175	pub fn column_mut(&mut self, name: &str) -> Result<SeriesViewMut<'_>> {
176		self
177			.columns
178			.iter_mut()
179			.find(|(n, _)| n == name)
180			.map(|(_, c)| c.view_mut())
181			.ok_or_else(|| Error::invalid_argument(format!("missing frame column: {name}")))
182	}
183
184	/// Column names in insertion order.
185	pub fn column_names(&self) -> impl ExactSizeIterator<Item = &str> {
186		self.columns.iter().map(|(n, _)| n.as_str())
187	}
188
189	/// Number of rows.
190	pub fn len(&self) -> usize {
191		self.rows
192	}
193
194	/// Whether the frame has no rows.
195	pub fn is_empty(&self) -> bool {
196		self.rows == 0
197	}
198}
199
200/// Borrowed row interval over a frame. Columns retain their original buffers.
201#[derive(Clone, Copy, Debug)]
202pub struct DataFrameView<'a> {
203	frame: &'a DataFrame,
204	start: usize,
205	end: usize,
206}
207
208impl DataFrame {
209	/// Borrow a checked row interval without allocating columns or metadata.
210	///
211	/// # Errors
212	/// Rejects reversed or out-of-bounds ranges.
213	pub fn slice(&self, range: Range<usize>) -> Result<DataFrameView<'_>> {
214		if range.start > range.end || range.end > self.rows {
215			return Err(Error::out_of_range("frame row range is outside the source"));
216		}
217		Ok(DataFrameView {
218			frame: self,
219			start: range.start,
220			end: range.end,
221		})
222	}
223}
224
225impl<'a> DataFrameView<'a> {
226	/// Number of rows in this view.
227	pub fn len(self) -> usize {
228		self.end - self.start
229	}
230
231	/// Whether this view is empty.
232	pub fn is_empty(self) -> bool {
233		self.start == self.end
234	}
235
236	/// Borrow a column restricted to the view's rows.
237	///
238	/// # Errors
239	/// Returns an error when the column does not exist.
240	pub fn column(self, name: &str) -> Result<SeriesView<'a>> {
241		self.frame.column(name)?.slice(self.start..self.end)
242	}
243}