-
Notifications
You must be signed in to change notification settings - Fork 20
/
patternmodel.h
3916 lines (3522 loc) · 203 KB
/
patternmodel.h
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
#ifndef PATTERNMODEL_H
#define PATTERNMODEL_H
/*****************************
* Colibri Core
* by Maarten van Gompel
* Centre for Language Studies
* Radboud University Nijmegen
*
* https://proycon.github.io/colibri-core
*
* Licensed under GPLv3
*****************************/
/**
* @file patternmodel.h
* \brief Contains classes for Pattern Models.
*
* @author Maarten van Gompel (proycon) <proycon@anaproy.nl>
*
* @section LICENSE
* Licensed under GPLv3
*
* @section DESCRIPTION
* Contains classes for Pattern Models
*
*/
/**
* \mainpage Colibri Core
*
* Colibri Core is a set of tools as well as a C++ and Python library for
* working with basic linguistic constructions such as n-grams and skipgrams (i.e
* patterns with one or more gaps, either of fixed or dynamic size) in a quick
* and memory-efficient way. At the core is the tool colibri-patternmodeller
* which allows you to build, view, manipulate and query pattern models.
*
* In Colibri Core, text data is encoded as a compressed binary representation
* using a class encoding. The ClassEncoder and ClassDecoder can be used to
* create and decode such a class encoding. The Pattern class represents any
* n-gram, skip-gram, flexgram. These patterns can be stored in various
* models, such as the PatternModel or it's indexed equivalent, the
* IndexedPatternModel. These are high-level classes built on lower-level
* containers such as PatternMap. Other containers such as PatternSet are
* available too.
*
* Corpus data can also be read into an IndexedCorpus class, which also acts
* as a reverse index for the pattern models.
*
*/
#include "patternstore.h"
#include "classencoder.h"
#include "algorithms.h"
#include <limits>
#include <cmath>
#include <cstdint>
#include <map>
#include <set>
#include <sstream>
#include <array>
#include <exception>
#include "bz2stream.h"
/**
* Defines the various types of pattern models
*/
enum ModelType {
UNINDEXEDPATTERNMODEL = 10,
UNINDEXEDPATTERNPOINTERMODEL = 11,
INDEXEDPATTERNMODEL = 20,
INDEXEDPATTERNPOINTERMODEL = 21,
PATTERNSETMODEL = 30,
PATTERNALIGNMENTMODEL = 40,
};
/**
* Defines Reverse Index Types
*/
enum ReverseIndexType {
NONE = 0,
QUICK = 1,
COMPACT = 2,
};
/**
* Extracts the model type (one of ModelType) from a file
*/
int getmodeltype(const std::string & filename);
class NoSuchPattern: public std::exception {
virtual const char* what() const throw()
{
return "Pattern not found in model";
}
};
/**
* \brief Options for Pattern Model loading and training.
*
* This class defines all kinds of parameters that can be set for loading and
* training Pattern Models, it is passed to various constructors and methods.
*/
class PatternModelOptions {
public:
int MINTOKENS; ///< The occurrence threshold, minimum amount of occurrences for a pattern to be included in a model
///< Defaults to 2 for building, to 1 for loading.
int MINTOKENS_SKIPGRAMS; ///< The occurrence threshold for skipgrams, minimum amount of occurrences for a pattern to be included in a model.
///< Defaults to the same value as MINTOKENS.
///< Only used if DOSKIPGRAMS or
///< DO_SKIPGRAMS_EXHAUSTIVE is set to true
int MINTOKENS_UNIGRAMS; ///< The occurrence threshold for unigrams, unigrams must occur at least this many times for higher-order ngram/skipgram to be included in a model
///< Defaults to the same value as MINTOKENS
///< Only has an effect if MINTOKENS_UNIGRAMS > MINTOKENS.
//
int MINLENGTH; ///< The minimum length of patterns to be loaded/extracted (in words/tokens) (default: 1)
int MAXLENGTH; ///< The maximum length of patterns to be loaded/extracted, inclusive (in words/tokens) (default: 100)
int MAXBACKOFFLENGTH; ///< Counting n-grams is done iteratively for each increasing n. (default: MAXLENGTH)
///< For each n, presence of sub-ngrams in n-1 is
///< checked. This values defines a maximum
///< length for this back-off check. In
///< combination with MINLENGTH, this allows earlier
///< pruning and conserves memory.
bool DOSKIPGRAMS; ///< Load/extract skipgrams? (default: false)
bool DOSKIPGRAMS_EXHAUSTIVE; ///< Load/extract skipgrams in an exhaustive fashion? More memory intensive, but the only options for unindexed models (default: false). Use DOSKIPGRAMS instead, this will be automatically used as a fallback whnever EXHAUSTIVE computation is necessary.
int MINSKIPTYPES; ///< Minimum required amount of distinct patterns that can fit in a gap of a skipgram for the skipgram to be included (default: 2)
int MAXSKIPS; ///< Maximum skips per skipgram
//bool CROSSBOUNDARIES; ///< Include n-grams that cross unit (e.g. sentence) boundaries (newlines in the original text). //MAYBE TODO
bool DOREVERSEINDEX; ///< Obsolete now, only here for backward-compatibility with v1
bool DOPATTERNPERLINE; ///< Assume each line contains one integral pattern, rather than actively extracting all subpatterns on a line (default: false)
int PRUNENONSUBSUMED; //< Prune all n-grams that are **NOT** subsumed by higher-order ngrams
int PRUNESUBSUMED; //< Prune all n-grams that are subsumed by higher-order ngrams
bool DOREMOVEINDEX; ///< Do not load index information (for indexed models), loads just the patterns without any counts
bool DOREMOVENGRAMS; ///< Remove n-grams from the model upon loading it
bool DOREMOVESKIPGRAMS; ///< Remove skip-grams from the model upon loading it
bool DOREMOVEFLEXGRAMS; ///< Remove flexgrams from the model upon loading it
bool DORESET; ///< sets all counts to zero upon loading, clears indices
bool QUIET; ///< Don't output to stderr
bool DEBUG; ///< Output extra debug information
/**
* Initialise with default values. All members are public and can be
* set explicitly..
*/
PatternModelOptions() {
MINTOKENS = -1; //defaults to 2 for building, 1 for loading
MINTOKENS_SKIPGRAMS = -1; //defaults to MINTOKENS
MINTOKENS_UNIGRAMS = 1; //defaults to, effectively disabled
MINLENGTH = 1;
MAXLENGTH = 100;
MAXBACKOFFLENGTH = 100;
MINSKIPTYPES = 2;
MAXSKIPS = 3;
DOSKIPGRAMS = false;
DOSKIPGRAMS_EXHAUSTIVE = false;
DOREVERSEINDEX = true; //obsolete
DOPATTERNPERLINE = false;
DORESET = false;
DOREMOVEINDEX = false; //only for indexed models
DOREMOVENGRAMS = false;
DOREMOVESKIPGRAMS = false;
DOREMOVEFLEXGRAMS = false;
PRUNENONSUBSUMED = 0;
PRUNESUBSUMED = 0;
DEBUG = false;
QUIET = false;
}
/**
* Copy constructor
*/
PatternModelOptions(const PatternModelOptions & ref) {
MINTOKENS = ref.MINTOKENS; //defaults to 2 for building, 1 for loading
MINTOKENS_UNIGRAMS = ref.MINTOKENS_UNIGRAMS;
MINTOKENS_SKIPGRAMS = ref.MINTOKENS_SKIPGRAMS; //defaults to 2 for building, 1 for loading
MINLENGTH = ref.MINLENGTH;
MAXLENGTH = ref.MAXLENGTH;
MAXBACKOFFLENGTH = ref.MAXBACKOFFLENGTH;
MINSKIPTYPES = ref.MINSKIPTYPES;
MAXSKIPS = ref.MAXSKIPS;
DOSKIPGRAMS = ref.DOSKIPGRAMS;
DOSKIPGRAMS_EXHAUSTIVE = ref.DOSKIPGRAMS_EXHAUSTIVE;
DOREVERSEINDEX = ref.DOREVERSEINDEX;
DOPATTERNPERLINE = ref.DOPATTERNPERLINE;
DORESET = ref.DORESET;
DOREMOVEINDEX = ref.DOREMOVEINDEX; //only for indexed models
DOREMOVENGRAMS = ref.DOREMOVENGRAMS;
DOREMOVESKIPGRAMS = ref.DOREMOVESKIPGRAMS;
DOREMOVEFLEXGRAMS = ref.DOREMOVEFLEXGRAMS;
PRUNENONSUBSUMED = ref.PRUNENONSUBSUMED;
PRUNESUBSUMED = ref.PRUNESUBSUMED;
DEBUG = ref.DEBUG;
QUIET = ref.QUIET;
}
};
/**
* A relationmap is just a pattern map, the map is specific for a pattern and
* holds patterns that are in a relation with the first pattern. The value of
* the map is an integer that expresses how often the relationship occurs.
*/
typedef PatternMap<uint32_t,BaseValueHandler<uint32_t>,uint64_t> t_relationmap;
/**
* A relationmap_double is just a pattern map, the map is specific for a pattern and
* holds patterns that are in a relation with the first pattern. The value of
* the map is an double that expresses the weight of the relation.
*/
typedef PatternMap<double,BaseValueHandler<double>,uint64_t> t_relationmap_double;
typedef PatternMap<uint32_t,BaseValueHandler<uint32_t>,uint64_t>::iterator t_relationmap_iterator; //needed for Cython
typedef PatternMap<double,BaseValueHandler<double>,uint64_t>::iterator t_relationmap_double_iterator;
/**
* \brief Basic read-only interface for pattern models, abstract base class.
*/
class PatternModelInterface: public PatternStoreInterface {
public:
/**
* Get the type of the model
* @return ModelType
*/
virtual int getmodeltype() const=0;
/**
* Get the version number of the model
*/
virtual int getmodelversion() const=0;
//these are already in PatternStoreInterface:
//virtual bool has(const Pattern &) const =0;
//virtual bool has(const PatternPointer &) const =0;
//virtual size_t size() const =0;
/**
* Returns the number of times this pattern occurs in the model
*/
virtual size_t occurrencecount(const Pattern & pattern)=0;
/**
* Returns the frequency of the pattern in the
* model, a relative/normalised value
*/
virtual double frequency(const Pattern &) =0;
/**
* Return the maximum pattern length in this model
*/
virtual int maxlength() const=0;
/**
* Returns the minumum pattern length in this model
*/
virtual int minlength() const=0;
/**
* Return the number of distinct words/unigram in the original corpus,
* includes types not covered by the model!
*/
virtual size_t types() =0;
/**
* Returns the number of tokens in the original corpus, includes tokens
* not covered by the model!
*/
virtual size_t tokens() const=0;
virtual PatternStoreInterface * getstoreinterface() {
return (PatternStoreInterface*) this;
};
};
/**
* \brief A pattern model based on an unordered set, does not hold data, only patterns.
* Very suitable for loading constraint models.
*/
class PatternSetModel: public PatternSet<uint64_t>, public PatternModelInterface {
protected:
unsigned char model_type;
unsigned char model_version;
uint64_t totaltokens; //INCLUDES TOKENS NOT COVERED BY THE MODEL!
uint64_t totaltypes; //TOTAL UNIGRAM TYPES, INCLUDING NOT COVERED BY THE MODEL!
int maxn;
int minn;
public:
/**
* Empty constructor
*/
PatternSetModel() {
totaltokens = 0;
totaltypes = 0;
maxn = 0;
minn = 999;
model_type = this->getmodeltype();
model_version = this->getmodelversion();
}
/**
* Load a PatternSetModel from stream
* @param options The options for loading
* @param constrainmodel Load only patterns that occur in this model
*/
PatternSetModel(std::istream *f, PatternModelOptions options, PatternModelInterface * constrainmodel = NULL) {
totaltokens = 0;
totaltypes = 0;
maxn = 0;
minn = 999;
model_type = this->getmodeltype();
model_version = this->getmodelversion();
this->load(f,options, constrainmodel);
}
/**
* Load a PatternSetModel from file
* @param filename The name of the file to load
* @param options The options for loading
* @param constrainmodel Load only patterns that occur in this model
*/
PatternSetModel(const std::string & filename, const PatternModelOptions & options, PatternModelInterface * constrainmodel = NULL) {
totaltokens = 0;
totaltypes = 0;
maxn = 0;
minn = 999;
model_type = this->getmodeltype();
model_version = this->getmodelversion();
if (!options.QUIET) std::cerr << "Loading " << filename << std::endl;
std::ifstream * in = new std::ifstream(filename.c_str());
if (!in->good()) {
std::cerr << "ERROR: Unable to load file " << filename << std::endl;
throw InternalError();
}
this->load( (std::istream *) in, options, constrainmodel);
in->close();
delete in;
}
virtual int getmodeltype() const { return PATTERNSETMODEL; }
virtual int getmodelversion() const { return 2; }
virtual size_t size() const {
return PatternSet<uint64_t>::size();
}
virtual bool has(const Pattern & pattern) const {
return PatternSet<uint64_t>::has(pattern);
}
virtual bool has(const PatternPointer & pattern) const {
return PatternSet<uint64_t>::has(pattern);
}
/**
* Load a PatternSetModel from file
* @param filename The name of the file to load
* @param options The options for loading
* @param constrainmodel Load only patterns that occur in this model
*/
virtual void load(std::string & filename, const PatternModelOptions & options, PatternModelInterface * constrainmodel = NULL) {
if (!options.QUIET) std::cerr << "Loading " << filename << " as set-model" << std::endl;
std::ifstream * in = new std::ifstream(filename.c_str());
if (!in->good()) {
std::cerr << "ERROR: Unable to load file " << filename << std::endl;
throw InternalError();
}
this->load( (std::istream *) in, options, constrainmodel);
in->close();
delete in;
}
/**
* Load a PatternSetModel from stream
* @param options The options for loading
* @param constrainmodel Load only patterns that occur in this model
*/
virtual void load(std::istream * f, const PatternModelOptions & options, PatternModelInterface * constrainmodel = NULL) { //load from file
char null;
f->read( (char*) &null, sizeof(char));
f->read( (char*) &model_type, sizeof(char));
f->read( (char*) &model_version, sizeof(char));
if (model_version == 1) this->classencodingversion = 1;
if ((null != 0) || ((model_type != UNINDEXEDPATTERNMODEL) && (model_type != INDEXEDPATTERNMODEL) && (model_type != PATTERNSETMODEL) && (model_type != PATTERNALIGNMENTMODEL) )) {
std::cerr << "ERROR: File is not a colibri patternmodel file" << std::endl;
throw InternalError();
}
if (model_version > 2) {
std::cerr << "WARNING: Model is created with a newer version of Colibri Core! Attempting to continue but failure is likely..." << std::endl;
}
f->read( (char*) &totaltokens, sizeof(uint64_t));
f->read( (char*) &totaltypes, sizeof(uint64_t));
PatternStoreInterface * constrainstore = NULL;
if (constrainmodel) constrainstore = constrainmodel->getstoreinterface();
if (options.DEBUG) {
std::cerr << "Debug enabled, loading PatternModel type " << (int) model_type << ", version " << (int) model_version << ", classencodingversion" << (int) this->classencodingversion << std::endl;
std::cerr << "Total tokens: " << totaltokens << ", total types: " << totaltypes << std::endl;;
}
if (model_type == PATTERNSETMODEL) {
//reading set
PatternSet<uint64_t>::read(f, options.MINLENGTH, options.MAXLENGTH, constrainstore, !options.DOREMOVENGRAMS, !options.DOREMOVESKIPGRAMS, !options.DOREMOVEFLEXGRAMS); //read PatternStore
} else if (model_type == INDEXEDPATTERNMODEL) {
//reading from indexed pattern model, ok:
readmap<IndexedData,IndexedDataHandler>(f, options.MINTOKENS, options.MINLENGTH,options.MAXLENGTH, constrainstore, !options.DOREMOVENGRAMS, !options.DOREMOVESKIPGRAMS, !options.DOREMOVEFLEXGRAMS);
} else if (model_type == UNINDEXEDPATTERNMODEL) {
//reading from unindexed pattern model, ok:
readmap<uint32_t,BaseValueHandler<uint32_t>>(f, options.MINTOKENS, options.MINLENGTH,options.MAXLENGTH, constrainstore, !options.DOREMOVENGRAMS, !options.DOREMOVESKIPGRAMS, !options.DOREMOVEFLEXGRAMS);
} else if (model_type == PATTERNALIGNMENTMODEL) {
//ok:
readmap<PatternFeatureVectorMap<double>, PatternFeatureVectorMapHandler<double>>(f, options.MINTOKENS, options.MINLENGTH,options.MAXLENGTH, constrainstore, !options.DOREMOVENGRAMS, !options.DOREMOVESKIPGRAMS, !options.DOREMOVEFLEXGRAMS);
} else {
std::cerr << "ERROR: Unknown model type" << std::endl;
throw InternalError();
}
}
/**
* Write a PatternSetModel to an output stream
*/
void write(std::ostream * out) {
const char null = 0;
out->write( (char*) &null, sizeof(char));
unsigned char t = this->getmodeltype();
out->write( (char*) &t, sizeof(char));
unsigned char v = this->getmodelversion();
out->write( (char*) &v, sizeof(char));
out->write( (char*) &totaltokens, sizeof(uint64_t));
const uint64_t tp = this->types(); //use this instead of totaltypes, as it may need to be computed on-the-fly still
out->write( (char*) &tp, sizeof(uint64_t));
PatternSet<uint64_t>::write(out); //write
}
/**
* Write a PatternSetModel to an output file. This is a wrapper around
* write(std::ostream *)
*/
void write(const std::string & filename) {
std::ofstream * out = new std::ofstream(filename.c_str());
this->write(out);
out->close();
delete out;
}
/**
* Get the interface (just a basic typecast)
*/
virtual PatternModelInterface * getinterface() {
return (PatternModelInterface*) this;
}
/**
* This function does not perform anything in a set context, it always
* returns zero
*/
virtual size_t occurrencecount(const Pattern & ) { return 0; }
/**
* This function does not perform anything in a set context, it always
* returns zero
*/
virtual double frequency(const Pattern &) { return 0; }
typedef typename PatternSet<uint64_t>::iterator iterator;
typedef typename PatternSet<uint64_t>::const_iterator const_iterator;
/**
* Return the maximum length of patterns in this model
*/
virtual int maxlength() const { return maxn; };
/**
* Return the minimum length of patterns in this model
*/
virtual int minlength() const { return minn; };
/**
* Returns the total amount of unigram/word types in the original corpus,
* includes types not covered by the model!
*/
virtual size_t types() {
return totaltypes;
}
/**
* Returns the total amount of tokens in the original corpus,
* includes tokens not covered by the model!
*/
virtual size_t tokens() const { return totaltokens; }
/**
* Returns the type of the model, value is of the PatternType
* enumeration.
*/
unsigned char type() const { return model_type; }
/**
* Returns the version of the model's implementation and binary serialisation format.
*/
unsigned char version() const { return model_version; }
};
typedef std::unordered_map<PatternPointer,std::vector<std::pair<uint32_t,unsigned char>>> t_matchskipgramhelper; //firstword => [pair<mask,n>]
typedef std::unordered_map<PatternPointer,std::unordered_set<PatternPointer>> t_matchflexgramhelper; //firstword => [flexgram]
/**
* \brief A model mapping patterns to values, high-level interface.
* @tparam ValueType The type of Value this model stores
* @tparam ValueHandler A handler class for this type of value
* @tparam MapType The type of container to use
*/
template<class ValueType, class ValueHandler = BaseValueHandler<ValueType>, class MapType = PatternMap<ValueType, BaseValueHandler<ValueType>>, class PatternType = Pattern>
class PatternModel: public MapType, public PatternModelInterface {
protected:
unsigned char model_type;
unsigned char model_version;
uint64_t totaltokens; ///< Total number of tokens in the original corpus, so INCLUDES TOKENS NOT COVERED BY THE MODEL!
uint64_t totaltypes; ///< Total number of unigram/word types in the original corpus, SO INCLUDING NOT COVERED BY THE MODEL!
int maxn;
int minn;
t_matchskipgramhelper matchskipgramhelper; ///< Helper structure for finding skipgrams in corpus data: maps the first word of skipgrams to series of mask,length pairs, so skipgrams need not be recomputed exhaustively for each pattern
t_matchflexgramhelper matchflexgramhelper; ///< Helper structure for finding flexgrams in corpus data: maps the first word of skipgrams to series of parts
//std::multimap<IndexReference,Pattern> reverseindex;
std::set<int> cache_categories;
std::set<int> cache_n;
std::map<int,std::map<int,unsigned int>> cache_grouptotal; ///< total occurrences (used for frequency computation, within a group)
std::map<int,std::map<int,unsigned int>> cache_grouptotalpatterns ; ///< total distinct patterns per group
std::map<int,std::map<int,unsigned int>> cache_grouptotalwordtypes; ///< total covered word types per group
std::map<int,std::map<int,unsigned int>> cache_grouptotaltokens; ///< total covered tokens per group
std::map<int,std::map<int,bool>> cache_processed; ///< are coverage statistics processed for this group?
bool cache_processed_all; ///< are coverage statistics processed for all groups?
std::map<int, std::vector< uint32_t > > gapmasks; ///< pre-computed masks representing possible gap configurations for various pattern lengths
virtual void postread(const PatternModelOptions& ) {
//this function has a specialisation specific to indexed pattern models,
//this is the generic version
for (iterator iter = this->begin(); iter != this->end(); iter++) {
const PatternType p = iter->first;
const PatternCategory category = p.category();
const int n = p.n();
if (n > maxn) maxn = n;
if (n < minn) minn = n;
if ((!hasskipgrams) && (category == SKIPGRAM)) hasskipgrams = true;
if ((!hasflexgrams) && (category == FLEXGRAM)) hasflexgrams = true;
}
}
virtual void posttrain(const PatternModelOptions& ) {
//nothing to do here, indexed model specialised this function to
//sort indices
}
virtual void compute_matchhelpers(bool quiet = false) {
const bool doskipgrams = (matchskipgramhelper.empty() && hasskipgrams);
const bool doflexgrams = (matchflexgramhelper.empty() && hasflexgrams);
if (!doskipgrams && !doflexgrams) return;
unsigned int skipgramcount = 0;
unsigned int flexgramcount = 0;
for (iterator iter = this->begin(); iter != this->end(); iter++) {
const PatternPointer pattern = iter->first;
const PatternCategory category = pattern.category();
const PatternPointer firstword = PatternPointer(pattern,0,1);
if (!firstword.unknown() && (!firstword.isgap(0))) {
if ((category == SKIPGRAM) && (doskipgrams)) {
bool found = false;
for (std::vector<std::pair<uint32_t,unsigned char>>::iterator iter2 = matchskipgramhelper[firstword].begin(); iter2 != matchskipgramhelper[firstword].end(); iter2++) {
if ((iter2->first == pattern.getmask()) && (iter2->second == pattern.n())) {
found = true;
break;
}
}
if (!found) {
matchskipgramhelper[firstword].push_back(std::pair<uint32_t,unsigned char>(pattern.getmask(),pattern.n()));
skipgramcount++;
}
} else if ((category == FLEXGRAM) && (doflexgrams)) {
matchflexgramhelper[firstword].insert(pattern);
flexgramcount++;
}
}
}
for (t_matchskipgramhelper::iterator iter = matchskipgramhelper.begin(); iter != matchskipgramhelper.end(); iter++) {
iter->second.shrink_to_fit();
}
if (!quiet && !matchskipgramhelper.empty()) std::cerr << "(helper structure has " << matchskipgramhelper.size() << " unigrams mapping to " << skipgramcount << " skipgrams total)" << std::endl;
if (!quiet && !matchflexgramhelper.empty()) std::cerr << "(helper structure has " << matchflexgramhelper.size() << " unigrams mapping to " << flexgramcount << " flexgrams total)" << std::endl;
}
public:
IndexedCorpus * reverseindex; ///< Pointer to the reverse index and corpus data for this model (or NULL)
bool reverseindex_internal;
bool hasskipgrams; ///< Does this model have skipgrams?
bool hasflexgrams; ///< Does this model have flexgrams?
/**
* Begin a new pattern model, optionally pre-setting a reverseindex.
*/
PatternModel<ValueType,ValueHandler,MapType,PatternType>(IndexedCorpus * corpus = NULL) {
totaltokens = 0;
totaltypes = 0;
maxn = 0;
minn = 999;
hasskipgrams = false;
hasflexgrams = false;
model_type = this->getmodeltype();
model_version = this->getmodelversion();
if (corpus) {
this->reverseindex = corpus;
this->attachcorpus(*corpus);
} else {
this->reverseindex = NULL;
}
reverseindex_internal = false;
}
/**
* Read a pattern model from an input stream
* @param f The input stream
* @param options Options for reading, these act as filter for the data, allowing you to raise thresholds etc
* @param constrainmodel Pointer to another pattern model which should be used to constrain the loading of this one, only patterns also occurring in the other model will be included. Defaults to NULL (no constraining)
* @param corpus Pointer to the loaded corpus, used as a reverse index.
*/
PatternModel<ValueType,ValueHandler,MapType,PatternType>(std::istream *f, PatternModelOptions options, PatternModelInterface * constrainmodel = NULL, IndexedCorpus * corpus = NULL) {
totaltokens = 0;
totaltypes = 0;
maxn = 0;
minn = 999;
hasskipgrams = false;
hasflexgrams = false;
model_type = this->getmodeltype();
model_version = this->getmodelversion();
this->load(f,options,constrainmodel);
if (corpus) {
this->reverseindex = corpus;
this->attachcorpus(*corpus);
} else {
this->reverseindex = NULL;
}
reverseindex_internal = false;
}
~PatternModel<ValueType,ValueHandler,MapType,PatternType>() {
if (reverseindex_internal && reverseindex != NULL) delete reverseindex;
}
/**
* Read a pattern model from file
* @param filename The input filename
* @param options Options for reading, these act as filter for the data, allowing you to raise thresholds etc
* @param constrainmodel Pointer to another pattern model which should be used to constrain the loading of this one, only patterns also occurring in the other model will be included. Defaults to NULL (no constraining)
* @param corpus Pointer to the loaded corpus, used as a reverse index.
*/
PatternModel<ValueType,ValueHandler,MapType,PatternType>(const std::string & filename, const PatternModelOptions & options, PatternModelInterface * constrainmodel = NULL, IndexedCorpus * corpus = NULL) { //load from file
//IndexedPatternModel will overload this
totaltokens = 0;
totaltypes = 0;
maxn = 0;
minn = 999;
hasskipgrams = false;
hasflexgrams = false;
model_type = this->getmodeltype();
model_version = this->getmodelversion();
if (corpus) {
this->reverseindex = corpus;
this->attachcorpus(*corpus);
} else {
this->reverseindex = NULL;
}
reverseindex_internal = false;
if (!options.QUIET) std::cerr << "Loading " << filename << std::endl;
std::ifstream * in = new std::ifstream(filename.c_str());
if (!in->good()) {
std::cerr << "ERROR: Unable to load file " << filename << std::endl;
throw InternalError();
}
this->load( (std::istream *) in, options, constrainmodel);
in->close();
delete in;
}
/**
* Returns the type of model (a value from ModelType)
*/
virtual int getmodeltype() const { return UNINDEXEDPATTERNMODEL; }
/**
* Returns the version of the model implementation and binary serialisation format
*/
virtual int getmodelversion() const { return 2; }
/**
* Returns the number of distinct patterns in the model
*/
virtual size_t size() const {
return MapType::size();
}
/**
* Checks whether the given pattern occurs in the model
*/
virtual bool has(const Pattern & pattern) const {
return MapType::has(pattern);
}
virtual bool has(const PatternPointer & pattern) const {
return MapType::has(pattern);
}
/**
* Read a pattern model from file
* @param filename The input filename
* @param options Options for reading, these act as filter for the data, allowing you to raise thresholds etc
* @param constrainmodel Pointer to another pattern model which should be used to constrain the loading of this one, only patterns also occurring in the other model will be included. Defaults to NULL (no constraining)
*/
virtual void load(std::string & filename, const PatternModelOptions & options, PatternModelInterface * constrainmodel = NULL) {
if (!options.QUIET) std::cerr << "Loading " << filename << std::endl;
std::ifstream * in = new std::ifstream(filename.c_str());
if (!in->good()) {
std::cerr << "ERROR: Unable to load file " << filename << std::endl;
throw InternalError();
}
this->load( (std::istream *) in, options, constrainmodel);
in->close();
delete in;
}
/**
* Read a pattern model from an input stream
* @param f The input stream
* @param options Options for reading, these act as filter for the data, allowing you to raise thresholds etc
* @param constrainmodel Pointer to another pattern model which should be used to constrain the loading of this one, only patterns also occurring in the other model will be included. Defaults to NULL (no constraining)
*/
virtual void load(std::istream * f, const PatternModelOptions & options, PatternModelInterface * constrainmodel = NULL) { //load from file
char null;
f->read( (char*) &null, sizeof(char));
f->read( (char*) &model_type, sizeof(char));
f->read( (char*) &model_version, sizeof(char));
if (model_version == 1) this->classencodingversion = 1;
if ((null != 0) || ((model_type != UNINDEXEDPATTERNMODEL) && (model_type != UNINDEXEDPATTERNPOINTERMODEL) && (model_type != INDEXEDPATTERNMODEL) && (model_type != INDEXEDPATTERNPOINTERMODEL) && (model_type != PATTERNALIGNMENTMODEL) )) {
std::cerr << "File is not a colibri model file (or a very old one)" << std::endl;
throw InternalError();
}
if (model_version > 2) {
std::cerr << "WARNING: Model is created with a newer version of Colibri Core! Attempting to continue but failure is likely..." << std::endl;
}
if (options.DEBUG) {
std::cerr << "Debug enabled, loading PatternModel type " << (int) model_type << ", version " << (int) model_version << ", classencodingversion=" << (int) this->classencodingversion << std::endl;
}
if ((model_type == UNINDEXEDPATTERNPOINTERMODEL) || (model_type == INDEXEDPATTERNPOINTERMODEL)) {
this->patterntype = PATTERNPOINTER;
if (options.DEBUG) std::cerr << "Reading corpus data" << std::endl;
uint64_t corpussize;
f->read( (char*) &corpussize, sizeof(uint64_t)); //backward incompatible (since v2.5)
unsigned char * corpusdata = new unsigned char[corpussize];
f->read((char*) corpusdata,sizeof(unsigned char) * corpussize);
reverseindex = new IndexedCorpus(corpusdata, corpussize);
this->attachcorpus(*reverseindex);
reverseindex_internal = true;
if (options.DEBUG) std::cerr << "(read " << corpussize << " bytes)" << std::endl;
}
f->read( (char*) &totaltokens, sizeof(uint64_t));
f->read( (char*) &totaltypes, sizeof(uint64_t));
PatternStoreInterface * constrainstore = NULL;
if (constrainmodel) constrainstore = constrainmodel->getstoreinterface();
if (options.DEBUG) {
std::cerr << "Total tokens: " << totaltokens << ", total types: " << totaltypes << std::endl;;
}
if (((model_type == INDEXEDPATTERNMODEL) && (this->getmodeltype() == UNINDEXEDPATTERNMODEL)) || ((model_type == INDEXEDPATTERNPOINTERMODEL) && (this->getmodeltype() == UNINDEXEDPATTERNPOINTERMODEL))) {
//reading indexed pattern model as unindexed, (or indexed patternPOINTErmodels as unindexed patternPOINTERmodels)
MapType::template read<IndexedData,IndexedDataHandler,PatternType>(f, options.MINTOKENS, options.MINLENGTH,options.MAXLENGTH, constrainstore, !options.DOREMOVENGRAMS, !options.DOREMOVESKIPGRAMS, !options.DOREMOVEFLEXGRAMS, options.DORESET, options.DEBUG);
} else if ((model_type == UNINDEXEDPATTERNMODEL) && (this->getmodeltype() == INDEXEDPATTERNMODEL)) {
//reading unindexed model as indexed, this will load the patterns but lose all the counts
MapType::template read<uint32_t,BaseValueHandler<uint32_t>,PatternType>(f, options.MINTOKENS, options.MINLENGTH,options.MAXLENGTH, constrainstore, !options.DOREMOVENGRAMS, !options.DOREMOVESKIPGRAMS, !options.DOREMOVEFLEXGRAMS, options.DORESET, options.DEBUG);
} else if ((model_type == UNINDEXEDPATTERNPOINTERMODEL) && (this->getmodeltype() == UNINDEXEDPATTERNMODEL)) {
//reading unindexed pointermodel as unindexed patternmodel
MapType::template read<uint32_t,BaseValueHandler<uint32_t>,PatternPointer>(f, options.MINTOKENS, options.MINLENGTH,options.MAXLENGTH, constrainstore, !options.DOREMOVENGRAMS, !options.DOREMOVESKIPGRAMS, !options.DOREMOVEFLEXGRAMS, options.DORESET, options.DEBUG);
} else if ((model_type == INDEXEDPATTERNPOINTERMODEL) && ((this->getmodeltype() == INDEXEDPATTERNMODEL) || (this->getmodeltype() == UNINDEXEDPATTERNMODEL))) {
//reading indexed patternpointermodel as (un)indexed patternmodel
MapType::template read<IndexedData,IndexedDataHandler,PatternPointer>(f, options.MINTOKENS, options.MINLENGTH,options.MAXLENGTH, constrainstore, !options.DOREMOVENGRAMS, !options.DOREMOVESKIPGRAMS, !options.DOREMOVEFLEXGRAMS, options.DORESET, options.DEBUG);
} else if (model_type == PATTERNALIGNMENTMODEL) {
//reading pattern alignment model as pattern model, can be
//done, but semantics change: count corresponds to the number of distinct alignments (for unindexed models)
//indexed models will lose all counts
MapType::template read<PatternFeatureVectorMap<double>,PatternFeatureVectorMapHandler<double>,PatternType>(f, options.MINTOKENS, options.MINLENGTH,options.MAXLENGTH, constrainstore, !options.DOREMOVENGRAMS, !options.DOREMOVESKIPGRAMS, !options.DOREMOVEFLEXGRAMS,options.DORESET, options.DEBUG);
} else {
MapType::template read(f, options.MINTOKENS,options.MINLENGTH, options.MAXLENGTH, constrainstore, !options.DOREMOVENGRAMS, !options.DOREMOVESKIPGRAMS, !options.DOREMOVEFLEXGRAMS, options.DORESET, options.DEBUG); //read PatternStore (also works for reading unindexed pattern models as indexed, which will load patterns but lose the counts)
}
this->postread(options);
}
/**
* Returns a more generic but limited PatternModelInterface instance (polymorphism)
*/
PatternModelInterface * getinterface() {
return (PatternModelInterface*) this;
}
/**
* Train a pattern model on corpus data (given an input stream)
* @param in The input stream of the corpus data (*.colibri.dat), may be NULL if a reverse index is loaded.
* @param options Options for training
* @param constrainbymodel Pointer to another pattern model which should be used to constrain the training of this one, only patterns also occurring in the other model will be included. Defaults to NULL (no constraining)
* @param filter A limited set of skipgrams/flexgrams to use as a filter, patterns will only be included if they are an instance of a skipgram in this list (i.e. disjunctive). Ngrams can also be included as filters, if a pattern subsumes one of the ngrams in the filter, it counts as a match (or if it matches it exactly).
* @param continued Continued training on the same corpus data
* @param firstsentence First sentence index, useful for augmenting a model with another corpus (keep continued set to false in this case), defaults to 1
* @param ignoreerrors Try to ignore errors (use for debug only)
*/
virtual void train(std::istream * in , PatternModelOptions options, PatternModelInterface * constrainbymodel = NULL, PatternSet<> * filter = NULL, bool continued=false, uint32_t firstsentence=1, bool ignoreerrors=false) {
if (options.MINTOKENS == -1) options.MINTOKENS = 2;
if (options.MINTOKENS == 0) options.MINTOKENS = 1;
if (options.MINTOKENS_SKIPGRAMS < options.MINTOKENS) options.MINTOKENS_SKIPGRAMS = options.MINTOKENS;
if (constrainbymodel == this) {
totaltypes = 0;
totaltokens = 0;
} else if (constrainbymodel != NULL) {
totaltypes = constrainbymodel->types();
totaltokens = constrainbymodel->tokens();
}
uint32_t sentence = firstsentence-1;
const unsigned char version = (in != NULL) ? getdataversion(in) : 2;
bool filterhasngrams = false;
bool filterhasskipgrams = false; //(or flexgrams)
if (filter != NULL) {
if (filter->size() == 0) { //cython will pass empty sets
filter = NULL;
} else {
for (PatternSet<>::iterator iter = filter->begin(); iter != filter->end(); iter++) {
if (iter->category() == NGRAM) {
filterhasngrams = true;
} else {
filterhasskipgrams = true;
}
if (filterhasngrams && filterhasskipgrams) break;
}
}
}
bool iter_unigramsonly = false; //only needed for counting unigrams when we need them but they would be discarded
bool skipunigrams = false; //will be set to true later only when MINTOKENS=1,MINLENGTH=1 to prevent double counting of unigrams
if (( (options.MINLENGTH > 1) ||(options.MINTOKENS == 1)) && (options.MINTOKENS_UNIGRAMS > options.MINTOKENS)) {
iter_unigramsonly = true;
}
if (!options.QUIET) {
std::cerr << "Training patternmodel";
if (constrainbymodel != NULL) std::cerr << ", constrained by another model";
std::cerr << ", occurrence threshold: " << options.MINTOKENS;
if (iter_unigramsonly) std::cerr << ", secondary word occurrence threshold: " << options.MINTOKENS_UNIGRAMS;
if (version < 2) std::cerr << ", class encoding version: " << (int) version;
std::cerr << std::endl;
if (filterhasngrams) {
std::cerr << "Filter with ngrams provided, only patterns that either match a filtered pattern or contain a smaller filtered pattern will be included..." << std::endl;
}
if (filterhasskipgrams) {
std::cerr << "Filter with skipgrams provided, only matching instances will be included..." << std::endl;
}
}
if (constrainbymodel != NULL) {
if ((options.DOSKIPGRAMS) && (!options.DOSKIPGRAMS_EXHAUSTIVE)) {
if (constrainbymodel != this) {
options.DOSKIPGRAMS = false;
options.DOSKIPGRAMS_EXHAUSTIVE = true;
if (!options.QUIET) std::cerr << "WARNING: Skipgrams will be extracted exhaustively on the basis of the ngrams found; the constraint model will be applied only afterwards. This implies some skipgrams in the constraint model that are present may be missed, and it will not be most efficient. Use in-place rebuilding of your constraint model instead." << std::endl;
if (options.MAXLENGTH >= 31) std::cerr << "WARNING: No maximum pattern length set or maximum pattern length is very high! This will drastically slow down skipgram computation" << std::endl;
}
}
}
if (options.DOSKIPGRAMS && options.DOSKIPGRAMS_EXHAUSTIVE) {
std::cerr << "ERROR: Both DOSKIPGRAMS as well as DOSKIPGRAMS_EXHAUSTIVE are set, this shouldn't happen, choose one." << std::endl;
if (!ignoreerrors) throw InternalError();
options.DOSKIPGRAMS = false;
}
std::vector<std::pair<PatternPointer,int> > ngrams;
std::vector<PatternPointer> subngrams;
bool found;
IndexReference ref;
int prevsize = this->size();
if (constrainbymodel == this) prevsize = 0; //going over same model
int backoffn = 0;
Pattern * linepattern = NULL;
if (!this->data.empty()) {
if ((continued) && (!options.QUIET)) std::cerr << "Continuing training on preloaded model, computing statistics..." << std::endl;
this->computestats();
}
for (int n = 1; n <= options.MAXLENGTH; n++) {
bool skipgramsonly = false; //only used when continued==true, prevent double counting of n-grams whilst allowing skipgrams to be counted later
if (continued) {
if ((options.MINTOKENS > 1) && (constrainbymodel == NULL)) {
if (cache_grouptotal[NGRAM][n] > 0) {
if ((options.DOSKIPGRAMS_EXHAUSTIVE) && (cache_grouptotal[SKIPGRAM][n] == 0) ) {
skipgramsonly= true;
} else {
if (!options.QUIET) std::cerr << "Skipping " << n << "-grams, already in model" << std::endl;
continue;
}
}
}
}
int foundngrams = 0;
int foundskipgrams = 0;
if (in != NULL) {
in->clear();
if (version >= 2) {
in->seekg(2);
} else {
in->seekg(0);
}
}
if (!options.QUIET) {
if (iter_unigramsonly) {
std::cerr << "Counting unigrams using secondary word occurrence threshold (" << options.MINTOKENS_UNIGRAMS << ")" << std::endl;
} else if (options.DOPATTERNPERLINE) {
std::cerr << "Counting patterns from list, one per line" << std::endl;
} else if (constrainbymodel != NULL) {
std::cerr << "Counting n-grams that occur in constraint model" << std::endl;
} else if (options.MINTOKENS > 1) {
std::cerr << "Counting " << n << "-grams" << std::endl;
if (skipgramsonly) std::cerr << "(only counting skipgrams actually, n-grams already counted earlier)" << std::endl;
} else {
std::cerr << "Counting *all* n-grams (occurrence threshold=1)" << std::endl;
}
}
if ((options.DOSKIPGRAMS_EXHAUSTIVE) && (gapmasks[n].empty())) gapmasks[n] = compute_skip_configurations(n, options.MAXSKIPS);
sentence = firstsentence-1; //reset
bool singlepass = false;
bool ignorefilter = false;
const unsigned int sentences = (reverseindex != NULL) ? reverseindex->sentences() : 0;
if ((options.DEBUG) && (reverseindex != NULL)) std::cerr << "Reverse index sentence count: " << sentences << std::endl;
while (((reverseindex != NULL) && (sentence < sentences)) || ((reverseindex == NULL) && (in != NULL) && (!in->eof()))) {
sentence++;
//read line
if (linepattern != NULL) delete linepattern;
if (reverseindex == NULL) linepattern = new Pattern(in,false,version);
PatternPointer line = (reverseindex != NULL) ? reverseindex->getsentence(sentence) : PatternPointer(linepattern);
//if (in->eof()) break;
const unsigned int linesize = line.n();
if (options.DEBUG) std::cerr << "Processing line " << sentence << ", size (tokens) " << linesize << " (bytes) " << line.bytesize() << ", n=" << n << std::endl;
if (linesize == 0) {
//skip empty lines
continue;
}
//count total tokens
if ((n==1) && (!continued)) totaltokens += linesize;
ngrams.clear();
ngrams.reserve(linesize);
if (options.DEBUG) std::cerr << " (container ready)" << std::endl;
if (options.DOPATTERNPERLINE) {
if (linesize > (unsigned int) options.MAXLENGTH) continue;
ngrams.push_back(std::pair<PatternPointer,int>(line,0));
} else {
if (iter_unigramsonly) {
line.ngrams(ngrams, n);
} else if ((options.MINTOKENS > 1) && (constrainbymodel == NULL)) {
line.ngrams(ngrams, n);
} else {
singlepass = true;
int minlength = options.MINLENGTH;
if (continued) minlength = this->maxn + 1;
line.subngrams(ngrams,minlength,options.MAXLENGTH); //extract ALL ngrams if MINTOKENS == 1 or a constraint model is set, no need to look back anyway, only one iteration over corpus