Skip to main content

lindera_dependency/
model.rs

1//! The model file: what a dictionary needs to be analyzed, in one file that
2//! is read in place.
3//!
4//! A model file says what dictionary it is for, by a name and by the
5//! [`Schema`] of the dictionary, and holds parts: the chunker and the
6//! parser. A part can be absent.
7//!
8//! [`Model`] reads a file from bytes it borrows or owns, without copying its
9//! tables: a file embedded with `include_bytes!`, read into a `Vec<u8>` or
10//! mapped into memory by the caller is used as it is. No number is read
11//! through a pointer, so the bytes can sit at any address. Bytes that are
12//! not a model file are refused when the model is made; nothing fails
13//! afterwards.
14//!
15//! [`ModelBuilder`] writes a file.
16//!
17//! # The format
18//!
19//! Version 4, little endian. A string is its length in bytes as a `u32`,
20//! then its UTF-8. A file of version 3 is read too: its schema ends with
21//! the rule of the head word, and the head word of a bunsetsu without one
22//! is its first morpheme
23//! ([`HeadFallback::FirstMorpheme`](crate::HeadFallback::FirstMorpheme)).
24//!
25//! ```text
26//! the magic number         8 bytes, "LDMODEL" and a zero
27//! the version              u32
28//! the name of the dictionary  string
29//! the schema, with its normalization of the surface, its rule of the
30//!                          head word, and the head word of a bunsetsu
31//!                          without one
32//! the number of parts      u32
33//! for each part:           its kind u32 (1 the chunker, 2 the parser),
34//!                          its offset from the first byte of the file u64,
35//!                          its length u64
36//! the parts, one after the other, in this order, up to the end of the file
37//! ```
38//!
39//! The chunker part: the number of columns as a `u32` and one byte for each,
40//! the template as a string, the nine weights of the transitions as `f64`,
41//! and a table of the feature strings, sorted, each with the weight of `B`
42//! and the weight of `I` as `f64`.
43//!
44//! The parser part: the feature set as a string, one byte for the
45//! quantization of the weights and one for how the weights of the pairs are
46//! kept, the bias and the scale of the quantization as `f64`, a table of the
47//! feature strings with their weights, and the weights of the pairs: a
48//! table of `2^bits` weights the pairs are hashed into, or the pairs of
49//! each feature with a weight of their own. The documentation of the
50//! project has every field.
51//!
52//! # Examples
53//!
54//! ```
55//! use std::collections::HashMap;
56//!
57//! use lindera_dependency::chunker::{ChunkerModel, Column, Template};
58//! use lindera_dependency::lattice::LatticeMorpheme;
59//! use lindera_dependency::model::{Model, ModelBuilder};
60//! use lindera_dependency::Schema;
61//!
62//! // A chunker made by hand: a morpheme after a particle starts a bunsetsu,
63//! // and anything else continues one.
64//! let mut features = HashMap::new();
65//! features.insert("U11:助詞-係助詞".to_string(), [1.0, 0.0]);
66//! let transitions = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.5], [0.0, 0.0, 0.5]];
67//! let chunker = ChunkerModel::new(
68//!     Schema::ipadic(),
69//!     vec![Column::Surface, Column::PartOfSpeech],
70//!     Template::cabocha(),
71//!     transitions,
72//!     features,
73//! )?;
74//!
75//! // The file of the dictionary, with this one part.
76//! let bytes = ModelBuilder::new("ipadic", Schema::ipadic())?
77//!     .chunker(&chunker)?
78//!     .to_bytes();
79//!
80//! // Reading borrows the bytes.
81//! let model = Model::new(bytes.as_slice())?;
82//! assert_eq!(model.dictionary(), "ipadic");
83//! model.check_dictionary("ipadic")?;
84//! assert!(model.check_dictionary("unidic").is_err());
85//!
86//! let morphemes = [
87//!     LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ"),
88//!     LatticeMorpheme::new("は", "助詞,係助詞,*,*,*,*,は,ハ,ワ"),
89//!     LatticeMorpheme::new("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
90//! ];
91//! let chunker = model.chunker().expect("the file has a chunker");
92//! assert_eq!(chunker.chunk(&morphemes)?, [0..2, 2..3]);
93//! # Ok::<(), lindera_dependency::Error>(())
94//! ```
95
96pub(crate) mod table;
97
98use std::fmt;
99use std::ops::Range;
100
101use crate::bytes::{Reader, push_string, push_u32};
102use crate::chunker::model::WEIGHTS_WIDTH;
103use crate::chunker::{Chunker, ChunkerData, ChunkerModel, Column, Template};
104use crate::error::{Error, Result};
105use crate::morpheme::Morpheme;
106use crate::parser::model::ParserLayout;
107use crate::parser::{Parser, ParserModel, ParserPart, Quantization};
108use crate::schema::Schema;
109use crate::sentence::Bunsetsu;
110use table::{Layout, Table};
111
112/// The first bytes of a model file.
113const MAGIC: &[u8; 8] = b"LDMODEL\0";
114
115/// The version of the format that is written.
116pub(crate) const VERSION: u32 = 4;
117
118/// The oldest version of the format that is read: the one of the models of
119/// Lindera 7.1.0, whose schema has no head word for a bunsetsu without one.
120const OLDEST_VERSION: u32 = 3;
121
122/// The kind of the chunker part.
123const KIND_CHUNKER: u32 = 1;
124
125/// The kind of the parser part.
126const KIND_PARSER: u32 = 2;
127
128/// What the bytes are, in the messages of the errors.
129const WHAT: &str = "model";
130
131/// A model file, read in place.
132///
133/// `B` is what holds the bytes: a `&[u8]`, a `Vec<u8>`, or the memory map of
134/// the caller. A model is made once and used from any number of threads.
135///
136/// See the [module](self) for the format and an example.
137#[derive(Clone)]
138pub struct Model<B> {
139    /// The bytes of the file.
140    bytes: B,
141    /// The name of the dictionary the model is for.
142    dictionary: String,
143    /// The schema of the dictionary.
144    schema: Schema,
145    /// The chunker part, when the file has one.
146    chunker: Option<ChunkerLayout>,
147    /// The parser part, when the file has one.
148    parser: Option<ParserLayout>,
149    /// Where each part is in the bytes, with its kind.
150    parts: Vec<(u32, Range<usize>)>,
151}
152
153/// The chunker part of a model: what is small is read, and the table of the
154/// weights is where it is in the bytes.
155#[derive(Debug, Clone, PartialEq)]
156struct ChunkerLayout {
157    /// The columns the template reads.
158    columns: Vec<Column>,
159    /// The template.
160    template: Template,
161    /// The weights of the transitions, as `[from][to]`.
162    transitions: [[f64; 3]; 3],
163    /// The table of the feature strings.
164    features: Layout,
165}
166
167impl<B: AsRef<[u8]>> Model<B> {
168    /// Reads a model file.
169    ///
170    /// The whole file is checked here, once: afterwards nothing of it is
171    /// parsed again and nothing can fail.
172    ///
173    /// # Arguments
174    ///
175    /// * `bytes` - The bytes of the file, as [`ModelBuilder::to_bytes`]
176    ///   wrote them.
177    ///
178    /// # Returns
179    ///
180    /// The model, or [`Error::Model`] for bytes that are not a model file
181    /// of this version: another magic number or version, an unknown kind of
182    /// part or the same kind twice, parts that are not one after the other
183    /// up to the end of the bytes, bytes that end early, or a part whose
184    /// content is not what the format says.
185    pub fn new(bytes: B) -> Result<Self> {
186        let all = bytes.as_ref();
187        let mut reader = Reader::new(all, WHAT, Error::Model);
188        if reader.take(MAGIC.len())? != MAGIC {
189            return Err(Error::Model(
190                "not a model file: the magic number is missing".to_string(),
191            ));
192        }
193        let version = reader.u32()?;
194        if !(OLDEST_VERSION..=VERSION).contains(&version) {
195            return Err(Error::Model(format!(
196                "the model has the version {version}, and this crate reads {OLDEST_VERSION} to {VERSION}"
197            )));
198        }
199        let dictionary = reader.string()?;
200        if dictionary.is_empty() {
201            return Err(reader.error("has no name of a dictionary"));
202        }
203        let schema = Schema::read(&mut reader, version)?;
204
205        let count = reader.u32()?;
206        let mut parts: Vec<(u32, Range<usize>)> = Vec::new();
207        for _ in 0..count {
208            let kind = reader.u32()?;
209            let offset = reader.u64()?;
210            let length = reader.u64()?;
211            let range = usize::try_from(offset)
212                .ok()
213                .zip(usize::try_from(length).ok())
214                .and_then(|(offset, length)| Some(offset..offset.checked_add(length)?))
215                .ok_or_else(|| reader.error("has a part past its end"))?;
216            if parts.iter().any(|(other, _)| *other == kind) {
217                return Err(reader.error(format_args!("has the part of kind {kind} twice")));
218            }
219            parts.push((kind, range));
220        }
221        // The parts follow the list, one after the other, and end the file:
222        // a file that was cut, or that has something else in it, is not
223        // read.
224        let mut position = reader.position();
225        for (_, range) in &parts {
226            if range.start != position {
227                return Err(reader.error("has parts that are not one after the other"));
228            }
229            position = range.end;
230        }
231        if position > all.len() {
232            return Err(reader.error(format_args!(
233                "ends early: {position} bytes expected, {} given",
234                all.len()
235            )));
236        }
237        if position < all.len() {
238            return Err(reader.error(format_args!(
239                "has {} bytes after its end",
240                all.len() - position
241            )));
242        }
243
244        let mut chunker = None;
245        let mut parser = None;
246        for (kind, range) in &parts {
247            match *kind {
248                KIND_CHUNKER => {
249                    chunker = Some(ChunkerLayout::read(&all[range.clone()], range.start)?)
250                }
251                KIND_PARSER => parser = Some(ParserLayout::read(&all[range.clone()], range.start)?),
252                _ => {
253                    return Err(Error::Model(format!(
254                        "the model has a part of the unknown kind {kind}"
255                    )));
256                }
257            }
258        }
259
260        Ok(Self {
261            bytes,
262            dictionary,
263            schema,
264            chunker,
265            parser,
266            parts,
267        })
268    }
269
270    /// The name of the dictionary the model is for.
271    ///
272    /// # Returns
273    ///
274    /// The name, as it was given to [`ModelBuilder::new`]: `ipadic`.
275    pub fn dictionary(&self) -> &str {
276        &self.dictionary
277    }
278
279    /// Checks that the model is for a dictionary.
280    ///
281    /// A model depends on the feature columns and on the segmentation of
282    /// its dictionary: on the morphemes of another one it gives wrong
283    /// answers without an error. What knows the dictionary of its
284    /// morphemes calls this before it analyzes them.
285    ///
286    /// Morphemes with fewer feature columns than the schema of the model
287    /// reads are refused when they are analyzed
288    /// ([`Schema::check`]); morphemes of another dictionary that are wide
289    /// enough are not, which is what this check is for.
290    ///
291    /// # Arguments
292    ///
293    /// * `name` - The name of the dictionary of the morphemes.
294    ///
295    /// # Returns
296    ///
297    /// `Ok(())` when it is the name of the model, or
298    /// [`Error::Dictionary`].
299    pub fn check_dictionary(&self, name: &str) -> Result<()> {
300        if name == self.dictionary {
301            Ok(())
302        } else {
303            Err(Error::Dictionary(format!(
304                "the model is for the dictionary {:?}, and the morphemes are of {name:?}",
305                self.dictionary
306            )))
307        }
308    }
309
310    /// The schema of the dictionary the model is for.
311    ///
312    /// # Returns
313    ///
314    /// The schema.
315    pub fn schema(&self) -> &Schema {
316        &self.schema
317    }
318
319    /// The chunker of the model.
320    ///
321    /// # Returns
322    ///
323    /// A chunker that reads its weights on the bytes of the model, or
324    /// `None` when the file has no chunker part.
325    pub fn chunker(&self) -> Option<Chunker<ChunkerPart<'_>>> {
326        let layout = self.chunker.as_ref()?;
327        Some(Chunker::new(ChunkerPart {
328            schema: &self.schema,
329            layout,
330            features: layout.features.table(self.bytes.as_ref()),
331        }))
332    }
333
334    /// The parser of the model.
335    ///
336    /// # Returns
337    ///
338    /// A parser whose classifier reads its weights on the bytes of the
339    /// model, or `None` when the file has no parser part.
340    pub fn parser(&self) -> Option<Parser<ParserPart<'_>>> {
341        let layout = self.parser.as_ref()?;
342        Some(Parser::new(
343            self.schema.clone(),
344            layout.feature_set().clone(),
345            layout.part(self.bytes.as_ref()),
346        ))
347    }
348
349    /// Analyzes a sentence: segments its morphemes into bunsetsu with the
350    /// chunker of the model, and finds the head of each with its parser.
351    ///
352    /// To analyze many sentences, take [`Model::chunker`] and
353    /// [`Model::parser`] once and use them for each: this makes both for
354    /// every call.
355    ///
356    /// # Arguments
357    ///
358    /// * `morphemes` - The morphemes of the sentence.
359    ///
360    /// # Returns
361    ///
362    /// The bunsetsu with their heads, as [`Parser::parse`] gives them; none
363    /// for an empty sentence. [`Error::Model`] when the file has no chunker
364    /// or no parser, and [`Error::Dictionary`] for a morpheme with fewer
365    /// feature columns than the schema reads.
366    pub fn analyze<M: Morpheme>(&self, morphemes: &[M]) -> Result<Vec<Bunsetsu>> {
367        let chunker = self
368            .chunker()
369            .ok_or_else(|| Error::Model("the model has no chunker".to_string()))?;
370        let parser = self
371            .parser()
372            .ok_or_else(|| Error::Model("the model has no parser".to_string()))?;
373        parser.parse(morphemes, &chunker.chunk(morphemes)?)
374    }
375
376    /// The bytes of the file.
377    ///
378    /// # Returns
379    ///
380    /// The bytes the model was made from.
381    pub fn as_bytes(&self) -> &[u8] {
382        self.bytes.as_ref()
383    }
384}
385
386impl<B: AsRef<[u8]>> fmt::Debug for Model<B> {
387    /// Writes what the model is for and what it has, not its bytes.
388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389        f.debug_struct("Model")
390            .field("dictionary", &self.dictionary)
391            .field("bytes", &self.bytes.as_ref().len())
392            .field("chunker", &self.chunker.is_some())
393            .field("parser", &self.parser.is_some())
394            .finish()
395    }
396}
397
398impl ChunkerLayout {
399    /// Reads and checks a chunker part.
400    ///
401    /// # Arguments
402    ///
403    /// * `part` - The bytes of the part.
404    /// * `base` - The position of the first byte of the part in the bytes
405    ///   of the model.
406    ///
407    /// # Returns
408    ///
409    /// The layout, or [`Error::Model`] for bytes that are not a chunker
410    /// part: an unknown column, a template that cannot be read or that
411    /// reads more columns than are given, a weight that is not finite, a
412    /// table that is not one, or bytes after the table.
413    fn read(part: &[u8], base: usize) -> Result<Self> {
414        let mut reader = Reader::new(part, WHAT, Error::Model);
415        let count = reader.u32()? as usize;
416        let mut columns = Vec::new();
417        for &code in reader.take(count)? {
418            columns.push(
419                Column::from_code(code)
420                    .ok_or_else(|| reader.error(format_args!("has the unknown column {code}")))?,
421            );
422        }
423
424        let template = Template::parse(&reader.string()?).map_err(|error| {
425            reader.error(format_args!("has a template that is not one: {error}"))
426        })?;
427        if template.columns() > columns.len() {
428            return Err(reader.error(format_args!(
429                "has a template that reads {} columns, and {} are given",
430                template.columns(),
431                columns.len()
432            )));
433        }
434
435        let mut transitions = [[0.0; 3]; 3];
436        for weight in transitions.iter_mut().flatten() {
437            *weight = reader.f64()?;
438        }
439
440        let features = Layout::read(&mut reader, WEIGHTS_WIDTH)?;
441        if reader.remaining() != 0 {
442            return Err(reader.error(format_args!(
443                "has {} bytes after its chunker",
444                reader.remaining()
445            )));
446        }
447
448        let table = features.table(part);
449        let finite = transitions
450            .iter()
451            .flatten()
452            .all(|weight| weight.is_finite())
453            && (0..table.len()).all(|index| {
454                weights(table.value(index))
455                    .is_some_and(|weights| weights.iter().all(|weight| weight.is_finite()))
456            });
457        if !finite {
458            return Err(reader.error("has a weight that is not finite"));
459        }
460        Ok(Self {
461            columns,
462            template,
463            transitions,
464            features: features.shifted(base),
465        })
466    }
467}
468
469/// The two weights of a feature string, from the bytes of its value.
470///
471/// # Arguments
472///
473/// * `value` - The value of the string in the table.
474///
475/// # Returns
476///
477/// The weight of `B` and the weight of `I`, or `None` for a value that has
478/// not the width of two weights.
479fn weights(value: &[u8]) -> Option<[f64; 2]> {
480    let begin = value.get(..8)?.try_into().ok()?;
481    let inside = value.get(8..16)?.try_into().ok()?;
482    Some([f64::from_le_bytes(begin), f64::from_le_bytes(inside)])
483}
484
485/// The chunker part of a model file, read on the bytes of the file.
486///
487/// It is what [`Model::chunker`] gives a [`Chunker`] to read.
488#[derive(Debug, Clone, Copy)]
489pub struct ChunkerPart<'a> {
490    /// The schema of the model.
491    schema: &'a Schema,
492    /// What is small of the part.
493    layout: &'a ChunkerLayout,
494    /// The table of the feature strings.
495    features: Table<'a>,
496}
497
498impl ChunkerPart<'_> {
499    /// The number of feature strings of the part.
500    ///
501    /// # Returns
502    ///
503    /// The number of strings.
504    pub fn feature_count(&self) -> usize {
505        self.features.len()
506    }
507
508    /// The number of weights of the part that are not 0: those of the
509    /// feature strings and those of the transitions.
510    ///
511    /// # Returns
512    ///
513    /// The number of weights.
514    pub fn weight_count(&self) -> usize {
515        let of_features: usize = (0..self.features.len())
516            .filter_map(|index| weights(self.features.value(index)))
517            .map(|weights| weights.iter().filter(|weight| **weight != 0.0).count())
518            .sum();
519        let of_transitions = self
520            .layout
521            .transitions
522            .iter()
523            .flatten()
524            .filter(|weight| **weight != 0.0)
525            .count();
526        of_features + of_transitions
527    }
528}
529
530impl ChunkerData for ChunkerPart<'_> {
531    fn schema(&self) -> &Schema {
532        self.schema
533    }
534
535    fn columns(&self) -> &[Column] {
536        &self.layout.columns
537    }
538
539    fn template(&self) -> &Template {
540        &self.layout.template
541    }
542
543    fn transition(&self, from: usize, to: usize) -> f64 {
544        self.layout
545            .transitions
546            .get(from)
547            .and_then(|row| row.get(to))
548            .copied()
549            .unwrap_or(0.0)
550    }
551
552    fn feature(&self, feature: &str) -> Option<[f64; 2]> {
553        weights(self.features.value(self.features.find(feature)?))
554    }
555}
556
557/// Writes a model file.
558///
559/// See the [module](self) for an example.
560#[derive(Debug, Clone, PartialEq)]
561pub struct ModelBuilder {
562    /// The name of the dictionary.
563    dictionary: String,
564    /// The schema of the dictionary.
565    schema: Schema,
566    /// The bytes of the chunker part, when one was given.
567    chunker: Option<Vec<u8>>,
568    /// The bytes of the parser part, when one was given.
569    parser: Option<Vec<u8>>,
570}
571
572impl ModelBuilder {
573    /// Starts a model file.
574    ///
575    /// # Arguments
576    ///
577    /// * `dictionary` - The name of the dictionary the model is for, as
578    ///   what uses the model names the dictionary of its morphemes:
579    ///   `ipadic`.
580    /// * `schema` - The schema of the dictionary.
581    ///
582    /// # Returns
583    ///
584    /// The builder, or [`Error::Model`] for an empty name.
585    pub fn new(dictionary: &str, schema: Schema) -> Result<Self> {
586        if dictionary.is_empty() {
587            return Err(Error::Model(
588                "a model needs the name of its dictionary".to_string(),
589            ));
590        }
591        Ok(Self {
592            dictionary: dictionary.to_string(),
593            schema,
594            chunker: None,
595            parser: None,
596        })
597    }
598
599    /// Starts a model file with the dictionary, the schema and the parts
600    /// of another one, to add a part to it or to replace one.
601    ///
602    /// # Arguments
603    ///
604    /// * `model` - The model file to start from.
605    ///
606    /// # Returns
607    ///
608    /// The builder, with the bytes of the parts of the model as they are.
609    pub fn from_model<B: AsRef<[u8]>>(model: &Model<B>) -> Self {
610        let part = |kind: u32| {
611            model
612                .parts
613                .iter()
614                .find(|(other, _)| *other == kind)
615                .and_then(|(_, range)| model.bytes.as_ref().get(range.clone()))
616                .map(<[u8]>::to_vec)
617        };
618        Self {
619            dictionary: model.dictionary.clone(),
620            schema: model.schema.clone(),
621            chunker: part(KIND_CHUNKER),
622            parser: part(KIND_PARSER),
623        }
624    }
625
626    /// Gives the file its chunker part.
627    ///
628    /// # Arguments
629    ///
630    /// * `model` - The model of the chunker.
631    ///
632    /// # Returns
633    ///
634    /// The builder, or [`Error::Model`] when the chunker was not trained
635    /// with the schema of the file.
636    pub fn chunker(mut self, model: &ChunkerModel) -> Result<Self> {
637        if model.schema() != &self.schema {
638            return Err(Error::Model(
639                "the chunker has another schema than the model".to_string(),
640            ));
641        }
642        let mut part = Vec::new();
643        model.write_part(&mut part);
644        self.chunker = Some(part);
645        Ok(self)
646    }
647
648    /// Gives the file its parser part.
649    ///
650    /// # Arguments
651    ///
652    /// * `model` - The model of the parser.
653    /// * `quantization` - How its weights are written.
654    ///
655    /// # Returns
656    ///
657    /// The builder, or [`Error::Model`] when the parser was not trained
658    /// with the schema of the file.
659    pub fn parser(mut self, model: &ParserModel, quantization: Quantization) -> Result<Self> {
660        if model.schema() != &self.schema {
661            return Err(Error::Model(
662                "the parser has another schema than the model".to_string(),
663            ));
664        }
665        let mut part = Vec::new();
666        model.write_part(&mut part, quantization);
667        self.parser = Some(part);
668        Ok(self)
669    }
670
671    /// Writes the file.
672    ///
673    /// The same parts give the same bytes.
674    ///
675    /// # Returns
676    ///
677    /// The bytes, which [`Model::new`] reads.
678    pub fn to_bytes(&self) -> Vec<u8> {
679        let mut bytes = Vec::new();
680        bytes.extend_from_slice(MAGIC);
681        push_u32(&mut bytes, VERSION);
682        push_string(&mut bytes, &self.dictionary);
683        self.schema.write(&mut bytes);
684
685        let parts: Vec<(u32, &[u8])> = [(KIND_CHUNKER, &self.chunker), (KIND_PARSER, &self.parser)]
686            .into_iter()
687            .filter_map(|(kind, part)| Some((kind, part.as_deref()?)))
688            .collect();
689        push_u32(&mut bytes, parts.len() as u32);
690        // Each entry of the list is a kind and two numbers of 8 bytes.
691        let mut offset = bytes.len() + parts.len() * 20;
692        for (kind, part) in &parts {
693            push_u32(&mut bytes, *kind);
694            bytes.extend_from_slice(&(offset as u64).to_le_bytes());
695            bytes.extend_from_slice(&(part.len() as u64).to_le_bytes());
696            offset += part.len();
697        }
698        for (_, part) in &parts {
699            bytes.extend_from_slice(part);
700        }
701        bytes
702    }
703}
704
705#[cfg(test)]
706// A sentence that is one bunsetsu is compared with `[0..n]`: an array of one
707// range, which is what is meant.
708#[allow(clippy::single_range_in_vec_init)]
709mod tests {
710    use super::*;
711    use crate::chunker::model::tests::model as chunker_model;
712    use crate::lattice::LatticeMorpheme;
713    use crate::schema::{HeadFallback, HeadRule, Normalization, Pattern, SentenceSplit};
714
715    /// A chunker for which a particle continues a bunsetsu and anything
716    /// else starts one, with weights that are told apart.
717    fn chunker() -> ChunkerModel {
718        chunker_model(
719            &[
720                ("U12:助詞-係助詞", [0.0, 1.0]),
721                ("U12:助詞-格助詞-一般", [0.0, 1.5]),
722                ("U02:は", [-0.25, 0.125]),
723            ],
724            [[0.0, 0.25, 0.0], [0.0, -0.5, 0.0625], [0.0, 0.125, 0.0]],
725        )
726    }
727
728    /// The bytes of a model file of IPADIC with the chunker.
729    fn bytes() -> Vec<u8> {
730        ModelBuilder::new("ipadic", Schema::ipadic())
731            .unwrap()
732            .chunker(&chunker())
733            .unwrap()
734            .to_bytes()
735    }
736
737    /// The message of the error of bytes that are not a model file.
738    fn error(bytes: &[u8]) -> String {
739        let error = Model::new(bytes).unwrap_err();
740        assert!(matches!(error, Error::Model(_)), "{error:?}");
741        error.to_string()
742    }
743
744    /// The position of the number of parts in [`bytes`]: after the magic
745    /// number, the version, the name and the schema.
746    fn list() -> usize {
747        let mut schema = Vec::new();
748        Schema::ipadic().write(&mut schema);
749        8 + 4 + 4 + "ipadic".len() + schema.len()
750    }
751
752    /// 彼 は 本 を 読む, with the features of IPADIC.
753    fn morphemes() -> Vec<LatticeMorpheme> {
754        vec![
755            LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ"),
756            LatticeMorpheme::new("は", "助詞,係助詞,*,*,*,*,は,ハ,ワ"),
757            LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
758            LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
759            LatticeMorpheme::new("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
760        ]
761    }
762
763    #[test]
764    fn a_file_gives_back_what_was_written() {
765        let schema = Schema {
766            part_of_speech: 1..3,
767            conjugation_type: None,
768            conjugation_form: Some(7),
769            base_form: None,
770            // The patterns, the symbols and the normalization go to the
771            // bytes too.
772            function_words: vec![Pattern::new(&["助詞"])],
773            not_heads: vec![Pattern::new(&["名詞", "非自立"]).after(Pattern::default())],
774            particles: vec![Pattern::new(&["助詞", "格助詞"])],
775            lexicalized: vec![Pattern::new(&["副詞"]), Pattern::new(&["連体詞"])],
776            symbols: Schema::ipadic().symbols,
777            normalization: Normalization::new(&[("ガ", "ガ"), ("1", "1")]).unwrap(),
778            head_rule: HeadRule::LastWords,
779            head_fallback: HeadFallback::FirstWord,
780            sentence_split: SentenceSplit::AfterEnds,
781        };
782        let transitions = [
783            [0.0, 0.25, -3.0],
784            [1e-300, -0.5, 1.0],
785            [0.75, f64::MAX, -0.0],
786        ];
787        let features = [
788            ("U00:彼", [-1.5, 2.0]),
789            ("U01:_B-1/連用形", [0.1, -0.2]),
790            ("U00:", [0.0, 3.0]),
791        ];
792        let original = ChunkerModel::new(
793            schema.clone(),
794            vec![
795                Column::Surface,
796                Column::PartOfSpeech,
797                Column::ConjugationForm,
798            ],
799            Template::parse("U00:%x[0,0]\nU01:%x[-1,1]/%x[0,2]\nB\n").unwrap(),
800            transitions,
801            features
802                .iter()
803                .map(|(feature, weights)| (feature.to_string(), *weights))
804                .collect(),
805        )
806        .unwrap();
807        let builder = ModelBuilder::new("a dictionary", schema.clone())
808            .unwrap()
809            .chunker(&original)
810            .unwrap();
811        let bytes = builder.to_bytes();
812        assert_eq!(&bytes[..8], b"LDMODEL\0");
813        assert_eq!(bytes[8..12], [4, 0, 0, 0]);
814        // The same parts give the same bytes, whatever the order of the
815        // table of the chunker in memory.
816        assert_eq!(builder.to_bytes(), bytes);
817        assert_eq!(
818            ModelBuilder::new("a dictionary", schema.clone())
819                .unwrap()
820                .chunker(&original.clone())
821                .unwrap()
822                .to_bytes(),
823            bytes
824        );
825
826        let model = Model::new(bytes.as_slice()).unwrap();
827        assert_eq!(model.dictionary(), "a dictionary");
828        assert_eq!(model.schema(), &schema);
829        assert_eq!(model.as_bytes(), bytes);
830        let chunker = model.chunker().unwrap();
831        let part = chunker.model();
832        assert_eq!(part.schema(), &schema);
833        assert_eq!(part.columns(), original.columns());
834        assert_eq!(part.template(), original.template());
835        for from in 0..4 {
836            for to in 0..4 {
837                let (read, written) = (part.transition(from, to), original.transition(from, to));
838                assert_eq!(read.to_bits(), written.to_bits(), "{from} {to}");
839            }
840        }
841        for (feature, weights) in features {
842            assert_eq!(part.feature(feature), Some(weights), "{feature}");
843        }
844        for missing in ["U00", "U00:彼は", "U02:", ""] {
845            assert_eq!(part.feature(missing), None, "{missing:?}");
846        }
847        assert_eq!(part.feature_count(), 3);
848        assert_eq!(part.feature_count(), original.feature_count());
849        assert_eq!(part.weight_count(), original.weight_count());
850    }
851
852    #[test]
853    fn a_file_without_a_part_is_read() {
854        let bytes = ModelBuilder::new("ipadic", Schema::ipadic())
855            .unwrap()
856            .to_bytes();
857        assert_eq!(bytes.len(), list() + 4);
858        let model = Model::new(bytes).unwrap();
859        assert_eq!(model.dictionary(), "ipadic");
860        assert_eq!(model.schema(), &Schema::ipadic());
861        assert!(model.chunker().is_none());
862    }
863
864    #[test]
865    fn the_chunker_of_a_file_chunks_as_the_model_in_memory() {
866        let in_memory = Chunker::new(chunker());
867        let model = Model::new(bytes()).unwrap();
868        let on_bytes = model.chunker().unwrap();
869        let morphemes = morphemes();
870        assert_eq!(on_bytes.chunk(&morphemes).unwrap(), [0..2, 2..4, 4..5]);
871        for range in [0..5, 0..1, 1..4, 1..2, 3..5, 0..0] {
872            let part = &morphemes[range.clone()];
873            assert_eq!(
874                on_bytes.labels(&on_bytes.features(part)),
875                in_memory.labels(&in_memory.features(part)),
876                "{range:?}"
877            );
878            assert_eq!(
879                on_bytes.chunk(part).unwrap(),
880                in_memory.chunk(part).unwrap()
881            );
882        }
883    }
884
885    #[test]
886    fn the_bytes_are_read_at_any_address() {
887        let bytes = bytes();
888        let morphemes = morphemes();
889        // The same file at eight addresses in a row: whatever the alignment
890        // of the first one, the others have every other one.
891        for shift in 0..8 {
892            let mut buffer = vec![0xa5; shift];
893            buffer.extend_from_slice(&bytes);
894            let model = Model::new(&buffer[shift..]).unwrap();
895            let chunker = model.chunker().unwrap();
896            assert_eq!(chunker.chunk(&morphemes).unwrap(), [0..2, 2..4, 4..5]);
897            assert_eq!(chunker.model().feature("U02:は"), Some([-0.25, 0.125]));
898            assert_eq!(chunker.model().transition(1, 2), 0.0625);
899        }
900    }
901
902    #[test]
903    fn a_model_holds_its_bytes_or_borrows_them() {
904        fn assert_send_sync<T: Send + Sync>() {}
905        assert_send_sync::<Model<Vec<u8>>>();
906        assert_send_sync::<Model<&'static [u8]>>();
907
908        // Owned: the model can be returned from where the bytes were read.
909        fn owned() -> Model<Vec<u8>> {
910            Model::new(bytes()).unwrap()
911        }
912        let model = owned();
913        let morphemes = morphemes();
914        std::thread::scope(|scope| {
915            for _ in 0..2 {
916                scope.spawn(|| {
917                    let chunker = model.chunker().unwrap();
918                    assert_eq!(chunker.chunk(&morphemes).unwrap(), [0..2, 2..4, 4..5]);
919                });
920            }
921        });
922
923        // Its description names what it is for, and not its bytes.
924        assert_eq!(
925            format!("{model:?}"),
926            format!(
927                "Model {{ dictionary: \"ipadic\", bytes: {}, chunker: true, parser: false }}",
928                model.as_bytes().len()
929            )
930        );
931    }
932
933    #[test]
934    fn the_name_of_the_dictionary_is_checked() {
935        let model = Model::new(bytes()).unwrap();
936        assert!(model.check_dictionary("ipadic").is_ok());
937        for other in ["unidic", "IPADIC", "ipadic-neologd", ""] {
938            let error = model.check_dictionary(other).unwrap_err();
939            assert!(matches!(error, Error::Dictionary(_)), "{error:?}");
940            assert_eq!(
941                error.to_string(),
942                format!(
943                    "the model is for the dictionary \"ipadic\", and the morphemes are of {other:?}"
944                )
945            );
946        }
947    }
948
949    #[test]
950    fn the_builder_refuses_no_name_and_another_schema() {
951        assert_eq!(
952            ModelBuilder::new("", Schema::ipadic())
953                .unwrap_err()
954                .to_string(),
955            "a model needs the name of its dictionary"
956        );
957        let mut other = Schema::ipadic();
958        other.base_form = None;
959        let error = ModelBuilder::new("other", other)
960            .unwrap()
961            .chunker(&chunker())
962            .unwrap_err();
963        assert!(matches!(error, Error::Model(_)), "{error:?}");
964        assert_eq!(
965            error.to_string(),
966            "the chunker has another schema than the model"
967        );
968    }
969
970    #[test]
971    fn refuses_bytes_that_are_not_a_model_file() {
972        let bytes = bytes();
973
974        let mut other = bytes.clone();
975        other[0] = b'X';
976        assert_eq!(
977            error(&other),
978            "not a model file: the magic number is missing"
979        );
980        // A chunker model of before the model file.
981        assert_eq!(
982            error(b"LDCHUNK\0\x03\0\0\0"),
983            "not a model file: the magic number is missing"
984        );
985        for version in [0, 1, 2, 5] {
986            let mut other = bytes.clone();
987            other[8] = version;
988            assert_eq!(
989                error(&other),
990                format!("the model has the version {version}, and this crate reads 3 to 4")
991            );
992        }
993
994        // Cut at any length, the file is refused.
995        for length in 0..bytes.len() {
996            let message = error(&bytes[..length]);
997            assert!(
998                message.starts_with("the model ends early"),
999                "{length}: {message}"
1000            );
1001        }
1002        let mut other = bytes.clone();
1003        other.push(0);
1004        assert_eq!(error(&other), "the model has 1 bytes after its end");
1005
1006        // The name has its length after the version.
1007        let mut other = bytes.clone();
1008        other[12] = 0;
1009        other.drain(16..22);
1010        assert_eq!(error(&other), "the model has no name of a dictionary");
1011    }
1012
1013    #[test]
1014    fn refuses_a_list_of_parts_that_is_not_one() {
1015        let bytes = bytes();
1016        let list = list();
1017        // One part: the chunker, right after the list, up to the end.
1018        assert_eq!(bytes[list..list + 8], [1, 0, 0, 0, 1, 0, 0, 0]);
1019        let offset = list + 4 + 20;
1020        assert_eq!(bytes[list + 8..list + 16], (offset as u64).to_le_bytes());
1021        let length = (bytes.len() - offset) as u64;
1022        assert_eq!(bytes[list + 16..list + 24], length.to_le_bytes());
1023
1024        let mut other = bytes.clone();
1025        other[list + 4] = 3;
1026        assert_eq!(error(&other), "the model has a part of the unknown kind 3");
1027
1028        // The part starts one byte later, or one byte earlier.
1029        for start in [offset + 1, offset - 1] {
1030            let mut other = bytes.clone();
1031            other[list + 8..list + 16].copy_from_slice(&(start as u64).to_le_bytes());
1032            assert_eq!(
1033                error(&other),
1034                "the model has parts that are not one after the other"
1035            );
1036        }
1037
1038        // A part whose end is past any number.
1039        let mut other = bytes.clone();
1040        other[list + 16..list + 24].copy_from_slice(&u64::MAX.to_le_bytes());
1041        assert_eq!(error(&other), "the model has a part past its end");
1042
1043        // A part that is longer than the bytes left, and one that is
1044        // shorter.
1045        let mut other = bytes.clone();
1046        other[list + 16..list + 24].copy_from_slice(&(length + 1).to_le_bytes());
1047        assert_eq!(
1048            error(&other),
1049            format!(
1050                "the model ends early: {} bytes expected, {} given",
1051                bytes.len() + 1,
1052                bytes.len()
1053            )
1054        );
1055        let mut other = bytes.clone();
1056        other[list + 16..list + 24].copy_from_slice(&(length - 1).to_le_bytes());
1057        assert_eq!(error(&other), "the model has 1 bytes after its end");
1058
1059        // The chunker twice: a second entry, of no length.
1060        let mut other = bytes[..list].to_vec();
1061        push_u32(&mut other, 2);
1062        for (start, length) in [(offset + 20, length), (offset + 20 + length as usize, 0)] {
1063            push_u32(&mut other, KIND_CHUNKER);
1064            other.extend_from_slice(&(start as u64).to_le_bytes());
1065            other.extend_from_slice(&length.to_le_bytes());
1066        }
1067        other.extend_from_slice(&bytes[offset..]);
1068        assert_eq!(error(&other), "the model has the part of kind 1 twice");
1069    }
1070
1071    /// The bytes of the chunker part of [`chunker`].
1072    fn part() -> Vec<u8> {
1073        let mut part = Vec::new();
1074        chunker().write_part(&mut part);
1075        part
1076    }
1077
1078    /// The message of the error of bytes that are not a chunker part.
1079    fn part_error(part: &[u8]) -> String {
1080        let error = ChunkerLayout::read(part, 0).unwrap_err();
1081        assert!(matches!(error, Error::Model(_)), "{error:?}");
1082        error.to_string()
1083    }
1084
1085    #[test]
1086    fn refuses_a_chunker_part_that_is_not_one() {
1087        let part = part();
1088        assert!(ChunkerLayout::read(&part, 0).is_ok());
1089        // The count of the columns, then one code each.
1090        assert_eq!(part[..6], [2, 0, 0, 0, 0, 1]);
1091
1092        let mut other = part.clone();
1093        other[5] = 9;
1094        assert_eq!(part_error(&other), "the model has the unknown column 9");
1095
1096        // One column for a template that reads two.
1097        let mut other = part.clone();
1098        other[0] = 1;
1099        other.remove(5);
1100        assert_eq!(
1101            part_error(&other),
1102            "the model has a template that reads 2 columns, and 1 are given"
1103        );
1104
1105        // The template is a string after the columns. Its first line is a
1106        // unigram line, and without its `U` it is no line of a template.
1107        assert_eq!(&part[10..14], b"U00:");
1108        let mut other = part.clone();
1109        other[10] = b'X';
1110        let message = part_error(&other);
1111        assert!(
1112            message.starts_with("the model has a template that is not one: "),
1113            "{message}"
1114        );
1115
1116        // A weight that is not a number. The table ends with the eight
1117        // slots of its three strings; the 8 bytes before them are the
1118        // weight of `I` of the last feature string. The transitions are the
1119        // 72 bytes before the table.
1120        let mut other = part.clone();
1121        let last = other.len() - 8 * 4 - 8;
1122        assert_eq!(other[last..last + 8], 1.5f64.to_le_bytes());
1123        other[last..last + 8].copy_from_slice(&f64::NAN.to_le_bytes());
1124        assert_eq!(
1125            part_error(&other),
1126            "the model has a weight that is not finite"
1127        );
1128        let template = u32::from_le_bytes(part[6..10].try_into().unwrap()) as usize;
1129        let transitions = 10 + template;
1130        assert_eq!(
1131            part[transitions + 8..transitions + 16],
1132            0.25f64.to_le_bytes()
1133        );
1134        let mut other = part.clone();
1135        other[transitions + 8..transitions + 16].copy_from_slice(&f64::INFINITY.to_le_bytes());
1136        assert_eq!(
1137            part_error(&other),
1138            "the model has a weight that is not finite"
1139        );
1140
1141        // The table has values of 16 bytes.
1142        let table = transitions + 72;
1143        assert_eq!(
1144            part[table..table + 12],
1145            [3, 0, 0, 0, 16, 0, 0, 0, 8, 0, 0, 0]
1146        );
1147        let mut other = part.clone();
1148        other[table + 4] = 8;
1149        assert_eq!(
1150            part_error(&other),
1151            "the model has a table with values of 8 bytes, and 16 are expected"
1152        );
1153
1154        let mut other = part.clone();
1155        other.push(0);
1156        assert_eq!(
1157            part_error(&other),
1158            "the model has 1 bytes after its chunker"
1159        );
1160        for length in 0..part.len() {
1161            let message = part_error(&part[..length]);
1162            assert!(
1163                message.starts_with("the model ends early"),
1164                "{length}: {message}"
1165            );
1166        }
1167    }
1168
1169    #[test]
1170    fn no_changed_byte_makes_reading_or_chunking_panic() {
1171        let bytes = bytes();
1172        let morphemes = morphemes();
1173        let mut read = 0;
1174        for position in 0..bytes.len() {
1175            for value in [0, 1, 0x7f, 0x80, 0xff, bytes[position] ^ 1] {
1176                if value == bytes[position] {
1177                    continue;
1178                }
1179                let mut other = bytes.clone();
1180                other[position] = value;
1181                // Either the file is refused, or it is a file with other
1182                // content, which chunks without a panic.
1183                if let Ok(model) = Model::new(other) {
1184                    read += 1;
1185                    if let Some(chunker) = model.chunker() {
1186                        let _ = chunker.chunk(&morphemes);
1187                        let _ = chunker.model().weight_count();
1188                    }
1189                }
1190            }
1191        }
1192        // A change of a weight, for one, gives another file that is read.
1193        assert!(read > 0);
1194    }
1195}
1196
1197/// A model file with the parser part.
1198#[cfg(test)]
1199// A sentence that is one bunsetsu is given as `[0..n]`: an array of one
1200// range, which is what is meant.
1201#[allow(clippy::single_range_in_vec_init)]
1202mod parser_tests {
1203    use super::*;
1204    use crate::chunker::model::tests::model as chunker_model;
1205    use crate::lattice::LatticeMorpheme;
1206    use crate::parser::{Classifier, FeatureSet, PairWeights};
1207
1208    /// A chunker for which a particle continues a bunsetsu and anything
1209    /// else starts one.
1210    fn chunker() -> ChunkerModel {
1211        chunker_model(
1212            &[
1213                ("U12:助詞-係助詞", [0.0, 1.0]),
1214                ("U12:助詞-格助詞-一般", [0.0, 1.0]),
1215            ],
1216            [[0.0; 3]; 3],
1217        )
1218    }
1219
1220    /// A parser for which a bunsetsu that ends in を depends on the next
1221    /// one, and nothing else is attached before the end of the sentence.
1222    fn parser() -> ParserModel {
1223        ParserModel::new(
1224            Schema::ipadic(),
1225            FeatureSet::cabocha(),
1226            -1.0,
1227            vec![("DIST:1".to_string(), 0.0), ("SFS:を".to_string(), 0.0)],
1228            PairWeights::Exact(vec![((0, 1), 2.0)]),
1229        )
1230        .unwrap()
1231    }
1232
1233    /// The bytes of a model file of IPADIC with the two parts.
1234    fn bytes(quantization: Quantization) -> Vec<u8> {
1235        ModelBuilder::new("ipadic", Schema::ipadic())
1236            .unwrap()
1237            .chunker(&chunker())
1238            .unwrap()
1239            .parser(&parser(), quantization)
1240            .unwrap()
1241            .to_bytes()
1242    }
1243
1244    /// 彼 は / 本 を / 読む / 人.
1245    fn morphemes() -> Vec<LatticeMorpheme> {
1246        vec![
1247            LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ"),
1248            LatticeMorpheme::new("は", "助詞,係助詞,*,*,*,*,は,ハ,ワ"),
1249            LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
1250            LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
1251            LatticeMorpheme::new("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
1252            LatticeMorpheme::new("人", "名詞,一般,*,*,*,*,人,ヒト,ヒト"),
1253        ]
1254    }
1255
1256    #[test]
1257    fn a_file_with_both_parts_analyzes_a_sentence() {
1258        for quantization in [Quantization::F32, Quantization::I16, Quantization::I8] {
1259            let bytes = bytes(quantization);
1260            let model = Model::new(bytes.as_slice()).unwrap();
1261            assert_eq!(
1262                format!("{model:?}"),
1263                format!(
1264                    "Model {{ dictionary: \"ipadic\", bytes: {}, chunker: true, parser: true }}",
1265                    bytes.len()
1266                )
1267            );
1268            let morphemes = morphemes();
1269            let analyzed = model.analyze(&morphemes).unwrap();
1270            let ranges: Vec<_> = analyzed.iter().map(|one| one.morphemes.clone()).collect();
1271            assert_eq!(ranges, [0..2, 2..4, 4..5, 5..6]);
1272            let heads: Vec<Option<usize>> = analyzed.iter().map(|one| one.head).collect();
1273            // 本 を depends on 読む, the next one; the others on the last.
1274            assert_eq!(heads, [Some(3), Some(2), Some(3), None]);
1275            // The bias and the weight of the pair, which every
1276            // quantization writes as it is: it is the largest weight.
1277            assert_eq!(analyzed[1].score, Some(1.0));
1278            assert_eq!(analyzed[1].positions, Some((0, 1)));
1279
1280            // The same as the two steps, and as the model in memory.
1281            let parser_of_file = model.parser().unwrap();
1282            assert_eq!(parser_of_file.feature_set(), &FeatureSet::cabocha());
1283            assert_eq!(parser_of_file.schema(), &Schema::ipadic());
1284            let chunks = model.chunker().unwrap().chunk(&morphemes).unwrap();
1285            assert_eq!(parser_of_file.parse(&morphemes, &chunks).unwrap(), analyzed);
1286            let in_memory = Parser::new(Schema::ipadic(), FeatureSet::cabocha(), parser());
1287            assert_eq!(in_memory.parse(&morphemes, &chunks).unwrap(), analyzed);
1288            assert_eq!(parser_of_file.classifier().id("SFS:を"), Some(1));
1289
1290            let none: [LatticeMorpheme; 0] = [];
1291            assert!(model.analyze(&none).unwrap().is_empty());
1292        }
1293    }
1294
1295    #[test]
1296    fn the_parts_are_listed_in_their_order() {
1297        let bytes = bytes(Quantization::F32);
1298        let mut schema = Vec::new();
1299        Schema::ipadic().write(&mut schema);
1300        let list = 8 + 4 + 4 + "ipadic".len() + schema.len();
1301        assert_eq!(bytes[list..list + 4], [2, 0, 0, 0]);
1302        // The chunker, then the parser, one after the other to the end.
1303        let entry = |index: usize| {
1304            let start = list + 4 + 20 * index;
1305            let number = |from: usize| {
1306                u64::from_le_bytes(bytes[start + from..start + from + 8].try_into().unwrap())
1307                    as usize
1308            };
1309            (bytes[start], number(4), number(12))
1310        };
1311        let (first, second) = (entry(0), entry(1));
1312        assert_eq!(first.0, 1);
1313        assert_eq!(second.0, 2);
1314        assert_eq!(first.1, list + 4 + 40);
1315        assert_eq!(second.1, first.1 + first.2);
1316        assert_eq!(second.1 + second.2, bytes.len());
1317        // In whatever order the parts are given.
1318        let other = ModelBuilder::new("ipadic", Schema::ipadic())
1319            .unwrap()
1320            .parser(&parser(), Quantization::F32)
1321            .unwrap()
1322            .chunker(&chunker())
1323            .unwrap()
1324            .to_bytes();
1325        assert_eq!(other, bytes);
1326    }
1327
1328    #[test]
1329    fn a_file_without_a_part_does_not_analyze() {
1330        let only_chunker = ModelBuilder::new("ipadic", Schema::ipadic())
1331            .unwrap()
1332            .chunker(&chunker())
1333            .unwrap()
1334            .to_bytes();
1335        let only_parser = ModelBuilder::new("ipadic", Schema::ipadic())
1336            .unwrap()
1337            .parser(&parser(), Quantization::I8)
1338            .unwrap()
1339            .to_bytes();
1340        let morphemes = morphemes();
1341        for (bytes, message) in [
1342            (only_chunker, "the model has no parser"),
1343            (only_parser, "the model has no chunker"),
1344        ] {
1345            let model = Model::new(bytes).unwrap();
1346            let error = model.analyze(&morphemes).unwrap_err();
1347            assert!(matches!(error, Error::Model(_)), "{error:?}");
1348            assert_eq!(error.to_string(), message);
1349            assert_eq!(model.parser().is_none(), message.ends_with("parser"));
1350            assert_eq!(model.chunker().is_none(), message.ends_with("chunker"));
1351        }
1352        // Morphemes of another dictionary are refused by both steps.
1353        let model = Model::new(bytes(Quantization::I8)).unwrap();
1354        let narrow = [LatticeMorpheme::new("彼", "名詞,代名詞")];
1355        let error = model.analyze(&narrow).unwrap_err();
1356        assert!(matches!(error, Error::Dictionary(_)), "{error:?}");
1357        let error = model.parser().unwrap().parse(&narrow, &[0..1]).unwrap_err();
1358        assert!(matches!(error, Error::Dictionary(_)), "{error:?}");
1359    }
1360
1361    #[test]
1362    fn a_file_is_started_from_another_one() {
1363        let only_chunker = ModelBuilder::new("ipadic", Schema::ipadic())
1364            .unwrap()
1365            .chunker(&chunker())
1366            .unwrap()
1367            .to_bytes();
1368        let model = Model::new(only_chunker.as_slice()).unwrap();
1369        // The chunker of the file, as its bytes are, and a parser.
1370        let both = ModelBuilder::from_model(&model)
1371            .parser(&parser(), Quantization::I16)
1372            .unwrap()
1373            .to_bytes();
1374        assert_eq!(both, bytes(Quantization::I16));
1375        // Nothing added: the same file.
1376        assert_eq!(ModelBuilder::from_model(&model).to_bytes(), only_chunker);
1377        let full = Model::new(both.as_slice()).unwrap();
1378        assert_eq!(ModelBuilder::from_model(&full).to_bytes(), both);
1379        // A part given again takes the place of the one of the file.
1380        let again = ModelBuilder::from_model(&full)
1381            .parser(&parser(), Quantization::I8)
1382            .unwrap()
1383            .to_bytes();
1384        assert_eq!(again, bytes(Quantization::I8));
1385        assert_ne!(again, both);
1386
1387        // The name and the schema are those of the file.
1388        let mut schema = Schema::ipadic();
1389        schema.base_form = None;
1390        let other = ModelBuilder::new("other", schema.clone())
1391            .unwrap()
1392            .to_bytes();
1393        let other = Model::new(other).unwrap();
1394        let copy = Model::new(ModelBuilder::from_model(&other).to_bytes()).unwrap();
1395        assert_eq!(copy.dictionary(), "other");
1396        assert_eq!(copy.schema(), &schema);
1397    }
1398
1399    #[test]
1400    fn the_builder_refuses_a_parser_of_another_schema() {
1401        let mut other = Schema::ipadic();
1402        other.base_form = None;
1403        let error = ModelBuilder::new("other", other)
1404            .unwrap()
1405            .parser(&parser(), Quantization::F32)
1406            .unwrap_err();
1407        assert!(matches!(error, Error::Model(_)), "{error:?}");
1408        assert_eq!(
1409            error.to_string(),
1410            "the parser has another schema than the model"
1411        );
1412    }
1413
1414    #[test]
1415    fn a_parser_part_that_is_not_one_is_refused_with_the_file() {
1416        let bytes = bytes(Quantization::F32);
1417        // The last weight of the file is the one of the pair.
1418        let mut other = bytes.clone();
1419        let last = other.len() - 4;
1420        assert_eq!(other[last..], 2.0f32.to_le_bytes());
1421        other[last..].copy_from_slice(&f32::NAN.to_le_bytes());
1422        let error = Model::new(other).unwrap_err();
1423        assert!(matches!(error, Error::Model(_)), "{error:?}");
1424        assert_eq!(
1425            error.to_string(),
1426            "the model has a weight that is not finite"
1427        );
1428        for length in 0..bytes.len() {
1429            assert!(Model::new(&bytes[..length]).is_err(), "{length}");
1430        }
1431    }
1432
1433    #[test]
1434    fn no_changed_byte_makes_reading_or_analyzing_panic() {
1435        let bytes = bytes(Quantization::I8);
1436        let morphemes = morphemes();
1437        let mut read = 0;
1438        for position in 0..bytes.len() {
1439            for value in [0, 1, 0x7f, 0x80, 0xff, bytes[position] ^ 1] {
1440                if value == bytes[position] {
1441                    continue;
1442                }
1443                let mut other = bytes.clone();
1444                other[position] = value;
1445                if let Ok(model) = Model::new(other) {
1446                    read += 1;
1447                    let _ = model.analyze(&morphemes);
1448                    let _ = ModelBuilder::from_model(&model).to_bytes();
1449                }
1450            }
1451        }
1452        assert!(read > 0);
1453    }
1454
1455    /// The model file of the tests of the other crates, as the version 3
1456    /// wrote it (Lindera 7.1.0), and as it is written now.
1457    #[test]
1458    fn a_file_of_version_3_is_read_and_takes_the_first_morpheme() {
1459        use crate::schema::{HeadFallback, SentenceSplit};
1460
1461        let directory = concat!(env!("CARGO_MANIFEST_DIR"), "/../resources/dependency");
1462        let old = std::fs::read(format!("{directory}/test_model_ipadic_v3.bin")).unwrap();
1463        let new = std::fs::read(format!("{directory}/test_model_ipadic.bin")).unwrap();
1464        assert_eq!(old[8..12], [3, 0, 0, 0]);
1465        assert_eq!(new[8..12], [VERSION as u8, 0, 0, 0]);
1466        // The schema has two bytes more: its two settings.
1467        assert_eq!(new.len(), old.len() + 2);
1468
1469        let old = Model::new(old).unwrap();
1470        let new = Model::new(new).unwrap();
1471        assert_eq!(old.dictionary(), "ipadic");
1472        assert_eq!(old.schema().head_fallback, HeadFallback::FirstMorpheme);
1473        assert_eq!(new.schema().head_fallback, HeadFallback::FirstWord);
1474        assert_eq!(old.schema().sentence_split, SentenceSplit::None);
1475        assert_eq!(new.schema().sentence_split, SentenceSplit::AfterEnds);
1476        // But for that, the two are one model.
1477        assert_eq!(
1478            *old.schema(),
1479            Schema {
1480                head_fallback: HeadFallback::FirstMorpheme,
1481                sentence_split: SentenceSplit::None,
1482                ..new.schema().clone()
1483            }
1484        );
1485        let morphemes = morphemes();
1486        let chunks = old.chunker().unwrap().chunk(&morphemes).unwrap();
1487        assert_eq!(chunks, new.chunker().unwrap().chunk(&morphemes).unwrap());
1488        assert_eq!(
1489            old.parser().unwrap().parse(&morphemes, &chunks).unwrap(),
1490            new.parser().unwrap().parse(&morphemes, &chunks).unwrap()
1491        );
1492    }
1493}