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::{
ByteRangeReader, CachingRangeReader, FileRangeReader, HttpRangeReader, 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]
#[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]
#[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]
#[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,
}
#[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__()
}
}
#[gen_stub_pyclass]
#[pyclass]
#[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,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyChannelGroupInfo {
fn __str__(&self) -> String {
format!("ChannelGroup(name={:?}, channels={}, records={})",
self.name, self.channel_count, self.record_count)
}
fn __repr__(&self) -> String {
self.__str__()
}
}
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 find_master_channel<'a>(channels: &Vec<crate::api::channel::Channel<'a>>) -> Option<usize> {
for (idx, channel) in channels.iter().enumerate() {
let block = channel.block();
if block.channel_type == 2 {
return Some(idx);
}
}
None
}
fn find_master_channel_indexed(channels: &Vec<IndexedChannel>) -> Option<usize> {
for (idx, channel) in channels.iter().enumerate() {
if channel.channel_type == 2 {
return Some(idx);
}
}
None
}
fn create_datetime_index(
py: Python,
pd: &PyObject,
relative_times: &[PyObject],
start_ns: u64,
) -> PyResult<PyObject> {
let to_datetime = pd.getattr(py, "to_datetime")?;
let start_timestamp = to_datetime.call(
py,
(start_ns,),
Some([("unit", "ns")].into_py_dict(py))
)?;
let timedelta_class = pd.getattr(py, "Timedelta")?;
let nat = pd.getattr(py, "NaT")?; let mut absolute_times = Vec::with_capacity(relative_times.len());
for rel_time in relative_times {
if rel_time.is_none(py) {
absolute_times.push(nat.clone());
continue;
}
let seconds: f64 = if let Ok(f) = rel_time.extract::<f64>(py) {
f
} else if let Ok(i) = rel_time.extract::<i64>(py) {
i as f64
} else if let Ok(u) = rel_time.extract::<u64>(py) {
u as f64
} else {
absolute_times.push(nat.clone());
continue;
};
let delta = timedelta_class.call(
py,
(seconds,),
Some([("unit", "s")].into_py_dict(py))
)?;
let absolute_time = start_timestamp.call_method1(py, "__add__", (delta,))?;
absolute_times.push(absolute_time);
}
let datetime_index_class = pd.getattr(py, "DatetimeIndex")?;
let datetime_index = datetime_index_class.call1(py, (absolute_times,))?;
Ok(datetime_index)
}
#[gen_stub_pyclass]
#[pyclass]
pub struct PyMDF {
mdf: Box<MDF>,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyMDF {
#[new]
fn new(path: &str) -> PyResult<Self> {
let mdf = Box::new(MDF::from_file(path)?);
Ok(PyMDF { mdf })
}
fn channel_groups(&self) -> PyResult<Vec<PyChannelGroupInfo>> {
let mut py_groups = Vec::new();
for group in self.mdf.channel_groups() {
let name = group.name()?;
let comment = group.comment()?;
let channel_count = group.channels().len();
let record_count = group.raw_channel_group().block.cycles_nr;
py_groups.push(PyChannelGroupInfo {
name,
comment,
channel_count,
record_count,
});
}
Ok(py_groups)
}
fn get_all_channels(&self) -> PyResult<Vec<PyChannelInfo>> {
let mut channels = Vec::new();
for group in self.mdf.channel_groups() {
for channel in group.channels() {
let block = channel.block();
let info = PyChannelInfo {
name: channel.name()?,
unit: channel.unit()?,
comment: channel.comment()?,
data_type: PyDataType::from(&block.data_type),
bit_count: block.bit_count,
};
channels.push(info);
}
}
Ok(channels)
}
fn get_channels_for_group(&self, group_index: usize) -> PyResult<Vec<PyChannelInfo>> {
let groups: Vec<_> = self.mdf.channel_groups().into_iter().collect();
if let Some(group) = groups.get(group_index) {
let mut channels = Vec::new();
for channel in group.channels() {
let block = channel.block();
let info = PyChannelInfo {
name: channel.name()?,
unit: channel.unit()?,
comment: channel.comment()?,
data_type: PyDataType::from(&block.data_type),
bit_count: block.bit_count,
};
channels.push(info);
}
Ok(channels)
} else {
Err(MdfException::new_err("Group index out of bounds"))
}
}
fn get_all_channel_names(&self) -> PyResult<Vec<String>> {
let mut names = Vec::new();
for group in self.mdf.channel_groups() {
for channel in group.channels() {
if let Some(name) = channel.name()? {
names.push(name);
}
}
}
Ok(names)
}
fn get_channel_values<'py>(&self, py: Python<'py>, channel_name: &str) -> PyResult<Option<PyObject>> {
for group in self.mdf.channel_groups() {
for channel in group.channels() {
if let Some(name) = channel.name()? {
if name == channel_name {
let values = channel.values_as_f64()?;
let array = PyArray1::from_vec_bound(py, values);
return Ok(Some(array.into()));
}
}
}
}
Ok(None)
}
fn get_channel_values_by_group_and_name<'py>(&self, py: Python<'py>, group_name: &str, channel_name: &str) -> PyResult<Option<PyObject>> {
for group in self.mdf.channel_groups() {
if let Some(gname) = group.name()? {
if gname == group_name {
for channel in group.channels() {
if let Some(cname) = channel.name()? {
if cname == channel_name {
let values = channel.values_as_f64()?;
let array = PyArray1::from_vec_bound(py, values);
return Ok(Some(array.into()));
}
}
}
return Ok(None);
}
}
}
Ok(None)
}
fn get_channel_as_series(&self, py: Python, channel_name: &str) -> PyResult<Option<PyObject>> {
let pd = check_pandas_available(py)?;
let start_time_ns = self.mdf.start_time_ns();
for group in self.mdf.channel_groups() {
let channels = group.channels();
for (ch_idx, channel) in channels.iter().enumerate() {
if let Some(name) = channel.name()? {
if name == channel_name {
let values = channel.values_as_f64()?;
let py_values = PyArray1::from_vec_bound(py, values);
let index: PyObject = if let Some(master_idx) = find_master_channel(&channels) {
if master_idx != ch_idx {
let master_values = channels[master_idx].values_as_f64()?;
let py_master = PyArray1::from_vec_bound(py, master_values);
if let Some(start_ns) = start_time_ns {
let to_datetime = pd.getattr(py, "to_datetime")?;
let to_timedelta = pd.getattr(py, "to_timedelta")?;
let start_ts = to_datetime.call(
py, (start_ns,),
Some([("unit", "ns")].into_py_dict(py))
)?;
let deltas = to_timedelta.call(
py, (py_master.clone(),),
Some([("unit", "s")].into_py_dict(py))
)?;
match deltas.call_method1(py, "__add__", (start_ts,)) {
Ok(datetime_index) => datetime_index,
Err(_) => py_master.into(),
}
} else {
py_master.into()
}
} else {
py.None()
}
} else {
py.None()
};
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", channel_name)?;
return Ok(Some(series));
}
}
}
}
Ok(None)
}
fn file_layout(&self) -> PyResult<PyFileLayout> {
let layout = self.mdf.file_layout()?;
Ok(PyFileLayout { inner: layout })
}
}
#[gen_stub_pyclass]
#[pyclass(unsendable)]
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 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]
pub struct PyMdfIndex {
index: MdfIndex,
}
#[gen_stub_pymethods]
#[pymethods]
impl PyMdfIndex {
#[staticmethod]
fn from_file(path: &str) -> PyResult<Self> {
let index = MdfIndex::from_file(path)?;
Ok(PyMdfIndex { index })
}
#[staticmethod]
fn load_from_file(path: &str) -> PyResult<Self> {
let index = MdfIndex::load_from_file(path)?;
Ok(PyMdfIndex { index })
}
#[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> {
let mut http = HttpRangeReader::new(&url)?;
let file_size = http.probe_size()?;
let mut cached = CachingRangeReader::with_chunk_size(http, chunk);
MdfIndex::from_range_reader(&mut cached, file_size)
})?;
Ok(PyMdfIndex { index })
}
fn save_to_file(&self, path: &str) -> PyResult<()> {
self.index.save_to_file(path)?;
Ok(())
}
fn list_channel_groups(&self) -> Vec<(usize, String, usize)> {
self.index.list_channel_groups()
.into_iter()
.map(|(idx, name, count)| (idx, name.to_string(), count))
.collect()
}
fn list_channels(&self, group_index: usize) -> Option<Vec<(usize, String, PyDataType)>> {
self.index.list_channels(group_index)
.map(|channels| {
channels.into_iter()
.map(|(idx, name, data_type)| (idx, name.to_string(), PyDataType::from(data_type)))
.collect()
})
}
fn read_channel_values(&self, py: Python, group_index: usize, channel_index: usize, file_path: &str) -> PyResult<Vec<Option<PyObject>>> {
let mut reader = FileRangeReader::new(file_path)?;
let values = self.index.read_channel_values(group_index, channel_index, &mut reader)?;
Ok(values.into_iter().map(|opt_val| {
opt_val.map(|dv| decoded_value_to_pyobject(dv, py))
}).collect())
}
fn read_channel_values_by_name(&self, py: Python, channel_name: &str, file_path: &str) -> PyResult<Vec<Option<PyObject>>> {
let mut reader = FileRangeReader::new(file_path)?;
let values = self.index.read_channel_values_by_name(channel_name, &mut reader)?;
Ok(values.into_iter().map(|opt_val| {
opt_val.map(|dv| decoded_value_to_pyobject(dv, py))
}).collect())
}
fn read_channel_values_from_url(
&self,
py: Python,
group_index: usize,
channel_index: usize,
url: &str,
) -> PyResult<Vec<Option<PyObject>>> {
let url = url.to_string();
let values = py.allow_threads(move || -> Result<_, MdfError> {
let http = HttpRangeReader::new(&url)?;
let mut cached = CachingRangeReader::new(http);
cached.set_bypass(true);
self.index
.read_channel_values(group_index, channel_index, &mut cached)
})?;
Ok(values
.into_iter()
.map(|opt_val| opt_val.map(|dv| decoded_value_to_pyobject(dv, py)))
.collect())
}
fn read_channel_values_by_name_from_url(
&self,
py: Python,
channel_name: &str,
url: &str,
) -> PyResult<Vec<Option<PyObject>>> {
let url = url.to_string();
let channel_name = channel_name.to_string();
let values = py.allow_threads(move || -> Result<_, MdfError> {
let http = HttpRangeReader::new(&url)?;
let mut cached = CachingRangeReader::new(http);
cached.set_bypass(true);
self.index
.read_channel_values_by_name(&channel_name, &mut cached)
})?;
Ok(values
.into_iter()
.map(|opt_val| opt_val.map(|dv| decoded_value_to_pyobject(dv, py)))
.collect())
}
fn read_channel_values_as_f64(&self, group_index: usize, channel_index: usize, file_path: &str) -> PyResult<Vec<f64>> {
let file = std::fs::File::open(file_path).map_err(|e| MdfError::IOError(e))?;
let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(|e| MdfError::IOError(e))?;
Ok(self.index.read_channel_values_from_slice_as_f64(group_index, channel_index, &mmap)?)
}
fn read_channel_values_by_name_as_f64(&self, channel_name: &str, file_path: &str) -> PyResult<Vec<f64>> {
let (group_index, channel_index) = self.index.find_channel_by_name_global(channel_name)
.ok_or_else(|| MdfError::BlockSerializationError(
format!("Channel '{}' not found", channel_name)
))?;
let file = std::fs::File::open(file_path).map_err(|e| MdfError::IOError(e))?;
let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(|e| MdfError::IOError(e))?;
Ok(self.index.read_channel_values_from_slice_as_f64(group_index, channel_index, &mmap)?)
}
fn find_channel_by_name(&self, channel_name: &str) -> Option<(usize, usize)> {
self.index.find_channel_by_name_global(channel_name)
}
fn get_channel_byte_ranges(&self, group_index: usize, channel_index: usize) -> PyResult<Vec<(u64, u64)>> {
Ok(self.index.get_channel_byte_ranges(group_index, channel_index)?)
}
fn get_channel_byte_ranges_for_records(&self, group_index: usize, channel_index: usize, start_record: u64, record_count: u64) -> PyResult<Vec<(u64, u64)>> {
Ok(self.index.get_channel_byte_ranges_for_records(group_index, channel_index, start_record, record_count)?)
}
fn get_channel_byte_summary(&self, group_index: usize, channel_index: usize) -> PyResult<(u64, usize)> {
Ok(self.index.get_channel_byte_summary(group_index, channel_index)?)
}
fn get_channel_byte_ranges_by_name(&self, channel_name: &str) -> PyResult<Vec<(u64, u64)>> {
Ok(self.index.get_channel_byte_ranges_by_name(channel_name)?)
}
fn get_channel_info_by_name(&self, channel_name: &str) -> Option<(usize, usize, PyChannelInfo)> {
self.index.get_channel_info_by_name(channel_name).map(|(group_idx, channel_idx, channel)| {
let info = PyChannelInfo {
name: channel.name.clone(),
unit: channel.unit.clone(),
comment: None, data_type: PyDataType::from(&channel.data_type),
bit_count: channel.bit_count,
};
(group_idx, channel_idx, info)
})
}
fn find_all_channels_by_name(&self, channel_name: &str) -> Vec<(usize, usize)> {
self.index.find_all_channels_by_name(channel_name)
}
fn get_file_size(&self) -> u64 {
self.index.file_size
}
fn has_resolved_conversions(&self) -> bool {
for group in &self.index.channel_groups {
for channel in &group.channels {
if let Some(conversion) = &channel.conversion {
if conversion.resolved_texts.is_some() || conversion.resolved_conversions.is_some() {
return true;
}
}
}
}
false
}
fn get_conversion_info(&self, group_index: usize, channel_index: usize) -> PyResult<Option<HashMap<String, PyObject>>> {
use pyo3::Python;
let group = self.index.channel_groups.get(group_index)
.ok_or_else(|| MdfException::new_err("Invalid group index"))?;
let channel = group.channels.get(channel_index)
.ok_or_else(|| MdfException::new_err("Invalid channel index"))?;
if let Some(conversion) = &channel.conversion {
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 let Some(_) = &conversion.resolved_conversions {
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)
}
}
fn read_channel_values_by_group_and_name(&self, py: Python, group_name: &str, channel_name: &str, file_path: &str) -> PyResult<Vec<Option<PyObject>>> {
let mut group_index = None;
for (idx, group) in self.index.channel_groups.iter().enumerate() {
if let Some(ref gname) = group.name {
if gname == group_name {
group_index = Some(idx);
break;
}
}
}
let group_idx = group_index.ok_or_else(||
MdfException::new_err(format!("Channel group '{}' not found", group_name))
)?;
let group = &self.index.channel_groups[group_idx];
let mut channel_index = None;
for (idx, channel) in group.channels.iter().enumerate() {
if let Some(ref cname) = channel.name {
if cname == channel_name {
channel_index = Some(idx);
break;
}
}
}
let channel_idx = channel_index.ok_or_else(||
MdfException::new_err(format!("Channel '{}' not found in group '{}'", channel_name, group_name))
)?;
let mut reader = FileRangeReader::new(file_path)?;
let values = self.index.read_channel_values(group_idx, channel_idx, &mut reader)?;
Ok(values.into_iter().map(|opt_val| {
opt_val.map(|dv| decoded_value_to_pyobject(dv, py))
}).collect())
}
fn read_channel_as_series(&self, py: Python, channel_name: &str, file_path: &str) -> PyResult<PyObject> {
let pd = check_pandas_available(py)?;
let start_time_ns = self.index.start_time_ns;
let (group_idx, channel_idx) = self.find_channel_by_name(channel_name)
.ok_or_else(|| MdfException::new_err(format!("Channel '{}' not found", channel_name)))?;
let mut reader = FileRangeReader::new(file_path)?;
let values = self.index.read_channel_values(group_idx, channel_idx, &mut reader)?;
let py_values: Vec<PyObject> = values.into_iter().map(|opt_val| {
opt_val.map(|dv| decoded_value_to_pyobject(dv, py)).unwrap_or_else(|| py.None())
}).collect();
let group = &self.index.channel_groups[group_idx];
let index: PyObject = if let Some(master_idx) = find_master_channel_indexed(&group.channels) {
if master_idx != channel_idx {
let master_values = self.index.read_channel_values(group_idx, master_idx, &mut reader)?;
let py_master_values: Vec<PyObject> = master_values.into_iter().map(|opt_val| {
opt_val.map(|dv| decoded_value_to_pyobject(dv, py)).unwrap_or_else(|| py.None())
}).collect();
if py_master_values.len() != py_values.len() {
return Err(MdfException::new_err(format!(
"Master channel length ({}) does not match data channel length ({}) for channel '{}'",
py_master_values.len(), py_values.len(), channel_name
)));
}
if let Some(start_ns) = start_time_ns {
match create_datetime_index(py, &pd, &py_master_values, start_ns) {
Ok(datetime_index) => datetime_index,
Err(_) => {
py_master_values.to_object(py)
}
}
} else {
py_master_values.to_object(py)
}
} else {
py.None()
}
} else {
py.None()
};
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", channel_name)?;
Ok(series)
}
}
#[gen_stub_pyclass]
#[pyclass]
#[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]
#[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]
#[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]
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(())
}
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 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 PyMDF, PyMdfWriter, PyMdfIndex, 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.PyMDF(\"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_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!(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)?)?;
Ok(())
}
define_stub_info_gatherer!(stub_info);