lindera-dependency 7.1.0

Japanese bunsetsu dependency analysis for Lindera.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
//! Converting the models of CaboCha.
//!
//! CaboCha comes with models trained on the Kyoto University Text Corpus,
//! which cannot be trained again without the corpus. This module reads the
//! two text files of such a model, `chunk.ipa.txt` and `dep.ipa.txt`, and
//! makes a model of this crate that analyzes as CaboCha does with them:
//!
//! - the chunker model is a CRF++ model in text: its template, its feature
//!   strings and its weights go into a [`ChunkerModel`] as they are;
//! - the parser model is the support vectors of a kernel of degree 2. They
//!   are expanded into weights of features and of pairs of features, as
//!   `cabocha-model-index` expands them, with its approximation;
//! - what makes the features is data of the model: [`schema`] is CaboCha's
//!   rule for the head and the function word of a bunsetsu, its
//!   punctuation and its brackets, and its normalization of the surface.
//!
//! # The terms of CaboCha's models
//!
//! The license of CaboCha does not cover its models. They were made from
//! the Mainichi Shimbun article data, and CaboCha's page limits the use of
//! the distributed models as they are to research and personal use. A
//! converted model is under the same terms: convert the files of your own
//! copy of CaboCha, and do not distribute the result. This crate holds no
//! model of CaboCha.
//!
//! # Which models
//!
//! The three models CaboCha distributes, in UTF-8: `chunk.ipa.txt` with
//! `dep.ipa.txt`, for the morphemes of IPADIC; `chunk.juman.txt` with
//! `dep.juman.txt`, for those of the JUMAN dictionary (`jumandic`); and
//! `chunk.unidic.txt` with `dep.unidic.txt`, for those of UniDic (`unidic`,
//! or `unidic-cwj` or `unidic-csj` with [`Converted::to_bytes_for`]). The
//! set is read in the header of the parser model; the chunker model does
//! not say which it is for, so the two files have to be given as a pair.
//!
//! # Examples
//!
//! ```no_run
//! use lindera_dependency::cabocha::{Options, convert};
//! use lindera_dependency::model::Model;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let chunker = std::fs::read_to_string("chunk.ipa.txt")?;
//! let parser = std::fs::read_to_string("dep.ipa.txt")?;
//! let converted = convert(&chunker, &parser, &Options::default())?;
//! println!("{} pairs of {}", converted.report.kept_pairs, converted.report.all_pairs);
//! let model = Model::new(converted.to_bytes()?)?;
//! # Ok(())
//! # }
//! ```

mod crfpp;
mod svm;

use crate::chunker::{ChunkerModel, Column, Template};
use crate::error::{Error, Result};
use crate::model::ModelBuilder;
use crate::parser::{FeatureSet, PairWeights, ParserModel, Quantization};
use crate::schema::{HeadRule, Marks, Normalization, Pattern, Schema, SurfaceRule, Symbols};

/// The table of `src/normalizer.rule` of CaboCha: a line is what is
/// replaced, a tab, and what it is replaced by.
const NORMALIZER_RULE: &str = include_str!("cabocha/normalizer.rule");

/// The part-of-speech set of the dictionary a model of CaboCha is for:
/// `posset` in the header of its parser model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PartOfSpeechSet {
    /// The set of IPADIC: `IPA`.
    Ipa,
    /// The set of the JUMAN dictionary: `JUMAN`.
    Juman,
    /// The set of UniDic: `UNIDIC`.
    Unidic,
}

impl PartOfSpeechSet {
    /// The set with the name CaboCha gives it.
    ///
    /// # Arguments
    ///
    /// * `name` - The value of `posset`: `IPA`, `JUMAN` or `UNIDIC`.
    ///
    /// # Returns
    ///
    /// The set, or [`Error::Cabocha`] for any other name.
    pub fn from_name(name: &str) -> Result<Self> {
        match name {
            "IPA" => Ok(PartOfSpeechSet::Ipa),
            "JUMAN" => Ok(PartOfSpeechSet::Juman),
            "UNIDIC" => Ok(PartOfSpeechSet::Unidic),
            other => Err(Error::Cabocha(format!(
                "the model is for the part-of-speech set {other:?}, which is not one of CaboCha"
            ))),
        }
    }

    /// The name of the dictionary of Lindera with this set: the name a
    /// converted model is for, unless another one of
    /// [`PartOfSpeechSet::dictionaries`] is asked for.
    ///
    /// # Returns
    ///
    /// `ipadic` for [`PartOfSpeechSet::Ipa`], `jumandic` for
    /// [`PartOfSpeechSet::Juman`], and `unidic` for
    /// [`PartOfSpeechSet::Unidic`].
    pub fn dictionary(self) -> &'static str {
        self.dictionaries()[0]
    }

    /// The names of the dictionaries of Lindera with this set.
    ///
    /// # Returns
    ///
    /// One name for IPA and for JUMAN; for UniDic `unidic`, `unidic-cwj`
    /// and `unidic-csj`, which have the columns a model reads at the same
    /// places.
    pub fn dictionaries(self) -> &'static [&'static str] {
        match self {
            PartOfSpeechSet::Ipa => &["ipadic"],
            PartOfSpeechSet::Juman => &["jumandic"],
            PartOfSpeechSet::Unidic => &["unidic", "unidic-cwj", "unidic-csj"],
        }
    }

    /// The feature set of the parser of CaboCha for this set.
    ///
    /// # Returns
    ///
    /// [`FeatureSet::cabocha`]; for UniDic with two levels of the part of
    /// speech, though the chunker and the patterns of the schema read
    /// four.
    pub fn feature_set(self) -> FeatureSet {
        match self {
            PartOfSpeechSet::Ipa | PartOfSpeechSet::Juman => FeatureSet::cabocha(),
            PartOfSpeechSet::Unidic => FeatureSet::cabocha()
                .with_part_of_speech_levels(2)
                .expect("two levels are a limit"),
        }
    }
}

/// How the pairs of features of the parser model are pruned: the options
/// of `cabocha-model-index`, with its defaults.
///
/// A pair of two of the `frequent_features` most frequent features is
/// always kept. Another pair is kept when it is in `min_support` support
/// vectors or more, and its weight is `sigma × positives / all` or more,
/// or `-sigma × negatives / all` or less.
///
/// `sigma` 0 with `min_support` 1 keeps every pair: the kernel itself,
/// which is not what CaboCha parses with.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Options {
    /// The threshold of the weight of a pair: `-s` of
    /// `cabocha-model-index`, 0.0001.
    pub sigma: f64,
    /// The number of support vectors a pair has to be in: `-n`, 2.
    pub min_support: usize,
    /// The number of frequent features, whose pairs are all kept: `-F`,
    /// 3000.
    pub frequent_features: usize,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            sigma: 0.0001,
            min_support: 2,
            frequent_features: 3000,
        }
    }
}

/// What a conversion did.
#[derive(Debug, Clone, PartialEq)]
pub struct Report {
    /// The number of feature strings of the chunker model.
    pub chunker_features: usize,
    /// The number of support vectors of the parser model.
    pub support_vectors: usize,
    /// The number of support vectors with a weight above 0.
    pub positives: usize,
    /// The number of feature strings of the parser model.
    pub parser_features: usize,
    /// The number of pairs of features in the support vectors.
    pub all_pairs: usize,
    /// The number of pairs the pruning keeps.
    pub kept_pairs: usize,
    /// The number of pairs of the converted model: the kept ones whose
    /// weight is not truncated to 0.
    pub pairs: usize,
    /// What the whole-number weights are multiplied by: CaboCha's
    /// normalize factor.
    pub unit: f64,
}

/// A model of CaboCha, converted.
#[derive(Debug, Clone)]
pub struct Converted {
    /// The part-of-speech set of the model.
    pub part_of_speech_set: PartOfSpeechSet,
    /// The chunker.
    pub chunker: ChunkerModel,
    /// The parser.
    pub parser: ParserModel,
    /// What the conversion did.
    pub report: Report,
}

impl Converted {
    /// The model as the bytes of a model file, for the dictionary of the
    /// part-of-speech set. The weights of the parser are not quantized:
    /// they are the whole numbers CaboCha adds up.
    ///
    /// # Returns
    ///
    /// The bytes, or the error of a model that cannot be written.
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        self.to_bytes_for(self.part_of_speech_set.dictionary())
    }

    /// The model as the bytes of a model file for a dictionary of the
    /// part-of-speech set: `unidic-cwj` or `unidic-csj` in place of
    /// `unidic`, for the model for UniDic.
    ///
    /// # Arguments
    ///
    /// * `dictionary` - The name of the dictionary, one of
    ///   [`PartOfSpeechSet::dictionaries`].
    ///
    /// # Returns
    ///
    /// The bytes; [`Error::Cabocha`] for a dictionary that has not the
    /// part-of-speech set of the model, or the error of a model that
    /// cannot be written.
    pub fn to_bytes_for(&self, dictionary: &str) -> Result<Vec<u8>> {
        let dictionaries = self.part_of_speech_set.dictionaries();
        if !dictionaries.contains(&dictionary) {
            return Err(Error::Cabocha(format!(
                "the model is not one for the dictionary {dictionary}: its part-of-speech set is that of {}",
                dictionaries.join(", ")
            )));
        }
        Ok(
            ModelBuilder::new(dictionary, self.chunker.schema().clone())?
                .chunker(&self.chunker)?
                .parser(&self.parser, Quantization::F32)?
                .to_bytes(),
        )
    }
}

/// CaboCha's table for the normalization of a surface.
///
/// # Returns
///
/// The table of `src/normalizer.rule` of CaboCha: the half-width katakana
/// in full width, the full-width letters, digits and signs in ASCII, the
/// spaces as `___`.
pub fn normalization() -> Normalization {
    let rules: Vec<(&str, &str)> = NORMALIZER_RULE
        .lines()
        .filter_map(|line| line.split_once('\t'))
        .collect();
    Normalization::new(&rules).expect("the table of CaboCha is a table")
}

/// The schema CaboCha has for a part-of-speech set: what makes the
/// features of its models.
///
/// For IPA (`src/selector_pat.h` of CaboCha): the function words are 助詞,
/// 助動詞, 動詞,非自立, 動詞,接尾, 形容詞,非自立 and 形容詞,接尾; the
/// head is the last morpheme that is neither one of them nor a 記号; the
/// punctuation is `。` and `、`, and the brackets are ten opening and ten
/// closing ones, each matched as the whole normalized surface. It is not
/// [`Schema::ipadic`], which has more patterns, for the bunsetsu of UD
/// Japanese-GSD.
///
/// For JUMAN: two levels of the part of speech, then the conjugation type,
/// the conjugation form and the base form, as mecab-jumandic has them. The
/// function word is the last morpheme that is not a 特殊, and the head the
/// last that is not a 特殊, a 助詞 or a 接尾辞
/// ([`HeadRule::LastWords`]); the punctuation, the brackets and the
/// normalization are those of IPA.
///
/// For UniDic: four levels of the part of speech, which the chunker and
/// the patterns read; the parser reads two of them
/// ([`PartOfSpeechSet::feature_set`]). The function words are 助詞,
/// 助動詞, 接尾辞,形容詞的, 接尾辞,形状詞的 and 接尾辞,動詞的, and the
/// head is the last morpheme that is neither one of them nor a 空白, a
/// 補助記号 or a 記号. The column of the conjugation form is the fourth,
/// which is the fourth level of the part of speech: CaboCha reads the
/// column after the two levels and the next, whatever it holds, and its
/// model was trained with that.
///
/// # Arguments
///
/// * `part_of_speech_set` - The set.
///
/// # Returns
///
/// The schema.
pub fn schema(part_of_speech_set: PartOfSpeechSet) -> Schema {
    match part_of_speech_set {
        PartOfSpeechSet::Ipa => Schema {
            part_of_speech: 0..4,
            conjugation_type: Some(4),
            conjugation_form: Some(5),
            base_form: Some(6),
            function_words: vec![
                Pattern::new(&["助詞"]),
                Pattern::new(&["助動詞"]),
                Pattern::new(&["動詞", "非自立"]),
                Pattern::new(&["動詞", "接尾"]),
                Pattern::new(&["形容詞", "非自立"]),
                Pattern::new(&["形容詞", "接尾"]),
            ],
            not_heads: Vec::new(),
            particles: vec![Pattern::new(&["助詞"])],
            lexicalized: vec![
                Pattern::new(&["助詞"]),
                Pattern::new(&["副詞"]),
                Pattern::new(&["連体詞"]),
                Pattern::new(&["接続詞"]),
            ],
            symbols: Symbols {
                others: Marks::new(&[&["記号"]], ""),
                commas: Marks::new(&[], "、"),
                periods: Marks::new(&[], "。"),
                open_brackets: Marks::new(&[], "((‘“《「『[〈{"),
                close_brackets: Marks::new(&[], "))’”》」』]〉}"),
                surface: SurfaceRule::OneCharacter,
            },
            normalization: normalization(),
            head_rule: HeadRule::FunctionWordsApart,
        },
        PartOfSpeechSet::Juman => Schema {
            part_of_speech: 0..2,
            conjugation_type: Some(2),
            conjugation_form: Some(3),
            base_form: Some(4),
            function_words: Vec::new(),
            not_heads: vec![Pattern::new(&["助詞"]), Pattern::new(&["接尾辞"])],
            particles: vec![Pattern::new(&["助詞"])],
            lexicalized: vec![
                Pattern::new(&["助詞"]),
                Pattern::new(&["副詞"]),
                Pattern::new(&["連体詞"]),
                Pattern::new(&["接続詞"]),
            ],
            symbols: Symbols {
                others: Marks::new(&[&["特殊"]], ""),
                commas: Marks::new(&[], "、"),
                periods: Marks::new(&[], "。"),
                open_brackets: Marks::new(&[], "((‘“《「『[〈{"),
                close_brackets: Marks::new(&[], "))’”》」』]〉}"),
                surface: SurfaceRule::OneCharacter,
            },
            normalization: normalization(),
            head_rule: HeadRule::LastWords,
        },
        PartOfSpeechSet::Unidic => Schema {
            part_of_speech: 0..4,
            conjugation_type: Some(4),
            conjugation_form: Some(3),
            base_form: Some(7),
            function_words: vec![
                Pattern::new(&["助詞"]),
                Pattern::new(&["助動詞"]),
                Pattern::new(&["接尾辞", "形容詞的"]),
                Pattern::new(&["接尾辞", "形状詞的"]),
                Pattern::new(&["接尾辞", "動詞的"]),
            ],
            not_heads: Vec::new(),
            particles: vec![Pattern::new(&["助詞"])],
            lexicalized: vec![
                Pattern::new(&["助詞"]),
                Pattern::new(&["副詞"]),
                Pattern::new(&["連体詞"]),
                Pattern::new(&["接続詞"]),
            ],
            symbols: Symbols {
                others: Marks::new(&[&["空白"], &["補助記号"], &["記号"]], ""),
                commas: Marks::new(&[], "、"),
                periods: Marks::new(&[], "。"),
                open_brackets: Marks::new(&[], "((‘“《「『[〈{"),
                close_brackets: Marks::new(&[], "))’”》」』]〉}"),
                surface: SurfaceRule::OneCharacter,
            },
            normalization: normalization(),
            head_rule: HeadRule::FunctionWordsApart,
        },
    }
}

/// Reads a value of the header of the parser model, and checks it.
fn check_header(model: &svm::SvmModel, key: &str, accepted: &[&str]) -> Result<()> {
    let value = model
        .header
        .get(key)
        .ok_or_else(|| Error::Cabocha(format!("the parser model has no `{key}` in its header")))?;
    if accepted
        .iter()
        .any(|one| one.eq_ignore_ascii_case(value.trim()))
    {
        Ok(())
    } else {
        Err(Error::Cabocha(format!(
            "the parser model has `{key}: {value}`, and only {} is supported",
            accepted.join(" or ")
        )))
    }
}

/// Converts a model of CaboCha.
///
/// # Arguments
///
/// * `chunker` - The content of the chunker model in text, as
///   `chunk.ipa.txt`.
/// * `parser` - The content of the parser model in text, as `dep.ipa.txt`.
/// * `options` - How the pairs of the parser model are pruned.
///
/// # Returns
///
/// The converted model, or [`Error::Cabocha`] for files that are not the
/// two text models of CaboCha, for a model that is not for IPA, JUMAN or
/// UniDic in UTF-8
/// with a kernel of degree 2, or for options that are not ones: a `sigma`
/// that is not a finite number of 0 or more.
pub fn convert(chunker: &str, parser: &str, options: &Options) -> Result<Converted> {
    if !options.sigma.is_finite() || options.sigma < 0.0 {
        return Err(Error::Cabocha(format!(
            "sigma is {}, and has to be 0 or more",
            options.sigma
        )));
    }

    let support = svm::read(parser)?;
    let name = support.header.get("posset").ok_or_else(|| {
        Error::Cabocha("the parser model has no `posset` in its header".to_string())
    })?;
    let part_of_speech_set = PartOfSpeechSet::from_name(name.trim())?;
    check_header(&support, "degree", &["2"])?;
    check_header(&support, "charset", &["UTF8", "UTF-8"])?;
    if let Some(kind) = support.header.get("type")
        && kind.trim() != "dep"
    {
        return Err(Error::Cabocha(format!(
            "the parser model has `type: {kind}`, and a parser model has `dep`"
        )));
    }
    let bias = support
        .header
        .get("bias")
        .and_then(|bias| bias.trim().parse::<f64>().ok());
    if bias != Some(0.0) {
        return Err(Error::Cabocha(
            "the parser model has no `bias: 0` in its header, and only a model without a bias is supported".to_string(),
        ));
    }
    let schema = schema(part_of_speech_set);

    let crf = crfpp::read(chunker)?;
    if crf.columns != 2 {
        return Err(Error::Cabocha(format!(
            "the chunker model has {} columns, and the chunker of CaboCha has 2: the surface and the part of speech",
            crf.columns
        )));
    }
    let chunker_features = crf.features.len();
    let chunker = ChunkerModel::new(
        schema.clone(),
        vec![Column::Surface, Column::PartOfSpeech],
        Template::parse(&crf.template)?,
        crf.transitions,
        crf.features,
    )?;

    let expansion = svm::expand(&support, options)?;
    // The features by their strings, which is the order of a model; a
    // number of CaboCha without a string is in no support vector.
    let mut order: Vec<u32> = (0..support.names.len() as u32)
        .filter(|number| !support.names[*number as usize].is_empty())
        .collect();
    order.sort_unstable_by_key(|number| support.names[*number as usize].as_bytes());
    let mut numbers = vec![u32::MAX; support.names.len()];
    for (index, number) in order.iter().enumerate() {
        numbers[*number as usize] = index as u32;
    }
    let features: Vec<(String, f32)> = order
        .iter()
        .map(|number| {
            let weight = expansion
                .weights
                .get(*number as usize)
                .copied()
                .unwrap_or(0);
            (support.names[*number as usize].clone(), weight as f32)
        })
        .collect();
    let mut pairs: Vec<((u32, u32), f32)> = expansion
        .pairs
        .iter()
        .map(|((one, other), weight)| {
            let (one, other) = (numbers[*one as usize], numbers[*other as usize]);
            ((one.min(other), one.max(other)), *weight as f32)
        })
        .collect();
    pairs.sort_unstable_by_key(|(pair, _)| *pair);
    let unit = f64::from(expansion.unit);
    let report = Report {
        chunker_features,
        support_vectors: support.vectors.len(),
        positives: expansion.positives,
        parser_features: features.len(),
        all_pairs: expansion.all_pairs,
        kept_pairs: expansion.kept_pairs,
        pairs: pairs.len(),
        unit,
    };
    // CaboCha starts a decision from the bias and adds whole numbers; the
    // bias of a model is not in the unit of its weights.
    let parser = ParserModel::new(
        schema,
        part_of_speech_set.feature_set(),
        f64::from(expansion.bias) * unit,
        features,
        PairWeights::Exact(pairs),
    )?
    .with_unit(unit)?;
    Ok(Converted {
        part_of_speech_set,
        chunker,
        parser,
        report,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lattice::LatticeMorpheme;
    use crate::model::Model;
    use crate::parser::Classifier;

    #[test]
    fn the_table_is_the_one_of_cabocha() {
        let table = normalization();
        // 182 lines, one of them twice.
        assert_eq!(NORMALIZER_RULE.lines().count(), 182);
        assert_eq!(table.rules().count(), 181);
        for (surface, expected) in [
            ("ガイド", "ガイド"),
            ("ABC123", "ABC123"),
            ("(株)", "(株)"),
            ("「ヲ」", "「ヲ」"),
            ("ヴ", "ヴ"),
            (" ", "___"),
            (" ", "___"),
            ("―", "-"),
            ("-", "-"),
            // What the table does not have stays: the full-width comma and
            // the period, the kanji, the hiragana.
            (",.読ん、。", ",.読ん、。"),
        ] {
            assert_eq!(table.apply(surface), expected, "{surface}");
        }
    }

    #[test]
    fn the_schema_is_the_rule_of_cabocha_for_ipa() {
        let schema = schema(PartOfSpeechSet::Ipa);
        let morpheme = |surface: &str, features: &str| LatticeMorpheme::new(surface, features);
        // The head is the last morpheme that is not a function word or a
        // 記号: する is a head here, and it is not for `Schema::ipadic`.
        let bunsetsu = [
            morpheme("利用", "名詞,サ変接続,*,*,*,*,利用,リヨウ,リヨー"),
            morpheme("し", "動詞,自立,*,*,サ変・スル,連用形,する,シ,シ"),
            morpheme("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ"),
            morpheme("。", "記号,句点,*,*,*,*,。,。,。"),
        ];
        assert_eq!(schema.positions(&bunsetsu), Some((1, 2)));
        assert_eq!(Schema::ipadic().positions(&bunsetsu), Some((0, 2)));
        // A formal noun is a head too.
        let bunsetsu = [
            morpheme("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
            morpheme("こと", "名詞,非自立,一般,*,*,*,こと,コト,コト"),
            morpheme("が", "助詞,格助詞,一般,*,*,*,が,ガ,ガ"),
        ];
        assert_eq!(schema.positions(&bunsetsu), Some((1, 2)));
        // Without a function word after the head, the head is it.
        assert_eq!(schema.positions(&bunsetsu[..2]), Some((1, 1)));

        // Punctuation and brackets by the normalized surface, as a whole.
        let noun = "名詞,サ変接続,*,*,*,*,*";
        assert!(schema.is_comma(&morpheme("、", noun)));
        assert!(schema.is_period(&morpheme("。", noun)));
        assert!(!schema.is_comma(&morpheme(",", noun)));
        assert!(!schema.is_comma(&morpheme(",", noun)));
        assert!(!schema.is_period(&morpheme(".", noun)));
        for open in ["(", "(", "‘", "“", "《", "「", "『", "[", "〈", "「"] {
            assert!(schema.is_open_bracket(&morpheme(open, noun)), "{open}");
        }
        for close in [")", ")", "》", "」", "』", "]", "〉", "」"] {
            assert!(schema.is_close_bracket(&morpheme(close, noun)), "{close}");
        }
        for other in ["[", "【", "((", "「「", ""] {
            assert!(!schema.is_open_bracket(&morpheme(other, noun)), "{other}");
        }
        // As in CaboCha, the table makes `{`, `}`, `’` and `”` the
        // characters of ASCII before they are matched, and those are not
        // among its brackets.
        assert!(!schema.is_open_bracket(&morpheme("{", noun)));
        assert!(!schema.is_open_bracket(&morpheme("{", noun)));
        for close in ["}", "}", "’", "”", "'", "\""] {
            assert!(!schema.is_close_bracket(&morpheme(close, noun)), "{close}");
        }
        // A bracket that is an unknown word is still a word.
        assert!(!schema.is_symbol(&morpheme("(", noun)));
        assert!(schema.is_symbol(&morpheme("x", "記号,一般,*,*,*,*,*")));
        assert!(schema.is_particle(&[morpheme("が", "助詞,格助詞,一般,*,*,*,が,ガ,ガ")], 0));
        assert_eq!(schema.width(), 7);
    }

    #[test]
    fn converts_the_two_models_into_one() {
        let converted = convert(
            crfpp::tests::MODEL,
            svm::tests::MODEL,
            &svm::tests::unpruned(),
        )
        .unwrap();
        assert_eq!(converted.part_of_speech_set, PartOfSpeechSet::Ipa);
        assert_eq!(
            converted.report,
            Report {
                chunker_features: 3,
                support_vectors: 4,
                positives: 2,
                parser_features: 5,
                all_pairs: 7,
                kept_pairs: 7,
                pairs: 7,
                unit: f64::from(2.25f32 / 1_048_575.0),
            }
        );

        // The parser scores with the whole numbers of CaboCha: the bias,
        // the features and the pairs of a decision, times the unit.
        let parser = &converted.parser;
        let unit = converted.report.unit;
        let whole = |weight: f32| f64::from((weight / (2.25f32 / 1_048_575.0)) as i32);
        let id = |name: &str| parser.id(name).unwrap();
        assert_eq!(parser.id("DIST:6-"), None);
        assert_eq!(parser.score(&[]), whole(0.375) * unit);
        assert_eq!(
            parser.score(&[id("DHS:読む")]),
            (whole(0.375) + 1_048_575.0) * unit
        );
        let mut both = [id("DIST:1"), id("DHS:読む")];
        both.sort_unstable();
        assert_eq!(
            parser.score(&both),
            (whole(0.375) + whole(0.375) + 1_048_575.0 + whole(1.0)) * unit
        );
        // A negative decision: the kernel gives -0.375.
        let mut negative = [id("DIST:1"), id("GNB:1"), id("SHS:本")];
        negative.sort_unstable();
        let score = parser.score(&negative);
        assert!((score + 0.375).abs() < 8.0 * unit, "{score}");
        assert_eq!(parser.feature_set(), &FeatureSet::cabocha());
        assert_eq!(parser.schema(), &schema(PartOfSpeechSet::Ipa));

        // The file is one for IPADIC, with both parts, and scores as the
        // model in memory.
        let model = Model::new(converted.to_bytes().unwrap()).unwrap();
        assert_eq!(model.dictionary(), "ipadic");
        assert_eq!(model.schema(), &schema(PartOfSpeechSet::Ipa));
        assert!(model.chunker().is_some());
        let part = model.parser().unwrap();
        let classifier = part.classifier();
        for features in [vec![], negative.to_vec(), both.to_vec()] {
            assert_eq!(classifier.score(&features), parser.score(&features));
        }
    }

    #[test]
    fn the_converted_model_analyzes_with_the_features_of_cabocha() {
        // A chunker that starts a bunsetsu at a noun after a particle, and
        // a parser that knows one feature of the source: the normalized
        // surface of its head.
        // After `B` and after `I` the chunker goes on with `I`, unless a
        // noun or a verb follows a particle.
        let chunker = "version: 100\ncost-factor: 1\nmaxid: 8\nxsize: 2\n\nB\nI\n\nU00:%x[0,0]\nU01:%x[-1,1]/%x[0,1]\nB\n\n0 B\n4 U01:助詞-格助詞-一般/名詞-一般\n6 U01:助詞-格助詞-一般/動詞-自立\n\n-1\n1\n-1\n1\n5\n-5\n5\n-5\n";
        let parser = "degree: 2\nbias: 0.000000\ncharset: UTF8\nposset: IPA\n\n0 SHS:ABC\n1 DIST:1\n\n1 0\n-0.25 1\n";
        let converted = convert(chunker, parser, &svm::tests::unpruned()).unwrap();
        let model = Model::new(converted.to_bytes().unwrap()).unwrap();
        let sentence = |first: &str| {
            vec![
                LatticeMorpheme::new(first, "名詞,一般,*,*,*,*,*"),
                LatticeMorpheme::new("が", "助詞,格助詞,一般,*,*,*,が,ガ,ガ"),
                LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
                LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
                LatticeMorpheme::new("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
            ]
        };
        // ABC is ABC for the model: its bunsetsu depends on the next.
        let bunsetsu = model.analyze(&sentence("ABC")).unwrap();
        let heads: Vec<Option<usize>> = bunsetsu.iter().map(|one| one.head).collect();
        assert_eq!(heads, [Some(1), Some(2), None]);
        // Another word has no positive feature, and waits for the last.
        let bunsetsu = model.analyze(&sentence("彼")).unwrap();
        let heads: Vec<Option<usize>> = bunsetsu.iter().map(|one| one.head).collect();
        assert_eq!(heads, [Some(2), Some(2), None]);
    }

    #[test]
    fn a_model_for_juman_is_converted_with_the_schema_of_juman() {
        // The chunker starts a bunsetsu at a verb or a noun after a
        // particle, and at a noun after a suffix: its second column is the
        // two levels of the part of speech of JUMAN, and the one level of
        // a verb, whose second is `*`.
        let chunker = "version: 100\ncost-factor: 1\nmaxid: 10\nxsize: 2\n\nB\nI\n\nU00:%x[0,0]\nU01:%x[-1,1]/%x[0,1]\nB\n\n0 B\n4 U01:助詞-格助詞/動詞\n6 U01:助詞-格助詞/名詞-普通名詞\n8 U01:接尾辞-動詞性接尾辞/名詞-普通名詞\n\n-1\n1\n-1\n1\n5\n-5\n5\n-5\n5\n-5\n";
        // The parser knows the conjugation form of the function word of
        // the source: a bunsetsu whose function word is in 基本形 depends
        // on the next one.
        let parser = "degree: 2\nbias: 0.000000\ncharset: UTF8\nposset: JUMAN\n\n0 SFF:基本形\n1 DIST:1\n\n1 0\n-0.25 1\n";
        let converted = convert(chunker, parser, &svm::tests::unpruned()).unwrap();
        assert_eq!(converted.part_of_speech_set, PartOfSpeechSet::Juman);
        let juman = schema(PartOfSpeechSet::Juman);
        assert_eq!(juman.part_of_speech, 0..2);
        assert_eq!(juman.conjugation_form, Some(3));
        assert_eq!(juman.head_rule, HeadRule::LastWords);
        assert_eq!(converted.parser.schema(), &juman);
        assert_ne!(juman, schema(PartOfSpeechSet::Ipa));

        let model = Model::new(converted.to_bytes().unwrap()).unwrap();
        assert_eq!(model.dictionary(), "jumandic");
        assert_eq!(model.schema(), &juman);
        // 彼 が / 読んで いる / 本 を / 買う 。 with the lines of
        // mecab-jumandic.
        let sentence = vec![
            LatticeMorpheme::new("彼", "名詞,普通名詞,*,*,彼,かれ,*"),
            LatticeMorpheme::new("が", "助詞,格助詞,*,*,が,が,*"),
            LatticeMorpheme::new("読んで", "動詞,*,子音動詞マ行,タ系連用テ形,読む,よんで,*"),
            LatticeMorpheme::new("いる", "接尾辞,動詞性接尾辞,母音動詞,基本形,いる,いる,*"),
            LatticeMorpheme::new("本", "名詞,普通名詞,*,*,本,ほん,*"),
            LatticeMorpheme::new("を", "助詞,格助詞,*,*,を,を,*"),
            LatticeMorpheme::new("買う", "動詞,*,子音動詞ワ行,基本形,買う,かう,*"),
            LatticeMorpheme::new("。", "特殊,句点,*,*,。,。,*"),
        ];
        let bunsetsu = model.analyze(&sentence).unwrap();
        let ranges: Vec<_> = bunsetsu.iter().map(|one| one.morphemes.clone()).collect();
        assert_eq!(ranges, [0..2, 2..4, 4..6, 6..8]);
        // The suffix is the function word of 読んで いる, and the verb its
        // head; the period is neither of 買う 。.
        let positions: Vec<_> = bunsetsu.iter().map(|one| one.positions).collect();
        assert_eq!(
            positions,
            [Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 0))]
        );
        // 読んで いる ends in 基本形, the fourth column of its function
        // word, and depends on the next bunsetsu, 本 を: without that
        // feature the score of the decision is 0, and it would not. 彼 が
        // then depends on 本 を too: a decision at a distance the model
        // does not know has the score of no feature, 0.75.
        let heads: Vec<Option<usize>> = bunsetsu.iter().map(|one| one.head).collect();
        assert_eq!(heads, [Some(2), Some(2), Some(3), None]);
        // (1 + 1)^2 for the vector with the form, and -0.25 (1 + 1)^2 for
        // the one with the distance.
        let score = bunsetsu[1].score.unwrap();
        assert!((score - 3.0).abs() < 1e-6, "{score}");
    }

    #[test]
    fn a_model_for_unidic_is_converted_with_two_levels_for_the_parser() {
        // The chunker reads four levels of the part of speech: it starts a
        // bunsetsu at a common noun after a name, and at a verb after a
        // case particle.
        let chunker = "version: 100\ncost-factor: 1\nmaxid: 8\nxsize: 2\n\nB\nI\n\nU00:%x[0,0]\nU01:%x[-1,1]/%x[0,1]\nB\n\n0 B\n4 U01:名詞-固有名詞-人名-名/名詞-普通名詞-一般\n6 U01:助詞-格助詞/動詞-一般\n\n-1\n1\n-1\n1\n5\n-5\n5\n-5\n";
        // The parser reads two, and the fourth column as the conjugation
        // form: a bunsetsu whose function word has 名 there depends on the
        // next one.
        let parser = "degree: 2\nbias: 0.000000\ncharset: UTF8\nposset: UNIDIC\n\n0 SFF:名\n1 DIST:1\n\n1 0\n-0.25 1\n";
        let converted = convert(chunker, parser, &svm::tests::unpruned()).unwrap();
        assert_eq!(converted.part_of_speech_set, PartOfSpeechSet::Unidic);
        let unidic = schema(PartOfSpeechSet::Unidic);
        assert_eq!(unidic.part_of_speech, 0..4);
        assert_eq!(unidic.conjugation_form, Some(3));
        assert_eq!(unidic.head_rule, HeadRule::FunctionWordsApart);
        assert_eq!(converted.parser.schema(), &unidic);
        let two = FeatureSet::cabocha().with_part_of_speech_levels(2).unwrap();
        assert_eq!(converted.parser.feature_set(), &two);
        assert_eq!(PartOfSpeechSet::Unidic.feature_set(), two);
        // The other sets read every level of their schema.
        for set in [PartOfSpeechSet::Ipa, PartOfSpeechSet::Juman] {
            assert_eq!(set.feature_set(), FeatureSet::cabocha());
        }

        // The limit is in the file.
        let model = Model::new(converted.to_bytes().unwrap()).unwrap();
        assert_eq!(model.dictionary(), "unidic");
        assert_eq!(model.schema(), &unidic);
        assert_eq!(model.parser().unwrap().feature_set(), &two);
        // 太郎 / 本 を / 読む 。 with the first columns of UniDic.
        let sentence = vec![
            LatticeMorpheme::new("太郎", "名詞,固有名詞,人名,名,*,*,タロウ,タロウ"),
            LatticeMorpheme::new("本", "名詞,普通名詞,一般,*,*,*,ホン,本"),
            LatticeMorpheme::new("を", "助詞,格助詞,*,*,*,*,ヲ,を"),
            LatticeMorpheme::new("読む", "動詞,一般,*,*,五段-マ行,終止形-一般,ヨム,読む"),
            LatticeMorpheme::new("。", "補助記号,句点,*,*,*,*,,。"),
        ];
        let bunsetsu = model.analyze(&sentence).unwrap();
        let ranges: Vec<_> = bunsetsu.iter().map(|one| one.morphemes.clone()).collect();
        assert_eq!(ranges, [0..1, 1..3, 3..5]);
        // The period is a 補助記号, and neither the head nor the function
        // word of 読む 。.
        let positions: Vec<_> = bunsetsu.iter().map(|one| one.positions).collect();
        assert_eq!(positions, [Some((0, 0)), Some((0, 1)), Some((0, 0))]);
        // 太郎 has 名 in its fourth column, and depends on 本 を.
        let heads: Vec<Option<usize>> = bunsetsu.iter().map(|one| one.head).collect();
        assert_eq!(heads, [Some(1), Some(2), None]);
        let score = bunsetsu[0].score.unwrap();
        assert!((score - 3.0).abs() < 1e-6, "{score}");
    }

    #[test]
    fn a_converted_model_is_for_a_dictionary_of_its_set() {
        let chunker = crfpp::tests::MODEL;
        let parser = svm::tests::MODEL;
        let options = svm::tests::unpruned();
        assert_eq!(PartOfSpeechSet::Ipa.dictionaries(), ["ipadic"]);
        assert_eq!(PartOfSpeechSet::Juman.dictionaries(), ["jumandic"]);
        assert_eq!(
            PartOfSpeechSet::Unidic.dictionaries(),
            ["unidic", "unidic-cwj", "unidic-csj"]
        );
        // The model for UniDic is one for each of the three dictionaries.
        let unidic = convert(
            chunker,
            &parser.replace("posset: IPA", "posset: UNIDIC"),
            &options,
        )
        .unwrap();
        for dictionary in ["unidic", "unidic-cwj", "unidic-csj"] {
            let model = Model::new(unidic.to_bytes_for(dictionary).unwrap()).unwrap();
            assert_eq!(model.dictionary(), dictionary);
        }
        assert_eq!(
            unidic.to_bytes_for("ipadic").unwrap_err().to_string(),
            "the model is not one for the dictionary ipadic: its part-of-speech set is that of unidic, unidic-cwj, unidic-csj"
        );
        // The model for IPA is one for IPADIC alone.
        let ipa = convert(chunker, parser, &options).unwrap();
        assert_eq!(ipa.to_bytes_for("ipadic").unwrap(), ipa.to_bytes().unwrap());
        assert_eq!(
            ipa.to_bytes_for("unidic").unwrap_err().to_string(),
            "the model is not one for the dictionary unidic: its part-of-speech set is that of ipadic"
        );
    }

    #[test]
    fn refuses_what_is_not_a_model_it_converts() {
        let chunker = crfpp::tests::MODEL;
        let parser = svm::tests::MODEL;
        let message = |chunker: &str, parser: &str, options: &Options| {
            convert(chunker, parser, options).unwrap_err().to_string()
        };
        let options = Options::default();
        for (parser, expected) in [
            (
                parser.replace("posset: IPA", "posset: PENN"),
                "the part-of-speech set \"PENN\", which is not one of CaboCha",
            ),
            (parser.replace("posset: IPA\n", ""), "has no `posset`"),
            (
                parser.replace("degree: 2", "degree: 3"),
                "has `degree: 3`, and only 2 is supported",
            ),
            (parser.replace("degree: 2\n", ""), "has no `degree`"),
            (
                parser.replace("charset: UTF8", "charset: EUC-JP"),
                "has `charset: EUC-JP`, and only UTF8 or UTF-8 is supported",
            ),
            (
                parser.replace("type: dep", "type: chunk"),
                "has `type: chunk`",
            ),
            (
                parser.replace("bias: 0.000000", "bias: 0.500000"),
                "has no `bias: 0`",
            ),
            (parser.replace("bias: 0.000000\n", ""), "has no `bias: 0`"),
        ] {
            let message = message(chunker, &parser, &options);
            assert!(message.contains(expected), "{expected}: {message}");
        }
        // The two files the other way round.
        assert!(message(parser, chunker, &options).starts_with("the parser model "));
        assert!(message(chunker, chunker, &options).starts_with("the parser model "));
        assert!(message(parser, parser, &options).starts_with("the chunker model "));
        let three = chunker.replace("xsize: 2", "xsize: 3");
        assert!(message(&three, parser, &options).contains("has 3 columns"));
        for sigma in [-0.1, f64::NAN, f64::INFINITY] {
            let options = Options { sigma, ..options };
            assert!(message(chunker, parser, &options).starts_with("sigma is "));
        }
    }

    #[test]
    fn the_defaults_are_those_of_cabocha_model_index() {
        assert_eq!(
            Options::default(),
            Options {
                sigma: 0.0001,
                min_support: 2,
                frequent_features: 3000
            }
        );
        assert_eq!(PartOfSpeechSet::Ipa.dictionary(), "ipadic");
        assert_eq!(PartOfSpeechSet::Juman.dictionary(), "jumandic");
        assert_eq!(PartOfSpeechSet::Unidic.dictionary(), "unidic");
    }
}