use crate::base::Value;
use crate::ir::{BuiltinId, DerivedFieldIr, LagAggregate, LinearNorm, Op, SymbolIdOrContinuous};
use chrono::Timelike;
use std::cell::RefCell;
use std::collections::HashMap;
use super::builtin::{eval_builtin, eval_string_builtin};
use super::mapvalues::eval_mapvalues;
use std::collections::VecDeque;
thread_local! {
static LAG_BUFFER: RefCell<HashMap<crate::base::FieldId, VecDeque<Value>>> = RefCell::new(HashMap::new());
}
#[allow(dead_code)]
fn lag_get(field: crate::base::FieldId, n: usize) -> Value {
LAG_BUFFER.with(|buf| {
let map = buf.borrow();
if let Some(hist) = map.get(&field) {
if n == 0 {
return hist.back().copied().unwrap_or(Value::Missing);
}
if hist.len() > n {
return hist[hist.len() - 1 - n];
}
}
Value::Missing
})
}
fn lag_push(field: crate::base::FieldId, val: Value) {
LAG_BUFFER.with(|buf| {
let mut map = buf.borrow_mut();
let hist = map.entry(field).or_insert_with(VecDeque::new);
hist.push_back(val);
if hist.len() > 128 {
hist.pop_front();
}
})
}
pub fn lag_update(field: crate::base::FieldId, val: Value) {
lag_push(field, val);
}
pub fn lag_clear() {
LAG_BUFFER.with(|buf| buf.borrow_mut().clear());
}
pub fn eval_derived_fields(fields: &[DerivedFieldIr], values: &mut [Value]) -> Result<(), String> {
let snapshot: Vec<Value> = values.to_vec();
for (idx, &val) in snapshot.iter().enumerate() {
if !val.is_missing() {
lag_push(crate::base::FieldId(idx as u32), val);
}
}
for df in fields {
let v = eval_bytecode(&df.bytecode, values)?;
let idx = df.field_id.as_usize();
if idx < values.len() {
values[idx] = v;
LAG_BUFFER.with(|buf| {
let mut map = buf.borrow_mut();
if let Some(hist) = map.get_mut(&df.field_id) {
if hist.back() == Some(&snapshot[idx]) {
hist.pop_back();
}
hist.push_back(v);
if hist.len() > 128 {
hist.pop_front();
}
} else {
let mut dq = VecDeque::new();
dq.push_back(v);
map.insert(df.field_id, dq);
}
});
}
}
Ok(())
}
fn value_to_f64(v: Value) -> Option<f64> {
match v {
Value::Continuous(f) => Some(f),
Value::Missing => None,
Value::Discrete(_) => None,
}
}
#[allow(dead_code)]
fn value_to_string(v: Value) -> String {
match v {
Value::Continuous(f) => {
if f.fract() == 0.0 {
format!("{}", f as i64)
} else {
f.to_string()
}
}
Value::Discrete(sid) => format!("{:?}", sid), Value::Missing => "Missing".into(),
}
}
thread_local! {
static SYMBOL_STR_MAP: RefCell<HashMap<crate::base::SymbolId, String>> = RefCell::new(HashMap::new());
}
pub fn vm_set_symbol_map(map: HashMap<crate::base::SymbolId, String>) {
SYMBOL_STR_MAP.with(|m| *m.borrow_mut() = map);
}
fn discrete_to_string(sid: crate::base::SymbolId) -> String {
SYMBOL_STR_MAP.with(|m| {
m.borrow()
.get(&sid)
.cloned()
.unwrap_or_else(|| format!("{:?}", sid))
})
}
fn value_to_string_with_symbols(v: Value) -> String {
match v {
Value::Continuous(f) => {
if f.fract() == 0.0 {
format!("{}", f as i64)
} else {
f.to_string()
}
}
Value::Discrete(sid) => discrete_to_string(sid),
Value::Missing => "Missing".into(),
}
}
fn f64_to_value(f: f64) -> Value {
if f.is_nan() {
Value::Missing
} else {
Value::Continuous(f)
}
}
fn eval_text_index(text: Value, term: Value) -> Value {
if text.is_missing() || term.is_missing() {
return Value::Missing;
}
let s = value_to_string_with_symbols(text);
let t = value_to_string_with_symbols(term);
if let Some(pos) = s.find(&t) {
Value::Continuous((pos + 1) as f64)
} else {
Value::Continuous(0.0)
}
}
fn eval_aggregate(func: BuiltinId, args: &[Value]) -> Value {
let nums: Vec<f64> = args.iter().filter_map(|v| value_to_f64(*v)).collect();
match func {
BuiltinId::AggregateCount => {
Value::Continuous(args.iter().filter(|v| !v.is_missing()).count() as f64)
}
BuiltinId::AggregateMultiset => {
Value::Continuous(args.iter().filter(|v| !v.is_missing()).count() as f64)
}
BuiltinId::AggregateSum => {
if nums.is_empty() {
Value::Missing
} else {
Value::Continuous(nums.iter().sum())
}
}
BuiltinId::AggregateAvg => {
if nums.is_empty() {
Value::Missing
} else {
Value::Continuous(nums.iter().sum::<f64>() / nums.len() as f64)
}
}
BuiltinId::AggregateMin => {
if nums.is_empty() {
Value::Missing
} else {
Value::Continuous(nums.iter().cloned().fold(f64::INFINITY, f64::min))
}
}
BuiltinId::AggregateMax => {
if nums.is_empty() {
Value::Missing
} else {
Value::Continuous(nums.iter().cloned().fold(f64::NEG_INFINITY, f64::max))
}
}
_ => Value::Missing,
}
}
fn eval_norm_continuous(val: Value, linear_norms: &[LinearNorm]) -> Value {
let x = match val {
Value::Continuous(f) => f,
Value::Missing => return Value::Missing,
Value::Discrete(_) => return Value::Missing,
};
if linear_norms.is_empty() {
return Value::Missing;
}
if linear_norms.len() == 1 {
return Value::Continuous(linear_norms[0].norm);
}
if x <= linear_norms[0].orig {
return Value::Continuous(linear_norms[0].norm);
}
if x >= linear_norms[linear_norms.len() - 1].orig {
return Value::Continuous(linear_norms[linear_norms.len() - 1].norm);
}
for w in linear_norms.windows(2) {
let a = w[0];
let b = w[1];
if x >= a.orig && x <= b.orig {
let t = (x - a.orig) / (b.orig - a.orig);
let norm = a.norm + t * (b.norm - a.norm);
return Value::Continuous(norm);
}
}
Value::Missing
}
fn eval_norm_discrete(
val: Value,
expected: crate::base::SymbolId,
map_missing_to: Option<f64>,
) -> Value {
if val.is_missing() {
return map_missing_to
.map(Value::Continuous)
.unwrap_or(Value::Missing);
}
match val {
Value::Discrete(sid) => {
if sid == expected {
Value::Continuous(1.0)
} else {
Value::Continuous(0.0)
}
}
Value::Continuous(_) => Value::Continuous(0.0),
Value::Missing => map_missing_to
.map(Value::Continuous)
.unwrap_or(Value::Missing),
}
}
fn eval_lag(field: crate::base::FieldId, n: usize, aggregate: LagAggregate) -> Value {
if aggregate == LagAggregate::None {
return lag_get(field, n);
}
let vals: Vec<Value> = LAG_BUFFER.with(|buf| {
let map = buf.borrow();
if let Some(hist) = map.get(&field) {
if hist.len() >= n && n > 0 {
hist.iter().rev().take(n).copied().collect()
} else if n == 0 {
hist.iter().rev().take(1).copied().collect()
} else {
vec![]
}
} else {
vec![]
}
});
if vals.is_empty() {
return Value::Missing;
}
let nums: Vec<f64> = vals.iter().filter_map(|v| value_to_f64(*v)).collect();
if nums.is_empty() {
return Value::Missing;
}
match aggregate {
LagAggregate::None => vals.first().copied().unwrap_or(Value::Missing),
LagAggregate::Avg => Value::Continuous(nums.iter().sum::<f64>() / nums.len() as f64),
LagAggregate::Min => Value::Continuous(nums.iter().cloned().fold(f64::INFINITY, f64::min)),
LagAggregate::Max => {
Value::Continuous(nums.iter().cloned().fold(f64::NEG_INFINITY, f64::max))
}
LagAggregate::Sum => Value::Continuous(nums.iter().sum()),
LagAggregate::Product => Value::Continuous(nums.iter().product()),
LagAggregate::Median => {
let mut v = nums.clone();
v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let mid = v.len() / 2;
if v.len() % 2 == 1 {
Value::Continuous(v[mid])
} else {
Value::Continuous((v[mid - 1] + v[mid]) / 2.0)
}
}
LagAggregate::Stddev => {
let mean = nums.iter().sum::<f64>() / nums.len() as f64;
let var = nums.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / nums.len() as f64;
Value::Continuous(var.sqrt())
}
}
}
fn parse_date_str(s: &str) -> Option<chrono::NaiveDate> {
if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
return Some(d);
}
if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y/%m/%d") {
return Some(d);
}
if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%m/%d/%Y") {
return Some(d);
}
if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S") {
return Some(dt.date());
}
if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S") {
return Some(dt.date());
}
None
}
fn parse_datetime_str(s: &str) -> Option<chrono::NaiveDateTime> {
if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S") {
return Some(dt);
}
if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S") {
return Some(dt);
}
if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
return Some(d.and_hms_opt(0, 0, 0).unwrap());
}
None
}
fn parse_time_str(s: &str) -> Option<chrono::NaiveTime> {
if let Ok(t) = chrono::NaiveTime::parse_from_str(s, "%H:%M:%S") {
return Some(t);
}
if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S") {
return Some(dt.time());
}
if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S") {
return Some(dt.time());
}
None
}
fn eval_date_days_since_year(val: Value, ref_year: i32) -> Value {
if val.is_missing() {
return Value::Missing;
}
let s = value_to_string_with_symbols(val);
if let Some(d) = parse_date_str(&s) {
if let Some(ref_date) = chrono::NaiveDate::from_ymd_opt(ref_year, 1, 1) {
let diff = d.signed_duration_since(ref_date).num_days();
return Value::Continuous(diff as f64);
}
}
if let Some(dt) = parse_datetime_str(&s) {
if let Some(ref_date) = chrono::NaiveDate::from_ymd_opt(ref_year, 1, 1) {
let ref_dt = ref_date.and_hms_opt(0, 0, 0).unwrap();
let diff = dt.signed_duration_since(ref_dt).num_days();
return Value::Continuous(diff as f64);
}
}
if let Some(f) = value_to_f64(val) {
return Value::Continuous(f);
}
Value::Missing
}
fn eval_date_seconds_since_year(val: Value, ref_year: i32) -> Value {
if val.is_missing() {
return Value::Missing;
}
let s = value_to_string_with_symbols(val);
if let Some(dt) = parse_datetime_str(&s) {
if let Some(ref_date) = chrono::NaiveDate::from_ymd_opt(ref_year, 1, 1) {
let ref_dt = ref_date.and_hms_opt(0, 0, 0).unwrap();
let diff = dt.signed_duration_since(ref_dt).num_seconds();
return Value::Continuous(diff as f64);
}
}
if let Some(d) = parse_date_str(&s) {
if let Some(ref_date) = chrono::NaiveDate::from_ymd_opt(ref_year, 1, 1) {
let ref_dt = ref_date.and_hms_opt(0, 0, 0).unwrap();
let dt = d.and_hms_opt(0, 0, 0).unwrap();
let diff = dt.signed_duration_since(ref_dt).num_seconds();
return Value::Continuous(diff as f64);
}
}
if let Some(f) = value_to_f64(val) {
return Value::Continuous(f);
}
Value::Missing
}
fn eval_date_seconds_since_midnight(val: Value) -> Value {
if val.is_missing() {
return Value::Missing;
}
let s = value_to_string_with_symbols(val);
if let Some(t) = parse_time_str(&s) {
return Value::Continuous(t.num_seconds_from_midnight() as f64);
}
if let Some(dt) = parse_datetime_str(&s) {
return Value::Continuous(dt.time().num_seconds_from_midnight() as f64);
}
if let Some(f) = value_to_f64(val) {
return Value::Continuous(f);
}
Value::Missing
}
fn eval_date_days_since_epoch(val: Value, epoch_year: i32) -> Value {
eval_date_days_since_year(val, epoch_year)
}
fn eval_datetime_seconds_since_epoch(val: Value, epoch_year: i32) -> Value {
eval_date_seconds_since_year(val, epoch_year)
}
fn eval_normal_cdf(x: f64, mean: f64, std: f64) -> f64 {
if std <= 0.0 {
return f64::NAN;
}
use statrs::distribution::{ContinuousCDF, Normal};
if let Ok(n) = Normal::new(mean, std) {
n.cdf(x)
} else {
f64::NAN
}
}
fn eval_normal_pdf(x: f64, mean: f64, std: f64) -> f64 {
if std <= 0.0 {
return f64::NAN;
}
use statrs::distribution::{Continuous, Normal};
if let Ok(n) = Normal::new(mean, std) {
n.pdf(x)
} else {
f64::NAN
}
}
fn eval_normal_idf(p: f64, mean: f64, std: f64) -> f64 {
if std <= 0.0 || p <= 0.0 || p >= 1.0 {
return f64::NAN;
}
use statrs::distribution::{ContinuousCDF, Normal};
if let Ok(n) = Normal::new(mean, std) {
n.inverse_cdf(p)
} else {
f64::NAN
}
}
fn eval_bytecode(bytecode: &[Op], values: &[Value]) -> Result<Value, String> {
if bytecode.is_empty() {
return Ok(Value::Missing);
}
let mut stack: Vec<Value> = Vec::with_capacity(8);
for op in bytecode {
match op {
Op::PushField(fid) => {
let idx = fid.as_usize();
let v = if idx < values.len() {
values[idx]
} else {
Value::Missing
};
stack.push(v);
}
Op::PushConst(c) => {
let v = match c {
SymbolIdOrContinuous::Continuous(f) => Value::Continuous(*f),
SymbolIdOrContinuous::Symbol(s) => Value::Discrete(*s),
SymbolIdOrContinuous::Missing => Value::Missing,
};
stack.push(v);
}
Op::CallBuiltin(id, arity) => {
let arity = *arity as usize;
if stack.len() < arity {
stack.push(Value::Missing);
continue;
}
let args: Vec<Value> = stack.drain(stack.len() - arity..).collect();
let result = match id {
BuiltinId::Add
| BuiltinId::Sub
| BuiltinId::Mul
| BuiltinId::Div
| BuiltinId::Pow
| BuiltinId::Log
| BuiltinId::Log10
| BuiltinId::Ln
| BuiltinId::Exp
| BuiltinId::Sqrt
| BuiltinId::Abs
| BuiltinId::Floor
| BuiltinId::Ceil
| BuiltinId::Round
| BuiltinId::Cbrt
| BuiltinId::Sign
| BuiltinId::Remainder
| BuiltinId::Modulo
| BuiltinId::Rint
| BuiltinId::Expm1
| BuiltinId::Ln1p
| BuiltinId::Hypot
| BuiltinId::Atan2
| BuiltinId::Sin
| BuiltinId::Cos
| BuiltinId::Tan
| BuiltinId::Asin
| BuiltinId::Acos
| BuiltinId::Atan
| BuiltinId::Sinh
| BuiltinId::Cosh
| BuiltinId::Tanh
| BuiltinId::Min
| BuiltinId::Max
| BuiltinId::Median
| BuiltinId::ProductOp
| BuiltinId::SumOp
| BuiltinId::AvgOp
| BuiltinId::Mean
| BuiltinId::StdDev
| BuiltinId::Variance
| BuiltinId::ErfOp => {
let has_missing = args.iter().any(|v| v.is_missing());
let is_aggregate = matches!(
id,
BuiltinId::Min
| BuiltinId::Max
| BuiltinId::Median
| BuiltinId::ProductOp
| BuiltinId::SumOp
| BuiltinId::AvgOp
| BuiltinId::Mean
| BuiltinId::StdDev
| BuiltinId::Variance
);
if has_missing && !is_aggregate {
Value::Missing
} else {
let filtered: Vec<Value> = if is_aggregate {
args.iter().filter(|v| !v.is_missing()).copied().collect()
} else {
args.clone()
};
if filtered.is_empty() && is_aggregate {
Value::Missing
} else {
let nums: Vec<f64> =
filtered.iter().filter_map(|v| value_to_f64(*v)).collect();
if nums.len() != filtered.len() {
Value::Missing
} else if let Some(f) = eval_builtin(*id, &nums) {
f64_to_value(f)
} else {
Value::Missing
}
}
}
}
BuiltinId::NormalCdf => {
if args.len() < 3 || args.iter().any(|v| v.is_missing()) {
Value::Missing
} else if let (Some(x), Some(m), Some(s)) = (
value_to_f64(args[0]),
value_to_f64(args[1]),
value_to_f64(args[2]),
) {
f64_to_value(eval_normal_cdf(x, m, s))
} else {
Value::Missing
}
}
BuiltinId::NormalPdf => {
if args.len() < 3 || args.iter().any(|v| v.is_missing()) {
Value::Missing
} else if let (Some(x), Some(m), Some(s)) = (
value_to_f64(args[0]),
value_to_f64(args[1]),
value_to_f64(args[2]),
) {
f64_to_value(eval_normal_pdf(x, m, s))
} else {
Value::Missing
}
}
BuiltinId::NormalIdf => {
if args.len() < 3 || args.iter().any(|v| v.is_missing()) {
Value::Missing
} else if let (Some(p), Some(m), Some(s)) = (
value_to_f64(args[0]),
value_to_f64(args[1]),
value_to_f64(args[2]),
) {
f64_to_value(eval_normal_idf(p, m, s))
} else {
Value::Missing
}
}
BuiltinId::StdNormalCdf => {
if args.is_empty() || args[0].is_missing() {
Value::Missing
} else if let Some(x) = value_to_f64(args[0]) {
f64_to_value(eval_normal_cdf(x, 0.0, 1.0))
} else {
Value::Missing
}
}
BuiltinId::StdNormalPdf => {
if args.is_empty() || args[0].is_missing() {
Value::Missing
} else if let Some(x) = value_to_f64(args[0]) {
f64_to_value(eval_normal_pdf(x, 0.0, 1.0))
} else {
Value::Missing
}
}
BuiltinId::StdNormalIdf => {
if args.is_empty() || args[0].is_missing() {
Value::Missing
} else if let Some(p) = value_to_f64(args[0]) {
f64_to_value(eval_normal_idf(p, 0.0, 1.0))
} else {
Value::Missing
}
}
BuiltinId::DateDaysSinceYear => {
if args.len() < 2 || args[0].is_missing() || args[1].is_missing() {
Value::Missing
} else if let Some(y) = value_to_f64(args[1]) {
eval_date_days_since_year(args[0], y as i32)
} else {
Value::Missing
}
}
BuiltinId::DateSecondsSinceYear => {
if args.len() < 2 || args[0].is_missing() || args[1].is_missing() {
Value::Missing
} else if let Some(y) = value_to_f64(args[1]) {
eval_date_seconds_since_year(args[0], y as i32)
} else {
Value::Missing
}
}
BuiltinId::DateSecondsSinceMidnight => {
if args.is_empty() || args[0].is_missing() {
Value::Missing
} else {
eval_date_seconds_since_midnight(args[0])
}
}
BuiltinId::DateDaysSince1960
| BuiltinId::DateDaysSince1970
| BuiltinId::DateDaysSince1980 => {
if args.is_empty() || args[0].is_missing() {
Value::Missing
} else {
let y = match id {
BuiltinId::DateDaysSince1960 => 1960,
BuiltinId::DateDaysSince1970 => 1970,
BuiltinId::DateDaysSince1980 => 1980,
_ => 1970,
};
eval_date_days_since_epoch(args[0], y)
}
}
BuiltinId::DateTimeSecondsSince1960
| BuiltinId::DateTimeSecondsSince1970
| BuiltinId::DateTimeSecondsSince1980
| BuiltinId::DateTimeSecondsSince0 => {
if args.is_empty() || args[0].is_missing() {
Value::Missing
} else {
let y = match id {
BuiltinId::DateTimeSecondsSince1960 => 1960,
BuiltinId::DateTimeSecondsSince1970 => 1970,
BuiltinId::DateTimeSecondsSince1980 => 1980,
BuiltinId::DateTimeSecondsSince0 => 1970, _ => 1970,
};
eval_datetime_seconds_since_epoch(args[0], y)
}
}
BuiltinId::TimeSeconds => {
if args.is_empty() || args[0].is_missing() {
Value::Missing
} else {
eval_date_seconds_since_midnight(args[0])
}
}
BuiltinId::Uppercase
| BuiltinId::Lowercase
| BuiltinId::TrimBlanks
| BuiltinId::NormalizeSpace
| BuiltinId::Concat
| BuiltinId::Substring
| BuiltinId::StringLength
| BuiltinId::Replace
| BuiltinId::Matches
| BuiltinId::FormatNumber
| BuiltinId::FormatDatetime => {
let strs: Vec<String> = args
.iter()
.map(|v| value_to_string_with_symbols(*v))
.collect();
match id {
BuiltinId::StringLength => {
if let Some(s) = strs.first() {
Value::Continuous(s.len() as f64)
} else {
Value::Missing
}
}
BuiltinId::Matches => {
if strs.len() >= 2 {
let input = &strs[0];
let pat = &strs[1];
match regex::Regex::new(pat) {
Ok(re) => Value::Continuous(if re.find(input).is_some() {
1.0
} else {
0.0
}),
Err(_) => Value::Continuous(if input.contains(pat) {
1.0
} else {
0.0
}),
}
} else {
Value::Missing
}
}
_ => {
if let Some(s) = eval_string_builtin(*id, &strs) {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut h = DefaultHasher::new();
s.hash(&mut h);
let sid =
crate::base::SymbolId((h.finish() & 0x7FFF_FFFF) as u32);
SYMBOL_STR_MAP.with(|m| m.borrow_mut().insert(sid, s.clone()));
Value::Discrete(sid)
} else {
Value::Missing
}
}
}
}
BuiltinId::TextIndex => {
if args.len() >= 2 {
eval_text_index(args[0], args[1])
} else {
Value::Missing
}
}
BuiltinId::AggregateCount
| BuiltinId::AggregateSum
| BuiltinId::AggregateAvg
| BuiltinId::AggregateMin
| BuiltinId::AggregateMax
| BuiltinId::AggregateMultiset => eval_aggregate(*id, &args),
BuiltinId::Lag => {
if args.len() == 2 {
if let Value::Continuous(n) = args[1] {
if n == 0.0 {
args[0]
} else {
Value::Missing
}
} else {
Value::Missing
}
} else if args.len() == 1 {
Value::Missing
} else {
Value::Missing
}
}
BuiltinId::NormContinuousOp | BuiltinId::NormDiscreteOp => Value::Missing,
BuiltinId::Equal
| BuiltinId::NotEqual
| BuiltinId::LessThan
| BuiltinId::LessOrEqual
| BuiltinId::GreaterThan
| BuiltinId::GreaterOrEqual => {
if args.len() < 2 {
Value::Missing
} else if args[0].is_missing() || args[1].is_missing() {
Value::Missing
} else {
let eq = match (args[0], args[1]) {
(Value::Continuous(a), Value::Continuous(b)) => {
(a - b).abs() < 1e-9
}
(Value::Discrete(a), Value::Discrete(b)) => a == b,
_ => {
let sa = value_to_string_with_symbols(args[0]);
let sb = value_to_string_with_symbols(args[1]);
sa == sb
}
};
let res = match id {
BuiltinId::Equal => eq,
BuiltinId::NotEqual => !eq,
BuiltinId::LessThan => {
matches!((args[0], args[1]), (Value::Continuous(a), Value::Continuous(b)) if a < b)
}
BuiltinId::LessOrEqual => {
matches!((args[0], args[1]), (Value::Continuous(a), Value::Continuous(b)) if a <= b)
}
BuiltinId::GreaterThan => {
matches!((args[0], args[1]), (Value::Continuous(a), Value::Continuous(b)) if a > b)
}
BuiltinId::GreaterOrEqual => {
matches!((args[0], args[1]), (Value::Continuous(a), Value::Continuous(b)) if a >= b)
}
_ => false,
};
Value::Continuous(if res { 1.0 } else { 0.0 })
}
}
BuiltinId::IsIn | BuiltinId::IsNotIn => {
if args.is_empty() {
Value::Missing
} else {
let target = args[0];
if target.is_missing() {
let has_missing = args[1..].iter().any(|v| v.is_missing());
let is_in = has_missing;
let res = if *id == BuiltinId::IsIn {
is_in
} else {
!is_in
};
Value::Continuous(if res { 1.0 } else { 0.0 })
} else {
let is_in = args[1..].iter().any(|v| {
if target.is_missing() && v.is_missing() {
true
} else if let (Value::Discrete(a), Value::Discrete(b)) =
(target, *v)
{
a == b
} else if let (Value::Continuous(a), Value::Continuous(b)) =
(target, *v)
{
(a - b).abs() < 1e-9
} else {
let sa = value_to_string_with_symbols(target);
let sb = value_to_string_with_symbols(*v);
sa == sb
}
});
let res = if *id == BuiltinId::IsIn {
is_in
} else {
!is_in
};
Value::Continuous(if res { 1.0 } else { 0.0 })
}
}
}
BuiltinId::And | BuiltinId::Or => {
if args.iter().any(|v| v.is_missing()) {
Value::Missing
} else {
let bools: Vec<bool> = args
.iter()
.map(|v| match v {
Value::Continuous(f) => *f != 0.0,
Value::Discrete(sid) => sid.0 != 0,
Value::Missing => false,
})
.collect();
let res = match id {
BuiltinId::And => bools.iter().all(|b| *b),
BuiltinId::Or => bools.iter().any(|b| *b),
_ => false,
};
Value::Continuous(if res { 1.0 } else { 0.0 })
}
}
BuiltinId::Not => {
if args.is_empty() || args[0].is_missing() {
Value::Missing
} else {
let b = match args[0] {
Value::Continuous(f) => f == 0.0,
Value::Discrete(sid) => sid.0 == 0,
Value::Missing => false,
};
Value::Continuous(if b { 1.0 } else { 0.0 })
}
}
BuiltinId::IsMissing => {
if args.is_empty() {
Value::Missing
} else {
Value::Continuous(if args[0].is_missing() { 1.0 } else { 0.0 })
}
}
BuiltinId::IsNotMissing => {
if args.is_empty() {
Value::Missing
} else {
Value::Continuous(if !args[0].is_missing() { 1.0 } else { 0.0 })
}
}
BuiltinId::IsValid => {
if args.is_empty() {
Value::Missing
} else {
let is_valid = match args[0] {
Value::Missing => false,
Value::Continuous(f) => !f.is_nan(),
Value::Discrete(_) => true,
};
Value::Continuous(if is_valid { 1.0 } else { 0.0 })
}
}
BuiltinId::IsNotValid => {
if args.is_empty() {
Value::Missing
} else {
let is_not_valid = match args[0] {
Value::Missing => false, Value::Continuous(f) => f.is_nan(),
Value::Discrete(_) => false,
};
Value::Continuous(if is_not_valid { 1.0 } else { 0.0 })
}
}
BuiltinId::If => {
if args.len() < 2 {
Value::Missing
} else if args.len() == 2 {
let cond = match args[0] {
Value::Continuous(f) => f != 0.0,
Value::Discrete(sid) => sid.0 != 0,
Value::Missing => false,
};
if cond {
args[1]
} else {
Value::Missing
}
} else {
let cond = match args[0] {
Value::Continuous(f) => f != 0.0,
Value::Discrete(sid) => sid.0 != 0,
Value::Missing => false,
};
if cond {
args[1]
} else {
args[2]
}
}
}
BuiltinId::Threshold => {
if args.len() < 2 || args[0].is_missing() || args[1].is_missing() {
Value::Missing
} else if let (Value::Continuous(v), Value::Continuous(t)) =
(args[0], args[1])
{
Value::Continuous(if v > t { 1.0 } else { 0.0 })
} else {
Value::Missing
}
}
BuiltinId::Unknown => Value::Missing,
};
stack.push(result);
}
Op::JumpIfMissing { target } => {
if let Some(top) = stack.last() {
if top.is_missing() {
let _ = target;
}
}
}
Op::MapValues { table, default } => {
let input = stack.pop().unwrap_or(Value::Missing);
let res = eval_mapvalues(input, table, *default);
stack.push(res);
}
Op::Discretize {
bins,
default_value,
map_missing_to,
} => {
let input = stack.pop().unwrap_or(Value::Missing);
let res = if input.is_missing() {
if let Some(missing_val) = map_missing_to {
Value::Discrete(*missing_val)
} else if let Some(def) = default_value {
Value::Discrete(*def)
} else {
Value::Missing
}
} else if let Value::Continuous(v) = input {
let mut found = None;
for b in bins {
let left_ok = if b.left_closed {
v >= b.interval_low
} else {
v > b.interval_low
};
let right_ok = if b.right_closed {
v <= b.interval_high
} else {
v < b.interval_high
};
if left_ok && right_ok {
found = Some(Value::Discrete(b.bin_value));
break;
}
}
if let Some(val) = found {
val
} else if let Some(def) = default_value {
Value::Discrete(*def)
} else {
Value::Missing
}
} else {
if let Some(def) = default_value {
Value::Discrete(*def)
} else {
Value::Missing
}
};
stack.push(res);
}
Op::NormContinuous {
field: _,
linear_norms,
} => {
let input = stack.pop().unwrap_or(Value::Missing);
let res = eval_norm_continuous(input, linear_norms);
stack.push(res);
}
Op::NormDiscrete {
field: _,
value,
map_missing_to,
} => {
let input = stack.pop().unwrap_or(Value::Missing);
let res = eval_norm_discrete(input, *value, *map_missing_to);
stack.push(res);
}
Op::Lag {
field,
n,
aggregate,
} => {
let res = eval_lag(*field, *n, *aggregate);
stack.push(res);
}
Op::MapValuesMulti {
inputs,
table,
default,
} => {
let n = inputs.len();
let mut popped = Vec::with_capacity(n);
for _ in 0..n {
popped.push(stack.pop().unwrap_or(Value::Missing));
}
popped.reverse();
let mut key = Vec::with_capacity(n);
let mut missing = false;
for v in &popped {
match v {
Value::Discrete(sid) => key.push(*sid),
Value::Missing => {
missing = true;
break;
}
Value::Continuous(_) => {
missing = true;
break;
}
}
}
let res = if missing {
default.map(Value::Discrete).unwrap_or(Value::Missing)
} else {
let mut found = None;
for (k, v) in table {
if k == &key {
found = Some(Value::Discrete(*v));
break;
}
}
found.unwrap_or_else(|| default.map(Value::Discrete).unwrap_or(Value::Missing))
};
stack.push(res);
let _ = inputs;
}
Op::CallDefine { name, arity } => {
for _ in 0..*arity {
stack.pop();
}
stack.push(Value::Missing);
let _ = name;
}
}
}
Ok(stack.pop().unwrap_or(Value::Missing))
}
pub fn eval_ops(ops: &[Op], values: &[Value]) -> Value {
eval_bytecode(ops, values).unwrap_or(Value::Missing)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::base::Value;
use crate::ir::{DiscretizeBin, LinearNorm};
#[test]
fn empty_bytecode() {
let mut vals = vec![Value::Continuous(1.0)];
let res = eval_derived_fields(&[], &mut vals);
assert!(res.is_ok());
}
#[test]
fn builtin_arithmetic() {
let mut vals = vec![Value::Continuous(2.0), Value::Continuous(3.0)];
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::PushField(crate::base::FieldId(1)),
Op::CallBuiltin(BuiltinId::Add, 2),
];
let res = eval_bytecode(&bytecode, &vals).unwrap();
assert_eq!(res, Value::Continuous(5.0));
}
#[test]
fn builtin_text_index() {
use crate::base::SymbolId;
let vals = vec![Value::Discrete(SymbolId(1)), Value::Discrete(SymbolId(2))];
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::PushField(crate::base::FieldId(1)),
Op::CallBuiltin(BuiltinId::TextIndex, 2),
];
let res = eval_bytecode(&bytecode, &vals).unwrap();
assert_eq!(res, Value::Continuous(0.0));
}
#[test]
fn discretize_bin() {
let bins = vec![
DiscretizeBin {
bin_value: crate::base::SymbolId(10),
interval_low: 0.0,
interval_high: 10.0,
left_closed: true,
right_closed: false,
},
DiscretizeBin {
bin_value: crate::base::SymbolId(20),
interval_low: 10.0,
interval_high: 20.0,
left_closed: true,
right_closed: true,
},
];
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::Discretize {
bins,
default_value: None,
map_missing_to: None,
},
];
let vals = vec![Value::Continuous(5.0)];
let res = eval_bytecode(&bytecode, &vals).unwrap();
assert_eq!(res, Value::Discrete(crate::base::SymbolId(10)));
let vals2 = vec![Value::Continuous(15.0)];
let res2 = eval_bytecode(&bytecode, &vals2).unwrap();
assert_eq!(res2, Value::Discrete(crate::base::SymbolId(20)));
}
#[test]
fn mapvalues_lookup() {
let table = vec![
(crate::base::SymbolId(1), crate::base::SymbolId(100)),
(crate::base::SymbolId(2), crate::base::SymbolId(200)),
];
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::MapValues {
table,
default: Some(crate::base::SymbolId(999)),
},
];
let vals = vec![Value::Discrete(crate::base::SymbolId(1))];
let res = eval_bytecode(&bytecode, &vals).unwrap();
assert_eq!(res, Value::Discrete(crate::base::SymbolId(100)));
let vals2 = vec![Value::Discrete(crate::base::SymbolId(3))];
let res2 = eval_bytecode(&bytecode, &vals2).unwrap();
assert_eq!(res2, Value::Discrete(crate::base::SymbolId(999)));
}
#[test]
fn norm_continuous_linear() {
let norms = vec![
LinearNorm {
orig: 0.0,
norm: 0.0,
},
LinearNorm {
orig: 10.0,
norm: 1.0,
},
];
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::NormContinuous {
field: crate::base::FieldId(0),
linear_norms: norms,
},
];
let vals = vec![Value::Continuous(5.0)];
let res = eval_bytecode(&bytecode, &vals).unwrap();
match res {
Value::Continuous(f) => assert!((f - 0.5).abs() < 1e-9),
_ => panic!("expected continuous"),
}
}
#[test]
fn aggregate_sum() {
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::PushField(crate::base::FieldId(1)),
Op::PushField(crate::base::FieldId(2)),
Op::CallBuiltin(BuiltinId::AggregateSum, 3),
];
let vals = vec![
Value::Continuous(1.0),
Value::Continuous(2.0),
Value::Continuous(3.0),
];
let res = eval_bytecode(&bytecode, &vals).unwrap();
assert_eq!(res, Value::Continuous(6.0));
}
#[test]
fn lag_missing() {
lag_clear();
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::PushConst(SymbolIdOrContinuous::Continuous(1.0)),
Op::CallBuiltin(BuiltinId::Lag, 2),
];
let vals = vec![Value::Continuous(10.0)];
let res = eval_bytecode(&bytecode, &vals).unwrap();
assert_eq!(res, Value::Missing);
}
#[test]
fn norm_discrete_basic() {
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::NormDiscrete {
field: crate::base::FieldId(0),
value: crate::base::SymbolId(5),
map_missing_to: None,
},
];
let vals = vec![Value::Discrete(crate::base::SymbolId(5))];
let res = eval_bytecode(&bytecode, &vals).unwrap();
assert_eq!(res, Value::Continuous(1.0));
let vals2 = vec![Value::Discrete(crate::base::SymbolId(6))];
let res2 = eval_bytecode(&bytecode, &vals2).unwrap();
assert_eq!(res2, Value::Continuous(0.0));
let vals3 = vec![Value::Missing];
let res3 = eval_bytecode(&bytecode, &vals3).unwrap();
assert_eq!(res3, Value::Missing);
}
#[test]
fn matches_regex() {
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::PushConst(SymbolIdOrContinuous::Symbol(crate::base::SymbolId(999))),
Op::CallBuiltin(BuiltinId::Matches, 2),
];
let vals = vec![Value::Continuous(0.0)];
let _ = eval_bytecode(&bytecode, &vals).unwrap();
}
#[test]
fn median_product() {
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::PushField(crate::base::FieldId(1)),
Op::PushField(crate::base::FieldId(2)),
Op::CallBuiltin(BuiltinId::Median, 3),
];
let vals = vec![
Value::Continuous(3.0),
Value::Continuous(1.0),
Value::Continuous(2.0),
];
let res = eval_bytecode(&bytecode, &vals).unwrap();
assert_eq!(res, Value::Continuous(2.0));
let bytecode2 = vec![
Op::PushField(crate::base::FieldId(0)),
Op::PushField(crate::base::FieldId(1)),
Op::CallBuiltin(BuiltinId::ProductOp, 2),
];
let vals2 = vec![Value::Continuous(3.0), Value::Continuous(4.0)];
let res2 = eval_bytecode(&bytecode2, &vals2).unwrap();
assert_eq!(res2, Value::Continuous(12.0));
}
#[test]
fn normalize_space() {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let s = " a b c ".to_string();
let mut h = DefaultHasher::new();
s.hash(&mut h);
let sid = crate::base::SymbolId((h.finish() & 0x7FFF_FFFF) as u32);
SYMBOL_STR_MAP.with(|m| m.borrow_mut().insert(sid, s));
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::CallBuiltin(BuiltinId::NormalizeSpace, 1),
];
let vals = vec![Value::Discrete(sid)];
let res = eval_bytecode(&bytecode, &vals).unwrap();
match res {
Value::Discrete(new_sid) => {
let out = SYMBOL_STR_MAP.with(|m| m.borrow().get(&new_sid).cloned().unwrap());
assert_eq!(out, "a b c");
}
_ => panic!("expected discrete"),
}
}
#[test]
fn modulo_python() {
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::PushField(crate::base::FieldId(1)),
Op::CallBuiltin(BuiltinId::Modulo, 2),
];
let vals = vec![Value::Continuous(11.0), Value::Continuous(3.0)];
assert_eq!(
eval_bytecode(&bytecode, &vals).unwrap(),
Value::Continuous(2.0)
);
let vals2 = vec![Value::Continuous(9.0), Value::Continuous(-7.0)];
assert_eq!(
eval_bytecode(&bytecode, &vals2).unwrap(),
Value::Continuous(-5.0)
);
}
#[test]
fn erf_normal() {
let bytecode = vec![
Op::PushField(crate::base::FieldId(0)),
Op::CallBuiltin(BuiltinId::ErfOp, 1),
];
let vals = vec![Value::Continuous(1.0)];
let res = eval_bytecode(&bytecode, &vals).unwrap();
match res {
Value::Continuous(f) => assert!((f - 0.84270079).abs() < 1e-6),
_ => panic!("expected continuous"),
}
let bytecode2 = vec![
Op::PushField(crate::base::FieldId(0)),
Op::CallBuiltin(BuiltinId::StdNormalCdf, 1),
];
let vals2 = vec![Value::Continuous(0.0)];
let res2 = eval_bytecode(&bytecode2, &vals2).unwrap();
match res2 {
Value::Continuous(f) => assert!((f - 0.5).abs() < 1e-6),
_ => panic!("expected continuous"),
}
}
}