lindera-dependency 7.2.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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
//! Training the chunker, with the conditional random fields of
//! `lindera-crf`.
//!
//! Each sentence becomes a lattice with, at each morpheme, one edge per
//! label; the first morpheme has the edge of `B` only. A feature of
//! `lindera-crf` stands for a pair of a feature string of the template and a
//! label, and the bigram feature of an edge is its label, so that the
//! bigram weights are the transitions between labels. After training, the
//! weights that are not 0 are copied into a [`ChunkerModel`], which needs
//! `lindera-crf` no more.

use std::collections::HashMap;
use std::num::NonZeroU32;

use lindera_crf::{Edge, FeatureProvider, FeatureSet, Lattice, RawModel, StopReason, Trainer};

use super::columns::Column;
use super::model::{ChunkerModel, Label};
use super::template::Template;
use super::{extract, words};
use crate::error::{Error, Result};
use crate::morpheme::Morpheme;
use crate::schema::Schema;
use crate::sentence::Sentence;

/// The regularization of the training.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Regularization {
    /// L1: most weights become 0, and the model is small.
    L1,
    /// L2: every feature of the training data keeps a weight.
    L2,
}

/// The settings of a training.
#[derive(Debug, Clone, PartialEq)]
pub struct TrainOptions {
    /// The schema of the dictionary of the training data.
    pub schema: Schema,
    /// The columns the template reads, in the order of their numbers in the
    /// template.
    pub columns: Vec<Column>,
    /// The template.
    pub template: Template,
    /// The regularization.
    pub regularization: Regularization,
    /// The coefficient of the regularization: the larger, the smaller the
    /// weights. With [`Regularization::L2`] it is `1 / C` of CRF++.
    pub lambda: f64,
    /// The largest number of iterations of the optimizer.
    pub max_iterations: u64,
    /// The number of threads.
    pub threads: usize,
    /// Whether texts that do not end as a sentence does are made from the
    /// sentences and added to the training data: each sentence without its
    /// last period, and a phrase cut out of each sentence. See [`train`].
    pub unfinished_texts: bool,
}

impl Default for TrainOptions {
    /// The schema of IPADIC; the surface, the part of speech and the
    /// conjugation form as columns, with the default template; L1
    /// regularization with the coefficient 0.5; at most 1,000 iterations;
    /// one thread. The columns, the template and the regularization are the
    /// ones a cross-validation on UD Japanese-GSD chose (#1421).
    fn default() -> Self {
        Self {
            schema: Schema::ipadic(),
            columns: vec![
                Column::Surface,
                Column::PartOfSpeech,
                Column::ConjugationForm,
            ],
            template: Template::default(),
            regularization: Regularization::L1,
            lambda: 0.5,
            max_iterations: 1000,
            threads: 1,
            unfinished_texts: true,
        }
    }
}

impl TrainOptions {
    /// The settings the chunker of a dictionary of Lindera is trained with:
    /// the ones of the model that is released for it.
    ///
    /// For `ipadic` they are the defaults. For `unidic`, `unidic-cwj` and
    /// `unidic-csj` they are the schema of UniDic, the base form as a
    /// fourth column with [`Template::unidic`], and L1 regularization with
    /// the coefficient 0.25: what a cross-validation on UD Japanese-GSD
    /// chose with UniDic CWJ, and what holds with the two others (#1441).
    ///
    /// # Arguments
    ///
    /// * `dictionary` - The name of the dictionary, as
    ///   [`Schema::for_dictionary`] takes it.
    ///
    /// # Returns
    ///
    /// The settings, or `None` for a dictionary without a schema.
    pub fn for_dictionary(dictionary: &str) -> Option<Self> {
        let schema = Schema::for_dictionary(dictionary)?;
        if dictionary == "ipadic" {
            return Some(Self {
                schema,
                ..Self::default()
            });
        }
        Some(Self {
            schema,
            columns: vec![
                Column::Surface,
                Column::PartOfSpeech,
                Column::ConjugationForm,
                Column::BaseForm,
            ],
            template: Template::unidic(),
            lambda: 0.25,
            ..Self::default()
        })
    }
}

/// A trained chunker model, and how its training ended.
#[derive(Debug, Clone, PartialEq)]
pub struct Trained {
    /// The model.
    pub model: ChunkerModel,
    /// The number of iterations the optimizer ran.
    pub iterations: u64,
    /// Whether the optimizer converged; `false` when it stopped at the
    /// largest number of iterations or could make no progress.
    pub converged: bool,
}

/// The feature of `lindera-crf` for a feature string and a label.
///
/// # Arguments
///
/// * `string` - The index of the feature string, from 0.
/// * `label` - The label.
///
/// # Returns
///
/// The feature, from 1: the strings in turn, `B` before `I`.
fn feature_id(string: u32, label: Label) -> Option<NonZeroU32> {
    string
        .checked_mul(2)?
        .checked_add(1 + label.index() as u32)
        .and_then(NonZeroU32::new)
}

/// The bigram feature of an edge with a label: 1 for `B`, 2 for `I`.
///
/// # Arguments
///
/// * `label` - The label.
///
/// # Returns
///
/// The feature.
fn bigram_id(label: Label) -> Option<NonZeroU32> {
    NonZeroU32::new(label.index() as u32 + 1)
}

/// An error of this module from an error of `lindera-crf`.
///
/// # Arguments
///
/// * `error` - The error.
///
/// # Returns
///
/// [`Error::Chunker`] with its message.
fn crf_error(error: lindera_crf::errors::RucrfError) -> Error {
    Error::Chunker(format!("training failed: {error}"))
}

/// Adds the edge of a label at a position of a lattice.
///
/// # Arguments
///
/// * `lattice` - The lattice.
/// * `provider` - Where the features of the edge are registered.
/// * `position` - The position.
/// * `label` - The label.
/// * `strings` - The indices of the feature strings of the position that
///   have features.
///
/// # Returns
///
/// The label `lindera-crf` gave the edge, or [`Error::Chunker`].
fn add_edge(
    lattice: &mut Lattice,
    provider: &mut FeatureProvider,
    position: usize,
    label: Label,
    strings: &[u32],
) -> Result<NonZeroU32> {
    let too_many = || Error::Chunker("too many feature strings".to_string());
    let unigram = strings
        .iter()
        .map(|&string| feature_id(string, label).ok_or_else(too_many))
        .collect::<Result<Vec<NonZeroU32>>>()?;
    let bigram = [bigram_id(label)];
    let edge_label = provider
        .add_feature_set(FeatureSet::new(&unigram, &bigram, &bigram))
        .map_err(crf_error)?;
    lattice
        .add_edge(position, Edge::new(position + 1, edge_label))
        .map_err(crf_error)?;
    Ok(edge_label)
}

/// The model of `lindera-crf` after training, and what its features stand
/// for.
struct Raw {
    /// The model.
    model: RawModel,
    /// The index of each feature string.
    strings: HashMap<String, u32>,
    /// The number of iterations the optimizer ran.
    iterations: u64,
    /// Whether the optimizer converged.
    converged: bool,
}

/// Where the texts that do not end as a sentence does end in a sentence:
/// what [`TrainOptions::unfinished_texts`] adds to the training data.
///
/// The sentences of a corpus end with a period, so a chunker trained on
/// them alone has learned the end of a text from periods only, and cuts the
/// last bunsetsu of a title, of a noun phrase or of a query wrongly. Two
/// texts are made from a sentence, both a start of it:
///
/// - the sentence without its last period;
/// - a phrase: the sentence up to the first bunsetsu, from the second one
///   to the one before the last, that ends with particles after another
///   word, without those particles (人を噛んだ犬 from 人を噛んだ犬が…).
///   The word before the particles is of any part of speech: phrases
///   that end with a noun only measured the same on UD Japanese-GSD and
///   PUD (#1499), and need the name a dictionary gives its nouns.
///
/// # Arguments
///
/// * `schema` - The schema of the dictionary of the words.
/// * `words` - The words of the sentence: its morphemes without the spaces.
/// * `labels` - The label of each word.
///
/// # Returns
///
/// The numbers of words of the texts, each smaller than the number of words
/// of the sentence and larger than 0; none for a sentence that gives none.
fn unfinished_ends<M: Morpheme>(schema: &Schema, words: &[M], labels: &[Label]) -> Vec<usize> {
    let mut ends = Vec::new();
    if words.len() > 1 && schema.is_period(&words[words.len() - 1]) {
        ends.push(words.len() - 1);
    }
    let starts: Vec<usize> = (0..labels.len())
        .filter(|&index| index == 0 || labels[index] == Label::Begin)
        .collect();
    for number in 1..starts.len().saturating_sub(1) {
        let bunsetsu = &words[starts[number]..starts[number + 1]];
        let mut end = bunsetsu.len();
        while end > 0 && schema.is_particle(bunsetsu, end - 1) {
            end -= 1;
        }
        if end == 0 || end == bunsetsu.len() {
            continue;
        }
        ends.push(starts[number] + end);
        break;
    }
    ends
}

/// Trains a model of `lindera-crf`.
///
/// # Arguments
///
/// * `sentences` - The training data.
/// * `options` - The settings.
///
/// # Returns
///
/// The model, or [`Error::Chunker`]: see [`train`].
fn train_raw<M: Morpheme>(sentences: &[Sentence<M>], options: &TrainOptions) -> Result<Raw> {
    if options.template.columns() > options.columns.len() {
        return Err(Error::Chunker(format!(
            "the template reads {} columns, and {} are given",
            options.template.columns(),
            options.columns.len()
        )));
    }

    let mut strings: HashMap<String, u32> = HashMap::new();
    let mut provider = FeatureProvider::new();
    let mut lattices = Vec::new();
    for (index, sentence) in sentences.iter().enumerate() {
        sentence.check()?;
        if sentence.morphemes.is_empty() {
            continue;
        }
        if sentence.bunsetsu.is_empty() {
            return Err(Error::Chunker(format!(
                "sentence {} of the training data has no bunsetsu",
                index + 1
            )));
        }
        let mut starts = vec![false; sentence.morphemes.len()];
        for bunsetsu in &sentence.bunsetsu {
            starts[bunsetsu.morphemes.start] = true;
        }
        // The words: the chunker does not read a space (`Chunker::chunk`),
        // so the training does not either. A bunsetsu that starts with
        // spaces starts at its first word.
        let words = words(&sentence.morphemes);
        if words.is_empty() {
            continue;
        }
        let mut gold = Vec::with_capacity(words.len());
        let mut next = 0;
        for &word in &words {
            gold.push(if starts[next..=word].contains(&true) {
                Label::Begin
            } else {
                Label::Inside
            });
            next = word + 1;
        }
        let kept: Vec<&M> = words
            .iter()
            .map(|&index| &sentence.morphemes[index])
            .collect();

        // The sentences of the text: the chunker gives each to the model on
        // its own (`Schema::sentence_starts`), so each is trained on apart.
        // The first word of a sentence starts a bunsetsu, whatever the
        // answer has there. A sentence of the corpus is one sentence, and
        // has one part.
        let mut from = 0;
        for to in options
            .schema
            .sentence_starts(&kept)
            .into_iter()
            .chain([kept.len()])
        {
            let kept = &kept[from..to];
            let mut gold = gold[from..to].to_vec();
            gold[0] = Label::Begin;
            from = to;
            // The sentence, then the texts made from it: each is the words of
            // the sentence up to an end, with the labels they have there.
            let mut ends = vec![kept.len()];
            if options.unfinished_texts {
                ends.extend(unfinished_ends(&options.schema, kept, &gold));
            }
            for end in ends {
                let features = extract(
                    &options.schema,
                    &options.columns,
                    &options.template,
                    &kept[..end],
                );
                let mut lattice = Lattice::new(features.len()).map_err(crf_error)?;
                for (position, features) in features.into_iter().enumerate() {
                    let ids: Vec<u32> = features
                        .into_iter()
                        .map(|feature| {
                            let next = strings.len() as u32;
                            *strings.entry(feature).or_insert(next)
                        })
                        .collect();
                    // The gold edge first: `lindera-crf` takes the first edge of
                    // a position as the positive example. The first morpheme
                    // always starts a bunsetsu, so it has no other edge.
                    add_edge(&mut lattice, &mut provider, position, gold[position], &ids)?;
                    if position > 0 {
                        let other = match gold[position] {
                            Label::Begin => Label::Inside,
                            Label::Inside => Label::Begin,
                        };
                        add_edge(&mut lattice, &mut provider, position, other, &ids)?;
                    }
                }
                lattices.push(lattice);
            }
        }
    }
    if lattices.is_empty() {
        return Err(Error::Chunker(
            "the training data has no sentence".to_string(),
        ));
    }

    let regularization = match options.regularization {
        Regularization::L1 => lindera_crf::Regularization::L1,
        Regularization::L2 => lindera_crf::Regularization::L2,
    };
    let trainer = Trainer::new()
        .regularization(regularization, options.lambda)
        .map_err(crf_error)?
        .max_iter(options.max_iterations)
        .map_err(crf_error)?
        .n_threads(options.threads)
        .map_err(crf_error)?;
    let (model, stats) = trainer.train_with_stats(&lattices, provider);
    Ok(Raw {
        model,
        strings,
        iterations: stats.iterations,
        converged: stats.stop_reason == StopReason::Converged,
    })
}

/// Copies the weights of a model of `lindera-crf` into a model of the
/// chunker.
///
/// # Arguments
///
/// * `raw` - The trained model.
/// * `options` - The settings it was trained with.
///
/// # Returns
///
/// The model, with the feature strings that have a weight that is not 0;
/// or the error of [`ChunkerModel::new`].
fn chunker_model(raw: &Raw, options: &TrainOptions) -> Result<ChunkerModel> {
    let mut features = HashMap::new();
    for (feature, &string) in &raw.strings {
        let mut weights = [0.0; 2];
        for label in Label::ALL {
            if let Some(id) = feature_id(string, label) {
                weights[label.index()] = raw.model.unigram_weight(&[id]);
            }
        }
        if weights != [0.0; 2] {
            features.insert(feature.clone(), weights);
        }
    }

    // The bigram weight of `lindera-crf` between a left and a right bigram
    // feature; 0 stands for the start of the sentence on the left and for
    // its end on the right. The bigram features are the label numbers.
    let mut transitions = [[0.0; 3]; 3];
    let indices = raw.model.bigram_weight_indices();
    for (from, row) in transitions.iter_mut().enumerate() {
        for (to, weight) in row.iter_mut().enumerate() {
            if let Some(&index) = indices.get(from).and_then(|map| map.get(&(to as u32))) {
                *weight = raw.model.weights()[index as usize];
            }
        }
    }

    ChunkerModel::new(
        options.schema.clone(),
        options.columns.clone(),
        options.template.clone(),
        transitions,
        features,
    )
}

/// Trains a chunker model.
///
/// # Arguments
///
/// * `sentences` - The training data: sentences with their bunsetsu. A
///   sentence without morphemes is skipped. A text of several sentences
///   is cut where the chunker cuts one ([`Schema::sentence_starts`]), and
///   each part is training data of its own.
/// * `options` - The settings.
///
/// # Returns
///
/// The model and how the training ended, or an error:
/// [`Error::Structure`] for a sentence [`Sentence::check`] refuses,
/// [`Error::Chunker`] for a template that reads more columns than are
/// given, a sentence without bunsetsu, training data without a sentence, or
/// settings `lindera-crf` refuses (a coefficient that is negative or not
/// finite, no iteration, no thread).
pub fn train<M: Morpheme>(sentences: &[Sentence<M>], options: &TrainOptions) -> Result<Trained> {
    let raw = train_raw(sentences, options)?;
    Ok(Trained {
        model: chunker_model(&raw, options)?,
        iterations: raw.iterations,
        converged: raw.converged,
    })
}

#[cfg(test)]
mod tests {
    use lindera_crf::Model;

    use super::*;
    use crate::chunker::Chunker;
    use crate::lattice::{self, LatticeMorpheme};
    use crate::model::{Model as ModelFile, ModelBuilder};

    /// The labels `search_best_path` of `lindera-crf` gives a sentence, for
    /// the trained model.
    fn crf_labels(raw: &mut Raw, features: &[Vec<String>]) -> Vec<Label> {
        let mut lattice = Lattice::new(features.len()).unwrap();
        let mut labels = HashMap::new();
        for (position, features) in features.iter().enumerate() {
            let ids: Vec<u32> = features
                .iter()
                .filter_map(|feature| raw.strings.get(feature).copied())
                .collect();
            for label in Label::ALL {
                if position == 0 && label == Label::Inside {
                    continue;
                }
                let edge_label = add_edge(
                    &mut lattice,
                    raw.model.feature_provider(),
                    position,
                    label,
                    &ids,
                )
                .unwrap();
                labels.insert(edge_label, label);
            }
        }
        let (path, _) = raw.model.search_best_path(&lattice);
        path.iter().map(|edge| labels[&edge.label()]).collect()
    }

    /// The labels of the bunsetsu of a sentence.
    fn gold_labels<M>(sentence: &Sentence<M>) -> Vec<Label> {
        let mut labels = vec![Label::Inside; sentence.morphemes.len()];
        for bunsetsu in &sentence.bunsetsu {
            labels[bunsetsu.morphemes.start] = Label::Begin;
        }
        labels
    }

    /// Checks that the chunker and `search_best_path` give every sentence
    /// the same labels, and returns the number of sentences whose labels
    /// are those of the answer.
    fn same_labels(
        raw: &mut Raw,
        options: &TrainOptions,
        sentences: &[Sentence<LatticeMorpheme>],
    ) -> usize {
        let chunker = Chunker::new(chunker_model(raw, options).unwrap());
        let mut right = 0;
        for (index, sentence) in sentences.iter().enumerate() {
            if sentence.morphemes.is_empty() {
                continue;
            }
            let features = chunker.features(&sentence.morphemes);
            let labels = chunker.labels(&features);
            assert_eq!(labels, crf_labels(raw, &features), "sentence {}", index + 1);
            if labels == gold_labels(sentence) {
                right += 1;
            }
        }
        right
    }

    /// A sentence in the lattice format, of bunsetsu given as their
    /// morphemes, each `surface/part of speech`.
    fn sentence(bunsetsu: &[&[&str]]) -> String {
        let mut text = String::new();
        for (index, morphemes) in bunsetsu.iter().enumerate() {
            let head = if index + 1 == bunsetsu.len() {
                -1
            } else {
                index as i32 + 1
            };
            text.push_str(&format!("* {index} {head}D \n"));
            for morpheme in *morphemes {
                let (surface, pos) = morpheme.split_once('/').unwrap();
                text.push_str(&format!("{surface}\t{pos},*,*,*,*,*,{surface},*,*\n"));
            }
        }
        text.push_str("EOS\n");
        text
    }

    /// Training data: nouns with particles and a verb, where a particle
    /// continues a bunsetsu; compound nouns, where a noun continues one
    /// after a noun and starts one after a particle, which only the features
    /// can tell; and runs of the same morpheme `x`, cut after every second
    /// one, which only the transitions between labels can tell.
    fn training_data() -> Vec<Sentence<LatticeMorpheme>> {
        let text = [
            sentence(&[
                &["彼/名詞", "は/助詞"],
                &["本/名詞", "を/助詞"],
                &["読む/動詞"],
            ]),
            sentence(&[
                &["私/名詞", "が/助詞"],
                &["水/名詞", "を/助詞"],
                &["飲む/動詞"],
            ]),
            sentence(&[&["犬/名詞", "が/助詞"], &["走る/動詞"]]),
            sentence(&[
                &["猫/名詞", "は/助詞"],
                &["魚/名詞", "を/助詞"],
                &["食べる/動詞"],
            ]),
            sentence(&[&["本/名詞", "を/助詞"], &["読む/動詞"]]),
            sentence(&[&["東京/名詞", "都/名詞", "に/助詞"], &["行く/動詞"]]),
            sentence(&[
                &["彼/名詞", "は/助詞"],
                &["日本/名詞", "語/名詞", "を/助詞"],
                &["話す/動詞"],
            ]),
            sentence(&[
                &["x/記号", "x/記号"],
                &["x/記号", "x/記号"],
                &["x/記号", "x/記号"],
            ]),
            sentence(&[
                &["x/記号", "x/記号"],
                &["x/記号", "x/記号"],
                &["x/記号", "x/記号"],
                &["x/記号", "x/記号"],
            ]),
        ]
        .concat();
        lattice::parse(&text).unwrap()
    }

    /// Sentences the training data does not hold, some with words it does
    /// not have.
    fn other_data() -> Vec<Sentence<LatticeMorpheme>> {
        let text = [
            sentence(&[
                &["犬/名詞", "は/助詞"],
                &["水/名詞", "を/助詞"],
                &["飲む/動詞"],
            ]),
            sentence(&[&["鳥/名詞", "が/助詞"], &["飛ぶ/動詞"]]),
            sentence(&[&["読む/動詞"]]),
            sentence(&[&["は/助詞"], &["を/助詞", "が/助詞"]]),
            sentence(&[
                &["x/記号", "x/記号"],
                &["x/記号", "x/記号"],
                &["x/記号", "x/記号"],
                &["x/記号", "x/記号"],
                &["x/記号", "x/記号"],
            ]),
            sentence(&[&["未知/感動詞", "語/感動詞"], &["x/記号"]]),
        ]
        .concat();
        lattice::parse(&text).unwrap()
    }

    /// Settings for the small data of these tests.
    fn options(regularization: Regularization, lambda: f64) -> TrainOptions {
        TrainOptions {
            regularization,
            lambda,
            ..TrainOptions::default()
        }
    }

    #[test]
    fn the_chunker_gives_the_labels_of_search_best_path() {
        for (regularization, lambda) in [
            (Regularization::L2, 0.01),
            (Regularization::L2, 1.0),
            (Regularization::L1, 0.01),
            (Regularization::L1, 0.5),
        ] {
            let options = options(regularization, lambda);
            let training = training_data();
            let mut raw = train_raw(&training, &options).unwrap();
            // The training data is reproduced with a small coefficient.
            let right = same_labels(&mut raw, &options, &training);
            if lambda == 0.01 {
                assert_eq!(right, training.len(), "{regularization:?} {lambda}");
            }
            same_labels(&mut raw, &options, &other_data());
        }
    }

    #[test]
    fn the_transitions_between_labels_are_learned() {
        let options = options(Regularization::L2, 0.01);
        let trained = train(&training_data(), &options).unwrap();
        let chunker = Chunker::new(trained.model);
        // A run of `x` longer than any of the training data: the middle
        // positions have the same features, and alternate.
        let run: Vec<LatticeMorpheme> = (0..10)
            .map(|_| LatticeMorpheme::new("x", "記号,*,*,*,*,*,x,*,*"))
            .collect();
        assert_eq!(
            chunker.chunk(&run).unwrap(),
            [0..2, 2..4, 4..6, 6..8, 8..10]
        );
        // After B, I is preferred to B, and after I, B to I.
        let model = chunker.model();
        assert!(model.transition(1, 2) > model.transition(1, 1));
        assert!(model.transition(2, 1) > model.transition(2, 2));
        // The direction of a transition: no sentence starts with I, as the
        // first position has no such edge, and the runs of `x` end with I.
        assert_eq!(model.transition(0, 2), 0.0);
        assert_ne!(model.transition(2, 0), 0.0);
    }

    #[test]
    fn a_trained_model_chunks_and_goes_through_bytes() {
        let options = options(Regularization::L2, 0.01);
        let trained = train(&training_data(), &options).unwrap();
        assert!(trained.iterations > 0);
        let model = trained.model;
        assert_eq!(model.schema(), &options.schema);
        assert_eq!(model.columns(), options.columns);
        assert_eq!(model.template(), &options.template);

        // Through a model file, the chunker reads the same weights where
        // they are in the bytes.
        let bytes = ModelBuilder::new("test", options.schema.clone())
            .unwrap()
            .chunker(&model)
            .unwrap()
            .to_bytes();
        let read = ModelFile::new(bytes).unwrap();
        let chunker = read.chunker().unwrap();
        assert_eq!(chunker.model().feature_count(), model.feature_count());
        assert_eq!(chunker.model().weight_count(), model.weight_count());
        for sentence in training_data() {
            let expected: Vec<_> = sentence
                .bunsetsu
                .iter()
                .map(|bunsetsu| bunsetsu.morphemes.clone())
                .collect();
            assert_eq!(chunker.chunk(&sentence.morphemes).unwrap(), expected);
        }
    }

    #[test]
    fn the_settings_of_a_dictionary_are_those_of_its_model() {
        // IPADIC: the defaults.
        assert_eq!(
            TrainOptions::for_dictionary("ipadic"),
            Some(TrainOptions::default())
        );
        // UniDic: the base form too, its template, and a smaller
        // coefficient.
        for name in ["unidic", "unidic-cwj", "unidic-csj"] {
            let options = TrainOptions::for_dictionary(name).unwrap();
            assert_eq!(options.schema, Schema::unidic(), "{name}");
            assert_eq!(
                options.columns,
                [
                    Column::Surface,
                    Column::PartOfSpeech,
                    Column::ConjugationForm,
                    Column::BaseForm
                ],
                "{name}"
            );
            assert_eq!(options.template, Template::unidic(), "{name}");
            assert_eq!(options.regularization, Regularization::L1, "{name}");
            assert_eq!(options.lambda, 0.25, "{name}");
            // The template reads no column the settings do not give.
            assert_eq!(options.template.columns(), options.columns.len());
        }
        // Every dictionary with a schema has settings, and no other has.
        for name in Schema::DICTIONARIES {
            assert!(TrainOptions::for_dictionary(name).is_some(), "{name}");
        }
        assert_eq!(TrainOptions::for_dictionary("ko-dic"), None);
    }

    #[test]
    fn l1_leaves_fewer_weights_than_l2() {
        let training = training_data();
        let l2 = train(&training, &options(Regularization::L2, 0.1))
            .unwrap()
            .model;
        let l1 = train(&training, &options(Regularization::L1, 0.1))
            .unwrap()
            .model;
        assert!(
            l1.feature_count() < l2.feature_count(),
            "{} and {}",
            l1.feature_count(),
            l2.feature_count()
        );
        assert!(l1.weight_count() < l2.weight_count());
        // No feature string of a model has only weights that are 0.
        assert!(l1.weight_count() >= l1.feature_count());
    }

    #[test]
    fn refuses_training_data_and_settings_it_cannot_use() {
        let error = |sentences: &[Sentence<LatticeMorpheme>], options: &TrainOptions| {
            train(sentences, options).unwrap_err().to_string()
        };
        let training = training_data();
        let default = TrainOptions::default();

        assert_eq!(error(&[], &default), "the training data has no sentence");
        // Morphemes without bunsetsu.
        let morphemes_only = lattice::parse("彼\t名詞\nEOS\n").unwrap();
        assert_eq!(
            error(&morphemes_only, &default),
            "sentence 1 of the training data has no bunsetsu"
        );
        // A template over three columns, and one column.
        let one_column = TrainOptions {
            columns: vec![Column::Surface],
            ..TrainOptions::default()
        };
        assert_eq!(
            error(&training, &one_column),
            "the template reads 3 columns, and 1 are given"
        );
        // Settings `lindera-crf` refuses.
        for options in [
            TrainOptions {
                lambda: -1.0,
                ..TrainOptions::default()
            },
            TrainOptions {
                max_iterations: 0,
                ..TrainOptions::default()
            },
            TrainOptions {
                threads: 0,
                ..TrainOptions::default()
            },
        ] {
            let message = error(&training, &options);
            assert!(message.starts_with("training failed: "), "{message}");
        }
    }

    /// The same check as
    /// `the_chunker_gives_the_labels_of_search_best_path`, on real data:
    /// run with `--ignored` and, in `LINDERA_DEPENDENCY_CHUNKER_TRAIN` and
    /// `LINDERA_DEPENDENCY_CHUNKER_EVAL`, the paths of a training file and
    /// of files to label (separated by `:`), in the lattice format.
    #[test]
    #[ignore = "needs training data: see the comment"]
    fn the_chunker_gives_the_labels_of_search_best_path_on_real_data() {
        let read = |path: &str| {
            let text = std::fs::read_to_string(path).unwrap();
            lattice::parse(&text).unwrap()
        };
        let training = read(&std::env::var("LINDERA_DEPENDENCY_CHUNKER_TRAIN").unwrap());
        let files = std::env::var("LINDERA_DEPENDENCY_CHUNKER_EVAL").unwrap();
        let threads = std::thread::available_parallelism().map_or(1, usize::from);
        for (regularization, lambda) in [(Regularization::L1, 1.0), (Regularization::L2, 1.0)] {
            let options = TrainOptions {
                regularization,
                lambda,
                threads,
                ..TrainOptions::default()
            };
            let mut raw = train_raw(&training, &options).unwrap();
            for path in files.split(':') {
                let sentences = read(path);
                let right = same_labels(&mut raw, &options, &sentences);
                println!(
                    "{regularization:?} {lambda} {path}: {} sentences with the same labels, {right} as the answer",
                    sentences.len()
                );
            }
        }
    }

    #[test]
    fn the_spaces_of_the_training_data_are_not_read() {
        // The same sentence with spaces at the start of a bunsetsu, inside
        // one and at the end: the bunsetsu of the answer start at a space.
        let plain = sentence(&[
            &["彼/名詞", "は/助詞"],
            &["本/名詞", "を/助詞"],
            &["読む/動詞"],
        ]);
        let spaced = sentence(&[
            &["\u{3000}/記号", "彼/名詞", "は/助詞"],
            &["\u{3000}/記号", "本/名詞", "\u{3000}/記号", "を/助詞"],
            &["読む/動詞", "\u{3000}/記号"],
        ]);
        let options = options(Regularization::L2, 0.01);
        let mut without = training_data();
        without.extend(lattice::parse(&plain).unwrap());
        let mut with = training_data();
        with.extend(lattice::parse(&spaced).unwrap());
        assert_ne!(with, without);
        let with = train(&with, &options).unwrap();
        let without = train(&without, &options).unwrap();
        assert_eq!(with.model, without.model);
        assert_eq!(with.iterations, without.iterations);
        // No feature of the model has a space in it.
        let bytes = ModelFile::new(
            ModelBuilder::new("ipadic", options.schema.clone())
                .unwrap()
                .chunker(&with.model)
                .unwrap()
                .to_bytes(),
        )
        .unwrap();
        assert!(!String::from_utf8_lossy(bytes.as_bytes()).contains('\u{3000}'));

        // A sentence of spaces alone is no training data.
        let spaces = lattice::parse(&sentence(&[&["\u{3000}/記号", "\u{3000}/記号"]])).unwrap();
        let mut with_spaces = training_data();
        with_spaces.extend(spaces.clone());
        assert_eq!(
            train(&with_spaces, &options).unwrap().model,
            train(&training_data(), &options).unwrap().model
        );
        assert_eq!(
            train(&spaces, &options).unwrap_err().to_string(),
            "the training data has no sentence"
        );
    }

    /// The ends [`unfinished_ends`] gives for a sentence of bunsetsu given
    /// as [`sentence`] takes them.
    fn ends(bunsetsu: &[&[&str]]) -> Vec<usize> {
        let sentences = lattice::parse(&sentence(bunsetsu)).unwrap();
        let one = &sentences[0];
        let labels = gold_labels(one);
        unfinished_ends(&Schema::ipadic(), &one.morphemes, &labels)
    }

    #[test]
    fn the_texts_made_from_a_sentence_end_before_its_period_and_after_a_phrase() {
        // 彼は / 本を / 読む。: without the period (5 words), and 彼は本
        // (3 words), the second bunsetsu without its particle.
        assert_eq!(
            ends(&[
                &["彼/名詞", "は/助詞"],
                &["本/名詞", "を/助詞"],
                &["読む/動詞", "。/記号,句点"],
            ]),
            [5, 3]
        );
        // The phrase ends in the first bunsetsu that has particles after
        // another word: not in 赤い, which has no particle, and not in a
        // bunsetsu of particles alone. The word before the particles need
        // not be a noun (走っ / て).
        assert_eq!(
            ends(&[
                &["彼/名詞", "は/助詞"],
                &["赤い/形容詞"],
                &["は/助詞"],
                &["走っ/動詞", "て/助詞", "も/助詞"],
                &["本/名詞", "を/助詞"],
                &["読む/動詞", "。/記号,句点"],
            ]),
            [10, 5]
        );
        // The first bunsetsu and the last one give no phrase: two bunsetsu
        // give the sentence without its period only.
        assert_eq!(
            ends(&[&["犬/名詞", "が/助詞"], &["走る/動詞", "。/記号,句点"]]),
            [3]
        );
        // The last bunsetsu is not cut, and a sentence without a period
        // gives the phrase only.
        assert_eq!(
            ends(&[
                &["彼/名詞", "は/助詞"],
                &["本/名詞", "を/助詞"],
                &["読む/動詞", "と/助詞"],
            ]),
            [3]
        );
        // Nothing: no period, and no bunsetsu between the first and the
        // last that ends with particles.
        assert!(ends(&[&["犬/名詞", "が/助詞"], &["走る/動詞"]]).is_empty());
        assert!(ends(&[&["彼/名詞", "は/助詞"], &["赤い/形容詞"], &["本/名詞"]]).is_empty());
        // A period alone is not made an empty text.
        assert!(ends(&[&["。/記号,句点"]]).is_empty());
    }

    #[test]
    fn the_training_adds_the_texts_made_from_the_sentences() {
        let full: &[&[&str]] = &[
            &["彼/名詞", "は/助詞"],
            &["本/名詞", "を/助詞"],
            &["読む/動詞", "。/記号,句点"],
        ];
        let data = |texts: &[&[&[&str]]]| {
            let mut sentences = training_data();
            for text in texts {
                sentences.extend(lattice::parse(&sentence(text)).unwrap());
            }
            sentences
        };
        // The data of the other tests has no period, and gives phrases of
        // its own: they are written out too, where the training adds them.
        let written_out = {
            let mut sentences = Vec::new();
            for one in data(&[full]) {
                let labels = gold_labels(&one);
                let ends = unfinished_ends(&Schema::ipadic(), &one.morphemes, &labels);
                let starts: Vec<usize> = one
                    .bunsetsu
                    .iter()
                    .map(|bunsetsu| bunsetsu.morphemes.start)
                    .collect();
                sentences.push(one.clone());
                for end in ends {
                    let mut text = String::new();
                    let mut number = 0;
                    for (index, morpheme) in one.morphemes[..end].iter().enumerate() {
                        if starts.contains(&index) {
                            text.push_str(&format!("* {number} -1D \n"));
                            number += 1;
                        }
                        text.push_str(&format!(
                            "{}\t{}\n",
                            morpheme.surface(),
                            morpheme.features()
                        ));
                    }
                    text.push_str("EOS\n");
                    sentences.extend(lattice::parse(&text).unwrap());
                }
            }
            sentences
        };
        // Two texts for the sentence with a period, and the phrases of the
        // other sentences.
        assert!(written_out.len() >= data(&[full]).len() + 2);

        let with = TrainOptions {
            unfinished_texts: true,
            ..options(Regularization::L2, 0.01)
        };
        let without = TrainOptions {
            unfinished_texts: false,
            ..with.clone()
        };
        assert!(TrainOptions::default().unfinished_texts);
        let trained = train(&data(&[full]), &with).unwrap();
        // The same model as the texts written out give without the option,
        // and another one than the sentences alone give.
        assert_eq!(trained.model, train(&written_out, &without).unwrap().model);
        assert_ne!(
            trained.model,
            train(&data(&[full]), &without).unwrap().model
        );
    }

    #[test]
    fn a_chunker_trained_with_the_texts_cuts_a_text_without_a_period() {
        // Sentences that all end with a period after a verb, and whose
        // nouns are followed by a particle everywhere but at the end of a
        // phrase: 「noun noun」 inside a sentence is one bunsetsu (東京 / 都).
        let mut text = String::new();
        for (subject, object, verb) in [
            ("彼", "本", "読む"),
            ("私", "水", "飲む"),
            ("犬", "魚", "食べる"),
            ("猫", "道", "歩く"),
        ] {
            text.push_str(&sentence(&[
                &[&format!("{subject}/名詞"), "は/助詞"],
                &[&format!("{object}/名詞"), "を/助詞"],
                &[&format!("{verb}/動詞"), "。/記号,句点"],
            ]));
        }
        let sentences = lattice::parse(&text).unwrap();
        let with = options(Regularization::L2, 0.01);
        let without = TrainOptions {
            unfinished_texts: false,
            ..with.clone()
        };
        // 彼は / 本を / 読む, without the period.
        let unfinished = lattice::parse(&sentence(&[
            &["彼/名詞", "は/助詞"],
            &["本/名詞", "を/助詞"],
            &["読む/動詞"],
        ]))
        .unwrap();
        let morphemes = &unfinished[0].morphemes;
        let chunk = |options: &TrainOptions| {
            Chunker::new(train(&sentences, options).unwrap().model)
                .chunk(morphemes)
                .unwrap()
        };
        assert_eq!(chunk(&with), [0..2, 2..4, 4..5]);
        // Both models cut the sentences themselves as the answer does.
        for options in [&with, &without] {
            let chunker = Chunker::new(train(&sentences, options).unwrap().model);
            for one in &sentences {
                assert_eq!(
                    chunker.chunk(&one.morphemes).unwrap(),
                    one.bunsetsu
                        .iter()
                        .map(|bunsetsu| bunsetsu.morphemes.clone())
                        .collect::<Vec<_>>()
                );
            }
        }
    }

    #[test]
    fn a_text_of_several_sentences_is_trained_on_as_its_sentences() {
        let first: &[&[&str]] = &[
            &["彼/名詞", "は/助詞"],
            &["本/名詞", "を/助詞"],
            &["読む/動詞", "。/記号,句点"],
        ];
        let second: &[&[&str]] = &[&["犬/名詞", "が/助詞"], &["走る/動詞", "。/記号,句点"]];
        // The two as one text, the second one continuing the bunsetsu of
        // the period in the answer: the cut makes 犬 start a bunsetsu.
        let joined: &[&[&str]] = &[
            &["彼/名詞", "は/助詞"],
            &["本/名詞", "を/助詞"],
            &["読む/動詞", "。/記号,句点", "犬/名詞", "が/助詞"],
            &["走る/動詞", "。/記号,句点"],
        ];
        let data = |texts: &[&[&[&str]]]| {
            let mut sentences = training_data();
            for text in texts {
                sentences.extend(lattice::parse(&sentence(text)).unwrap());
            }
            sentences
        };
        let options = options(Regularization::L2, 0.01);
        assert_eq!(
            options.schema.sentence_split,
            crate::schema::SentenceSplit::AfterEnds
        );
        let apart = train(&data(&[first, second]), &options).unwrap();
        let together = train(&data(&[joined]), &options).unwrap();
        assert_eq!(together.model, apart.model);

        // A schema that does not cut trains on the text as it is.
        let whole = TrainOptions {
            schema: Schema {
                sentence_split: crate::schema::SentenceSplit::None,
                ..options.schema.clone()
            },
            ..options.clone()
        };
        let uncut = train(&data(&[joined]), &whole).unwrap();
        let uncut_apart = train(&data(&[first, second]), &whole).unwrap();
        assert_ne!(uncut.model, uncut_apart.model);
    }
}