use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
use pyo3::{create_exception, wrap_pyfunction};
use numpy::{PyArray1, PyReadonlyArray1};
use pyo3_stub_gen::derive::{
gen_stub_pyclass, gen_stub_pyclass_enum, 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::{IndexedChannel, MdfIndex};
use crate::blocks::common::DataType;
use crate::parsing::decoder::DecodedValue;
use crate::error::MdfError;
use crate::block_layout::{BlockInfo, FileLayout, GapInfo, LinkInfo};
create_exception!(mf4_rs, MdfException, pyo3::exceptions::PyException);
impl From<MdfError> for PyErr {
fn from(err: MdfError) -> PyErr {
MdfException::new_err(format!("{}", err))
}
}
#[gen_stub_pyclass]
#[pyclass(name = "DataType")]
#[derive(Debug, Clone)]
pub struct PyDataType {
#[pyo3(get)]
pub name: String,
#[pyo3(get)]
pub value: u8,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyDataType {
fn __str__(&self) -> String {
self.name.clone()
}
fn __repr__(&self) -> String {
format!("DataType({})", self.name)
}
}
impl From<&DataType> for PyDataType {
fn from(dt: &DataType) -> Self {
let (name, value) = match dt {
DataType::UnsignedIntegerLE => ("UnsignedIntegerLE", 0),
DataType::UnsignedIntegerBE => ("UnsignedIntegerBE", 1),
DataType::SignedIntegerLE => ("SignedIntegerLE", 2),
DataType::SignedIntegerBE => ("SignedIntegerBE", 3),
DataType::FloatLE => ("FloatLE", 4),
DataType::FloatBE => ("FloatBE", 5),
DataType::StringLatin1 => ("StringLatin1", 6),
DataType::StringUtf8 => ("StringUtf8", 7),
DataType::StringUtf16LE => ("StringUtf16LE", 8),
DataType::StringUtf16BE => ("StringUtf16BE", 9),
DataType::ByteArray => ("ByteArray", 10),
DataType::MimeSample => ("MimeSample", 11),
DataType::MimeStream => ("MimeStream", 12),
DataType::CanOpenDate => ("CanOpenDate", 13),
DataType::CanOpenTime => ("CanOpenTime", 14),
DataType::ComplexLE => ("ComplexLE", 15),
DataType::ComplexBE => ("ComplexBE", 16),
DataType::Unknown(_) => ("Unknown", 255),
};
PyDataType {
name: name.to_string(),
value,
}
}
}
impl From<PyDataType> for DataType {
fn from(py_dt: PyDataType) -> Self {
match py_dt.value {
0 => DataType::UnsignedIntegerLE,
1 => DataType::UnsignedIntegerBE,
2 => DataType::SignedIntegerLE,
3 => DataType::SignedIntegerBE,
4 => DataType::FloatLE,
5 => DataType::FloatBE,
6 => DataType::StringLatin1,
7 => DataType::StringUtf8,
8 => DataType::StringUtf16LE,
9 => DataType::StringUtf16BE,
10 => DataType::ByteArray,
11 => DataType::MimeSample,
12 => DataType::MimeStream,
13 => DataType::CanOpenDate,
14 => DataType::CanOpenTime,
15 => DataType::ComplexLE,
16 => DataType::ComplexBE,
_ => DataType::Unknown(()),
}
}
}
#[gen_stub_pyclass_enum]
#[pyclass(name = "DecodedValue")]
#[derive(Debug, Clone)]
pub enum PyDecodedValue {
Float { value: f64 },
UnsignedInteger { value: u64 },
SignedInteger { value: i64 },
String { value: String },
ByteArray { value: Vec<u8> },
Unknown { },
}
#[pymethods]
impl PyDecodedValue {
fn __str__(&self) -> String {
match self {
PyDecodedValue::Float { value } => format!("{}", value),
PyDecodedValue::UnsignedInteger { value } => format!("{}", value),
PyDecodedValue::SignedInteger { value } => format!("{}", value),
PyDecodedValue::String { value } => value.clone(),
PyDecodedValue::ByteArray { value } => format!("bytes[{}]", value.len()),
PyDecodedValue::Unknown { } => "Unknown".to_string(),
}
}
fn __repr__(&self) -> String {
match self {
PyDecodedValue::Float { value } => format!("Float({})", value),
PyDecodedValue::UnsignedInteger { value } => format!("UnsignedInteger({})", value),
PyDecodedValue::SignedInteger { value } => format!("SignedInteger({})", value),
PyDecodedValue::String { value } => format!("String('{}')", value),
PyDecodedValue::ByteArray { value } => format!("ByteArray({})", value.len()),
PyDecodedValue::Unknown { } => "Unknown".to_string(),
}
}
#[getter]
fn value(&self, py: Python) -> PyObject {
match self {
PyDecodedValue::Float { value } => value.to_object(py),
PyDecodedValue::UnsignedInteger { value } => value.to_object(py),
PyDecodedValue::SignedInteger { value } => value.to_object(py),
PyDecodedValue::String { value } => value.to_object(py),
PyDecodedValue::ByteArray { value } => value.to_object(py),
PyDecodedValue::Unknown { } => py.None(),
}
}
}
impl From<DecodedValue> for PyDecodedValue {
fn from(dv: DecodedValue) -> Self {
match dv {
DecodedValue::Float(v) => PyDecodedValue::Float { value: v },
DecodedValue::UnsignedInteger(v) => PyDecodedValue::UnsignedInteger { value: v },
DecodedValue::SignedInteger(v) => PyDecodedValue::SignedInteger { value: v },
DecodedValue::String(v) => PyDecodedValue::String { value: v },
DecodedValue::ByteArray(v) => PyDecodedValue::ByteArray { value: v },
DecodedValue::MimeSample(v) => PyDecodedValue::ByteArray { value: v },
DecodedValue::MimeStream(v) => PyDecodedValue::ByteArray { value: v },
DecodedValue::Unknown => PyDecodedValue::Unknown { },
}
}
}
impl From<PyDecodedValue> for DecodedValue {
fn from(py_dv: PyDecodedValue) -> Self {
match py_dv {
PyDecodedValue::Float { value } => DecodedValue::Float(value),
PyDecodedValue::UnsignedInteger { value } => DecodedValue::UnsignedInteger(value),
PyDecodedValue::SignedInteger { value } => DecodedValue::SignedInteger(value),
PyDecodedValue::String { value } => DecodedValue::String(value),
PyDecodedValue::ByteArray { value } => DecodedValue::ByteArray(value),
PyDecodedValue::Unknown { } => DecodedValue::Unknown,
}
}
}
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) => {
v.to_object(py)
}
DecodedValue::Unknown => py.None(),
}
}
#[gen_stub_pyclass]
#[pyclass(name = "ChannelInfo")]
#[derive(Debug, 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: PyDataType,
#[pyo3(get)]
pub bit_count: u32,
#[pyo3(get)]
pub is_master: bool,
#[pyo3(get)]
pub is_vlsd: bool,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyChannelInfo {
fn __str__(&self) -> String {
format!("Channel(name={:?}, data_type={}, bit_count={})",
self.name, self.data_type.name, self.bit_count)
}
fn __repr__(&self) -> String {
self.__str__()
}
}
impl PyChannelInfo {
fn from_channel(channel: &crate::api::channel::Channel<'_>) -> PyResult<Self> {
let block = channel.block();
Ok(PyChannelInfo {
name: channel.name()?,
unit: channel.unit()?,
comment: channel.comment()?,
data_type: PyDataType::from(&block.data_type),
bit_count: block.bit_count,
is_master: block.channel_type == 2,
is_vlsd: block.channel_type == 1 && block.data != 0,
})
}
fn from_indexed(channel: &IndexedChannel) -> Self {
PyChannelInfo {
name: channel.name.clone(),
unit: channel.unit.clone(),
comment: None,
data_type: PyDataType::from(&channel.data_type),
bit_count: channel.bit_count,
is_master: channel.is_master(),
is_vlsd: channel.is_vlsd(),
}
}
}
#[gen_stub_pyclass]
#[pyclass(name = "GroupInfo")]
#[derive(Debug, Clone)]
pub struct PyChannelGroupInfo {
#[pyo3(get)]
pub name: Option<String>,
#[pyo3(get)]
pub comment: Option<String>,
#[pyo3(get)]
pub channel_count: usize,
#[pyo3(get)]
pub record_count: u64,
#[pyo3(get)]
pub channels: Vec<PyChannelInfo>,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyChannelGroupInfo {
fn channel(&self, name: &str) -> Option<PyChannelInfo> {
self.channels
.iter()
.find(|c| c.name.as_deref() == Some(name))
.cloned()
}
#[getter]
fn channel_names(&self) -> Vec<String> {
self.channels.iter().filter_map(|c| c.name.clone()).collect()
}
fn __str__(&self) -> String {
format!("Group(name={:?}, channels={}, records={})",
self.name, self.channel_count, self.record_count)
}
fn __repr__(&self) -> String {
self.__str__()
}
}
impl PyChannelGroupInfo {
fn from_group(group: &crate::api::channel_group::ChannelGroup<'_>) -> PyResult<Self> {
let channels = group
.channels()
.iter()
.map(PyChannelInfo::from_channel)
.collect::<PyResult<Vec<_>>>()?;
Ok(PyChannelGroupInfo {
name: group.name()?,
comment: group.comment()?,
channel_count: channels.len(),
record_count: group.raw_channel_group().block.cycles_nr,
channels,
})
}
fn from_indexed(group: &crate::index::IndexedChannelGroup) -> Self {
let channels: Vec<PyChannelInfo> =
group.channels.iter().map(PyChannelInfo::from_indexed).collect();
PyChannelGroupInfo {
name: group.name.clone(),
comment: group.comment.clone(),
channel_count: channels.len(),
record_count: group.record_count,
channels,
}
}
}
fn check_pandas_available(py: Python) -> PyResult<PyObject> {
py.import_bound("pandas")
.map(|m| m.into())
.map_err(|_| MdfException::new_err(
"Pandas is not installed. Please install pandas to use Series-based methods."
))
}
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",
))
}
}
fn signal_to_series(
py: Python,
pd: &PyObject,
name: &str,
timestamps: &[f64],
values: Vec<Option<DecodedValue>>,
start_time_ns: Option<u64>,
) -> PyResult<PyObject> {
let mut numeric: Vec<f64> = Vec::with_capacity(values.len());
let mut all_numeric = true;
for v in &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 py_values: PyObject = if all_numeric {
PyArray1::from_vec_bound(py, numeric).into()
} else {
values
.into_iter()
.map(|o| o.map(|dv| decoded_value_to_pyobject(dv, py)).unwrap_or_else(|| py.None()))
.collect::<Vec<PyObject>>()
.to_object(py)
};
let index: PyObject = if timestamps.is_empty() {
py.None()
} else {
let dt_index = 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))
});
match dt_index {
Some(idx) => idx,
None => PyArray1::from_vec_bound(py, timestamps.to_vec()).into(),
}
};
let series_class = pd.getattr(py, "Series")?;
let series = if index.is_none(py) {
series_class.call1(py, (py_values,))?
} else {
series_class.call(py, (py_values,), Some([("index", index)].into_py_dict(py)))?
};
series.setattr(py, "name", name)?;
Ok(series)
}
#[gen_stub_pyclass]
#[pyclass(name = "Mdf")]
pub struct PyMDF {
mdf: Box<MDF>,
path: String,
}
impl PyMDF {
fn find_group_channel<'a>(
&'a self,
group: Option<&str>,
name: &str,
) -> PyResult<(crate::api::channel_group::ChannelGroup<'a>, usize)> {
for g in self.mdf.channel_groups() {
if let Some(gn) = group {
if g.name()?.as_deref() != Some(gn) {
continue;
}
}
let chans = g.channels();
for (i, ch) in chans.iter().enumerate() {
if ch.name()?.as_deref() == Some(name) {
return Ok((g, i));
}
}
}
Err(MdfException::new_err(match group {
Some(gn) => format!("Channel '{}' not found in group '{}'", name, gn),
None => format!("Channel '{}' not found", name),
}))
}
}
#[gen_stub_pymethods]
#[pymethods]
impl PyMDF {
#[new]
fn new(path: &str) -> PyResult<Self> {
let mdf = Box::new(MDF::from_file(path)?);
Ok(PyMDF { mdf, path: path.to_string() })
}
#[getter]
fn source(&self) -> String {
self.path.clone()
}
fn list_signals(&self) -> PyResult<Vec<(String, Option<String>, Option<String>)>> {
let mut out = Vec::new();
for group in self.mdf.channel_groups() {
let gname = group.name()?;
for channel in group.channels() {
out.push((self.path.clone(), gname.clone(), channel.name()?));
}
}
Ok(out)
}
#[getter]
fn groups(&self) -> PyResult<Vec<PyChannelGroupInfo>> {
self.mdf
.channel_groups()
.iter()
.map(PyChannelGroupInfo::from_group)
.collect()
}
fn group(&self, name: &str) -> PyResult<Option<PyChannelGroupInfo>> {
for g in self.mdf.channel_groups() {
if g.name()?.as_deref() == Some(name) {
return Ok(Some(PyChannelGroupInfo::from_group(&g)?));
}
}
Ok(None)
}
fn channel(&self, name: &str) -> PyResult<Option<PyChannelInfo>> {
for g in self.mdf.channel_groups() {
for ch in g.channels() {
if ch.name()?.as_deref() == Some(name) {
return Ok(Some(PyChannelInfo::from_channel(&ch)?));
}
}
}
Ok(None)
}
#[getter]
fn channel_names(&self) -> PyResult<Vec<String>> {
let mut names = Vec::new();
for g in self.mdf.channel_groups() {
for ch in g.channels() {
if let Some(n) = ch.name()? {
names.push(n);
}
}
}
Ok(names)
}
fn read(&self, py: Python, name: &str, group: Option<&str>) -> PyResult<PyObject> {
let pd = check_pandas_available(py)?;
let start_time_ns = self.mdf.start_time_ns();
let signal = py.allow_threads(|| -> Result<Option<crate::signal::Signal>, MdfError> {
match group {
Some(gn) => match self.mdf.group(gn) {
Some(_) => self.mdf.signal_in(gn, name),
None => Err(MdfError::BlockSerializationError(format!(
"Channel group '{}' not found", gn
))),
},
None => self.mdf.signal(name),
}
})?;
let signal = signal.ok_or_else(|| {
MdfException::new_err(match group {
Some(gn) => format!("Channel '{}' not found in group '{}'", name, gn),
None => format!("Channel '{}' not found", name),
})
})?;
signal_to_series(py, &pd, &signal.name, &signal.timestamps, signal.values, start_time_ns)
}
fn values<'py>(&self, py: Python<'py>, name: &str, group: Option<&str>) -> PyResult<PyObject> {
let (g, idx) = self.find_group_channel(group, name)?;
let values = py.allow_threads(|| g.channels()[idx].values_as_f64())?;
Ok(PyArray1::from_vec_bound(py, values).into())
}
fn __getitem__(&self, py: Python, key: &Bound<'_, PyAny>) -> PyResult<PyObject> {
let (name, group) = parse_lookup_key(key)?;
self.read(py, &name, group.as_deref())
}
fn file_layout(&self) -> PyResult<PyFileLayout> {
let layout = self.mdf.file_layout()?;
Ok(PyFileLayout { inner: layout })
}
}
#[gen_stub_pyclass]
#[pyclass(unsendable, name = "MdfWriter")]
pub struct PyMdfWriter {
writer: Option<MdfWriter>,
channel_groups: HashMap<String, String>, channels: HashMap<String, String>, last_channels: HashMap<String, String>, next_id: usize,
}
impl PyMdfWriter {
fn add_channel_with_bits(&mut self, group_id: &str, name: &str, data_type: PyDataType, bit_count: u32) -> PyResult<String> {
if let Some(ref mut writer) = self.writer {
let cg_id = self.channel_groups.get(group_id)
.ok_or_else(|| MdfException::new_err("Channel group not found"))?;
let prev_channel_id = self.last_channels.get(group_id)
.and_then(|py_id| self.channels.get(py_id))
.cloned();
let rust_data_type = DataType::from(data_type);
let ch_id = writer.add_channel(cg_id, prev_channel_id.as_ref().map(|s| s.as_str()), |ch| {
ch.data_type = rust_data_type.clone();
ch.name = Some(name.to_string());
ch.bit_count = bit_count;
})?;
let py_id = format!("ch_{}", self.next_id);
self.next_id += 1;
self.channels.insert(py_id.clone(), ch_id);
self.last_channels.insert(group_id.to_string(), py_id.clone());
Ok(py_id)
} else {
Err(MdfException::new_err("Writer has been finalized"))
}
}
}
#[gen_stub_pymethods]
#[pymethods]
impl PyMdfWriter {
#[new]
fn new(path: &str) -> PyResult<Self> {
let writer = MdfWriter::new(path)?;
Ok(PyMdfWriter {
writer: Some(writer),
channel_groups: HashMap::new(),
channels: HashMap::new(),
last_channels: HashMap::new(),
next_id: 0,
})
}
fn init_mdf_file(&mut self) -> PyResult<()> {
if let Some(ref mut writer) = self.writer {
writer.init_mdf_file()?;
Ok(())
} else {
Err(MdfException::new_err("Writer has been finalized"))
}
}
fn add_channel_group(&mut self, name: Option<String>) -> PyResult<String> {
if let Some(ref mut writer) = self.writer {
let cg_id = writer.add_channel_group(None, |_cg| {})?;
if let Some(n) = &name {
writer.set_channel_group_name(&cg_id, n)?;
}
let py_id = format!("cg_{}", self.next_id);
self.next_id += 1;
self.channel_groups.insert(py_id.clone(), cg_id);
Ok(py_id)
} else {
Err(MdfException::new_err("Writer has been finalized"))
}
}
fn set_channel_group_comment(&mut self, group_id: &str, comment: &str) -> PyResult<()> {
let writer = self
.writer
.as_mut()
.ok_or_else(|| MdfException::new_err("Writer has been finalized"))?;
let rust_id = self
.channel_groups
.get(group_id)
.ok_or_else(|| MdfException::new_err(format!("Unknown group_id: {}", group_id)))?
.clone();
writer.set_channel_group_comment(&rust_id, comment)?;
Ok(())
}
fn add_channel(&mut self,
group_id: &str,
name: &str,
data_type: PyDataType) -> PyResult<String> {
let bits = {
let rust_dt = DataType::from(data_type.clone());
rust_dt.default_bits()
};
self.add_channel_with_bits(group_id, name, data_type, bits)
}
fn add_time_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
let ch_id = self.add_channel_with_bits(group_id, name, PyDataType { name: "FloatLE".to_string(), value: 4 }, 64)?;
self.set_time_channel(&ch_id)?;
Ok(ch_id)
}
fn add_float_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
self.add_channel_with_bits(group_id, name, PyDataType { name: "FloatLE".to_string(), value: 4 }, 64)
}
fn add_float32_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
self.add_channel_with_bits(group_id, name, PyDataType { name: "FloatLE".to_string(), value: 4 }, 32)
}
fn add_int_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
self.add_channel_with_bits(group_id, name, PyDataType { name: "UnsignedIntegerLE".to_string(), value: 0 }, 64)
}
fn add_sint_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
self.add_channel_with_bits(group_id, name, PyDataType { name: "SignedIntegerLE".to_string(), value: 2 }, 64)
}
fn add_string_channel(&mut self, group_id: &str, name: &str) -> PyResult<String> {
if let Some(ref mut writer) = self.writer {
let cg_id = self.channel_groups.get(group_id)
.ok_or_else(|| MdfException::new_err("Channel group not found"))?;
let prev_channel_id = self.last_channels.get(group_id)
.and_then(|py_id| self.channels.get(py_id))
.cloned();
let ch_id = writer.add_channel(cg_id, prev_channel_id.as_ref().map(|s| s.as_str()), |ch| {
ch.data_type = DataType::StringUtf8;
ch.name = Some(name.to_string());
ch.channel_type = 1; ch.data = 1; ch.bit_count = 64; })?;
let py_id = format!("ch_{}", self.next_id);
self.next_id += 1;
self.channels.insert(py_id.clone(), ch_id);
self.last_channels.insert(group_id.to_string(), py_id.clone());
Ok(py_id)
} else {
Err(MdfException::new_err("Writer has been finalized"))
}
}
fn set_time_channel(&mut self, channel_id: &str) -> PyResult<()> {
if let Some(ref mut writer) = self.writer {
let ch_id = self.channels.get(channel_id)
.ok_or_else(|| MdfException::new_err("Channel not found"))?;
writer.set_time_channel(ch_id)?;
Ok(())
} else {
Err(MdfException::new_err("Writer has been finalized"))
}
}
fn start_data_block(&mut self, group_id: &str) -> PyResult<()> {
if let Some(ref mut writer) = self.writer {
let cg_id = self.channel_groups.get(group_id)
.ok_or_else(|| MdfException::new_err("Channel group not found"))?;
writer.start_data_block_for_cg(cg_id, 0)?;
Ok(())
} else {
Err(MdfException::new_err("Writer has been finalized"))
}
}
fn write_record(&mut self, group_id: &str, values: Vec<PyDecodedValue>) -> PyResult<()> {
if let Some(ref mut writer) = self.writer {
let cg_id = self.channel_groups.get(group_id)
.ok_or_else(|| MdfException::new_err("Channel group not found"))?;
let rust_values: Vec<DecodedValue> = values.into_iter().map(DecodedValue::from).collect();
writer.write_record(cg_id, &rust_values)?;
Ok(())
} else {
Err(MdfException::new_err("Writer has been finalized"))
}
}
fn finish_data_block(&mut self, group_id: &str) -> PyResult<()> {
if let Some(ref mut writer) = self.writer {
let cg_id = self.channel_groups.get(group_id)
.ok_or_else(|| MdfException::new_err("Channel group not found"))?;
writer.finish_data_block(cg_id)?;
Ok(())
} else {
Err(MdfException::new_err("Writer has been finalized"))
}
}
fn write_columns_f64(&mut self, _py: Python<'_>, group_id: &str, columns: Vec<Bound<'_, PyAny>>) -> PyResult<()> {
if let Some(ref mut writer) = self.writer {
let cg_id = self.channel_groups.get(group_id)
.ok_or_else(|| MdfException::new_err("Channel group not found"))?
.clone();
let arrays: Vec<PyReadonlyArray1<f64>> = columns.iter()
.map(|c| c.extract::<PyReadonlyArray1<f64>>())
.collect::<PyResult<Vec<_>>>()?;
let slices: Vec<&[f64]> = arrays.iter()
.map(|a| a.as_slice().map_err(|e| MdfException::new_err(format!("Array not contiguous: {}", e))))
.collect::<PyResult<Vec<_>>>()?;
writer.write_columns_f64(&cg_id, &slices)?;
Ok(())
} else {
Err(MdfException::new_err("Writer has been finalized"))
}
}
fn write_columns(&mut self, _py: Python<'_>, group_id: &str, columns: Vec<Bound<'_, PyAny>>, dtypes: Vec<String>) -> PyResult<()> {
if columns.len() != dtypes.len() {
return Err(MdfException::new_err(format!(
"columns length ({}) must match dtypes length ({})",
columns.len(), dtypes.len()
)));
}
if let Some(ref mut writer) = self.writer {
let cg_id = self.channel_groups.get(group_id)
.ok_or_else(|| MdfException::new_err("Channel group not found"))?
.clone();
enum OwnedArray<'py> {
F64(PyReadonlyArray1<'py, f64>),
F32(PyReadonlyArray1<'py, f32>),
U64(PyReadonlyArray1<'py, u64>),
I64(PyReadonlyArray1<'py, i64>),
}
let owned: Vec<OwnedArray<'_>> = columns.iter().zip(dtypes.iter())
.map(|(col, dtype)| match dtype.as_str() {
"f64" => col.extract::<PyReadonlyArray1<f64>>().map(OwnedArray::F64),
"f32" => col.extract::<PyReadonlyArray1<f32>>().map(OwnedArray::F32),
"u64" => col.extract::<PyReadonlyArray1<u64>>().map(OwnedArray::U64),
"i64" => col.extract::<PyReadonlyArray1<i64>>().map(OwnedArray::I64),
other => Err(MdfException::new_err(format!(
"Unknown dtype '{}'; expected one of: f64, f32, u64, i64", other
))),
})
.collect::<PyResult<Vec<_>>>()?;
let column_data: Vec<ColumnData<'_>> = owned.iter()
.map(|arr| match arr {
OwnedArray::F64(a) => a.as_slice()
.map(ColumnData::F64)
.map_err(|e| MdfException::new_err(format!("Array not contiguous: {}", e))),
OwnedArray::F32(a) => a.as_slice()
.map(ColumnData::F32)
.map_err(|e| MdfException::new_err(format!("Array not contiguous: {}", e))),
OwnedArray::U64(a) => a.as_slice()
.map(ColumnData::U64)
.map_err(|e| MdfException::new_err(format!("Array not contiguous: {}", e))),
OwnedArray::I64(a) => a.as_slice()
.map(ColumnData::I64)
.map_err(|e| MdfException::new_err(format!("Array not contiguous: {}", e))),
})
.collect::<PyResult<Vec<_>>>()?;
writer.write_columns(&cg_id, &column_data)?;
Ok(())
} else {
Err(MdfException::new_err("Writer has been finalized"))
}
}
fn finalize(&mut self) -> PyResult<()> {
if let Some(writer) = self.writer.take() {
writer.finalize()?;
Ok(())
} else {
Err(MdfException::new_err("Writer already finalized"))
}
}
}
#[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 load(path: &str) -> PyResult<Self> {
Ok(PyMdfIndex { index: MdfIndex::load_from_file(path)? })
}
#[staticmethod]
fn from_url(py: Python, url: &str, chunk_size: Option<u64>) -> PyResult<Self> {
let url = url.to_string();
let chunk = chunk_size.unwrap_or(1 << 20);
let index = py.allow_threads(move || -> Result<MdfIndex, MdfError> {
MdfIndex::from_url_with_chunk_size(&url, chunk)
})?;
Ok(PyMdfIndex { index })
}
fn save(&self, path: &str) -> PyResult<()> {
self.index.save_to_file(path)?;
Ok(())
}
#[getter]
fn groups(&self) -> Vec<PyChannelGroupInfo> {
self.index.groups().iter().map(PyChannelGroupInfo::from_indexed).collect()
}
fn group(&self, name: &str) -> Option<PyChannelGroupInfo> {
self.index.group(name).map(PyChannelGroupInfo::from_indexed)
}
fn channel(&self, name: &str) -> Option<PyChannelInfo> {
self.index.channel(name).map(PyChannelInfo::from_indexed)
}
#[getter]
fn channel_names(&self) -> Vec<String> {
self.index.channel_names().into_iter().map(String::from).collect()
}
fn groups_with_channel(&self, name: &str) -> Vec<String> {
self.index
.find_channels(name)
.into_iter()
.filter_map(|(g, _)| self.index.groups().get(g).and_then(|grp| grp.name.clone()))
.collect()
}
fn byte_ranges(&self, name: &str, group: Option<&str>) -> PyResult<Vec<(u64, u64)>> {
Ok(match group {
Some(g) => self.index.byte_ranges_in(g, name)?,
None => self.index.byte_ranges(name)?,
})
}
fn byte_ranges_for_records(
&self,
name: &str,
start_record: u64,
record_count: u64,
) -> PyResult<Vec<(u64, u64)>> {
Ok(self.index.byte_ranges_for_records(name, start_record, record_count)?)
}
fn conversion_info(&self, name: &str) -> PyResult<Option<HashMap<String, PyObject>>> {
let resolved = self
.index
.conversion(name)
.map_err(|e| MdfException::new_err(e.to_string()))?;
if let Some(conversion) = resolved.as_ref() {
Python::with_gil(|py| {
let mut info = HashMap::new();
info.insert("conversion_type".to_string(), format!("{:?}", conversion.cc_type).to_object(py));
info.insert("precision".to_string(), conversion.cc_precision.to_object(py));
info.insert("flags".to_string(), conversion.cc_flags.to_object(py));
info.insert("values_count".to_string(), conversion.cc_val_count.to_object(py));
info.insert("values".to_string(), conversion.cc_val.to_object(py));
if let Some(resolved_texts) = &conversion.resolved_texts {
let texts: HashMap<usize, String> = resolved_texts.clone();
info.insert("resolved_texts".to_string(), texts.to_object(py));
}
if conversion.resolved_conversions.is_some() {
info.insert("has_resolved_conversions".to_string(), true.to_object(py));
}
if let Some(formula) = &conversion.formula {
info.insert("formula".to_string(), formula.to_object(py));
}
Ok(Some(info))
})
} else {
Ok(None)
}
}
#[getter]
fn file_size(&self) -> u64 {
self.index.file_size
}
#[getter]
fn source(&self) -> Option<String> {
self.index.source_string()
}
fn list_signals(&self) -> Vec<(Option<String>, Option<String>, Option<String>)> {
self.index.signal_list()
}
#[setter(source)]
fn set_source_prop(&mut self, value: Option<&str>) {
self.apply_source(value);
}
fn set_source(&mut self, value: Option<&str>) {
self.apply_source(value);
}
fn read(&self, py: Python, name: &str, group: Option<&str>) -> PyResult<PyObject> {
let pd = check_pandas_available(py)?;
let signal = py.allow_threads(|| match group {
Some(g) => self.index.read_in(g, name),
None => self.index.read(name),
})?;
signal_to_series(
py, &pd, &signal.name, &signal.timestamps, signal.values, self.index.start_time_ns,
)
}
fn values<'py>(&self, py: Python<'py>, name: &str, group: Option<&str>) -> PyResult<PyObject> {
let (g, c) = match group {
Some(gn) => self.index.locate_in(gn, name).ok_or_else(|| {
MdfException::new_err(format!("Channel '{}' not found in group '{}'", name, gn))
})?,
None => self.index.locate(name).ok_or_else(|| {
MdfException::new_err(format!("Channel '{}' not found", name))
})?,
};
let values = py.allow_threads(|| self.index.read_values_f64_via_source(g, c))?;
Ok(PyArray1::from_vec_bound(py, values).into())
}
fn __getitem__(&self, py: Python, key: &Bound<'_, PyAny>) -> PyResult<PyObject> {
let (name, group) = parse_lookup_key(key)?;
self.read(py, &name, group.as_deref())
}
}
impl PyMdfIndex {
fn apply_source(&mut self, value: Option<&str>) {
match value {
None => self.index.source = None,
Some(v) if v.starts_with("http://") || v.starts_with("https://") => {
self.index.set_url(v);
}
Some(v) => self.index.set_file(v),
}
}
}
#[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]
fn file_layout_from_file(path: &str) -> PyResult<PyFileLayout> {
PyFileLayout::from_file(path)
}
#[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(signal_groups={}, time_groups={}, shared_time_groups={}, \
data_blocks={}, metadata_size={}, file_size={}, skipped_channels={})",
self.signal_groups,
self.time_groups,
self.shared_time_groups,
self.data_blocks,
self.metadata_size,
self.file_size,
self.skipped_channels.len()
)
}
}
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>,
) -> 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),
..defaults
};
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_ns(input_path, output_path, start_ns, end_ns)?;
Ok(())
}
#[gen_stub_pyfunction]
#[pyfunction]
fn create_float_value(value: f64) -> PyDecodedValue {
PyDecodedValue::Float { value }
}
#[gen_stub_pyfunction]
#[pyfunction]
fn create_uint_value(value: u64) -> PyDecodedValue {
PyDecodedValue::UnsignedInteger { value }
}
#[gen_stub_pyfunction]
#[pyfunction]
fn create_int_value(value: i64) -> PyDecodedValue {
PyDecodedValue::SignedInteger { value }
}
#[gen_stub_pyfunction]
#[pyfunction]
fn create_string_value(value: String) -> PyDecodedValue {
PyDecodedValue::String { value }
}
#[gen_stub_pyfunction]
#[pyfunction]
fn create_data_type_uint_le() -> PyDataType {
PyDataType { name: "UnsignedIntegerLE".to_string(), value: 0 }
}
#[gen_stub_pyfunction]
#[pyfunction]
fn create_data_type_float_le() -> PyDataType {
PyDataType { name: "FloatLE".to_string(), value: 4 }
}
#[gen_stub_pyfunction]
#[pyfunction]
fn create_data_type_string_utf8() -> PyDataType {
PyDataType { name: "StringUtf8".to_string(), value: 7 }
}
#[gen_stub_pyfunction]
#[pyfunction]
fn create_data_type_signed_le() -> PyDataType {
PyDataType { name: "SignedIntegerLE".to_string(), value: 2 }
}
#[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__",
"Exception raised by mf4_rs for any error originating from the \
underlying Rust library: malformed or unsupported MDF files, \
out-of-range indices, missing channels, I/O failures, conversion \
dependency cycles, attempts to use a finalized writer, missing \
optional dependencies (e.g. pandas), and so on.\n\n\
All public methods on Mdf, MdfWriter, MdfIndex, and the \
module-level free functions raise this (or a subclass of \
Exception) on failure. Catch it as a single category to handle \
every mf4_rs failure path:\n\n\
>>> try:\n\
... mdf = mf4_rs.Mdf(\"missing.mf4\")\n\
... except mf4_rs.MdfException as e:\n\
... print(\"could not open:\", e)",
)?;
m.add("MdfException", mdf_exception)?;
m.add_class::<PyMDF>()?;
m.add_class::<PyMdfWriter>()?;
m.add_class::<PyMdfIndex>()?;
m.add_class::<PyChannelGroupInfo>()?;
m.add_class::<PyChannelInfo>()?;
m.add_class::<PyDecodedValue>()?;
m.add_class::<PyDataType>()?;
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!(create_float_value, m)?)?;
m.add_function(wrap_pyfunction!(create_uint_value, m)?)?;
m.add_function(wrap_pyfunction!(create_int_value, m)?)?;
m.add_function(wrap_pyfunction!(create_string_value, m)?)?;
m.add_function(wrap_pyfunction!(create_data_type_uint_le, m)?)?;
m.add_function(wrap_pyfunction!(create_data_type_float_le, m)?)?;
m.add_function(wrap_pyfunction!(create_data_type_string_utf8, m)?)?;
m.add_function(wrap_pyfunction!(create_data_type_signed_le, m)?)?;
m.add_function(wrap_pyfunction!(file_layout_from_file, m)?)?;
m.add_function(wrap_pyfunction!(merge_files, 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!(to_column_oriented, m)?)?;
Ok(())
}
define_stub_info_gatherer!(stub_info);