use pyo3::prelude::*;
use pyo3::types::{IntoPyDict, PyDict};
use pyo3::{create_exception, wrap_pyfunction};
use numpy::{PyArray1, PyReadonlyArray1};
use pyo3_stub_gen::derive::{gen_stub_pyclass, gen_stub_pyfunction, gen_stub_pymethods};
use pyo3_stub_gen::define_stub_info_gatherer;
use std::collections::HashMap;
use crate::api::mdf::Mdf;
use crate::writer::{MdfWriter, ColumnData};
use crate::index::MdfIndex;
use crate::blocks::common::DataType;
use crate::parsing::decoder::DecodedValue;
use crate::error::MdfError;
use crate::block_layout::{BlockInfo, FileLayout, GapInfo, LinkInfo};
use crate::signal::Signal;
use crate::types::{ChannelInfo, ConversionInfo, GroupInfo, ReadOptions, TimeRange};
create_exception!(mf4_rs, MdfException, pyo3::exceptions::PyException);
create_exception!(mf4_rs, ChannelNotFoundError, MdfException);
impl From<MdfError> for PyErr {
fn from(err: MdfError) -> PyErr {
match err {
MdfError::ChannelNotFound { .. } => ChannelNotFoundError::new_err(err.to_string()),
other => MdfException::new_err(other.to_string()),
}
}
}
fn decoded_value_to_pyobject(dv: DecodedValue, py: Python) -> PyObject {
match dv {
DecodedValue::Float(v) => v.to_object(py),
DecodedValue::UnsignedInteger(v) => v.to_object(py),
DecodedValue::SignedInteger(v) => v.to_object(py),
DecodedValue::String(v) => v.to_object(py),
DecodedValue::ByteArray(v) | DecodedValue::MimeSample(v) | DecodedValue::MimeStream(v) => {
pyo3::types::PyBytes::new_bound(py, &v).into()
}
DecodedValue::Unknown => py.None(),
}
}
fn repr_opt(value: &Option<String>) -> String {
match value {
Some(v) => format!("'{}'", v),
None => "None".to_string(),
}
}
#[gen_stub_pyclass]
#[pyclass(name = "ChannelInfo")]
#[derive(Clone)]
pub struct PyChannelInfo {
#[pyo3(get)]
pub name: Option<String>,
#[pyo3(get)]
pub unit: Option<String>,
#[pyo3(get)]
pub comment: Option<String>,
#[pyo3(get)]
pub data_type: String,
#[pyo3(get)]
pub bit_count: u32,
#[pyo3(get)]
pub is_master: bool,
#[pyo3(get)]
pub is_vlsd: bool,
#[pyo3(get)]
pub has_conversion: bool,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyChannelInfo {
fn __repr__(&self) -> String {
format!(
"ChannelInfo(name={}, unit={}, data_type='{}', bit_count={}, is_master={})",
repr_opt(&self.name),
repr_opt(&self.unit),
self.data_type,
self.bit_count,
if self.is_master { "True" } else { "False" }
)
}
}
impl From<ChannelInfo> for PyChannelInfo {
fn from(c: ChannelInfo) -> Self {
PyChannelInfo {
name: c.name,
unit: c.unit,
comment: c.comment,
data_type: c.data_type,
bit_count: c.bit_count,
is_master: c.is_master,
is_vlsd: c.is_vlsd,
has_conversion: c.has_conversion,
}
}
}
#[gen_stub_pyclass]
#[pyclass(name = "GroupInfo")]
#[derive(Clone)]
pub struct PyGroupInfo {
#[pyo3(get)]
pub name: Option<String>,
#[pyo3(get)]
pub comment: Option<String>,
#[pyo3(get)]
pub record_count: u64,
#[pyo3(get)]
pub channel_names: Vec<String>,
#[pyo3(get)]
pub master_channel: Option<String>,
#[pyo3(get)]
pub channels: Vec<PyChannelInfo>,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyGroupInfo {
fn __repr__(&self) -> String {
format!(
"GroupInfo(name={}, record_count={}, channel_names={:?})",
repr_opt(&self.name),
self.record_count,
self.channel_names
)
}
}
impl From<GroupInfo> for PyGroupInfo {
fn from(g: GroupInfo) -> Self {
PyGroupInfo {
name: g.name,
comment: g.comment,
record_count: g.record_count,
channel_names: g.channel_names,
master_channel: g.master_channel,
channels: g.channels.into_iter().map(Into::into).collect(),
}
}
}
#[gen_stub_pyclass]
#[pyclass(name = "Signal")]
pub struct PySignal {
#[pyo3(get)]
name: String,
#[pyo3(get)]
unit: Option<String>,
#[pyo3(get)]
timestamps: PyObject,
#[pyo3(get)]
values: PyObject,
start_time_ns: Option<u64>,
}
#[gen_stub_pymethods]
#[pymethods]
impl PySignal {
fn __len__(&self, py: Python) -> PyResult<usize> {
self.values.bind(py).len()
}
fn __repr__(&self, py: Python) -> PyResult<String> {
Ok(format!(
"Signal(name='{}', unit={}, samples={})",
self.name,
repr_opt(&self.unit),
self.values.bind(py).len()?
))
}
fn to_series(&self, py: Python) -> PyResult<PyObject> {
let pd = py.import_bound("pandas").map_err(|_| {
MdfException::new_err("pandas is not installed; install it to use Signal.to_series()")
})?;
let timestamps: PyReadonlyArray1<f64> = self.timestamps.bind(py).extract()?;
let timestamps = timestamps.as_slice()?;
let series_class = pd.getattr("Series")?;
let series = if timestamps.is_empty() {
series_class.call1((self.values.clone_ref(py),))?
} else {
let dt_index = self.start_time_ns.and_then(|start_ns| {
let start_i64 = i64::try_from(start_ns).ok()?;
let mut ns: Vec<i64> = Vec::with_capacity(timestamps.len());
for &t in timestamps {
let rel = t * 1e9;
if !rel.is_finite() || rel.abs() >= i64::MAX as f64 {
return None;
}
ns.push(start_i64.checked_add(rel.round() as i64)?);
}
let arr = PyArray1::from_vec_bound(py, ns);
arr.call_method1("view", ("datetime64[ns]",)).ok().map(|a| a.to_object(py))
});
let index = dt_index.unwrap_or_else(|| self.timestamps.clone_ref(py));
series_class.call(
(self.values.clone_ref(py),),
Some(&[("index", index)].into_py_dict_bound(py)),
)?
};
series.setattr("name", &self.name)?;
Ok(series.into())
}
}
impl PySignal {
fn new(py: Python, signal: Signal, start_time_ns: Option<u64>) -> PyResult<Self> {
let mut numeric: Vec<f64> = Vec::with_capacity(signal.values.len());
let mut all_numeric = true;
for v in &signal.values {
match v {
None => numeric.push(f64::NAN),
Some(DecodedValue::Float(f)) => numeric.push(*f),
Some(DecodedValue::UnsignedInteger(u)) => numeric.push(*u as f64),
Some(DecodedValue::SignedInteger(i)) => numeric.push(*i as f64),
_ => {
all_numeric = false;
break;
}
}
}
let values: PyObject = if all_numeric {
PyArray1::from_vec_bound(py, numeric).into()
} else {
let list: Vec<PyObject> = signal
.values
.into_iter()
.map(|o| o.map(|dv| decoded_value_to_pyobject(dv, py)).unwrap_or_else(|| py.None()))
.collect();
let np = py.import_bound("numpy")?;
let arr = np.call_method1("empty", (list.len(), "object"))?;
arr.set_item(pyo3::types::PySlice::full_bound(py), list)?;
arr.into()
};
Ok(PySignal {
name: signal.name,
unit: signal.unit,
timestamps: PyArray1::from_vec_bound(py, signal.timestamps).into(),
values,
start_time_ns,
})
}
}
fn conversion_to_py(py: Python, info: &ConversionInfo) -> PyResult<PyObject> {
let d = PyDict::new_bound(py);
d.set_item("type", &info.conversion_type)?;
d.set_item("values", info.values.clone())?;
d.set_item("precision", info.precision)?;
d.set_item("flags", info.flags)?;
if let Some([lo, hi]) = info.physical_range {
d.set_item("physical_range", (lo, hi))?;
}
if let Some(formula) = &info.formula {
d.set_item("formula", formula)?;
}
if !info.texts.is_empty() {
let texts = PyDict::new_bound(py);
for (k, v) in &info.texts {
texts.set_item(k, v)?;
}
d.set_item("texts", texts)?;
}
if !info.refs.is_empty() {
let refs = PyDict::new_bound(py);
for (k, v) in &info.refs {
refs.set_item(k, conversion_to_py(py, v)?)?;
}
d.set_item("refs", refs)?;
}
if let Some(default) = &info.default {
d.set_item("default", conversion_to_py(py, default)?)?;
}
Ok(d.into())
}
fn optional_conversion_to_py(py: Python, info: Option<ConversionInfo>) -> PyResult<PyObject> {
match info {
Some(info) => conversion_to_py(py, &info),
None => Ok(py.None()),
}
}
fn time_range_to_py(range: Option<TimeRange>) -> Option<(f64, f64)> {
range.map(|r| (r.start, r.end))
}
fn parse_lookup_key(key: &Bound<'_, PyAny>) -> PyResult<(String, Option<String>)> {
if let Ok((name, group)) = key.extract::<(String, String)>() {
Ok((name, Some(group)))
} else if let Ok(name) = key.extract::<String>() {
Ok((name, None))
} else {
Err(MdfException::new_err(
"channel key must be a name string or a (name, group) tuple",
))
}
}
#[gen_stub_pyclass]
#[pyclass(name = "Mdf")]
pub struct PyMDF {
mdf: Box<Mdf>,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyMDF {
#[staticmethod]
fn from_file(path: &str) -> PyResult<Self> {
Ok(PyMDF { mdf: Box::new(Mdf::from_file(path)?) })
}
#[staticmethod]
fn from_bytes(data: &Bound<'_, pyo3::types::PyBytes>) -> PyResult<Self> {
Ok(PyMDF { mdf: Box::new(Mdf::from_bytes(data.as_bytes().to_vec())?) })
}
#[staticmethod]
fn from_url(py: Python, url: &str) -> PyResult<Self> {
let mdf = py.allow_threads(|| Mdf::from_url(url))?;
Ok(PyMDF { mdf: Box::new(mdf) })
}
#[getter]
fn groups(&self) -> PyResult<Vec<PyGroupInfo>> {
Ok(self.mdf.groups()?.into_iter().map(Into::into).collect())
}
#[getter]
fn channel_names(&self) -> PyResult<Vec<String>> {
Ok(self.mdf.channel_names()?)
}
#[getter]
fn start_time_ns(&self) -> Option<u64> {
self.mdf.start_time_ns()
}
fn group(&self, name: &str) -> PyResult<Option<PyGroupInfo>> {
Ok(self.mdf.group(name)?.map(Into::into))
}
fn channel(&self, name: &str, group: Option<&str>) -> PyResult<Option<PyChannelInfo>> {
Ok(self.mdf.channel(name, group)?.map(Into::into))
}
fn read(
&self,
py: Python,
name: &str,
group: Option<&str>,
start_time: Option<f64>,
end_time: Option<f64>,
start_record: Option<u64>,
record_count: Option<u64>,
raw: Option<bool>,
) -> PyResult<PySignal> {
let options = ReadOptions::from_parts(group, start_time, end_time, start_record, record_count)
.raw(raw.unwrap_or(false));
let signal = py.allow_threads(|| self.mdf.read(name, &options))?;
PySignal::new(py, signal, self.mdf.start_time_ns())
}
fn read_many(
&self,
py: Python,
names: Vec<String>,
group: Option<&str>,
start_time: Option<f64>,
end_time: Option<f64>,
start_record: Option<u64>,
record_count: Option<u64>,
raw: Option<bool>,
) -> PyResult<Vec<PySignal>> {
let options = ReadOptions::from_parts(group, start_time, end_time, start_record, record_count)
.raw(raw.unwrap_or(false));
let signals = py.allow_threads(|| self.mdf.read_many(&names, &options))?;
let start = self.mdf.start_time_ns();
signals.into_iter().map(|signal| PySignal::new(py, signal, start)).collect()
}
fn values(
&self,
py: Python,
name: &str,
group: Option<&str>,
start_time: Option<f64>,
end_time: Option<f64>,
start_record: Option<u64>,
record_count: Option<u64>,
raw: Option<bool>,
) -> PyResult<PyObject> {
let options = ReadOptions::from_parts(group, start_time, end_time, start_record, record_count)
.raw(raw.unwrap_or(false));
let values = py.allow_threads(|| self.mdf.values(name, &options))?;
Ok(PyArray1::from_vec_bound(py, values).into())
}
fn __getitem__(&self, py: Python, key: &Bound<'_, PyAny>) -> PyResult<PySignal> {
let (name, group) = parse_lookup_key(key)?;
self.read(py, &name, group.as_deref(), None, None, None, None, None)
}
fn time_range(&self, name: &str, group: Option<&str>) -> PyResult<Option<(f64, f64)>> {
Ok(time_range_to_py(self.mdf.time_range(name, group)?))
}
fn conversion(&self, py: Python, name: &str, group: Option<&str>) -> PyResult<PyObject> {
optional_conversion_to_py(py, self.mdf.conversion(name, group)?)
}
fn file_layout(&self) -> PyResult<PyFileLayout> {
Ok(PyFileLayout { inner: self.mdf.file_layout()? })
}
}
#[gen_stub_pyclass]
#[pyclass(name = "MdfIndex")]
pub struct PyMdfIndex {
index: MdfIndex,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyMdfIndex {
#[staticmethod]
fn from_file(path: &str) -> PyResult<Self> {
Ok(PyMdfIndex { index: MdfIndex::from_file(path)? })
}
#[staticmethod]
fn from_bytes(data: &Bound<'_, pyo3::types::PyBytes>) -> PyResult<Self> {
Ok(PyMdfIndex { index: MdfIndex::from_bytes(data.as_bytes().to_vec())? })
}
#[staticmethod]
fn from_url(py: Python, url: &str, chunk_size: Option<u64>) -> PyResult<Self> {
let chunk = chunk_size.unwrap_or(1 << 20);
let index = py.allow_threads(|| MdfIndex::from_url_with_chunk_size(url, chunk))?;
Ok(PyMdfIndex { index })
}
#[staticmethod]
fn from_json(json: &str) -> PyResult<Self> {
Ok(PyMdfIndex { index: MdfIndex::from_json(json)? })
}
#[staticmethod]
fn load(path: &str) -> PyResult<Self> {
Ok(PyMdfIndex { index: MdfIndex::load(path)? })
}
fn to_json(&self) -> PyResult<String> {
Ok(self.index.to_json()?)
}
fn save(&self, path: &str) -> PyResult<()> {
Ok(self.index.save(path)?)
}
fn validate(&self) -> PyResult<()> {
Ok(self.index.validate()?)
}
#[getter]
fn groups(&self) -> PyResult<Vec<PyGroupInfo>> {
Ok(self.index.groups()?.into_iter().map(Into::into).collect())
}
#[getter]
fn channel_names(&self) -> PyResult<Vec<String>> {
Ok(self.index.channel_names()?)
}
#[getter]
fn start_time_ns(&self) -> Option<u64> {
self.index.start_time_ns()
}
#[getter]
fn file_size(&self) -> u64 {
self.index.file_size()
}
#[getter]
fn source(&self) -> Option<String> {
self.index.source().map(|s| s.as_str().to_string())
}
fn set_source(&mut self, source: Option<&str>) {
match source {
Some(source) => self.index.set_source(source),
None => self.index.clear_source(),
}
}
fn group(&self, name: &str) -> PyResult<Option<PyGroupInfo>> {
Ok(self.index.group(name)?.map(Into::into))
}
fn channel(&self, name: &str, group: Option<&str>) -> PyResult<Option<PyChannelInfo>> {
Ok(self.index.channel(name, group)?.map(Into::into))
}
fn read(
&self,
py: Python,
name: &str,
group: Option<&str>,
start_time: Option<f64>,
end_time: Option<f64>,
start_record: Option<u64>,
record_count: Option<u64>,
raw: Option<bool>,
) -> PyResult<PySignal> {
let options = ReadOptions::from_parts(group, start_time, end_time, start_record, record_count)
.raw(raw.unwrap_or(false));
let signal = py.allow_threads(|| self.index.read(name, &options))?;
PySignal::new(py, signal, self.index.start_time_ns())
}
fn read_many(
&self,
py: Python,
names: Vec<String>,
group: Option<&str>,
start_time: Option<f64>,
end_time: Option<f64>,
start_record: Option<u64>,
record_count: Option<u64>,
raw: Option<bool>,
) -> PyResult<Vec<PySignal>> {
let options = ReadOptions::from_parts(group, start_time, end_time, start_record, record_count)
.raw(raw.unwrap_or(false));
let signals = py.allow_threads(|| self.index.read_many(&names, &options))?;
let start = self.index.start_time_ns();
signals.into_iter().map(|signal| PySignal::new(py, signal, start)).collect()
}
fn values(
&self,
py: Python,
name: &str,
group: Option<&str>,
start_time: Option<f64>,
end_time: Option<f64>,
start_record: Option<u64>,
record_count: Option<u64>,
raw: Option<bool>,
) -> PyResult<PyObject> {
let options = ReadOptions::from_parts(group, start_time, end_time, start_record, record_count)
.raw(raw.unwrap_or(false));
let values = py.allow_threads(|| self.index.values(name, &options))?;
Ok(PyArray1::from_vec_bound(py, values).into())
}
fn __getitem__(&self, py: Python, key: &Bound<'_, PyAny>) -> PyResult<PySignal> {
let (name, group) = parse_lookup_key(key)?;
self.read(py, &name, group.as_deref(), None, None, None, None, None)
}
fn time_range(&self, py: Python, name: &str, group: Option<&str>) -> PyResult<Option<(f64, f64)>> {
let range = py.allow_threads(|| self.index.time_range(name, group))?;
Ok(time_range_to_py(range))
}
fn conversion(&self, py: Python, name: &str, group: Option<&str>) -> PyResult<PyObject> {
let info = py.allow_threads(|| self.index.conversion(name, group))?;
optional_conversion_to_py(py, info)
}
fn byte_ranges(&self, name: &str, group: Option<&str>) -> PyResult<Vec<(u64, u64)>> {
Ok(self.index.byte_ranges(name, group)?)
}
fn byte_ranges_for_records(
&self,
name: &str,
start_record: u64,
record_count: u64,
group: Option<&str>,
) -> PyResult<Vec<(u64, u64)>> {
Ok(self.index.byte_ranges_for_records(name, start_record, record_count, group)?)
}
}
#[gen_stub_pyclass]
#[pyclass(unsendable, name = "MdfWriter")]
pub struct PyMdfWriter {
writer: Option<MdfWriter>,
record_types: HashMap<String, Vec<DataType>>,
}
impl PyMdfWriter {
fn writer(&mut self) -> PyResult<&mut MdfWriter> {
self.writer
.as_mut()
.ok_or_else(|| MdfException::new_err("Writer has been finalized"))
}
}
fn record_value(value: &Bound<'_, PyAny>, data_type: &DataType, index: usize) -> PyResult<DecodedValue> {
use crate::writer::mdf_writer::simple::{record_value, PlainValue};
use pyo3::types::{PyBool, PyByteArray, PyBytes, PyFloat, PyString};
let (text, byte_array);
let is_numpy_bool = || {
let ty = value.get_type();
let attr = |name: &str| ty.getattr(name).and_then(|v| v.extract::<String>()).unwrap_or_default();
attr("__module__") == "numpy" && attr("__name__").starts_with("bool")
};
let plain = if value.is_instance_of::<PyBool>() || is_numpy_bool() {
PlainValue::Bool
} else if value.is_instance_of::<PyFloat>() {
PlainValue::Float(value.extract()?)
} else if let Ok(s) = value.downcast::<PyString>() {
text = s.to_string();
PlainValue::Text(&text)
} else if let Ok(b) = value.downcast::<PyBytes>() {
PlainValue::Bytes(b.as_bytes())
} else if let Ok(b) = value.downcast::<PyByteArray>() {
byte_array = b.to_vec();
PlainValue::Bytes(&byte_array)
} else if let Ok(i) = value.extract::<i128>() {
PlainValue::Int(i)
} else if let Ok(f) = value.extract::<f64>() {
PlainValue::Float(f)
} else {
PlainValue::Other
};
Ok(record_value(plain, data_type, index)?)
}
#[gen_stub_pymethods]
#[pymethods]
impl PyMdfWriter {
#[new]
fn new(path: &str) -> PyResult<Self> {
Ok(PyMdfWriter { writer: Some(MdfWriter::new(path)?), record_types: HashMap::new() })
}
fn init_mdf_file(&mut self) -> PyResult<()> {
self.writer()?.init_mdf_file()?;
Ok(())
}
fn set_start_time(&mut self, abs_time_ns: u64) -> PyResult<()> {
Ok(self.writer()?.set_start_time(abs_time_ns)?)
}
fn add_channel_group(&mut self, name: Option<&str>) -> PyResult<String> {
Ok(self.writer()?.add_channel_group(name)?)
}
fn set_channel_group_comment(&mut self, group_id: &str, comment: &str) -> PyResult<()> {
Ok(self.writer()?.set_channel_group_comment(group_id, comment)?)
}
fn add_channel(&mut self, group_id: &str, name: &str, data_type: &str) -> PyResult<String> {
let data_type = DataType::from_name(data_type)?;
Ok(self.writer()?.add_channel(group_id, name, data_type)?)
}
fn add_time_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
Ok(self.writer()?.add_time_channel(group_id, name)?)
}
fn add_float_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
Ok(self.writer()?.add_float_channel(group_id, name)?)
}
fn add_float32_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
Ok(self.writer()?.add_float32_channel(group_id, name)?)
}
fn add_int_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
Ok(self.writer()?.add_int_channel(group_id, name)?)
}
fn add_sint_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
Ok(self.writer()?.add_sint_channel(group_id, name)?)
}
fn add_string_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
Ok(self.writer()?.add_string_channel(group_id, name)?)
}
fn set_time_channel(&mut self, channel_id: &str) -> PyResult<()> {
Ok(self.writer()?.set_time_channel(channel_id)?)
}
fn add_linear_conversion(&mut self, channel_id: &str, offset: f64, factor: f64) -> PyResult<()> {
Ok(self.writer()?.add_linear_conversion(channel_id, offset, factor)?)
}
fn add_value_to_text_conversion(
&mut self,
channel_id: &str,
mapping: Vec<(i64, String)>,
default_text: &str,
) -> PyResult<()> {
let pairs: Vec<(i64, &str)> = mapping.iter().map(|(v, t)| (*v, t.as_str())).collect();
Ok(self.writer()?.add_value_to_text_conversion(channel_id, &pairs, default_text)?)
}
fn start_data_block(&mut self, group_id: &str) -> PyResult<()> {
let types = self.writer()?.channel_data_types(group_id)?;
self.writer()?.start_data_block(group_id)?;
self.record_types.insert(group_id.to_string(), types);
Ok(())
}
fn write_record(&mut self, group_id: &str, values: Vec<Bound<'_, PyAny>>) -> PyResult<()> {
let types = self
.record_types
.get(group_id)
.ok_or_else(|| MdfException::new_err(format!("no open data block for group '{group_id}'")))?;
if values.len() != types.len() {
return Err(MdfException::new_err(format!(
"expected {} values for this group, got {}",
types.len(),
values.len()
)));
}
let record = values
.iter()
.zip(types)
.enumerate()
.map(|(i, (value, data_type))| record_value(value, data_type, i))
.collect::<PyResult<Vec<_>>>()?;
Ok(self.writer()?.write_record(group_id, &record)?)
}
fn write_columns(&mut self, group_id: &str, columns: Vec<Bound<'_, PyAny>>) -> PyResult<()> {
enum OwnedArray<'py> {
F64(PyReadonlyArray1<'py, f64>),
F32(PyReadonlyArray1<'py, f32>),
U64(PyReadonlyArray1<'py, u64>),
I64(PyReadonlyArray1<'py, i64>),
}
let mut owned = Vec::with_capacity(columns.len());
for (i, col) in columns.iter().enumerate() {
owned.push(if let Ok(a) = col.extract::<PyReadonlyArray1<f64>>() {
OwnedArray::F64(a)
} else if let Ok(a) = col.extract::<PyReadonlyArray1<f32>>() {
OwnedArray::F32(a)
} else if let Ok(a) = col.extract::<PyReadonlyArray1<u64>>() {
OwnedArray::U64(a)
} else if let Ok(a) = col.extract::<PyReadonlyArray1<i64>>() {
OwnedArray::I64(a)
} else {
return Err(MdfException::new_err(format!(
"column {i} must be a 1-D numpy array of dtype float64, float32, uint64 or int64"
)));
});
}
let contiguous = |e: numpy::NotContiguousError| MdfException::new_err(format!("Array not contiguous: {e}"));
let column_data = owned
.iter()
.map(|arr| match arr {
OwnedArray::F64(a) => a.as_slice().map(ColumnData::F64).map_err(contiguous),
OwnedArray::F32(a) => a.as_slice().map(ColumnData::F32).map_err(contiguous),
OwnedArray::U64(a) => a.as_slice().map(ColumnData::U64).map_err(contiguous),
OwnedArray::I64(a) => a.as_slice().map(ColumnData::I64).map_err(contiguous),
})
.collect::<PyResult<Vec<_>>>()?;
Ok(self.writer()?.write_columns(group_id, &column_data)?)
}
fn finish_data_block(&mut self, group_id: &str) -> PyResult<()> {
self.record_types.remove(group_id);
Ok(self.writer()?.finish_data_block(group_id)?)
}
fn finalize(&mut self) -> PyResult<()> {
match self.writer.take() {
Some(writer) => Ok(writer.finalize()?),
None => Err(MdfException::new_err("Writer already finalized")),
}
}
}
#[gen_stub_pyclass]
#[pyclass(name = "LinkInfo")]
#[derive(Clone)]
pub struct PyLinkInfo {
#[pyo3(get)]
pub name: String,
#[pyo3(get)]
pub target: u64,
#[pyo3(get)]
pub target_type: Option<String>,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyLinkInfo {
fn __repr__(&self) -> String {
if self.target == 0 {
format!("Link({} -> null)", self.name)
} else {
format!(
"Link({} -> 0x{:010x} [{}])",
self.name,
self.target,
self.target_type.as_deref().unwrap_or("?")
)
}
}
}
impl From<LinkInfo> for PyLinkInfo {
fn from(l: LinkInfo) -> Self {
PyLinkInfo {
name: l.name,
target: l.target,
target_type: l.target_type,
}
}
}
#[gen_stub_pyclass]
#[pyclass(name = "BlockInfo")]
#[derive(Clone)]
pub struct PyBlockInfo {
#[pyo3(get)]
pub offset: u64,
#[pyo3(get)]
pub end_offset: u64,
#[pyo3(get)]
pub size: u64,
#[pyo3(get)]
pub block_type: String,
#[pyo3(get)]
pub description: String,
#[pyo3(get)]
pub links: Vec<PyLinkInfo>,
#[pyo3(get)]
pub extra: Option<String>,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyBlockInfo {
fn __repr__(&self) -> String {
format!(
"Block({} @ 0x{:010x}..0x{:010x}, size={}, {})",
self.block_type, self.offset, self.end_offset, self.size, self.description
)
}
}
impl From<BlockInfo> for PyBlockInfo {
fn from(b: BlockInfo) -> Self {
PyBlockInfo {
offset: b.offset,
end_offset: b.end_offset,
size: b.size,
block_type: b.block_type,
description: b.description,
links: b.links.into_iter().map(Into::into).collect(),
extra: b.extra,
}
}
}
#[gen_stub_pyclass]
#[pyclass(name = "GapInfo")]
#[derive(Clone)]
pub struct PyGapInfo {
#[pyo3(get)]
pub start: u64,
#[pyo3(get)]
pub end: u64,
#[pyo3(get)]
pub size: u64,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyGapInfo {
fn __repr__(&self) -> String {
format!(
"Gap(0x{:010x}..0x{:010x}, size={})",
self.start, self.end, self.size
)
}
}
impl From<GapInfo> for PyGapInfo {
fn from(g: GapInfo) -> Self {
PyGapInfo {
start: g.start,
end: g.end,
size: g.size,
}
}
}
#[gen_stub_pyclass]
#[pyclass(name = "FileLayout")]
pub struct PyFileLayout {
pub(crate) inner: FileLayout,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyFileLayout {
#[staticmethod]
fn from_file(path: &str) -> PyResult<Self> {
let inner = FileLayout::from_file(path)?;
Ok(PyFileLayout { inner })
}
#[getter]
fn file_size(&self) -> u64 {
self.inner.file_size
}
#[getter]
fn blocks(&self) -> Vec<PyBlockInfo> {
self.inner.blocks.iter().cloned().map(Into::into).collect()
}
#[getter]
fn gaps(&self) -> Vec<PyGapInfo> {
self.inner.gaps.iter().cloned().map(Into::into).collect()
}
fn to_text(&self) -> String {
self.inner.to_text()
}
fn to_tree(&self) -> String {
self.inner.to_tree()
}
fn to_json(&self) -> PyResult<String> {
Ok(self.inner.to_json()?)
}
fn write_text_to_file(&self, path: &str) -> PyResult<()> {
self.inner.write_text_to_file(path)?;
Ok(())
}
fn write_tree_to_file(&self, path: &str) -> PyResult<()> {
self.inner.write_tree_to_file(path)?;
Ok(())
}
fn write_json_to_file(&self, path: &str) -> PyResult<()> {
self.inner.write_json_to_file(path)?;
Ok(())
}
fn __repr__(&self) -> String {
format!(
"FileLayout(file_size={}, blocks={}, gaps={})",
self.inner.file_size,
self.inner.blocks.len(),
self.inner.gaps.len()
)
}
}
#[gen_stub_pyfunction]
#[pyfunction]
#[pyo3(signature = (input_path, output_path, start_time, end_time))]
fn cut_mdf_by_time(
input_path: &str,
output_path: &str,
start_time: f64,
end_time: f64,
) -> PyResult<()> {
crate::cut::cut_mdf_by_time(input_path, output_path, start_time, end_time)?;
Ok(())
}
#[gen_stub_pyclass]
#[pyclass(name = "ColumnReport")]
#[derive(Clone)]
pub struct PyColumnReport {
#[pyo3(get)]
pub source_groups: usize,
#[pyo3(get)]
pub time_groups: usize,
#[pyo3(get)]
pub signal_groups: usize,
#[pyo3(get)]
pub shared_time_groups: usize,
#[pyo3(get)]
pub data_blocks: usize,
#[pyo3(get)]
pub metadata_size: u64,
#[pyo3(get)]
pub file_size: u64,
#[pyo3(get)]
pub skipped_channels: Vec<String>,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyColumnReport {
fn __repr__(&self) -> String {
format!(
"ColumnReport(source_groups={}, signal_groups={}, time_groups={}, shared_time_groups={}, \
data_blocks={}, metadata_size={}, file_size={}, skipped_channels={:?})",
self.source_groups,
self.signal_groups,
self.time_groups,
self.shared_time_groups,
self.data_blocks,
self.metadata_size,
self.file_size,
self.skipped_channels
)
}
}
impl From<crate::column::ColumnReport> for PyColumnReport {
fn from(r: crate::column::ColumnReport) -> Self {
Self {
source_groups: r.source_groups,
time_groups: r.time_groups,
signal_groups: r.signal_groups,
shared_time_groups: r.shared_time_groups,
data_blocks: r.data_blocks,
metadata_size: r.metadata_size,
file_size: r.file_size,
skipped_channels: r.skipped_channels,
}
}
}
#[gen_stub_pyfunction]
#[pyfunction]
fn to_column_oriented(
py: Python<'_>,
input_path: &str,
output_path: &str,
block_size: Option<u64>,
memory_budget: Option<u64>,
share_identical_time: Option<bool>,
read_chunk_size: Option<u64>,
) -> PyResult<PyColumnReport> {
let defaults = crate::column::ColumnOptions::default();
let options = crate::column::ColumnOptions {
block_size: block_size.unwrap_or(defaults.block_size),
memory_budget: memory_budget.unwrap_or(defaults.memory_budget),
share_identical_time: share_identical_time.unwrap_or(defaults.share_identical_time),
read_chunk_size: read_chunk_size.unwrap_or(defaults.read_chunk_size),
};
let report = py.allow_threads(|| {
crate::column::to_column_oriented(input_path, output_path, &options)
})?;
Ok(report.into())
}
fn coerce_to_unix_ns(py: Python<'_>, value: &Bound<'_, PyAny>) -> PyResult<i64> {
let datetime_mod = py.import_bound("datetime")?;
let datetime_cls = datetime_mod.getattr("datetime")?;
if value.is_instance(&datetime_cls)? {
let dt = ensure_utc_aware(py, value, &datetime_mod)?;
let ts: f64 = dt.call_method0("timestamp")?.extract()?;
return Ok((ts * 1.0e9).round() as i64);
}
if let Ok(s) = value.extract::<String>() {
let normalized = if s.ends_with('Z') || s.ends_with('z') {
format!("{}+00:00", &s[..s.len() - 1])
} else {
s
};
let parsed = datetime_cls.call_method1("fromisoformat", (normalized,))?;
let dt = ensure_utc_aware(py, &parsed, &datetime_mod)?;
let ts: f64 = dt.call_method0("timestamp")?.extract()?;
return Ok((ts * 1.0e9).round() as i64);
}
if let Ok(secs) = value.extract::<f64>() {
if !secs.is_finite() {
return Err(MdfException::new_err("timestamp is not a finite number"));
}
return Ok((secs * 1.0e9).round() as i64);
}
Err(MdfException::new_err(
"expected datetime.datetime, ISO 8601 string, or numeric UNIX timestamp",
))
}
fn ensure_utc_aware<'py>(
py: Python<'py>,
dt: &Bound<'py, PyAny>,
datetime_mod: &Bound<'py, PyModule>,
) -> PyResult<Bound<'py, PyAny>> {
let tzinfo = dt.getattr("tzinfo")?;
if !tzinfo.is_none() {
return Ok(dt.clone());
}
let timezone = datetime_mod.getattr("timezone")?;
let utc = timezone.getattr("utc")?;
let kwargs = [("tzinfo", utc)].into_py_dict_bound(py);
dt.call_method("replace", (), Some(&kwargs))
}
#[gen_stub_pyfunction]
#[pyfunction]
#[pyo3(signature = (input_path, output_path, start_utc, end_utc))]
fn cut_mdf_by_utc(
py: Python<'_>,
input_path: &str,
output_path: &str,
start_utc: &Bound<'_, PyAny>,
end_utc: &Bound<'_, PyAny>,
) -> PyResult<()> {
let start_ns = coerce_to_unix_ns(py, start_utc)?;
let end_ns = coerce_to_unix_ns(py, end_utc)?;
crate::cut::cut_mdf_by_utc(input_path, output_path, start_ns, end_ns)?;
Ok(())
}
#[gen_stub_pyfunction]
#[pyfunction]
fn merge_files(output: &str, first: &str, second: &str) -> PyResult<()> {
crate::merge::merge_files(output, first, second)?;
Ok(())
}
pub fn init_mf4_rs_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
let mdf_exception = m.py().get_type_bound::<MdfException>();
mdf_exception.setattr(
"__doc__",
"Base class of every error raised by mf4_rs: malformed or unsupported \
MDF files, I/O failures, invalid arguments, a missing data source, a \
finalized writer, and so on.\n\n\
>>> try:\n\
... mdf = mf4_rs.Mdf.from_file(\"missing.mf4\")\n\
... except mf4_rs.MdfException as e:\n\
... print(\"could not open:\", e)",
)?;
m.add("MdfException", mdf_exception)?;
let not_found = m.py().get_type_bound::<ChannelNotFoundError>();
not_found.setattr(
"__doc__",
"Raised by data operations (read, values, time_range, conversion, \
byte_ranges) when the named channel does not exist. Metadata lookups \
(group, channel) return None instead. Subclass of MdfException.",
)?;
m.add("ChannelNotFoundError", not_found)?;
m.add_class::<PyMDF>()?;
m.add_class::<PyMdfIndex>()?;
m.add_class::<PyMdfWriter>()?;
m.add_class::<PySignal>()?;
m.add_class::<PyGroupInfo>()?;
m.add_class::<PyChannelInfo>()?;
m.add_class::<PyFileLayout>()?;
m.add_class::<PyBlockInfo>()?;
m.add_class::<PyLinkInfo>()?;
m.add_class::<PyGapInfo>()?;
m.add_class::<PyColumnReport>()?;
m.add_function(wrap_pyfunction!(to_column_oriented, m)?)?;
m.add_function(wrap_pyfunction!(cut_mdf_by_time, m)?)?;
m.add_function(wrap_pyfunction!(cut_mdf_by_utc, m)?)?;
m.add_function(wrap_pyfunction!(merge_files, m)?)?;
Ok(())
}
define_stub_info_gatherer!(stub_info);