├── data ├── toy.char.test ├── toy.char.train ├── toy.word.test ├── toy.word.train ├── seql.toy.char.model.bin ├── seql.toy.word.model.bin ├── toy.seql.char.model.bin ├── seql.toy.char.model ├── toy.seql.char.model ├── seql.toy.word.model ├── seql.toy.char.model.predictors ├── toy.seql.char.model.predictors └── seql.toy.word.model.predictors ├── common.h ├── common_string_symbol.h ├── changes_from_seqlv1.0.txt ├── Makefile ├── test_type_limits.cpp ├── str2node_string_symbol.cpp ├── basic_symbol.h ├── seql_mkmodel.cpp ├── mmap.h ├── README.txt ├── seql_classify_tune_threshold_min_errors.cpp ├── seql_classify.cpp ├── LICENSE └── darts.h /data/toy.char.test: -------------------------------------------------------------------------------- 1 | +1 abc 2 | +1 ada 3 | -1 bda 4 | -1 bc 5 | -------------------------------------------------------------------------------- /data/toy.char.train: -------------------------------------------------------------------------------- 1 | +1 ab 2 | +1 abcd 3 | -1 abd 4 | -1 bcd 5 | -------------------------------------------------------------------------------- /data/toy.word.test: -------------------------------------------------------------------------------- 1 | +1 a b c 2 | +1 a d a 3 | -1 b d a 4 | -1 b c 5 | -------------------------------------------------------------------------------- /data/toy.word.train: -------------------------------------------------------------------------------- 1 | +1 a b 2 | +1 a b c d 3 | -1 a b d 4 | -1 b c d 5 | -------------------------------------------------------------------------------- /data/seql.toy.char.model.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/heerme/seql-sequence-learner/HEAD/data/seql.toy.char.model.bin -------------------------------------------------------------------------------- /data/seql.toy.word.model.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/heerme/seql-sequence-learner/HEAD/data/seql.toy.word.model.bin -------------------------------------------------------------------------------- /data/toy.seql.char.model.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/heerme/seql-sequence-learner/HEAD/data/toy.seql.char.model.bin -------------------------------------------------------------------------------- /data/seql.toy.char.model: -------------------------------------------------------------------------------- 1 | 0.193875000000 a 2 | -0.304880485164 d 3 | 0.312411962616 abc 4 | -0.260224676687 abd 5 | 0.252054120522 ab 6 | -0.258162420542 bd 7 | 0.198543068031 abcd 8 | -0.109861414648 abc 9 | -------------------------------------------------------------------------------- /data/toy.seql.char.model: -------------------------------------------------------------------------------- 1 | 0.193875000000 a 2 | -0.304880485164 d 3 | 0.312411962616 abc 4 | -0.260224676687 abd 5 | 0.252054120522 ab 6 | -0.258162420542 bd 7 | 0.198543068031 abcd 8 | -0.109861414648 abc 9 | -------------------------------------------------------------------------------- /data/seql.toy.word.model: -------------------------------------------------------------------------------- 1 | 0.193875000000 a 2 | -0.304880485164 d 3 | 0.312411962616 a b c 4 | -0.260224676687 a b d 5 | 0.252054120522 a b 6 | -0.258162420542 b d 7 | 0.198543068031 a b c d 8 | -0.109861414648 a b c 9 | -------------------------------------------------------------------------------- /data/seql.toy.char.model.predictors: -------------------------------------------------------------------------------- 1 | -0.0125687771804646342826972 2 | 0.26672208154817994563146 ab 3 | 0.214337713110442890096508 abc 4 | 0.2100970231017036116139 abcd 5 | 0.205157302935818991462824 a 6 | -0.273185846126521691967781 bd 7 | -0.275368112580015034218661 abd 8 | -0.322622607628679447522302 d 9 | -------------------------------------------------------------------------------- /data/toy.seql.char.model.predictors: -------------------------------------------------------------------------------- 1 | -0.0125687771804646342826972 2 | 0.26672208154817994563146 ab 3 | 0.214337713110442890096508 abc 4 | 0.2100970231017036116139 abcd 5 | 0.205157302935818991462824 a 6 | -0.273185846126521691967781 bd 7 | -0.275368112580015034218661 abd 8 | -0.322622607628679447522302 d 9 | -------------------------------------------------------------------------------- /data/seql.toy.word.model.predictors: -------------------------------------------------------------------------------- 1 | -0.0125687771804646342826972 2 | 0.26672208154817994563146 a b 3 | 0.214337713110442890096508 a b c 4 | 0.2100970231017036116139 a b c d 5 | 0.205157302935818991462824 a 6 | -0.273185846126521691967781 b d 7 | -0.275368112580015034218661 a b d 8 | -0.322622607628679447522302 d 9 | -------------------------------------------------------------------------------- /common.h: -------------------------------------------------------------------------------- 1 | #ifndef FREQT_COMMON_H 2 | #define FREQT_COMMON_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | template 13 | static inline unsigned int tokenize (char *str, char *del, Iterator out, unsigned int max) 14 | { 15 | char *stre = str + strlen (str); 16 | char *dele = del + strlen (del); 17 | unsigned int size = 1; 18 | 19 | while (size < max) { 20 | char *n = std::find_first_of (str, stre, del, dele); 21 | *n = '\0'; 22 | *out++ = str; 23 | ++size; 24 | if (n == stre) break; 25 | str = n + 1; 26 | } 27 | *out++ = str; 28 | 29 | return size; 30 | } 31 | 32 | #endif 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /common_string_symbol.h: -------------------------------------------------------------------------------- 1 | #ifndef FREQT_COMMON_H 2 | #define FREQT_COMMON_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include "basic_symbol.h" 12 | 13 | template 14 | static inline unsigned int tokenize (char *str, char *del, Iterator out, unsigned int max) 15 | { 16 | char *stre = str + strlen (str); 17 | char *dele = del + strlen (del); 18 | unsigned int size = 1; 19 | 20 | while (size < max) { 21 | char *n = std::find_first_of (str, stre, del, dele); 22 | *n = '\0'; 23 | *out++ = str; 24 | ++size; 25 | if (n == stre) break; 26 | str = n + 1; 27 | } 28 | *out++ = str; 29 | 30 | return size; 31 | } 32 | 33 | extern void str2node (const char *, std::vector &, int); 34 | 35 | #endif 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /changes_from_seqlv1.0.txt: -------------------------------------------------------------------------------- 1 | Updated 23.05.2011 2 | ------------------ 3 | 4 | Fixed bug wrt word-level tokenization. 5 | 6 | This SEQL version has additional stopping criteria (besides conv_threshold also use threshold on weight of max gradient feature). 7 | 8 | Changes: 9 | in seql_learn.cpp 10 | ----------------- 11 | in can_prune() use ngram = t->ne + ngram instead of reversed_ngram to retrieve ngram from trie going backwards 12 | in span_bfs and span_dfs change the candidate search procedure for word-level tokenization and char-level tokenization 13 | change the best ngram to have spaces when using word-tokens 14 | change the step size found by the line search to full step rather than the cautious 0.5 full_step as before. 15 | 16 | set C=1 and alpha=0.2 by default (0.2 * l1 + 0.8 * l2) 17 | 18 | in seql_classify_tune_thereshold_min_errors 19 | ------------------------------------------- 20 | output the best threshold instead of the bias 21 | modify project() such that search trie for word tokens or char-tokens (before worked for char-only) 22 | 23 | in seql_classify.cpp 24 | -------------------- 25 | take classif_thereshold as input and initilise bias=-threshold 26 | modify project() to work for work-tokens and char-tokens as well (takes token_type as parameter) 27 | by default use a threshold=0=bias, rather than the one computed during seql_mkmodel 28 | 29 | Checked that code has the same behaviour as seqlv1.0-online, when not changing the line search step size to full, rather than 0.5. 30 | In the new version, step size is full. 31 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | VERSION = 0.13 3 | CXXFLAGS_DEBUG = -g -Wall -Wno-deprecated 4 | CXXFLAGS = -O3 -Wall -Wno-deprecated 5 | EXECPREFIX = 6 | LDFLAGS = 7 | TARGETS0 = seql_learn${EXEC_PREFIX} 8 | TARGETS1 = seql_mkmodel${EXEC_PREFIX} 9 | TARGETS2 = seql_classify${EXEC_PREFIX} 10 | TARGETS3 = seql_classify_tune_threshold_min_errors${EXEC_PREFIX} 11 | 12 | OBJ2 = str2node_string_symbol.o 13 | 14 | all: seql_learn seql_mkmodel seql_classify seql_classify_tune_threshold_min_errors 15 | 16 | seql_learn: seql_learn.o 17 | ${CXX} ${CFLAGS} ${LDFLAGS} -o ${TARGETS0} seql_learn.o ${LDFLAGS} 18 | 19 | seql_mkmodel: seql_mkmodel.o ${OBJ2} 20 | ${CXX} ${CFLAGS} ${LDFLAGS} -o ${TARGETS1} seql_mkmodel.o ${LDFLAGS} 21 | 22 | seql_classify: seql_classify.o ${OBJ2} 23 | ${CXX} ${CFLAGS} ${LDFLAGS} -o ${TARGETS2} ${OBJ2} seql_classify.o ${LDFLAGS} 24 | 25 | seql_classify_tune_threshold_min_errors: seql_classify_tune_threshold_min_errors.o ${OBJ2} 26 | ${CXX} ${CFLAGS} ${LDFLAGS} -o ${TARGETS3} ${OBJ2} seql_classify_tune_threshold_min_errors.o ${LDFLAGS} 27 | 28 | clean: 29 | rm -f *.o ${TARGETS0} ${TARGETS01} ${TARGETS1} ${TARGETS2} ${TARGETS3} core *~ *.tar.gz *.exe core* 30 | 31 | check: 32 | test_word: 33 | ./seql_learn -n 0 -v 2 data/toy.word.train seql.toy.word.model 34 | echo 35 | ./seql_mkmodel -i seql.toy.word.model -o seql.toy.word.model.bin -O seql.toy.word.model.predictors 36 | echo 37 | ./seql_classify -n 0 -v 4 -t 0 data/toy.word.test seql.toy.word.model.bin 38 | 39 | test_char: 40 | ./seql_learn -n 1 -v 2 data/toy.char.train seql.toy.char.model 41 | echo 42 | ./seql_mkmodel -i seql.toy.char.model -o seql.toy.char.model.bin -O seql.toy.char.model.predictors 43 | echo 44 | ./seql_classify -n 1 -v 4 -t 0 data/toy.char.test seql.toy.char.model.bin 45 | 46 | -------------------------------------------------------------------------------- /test_type_limits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std ; 6 | 7 | template void show_limits() 8 | { 9 | typedef numeric_limits limits ; 10 | cout << "********************* type " << typeid(T).name() 11 | << " **************************\n" ; 12 | cout << "size: " 13 | << sizeof(T) << "\n"; 14 | cout << "smallest nonzero denormalized value: " 15 | << limits::denorm_min() << '\n' ; 16 | cout << "allows denormalized values? " << boolalpha 17 | << (limits::has_denorm==denorm_present) << '\n' ; 18 | cout << "difference between 1 and the smallest value greater than 1: " 19 | << limits::epsilon() << '\n' ; 20 | cout << "maximum rounding error: " << limits::round_error() << '\n' ; 21 | cout << "base (radix) used for the representation: " 22 | << limits::radix << '\n' ; 23 | cout << "minimum value of exponent (radix): " 24 | << limits::min_exponent << '\n' ; 25 | cout << "approximate minimum value of exponent (decimal): " 26 | << limits::min_exponent10 << '\n' ; 27 | cout << "maximum value of exponent (radix): " 28 | << limits::max_exponent << '\n' ; 29 | cout << "approximate maximum value of exponent (decimal): " 30 | << limits::max_exponent10 << '\n' ; 31 | cout << "minimum normalized value: " << limits::min() << '\n' ; 32 | cout << "maximum normalized value: " << limits::max() << "\n\n" ; 33 | 34 | } 35 | 36 | int main() 37 | { 38 | show_limits() ; 39 | show_limits() ; 40 | show_limits() ; 41 | show_limits() ; 42 | show_limits() ; 43 | 44 | double x = 1.0e+20, y = 1.0e-20, z = -1.0e+20 ; 45 | cout << scientific << "x+y+z: " << x+y+z << '\n' ; 46 | cout << "x+z+y: " << x+z+y << '\n' ; 47 | cout << fixed << setprecision(50) << "x+y+z: " << x+y+z << '\n' ; 48 | cout << "x+z+y: " << x+z+y << '\n' ; 49 | } 50 | -------------------------------------------------------------------------------- /str2node_string_symbol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "common_string_symbol.h" 5 | 6 | void str2node (const char *str, std::vector & doc, int token_type) 7 | { 8 | unsigned int len = strlen (str); 9 | bool at_space = false; 10 | std::string unigram = ""; 11 | 12 | for (unsigned int pos = 0; pos < len; ++pos) { 13 | // Skip white spaces. They are not considered as unigrams. 14 | if (isspace(str[pos])) { 15 | at_space = true; 16 | continue; 17 | } 18 | // If word level tokens. 19 | if (!token_type) { 20 | if (at_space || pos == 0) { 21 | at_space = false; 22 | 23 | if (!unigram.empty()) { 24 | doc.push_back(unigram); 25 | unigram.clear(); 26 | } 27 | unigram += str[pos]; 28 | } else { 29 | unigram += str[pos]; 30 | } 31 | } else { 32 | // Char (i.e. byte) level token. 33 | unigram = str[pos]; 34 | doc.push_back(unigram); 35 | unigram.clear(); 36 | } 37 | } 38 | 39 | if (!token_type) { 40 | if (!unigram.empty()) { 41 | doc.push_back(unigram); 42 | unigram.clear(); 43 | } 44 | } 45 | } 46 | 47 | //void str2node (const char *str, std::vector & doc, int token_type) 48 | //{ 49 | // try { 50 | // 51 | // //unsigned int size = 0; 52 | // unsigned int len = strlen (str); 53 | // std::string buf = ""; 54 | // //char prev_char; 55 | // 56 | // for (unsigned int i = 0; i < len; i++) { 57 | //// if (i > 0) { 58 | //// prev_char = str[i - 1]; 59 | //// } else { 60 | //// prev_char = str[i]; 61 | //// } 62 | // if (str[i] == '(' || str[i] == ')') { 63 | // if (! buf.empty()) { 64 | // doc.push_back (buf); 65 | // //std::cout << doc[doc.size() - 1] << " "; 66 | // buf = ""; 67 | // //++size; 68 | // } 69 | // } 70 | // else { 71 | // if (str[i] == '\t' || str[i] == ' ') { // do nothing 72 | // // if (str[i] == '\t') { // do nothing 73 | // } else { 74 | // //if (prev_char == ' ') { //do nothing 75 | // //} else { 76 | // buf += str[i]; 77 | // } 78 | // } 79 | // } 80 | // //std::cout << "\n"; 81 | // //std::cout << "bf size: " << buf.size(); 82 | // if (!buf.empty()) {// && !isspace(buf[buf.size() - 1])) { 83 | // throw 2; 84 | // } 85 | // 86 | // return; 87 | // } catch (const int) { 88 | // std::cerr << "Fatal: parse error << [" << str << "]\n"; 89 | // std::exit (-1); 90 | // } 91 | //} 92 | -------------------------------------------------------------------------------- /basic_symbol.h: -------------------------------------------------------------------------------- 1 | #ifndef _BASIC_SYMBOL_H 2 | #define _BASIC_SYMBOL_H 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | namespace stx { 10 | 11 | template > 12 | class basic_symbol { 13 | public: 14 | typedef unsigned long hash_type; 15 | typedef Key key_type; 16 | 17 | basic_symbol() 18 | { k = &(*key_pool().insert(key_type()).first); } 19 | basic_symbol(const key_type& key) 20 | { 21 | k = &(*key_pool().insert(key).first); 22 | } 23 | basic_symbol(const basic_symbol& sym) 24 | : k(sym.k) {} 25 | 26 | basic_symbol& operator=(const basic_symbol& sym) 27 | { k = sym.k; return *this; } 28 | basic_symbol& operator=(const key_type& key) 29 | { 30 | //cout << "\ninserting key: " << key; 31 | k = &(*key_pool().insert(key).first); 32 | //cout << "\nk: " << k; 33 | return *this; } 34 | 35 | const key_type& key() const { return *k; } 36 | hash_type hash() const { return hash_type(k); } 37 | 38 | private: 39 | typedef std::set pool_allocator; 40 | static pool_allocator& key_pool(); 41 | const key_type* k; 42 | }; 43 | 44 | template 45 | typename basic_symbol::pool_allocator& 46 | basic_symbol::key_pool() { 47 | static pool_allocator pool; 48 | return pool; 49 | } 50 | 51 | template 52 | inline bool operator==(const basic_symbol& x, const basic_symbol& y) 53 | { return x.hash() == y.hash(); } 54 | 55 | template 56 | inline bool operator!=(const basic_symbol& x, const basic_symbol& y) 57 | { return x.hash() != y.hash(); } 58 | 59 | template 60 | inline bool operator<(const basic_symbol& x, const basic_symbol& y) 61 | { return x.hash() < y.hash(); } 62 | 63 | template 64 | inline bool operator<=(const basic_symbol& x, const basic_symbol& y) 65 | { return x.hash() <= y.hash(); } 66 | 67 | template 68 | inline bool operator>(const basic_symbol& x, const basic_symbol& y) 69 | { return x.hash() > y.hash(); } 70 | 71 | template 72 | inline bool operator>=(const basic_symbol& x, const basic_symbol& y) 73 | { return x.hash() >= y.hash(); } 74 | 75 | template 76 | inline std::ostream& operator<<(std::ostream &x, const basic_symbol& y) 77 | { return x << y.key(); } 78 | 79 | template 80 | inline std::istream& operator<<(std::istream &x, const basic_symbol& y) 81 | { return y.key() >> x; } 82 | 83 | typedef basic_symbol string_symbol; 84 | } 85 | #endif 86 | -------------------------------------------------------------------------------- /seql_mkmodel.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: Georgiana Ifrim (georgiana.ifrim@gmail.com) 3 | * 4 | * This library takes as input the classification model provided by seql_learn.cpp (with potential repetitions of the same feature), 5 | * prepares the final model by aggregating the weights of repeated (identical) features 6 | * and builds a trie from the resulting (unique) features for fast classification (as done in seql_classify.cpp). 7 | * 8 | * The library uses parts of Taku Kudo's 9 | * open source code for BACT, available from: http://chasen.org/~taku/software/bact/ 10 | * 11 | * This program is free software; you can redistribute it and/or 12 | * modify it under the terms of the GNU Library General Public 13 | * License as published by the Free Software Foundation. 14 | * 15 | */ 16 | 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include "unistd.h" 25 | #include "darts.h" 26 | #include "common.h" 27 | 28 | #define OPT " [-i model_file] [-o binary_model_file] [-O predictors_file]" 29 | 30 | template 31 | struct pair_2nd_cmp: public std::binary_function { 32 | bool operator () (const std::pair & x1, const std::pair &x2) 33 | { 34 | return x1.second > x2.second; 35 | } 36 | }; 37 | 38 | int main (int argc, char **argv) 39 | { 40 | std::string file = ""; 41 | std::string index = ""; 42 | std::string ofile = ""; 43 | extern char *optarg; 44 | 45 | int opt; 46 | while ((opt = getopt(argc, argv, "i:o:O:")) != -1) { 47 | switch(opt) { 48 | case 'i': 49 | file = std::string (optarg); 50 | break; 51 | case 'o': 52 | index = std::string (optarg); 53 | break; 54 | case 'O': 55 | ofile = std::string (optarg); 56 | break; 57 | default: 58 | std::cout << "Usage: " << argv[0] << OPT << std::endl; 59 | return -1; 60 | } 61 | } 62 | 63 | if (file.empty () || index.empty ()) { 64 | std::cout << "Usage: " << argv[0] << OPT << std::endl; 65 | return -1; 66 | } 67 | 68 | std::istream *is; 69 | if (file == "-") is = &std::cin; 70 | else is = new std::ifstream (file.c_str()); 71 | 72 | if (! *is) { 73 | std::cerr << "Cannot Open: " << file << std::endl; 74 | return -1; 75 | } 76 | 77 | std::vector ary; 78 | std::vector > ary2; 79 | std::vector alpha; 80 | std::map rules; 81 | 82 | char buf[8192]; 83 | char *column[2]; 84 | double bias = 0.0; 85 | double alpha_sum = 0.0; 86 | double l1_norm = 0.0; 87 | double l2_norm = 0.0; 88 | 89 | while (is->getline (buf, 8192)) { 90 | if (buf[strlen(buf) - 1] == '\r') { 91 | buf[strlen(buf) - 1] = '\0'; 92 | } 93 | 94 | //cout << "\nline:" << no_cr_line; 95 | //cout.flush(); 96 | if (2 != tokenize (buf, "\t ", column, 2)) { 97 | std::cerr << "FATAL: Format Error: " << buf << std::endl; 98 | return -1; 99 | } 100 | // Ignore rules containing only 1 character. 101 | //if (strlen(column[1]) <= 1) continue; 102 | 103 | double a = atof (column[0]); 104 | bias -= a; 105 | alpha_sum += std::abs (a); 106 | rules[column[1]] += 2 * a; 107 | } 108 | 109 | bias /= alpha_sum; 110 | //bias = 0; 111 | l1_norm = alpha_sum; 112 | 113 | for (std::map::iterator it = rules.begin(); it != rules.end(); ++it) { 114 | double a = it->second / alpha_sum; 115 | l2_norm += pow(it->second, 2); 116 | 117 | ary2.push_back (std::make_pair(it->first.c_str(), a)); 118 | ary.push_back ((Darts::DoubleArray::key_type *)it->first.c_str()); 119 | alpha.push_back (a); 120 | } 121 | 122 | l2_norm = pow(l2_norm, 0.5); 123 | 124 | std::cout << "Total: " << alpha.size() << " rule(s)" << std::endl; 125 | std::cout << "l1_norm: " << l1_norm << ", l2_norm: " << l2_norm << std::endl; 126 | 127 | if (ary.empty()) { 128 | std::cerr << "FATAL: no feature is added" << std::endl; 129 | return -1; 130 | } 131 | 132 | if (file != "-") delete is; 133 | 134 | Darts::DoubleArray da; 135 | 136 | if (da.build (ary.size(), &ary[0], 0, 0, 0) != 0) { 137 | std::cerr << "Error: cannot build double array " << file << std::endl; 138 | return -1; 139 | } 140 | 141 | std::ofstream ofs (index.c_str(), std::ios::binary|std::ios::out); 142 | 143 | if (!ofs) { 144 | std::cerr << "Error: cannot open " << index << std::endl; 145 | return -1; 146 | } 147 | 148 | unsigned int s = da.size() * da.unit_size(); 149 | ofs.write ((char *)&s, sizeof (unsigned)); 150 | ofs.write ((char *)da.array (), s); 151 | ofs.write ((char *)&bias, sizeof (double)); 152 | ofs.write ((char *)&alpha[0], sizeof (double) * alpha.size()); 153 | ofs.close (); 154 | 155 | if (! ary2.empty() && ! ofile.empty()) { 156 | std::ofstream ofs2 (ofile.c_str()); 157 | if (! ofs2) { 158 | std::cerr << "Cannot Open: " << ofile << std::endl; 159 | return -1; 160 | } 161 | ofs2.precision (24); 162 | ofs2 << bias << std::endl; 163 | std::sort (ary2.begin(), ary2.end(), pair_2nd_cmp ()); 164 | for (unsigned int i = 0; i < ary2.size (); ++i) ofs2 << ary2[i].second << " " << ary2[i].first << std::endl; 165 | } 166 | 167 | return 0; 168 | } 169 | -------------------------------------------------------------------------------- /mmap.h: -------------------------------------------------------------------------------- 1 | /* 2 | MeCab -- Yet Another Part-of-Speech and Morphological Analyzer 3 | 4 | $Id: mmap.h,v 1.1.1.1 2004/06/23 05:00:42 taku-ku Exp $; 5 | 6 | Copyright (C) 2001-2002 Taku Kudo 7 | All rights reserved. 8 | 9 | This library is free software; you can redistribute it and/or 10 | modify it under the terms of the GNU Library General Public 11 | License as published by the Free Software Foundation; either 12 | version 2 of the License, or (at your option) any later verjsion. 13 | 14 | This library is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | Library General Public License for more details. 18 | 19 | You should have received a copy of the GNU Library General Public 20 | License along with this library; if not, write to the 21 | Free Software Foundation, Inc., 59 Temple Place - Suite 330, 22 | Boston, MA 02111-1307, USA. 23 | */ 24 | #ifndef _MECAB_MMAP_H 25 | #define _MECAB_MMAP_H 26 | 27 | #include 28 | #include 29 | #include 30 | 31 | #ifdef HAVE_CONFIG_H 32 | #include "config.h" 33 | #endif 34 | 35 | extern "C" { 36 | 37 | #define HAVE_MMAP 38 | 39 | //#ifdef HAVE_SYS_TYPES_H 40 | #include 41 | //#endif 42 | 43 | //#ifdef HAVE_SYS_STAT_H 44 | #include 45 | //#endif 46 | 47 | //#ifdef HAVE_FCNTL_H 48 | #include 49 | //#endif 50 | 51 | //#ifdef HAVE_STRING_H 52 | #include 53 | //#endif 54 | 55 | #if defined (_WIN32) && !defined (__CYGWIN__) 56 | #ifdef HAVE_WINDOWS_H 57 | #include 58 | #endif 59 | #else 60 | 61 | //#ifdef HAVE_SYS_MMAN_H 62 | #include 63 | //#endif 64 | 65 | //#ifdef HAVE_UNISTD_H 66 | #include 67 | //#endif 68 | #endif 69 | } 70 | 71 | #ifndef O_BINARY 72 | #define O_BINARY 0 73 | #endif 74 | 75 | #if !defined (_WIN32) || defined (__CYGWIN__) 76 | static inline int open__ (const char* name, int flag) { return open (name, flag); } 77 | static inline int close__ (int fd) { return close (fd); } 78 | #endif 79 | 80 | namespace MeCab 81 | { 82 | template 83 | class Mmap 84 | { 85 | private: 86 | T *text; 87 | unsigned int length; 88 | std::string fileName; 89 | std::string _what; 90 | 91 | #if defined (_WIN32) && !defined (__CYGWIN__) 92 | HANDLE hFile; 93 | HANDLE hMap; 94 | #else 95 | int fd; 96 | int flag; 97 | #endif 98 | 99 | public: 100 | T& operator [] (unsigned int n) { return *(text + n); } 101 | const T& operator [] (unsigned int n) const { return *(text + n); } 102 | T* begin () { return text; } 103 | const T* begin () const { return text; } 104 | T* end () { return text + size(); } 105 | const T* end () const { return text + size(); } 106 | unsigned int size () { return length/sizeof(T); } 107 | const char *what () { return _what.c_str(); } 108 | const char *getFileName () { return fileName.c_str(); } 109 | unsigned int getFileSize () { return length; } 110 | 111 | /* 112 | * This code is imported from sufary, develoved by 113 | * TATUO Yamashita Thanks! 114 | */ 115 | #if defined (_WIN32) && !defined (__CYGWIN__) 116 | bool open (const char *filename, const char *mode = "r") 117 | { 118 | try { 119 | this->close (); 120 | unsigned long mode1, mode2, mode3; 121 | fileName = std::string (filename); 122 | 123 | if (strcmp (mode, "r") == 0) { 124 | mode1 = GENERIC_READ; 125 | mode2 = PAGE_READONLY; 126 | mode3 = FILE_MAP_READ; 127 | } else if (strcmp (mode, "r+") == 0) { 128 | mode1 = GENERIC_READ | GENERIC_WRITE; 129 | mode2 = PAGE_READWRITE; 130 | mode3 = FILE_MAP_ALL_ACCESS; 131 | } else { 132 | throw std::runtime_error ("unknown open mode"); 133 | } 134 | 135 | hFile = CreateFile (filename, mode1, FILE_SHARE_READ, 0, 136 | OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); 137 | if (hFile == INVALID_HANDLE_VALUE) 138 | throw std::runtime_error ("CreateFile() failed"); 139 | 140 | length = GetFileSize (hFile, 0); 141 | 142 | hMap = CreateFileMapping (hFile, 0, mode2, 0, 0, 0); 143 | if (! hMap) throw std::runtime_error ("CreateFileMapping() failed"); 144 | 145 | text = (T *)MapViewOfFile (hMap, mode3, 0, 0, 0); 146 | if (! text) throw std::runtime_error ("MapViewOfFile() failed"); 147 | 148 | return true; 149 | } 150 | 151 | catch (std::exception &e) { 152 | this->close(); 153 | _what = "Mmap::open(): " + std::string (filename) + " : " + e.what (); 154 | return false; 155 | } 156 | } 157 | 158 | bool close() 159 | { 160 | if (text) { UnmapViewOfFile (text); text = 0; } 161 | if (hFile != INVALID_HANDLE_VALUE) { CloseHandle (hFile); hFile = INVALID_HANDLE_VALUE; } 162 | if (hMap) { CloseHandle (hMap); hMap = 0; } 163 | 164 | return true; 165 | } 166 | 167 | Mmap (): text(0), hFile (INVALID_HANDLE_VALUE), hMap (0) {} 168 | 169 | Mmap (const char *filename, const char *mode = "r"): 170 | text(0), hFile (INVALID_HANDLE_VALUE), hMap (0) 171 | { 172 | if (! this->open (filename, mode)) 173 | throw std::runtime_error (_what); 174 | } 175 | 176 | #else 177 | 178 | bool open (const char *filename, const char *mode = "r") 179 | { 180 | try { 181 | this->close (); 182 | struct stat st; 183 | fileName = std::string(filename); 184 | 185 | if (strcmp (mode, "r") == 0) flag = O_RDONLY; 186 | else if (strcmp (mode, "r+") == 0) flag = O_RDWR; 187 | else throw std::runtime_error ("unknown open mode"); 188 | 189 | if ((fd = open__ (filename, flag | O_BINARY)) < 0) 190 | throw std::runtime_error ("open() failed"); 191 | 192 | if (fstat (fd, &st) < 0) 193 | throw std::runtime_error ("failed to get file size"); 194 | 195 | length = (unsigned int)st.st_size; 196 | 197 | #ifdef HAVE_MMAP 198 | int prot = PROT_READ; 199 | if (flag == O_RDWR) prot |= PROT_WRITE; 200 | char *p; 201 | if ((p = (char *)mmap (0, length, prot, MAP_SHARED, fd, 0)) == MAP_FAILED) 202 | throw std::runtime_error ("mmap() failed"); 203 | text = reinterpret_cast(p); 204 | 205 | #else 206 | text = new T [length]; 207 | if (read (fd, text, length) < 0) 208 | throw std::runtime_error ("read() failed"); 209 | #endif 210 | close__ (fd); 211 | fd = -1; 212 | 213 | return true; 214 | } 215 | 216 | catch (std::exception &e) { 217 | this->close(); 218 | _what = "Mmap::open(): " + std::string (filename) + " : " + e.what (); 219 | return false; 220 | } 221 | } 222 | 223 | bool close () 224 | { 225 | if (fd >= 0) { close__ (fd); fd = -1; }; 226 | 227 | if (text) { 228 | 229 | #ifdef HAVE_MMAP 230 | munmap ((char *)text, length); 231 | #else 232 | if (flag == O_RDWR) { 233 | int fd2; 234 | if ((fd2 = open__ (fileName.c_str(), O_RDWR)) >= 0) { 235 | write (fd2, text, length); 236 | close__ (fd2); 237 | } 238 | } 239 | delete [] text; 240 | text = 0; 241 | #endif 242 | } 243 | 244 | return true; 245 | } 246 | 247 | Mmap (): text(0), fd (-1) {} 248 | 249 | Mmap (const char *filename, const char *mode = "r"): 250 | text(0), fd (-1) 251 | { 252 | if (! this->open (filename, mode)) 253 | throw std::runtime_error (_what); 254 | } 255 | #endif 256 | 257 | ~Mmap () { this->close (); } 258 | }; 259 | } 260 | #endif 261 | -------------------------------------------------------------------------------- /README.txt: -------------------------------------------------------------------------------- 1 | Description 2 | ———————————— 3 | This page describes the usage of the SEQL (SEQuence Learner) software and gives links to open source code and sequence data. 4 | This tool has been used for text and biological sequence classification (see References section, PlosOne14, KDD11, KDD08), but can be applied to any string classification task. 5 | 6 | SEQL is an implementation of a greedy coordinate-wise gradient descent technique for efficiently learning sequence classifiers. 7 | 8 | The theoretical framework is based on discriminative sequence classification where linear classifiers work directly in the high dimensional predictor space of all subsequences in the training set (as opposed to string-kernel-induced feature spaces). This is computationally challenging, but made feasible by employing a greedy coordinate-descent algorithm coupled with bounding the magnitude of the gradient for efficiently selecting discriminative subsequences. Logistic regression (binomial log-likelihood loss) and support vector machines (squared hinge loss) are currently implemented. 9 | 10 | 11 | Installation 12 | --------------- 13 | * Requirements 14 | o C++ compiler (gcc 3.4 or higher) 15 | o POSIX getopt library. 16 | * 17 | 18 | To install SEQL download seqlv2.0.tar.gz and unpack it with 19 | 20 | tar -zxvf seql-v2.0.tar.gz 21 | Execute 22 | o cd seql-v2.0/ 23 | o make or make all 24 | 25 | which compiles the code and creates the three executables 26 | 27 | seql_learn (learning module) 28 | seql_mkmodel (prepare the model) 29 | seql_classify (classification module) 30 | 31 | * For running the code on a toy example 32 | o make test_char (or make test_word) 33 | 34 | 35 | How to Use 36 | ----------- 37 | A simple toy training/test example can be found in: data/toy.char.train data/toy.char.test. 38 | The data is represented in the file as "class_label example_sequence" per line. 39 | Please be aware of setting the parameter [-n: 0 or 1] for the token representation desired, i.e., word-level ([-n 0]), where word-tokens are separated by space, or char-level ([-n 0]), where the input is a continuous string of characters, without spaces. This parameter needs to be set for "./seql_learn", "./seql_classify" and 40 | "./seql_classify_tune_threshold_min_errors". To see an example of running the code for word-tokens and char-tokens, please also have a look at the Makefile. 41 | 42 | 1. Train using ./seql_learn 43 | Usage: 44 | ./seql_learn [-o objective_function] [-m minsup] [-l minpat] [-L maxpat] [-g maxgap] [-r traversal_strategy ] 45 | [-T #round] [-n token_type] [-c convergence_threshold] [-C regularizer_value] [-a l1_vs_l2_regularizer_weight] 46 | [-v verbosity] train_file model_file 47 | 48 | Default values for parameters: 49 | [-o objective: 0 or 2] Objective function. Choice between logistic regression (-o 0) and squared-hinge support vector ma- 50 | chines (-o 2). By default set to logistic regression. 51 | [-g maxgap >= 0] Maximum number of consecutive gaps or wildcards allowed in a feature, e.g., a**b, 52 | is a feature of size 4 with any 2 characters from the input alphabet in the middle. By default 53 | set to 0. 54 | [-C regularizer value > 0] Value of the regularization parameter. By default set to 1. 55 | [-a alpha in [0,1]] Weight of l1 vs l2 regularizer for the elastic-net penalty. By default set to 0.2, i.e., 0.8*l1 + 0.2*l2 regularization. 56 | [-l minpat >= 1] Threshold on the minimum length of any feature. By default set to 1. 57 | [-L maxpat] Threshold on the maximum length of any feature. By default the maximum length 58 | is unrestricted, i.e., at most as long as the longest sequence in the training set. 59 | [-m minsup >= 1] Threshold on the minimum support of features, i.e., number of sequences containing 60 | a given feature. By default set to 1. 61 | [-n token type: 0 or 1] Word or character-level token. Words are delimited by white spaces. By default 62 | set to 1, character-level tokens. 63 | [-r traversal strategy: 0 or 1] Breadth First Search or Depth First Search traversal of the search tree. 64 | By default set to BFS. 65 | [-c convergence threshold >= 0] Stopping threshold based on change in aggregated score predictions. 66 | By default set to 0.005. 67 | [-T maxitr] Number of optimization iterations. By default set to the maximum between 5,000 68 | and the number of iterations resulting by using a convergence threshold on the aggregated 69 | change in score predictions. 70 | [-v verbosity: 1 to 5] Amount of printed detail about the training of the classifier. By default set to 1 71 | (light profiling information). 72 | 73 | 74 | Example call for char-token representation: (all other parameters set to their default values): 75 | ./seql_learn -n 1 -v 2 data/toy.char.train toy.seql.char.model 76 | 77 | 2. Prepare the final model using ./seql_mkmodel (this builds a trie on the features of the model for fast classification). 78 | Usage: ./seql_mkmodel [-i model_file] [-o binary_model_file] [-O predictors_file] 79 | 80 | Example call: 81 | ./seql_mkmodel -i toy.seql.char.model -o toy.seql.char.model.bin -O toy.seql.char.model.predictors 82 | 83 | 3. Classify using ./seql_classify (apply the learned model on new examples). 84 | Usage: ./seql_classify [-n token_type: 0 word tokens, 1 char tokens; by default set to 1] [-t classif_threshold: default 0] [-v verbosity level: default 0] test_file binary_model_file 85 | 86 | Example call: 87 | ./seql_classify -n 1 -v 2 data/toy.char.test toy.seql.char.model.bin 88 | 89 | Optionally one can tune the classification threshold on the training set, to minimize the number of training errors: 90 | ./seql_classify_tune_threshold_min_errors -n 1 -v 2 data/toy.char.train toy.seql.char.model.bin 91 | 92 | Best threshold:0.0746284 93 | 94 | and use the best theshold for classifying the test set: 95 | ./seql_classify -n 1 -t 0.0746284 -v 2 data/toy.char.test toy.seql.char.model.bin 96 | 97 | 98 | Disclaimer 99 | ---------- 100 | These software distributions are open source, licensed under the GNU General Public License (v3 or later). 101 | Note that this is the full GPL, which allows many free uses, but does not allow its incorporation 102 | (even in part or in translation) into any type of proprietary software which you distribute. 103 | Commercial licensing is also available; please contact us if you are interested. 104 | 105 | This program is distributed in the hope that it will be useful, 106 | but WITHOUT ANY WARRANTY; without even the implied warranty of 107 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 108 | GNU General Public License for more details. 109 | 110 | 111 | Acknowledgements 112 | ———————————————— 113 | Many thanks to Dan Søndergaard for his patch of darts.h and related files. 114 | 115 | 116 | References 117 | ---------- 118 | 119 | B. P. Pedersen, G. Ifrim, P. Liboriussen, K. B. Axelsen, M. G. Palmgren, P. Nissen, C. Wiuf, C. N. S. Pedersen 120 | “Large scale identification and categorization of protein sequences using Structured Logistic Regression” (PlosOne14) 121 | 122 | G. Ifrim, C. Wiuf 123 | “Bounded Coordinate-Descent for Biological Sequence Classification in High Dimensional Predictor Space” (KDD 2011) 124 | 125 | G. Ifrim: 126 | “Sequence Classification in High Dimensional Predictor Space", Cork Constraint Computation Centre, Seminar Talk, 2011. 127 | 128 | 129 | G. Ifrim, G. Bakir, G. Weikum: "Fast Logistic Regression for Text Categorization with Variable-Length N-grams", (KDD 2008) 130 | -------------------------------------------------------------------------------- /seql_classify_tune_threshold_min_errors.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: Georgiana Ifrim (georgiana.ifrim@gmail.com) 3 | * 4 | * This library uses a model stored in a trie 5 | * for fast classification of a given document set. 6 | * 7 | * The classification threshold is tuned on the given set in order 8 | * to maximize accuracy. This code is used for tuning the classification 9 | * threshold on the training set. 10 | * 11 | * This program is free software; you can redistribute it and/or 12 | * modify it under the terms of the GNU Library General Public 13 | * License as published by the Free Software Foundation. 14 | * 15 | */ 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include "mmap.h" 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include "common_string_symbol.h" 29 | #include "darts.h" 30 | #include "sys/time.h" 31 | 32 | static inline char *read_ptr (char **ptr, size_t size) 33 | { 34 | char *r = *ptr; 35 | *ptr += size; 36 | return r; 37 | } 38 | 39 | template static inline void read_static (char **ptr, T& value) 40 | { 41 | char *r = read_ptr (ptr, sizeof (T)); 42 | memcpy (&value, r, sizeof (T)); 43 | } 44 | 45 | template 46 | struct pair_2nd_cmp: public std::binary_function { 47 | bool operator () (const std::pair & x1, const std::pair &x2) 48 | { 49 | return x1.second > x2.second; 50 | } 51 | }; 52 | 53 | class SEQLClassifier 54 | { 55 | private: 56 | 57 | MeCab::Mmap mmap; 58 | double *alpha; 59 | Darts::DoubleArray da; 60 | std::vector result; 61 | std::vector doc; 62 | std::map rules; 63 | bool userule; 64 | 65 | // Recursive traversal of strings starting at pos. 66 | // prefix: current prefix, pos: current pos in the document 67 | void project (std::string prefix, unsigned int pos, size_t trie_pos, size_t str_pos, bool token_type) { 68 | 69 | if (pos == doc.size() - 1) return; 70 | 71 | // Check traversal with both the next actual unigram in the doc and the wildcard *. 72 | string next_unigrams[2]; 73 | next_unigrams[0] = doc[pos + 1].key(); 74 | next_unigrams[1] = "*"; 75 | 76 | for (int i = 0; i < 2; ++i) { 77 | 78 | string next_unigram = next_unigrams[i]; 79 | std::string item; 80 | if (!token_type) { //word-level token 81 | item = prefix + " " + next_unigram; 82 | } else { // char-level token 83 | item = prefix + next_unigram; 84 | } 85 | 86 | //cout << "\nitem: " << item.c_str(); 87 | size_t new_trie_pos = trie_pos; 88 | size_t new_str_pos = str_pos; 89 | int id = da.traverse (item.c_str(), new_trie_pos, new_str_pos); 90 | //cout <<"\nid: " << id; 91 | 92 | //if (id == -2) return; 93 | if (id == -2) { 94 | if (i == 0) continue; 95 | else return; 96 | } 97 | if (id >= 0) { 98 | if (userule) { 99 | //cout << "\nnew rule: " << item; 100 | rules.insert (std::make_pair (item, alpha[id])); 101 | } 102 | result.push_back (id); 103 | } 104 | project (item, pos + 1, new_trie_pos, new_str_pos, token_type); 105 | } 106 | } 107 | 108 | 109 | public: 110 | double bias; 111 | 112 | SEQLClassifier(): userule(false) {}; 113 | 114 | void setRule(bool t) { 115 | userule = t; 116 | } 117 | 118 | bool open (const char *file) { 119 | 120 | if (! mmap.open (file)) return false; 121 | 122 | char *ptr = mmap.begin (); 123 | unsigned int size = 0; 124 | read_static(&ptr, size); 125 | da.set_array (ptr); 126 | ptr += size; 127 | read_static(&ptr, bias); 128 | alpha = (double *)ptr; 129 | 130 | return true; 131 | } 132 | 133 | // Compute the area under the ROC curve. 134 | double calcROC( std::vector< std::pair >& forROC ) { 135 | 136 | //std::sort( forROC.begin(), forROC.end() ); 137 | double area = 0; 138 | double x=0, xbreak=0; 139 | double y=0, ybreak=0; 140 | double prevscore = - numeric_limits::infinity(); 141 | for( vector< pair >::reverse_iterator ritr=forROC.rbegin(); ritr!=forROC.rend(); ritr++ ) 142 | { 143 | double score = ritr->first; 144 | int label = ritr->second; 145 | if( score != prevscore ) { 146 | area += (x-xbreak)*(y+ybreak)/2.0; 147 | xbreak = x; 148 | ybreak = y; 149 | prevscore = score; 150 | } 151 | if( label > 0) y ++; 152 | else x ++; 153 | } 154 | area += (x-xbreak)*(y+ybreak)/2.0; //the last bin 155 | if( 0==y || x==0 ) area = 0.0; // degenerate case 156 | else area = 100.0 * area /( x*y ); 157 | return area; 158 | } 159 | 160 | // Classify with several classif threshold provided. 161 | // Return classification results in vector results_tuned_threshold. 162 | void classify (const char *line, double* predicted_score, bool token_type) { 163 | 164 | result.clear (); 165 | doc.clear (); 166 | rules.clear (); 167 | 168 | // Prepare instance as a vector of string_symbol, where sting symbol is a word or a character depending on tokenization type 169 | str2node (line, doc, token_type); 170 | 171 | for (unsigned int i = 0; i < doc.size(); ++i) { 172 | std::string item = doc[i].key(); 173 | int id; 174 | da.exactMatchSearch (item.c_str(), id); 175 | //cout << "\ndoc[i]: " << doc[i].key(); 176 | //cout << "\nid: " << id; 177 | if (id == -2) continue; 178 | if (id >= 0) { 179 | if (userule) { 180 | //cout << "\nnew rule: " << doc[i].key(); 181 | rules.insert (std::make_pair (doc[i].key(), alpha[id])); 182 | } 183 | result.push_back (id); 184 | } 185 | project (doc[i].key(), i, 0, 0, token_type); 186 | } 187 | 188 | std::sort (result.begin(), result.end()); 189 | // Binary frequencies, erase the duplicate feature ids, features count only once. 190 | result.erase (std::unique (result.begin(), result.end()), result.end()); 191 | 192 | for (unsigned int i = 0; i < result.size(); ++i) { 193 | (*predicted_score) += alpha[result[i]]; 194 | } 195 | } 196 | 197 | std::ostream &printRules (std::ostream &os) { 198 | 199 | std::vector > tmp; 200 | 201 | for (std::map ::iterator it = rules.begin(); it != rules.end(); ++it) 202 | tmp.push_back (std::make_pair (it->first, it->second)); 203 | 204 | std::sort (tmp.begin(), tmp.end(), pair_2nd_cmp()); 205 | 206 | //os << "rule: " << bias << " __DFAULT__" << std::endl; 207 | 208 | for (std::vector >::iterator it = tmp.begin(); it != tmp.end(); ++it) 209 | os << "rule: " << it->second << " " << it->first << std::endl; 210 | 211 | return os; 212 | } 213 | }; 214 | 215 | #define OPT " [-v verbose] [-n token_type: 0 word tokens, 1 char tokens] test_file binary_model_file" 216 | 217 | int main (int argc, char **argv) { 218 | 219 | std::istream *is = 0; 220 | unsigned int verbose = 0; 221 | // By default char token. 222 | bool token_type = 1; 223 | // Profiling variables. 224 | struct timeval t; 225 | struct timeval t_origin; 226 | 227 | gettimeofday(&t_origin, NULL); 228 | 229 | int opt; 230 | while ((opt = getopt(argc, argv, "n:v:")) != -1) { 231 | switch(opt) { 232 | case 'n': 233 | token_type = atoi(optarg); 234 | break; 235 | case 'v': 236 | verbose = atoi (optarg); 237 | break; 238 | default: 239 | std::cout << "Usage: " << argv[0] << OPT << std::endl; 240 | return -1; 241 | } 242 | } 243 | 244 | if (argc < 3) { 245 | std::cout << "Usage: " << argv[0] << OPT << std::endl; 246 | return -1; 247 | } 248 | 249 | if (! strcmp (argv[argc - 2], "-")) { 250 | is = &std::cin; 251 | } else { 252 | is = new std::ifstream (argv[argc - 2]); 253 | if (! *is) { 254 | std::cerr << argv[0] << " " << argv[argc-2] << " No such file or directory" << std::endl; 255 | return -1; 256 | } 257 | } 258 | 259 | SEQLClassifier seql; 260 | 261 | if (verbose >= 3) seql.setRule (true); 262 | 263 | if (! seql.open (argv[argc-1])) { 264 | std::cerr << argv[0] << " " << argv[argc-1] << " No such file or directory" << std::endl; 265 | return -1; 266 | } 267 | 268 | std::string line; 269 | char *column[4]; 270 | 271 | // Predicted score for a single document. 272 | double predicted_score = 0; 273 | // Predicted and true scores for all docs. 274 | vector > scores; 275 | // Total number of true positives. 276 | unsigned int num_positives = 0; 277 | // Total number of docs. 278 | unsigned int all = 0; 279 | 280 | cout << "\nreading training file for classif_tune_threshold...\n\n"; 281 | // Gather the predicted scores for all docs. 282 | while (std::getline (*is, line)) { 283 | 284 | if (line[0] == '\0' || line[0] == ';') continue; 285 | if (line[line.size() - 1] == '\r') { 286 | line[line.size() - 1] = '\0'; 287 | } 288 | 289 | if (2 != tokenize ((char *)line.c_str(), "\t ", column, 2)) { 290 | std::cerr << "Format Error: " << line.c_str() << std::endl; 291 | return -1; 292 | } 293 | 294 | // cout <<"\ncolumn[0]:*" << column[0] << "*"; 295 | // cout <<"\ncolumn[1]:*" << column[1] << "*"; 296 | // cout.flush(); 297 | 298 | int y = atoi (column[0]); 299 | predicted_score = 0; 300 | seql.classify (column[1], &predicted_score, token_type); 301 | // Keep predicted and true score. 302 | scores.push_back(pair(predicted_score, y)); 303 | 304 | // Transform the predicted_score which is a real number, into a probability, 305 | // using the logistic transformation: exp^{predicted_score} / 1 + exp^{predicted_score} = 1 / 2+ e^{-predicted_score}. 306 | double predicted_prob; 307 | if (predicted_score < -8000) { 308 | predicted_prob = 0; 309 | } else { 310 | predicted_prob = 1.0 / (1.0 + exp(-predicted_score)); 311 | } 312 | if (verbose == 1) { 313 | std::cout << y << " " << predicted_score << " " << predicted_prob << std::endl; 314 | } else if (verbose == 2) { 315 | std::cout << y << " " << predicted_score << " " << predicted_prob << " " << column[1] << std::endl; 316 | } else if (verbose >= 3) { 317 | std::cout << "" << std::endl; 318 | std::cout << y << " " << predicted_score << " " << predicted_prob << " " << column[1] << std::endl; 319 | seql.printRules (std::cout); 320 | std::cout << "" << std::endl; 321 | } 322 | 323 | ++all; 324 | if (y > 0) { 325 | ++num_positives; 326 | } 327 | } 328 | 329 | // Sort the scores ascendingly by the predicted score. 330 | sort(scores.begin(), scores.end()); 331 | double AUC = seql.calcROC(scores); 332 | 333 | std::printf ("AUC: %.5f%%\n", AUC); 334 | std::printf ("(1 - AUC): %.5f%%\n", (100 - AUC)); 335 | // Choose the threshold that minimized the errors on training data. 336 | // Same as Madigan et al BBR. 337 | 338 | // Start by retrieving all, e.g. predict all as positives. 339 | // Compute the error as FP + FN. 340 | unsigned int TP = num_positives; 341 | unsigned int FP = all - num_positives; 342 | unsigned int FN = 0; 343 | unsigned int TN = 0; 344 | 345 | unsigned int min_error = FP + FN; 346 | unsigned int current_error = 0; 347 | double best_threshold = -numeric_limits::max(); 348 | 349 | for (unsigned int i = 0; i < all; ++i) { 350 | // Take only 1st in a string of equal values 351 | if (i != 0 && scores[i].first > scores[i-1].first) { 352 | current_error = FP + FN; // sum of errors, e.g # training errors 353 | if (current_error < min_error) { 354 | min_error = current_error; 355 | best_threshold = (scores[i-1].first + scores[i].first) / 2; 356 | //cout << "\nThreshold: " << best_threshold; 357 | //cout << "\n# errors (FP + FN): " << min_error; 358 | //std::printf ("\nAccuracy: %.5f%% (%d/%d)\n", 100.0 * (TP + TN) / all, TP + TN, all); 359 | } 360 | } 361 | if (scores[i].second > 0) { 362 | FN++; TP--; 363 | }else{ 364 | FP--; TN++; 365 | } 366 | } 367 | 368 | // Finally, check the "retrieve none" situation 369 | current_error = FP + FN; 370 | if (current_error < min_error) { 371 | min_error = current_error; 372 | best_threshold = scores[all-1].first + 1; 373 | //cout << "\nThreshold (retrieve none): " << best_threshold; 374 | //cout << "\n# errors (FP + FN): " << min_error; 375 | //std::printf ("\nAccuracy: %.5f%% (%d/%d)\n", 100.0 * (TP + TN) / all, TP + TN, all); 376 | } 377 | 378 | // This procedure finds best_threshold such as if(predicted_score > best_threshold) classify pos; 379 | // Our seql_classify code uses predicted_score + bias > 0, thus we need to take -threshold. 380 | 381 | gettimeofday(&t, NULL); 382 | cout << "end classification( " << (t.tv_sec - t_origin.tv_sec) << " seconds; " << (t.tv_sec - t_origin.tv_sec) / 60.0 << " minutes )\n"; 383 | cout.flush(); 384 | 385 | // cout << "\nBest Threshold: " << best_threshold; 386 | cout << "\n# errors (FP + FN): " << min_error; 387 | std::printf ("\nAccuracy: %.5f%% (%d/%d)\n", 100.0 * (all - min_error) / all, all - min_error, all); 388 | 389 | // std::cout << "\nBias (-best_threshold):" << -best_threshold << std::endl; 390 | cout << "\nBest threshold: " << best_threshold; 391 | if (is != &std::cin) delete is; 392 | 393 | return 0; 394 | } 395 | -------------------------------------------------------------------------------- /seql_classify.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Author: Georgiana Ifrim (georgiana.ifrim@gmail.com) 3 | * 4 | * This library uses a model stored in a trie 5 | * for fast classification of a given test set. 6 | * 7 | * A customized (tuned) classification threshold can be provided as input to the classifier. 8 | * The program simply applies a suffix tree model to the test documents for predicting classification labels. 9 | * Prec, Recall, F1 and Accuracy are reported. 10 | * 11 | * This program is free software; you can redistribute it and/or 12 | * modify it under the terms of the GNU Library General Public 13 | * License as published by the Free Software Foundation. 14 | * 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include "mmap.h" 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include "common_string_symbol.h" 30 | #include "darts.h" 31 | #include "sys/time.h" 32 | 33 | static inline char *read_ptr (char **ptr, size_t size) 34 | { 35 | char *r = *ptr; 36 | *ptr += size; 37 | return r; 38 | } 39 | 40 | template static inline void read_static (char **ptr, T& value) 41 | { 42 | char *r = read_ptr (ptr, sizeof (T)); 43 | memcpy (&value, r, sizeof (T)); 44 | } 45 | 46 | template 47 | struct pair_2nd_cmp: public std::binary_function { 48 | bool operator () (const std::pair & x1, const std::pair &x2) 49 | { 50 | return x1.second > x2.second; 51 | } 52 | }; 53 | 54 | class SEQLClassifier 55 | { 56 | private: 57 | 58 | MeCab::Mmap mmap; 59 | double *alpha; 60 | double bias; 61 | Darts::DoubleArray da; 62 | std::vector result; 63 | std::vector doc; 64 | std::map rules; 65 | std::map rules_and_ids; 66 | 67 | bool userule; 68 | int oov_docs; 69 | 70 | void project (std::string prefix, 71 | unsigned int pos, 72 | size_t trie_pos, 73 | size_t str_pos, 74 | bool token_type) 75 | { 76 | if (pos == doc.size() - 1) return; 77 | 78 | // Check traversal with both the next actual unigram in the doc and the wildcard *. 79 | string next_unigrams[2]; 80 | next_unigrams[0] = doc[pos + 1].key(); 81 | next_unigrams[1] = "*"; 82 | 83 | for (int i = 0; i < 2; ++i) { 84 | 85 | string next_unigram = next_unigrams[i]; 86 | std::string item; 87 | if (!token_type) { //word-level token 88 | item = prefix + " " + next_unigram; 89 | } else { // char-level token 90 | item = prefix + next_unigram; 91 | } 92 | //cout << "\nitem: " << item.c_str(); 93 | size_t new_trie_pos = trie_pos; 94 | size_t new_str_pos = str_pos; 95 | int id = da.traverse (item.c_str(), new_trie_pos, new_str_pos); 96 | //cout <<"\nid: " << id; 97 | 98 | //if (id == -2) return; 99 | if (id == -2) { 100 | if (i == 0) continue; 101 | else return; 102 | } 103 | if (id >= 0) { 104 | if (userule) { 105 | //cout << "\nnew rule: " << item; 106 | rules.insert (std::make_pair(item, alpha[id])); 107 | rules_and_ids.insert (std::make_pair(item, id)); 108 | } 109 | result.push_back (id); 110 | } 111 | project (item, pos + 1, new_trie_pos, new_str_pos, token_type); 112 | } 113 | } 114 | 115 | public: 116 | 117 | SEQLClassifier(): userule(false), oov_docs(0) {}; 118 | 119 | double getBias() { 120 | return bias; 121 | } 122 | 123 | int getOOVDocs() { 124 | return oov_docs; 125 | } 126 | 127 | void setRule(bool t) 128 | { 129 | userule = t; 130 | } 131 | 132 | bool open (const char *file, double threshold) 133 | { 134 | if (! mmap.open (file)) return false; 135 | 136 | char *ptr = mmap.begin (); 137 | unsigned int size = 0; 138 | read_static(&ptr, size); 139 | da.set_array (ptr); 140 | ptr += size; 141 | read_static(&ptr, bias); // this bias from the model file is not used for classif; it is automatically obtained by summing 142 | // up the features of the model and it is used for info only 143 | bias = -threshold; //set bias to minus user-provided-thereshold 144 | 145 | alpha = (double *)ptr; 146 | 147 | return true; 148 | } 149 | 150 | // Compute the area under the ROC curve. 151 | double calcROC( std::vector< std::pair >& forROC ) 152 | { 153 | //std::sort( forROC.begin(), forROC.end() ); 154 | double area = 0; 155 | double x=0, xbreak=0; 156 | double y=0, ybreak=0; 157 | double prevscore = - numeric_limits::infinity(); 158 | for( vector< pair >::reverse_iterator ritr=forROC.rbegin(); ritr!=forROC.rend(); ritr++ ) 159 | { 160 | double score = ritr->first; 161 | int label = ritr->second; 162 | //cout << "\nscore: " << score << " label: " << label; 163 | if( score != prevscore ) { 164 | //cout << "\nx: " << x << " xbreak: " << xbreak << " y: " << y << " ybreak: " << ybreak; 165 | area += (x-xbreak)*(y+ybreak)/2.0; 166 | //cout << "\narea: " << area; 167 | xbreak = x; 168 | ybreak = y; 169 | prevscore = score; 170 | } 171 | if( label > 0) y ++; 172 | else x ++; 173 | } 174 | area += (x-xbreak)*(y+ybreak)/2.0; //the last bin 175 | if( 0==y || x==0 ) area = 0.0; // degenerate case 176 | else area = 100.0 * area /( x*y ); 177 | //cout << "\narea: " << area; 178 | return area; 179 | } 180 | 181 | // Compute the area under the ROC50 curve. 182 | // Fixes the number of negatives to 50. 183 | // Stop computing curve after seeing 50 negatives. 184 | double calcROC50( std::vector< std::pair >& forROC ) 185 | { 186 | //std::sort( forROC.begin(), forROC.end() ); 187 | double area50 = 0; 188 | double x=0, xbreak=0; 189 | double y=0, ybreak=0; 190 | double prevscore = - numeric_limits::infinity(); 191 | for( vector< pair >::reverse_iterator ritr=forROC.rbegin(); ritr!=forROC.rend(); ritr++ ) 192 | { 193 | double score = ritr->first; 194 | int label = ritr->second; 195 | 196 | if( score != prevscore && x < 50) { 197 | area50 += (x-xbreak)*(y+ybreak)/2.0; 198 | xbreak = x; 199 | ybreak = y; 200 | prevscore = score; 201 | } 202 | if( label > 0) y ++; 203 | else if (x < 50) x ++; 204 | } 205 | area50 += (x-xbreak)*(y+ybreak)/2.0; //the last bin 206 | if( 0==y || x==0 ) area50 = 0.0; // degenerate case 207 | else area50 = 100.0 * area50 /( 50*y ); 208 | return area50; 209 | } 210 | 211 | double classify (const char *line, bool token_type) 212 | { 213 | result.clear (); 214 | doc.clear (); 215 | rules.clear (); 216 | double r = bias; 217 | 218 | // Prepare instance as a vector of string_symbol 219 | str2node (line, doc, token_type); 220 | 221 | for (unsigned int i = 0; i < doc.size(); ++i) { 222 | std::string item = doc[i].key(); 223 | int id; 224 | da.exactMatchSearch (item.c_str(), id); 225 | //int id = da.exactMatchSearch (doc[i].key().c_str()); 226 | if (id == -2) continue; 227 | if (id >= 0) { 228 | if (userule) { 229 | rules.insert (std::make_pair(doc[i].key(), alpha[id])); 230 | rules_and_ids.insert (std::make_pair(doc[i].key(), id)); 231 | } 232 | result.push_back (id); 233 | } 234 | project (doc[i].key(), i, 0, 0, token_type); 235 | } 236 | 237 | std::sort (result.begin(), result.end()); 238 | 239 | // Binary frequencies, erase the duplicate feature ids, features count only once. 240 | result.erase (std::unique (result.begin(), result.end()), result.end()); 241 | 242 | if (result.size() == 0) { 243 | if (userule) 244 | cout << "\n Test doc out of vocabulary\n"; 245 | oov_docs++; 246 | } 247 | for (unsigned int i = 0; i < result.size(); ++i) r += alpha[result[i]]; 248 | 249 | return r; 250 | } 251 | 252 | std::ostream &printRules (std::ostream &os) 253 | { 254 | std::vector > tmp; 255 | 256 | for (std::map ::iterator it = rules.begin(); 257 | it != rules.end(); ++it) 258 | tmp.push_back (std::make_pair(it->first, it->second)); 259 | 260 | std::sort (tmp.begin(), tmp.end(), pair_2nd_cmp()); 261 | os << "\nrule: " << bias << " __DFAULT__" << std::endl; 262 | 263 | // for (std::vector >::iterator it = tmp.begin(); 264 | // it != tmp.end(); ++it) 265 | for (std::map ::iterator it = rules.begin(); 266 | it != rules.end(); ++it) 267 | //os << "rule: " << rules_and_ids[it->first] << " " << it->second << " " << it->first << std::endl; 268 | os << "rule: " << it->first << " " << it->second << std::endl; 269 | 270 | return os; 271 | } 272 | 273 | std::ostream &printIds (std::ostream &os) { 274 | for (std::map ::iterator it = rules_and_ids.begin(); it != rules_and_ids.end(); ++it) 275 | os << (it->second + 1) << ":1.0 "; 276 | os << "\n"; 277 | 278 | return os; 279 | } 280 | }; 281 | 282 | #define OPT " [-n token_type: 0 word tokens, 1 char tokens] [-t classif_threshold] [-v verbose] test_file binary_model_file" 283 | 284 | int main (int argc, char **argv) 285 | { 286 | std::istream *is = 0; 287 | unsigned int verbose = 0; 288 | double threshold = 0; // By default zero threshold = zero bias. 289 | // By default char tokens. 290 | bool token_type = 1; 291 | // Profiling variables. 292 | struct timeval t; 293 | struct timeval t_origin; 294 | 295 | gettimeofday(&t_origin, NULL); 296 | 297 | int opt; 298 | while ((opt = getopt(argc, argv, "n:t:v:")) != -1) { 299 | switch(opt) { 300 | case 'n': 301 | token_type = atoi(optarg); 302 | break; 303 | case 't': 304 | threshold = atof(optarg); 305 | break; 306 | case 'v': 307 | verbose = atoi(optarg); 308 | break; 309 | default: 310 | std::cout << "Usage: " << argv[0] << OPT << std::endl; 311 | return -1; 312 | } 313 | } 314 | 315 | if (argc < 3) { 316 | std::cout << "Usage: " << argv[0] << OPT << std::endl; 317 | return -1; 318 | } 319 | 320 | if (! strcmp (argv[argc - 2], "-")) { 321 | is = &std::cin; 322 | } else { 323 | is = new std::ifstream (argv[argc - 2]); 324 | if (! *is) { 325 | std::cerr << argv[0] << " " << argv[argc-2] << " No such file or directory" << std::endl; 326 | return -1; 327 | } 328 | } 329 | 330 | SEQLClassifier seql; 331 | 332 | if (verbose >= 3) seql.setRule (true); 333 | 334 | if (! seql.open (argv[argc-1], threshold)) { 335 | std::cerr << argv[0] << " " << argv[argc-1] << " No such file or directory" << std::endl; 336 | return -1; 337 | } 338 | 339 | std::string line; 340 | char *column[4]; 341 | // Predicted and true scores for all docs. 342 | vector > scores; 343 | 344 | unsigned int all = 0; 345 | unsigned int correct = 0; 346 | unsigned int res_a = 0; 347 | unsigned int res_b = 0; 348 | unsigned int res_c = 0; 349 | unsigned int res_d = 0; 350 | 351 | //cout << "\n\nreading test data...\n"; 352 | while (std::getline (*is, line)) { 353 | 354 | if (line[0] == '\0' || line[0] == ';') continue; 355 | if (line[line.size() - 1] == '\r') { 356 | line[line.size() - 1] = '\0'; 357 | } 358 | //cout << "\nline:*" << aux.c_str() << "*"; 359 | 360 | if (2 != tokenize ((char *)line.c_str(), "\t ", column, 2)) { 361 | std::cerr << "Format Error: " << line.c_str() << std::endl; 362 | return -1; 363 | } 364 | 365 | //cout <<"\ncolumn[0]:*" << column[0] << "*"; 366 | //cout <<"\ncolumn[1]:*" << column[1] << "*"; 367 | //cout.flush(); 368 | 369 | int y = atoi (column[0]); 370 | //cout << "\ny: " << y; 371 | double predicted_score = seql.classify (column[1], token_type); 372 | 373 | // Keep predicted and true score. 374 | scores.push_back(pair(predicted_score, y)); 375 | 376 | // Transform the predicted_score which is a real number, into a probability, 377 | // using the logistic transformation: exp^{predicted_score} / 1 + exp^{predicted_score} = 1 / 1 + e^{-predicted_score}. 378 | double predicted_prob; 379 | if (predicted_score < -8000) { 380 | predicted_prob = 0; 381 | } else { 382 | predicted_prob = 1.0 / (1.0 + exp(-predicted_score)); 383 | } 384 | 385 | if (verbose == 1) { 386 | std::cout << y << " " << predicted_score << " " << predicted_prob << std::endl; 387 | } else if (verbose == 2) { 388 | std::cout << y << " " << predicted_score << " " << predicted_prob << " " << column[1] << std::endl; 389 | } else if (verbose == 4) { 390 | std::cout << "" << std::endl; 391 | std::cout << y << " " << predicted_score << " " << predicted_prob << " " << column[1] << std::endl; 392 | seql.printRules (std::cout); 393 | std::cout << "" << std::endl; 394 | } else if (verbose == 5) { 395 | std::cout << y << " "; 396 | seql.printIds (std::cout); 397 | } 398 | 399 | all++; 400 | if (predicted_score > 0) { 401 | if(y > 0) correct++; 402 | if(y > 0) res_a++; else res_b++; 403 | } else { 404 | if(y < 0) correct++; 405 | if(y > 0) res_c++; else res_d++; 406 | } 407 | } 408 | 409 | double prec = 1.0 * res_a/(res_a + res_b); 410 | if (res_a + res_b == 0) prec = 0; 411 | double rec = 1.0 * res_a/(res_a + res_c); 412 | if (res_a + res_c == 0) rec = 0; 413 | double f1 = 2 * rec * prec / (prec+rec); 414 | if (prec + rec == 0) f1 = 0; 415 | 416 | double specificity = 1.0 * res_d/(res_d + res_b); 417 | if (res_d + res_b == 0) specificity = 0; 418 | // sensitivity = recall 419 | double sensitivity = 1.0 * res_a/(res_a + res_c); 420 | if (res_a + res_c == 0) sensitivity = 0; 421 | double fss = 2 * specificity * sensitivity / (specificity + sensitivity); 422 | if (specificity + sensitivity == 0) fss = 0; 423 | 424 | // Sort the scores ascendingly by the predicted score. 425 | sort(scores.begin(), scores.end()); 426 | double AUC = seql.calcROC(scores); 427 | double AUC50 = seql.calcROC50(scores); 428 | double balanced_error = 0.5 * ((1.0 * res_c / (res_a + res_c)) + (1.0 * res_b / (res_b + res_d))); 429 | 430 | //if (verbose >= 3) { 431 | std::printf ("Classif Threshold: %.5f\n", -seql.getBias()); 432 | std::printf ("Accuracy: %.5f%% (%d/%d)\n", 100.0 * correct / all , correct, all); 433 | std::printf ("Error: %.5f%% (%d/%d)\n", 100.0 - 100.0 * correct / all, all - correct, all); 434 | std::printf ("Balanced Error: %.5f%%\n", 100.0 * balanced_error); 435 | std::printf ("AUC: %.5f%%\n", AUC); 436 | //std::printf ("(1 - AUC): %.5f%%\n", 100 - AUC); 437 | std::printf ("AUC50: %.5f%%\n", AUC50); 438 | std::printf ("Precision: %.5f%% (%d/%d)\n", 100.0 * prec, res_a, res_a + res_b); 439 | std::printf ("Recall: %.5f%% (%d/%d)\n", 100.0 * rec, res_a, res_a + res_c); 440 | std::printf ("F1: %.5f%%\n", 100.0 * f1); 441 | std::printf ("Specificity: %.5f%% (%d/%d)\n", 100.0 * specificity, res_d, res_d + res_b); 442 | std::printf ("Sensitivity: %.5f%% (%d/%d)\n", 100.0 * sensitivity, res_a, res_a + res_c); 443 | std::printf ("FSS: %.5f%%\n", 100.0 * fss); 444 | 445 | std::printf ("System/Answer p/p p/n n/p n/n: %d %d %d %d\n", res_a,res_b,res_c,res_d); 446 | std::printf ("OOV docs: %d\n", seql.getOOVDocs()); 447 | 448 | gettimeofday(&t, NULL); 449 | cout << "end classification( " << (t.tv_sec - t_origin.tv_sec) << " seconds; " << (t.tv_sec - t_origin.tv_sec) / 60.0 << " minutes )\n"; 450 | cout.flush(); 451 | //} 452 | if (is != &std::cin) delete is; 453 | 454 | return 0; 455 | } 456 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /darts.h: -------------------------------------------------------------------------------- 1 | #ifndef DARTS_H_ 2 | #define DARTS_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #define DARTS_VERSION "0.32" 9 | 10 | // DARTS_THROW() throws a whose message starts with the 11 | // file name and the line number. For example, DARTS_THROW("error message") at 12 | // line 123 of "darts.h" throws a which has a pointer to 13 | // "darts.h:123: exception: error message". The message is available by using 14 | // what() as well as that of . 15 | #define DARTS_INT_TO_STR(value) #value 16 | #define DARTS_LINE_TO_STR(line) DARTS_INT_TO_STR(line) 17 | #define DARTS_LINE_STR DARTS_LINE_TO_STR(__LINE__) 18 | #define DARTS_THROW(msg) throw Darts::Details::Exception( \ 19 | __FILE__ ":" DARTS_LINE_STR ": exception: " msg) 20 | 21 | namespace Darts { 22 | 23 | // The following namespace hides the internal types and classes. 24 | namespace Details { 25 | 26 | // This header assumes that and are 32-bit integer types. 27 | // 28 | // Darts-clone keeps values associated with keys. The type of the values is 29 | // . Note that the values must be positive integers because the 30 | // most significant bit (MSB) of each value is used to represent whether the 31 | // corresponding unit is a leaf or not. Also, the keys are represented by 32 | // sequences of s. is the unsigned type of . 33 | typedef char char_type; 34 | typedef unsigned char uchar_type; 35 | typedef int value_type; 36 | 37 | // The main structure of Darts-clone is an array of s, and the 38 | // unit type is actually a wrapper of . 39 | typedef unsigned int id_type; 40 | 41 | // is the type of callback functions for reporting the 42 | // progress of building a dictionary. See also build() of . 43 | // The 1st argument receives the progress value and the 2nd argument receives 44 | // the maximum progress value. A usage example is to show the progress 45 | // percentage, 100.0 * (the 1st argument) / (the 2nd argument). 46 | typedef int (*progress_func_type)(std::size_t, std::size_t); 47 | 48 | // is the type of double-array units and it is a wrapper of 49 | // in practice. 50 | class DoubleArrayUnit { 51 | public: 52 | DoubleArrayUnit() : unit_() {} 53 | 54 | // has_leaf() returns whether a leaf unit is immediately derived from the 55 | // unit (true) or not (false). 56 | bool has_leaf() const { 57 | return ((unit_ >> 8) & 1) == 1; 58 | } 59 | // value() returns the value stored in the unit, and thus value() is 60 | // available when and only when the unit is a leaf unit. 61 | value_type value() const { 62 | return static_cast(unit_ & ((1U << 31) - 1)); 63 | } 64 | 65 | // label() returns the label associted with the unit. Note that a leaf unit 66 | // always returns an invalid label. For this feature, leaf unit's label() 67 | // returns an that has the MSB of 1. 68 | id_type label() const { 69 | return unit_ & ((1U << 31) | 0xFF); 70 | } 71 | // offset() returns the offset from the unit to its derived units. 72 | id_type offset() const { 73 | return (unit_ >> 10) << ((unit_ & (1U << 9)) >> 6); 74 | } 75 | 76 | private: 77 | id_type unit_; 78 | 79 | // Copyable. 80 | }; 81 | 82 | // Darts-clone throws an for memory allocation failure, invalid 83 | // arguments or a too large offset. The last case means that there are too many 84 | // keys in the given set of keys. Note that the `msg' of must be a 85 | // constant or static string because an keeps only a pointer to 86 | // that string. 87 | class Exception : public std::exception { 88 | public: 89 | explicit Exception(const char *msg = NULL) throw() : msg_(msg) {} 90 | Exception(const Exception &rhs) throw() : msg_(rhs.msg_) {} 91 | virtual ~Exception() throw() {} 92 | 93 | // overrides what() of . 94 | virtual const char *what() const throw() { 95 | return (msg_ != NULL) ? msg_ : ""; 96 | } 97 | 98 | private: 99 | const char *msg_; 100 | 101 | // Disallows operator=. 102 | Exception &operator=(const Exception &); 103 | }; 104 | 105 | } // namespace Details 106 | 107 | // is the interface of Darts-clone. Note that other 108 | // classes should not be accessed from outside. 109 | // 110 | // has 4 template arguments but only the 3rd one is used as 111 | // the type of values. Note that the given is used only from outside, and 112 | // the internal value type is not changed from . 113 | // In build(), given values are casted from to 114 | // by using static_cast. On the other hand, values are casted from 115 | // to in searching dictionaries. 116 | template 117 | class DoubleArrayImpl { 118 | public: 119 | // Even if this is changed, the internal value type is still 120 | // . Other types, such as 64-bit integer types 121 | // and floating-point number types, should not be used. 122 | typedef T value_type; 123 | // A key is reprenseted by a sequence of s. For example, 124 | // exactMatchSearch() takes a . 125 | typedef Details::char_type key_type; 126 | // In searching dictionaries, the values associated with the matched keys are 127 | // stored into or returned as s. 128 | typedef value_type result_type; 129 | 130 | // enables applications to get the lengths of the matched 131 | // keys in addition to the values. 132 | struct result_pair_type { 133 | value_type value; 134 | std::size_t length; 135 | }; 136 | 137 | // The constructor initializes member variables with 0 and NULLs. 138 | DoubleArrayImpl() : size_(0), array_(NULL), buf_(NULL) {} 139 | // The destructor frees memory allocated for units and then initializes 140 | // member variables with 0 and NULLs. 141 | virtual ~DoubleArrayImpl() { 142 | clear(); 143 | } 144 | 145 | // has 2 kinds of set_result()s. The 1st set_result() is to 146 | // set a value to a . The 2nd set_result() is to set a value and 147 | // a length to a . By using set_result()s, search methods 148 | // can return the 2 kinds of results in the same way. 149 | // Why the set_result()s are non-static? It is for compatibility. 150 | // 151 | // The 1st set_result() takes a length as the 3rd argument but it is not 152 | // used. If a compiler does a good job, codes for getting the length may be 153 | // removed. 154 | void set_result(value_type *result, value_type value, std::size_t) const { 155 | *result = value; 156 | } 157 | // The 2nd set_result() uses both `value' and `length'. 158 | void set_result(result_pair_type *result, 159 | value_type value, std::size_t length) const { 160 | result->value = value; 161 | result->length = length; 162 | } 163 | 164 | // set_array() calls clear() in order to free memory allocated to the old 165 | // array and then sets a new array. This function is useful to set a memory- 166 | // mapped array. Note that the array set by set_array() is not freed in 167 | // clear() and the destructor of . 168 | // set_array() can also set the size of the new array but the size is not 169 | // used in search methods. So it works well even if the 2nd argument is 0 or 170 | // omitted. Remember that size() and total_size() returns 0 in such a case. 171 | void set_array(const void *ptr, std::size_t size = 0) { 172 | clear(); 173 | array_ = static_cast(ptr); 174 | size_ = size; 175 | } 176 | // array() returns a pointer to the array of units. 177 | const void *array() const { 178 | return array_; 179 | } 180 | 181 | // clear() frees memory allocated to units and then initializes member 182 | // variables with 0 and NULLs. Note that clear() does not free memory if the 183 | // array of units was set by set_array(). In such a case, `array_' is not 184 | // NULL and `buf_' is NULL. 185 | void clear() { 186 | size_ = 0; 187 | array_ = NULL; 188 | if (buf_ != NULL) { 189 | delete[] buf_; 190 | buf_ = NULL; 191 | } 192 | } 193 | 194 | // unit_size() returns the size of each unit. The size must be 4 bytes. 195 | std::size_t unit_size() const { 196 | return sizeof(unit_type); 197 | } 198 | // size() returns the number of units. It can be 0 if set_array() is used. 199 | std::size_t size() const { 200 | return size_; 201 | } 202 | // total_size() returns the number of bytes allocated to the array of units. 203 | // It can be 0 if set_array() is used. 204 | std::size_t total_size() const { 205 | return unit_size() * size(); 206 | } 207 | // nonzero_size() exists for compatibility. It always returns the number of 208 | // units because it takes long time to count the number of non-zero units. 209 | std::size_t nonzero_size() const { 210 | return size(); 211 | } 212 | 213 | // build() constructs a dictionary from given key-value pairs. If `lengths' 214 | // is NULL, `keys' is handled as an array of zero-terminated strings. If 215 | // `values' is NULL, the index in `keys' is associated with each key, i.e. 216 | // the ith key has (i - 1) as its value. 217 | // Note that the key-value pairs must be arranged in key order and the values 218 | // must not be negative. Also, if there are duplicate keys, only the first 219 | // pair will be stored in the resultant dictionary. 220 | // `progress_func' is a pointer to a callback function. If it is not NULL, 221 | // it will be called in build() so that the caller can check the progress of 222 | // dictionary construction. For details, please see the definition of 223 | // . 224 | // The return value of build() is 0, and it indicates the success of the 225 | // operation. Otherwise, build() throws a , which is a 226 | // derived class of . 227 | // build() uses another construction algorithm if `values' is not NULL. In 228 | // this case, Darts-clone uses a Directed Acyclic Word Graph (DAWG) instead 229 | // of a trie because a DAWG is likely to be more compact than a trie. 230 | int build(std::size_t num_keys, const key_type *const *keys, 231 | const std::size_t *lengths = NULL, const value_type *values = NULL, 232 | Details::progress_func_type progress_func = NULL); 233 | 234 | // open() reads an array of units from the specified file. And if it goes 235 | // well, the old array will be freed and replaced with the new array read 236 | // from the file. `offset' specifies the number of bytes to be skipped before 237 | // reading an array. `size' specifies the number of bytes to be read from the 238 | // file. If the `size' is 0, the whole file will be read. 239 | // open() returns 0 iff the operation succeeds. Otherwise, it returns a 240 | // non-zero value or throws a . The exception is thrown 241 | // when and only when a memory allocation fails. 242 | int open(const char *file_name, const char *mode = "rb", 243 | std::size_t offset = 0, std::size_t size = 0); 244 | // save() writes the array of units into the specified file. `offset' 245 | // specifies the number of bytes to be skipped before writing the array. 246 | // open() returns 0 iff the operation succeeds. Otherwise, it returns a 247 | // non-zero value. 248 | int save(const char *file_name, const char *mode = "wb", 249 | std::size_t offset = 0) const; 250 | 251 | // The 1st exactMatchSearch() tests whether the given key exists or not, and 252 | // if it exists, its value and length are set to `result'. Otherwise, the 253 | // value and the length of `result' are set to -1 and 0 respectively. 254 | // Note that if `length' is 0, `key' is handled as a zero-terminated string. 255 | // `node_pos' specifies the start position of matching. This argument enables 256 | // the combination of exactMatchSearch() and traverse(). For example, if you 257 | // want to test "xyzA", "xyzBC", and "xyzDE", you can use traverse() to get 258 | // the node position corresponding to "xyz" and then you can use 259 | // exactMatchSearch() to test "A", "BC", and "DE" from that position. 260 | // Note that the length of `result' indicates the length from the `node_pos'. 261 | // In the above example, the lengths are { 1, 2, 2 }, not { 4, 5, 5 }. 262 | template 263 | void exactMatchSearch(const key_type *key, U &result, 264 | std::size_t length = 0, std::size_t node_pos = 0) const { 265 | result = exactMatchSearch(key, length, node_pos); 266 | } 267 | // The 2nd exactMatchSearch() returns a result instead of updating the 2nd 268 | // argument. So, the following exactMatchSearch() has only 3 arguments. 269 | template 270 | inline U exactMatchSearch(const key_type *key, std::size_t length = 0, 271 | std::size_t node_pos = 0) const; 272 | 273 | // commonPrefixSearch() searches for keys which match a prefix of the given 274 | // string. If `length' is 0, `key' is handled as a zero-terminated string. 275 | // The values and the lengths of at most `max_num_results' matched keys are 276 | // stored in `results'. commonPrefixSearch() returns the number of matched 277 | // keys. Note that the return value can be larger than `max_num_results' if 278 | // there are more than `max_num_results' matches. If you want to get all the 279 | // results, allocate more spaces and call commonPrefixSearch() again. 280 | // `node_pos' works as well as in exactMatchSearch(). 281 | template 282 | inline std::size_t commonPrefixSearch(const key_type *key, U *results, 283 | std::size_t max_num_results, std::size_t length = 0, 284 | std::size_t node_pos = 0) const; 285 | 286 | // In Darts-clone, a dictionary is a deterministic finite-state automaton 287 | // (DFA) and traverse() tests transitions on the DFA. The initial state is 288 | // `node_pos' and traverse() chooses transitions labeled key[key_pos], 289 | // key[key_pos + 1], ... in order. If there is not a transition labeled 290 | // key[key_pos + i], traverse() terminates the transitions at that state and 291 | // returns -2. Otherwise, traverse() ends without a termination and returns 292 | // -1 or a nonnegative value, -1 indicates that the final state was not an 293 | // accept state. When a nonnegative value is returned, it is the value 294 | // associated with the final accept state. That is, traverse() returns the 295 | // value associated with the given key if it exists. Note that traverse() 296 | // updates `node_pos' and `key_pos' after each transition. 297 | inline value_type traverse(const key_type *key, std::size_t &node_pos, 298 | std::size_t &key_pos, std::size_t length = 0) const; 299 | 300 | private: 301 | typedef Details::uchar_type uchar_type; 302 | typedef Details::id_type id_type; 303 | typedef Details::DoubleArrayUnit unit_type; 304 | 305 | std::size_t size_; 306 | const unit_type *array_; 307 | unit_type *buf_; 308 | 309 | // Disallows copy and assignment. 310 | DoubleArrayImpl(const DoubleArrayImpl &); 311 | DoubleArrayImpl &operator=(const DoubleArrayImpl &); 312 | }; 313 | 314 | // is the typical instance of . It uses 315 | // as the type of values and it is suitable for most cases. 316 | typedef DoubleArrayImpl DoubleArray; 317 | 318 | // The interface section ends here. For using Darts-clone, there is no need 319 | // to read the remaining section, which gives the implementation of 320 | // Darts-clone. 321 | 322 | // 323 | // Member functions of DoubleArrayImpl (except build()). 324 | // 325 | 326 | template 327 | int DoubleArrayImpl::open(const char *file_name, 328 | const char *mode, std::size_t offset, std::size_t size) { 329 | #ifdef _MSC_VER 330 | std::FILE *file; 331 | if (::fopen_s(&file, file_name, mode) != 0) { 332 | return -1; 333 | } 334 | #else 335 | std::FILE *file = std::fopen(file_name, mode); 336 | if (file == NULL) { 337 | return -1; 338 | } 339 | #endif 340 | if (size == 0) { 341 | if (std::fseek(file, 0, SEEK_END) != 0) { 342 | std::fclose(file); 343 | return -1; 344 | } 345 | size = std::ftell(file) - offset; 346 | } 347 | size /= unit_size(); 348 | if (size < 256 || (size & 0xFF) != 0) { 349 | std::fclose(file); 350 | return -1; 351 | } 352 | if (std::fseek(file, offset, SEEK_SET) != 0) { 353 | std::fclose(file); 354 | return -1; 355 | } 356 | unit_type units[256]; 357 | if (std::fread(units, unit_size(), 256, file) != 256) { 358 | std::fclose(file); 359 | return -1; 360 | } 361 | if (units[0].label() != '\0' || units[0].has_leaf() || 362 | units[0].offset() == 0 || units[0].offset() >= 512) { 363 | std::fclose(file); 364 | return -1; 365 | } 366 | for (id_type i = 1; i < 256; ++i) { 367 | if (units[i].label() <= 0xFF && units[i].offset() >= size) { 368 | std::fclose(file); 369 | return -1; 370 | } 371 | } 372 | unit_type *buf; 373 | try { 374 | buf = new unit_type[size]; 375 | for (id_type i = 0; i < 256; ++i) { 376 | buf[i] = units[i]; 377 | } 378 | } catch (const std::bad_alloc &) { 379 | std::fclose(file); 380 | DARTS_THROW("failed to open double-array: std::bad_alloc"); 381 | } 382 | if (size > 256) { 383 | if (std::fread(buf + 256, unit_size(), size - 256, file) != size - 256) { 384 | std::fclose(file); 385 | delete[] buf; 386 | return -1; 387 | } 388 | } 389 | std::fclose(file); 390 | clear(); 391 | size_ = size; 392 | array_ = buf; 393 | buf_ = buf; 394 | return 0; 395 | } 396 | 397 | template 398 | int DoubleArrayImpl::save(const char *file_name, 399 | const char *mode, std::size_t offset) const { 400 | if (size() == 0) { 401 | return -1; 402 | } 403 | #ifdef _MSC_VER 404 | std::FILE *file; 405 | if (::fopen_s(&file, file_name, mode) != 0) { 406 | return -1; 407 | } 408 | #else 409 | std::FILE *file = std::fopen(file_name, mode); 410 | if (file == NULL) { 411 | return -1; 412 | } 413 | #endif 414 | if (std::fseek(file, offset, SEEK_SET) != 0) { 415 | std::fclose(file); 416 | return -1; 417 | } 418 | if (std::fwrite(array_, unit_size(), size(), file) != size()) { 419 | std::fclose(file); 420 | return -1; 421 | } 422 | std::fclose(file); 423 | return 0; 424 | } 425 | 426 | template 427 | template 428 | inline U DoubleArrayImpl::exactMatchSearch(const key_type *key, 429 | std::size_t length, std::size_t node_pos) const { 430 | U result; 431 | set_result(&result, static_cast(-1), 0); 432 | unit_type unit = array_[node_pos]; 433 | if (length != 0) { 434 | for (std::size_t i = 0; i < length; ++i) { 435 | node_pos ^= unit.offset() ^ static_cast(key[i]); 436 | unit = array_[node_pos]; 437 | if (unit.label() != static_cast(key[i])) { 438 | return result; 439 | } 440 | } 441 | } else { 442 | for (; key[length] != '\0'; ++length) { 443 | node_pos ^= unit.offset() ^ static_cast(key[length]); 444 | unit = array_[node_pos]; 445 | if (unit.label() != static_cast(key[length])) { 446 | return result; 447 | } 448 | } 449 | } 450 | if (!unit.has_leaf()) { 451 | return result; 452 | } 453 | unit = array_[node_pos ^ unit.offset()]; 454 | set_result(&result, static_cast(unit.value()), length); 455 | return result; 456 | } 457 | 458 | template 459 | template 460 | inline std::size_t DoubleArrayImpl::commonPrefixSearch( 461 | const key_type *key, U *results, std::size_t max_num_results, 462 | std::size_t length, std::size_t node_pos) const { 463 | std::size_t num_results = 0; 464 | unit_type unit = array_[node_pos]; 465 | node_pos ^= unit.offset(); 466 | if (length != 0) { 467 | for (std::size_t i = 0; i < length; ++i) { 468 | node_pos ^= static_cast(key[i]); 469 | unit = array_[node_pos]; 470 | if (unit.label() != static_cast(key[i])) { 471 | return num_results; 472 | } 473 | node_pos ^= unit.offset(); 474 | if (unit.has_leaf()) { 475 | if (num_results < max_num_results) { 476 | set_result(&results[num_results], static_cast( 477 | array_[node_pos].value()), i + 1); 478 | } 479 | ++num_results; 480 | } 481 | } 482 | } else { 483 | for (; key[length] != '\0'; ++length) { 484 | node_pos ^= static_cast(key[length]); 485 | unit = array_[node_pos]; 486 | if (unit.label() != static_cast(key[length])) { 487 | return num_results; 488 | } 489 | node_pos ^= unit.offset(); 490 | if (unit.has_leaf()) { 491 | if (num_results < max_num_results) { 492 | set_result(&results[num_results], static_cast( 493 | array_[node_pos].value()), length + 1); 494 | } 495 | ++num_results; 496 | } 497 | } 498 | } 499 | return num_results; 500 | } 501 | 502 | template 503 | inline typename DoubleArrayImpl::value_type 504 | DoubleArrayImpl::traverse(const key_type *key, 505 | std::size_t &node_pos, std::size_t &key_pos, std::size_t length) const { 506 | id_type id = static_cast(node_pos); 507 | unit_type unit = array_[id]; 508 | if (length != 0) { 509 | for (; key_pos < length; ++key_pos) { 510 | id ^= unit.offset() ^ static_cast(key[key_pos]); 511 | unit = array_[id]; 512 | if (unit.label() != static_cast(key[key_pos])) { 513 | return static_cast(-2); 514 | } 515 | node_pos = id; 516 | } 517 | } else { 518 | for (; key[key_pos] != '\0'; ++key_pos) { 519 | id ^= unit.offset() ^ static_cast(key[key_pos]); 520 | unit = array_[id]; 521 | if (unit.label() != static_cast(key[key_pos])) { 522 | return static_cast(-2); 523 | } 524 | node_pos = id; 525 | } 526 | } 527 | if (!unit.has_leaf()) { 528 | return static_cast(-1); 529 | } 530 | unit = array_[id ^ unit.offset()]; 531 | return static_cast(unit.value()); 532 | } 533 | 534 | namespace Details { 535 | 536 | // 537 | // Memory management of array. 538 | // 539 | 540 | template 541 | class AutoArray { 542 | public: 543 | explicit AutoArray(T *array = NULL) : array_(array) {} 544 | ~AutoArray() { 545 | clear(); 546 | } 547 | 548 | const T &operator[](std::size_t id) const { 549 | return array_[id]; 550 | } 551 | T &operator[](std::size_t id) { 552 | return array_[id]; 553 | } 554 | 555 | bool empty() const { 556 | return array_ == NULL; 557 | } 558 | 559 | void clear() { 560 | if (array_ != NULL) { 561 | delete[] array_; 562 | array_ = NULL; 563 | } 564 | } 565 | void swap(AutoArray *array) { 566 | T *temp = array_; 567 | array_ = array->array_; 568 | array->array_ = temp; 569 | } 570 | void reset(T *array = NULL) { 571 | AutoArray(array).swap(this); 572 | } 573 | 574 | private: 575 | T *array_; 576 | 577 | // Disallows copy and assignment. 578 | AutoArray(const AutoArray &); 579 | AutoArray &operator=(const AutoArray &); 580 | }; 581 | 582 | // 583 | // Memory management of resizable array. 584 | // 585 | 586 | template 587 | class AutoPool { 588 | public: 589 | AutoPool() : buf_(), size_(0), capacity_(0) {} 590 | ~AutoPool() { 591 | clear(); 592 | } 593 | 594 | const T &operator[](std::size_t id) const { 595 | return *(reinterpret_cast(&buf_[0]) + id); 596 | } 597 | T &operator[](std::size_t id) { 598 | return *(reinterpret_cast(&buf_[0]) + id); 599 | } 600 | 601 | bool empty() const { 602 | return size_ == 0; 603 | } 604 | std::size_t size() const { 605 | return size_; 606 | } 607 | 608 | void clear() { 609 | resize(0); 610 | buf_.clear(); 611 | size_ = 0; 612 | capacity_ = 0; 613 | } 614 | 615 | void push_back(const T &value) { 616 | append(value); 617 | } 618 | void pop_back() { 619 | (*this)[--size_].~T(); 620 | } 621 | 622 | void append() { 623 | if (size_ == capacity_) { 624 | resize_buf(size_ + 1); 625 | } 626 | new(&(*this)[size_++]) T; 627 | } 628 | void append(const T &value) { 629 | if (size_ == capacity_) { 630 | resize_buf(size_ + 1); 631 | } 632 | new(&(*this)[size_++]) T(value); 633 | } 634 | 635 | void resize(std::size_t size) { 636 | while (size_ > size) { 637 | (*this)[--size_].~T(); 638 | } 639 | if (size > capacity_) { 640 | resize_buf(size); 641 | } 642 | while (size_ < size) { 643 | new(&(*this)[size_++]) T; 644 | } 645 | } 646 | void resize(std::size_t size, const T &value) { 647 | while (size_ > size) { 648 | (*this)[--size_].~T(); 649 | } 650 | if (size > capacity_) { 651 | resize_buf(size); 652 | } 653 | while (size_ < size) { 654 | new(&(*this)[size_++]) T(value); 655 | } 656 | } 657 | 658 | void reserve(std::size_t size) { 659 | if (size > capacity_) { 660 | resize_buf(size); 661 | } 662 | } 663 | 664 | private: 665 | AutoArray buf_; 666 | std::size_t size_; 667 | std::size_t capacity_; 668 | 669 | // Disallows copy and assignment. 670 | AutoPool(const AutoPool &); 671 | AutoPool &operator=(const AutoPool &); 672 | 673 | void resize_buf(std::size_t size); 674 | }; 675 | 676 | template 677 | void AutoPool::resize_buf(std::size_t size) { 678 | std::size_t capacity; 679 | if (size >= capacity_ * 2) { 680 | capacity = size; 681 | } else { 682 | capacity = 1; 683 | while (capacity < size) { 684 | capacity <<= 1; 685 | } 686 | } 687 | AutoArray buf; 688 | try { 689 | buf.reset(new char[sizeof(T) * capacity]); 690 | } catch (const std::bad_alloc &) { 691 | DARTS_THROW("failed to resize pool: std::bad_alloc"); 692 | } 693 | if (size_ > 0) { 694 | T *src = reinterpret_cast(&buf_[0]); 695 | T *dest = reinterpret_cast(&buf[0]); 696 | for (std::size_t i = 0; i < size_; ++i) { 697 | new(&dest[i]) T(src[i]); 698 | src[i].~T(); 699 | } 700 | } 701 | buf_.swap(&buf); 702 | capacity_ = capacity; 703 | } 704 | 705 | // 706 | // Memory management of stack. 707 | // 708 | 709 | template 710 | class AutoStack { 711 | public: 712 | AutoStack() : pool_() {} 713 | ~AutoStack() { 714 | clear(); 715 | } 716 | 717 | const T &top() const { 718 | return pool_[size() - 1]; 719 | } 720 | T &top() { 721 | return pool_[size() - 1]; 722 | } 723 | 724 | bool empty() const { 725 | return pool_.empty(); 726 | } 727 | std::size_t size() const { 728 | return pool_.size(); 729 | } 730 | 731 | void push(const T &value) { 732 | pool_.push_back(value); 733 | } 734 | void pop() { 735 | pool_.pop_back(); 736 | } 737 | 738 | void clear() { 739 | pool_.clear(); 740 | } 741 | 742 | private: 743 | AutoPool pool_; 744 | 745 | // Disallows copy and assignment. 746 | AutoStack(const AutoStack &); 747 | AutoStack &operator=(const AutoStack &); 748 | }; 749 | 750 | // 751 | // Succinct bit vector. 752 | // 753 | 754 | class BitVector { 755 | public: 756 | BitVector() : units_(), ranks_(), num_ones_(0), size_(0) {} 757 | ~BitVector() { 758 | clear(); 759 | } 760 | 761 | bool operator[](std::size_t id) const { 762 | return (units_[id / UNIT_SIZE] >> (id % UNIT_SIZE) & 1) == 1; 763 | } 764 | 765 | id_type rank(std::size_t id) const { 766 | std::size_t unit_id = id / UNIT_SIZE; 767 | return ranks_[unit_id] + pop_count(units_[unit_id] 768 | & (~0U >> (UNIT_SIZE - (id % UNIT_SIZE) - 1))); 769 | } 770 | 771 | void set(std::size_t id, bool bit) { 772 | if (bit) { 773 | units_[id / UNIT_SIZE] |= 1U << (id % UNIT_SIZE); 774 | } else { 775 | units_[id / UNIT_SIZE] &= ~(1U << (id % UNIT_SIZE)); 776 | } 777 | } 778 | 779 | bool empty() const { 780 | return units_.empty(); 781 | } 782 | std::size_t num_ones() const { 783 | return num_ones_; 784 | } 785 | std::size_t size() const { 786 | return size_; 787 | } 788 | 789 | void append() { 790 | if ((size_ % UNIT_SIZE) == 0) { 791 | units_.append(0); 792 | } 793 | ++size_; 794 | } 795 | void build(); 796 | 797 | void clear() { 798 | units_.clear(); 799 | ranks_.clear(); 800 | } 801 | 802 | private: 803 | enum { UNIT_SIZE = sizeof(id_type) * 8 }; 804 | 805 | AutoPool units_; 806 | AutoArray ranks_; 807 | std::size_t num_ones_; 808 | std::size_t size_; 809 | 810 | // Disallows copy and assignment. 811 | BitVector(const BitVector &); 812 | BitVector &operator=(const BitVector &); 813 | 814 | static id_type pop_count(id_type unit) { 815 | unit = ((unit & 0xAAAAAAAA) >> 1) + (unit & 0x55555555); 816 | unit = ((unit & 0xCCCCCCCC) >> 2) + (unit & 0x33333333); 817 | unit = ((unit >> 4) + unit) & 0x0F0F0F0F; 818 | unit += unit >> 8; 819 | unit += unit >> 16; 820 | return unit & 0xFF; 821 | } 822 | }; 823 | 824 | inline void BitVector::build() { 825 | try { 826 | ranks_.reset(new id_type[units_.size()]); 827 | } catch (const std::bad_alloc &) { 828 | DARTS_THROW("failed to build rank index: std::bad_alloc"); 829 | } 830 | num_ones_ = 0; 831 | for (std::size_t i = 0; i < units_.size(); ++i) { 832 | ranks_[i] = num_ones_; 833 | num_ones_ += pop_count(units_[i]); 834 | } 835 | } 836 | 837 | // 838 | // Keyset. 839 | // 840 | 841 | template 842 | class Keyset { 843 | public: 844 | Keyset(std::size_t num_keys, const char_type *const *keys, 845 | const std::size_t *lengths, const T *values) : 846 | num_keys_(num_keys), keys_(keys), lengths_(lengths), values_(values) {} 847 | 848 | std::size_t num_keys() const { 849 | return num_keys_; 850 | } 851 | const char_type *keys(std::size_t id) const { 852 | return keys_[id]; 853 | } 854 | uchar_type keys(std::size_t key_id, std::size_t char_id) const { 855 | if (has_lengths() && char_id >= lengths_[key_id]) { 856 | return '\0'; 857 | } 858 | return keys_[key_id][char_id]; 859 | } 860 | 861 | bool has_lengths() const { 862 | return lengths_ != NULL; 863 | } 864 | std::size_t lengths(std::size_t id) const { 865 | if (has_lengths()) { 866 | return lengths_[id]; 867 | } 868 | std::size_t length = 0; 869 | while (keys_[id][length] != '\0') { 870 | ++length; 871 | } 872 | return length; 873 | } 874 | 875 | bool has_values() const { 876 | return values_ != NULL; 877 | } 878 | value_type values(std::size_t id) const { 879 | if (has_values()) { 880 | return static_cast(values_[id]); 881 | } 882 | return static_cast(id); 883 | } 884 | 885 | private: 886 | std::size_t num_keys_; 887 | const char_type *const *keys_; 888 | const std::size_t *lengths_; 889 | const T *values_; 890 | 891 | // Disallows copy and assignment. 892 | Keyset(const Keyset &); 893 | Keyset &operator=(const Keyset &); 894 | }; 895 | 896 | // 897 | // Node of Directed Acyclic Word Graph (DAWG). 898 | // 899 | 900 | class DawgNode { 901 | public: 902 | DawgNode() : child_(0), sibling_(0), label_('\0'), 903 | is_state_(false), has_sibling_(false) {} 904 | 905 | void set_child(id_type child) { 906 | child_ = child; 907 | } 908 | void set_sibling(id_type sibling) { 909 | sibling_ = sibling; 910 | } 911 | void set_value(value_type value) { 912 | child_ = value; 913 | } 914 | void set_label(uchar_type label) { 915 | label_ = label; 916 | } 917 | void set_is_state(bool is_state) { 918 | is_state_ = is_state; 919 | } 920 | void set_has_sibling(bool has_sibling) { 921 | has_sibling_ = has_sibling; 922 | } 923 | 924 | id_type child() const { 925 | return child_; 926 | } 927 | id_type sibling() const { 928 | return sibling_; 929 | } 930 | value_type value() const { 931 | return static_cast(child_); 932 | } 933 | uchar_type label() const { 934 | return label_; 935 | } 936 | bool is_state() const { 937 | return is_state_; 938 | } 939 | bool has_sibling() const { 940 | return has_sibling_; 941 | } 942 | 943 | id_type unit() const { 944 | if (label_ == '\0') { 945 | return (child_ << 1) | (has_sibling_ ? 1 : 0); 946 | } 947 | return (child_ << 2) | (is_state_ ? 2 : 0) | (has_sibling_ ? 1 : 0); 948 | } 949 | 950 | private: 951 | id_type child_; 952 | id_type sibling_; 953 | uchar_type label_; 954 | bool is_state_; 955 | bool has_sibling_; 956 | 957 | // Copyable. 958 | }; 959 | 960 | // 961 | // Fixed unit of Directed Acyclic Word Graph (DAWG). 962 | // 963 | 964 | class DawgUnit { 965 | public: 966 | explicit DawgUnit(id_type unit = 0) : unit_(unit) {} 967 | DawgUnit(const DawgUnit &unit) : unit_(unit.unit_) {} 968 | 969 | DawgUnit &operator=(id_type unit) { 970 | unit_ = unit; 971 | return *this; 972 | } 973 | 974 | id_type unit() const { 975 | return unit_; 976 | } 977 | 978 | id_type child() const { 979 | return unit_ >> 2; 980 | } 981 | bool has_sibling() const { 982 | return (unit_ & 1) == 1; 983 | } 984 | value_type value() const { 985 | return static_cast(unit_ >> 1); 986 | } 987 | bool is_state() const { 988 | return (unit_ & 2) == 2; 989 | } 990 | 991 | private: 992 | id_type unit_; 993 | 994 | // Copyable. 995 | }; 996 | 997 | // 998 | // Directed Acyclic Word Graph (DAWG) builder. 999 | // 1000 | 1001 | class DawgBuilder { 1002 | public: 1003 | DawgBuilder() : nodes_(), units_(), labels_(), is_intersections_(), 1004 | table_(), node_stack_(), recycle_bin_(), num_states_(0) {} 1005 | ~DawgBuilder() { 1006 | clear(); 1007 | } 1008 | 1009 | id_type root() const { 1010 | return 0; 1011 | } 1012 | 1013 | id_type child(id_type id) const { 1014 | return units_[id].child(); 1015 | } 1016 | id_type sibling(id_type id) const { 1017 | return units_[id].has_sibling() ? (id + 1) : 0; 1018 | } 1019 | int value(id_type id) const { 1020 | return units_[id].value(); 1021 | } 1022 | 1023 | bool is_leaf(id_type id) const { 1024 | return label(id) == '\0'; 1025 | } 1026 | uchar_type label(id_type id) const { 1027 | return labels_[id]; 1028 | } 1029 | 1030 | bool is_intersection(id_type id) const { 1031 | return is_intersections_[id]; 1032 | } 1033 | id_type intersection_id(id_type id) const { 1034 | return is_intersections_.rank(id) - 1; 1035 | } 1036 | 1037 | std::size_t num_intersections() const { 1038 | return is_intersections_.num_ones(); 1039 | } 1040 | 1041 | std::size_t size() const { 1042 | return units_.size(); 1043 | } 1044 | 1045 | void init(); 1046 | void finish(); 1047 | 1048 | void insert(const char *key, std::size_t length, value_type value); 1049 | 1050 | void clear(); 1051 | 1052 | private: 1053 | enum { INITIAL_TABLE_SIZE = 1 << 10 }; 1054 | 1055 | AutoPool nodes_; 1056 | AutoPool units_; 1057 | AutoPool labels_; 1058 | BitVector is_intersections_; 1059 | AutoPool table_; 1060 | AutoStack node_stack_; 1061 | AutoStack recycle_bin_; 1062 | std::size_t num_states_; 1063 | 1064 | // Disallows copy and assignment. 1065 | DawgBuilder(const DawgBuilder &); 1066 | DawgBuilder &operator=(const DawgBuilder &); 1067 | 1068 | void flush(id_type id); 1069 | 1070 | void expand_table(); 1071 | 1072 | id_type find_unit(id_type id, id_type *hash_id) const; 1073 | id_type find_node(id_type node_id, id_type *hash_id) const; 1074 | 1075 | bool are_equal(id_type node_id, id_type unit_id) const; 1076 | 1077 | id_type hash_unit(id_type id) const; 1078 | id_type hash_node(id_type id) const; 1079 | 1080 | id_type append_node(); 1081 | id_type append_unit(); 1082 | 1083 | void free_node(id_type id) { 1084 | recycle_bin_.push(id); 1085 | } 1086 | 1087 | static id_type hash(id_type key) { 1088 | key = ~key + (key << 15); // key = (key << 15) - key - 1; 1089 | key = key ^ (key >> 12); 1090 | key = key + (key << 2); 1091 | key = key ^ (key >> 4); 1092 | key = key * 2057; // key = (key + (key << 3)) + (key << 11); 1093 | key = key ^ (key >> 16); 1094 | return key; 1095 | } 1096 | }; 1097 | 1098 | inline void DawgBuilder::init() { 1099 | table_.resize(INITIAL_TABLE_SIZE, 0); 1100 | append_node(); 1101 | append_unit(); 1102 | num_states_ = 1; 1103 | nodes_[0].set_label(0xFF); 1104 | node_stack_.push(0); 1105 | } 1106 | 1107 | inline void DawgBuilder::finish() { 1108 | flush(0); 1109 | units_[0] = nodes_[0].unit(); 1110 | labels_[0] = nodes_[0].label(); 1111 | nodes_.clear(); 1112 | table_.clear(); 1113 | node_stack_.clear(); 1114 | recycle_bin_.clear(); 1115 | is_intersections_.build(); 1116 | } 1117 | 1118 | inline void DawgBuilder::insert(const char *key, std::size_t length, 1119 | value_type value) { 1120 | if (value < 0) { 1121 | DARTS_THROW("failed to insert key: negative value"); 1122 | } else if (length == 0) { 1123 | DARTS_THROW("failed to insert key: zero-length key"); 1124 | } 1125 | id_type id = 0; 1126 | std::size_t key_pos = 0; 1127 | for (; key_pos <= length; ++key_pos) { 1128 | id_type child_id = nodes_[id].child(); 1129 | if (child_id == 0) { 1130 | break; 1131 | } 1132 | uchar_type key_label = static_cast(key[key_pos]); 1133 | if (key_pos < length && key_label == '\0') { 1134 | DARTS_THROW("failed to insert key: invalid null character"); 1135 | } 1136 | uchar_type unit_label = nodes_[child_id].label(); 1137 | if (key_label < unit_label) { 1138 | DARTS_THROW("failed to insert key: wrong key order"); 1139 | } else if (key_label > unit_label) { 1140 | nodes_[child_id].set_has_sibling(true); 1141 | flush(child_id); 1142 | break; 1143 | } 1144 | id = child_id; 1145 | } 1146 | if (key_pos > length) { 1147 | return; 1148 | } 1149 | for (; key_pos <= length; ++key_pos) { 1150 | uchar_type key_label = static_cast( 1151 | (key_pos < length) ? key[key_pos] : '\0'); 1152 | id_type child_id = append_node(); 1153 | if (nodes_[id].child() == 0) { 1154 | nodes_[child_id].set_is_state(true); 1155 | } 1156 | nodes_[child_id].set_sibling(nodes_[id].child()); 1157 | nodes_[child_id].set_label(key_label); 1158 | nodes_[id].set_child(child_id); 1159 | node_stack_.push(child_id); 1160 | id = child_id; 1161 | } 1162 | nodes_[id].set_value(value); 1163 | } 1164 | 1165 | inline void DawgBuilder::clear() { 1166 | nodes_.clear(); 1167 | units_.clear(); 1168 | labels_.clear(); 1169 | is_intersections_.clear(); 1170 | table_.clear(); 1171 | node_stack_.clear(); 1172 | recycle_bin_.clear(); 1173 | num_states_ = 0; 1174 | } 1175 | 1176 | inline void DawgBuilder::flush(id_type id) { 1177 | while (node_stack_.top() != id) { 1178 | id_type node_id = node_stack_.top(); 1179 | node_stack_.pop(); 1180 | if (num_states_ >= table_.size() - (table_.size() >> 2)) { 1181 | expand_table(); 1182 | } 1183 | id_type num_siblings = 0; 1184 | for (id_type i = node_id; i != 0; i = nodes_[i].sibling()) { 1185 | ++num_siblings; 1186 | } 1187 | id_type hash_id; 1188 | id_type match_id = find_node(node_id, &hash_id); 1189 | if (match_id != 0) { 1190 | is_intersections_.set(match_id, true); 1191 | } else { 1192 | id_type unit_id = 0; 1193 | for (id_type i = 0; i < num_siblings; ++i) { 1194 | unit_id = append_unit(); 1195 | } 1196 | for (id_type i = node_id; i != 0; i = nodes_[i].sibling()) { 1197 | units_[unit_id] = nodes_[i].unit(); 1198 | labels_[unit_id] = nodes_[i].label(); 1199 | --unit_id; 1200 | } 1201 | match_id = unit_id + 1; 1202 | table_[hash_id] = match_id; 1203 | ++num_states_; 1204 | } 1205 | for (id_type i = node_id, next; i != 0; i = next) { 1206 | next = nodes_[i].sibling(); 1207 | free_node(i); 1208 | } 1209 | nodes_[node_stack_.top()].set_child(match_id); 1210 | } 1211 | node_stack_.pop(); 1212 | } 1213 | 1214 | inline void DawgBuilder::expand_table() { 1215 | std::size_t table_size = table_.size() << 1; 1216 | table_.clear(); 1217 | table_.resize(table_size, 0); 1218 | for (std::size_t i = 1; i < units_.size(); ++i) { 1219 | id_type id = static_cast(i); 1220 | if (labels_[id] == '\0' || units_[id].is_state()) { 1221 | id_type hash_id; 1222 | find_unit(id, &hash_id); 1223 | table_[hash_id] = id; 1224 | } 1225 | } 1226 | } 1227 | 1228 | inline id_type DawgBuilder::find_unit(id_type id, id_type *hash_id) const { 1229 | *hash_id = hash_unit(id) % table_.size(); 1230 | for (; ; *hash_id = (*hash_id + 1) % table_.size()) { 1231 | id_type unit_id = table_[*hash_id]; 1232 | if (unit_id == 0) { 1233 | break; 1234 | } 1235 | // There must not be the same unit. 1236 | } 1237 | return 0; 1238 | } 1239 | 1240 | inline id_type DawgBuilder::find_node(id_type node_id, 1241 | id_type *hash_id) const { 1242 | *hash_id = hash_node(node_id) % table_.size(); 1243 | for (; ; *hash_id = (*hash_id + 1) % table_.size()) { 1244 | id_type unit_id = table_[*hash_id]; 1245 | if (unit_id == 0) { 1246 | break; 1247 | } 1248 | if (are_equal(node_id, unit_id)) { 1249 | return unit_id; 1250 | } 1251 | } 1252 | return 0; 1253 | } 1254 | 1255 | inline bool DawgBuilder::are_equal(id_type node_id, id_type unit_id) const { 1256 | for (id_type i = nodes_[node_id].sibling(); i != 0; 1257 | i = nodes_[i].sibling()) { 1258 | if (units_[unit_id].has_sibling() == false) { 1259 | return false; 1260 | } 1261 | ++unit_id; 1262 | } 1263 | if (units_[unit_id].has_sibling() == true) { 1264 | return false; 1265 | } 1266 | for (id_type i = node_id; i != 0; i = nodes_[i].sibling(), --unit_id) { 1267 | if (nodes_[i].unit() != units_[unit_id].unit() || 1268 | nodes_[i].label() != labels_[unit_id]) { 1269 | return false; 1270 | } 1271 | } 1272 | return true; 1273 | } 1274 | 1275 | inline id_type DawgBuilder::hash_unit(id_type id) const { 1276 | id_type hash_value = 0; 1277 | for (; id != 0; ++id) { 1278 | id_type unit = units_[id].unit(); 1279 | uchar_type label = labels_[id]; 1280 | hash_value ^= hash((label << 24) ^ unit); 1281 | if (units_[id].has_sibling() == false) { 1282 | break; 1283 | } 1284 | } 1285 | return hash_value; 1286 | } 1287 | 1288 | inline id_type DawgBuilder::hash_node(id_type id) const { 1289 | id_type hash_value = 0; 1290 | for (; id != 0; id = nodes_[id].sibling()) { 1291 | id_type unit = nodes_[id].unit(); 1292 | uchar_type label = nodes_[id].label(); 1293 | hash_value ^= hash((label << 24) ^ unit); 1294 | } 1295 | return hash_value; 1296 | } 1297 | 1298 | inline id_type DawgBuilder::append_unit() { 1299 | is_intersections_.append(); 1300 | units_.append(); 1301 | labels_.append(); 1302 | return static_cast(is_intersections_.size() - 1); 1303 | } 1304 | 1305 | inline id_type DawgBuilder::append_node() { 1306 | id_type id; 1307 | if (recycle_bin_.empty()) { 1308 | id = static_cast(nodes_.size()); 1309 | nodes_.append(); 1310 | } else { 1311 | id = recycle_bin_.top(); 1312 | nodes_[id] = DawgNode(); 1313 | recycle_bin_.pop(); 1314 | } 1315 | return id; 1316 | } 1317 | 1318 | // 1319 | // Unit of double-array builder. 1320 | // 1321 | 1322 | class DoubleArrayBuilderUnit { 1323 | public: 1324 | DoubleArrayBuilderUnit() : unit_(0) {} 1325 | 1326 | void set_has_leaf(bool has_leaf) { 1327 | if (has_leaf) { 1328 | unit_ |= 1U << 8; 1329 | } else { 1330 | unit_ &= ~(1U << 8); 1331 | } 1332 | } 1333 | void set_value(value_type value) { 1334 | unit_ = value | (1U << 31); 1335 | } 1336 | void set_label(uchar_type label) { 1337 | unit_ = (unit_ & ~0xFFU) | label; 1338 | } 1339 | void set_offset(id_type offset) { 1340 | if (offset >= 1U << 29) { 1341 | DARTS_THROW("failed to modify unit: too large offset"); 1342 | } 1343 | unit_ &= (1U << 31) | (1U << 8) | 0xFF; 1344 | if (offset < 1U << 21) { 1345 | unit_ |= (offset << 10); 1346 | } else { 1347 | unit_ |= (offset << 2) | (1U << 9); 1348 | } 1349 | } 1350 | 1351 | private: 1352 | id_type unit_; 1353 | 1354 | // Copyable. 1355 | }; 1356 | 1357 | // 1358 | // Extra unit of double-array builder. 1359 | // 1360 | 1361 | class DoubleArrayBuilderExtraUnit { 1362 | public: 1363 | DoubleArrayBuilderExtraUnit() : prev_(0), next_(0), 1364 | is_fixed_(false), is_used_(false) {} 1365 | 1366 | void set_prev(id_type prev) { 1367 | prev_ = prev; 1368 | } 1369 | void set_next(id_type next) { 1370 | next_ = next; 1371 | } 1372 | void set_is_fixed(bool is_fixed) { 1373 | is_fixed_ = is_fixed; 1374 | } 1375 | void set_is_used(bool is_used) { 1376 | is_used_ = is_used; 1377 | } 1378 | 1379 | id_type prev() const { 1380 | return prev_; 1381 | } 1382 | id_type next() const { 1383 | return next_; 1384 | } 1385 | bool is_fixed() const { 1386 | return is_fixed_; 1387 | } 1388 | bool is_used() const { 1389 | return is_used_; 1390 | } 1391 | 1392 | private: 1393 | id_type prev_; 1394 | id_type next_; 1395 | bool is_fixed_; 1396 | bool is_used_; 1397 | 1398 | // Copyable. 1399 | }; 1400 | 1401 | // 1402 | // DAWG -> double-array converter. 1403 | // 1404 | 1405 | class DoubleArrayBuilder { 1406 | public: 1407 | explicit DoubleArrayBuilder(progress_func_type progress_func) 1408 | : progress_func_(progress_func), units_(), extras_(), labels_(), 1409 | table_(), extras_head_(0) {} 1410 | ~DoubleArrayBuilder() { 1411 | clear(); 1412 | } 1413 | 1414 | template 1415 | void build(const Keyset &keyset); 1416 | void copy(std::size_t *size_ptr, DoubleArrayUnit **buf_ptr) const; 1417 | 1418 | void clear(); 1419 | 1420 | private: 1421 | enum { BLOCK_SIZE = 256 }; 1422 | enum { NUM_EXTRA_BLOCKS = 16 }; 1423 | enum { NUM_EXTRAS = BLOCK_SIZE * NUM_EXTRA_BLOCKS }; 1424 | 1425 | enum { UPPER_MASK = 0xFF << 21 }; 1426 | enum { LOWER_MASK = 0xFF }; 1427 | 1428 | typedef DoubleArrayBuilderUnit unit_type; 1429 | typedef DoubleArrayBuilderExtraUnit extra_type; 1430 | 1431 | progress_func_type progress_func_; 1432 | AutoPool units_; 1433 | AutoArray extras_; 1434 | AutoPool labels_; 1435 | AutoArray table_; 1436 | id_type extras_head_; 1437 | 1438 | // Disallows copy and assignment. 1439 | DoubleArrayBuilder(const DoubleArrayBuilder &); 1440 | DoubleArrayBuilder &operator=(const DoubleArrayBuilder &); 1441 | 1442 | std::size_t num_blocks() const { 1443 | return units_.size() / BLOCK_SIZE; 1444 | } 1445 | 1446 | const extra_type &extras(id_type id) const { 1447 | return extras_[id % NUM_EXTRAS]; 1448 | } 1449 | extra_type &extras(id_type id) { 1450 | return extras_[id % NUM_EXTRAS]; 1451 | } 1452 | 1453 | template 1454 | void build_dawg(const Keyset &keyset, DawgBuilder *dawg_builder); 1455 | void build_from_dawg(const DawgBuilder &dawg); 1456 | void build_from_dawg(const DawgBuilder &dawg, 1457 | id_type dawg_id, id_type dic_id); 1458 | id_type arrange_from_dawg(const DawgBuilder &dawg, 1459 | id_type dawg_id, id_type dic_id); 1460 | 1461 | template 1462 | void build_from_keyset(const Keyset &keyset); 1463 | template 1464 | void build_from_keyset(const Keyset &keyset, std::size_t begin, 1465 | std::size_t end, std::size_t depth, id_type dic_id); 1466 | template 1467 | id_type arrange_from_keyset(const Keyset &keyset, std::size_t begin, 1468 | std::size_t end, std::size_t depth, id_type dic_id); 1469 | 1470 | id_type find_valid_offset(id_type id) const; 1471 | bool is_valid_offset(id_type id, id_type offset) const; 1472 | 1473 | void reserve_id(id_type id); 1474 | void expand_units(); 1475 | 1476 | void fix_all_blocks(); 1477 | void fix_block(id_type block_id); 1478 | }; 1479 | 1480 | template 1481 | void DoubleArrayBuilder::build(const Keyset &keyset) { 1482 | if (keyset.has_values()) { 1483 | Details::DawgBuilder dawg_builder; 1484 | build_dawg(keyset, &dawg_builder); 1485 | build_from_dawg(dawg_builder); 1486 | dawg_builder.clear(); 1487 | } else { 1488 | build_from_keyset(keyset); 1489 | } 1490 | } 1491 | 1492 | inline void DoubleArrayBuilder::copy(std::size_t *size_ptr, 1493 | DoubleArrayUnit **buf_ptr) const { 1494 | if (size_ptr != NULL) { 1495 | *size_ptr = units_.size(); 1496 | } 1497 | if (buf_ptr != NULL) { 1498 | *buf_ptr = new DoubleArrayUnit[units_.size()]; 1499 | unit_type *units = reinterpret_cast(*buf_ptr); 1500 | for (std::size_t i = 0; i < units_.size(); ++i) { 1501 | units[i] = units_[i]; 1502 | } 1503 | } 1504 | } 1505 | 1506 | inline void DoubleArrayBuilder::clear() { 1507 | units_.clear(); 1508 | extras_.clear(); 1509 | labels_.clear(); 1510 | table_.clear(); 1511 | extras_head_ = 0; 1512 | } 1513 | 1514 | template 1515 | void DoubleArrayBuilder::build_dawg(const Keyset &keyset, 1516 | DawgBuilder *dawg_builder) { 1517 | dawg_builder->init(); 1518 | for (std::size_t i = 0; i < keyset.num_keys(); ++i) { 1519 | dawg_builder->insert(keyset.keys(i), keyset.lengths(i), keyset.values(i)); 1520 | if (progress_func_ != NULL) { 1521 | progress_func_(i + 1, keyset.num_keys() + 1); 1522 | } 1523 | } 1524 | dawg_builder->finish(); 1525 | } 1526 | 1527 | inline void DoubleArrayBuilder::build_from_dawg(const DawgBuilder &dawg) { 1528 | std::size_t num_units = 1; 1529 | while (num_units < dawg.size()) { 1530 | num_units <<= 1; 1531 | } 1532 | units_.reserve(num_units); 1533 | table_.reset(new id_type[dawg.num_intersections()]); 1534 | for (std::size_t i = 0; i < dawg.num_intersections(); ++i) { 1535 | table_[i] = 0; 1536 | } 1537 | extras_.reset(new extra_type[NUM_EXTRAS]); 1538 | reserve_id(0); 1539 | extras(0).set_is_used(true); 1540 | units_[0].set_offset(1); 1541 | units_[0].set_label('\0'); 1542 | if (dawg.child(dawg.root()) != 0) { 1543 | build_from_dawg(dawg, dawg.root(), 0); 1544 | } 1545 | fix_all_blocks(); 1546 | extras_.clear(); 1547 | labels_.clear(); 1548 | table_.clear(); 1549 | } 1550 | 1551 | inline void DoubleArrayBuilder::build_from_dawg(const DawgBuilder &dawg, 1552 | id_type dawg_id, id_type dic_id) { 1553 | id_type dawg_child_id = dawg.child(dawg_id); 1554 | if (dawg.is_intersection(dawg_child_id)) { 1555 | id_type intersection_id = dawg.intersection_id(dawg_child_id); 1556 | id_type offset = table_[intersection_id]; 1557 | if (offset != 0) { 1558 | offset ^= dic_id; 1559 | if (!(offset & UPPER_MASK) || !(offset & LOWER_MASK)) { 1560 | if (dawg.is_leaf(dawg_child_id)) { 1561 | units_[dic_id].set_has_leaf(true); 1562 | } 1563 | units_[dic_id].set_offset(offset); 1564 | return; 1565 | } 1566 | } 1567 | } 1568 | id_type offset = arrange_from_dawg(dawg, dawg_id, dic_id); 1569 | if (dawg.is_intersection(dawg_child_id)) { 1570 | table_[dawg.intersection_id(dawg_child_id)] = offset; 1571 | } 1572 | do { 1573 | uchar_type child_label = dawg.label(dawg_child_id); 1574 | id_type dic_child_id = offset ^ child_label; 1575 | if (child_label != '\0') { 1576 | build_from_dawg(dawg, dawg_child_id, dic_child_id); 1577 | } 1578 | dawg_child_id = dawg.sibling(dawg_child_id); 1579 | } while (dawg_child_id != 0); 1580 | } 1581 | 1582 | inline id_type DoubleArrayBuilder::arrange_from_dawg(const DawgBuilder &dawg, 1583 | id_type dawg_id, id_type dic_id) { 1584 | labels_.resize(0); 1585 | id_type dawg_child_id = dawg.child(dawg_id); 1586 | while (dawg_child_id != 0) { 1587 | labels_.append(dawg.label(dawg_child_id)); 1588 | dawg_child_id = dawg.sibling(dawg_child_id); 1589 | } 1590 | id_type offset = find_valid_offset(dic_id); 1591 | units_[dic_id].set_offset(dic_id ^ offset); 1592 | dawg_child_id = dawg.child(dawg_id); 1593 | for (std::size_t i = 0; i < labels_.size(); ++i) { 1594 | id_type dic_child_id = offset ^ labels_[i]; 1595 | reserve_id(dic_child_id); 1596 | if (dawg.is_leaf(dawg_child_id)) { 1597 | units_[dic_id].set_has_leaf(true); 1598 | units_[dic_child_id].set_value(dawg.value(dawg_child_id)); 1599 | } else { 1600 | units_[dic_child_id].set_label(labels_[i]); 1601 | } 1602 | dawg_child_id = dawg.sibling(dawg_child_id); 1603 | } 1604 | extras(offset).set_is_used(true); 1605 | return offset; 1606 | } 1607 | 1608 | template 1609 | void DoubleArrayBuilder::build_from_keyset(const Keyset &keyset) { 1610 | std::size_t num_units = 1; 1611 | while (num_units < keyset.num_keys()) { 1612 | num_units <<= 1; 1613 | } 1614 | units_.reserve(num_units); 1615 | extras_.reset(new extra_type[NUM_EXTRAS]); 1616 | reserve_id(0); 1617 | extras(0).set_is_used(true); 1618 | units_[0].set_offset(1); 1619 | units_[0].set_label('\0'); 1620 | if (keyset.num_keys() > 0) { 1621 | build_from_keyset(keyset, 0, keyset.num_keys(), 0, 0); 1622 | } 1623 | fix_all_blocks(); 1624 | extras_.clear(); 1625 | labels_.clear(); 1626 | } 1627 | 1628 | template 1629 | void DoubleArrayBuilder::build_from_keyset(const Keyset &keyset, 1630 | std::size_t begin, std::size_t end, std::size_t depth, id_type dic_id) { 1631 | id_type offset = arrange_from_keyset(keyset, begin, end, depth, dic_id); 1632 | while (begin < end) { 1633 | if (keyset.keys(begin, depth) != '\0') { 1634 | break; 1635 | } 1636 | ++begin; 1637 | } 1638 | if (begin == end) { 1639 | return; 1640 | } 1641 | std::size_t last_begin = begin; 1642 | uchar_type last_label = keyset.keys(begin, depth); 1643 | while (++begin < end) { 1644 | uchar_type label = keyset.keys(begin, depth); 1645 | if (label != last_label) { 1646 | build_from_keyset(keyset, last_begin, begin, 1647 | depth + 1, offset ^ last_label); 1648 | last_begin = begin; 1649 | last_label = keyset.keys(begin, depth); 1650 | } 1651 | } 1652 | build_from_keyset(keyset, last_begin, end, depth + 1, offset ^ last_label); 1653 | } 1654 | 1655 | template 1656 | id_type DoubleArrayBuilder::arrange_from_keyset(const Keyset &keyset, 1657 | std::size_t begin, std::size_t end, std::size_t depth, id_type dic_id) { 1658 | labels_.resize(0); 1659 | value_type value = -1; 1660 | for (std::size_t i = begin; i < end; ++i) { 1661 | uchar_type label = keyset.keys(i, depth); 1662 | if (label == '\0') { 1663 | if (keyset.has_lengths() && depth < keyset.lengths(i)) { 1664 | DARTS_THROW("failed to build double-array: " 1665 | "invalid null character"); 1666 | } else if (keyset.values(i) < 0) { 1667 | DARTS_THROW("failed to build double-array: negative value"); 1668 | } 1669 | if (value == -1) { 1670 | value = keyset.values(i); 1671 | } 1672 | if (progress_func_ != NULL) { 1673 | progress_func_(i + 1, keyset.num_keys() + 1); 1674 | } 1675 | } 1676 | if (labels_.empty()) { 1677 | labels_.append(label); 1678 | } else if (label != labels_[labels_.size() - 1]) { 1679 | if (label < labels_[labels_.size() - 1]) { 1680 | DARTS_THROW("failed to build double-array: wrong key order"); 1681 | } 1682 | labels_.append(label); 1683 | } 1684 | } 1685 | id_type offset = find_valid_offset(dic_id); 1686 | units_[dic_id].set_offset(dic_id ^ offset); 1687 | for (std::size_t i = 0; i < labels_.size(); ++i) { 1688 | id_type dic_child_id = offset ^ labels_[i]; 1689 | reserve_id(dic_child_id); 1690 | if (labels_[i] == '\0') { 1691 | units_[dic_id].set_has_leaf(true); 1692 | units_[dic_child_id].set_value(value); 1693 | } else { 1694 | units_[dic_child_id].set_label(labels_[i]); 1695 | } 1696 | } 1697 | extras(offset).set_is_used(true); 1698 | return offset; 1699 | } 1700 | 1701 | inline id_type DoubleArrayBuilder::find_valid_offset(id_type id) const { 1702 | if (extras_head_ >= units_.size()) { 1703 | return units_.size() | (id & LOWER_MASK); 1704 | } 1705 | id_type unfixed_id = extras_head_; 1706 | do { 1707 | id_type offset = unfixed_id ^ labels_[0]; 1708 | if (is_valid_offset(id, offset)) { 1709 | return offset; 1710 | } 1711 | unfixed_id = extras(unfixed_id).next(); 1712 | } while (unfixed_id != extras_head_); 1713 | return units_.size() | (id & LOWER_MASK); 1714 | } 1715 | 1716 | inline bool DoubleArrayBuilder::is_valid_offset(id_type id, 1717 | id_type offset) const { 1718 | if (extras(offset).is_used()) { 1719 | return false; 1720 | } 1721 | id_type rel_offset = id ^ offset; 1722 | if ((rel_offset & LOWER_MASK) && (rel_offset & UPPER_MASK)) { 1723 | return false; 1724 | } 1725 | for (std::size_t i = 1; i < labels_.size(); ++i) { 1726 | if (extras(offset ^ labels_[i]).is_fixed()) { 1727 | return false; 1728 | } 1729 | } 1730 | return true; 1731 | } 1732 | 1733 | inline void DoubleArrayBuilder::reserve_id(id_type id) { 1734 | if (id >= units_.size()) { 1735 | expand_units(); 1736 | } 1737 | if (id == extras_head_) { 1738 | extras_head_ = extras(id).next(); 1739 | if (extras_head_ == id) { 1740 | extras_head_ = units_.size(); 1741 | } 1742 | } 1743 | extras(extras(id).prev()).set_next(extras(id).next()); 1744 | extras(extras(id).next()).set_prev(extras(id).prev()); 1745 | extras(id).set_is_fixed(true); 1746 | } 1747 | 1748 | inline void DoubleArrayBuilder::expand_units() { 1749 | id_type src_num_units = units_.size(); 1750 | id_type src_num_blocks = num_blocks(); 1751 | id_type dest_num_units = src_num_units + BLOCK_SIZE; 1752 | id_type dest_num_blocks = src_num_blocks + 1; 1753 | if (dest_num_blocks > NUM_EXTRA_BLOCKS) { 1754 | fix_block(src_num_blocks - NUM_EXTRA_BLOCKS); 1755 | } 1756 | units_.resize(dest_num_units); 1757 | if (dest_num_blocks > NUM_EXTRA_BLOCKS) { 1758 | for (std::size_t id = src_num_units; id < dest_num_units; ++id) { 1759 | extras(id).set_is_used(false); 1760 | extras(id).set_is_fixed(false); 1761 | } 1762 | } 1763 | for (id_type i = src_num_units + 1; i < dest_num_units; ++i) { 1764 | extras(i - 1).set_next(i); 1765 | extras(i).set_prev(i - 1); 1766 | } 1767 | extras(src_num_units).set_prev(dest_num_units - 1); 1768 | extras(dest_num_units - 1).set_next(src_num_units); 1769 | extras(src_num_units).set_prev(extras(extras_head_).prev()); 1770 | extras(dest_num_units - 1).set_next(extras_head_); 1771 | extras(extras(extras_head_).prev()).set_next(src_num_units); 1772 | extras(extras_head_).set_prev(dest_num_units - 1); 1773 | } 1774 | 1775 | inline void DoubleArrayBuilder::fix_all_blocks() { 1776 | id_type begin = 0; 1777 | if (num_blocks() > NUM_EXTRA_BLOCKS) { 1778 | begin = num_blocks() - NUM_EXTRA_BLOCKS; 1779 | } 1780 | id_type end = num_blocks(); 1781 | for (id_type block_id = begin; block_id != end; ++block_id) { 1782 | fix_block(block_id); 1783 | } 1784 | } 1785 | 1786 | inline void DoubleArrayBuilder::fix_block(id_type block_id) { 1787 | id_type begin = block_id * BLOCK_SIZE; 1788 | id_type end = begin + BLOCK_SIZE; 1789 | id_type unused_offset = 0; 1790 | for (id_type offset = begin; offset != end; ++offset) { 1791 | if (!extras(offset).is_used()) { 1792 | unused_offset = offset; 1793 | break; 1794 | } 1795 | } 1796 | for (id_type id = begin; id != end; ++id) { 1797 | if (!extras(id).is_fixed()) { 1798 | reserve_id(id); 1799 | units_[id].set_label(static_cast(id ^ unused_offset)); 1800 | } 1801 | } 1802 | } 1803 | 1804 | } // namespace Details 1805 | 1806 | // 1807 | // Member function build() of DoubleArrayImpl. 1808 | // 1809 | 1810 | template 1811 | int DoubleArrayImpl::build(std::size_t num_keys, 1812 | const key_type *const *keys, const std::size_t *lengths, 1813 | const value_type *values, Details::progress_func_type progress_func) { 1814 | Details::Keyset keyset(num_keys, keys, lengths, values); 1815 | Details::DoubleArrayBuilder builder(progress_func); 1816 | builder.build(keyset); 1817 | std::size_t size = 0; 1818 | unit_type *buf = NULL; 1819 | builder.copy(&size, &buf); 1820 | clear(); 1821 | size_ = size; 1822 | array_ = buf; 1823 | buf_ = buf; 1824 | if (progress_func != NULL) { 1825 | progress_func(num_keys + 1, num_keys + 1); 1826 | } 1827 | return 0; 1828 | } 1829 | 1830 | } // namespace Darts 1831 | 1832 | #undef DARTS_INT_TO_STR 1833 | #undef DARTS_LINE_TO_STR 1834 | #undef DARTS_LINE_STR 1835 | #undef DARTS_THROW 1836 | 1837 | #endif // DARTS_H_ 1838 | --------------------------------------------------------------------------------