use std::collections::HashMap;
use super::columns::Column;
use super::template::Template;
use crate::bytes::{push_string, push_u32};
use crate::error::{Error, Result};
use crate::model::table;
use crate::schema::Schema;
pub(crate) const WEIGHTS_WIDTH: usize = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Label {
Begin,
Inside,
}
impl Label {
pub(crate) const ALL: [Label; 2] = [Label::Begin, Label::Inside];
pub(crate) fn index(self) -> usize {
match self {
Label::Begin => 0,
Label::Inside => 1,
}
}
}
pub(crate) const BOUNDARY: usize = 0;
pub trait ChunkerData {
fn schema(&self) -> &Schema;
fn columns(&self) -> &[Column];
fn template(&self) -> &Template;
fn transition(&self, from: usize, to: usize) -> f64;
fn feature(&self, feature: &str) -> Option<[f64; 2]>;
}
#[derive(Debug, Clone, PartialEq)]
pub struct ChunkerModel {
schema: Schema,
columns: Vec<Column>,
template: Template,
transitions: [[f64; 3]; 3],
features: HashMap<String, [f64; 2]>,
}
impl ChunkerModel {
pub fn new(
schema: Schema,
columns: Vec<Column>,
template: Template,
transitions: [[f64; 3]; 3],
features: HashMap<String, [f64; 2]>,
) -> Result<Self> {
if template.columns() > columns.len() {
return Err(Error::Chunker(format!(
"the template reads {} columns, and {} are given",
template.columns(),
columns.len()
)));
}
let finite = transitions
.iter()
.flatten()
.all(|weight| weight.is_finite())
&& features.values().flatten().all(|weight| weight.is_finite());
if !finite {
return Err(Error::Chunker("a weight is not finite".to_string()));
}
Ok(Self {
schema,
columns,
template,
transitions,
features,
})
}
pub fn schema(&self) -> &Schema {
&self.schema
}
pub fn columns(&self) -> &[Column] {
&self.columns
}
pub fn template(&self) -> &Template {
&self.template
}
pub fn transition(&self, from: usize, to: usize) -> f64 {
self.transitions
.get(from)
.and_then(|row| row.get(to))
.copied()
.unwrap_or(0.0)
}
pub fn feature(&self, feature: &str) -> Option<[f64; 2]> {
self.features.get(feature).copied()
}
pub fn feature_count(&self) -> usize {
self.features.len()
}
pub fn weight_count(&self) -> usize {
self.features
.values()
.flatten()
.chain(self.transitions.iter().flatten())
.filter(|weight| **weight != 0.0)
.count()
}
pub(crate) fn write_part(&self, bytes: &mut Vec<u8>) {
push_u32(bytes, self.columns.len() as u32);
for column in &self.columns {
bytes.push(column.code());
}
push_string(bytes, &self.template.to_string());
for weight in self.transitions.iter().flatten() {
bytes.extend_from_slice(&weight.to_le_bytes());
}
let mut features: Vec<(&str, [u8; WEIGHTS_WIDTH])> = self
.features
.iter()
.map(|(feature, weights)| {
let mut value = [0; WEIGHTS_WIDTH];
value[..8].copy_from_slice(&weights[0].to_le_bytes());
value[8..].copy_from_slice(&weights[1].to_le_bytes());
(feature.as_str(), value)
})
.collect();
features.sort_by(|left, right| left.0.as_bytes().cmp(right.0.as_bytes()));
let entries: Vec<(&str, &[u8])> = features
.iter()
.map(|(feature, value)| (*feature, value.as_slice()))
.collect();
table::write(bytes, WEIGHTS_WIDTH, &entries);
}
}
impl ChunkerData for ChunkerModel {
fn schema(&self) -> &Schema {
&self.schema
}
fn columns(&self) -> &[Column] {
&self.columns
}
fn template(&self) -> &Template {
&self.template
}
fn transition(&self, from: usize, to: usize) -> f64 {
ChunkerModel::transition(self, from, to)
}
fn feature(&self, feature: &str) -> Option<[f64; 2]> {
ChunkerModel::feature(self, feature)
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub(crate) fn model(features: &[(&str, [f64; 2])], transitions: [[f64; 3]; 3]) -> ChunkerModel {
ChunkerModel::new(
Schema::ipadic(),
vec![Column::Surface, Column::PartOfSpeech],
Template::cabocha(),
transitions,
features
.iter()
.map(|(feature, weights)| (feature.to_string(), *weights))
.collect(),
)
.unwrap()
}
#[test]
fn a_model_gives_back_what_it_was_made_of() {
let model = model(
&[("U02:は", [-1.5, 2.0]), ("U12:名詞", [0.5, 0.0])],
[[0.0, 0.25, 0.0], [0.0, -0.5, 1.0], [0.75, 0.0, 0.0]],
);
assert_eq!(model.schema(), &Schema::ipadic());
assert_eq!(model.columns(), [Column::Surface, Column::PartOfSpeech]);
assert_eq!(model.template(), &Template::cabocha());
assert_eq!(model.feature("U02:は"), Some([-1.5, 2.0]));
assert_eq!(model.feature("U02:が"), None);
assert_eq!(model.transition(0, 1), 0.25);
assert_eq!(model.transition(1, 2), 1.0);
assert_eq!(model.transition(2, 0), 0.75);
assert_eq!(model.transition(3, 0), 0.0);
assert_eq!(model.feature_count(), 2);
assert_eq!(model.weight_count(), 7);
}
#[test]
fn new_refuses_a_template_with_more_columns_and_weights_that_are_not_finite() {
let make = |columns: Vec<Column>, weight: f64| {
ChunkerModel::new(
Schema::ipadic(),
columns,
Template::cabocha(),
[[0.0, weight, 0.0], [0.0; 3], [0.0; 3]],
HashMap::new(),
)
};
assert_eq!(
make(vec![Column::Surface], 0.0).unwrap_err().to_string(),
"the template reads 2 columns, and 1 are given"
);
assert_eq!(
make(vec![Column::Surface, Column::PartOfSpeech], f64::INFINITY)
.unwrap_err()
.to_string(),
"a weight is not finite"
);
assert!(make(vec![Column::Surface, Column::PartOfSpeech], 1.0).is_ok());
}
}