use crate::base::field::ResultFeature;
use crate::base::{SymbolId, Value};
use crate::ir::OutputFieldIr;
use std::collections::HashMap;
pub fn build_output(
output_fields: &[OutputFieldIr],
predicted: Value,
probabilities: &HashMap<String, f64>,
) -> HashMap<String, Value> {
build_output_with_context(
output_fields,
predicted,
probabilities,
&HashMap::new(),
&[],
None,
&HashMap::new(),
&HashMap::new(),
)
}
#[allow(clippy::too_many_arguments)]
pub fn build_output_with_context(
output_fields: &[OutputFieldIr],
predicted: Value,
probabilities_str: &HashMap<String, f64>,
probabilities_sid: &HashMap<SymbolId, f64>,
values: &[Value],
target_field: Option<crate::base::FieldId>,
symbol_names: &HashMap<SymbolId, String>,
_field_names: &HashMap<crate::base::FieldId, String>,
) -> HashMap<String, Value> {
let mut out = HashMap::new();
let prob_for_sid = |sid: SymbolId| -> Option<f64> {
if let Some(&p) = probabilities_sid.get(&sid) {
return Some(p);
}
if let Some(name) = symbol_names.get(&sid) {
if let Some(&p) = probabilities_str.get(name) {
return Some(p);
}
}
None
};
let prob_for_predicted = || -> f64 {
if let Value::Discrete(sid) = predicted {
prob_for_sid(sid).unwrap_or(0.0)
} else {
0.0
}
};
let expected = target_field.and_then(|fid| {
let idx = fid.as_usize();
if idx < values.len() {
Some(values[idx])
} else {
None
}
});
if output_fields.is_empty() {
out.insert("predictedValue".to_string(), predicted);
return out;
}
for of in output_fields {
let val = match of.feature {
ResultFeature::PredictedValue => predicted,
ResultFeature::PredictedDisplayValue => {
predicted
}
ResultFeature::TransformedValue | ResultFeature::Decision | ResultFeature::Warning => {
if of.feature == ResultFeature::Warning {
Value::Missing
} else {
predicted
}
}
ResultFeature::Probability => {
if let Some(sid) = of.value {
prob_for_sid(sid)
.map(Value::Continuous)
.unwrap_or(Value::Missing)
} else {
Value::Continuous(prob_for_predicted())
}
}
ResultFeature::Affinity
| ResultFeature::ClusterAffinity
| ResultFeature::EntityAffinity => {
Value::Continuous(prob_for_predicted())
}
ResultFeature::Residual => {
if let Some(exp) = expected {
if exp.is_missing() || predicted.is_missing() {
Value::Missing
} else {
match (exp, predicted) {
(Value::Continuous(e), Value::Continuous(p)) => {
Value::Continuous(e - p)
}
(Value::Discrete(exp_sid), Value::Discrete(pred_sid)) => {
let prob = prob_for_sid(pred_sid).unwrap_or(0.0);
if exp_sid == pred_sid {
Value::Continuous(1.0 - prob)
} else {
Value::Continuous(0.0 - prob)
}
}
_ => Value::Missing,
}
}
} else {
Value::Missing
}
}
ResultFeature::ClusterId => predicted, ResultFeature::EntityId => {
predicted
}
ResultFeature::ReasonCode => {
Value::Missing
}
ResultFeature::RuleValue
| ResultFeature::Antecedent
| ResultFeature::Consequent
| ResultFeature::Rule
| ResultFeature::RuleId
| ResultFeature::Confidence
| ResultFeature::Support
| ResultFeature::Lift
| ResultFeature::Leverage => {
match of.feature {
ResultFeature::Confidence
| ResultFeature::Support
| ResultFeature::Lift
| ResultFeature::Leverage => Value::Continuous(0.0),
_ => predicted,
}
}
ResultFeature::StandardError
| ResultFeature::StandardDeviation
| ResultFeature::ConfidenceIntervalLower
| ResultFeature::ConfidenceIntervalUpper => {
Value::Missing
}
};
out.insert(of.name.clone(), val);
}
if out.is_empty() {
out.insert("predictedValue".to_string(), predicted);
}
out
}
pub fn build_output_strict(
output_fields: &[OutputFieldIr],
predicted: Value,
probabilities: &HashMap<String, f64>,
) -> Result<HashMap<String, Value>, crate::base::error::PmmlError> {
for of in output_fields {
if of.feature.is_unsupported() {
return Err(crate::base::error::PmmlError::UnsupportedMarkup(format!(
"unsupported ResultFeature {:?} for OutputField {}",
of.feature, of.name
)));
}
}
Ok(build_output(output_fields, predicted, probabilities))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::base::field::ResultFeature;
use crate::base::{FieldId, SymbolId, Value};
use crate::ir::{RankBasis, RankOrder};
fn make_output_field(
name: &str,
feature: ResultFeature,
value: Option<SymbolId>,
) -> OutputFieldIr {
OutputFieldIr {
name: name.to_string(),
feature,
value,
field: None,
target_field: None,
data_type: None,
op_type: None,
rule_feature: None,
algorithm: None,
rank: 1,
rank_basis: RankBasis::Confidence,
rank_order: RankOrder::Descending,
is_multi_valued: false,
segment_id: None,
is_final_result: true,
display_name: None,
expression_bytecode: None,
}
}
#[test]
fn predicted_value() {
let fields = vec![make_output_field(
"out",
ResultFeature::PredictedValue,
None,
)];
let out = build_output(&fields, Value::Continuous(5.0), &HashMap::new());
assert_eq!(out.get("out"), Some(&Value::Continuous(5.0)));
}
#[test]
fn probability_with_value() {
let sid = SymbolId(1);
let fields = vec![make_output_field(
"prob_setosa",
ResultFeature::Probability,
Some(sid),
)];
let mut probs = HashMap::new();
probs.insert("setosa".to_string(), 0.8);
let mut symbol_names = HashMap::new();
symbol_names.insert(sid, "setosa".to_string());
let out = build_output_with_context(
&fields,
Value::Discrete(SymbolId(1)),
&probs,
&HashMap::new(),
&[],
None,
&symbol_names,
&HashMap::new(),
);
assert_eq!(out.get("prob_setosa"), Some(&Value::Continuous(0.8)));
}
#[test]
fn probability_without_value_returns_pred_prob() {
let fields = vec![make_output_field("prob", ResultFeature::Probability, None)];
let mut probs = HashMap::new();
probs.insert("versicolor".to_string(), 0.6);
let mut symbol_names = HashMap::new();
symbol_names.insert(SymbolId(1), "versicolor".to_string());
let out = build_output_with_context(
&fields,
Value::Discrete(SymbolId(1)),
&probs,
&HashMap::new(),
&[],
None,
&symbol_names,
&HashMap::new(),
);
assert_eq!(out.get("prob"), Some(&Value::Continuous(0.6)));
}
#[test]
fn residual_continuous() {
let fields = vec![make_output_field("res", ResultFeature::Residual, None)];
let values = vec![Value::Continuous(10.0)]; let out = build_output_with_context(
&fields,
Value::Continuous(7.0),
&HashMap::new(),
&HashMap::new(),
&values,
Some(FieldId(0)),
&HashMap::new(),
&HashMap::new(),
);
assert_eq!(out.get("res"), Some(&Value::Continuous(3.0)));
}
#[test]
fn unsupported_returns_missing() {
let fields = vec![make_output_field("out", ResultFeature::StandardError, None)];
let out = build_output(&fields, Value::Continuous(5.0), &HashMap::new());
assert_eq!(out.get("out"), Some(&Value::Missing));
}
#[test]
fn strict_unsupported_error() {
let fields = vec![make_output_field("out", ResultFeature::StandardError, None)];
let res = build_output_strict(&fields, Value::Continuous(5.0), &HashMap::new());
assert!(res.is_err());
}
}