use crate::base::error::{PmmlError, Result};
use crate::base::{FieldId, SymbolId, Value};
use crate::ir::Ir;
use crate::session::batch::{Batch, BatchCtx, BatchResult};
use crate::session::env::PmmlEnv;
use crate::session::options::SessionOptions;
use crate::session::providers::{CpuProvider, ExecutionProvider};
use ahash::AHashMap;
#[allow(unused_imports)]
use arrow::array::{Array, Float64Array, StringArray};
#[allow(unused_imports)]
use arrow::datatypes::DataType as ArrowDataType;
use arrow::record_batch::RecordBatch;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;
thread_local! {
static THREAD_VALUES: RefCell<Vec<Value>> = const { RefCell::new(Vec::new()) };
}
const STACK_VALUES_THRESHOLD: usize = 64;
#[inline(always)]
pub(crate) fn with_value_buffer<R>(needed: usize, f: impl FnOnce(&mut [Value]) -> R) -> R {
if needed <= STACK_VALUES_THRESHOLD {
let mut buf = [Value::Missing; STACK_VALUES_THRESHOLD];
let slice = &mut buf[..needed];
f(slice)
} else {
THREAD_VALUES.with(|cell| {
let mut values = cell.borrow_mut();
if values.len() < needed {
values.resize(needed, Value::Missing);
} else {
for v in values.iter_mut().take(needed) {
*v = Value::Missing;
}
}
f(&mut values[..needed])
})
}
}
pub struct Session {
pub env: PmmlEnv,
pub options: SessionOptions,
pub ir: Arc<Ir>,
provider: Box<dyn ExecutionProvider>,
name_to_id: AHashMap<String, FieldId>,
name_to_id_std: HashMap<String, FieldId>,
max_field_id: usize,
target_name: Option<String>,
output_fields: Vec<crate::ir::OutputFieldIr>,
symbol_str_to_id: HashMap<String, crate::base::SymbolId>,
symbol_names_vec: Vec<String>,
}
impl Session {
pub fn from_bytes(env: &PmmlEnv, bytes: &[u8], options: SessionOptions) -> Result<Self> {
let raw = crate::xml::unmarshal(bytes)?;
crate::ir::verify_raw(&raw)?;
let ir = crate::ir::lower(raw)?;
crate::ir::verify_ir(&ir)?;
Self::from_ir(env.clone(), ir, options)
}
pub fn from_file(env: &PmmlEnv, path: &str, options: SessionOptions) -> Result<Self> {
let bytes = std::fs::read(path).map_err(|e| PmmlError::Io(e.to_string()))?;
Self::from_bytes(env, &bytes, options)
}
fn from_ir(env: PmmlEnv, ir: Ir, options: SessionOptions) -> Result<Self> {
let provider: Box<dyn ExecutionProvider> = Box::new(CpuProvider::new());
let mut name_to_id: AHashMap<String, FieldId> = AHashMap::new();
let mut name_to_id_std: HashMap<String, FieldId> = HashMap::new();
for (fid, name) in &ir.field_names {
name_to_id.insert(name.clone(), *fid);
name_to_id_std.insert(name.clone(), *fid);
}
let max_field_id = name_to_id
.values()
.map(|fid| fid.as_usize())
.max()
.unwrap_or(0)
+ 1;
let target_name = match &ir.model {
crate::ir::ModelIr::Tree(t) => t
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::Regression(r) => r
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::Mining(m) => m
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::Scorecard(s) => s
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::Clustering(c) => c
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::NaiveBayes(n) => n
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::NearestNeighbor(n) => n
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::SupportVectorMachine(s) => s
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::GeneralRegression(g) => g
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::Association(a) => a
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::RuleSet(r) => r
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::NeuralNetwork(n) => n
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::AnomalyDetection(a) => a
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::Baseline(b) => b
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::GaussianProcess(g) => g
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::Text(t) => t
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::TimeSeries(t) => t
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::Sequence(s) => s
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
crate::ir::ModelIr::BayesianNetwork(b) => b
.mining_schema
.target_field
.and_then(|fid| ir.field_names.get(&fid).cloned()),
};
let output_fields = match &ir.model {
crate::ir::ModelIr::Tree(t) => t.output.clone(),
crate::ir::ModelIr::Regression(r) => r.output.clone(),
crate::ir::ModelIr::Mining(m) => m.output.clone(),
crate::ir::ModelIr::Scorecard(s) => s.output.clone(),
crate::ir::ModelIr::Clustering(c) => c.output.clone(),
crate::ir::ModelIr::NaiveBayes(n) => n.output.clone(),
crate::ir::ModelIr::NearestNeighbor(n) => n.output.clone(),
crate::ir::ModelIr::SupportVectorMachine(s) => s.output.clone(),
crate::ir::ModelIr::GeneralRegression(g) => g.output.clone(),
crate::ir::ModelIr::Association(a) => a.output.clone(),
crate::ir::ModelIr::RuleSet(r) => r.output.clone(),
crate::ir::ModelIr::NeuralNetwork(n) => n.output.clone(),
crate::ir::ModelIr::AnomalyDetection(a) => a.output.clone(),
crate::ir::ModelIr::Baseline(b) => b.output.clone(),
crate::ir::ModelIr::GaussianProcess(g) => g.output.clone(),
crate::ir::ModelIr::Text(t) => t.output.clone(),
crate::ir::ModelIr::TimeSeries(t) => t.output.clone(),
crate::ir::ModelIr::Sequence(s) => s.output.clone(),
crate::ir::ModelIr::BayesianNetwork(b) => b.output.clone(),
};
let symbol_str_to_id: HashMap<String, crate::base::SymbolId> = ir
.symbol_names
.iter()
.map(|(sid, s)| (s.clone(), *sid))
.collect();
let max_symbol_id = ir.symbol_names.keys().map(|sid| sid.0).max().unwrap_or(0) as usize;
let mut symbol_names_vec = vec![String::new(); max_symbol_id + 1];
for (sid, name) in &ir.symbol_names {
let idx = sid.0 as usize;
if idx < symbol_names_vec.len() {
symbol_names_vec[idx] = name.clone();
}
}
Ok(Self {
env,
options,
ir: Arc::new(ir),
provider,
name_to_id,
name_to_id_std,
max_field_id: max_field_id.max(16), target_name,
output_fields,
symbol_str_to_id,
symbol_names_vec,
})
}
pub fn run(&self, batch: &dyn Batch) -> Result<BatchResult> {
if batch.is_empty() {
return Ok(BatchResult::Rows(Vec::new()));
}
#[cfg(all(feature = "simd", not(target_arch = "wasm32")))]
if batch.format() == crate::session::batch::BatchFormat::Columnar {
if let Some(rb) = batch.as_any().downcast_ref::<RecordBatch>() {
if let crate::ir::ModelIr::Regression(reg) = &self.ir.model {
if reg.regression_tables.len() == 1 && rb.num_rows() >= 4 {
let needed = self.max_field_id.max(self.ir.num_fields() + 4);
let mut col_map: Vec<(FieldId, usize)> = Vec::new();
for (col_idx, field) in rb.schema().fields().iter().enumerate() {
if let Some(&fid) = self.name_to_id.get(field.name().as_str()) {
col_map.push((fid, col_idx));
}
}
let mut batch_values: Vec<Vec<Value>> = Vec::with_capacity(rb.num_rows());
for row_idx in 0..rb.num_rows() {
let mut row_vals = vec![Value::Missing; needed];
for (fid, col_idx) in &col_map {
let col = rb.column(*col_idx);
if !col.is_null(row_idx) {
let val = match col.data_type() {
ArrowDataType::Float64 => {
let arr = col
.as_any()
.downcast_ref::<Float64Array>()
.unwrap();
Value::Continuous(arr.value(row_idx))
}
ArrowDataType::Utf8 => {
let arr =
col.as_any().downcast_ref::<StringArray>().unwrap();
let s = arr.value(row_idx);
if let Some(sid) = self.symbol_str_to_id.get(s) {
Value::Discrete(*sid)
} else if let Ok(f) = s.parse::<f64>() {
Value::Continuous(f)
} else {
Value::Missing
}
}
_ => Value::Missing,
};
row_vals[fid.as_usize()] = val;
}
}
batch_values.push(row_vals);
}
let refs: Vec<&[Value]> =
batch_values.iter().map(|v| v.as_slice()).collect();
let simd_results =
crate::engine::simd::evaluate_regression_batch_simd(reg, &refs);
let mut results = Vec::with_capacity(rb.num_rows());
for predicted in simd_results {
let mut output =
HashMap::with_capacity(self.output_fields.len().max(1) + 2);
if self.output_fields.is_empty() {
output.insert("predictedValue".to_string(), predicted);
} else {
for of in &self.output_fields {
match of.feature {
crate::base::field::ResultFeature::PredictedValue => {
output.insert(of.name.clone(), predicted);
}
crate::base::field::ResultFeature::Probability => {
output.insert(of.name.clone(), Value::Continuous(0.0));
}
_ => {
output.insert(of.name.clone(), predicted);
}
}
}
}
let mut final_out = output;
if let Some(tname) = &self.target_name {
final_out.entry(tname.clone()).or_insert(predicted);
}
final_out
.entry("predictedValue".to_string())
.or_insert(predicted);
results.push(final_out);
}
return Ok(BatchResult::Rows(results));
}
}
}
}
let ctx = if batch.format() == crate::session::batch::BatchFormat::Columnar {
if let Some(rb) = batch.as_any().downcast_ref::<RecordBatch>() {
BatchCtx::for_record_batch(
&self.name_to_id,
&self.name_to_id_std,
&self.symbol_str_to_id,
&self.ir.symbol_names,
&self.ir,
self.max_field_id,
&self.output_fields,
self.target_name.as_ref(),
&self.symbol_names_vec,
rb,
)
} else {
BatchCtx::new(
&self.name_to_id,
&self.name_to_id_std,
&self.symbol_str_to_id,
&self.ir.symbol_names,
&self.ir,
self.max_field_id,
&self.output_fields,
self.target_name.as_ref(),
&self.symbol_names_vec,
)
}
} else {
BatchCtx::new(
&self.name_to_id,
&self.name_to_id_std,
&self.symbol_str_to_id,
&self.ir.symbol_names,
&self.ir,
self.max_field_id,
&self.output_fields,
self.target_name.as_ref(),
&self.symbol_names_vec,
)
};
self.provider.eval_batch(&self.ir, batch, &ctx)
}
pub fn field_id(&self, name: &str) -> Option<FieldId> {
self.name_to_id.get(name).copied()
}
pub fn symbol_id(&self, s: &str) -> Option<SymbolId> {
self.symbol_str_to_id.get(s).copied()
}
pub fn string_to_value(&self, field_name: &str, s: &str) -> Value {
let fid = self.field_id(field_name);
let (dt, op) = if let Some(f) = fid {
if let Some(meta) = self.ir.data_dictionary.iter().find(|m| m.field_id == f) {
(Some(meta.data_type), Some(meta.op_type))
} else {
(None, None)
}
} else {
(None, None)
};
crate::session::input::string_to_value(field_name, s, fid, dt, op, &self.symbol_str_to_id)
}
pub fn num_active_fields(&self) -> usize {
match &self.ir.model {
crate::ir::ModelIr::Tree(t) => t.mining_schema.active_fields.len(),
crate::ir::ModelIr::Regression(r) => r.mining_schema.active_fields.len(),
crate::ir::ModelIr::Mining(m) => m.mining_schema.active_fields.len(),
crate::ir::ModelIr::Scorecard(s) => s.mining_schema.active_fields.len(),
crate::ir::ModelIr::Clustering(c) => c.mining_schema.active_fields.len(),
crate::ir::ModelIr::NaiveBayes(n) => n.mining_schema.active_fields.len(),
crate::ir::ModelIr::NearestNeighbor(n) => n.mining_schema.active_fields.len(),
crate::ir::ModelIr::SupportVectorMachine(s) => s.mining_schema.active_fields.len(),
crate::ir::ModelIr::GeneralRegression(g) => g.mining_schema.active_fields.len(),
crate::ir::ModelIr::Association(a) => a.mining_schema.active_fields.len(),
crate::ir::ModelIr::RuleSet(r) => r.mining_schema.active_fields.len(),
crate::ir::ModelIr::NeuralNetwork(n) => n.mining_schema.active_fields.len(),
crate::ir::ModelIr::AnomalyDetection(a) => a.mining_schema.active_fields.len(),
crate::ir::ModelIr::Baseline(b) => b.mining_schema.active_fields.len(),
crate::ir::ModelIr::GaussianProcess(g) => g.mining_schema.active_fields.len(),
crate::ir::ModelIr::Text(t) => t.mining_schema.active_fields.len(),
crate::ir::ModelIr::TimeSeries(t) => t.mining_schema.active_fields.len(),
crate::ir::ModelIr::Sequence(s) => s.mining_schema.active_fields.len(),
crate::ir::ModelIr::BayesianNetwork(b) => b.mining_schema.active_fields.len(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::base::Value;
use std::collections::HashMap;
#[test]
fn session_iris_tree() {
let xml = std::fs::read("bench/pmml/DecisionTreeIris.pmml")
.or_else(|_| std::fs::read("../../bench/pmml/DecisionTreeIris.pmml"))
.unwrap();
let env = PmmlEnv::new();
let opts = SessionOptions::default();
let sess = Session::from_bytes(&env, &xml, opts).unwrap();
let mut input = HashMap::new();
input.insert("Petal.Length".to_string(), Value::Continuous(1.4)); input.insert("Petal.Width".to_string(), Value::Continuous(0.2));
let out = sess
.run(&input as &dyn crate::session::batch::Batch)
.unwrap()
.into_single()
.unwrap();
let pred = out.get("predictedValue").unwrap();
match pred {
Value::Discrete(sid) => {
assert_ne!(sid.0, u32::MAX);
}
_ => panic!("expected discrete"),
}
}
#[test]
fn session_iris_virginica() {
let xml = std::fs::read("bench/pmml/DecisionTreeIris.pmml")
.or_else(|_| std::fs::read("../../bench/pmml/DecisionTreeIris.pmml"))
.unwrap();
let env = PmmlEnv::new();
let sess = Session::from_bytes(&env, &xml, SessionOptions::default()).unwrap();
let mut input = HashMap::new();
input.insert("Petal.Length".to_string(), Value::Continuous(6.0));
input.insert("Petal.Width".to_string(), Value::Continuous(2.0));
let out = sess
.run(&input as &dyn crate::session::batch::Batch)
.unwrap()
.into_single()
.unwrap();
assert!(out.contains_key("predictedValue"));
}
}