forked from fizx/libbow-osx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rainbow.c
2431 lines (2155 loc) · 75 KB
/
rainbow.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* rainbow - a document classification front-end to libbow. */
/* Copyright (C) 1997, 1998, 1999, 2000 Andrew McCallum
Written by: Andrew Kachites McCallum <[email protected]>
This file is part of the Bag-Of-Words Library, `libbow'.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License
as published by the Free Software Foundation, version 2.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA */
#include <bow/libbow.h>
#include <argp.h>
#include <argp/argp1.h> /* drapp-2/11 */
#include <setjmp.h> /* drapp-2/11 */
#include <errno.h> /* needed on DEC Alpha's */
#include <unistd.h> /* for getopt(), maybe */
#include <stdlib.h> /* for atoi() */
#include <string.h> /* for strrchr() */
#include <strings.h> /* for bzero() on Solaris */
#include <sys/types.h>
#include <sys/socket.h>
#ifndef WINNT
#include <sys/un.h>
#endif /* WINNT */
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
static int rainbow_sockfd;
/* The version number of this program. */
#define RAINBOW_MAJOR_VERSION 0
#define RAINBOW_MINOR_VERSION 2
#define rainbow_default_method (&bow_method_naivebayes)
/* Definitions for using argp command-line processing */
const char *argp_program_version =
"rainbow "
STRINGIFY(RAINBOW_MAJOR_VERSION) "." STRINGIFY(RAINBOW_MINOR_VERSION);
const char *argp_program_bug_address = "<[email protected]>";
static char rainbow_argp_doc[] =
"Rainbow -- a document classification front-end to libbow";
static char rainbow_argp_args_doc[] = "[ARG...]";
enum {
PRINT_COUNTS_FOR_WORD_KEY = 10000,
INFOGAIN_PAIR_VECTOR_KEY,
USE_VOCAB_IN_FILE_KEY,
NO_LISP_SCORE_TRUNCATION_KEY,
SERVER_KEY,
FORKING_SERVER_KEY,
PRINT_DOC_NAMES_KEY,
PRINT_LOG_ODDS_RATIO_KEY,
WORD_PROBABILITIES_KEY,
PRINT_WORD_PROBABILITIES_KEY,
INDEX_MATRIX_KEY,
HIDE_VOCAB_IN_FILE_KEY,
HIDE_VOCAB_INDICES_IN_FILE_KEY,
TEST_ON_TRAINING_KEY,
VPC_ONLY_KEY,
BUILD_AND_SAVE,
TEST_FROM_SAVED,
USE_SAVED_CLASSIFIER_KEY,
PRINT_DOC_LENGTH_KEY,
INDEX_LINES_KEY,
};
static struct argp_option rainbow_options[] =
{
{0, 0, 0, 0,
"For building data structures from text files:", 20},
{"index", 'i', 0, 0,
"Tokenize training documents found under directories ARG... "
"(where each ARG directory contains documents of a different class), "
"build token-document matrix, and save it to disk."},
{"index-matrix", INDEX_MATRIX_KEY, "FORMAT", 0,
"Read document/word statistics from a file in the format produced by "
"--print-matrix=FORMAT. See --print-matrix for details about FORMAT."},
{"index-lines", INDEX_LINES_KEY, "FILENAME", 0,
"Read documents' contents from the filename argument, one-per-line. "
"The first two "
"space-delimited words on each line are the document name and class name "
"respectively"},
#if VPC_ONLY
{"vpc-only", VPC_ONLY_KEY, 0, 0,
"Only create a vector-per-class barrel. Do not create a document barrel. "
"Useful for creating barrels to be used with --query-server. "
"NOTE: This is a hack which assumes multinomial and a naive Bayes-like "
"method. Not meant for general purpose usage!"},
#endif
{0, 0, 0, 0,
"For doing document classification using the token-document matrix "
"built with -i:", 21},
{"query", 'q', "FILE", OPTION_ARG_OPTIONAL,
"Tokenize input from stdin [or FILE], then print classification scores."},
{"output-text", 'o', "FILE", OPTION_HIDDEN,
"Intead of outputing the classnames, output the contents of FILE in the "
"data directory of the winning class, (for use as email auto-answer)."},
{"repeat", 'r', 0, 0,
"Prompt for repeated queries."},
{"query-server", SERVER_KEY, "PORTNUM", 0,
"Run rainbow in server mode, listening on socket number PORTNUM. "
"You can try it by executing this command, then in a different shell "
"window on the same machine typing `telnet localhost PORTNUM'."},
{"forking-query-server", FORKING_SERVER_KEY, "PORTNUM", 0,
"Same as `--query-server', except allow multiple clients at once by "
"forking for each client."},
{"print-doc-length", PRINT_DOC_LENGTH_KEY, 0, 0,
"When printing the classification scores for each test document, at the "
"end also print the number of words in the document. This only works "
"with the --test option."},
{0, 0, 0, 0,
"Rainbow-specific vocabulary options:", 22},
{"use-vocab-in-file", USE_VOCAB_IN_FILE_KEY, "FILE", 0,
"Limit vocabulary to just those words read as space-separated strings "
"from FILE. Note that regular lexing is not done on these strings."},
{"hide-vocab-in-file", HIDE_VOCAB_IN_FILE_KEY, "FILE", 0,
"Hide from the vocabulary all words read as space-separated strings "
"from FILE. Note that regular lexing is not done on these strings."},
{"hide-vocab-indices-in-file", HIDE_VOCAB_INDICES_IN_FILE_KEY, "FILE", 0,
"Hide from the vocabulary all words read as space-separated word "
"integer indices from FILE."},
{0, 0, 0, 0,
"Testing documents that were indexed with `-i':", 23},
{"test", 't', "N", 0,
"Perform N test/train splits of the indexed documents, and output "
"classifications of all test documents each time. The parameters of "
"the test/train splits are determined by the option `--test-set' "
"and its siblings"},
{"test-on-training", TEST_ON_TRAINING_KEY, "N", 0,
"Like `--test', but instead of classifing the held-out test documents "
"classify the training data in leave-one-out fashion. Perform N trials."},
#if 0
{"no-lisp-score-truncation", NO_LISP_SCORE_TRUNCATION_KEY, 0, 0,
"Normally scores that are lower than 1e-35 are printed as 0, "
"because our LISP reader can't handle floating point numbers smaller "
"than 1e-35. This option turns off that truncation."},
#endif
{0, 0, 0, 0,
"Testing documents that are specified on the command line:", 5},
{"test-files", 'x', 0, 0,
"In same format as `-t', output classifications of documents in "
"the directory ARG The ARG must have the same subdir names as the "
"ARG's specified when --index'ing."},
{"test-files-loo", 'X', 0, 0,
"Same as --test-files, but evaulate the files assuming that they "
"were part of the training data, and doing leave-one-out "
"cross-validation. This only works with the classification methods "
"that support leave-one-out evaluation"},
{0, 0, 0, 0,
"Diagnostics:", 24},
{"print-word-infogain", 'I', "N", 0,
"Print the N words with the highest information gain."},
{"print-word-pair-infogain", INFOGAIN_PAIR_VECTOR_KEY, "N", 0,
"Print the N word-pairs, which when co-occuring in a document, have "
"the highest information gain. (Unfinished; ignores N.)"},
{"print-log-odds-ratio", PRINT_LOG_ODDS_RATIO_KEY, "N", OPTION_ARG_OPTIONAL,
"For each class, print the N words with the highest log odds ratio score. "
"Default is N=10."},
{"print-word-weights", 'W', "CLASSNAME", 0,
"Print the word/weight vector for CLASSNAME, "
"sorted with high weights first. The meaning of `weight' is undefined."},
{"print-word-probabilities", PRINT_WORD_PROBABILITIES_KEY, "CLASS", 0,
"Print P(w|CLASS), the probability in class CLASS "
"of each word in the vocabulary."},
{"print-word-foilgain", 'F', "CLASSNAME", 0,
"Print the word/foilgain vector for CLASSNAME. See Mitchell's "
"Machine Learning textbook for a description of foilgain."},
{"print-matrix", 'B', "FORMAT", OPTION_ARG_OPTIONAL,
"Print the word/document count matrix in an awk- or perl-accessible "
"format. Format is specified by the following letters:\n"
"print all vocab or just words in document:\n"
" a=all OR s=sparse\n"
"print counts as ints or binary:\n"
" b=binary OR i=integer\n"
"print word as:\n "
" n=integer index OR w=string OR e=empty OR c=combination\n"
"The default is the last in each list"},
{"print-barrel", 'B', "FORMAT",
OPTION_ARG_OPTIONAL | OPTION_ALIAS | OPTION_HIDDEN},
{"print-word-counts", PRINT_COUNTS_FOR_WORD_KEY, "WORD", 0,
"Print the number of times WORD occurs in each class."},
{"print-counts-for-word", PRINT_COUNTS_FOR_WORD_KEY, "WORD",
OPTION_ALIAS | OPTION_HIDDEN},
{"print-doc-names", PRINT_DOC_NAMES_KEY, "TAG", OPTION_ARG_OPTIONAL,
"Print the filenames of documents contained in the model. "
"If the optional TAG argument is given, print only the documents "
"that have the specified tag, where TAG might be `train', `test', etc."},
{"build-and-save", BUILD_AND_SAVE, 0, 0,
"Builds a class model and saves it to disk. This option is unstable."},
{"test-from-saved", TEST_FROM_SAVED, 0, 0,
"Classify using the class model saved to disk. This option is unstable."},
{"use-saved-classifier", USE_SAVED_CLASSIFIER_KEY, 0, 0,
"Don't ever re-train the classifier. Use whatever class barrel was saved "
"to disk. This option designed for use with --query-server"},
{ 0 }
};
struct rainbow_arg_state
{
/* Is this invocation of rainbow to do indexing or querying? */
enum {
rainbow_indexing,
rainbow_querying,
rainbow_query_serving,
rainbow_testing, /* many queries, from train/test split */
rainbow_file_testing, /* many queries, from a directory */
rainbow_infogain_printing,
rainbow_infogain_pair_printing,
rainbow_logodds_printing,
rainbow_weight_vector_printing,
rainbow_foilgain_printing,
rainbow_barrel_printing,
rainbow_word_count_printing,
rainbow_doc_name_printing,
rainbow_printing_word_probabilities,
rainbow_building_and_saving,
rainbow_testing_from_saved_model,
rainbow_indexing_lines
} what_doing;
/* Where to find query text, or if NULL get query text from stdin */
const char *query_filename;
/* Name of file to find in each class directory; output the contents
of this file instead of the classname. */
const char *output_filename;
/* If we are doing test, how many test are we doing? */
int num_trials;
/* If we are printing info gain stats, how many of the top words? */
int infogain_words_to_print;
/* If we are printing log odds ratio stats, how many of the top words? */
int logodds_words_to_print;
/* Used for selecting the class for which the weight-vector will be
printed. */
const char *printing_class;
/* Index into argv of the non-option args at the end (i.e. for -i
classnames or -x filenames, etc). */
int non_option_argi;
int repeat_query;
bow_int4str *vocab_map;
bow_int4str *hide_vocab_map;
int use_lisp_score_truncation;
int loo_cv;
const char *server_port_num;
const char *barrel_printing_format;
const char *hide_vocab_indices_filename;
int test_on_training;
int use_saved_classifier;
int forking_server;
#if VPC_ONLY
/* Set if we only want to build a class barrel */
int vpc_only;
#endif
int print_doc_length;
const char *indexing_lines_filename;
} rainbow_arg_state;
static error_t
rainbow_parse_opt (int key, char *arg, struct argp_state *state)
{
switch (key)
{
case 'q':
rainbow_arg_state.what_doing = rainbow_querying;
rainbow_arg_state.query_filename = arg;
break;
case FORKING_SERVER_KEY:
rainbow_arg_state.forking_server = 1;
case SERVER_KEY:
rainbow_arg_state.what_doing = rainbow_query_serving;
rainbow_arg_state.server_port_num = arg;
bow_lexer_document_end_pattern = "\n.\r\n";
break;
case 'i':
rainbow_arg_state.what_doing = rainbow_indexing;
break;
case INDEX_MATRIX_KEY:
rainbow_arg_state.what_doing = rainbow_indexing;
rainbow_arg_state.barrel_printing_format = arg;
break;
#if VPC_ONLY
case VPC_ONLY_KEY:
rainbow_arg_state.vpc_only = 1;
break;
#endif
case INDEX_LINES_KEY:
rainbow_arg_state.what_doing = rainbow_indexing_lines;
rainbow_arg_state.indexing_lines_filename = arg;
break;
case 'r':
rainbow_arg_state.repeat_query = 1;
break;
case USE_VOCAB_IN_FILE_KEY:
rainbow_arg_state.vocab_map = bow_int4str_new_from_string_file (arg);
bow_verbosify (bow_progress,
"Using vocab with %d words from file `%s'\n",
rainbow_arg_state.vocab_map->str_array_length, arg);
bow_word2int_do_not_add = 1;
break;
case HIDE_VOCAB_IN_FILE_KEY:
rainbow_arg_state.hide_vocab_map = bow_int4str_new_from_string_file(arg);
break;
case HIDE_VOCAB_INDICES_IN_FILE_KEY:
rainbow_arg_state.hide_vocab_indices_filename = arg;
break;
/* Switches for testing */
case 't':
rainbow_arg_state.what_doing = rainbow_testing;
rainbow_arg_state.num_trials = atoi (arg);
break;
case TEST_ON_TRAINING_KEY:
rainbow_arg_state.what_doing = rainbow_testing;
rainbow_arg_state.test_on_training = 1;
rainbow_arg_state.num_trials = atoi (arg);
break;
case NO_LISP_SCORE_TRUNCATION_KEY:
rainbow_arg_state.use_lisp_score_truncation = 0;
break;
/* Switches for file testing */
case 'X':
rainbow_arg_state.loo_cv = 1;
case 'x':
rainbow_arg_state.what_doing = rainbow_file_testing;
break;
/* Switches for diagnostics */
case 'I':
/* Print out ARG number of vocab words ranked by infogain. */
rainbow_arg_state.what_doing = rainbow_infogain_printing;
rainbow_arg_state.infogain_words_to_print = atoi (arg);
break;
case PRINT_LOG_ODDS_RATIO_KEY:
/* Print out ARG number of vocab words ranked by infogain. */
rainbow_arg_state.what_doing = rainbow_logodds_printing;
if (arg)
rainbow_arg_state.logodds_words_to_print = atoi (arg);
break;
case 'W':
/* Print the weight-vector for the named class */
rainbow_arg_state.what_doing = rainbow_weight_vector_printing;
rainbow_arg_state.printing_class = arg;
break;
case 'F':
/* Print the foil gain for the named class */
rainbow_arg_state.what_doing = rainbow_foilgain_printing;
rainbow_arg_state.printing_class = arg;
break;
case 'P':
/* Print the contribution of each word to each class during
scoring. */
bow_print_word_scores = 1;
break;
case 'B':
/* Print the barrel in awk-accessible form to stdout. */
rainbow_arg_state.what_doing = rainbow_barrel_printing;
rainbow_arg_state.barrel_printing_format = arg;
break;
case PRINT_COUNTS_FOR_WORD_KEY:
rainbow_arg_state.what_doing = rainbow_word_count_printing;
rainbow_arg_state.printing_class = arg;
break;
case INFOGAIN_PAIR_VECTOR_KEY:
rainbow_arg_state.what_doing = rainbow_infogain_pair_printing;
rainbow_arg_state.infogain_words_to_print = atoi (arg);
break;
case PRINT_DOC_NAMES_KEY:
rainbow_arg_state.what_doing = rainbow_doc_name_printing;
rainbow_arg_state.printing_class = arg;
break;
case PRINT_WORD_PROBABILITIES_KEY:
rainbow_arg_state.what_doing = rainbow_printing_word_probabilities;
rainbow_arg_state.printing_class = arg;
break;
#if 0
case ARGP_KEY_NO_ARGS:
argp_usage (state);
#endif
case ARGP_KEY_ARG:
/* Now we consume all the rest of the arguments. STATE->next is the
index in STATE->argv of the next argument to be parsed, which is the
first STRING we're interested in, so we can just use
`&state->argv[state->next]' as the value for RAINBOW_ARG_STATE->ARGS.
IN ADDITION, by setting STATE->next to the end of the arguments, we
can force argp to stop parsing here and return. */
rainbow_arg_state.non_option_argi = state->next - 1;
if (rainbow_arg_state.what_doing == rainbow_indexing
&& rainbow_arg_state.barrel_printing_format == NULL
&& state->next == state->argc)
{
/* Only one classname is not enough. */
fprintf (stderr, "Need data from more than one class.\n");
argp_usage (state);
}
state->next = state->argc;
break;
case ARGP_KEY_END:
/* Here we know that STATE->arg_num == 0, since we force argument
parsing to end before any more arguments can get here. */
if (rainbow_arg_state.what_doing == rainbow_indexing
|| rainbow_arg_state.what_doing == rainbow_file_testing)
{
if (state->arg_num == 0)
{
/* Too few arguments. */
fprintf (stderr, "No non-option arguments needed.\n");
argp_usage (state);
}
}
else if (state->arg_num != 0)
{
/* Too many arguments. */
fprintf (stderr, "No non-option arguments needed.\n");
argp_usage (state);
}
break;
case BUILD_AND_SAVE:
rainbow_arg_state.what_doing = rainbow_building_and_saving;
break;
case TEST_FROM_SAVED:
rainbow_arg_state.what_doing = rainbow_testing_from_saved_model;
break;
case USE_SAVED_CLASSIFIER_KEY:
rainbow_arg_state.use_saved_classifier = 1;
break;
case PRINT_DOC_LENGTH_KEY:
rainbow_arg_state.print_doc_length = 1;
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static struct argp rainbow_argp =
{ rainbow_options, rainbow_parse_opt, rainbow_argp_args_doc,
rainbow_argp_doc, bow_argp_children};
/* The structures that hold the data necessary for answering a query. */
bow_barrel *rainbow_doc_barrel; /* the stats about words and documents */
bow_barrel *rainbow_class_barrel=NULL; /* the stats about words and classes */
/* The static structure in bow/int4word.c is also used. */
/* Given a fully-specified file path name (all the way from `/'),
return just the last filename part of it. */
static inline const char *
filename_to_classname (const char *filename)
{
#if 0
/* Don't bother stripping off the directory name from the classname.
This way, even when we give rainbow multi-directory
specifications for where to find the data for each class, and
some of the lowest-level directories have the same name, we can
still distinguish between them. */
return filename;
#else
const char *ret;
ret = strrchr (filename, '/');
if (ret)
return ret + 1;
return filename;
#endif
}
/* Writing and reading the word/document stats to disk. */
#define VOCABULARY_FILENAME "vocabulary"
#define DOC_BARREL_FILENAME "doc-barrel"
#define CLASS_BARREL_FILENAME "class-barrel"
#define OUTPUTNAME_FILENAME "outfile"
#define FORMAT_VERSION_FILENAME "format-version"
/* Write the stats in the directory DATA_DIRNAME. */
void
rainbow_archive ()
{
char filename[BOW_MAX_WORD_LENGTH];
char *fnp;
FILE *fp;
strcpy (filename, bow_data_dirname);
strcat (filename, "/");
fnp = filename + strlen (filename);
strcpy (fnp, FORMAT_VERSION_FILENAME);
bow_write_format_version_to_file (filename);
strcpy (fnp, OUTPUTNAME_FILENAME);
fp = bow_fopen (filename, "w");
if (rainbow_arg_state.output_filename)
fprintf (fp, "%s\n", rainbow_arg_state.output_filename);
fclose (fp);
strcpy (fnp, VOCABULARY_FILENAME);
fp = bow_fopen (filename, "wb");
bow_words_write (fp);
fclose (fp);
strcpy (fnp, CLASS_BARREL_FILENAME);
fp = bow_fopen (filename, "wb");
bow_barrel_write (rainbow_class_barrel, fp);
fclose (fp);
strcpy (fnp, DOC_BARREL_FILENAME);
fp = bow_fopen (filename, "wb");
bow_barrel_write (rainbow_doc_barrel, fp);
fclose (fp);
}
/* Read the stats from the directory DATA_DIRNAME. */
void
rainbow_unarchive ()
{
char filename[BOW_MAX_WORD_LENGTH];
char *fnp;
FILE *fp;
char buf[1024];
struct stat st;
int e;
if (rainbow_arg_state.what_doing != rainbow_query_serving)
bow_verbosify (bow_progress, "Loading data files...\n");
strcpy (filename, bow_data_dirname);
strcat (filename, "/");
fnp = filename + strlen (filename);
strcpy (fnp, FORMAT_VERSION_FILENAME);
e = stat (filename, &st);
if (e != 0)
{
/* Assume this means the file doesn't exist, and this archive
was created before BOW_DEFAULT_FORMAT_VERSION was added to
the library. The version number before
BOW_DEFAULT_FORMAT_VERSION was added to the library was 3. */
bow_file_format_version = 3;
}
else
{
bow_read_format_version_from_file (filename);
}
strcpy (fnp, OUTPUTNAME_FILENAME);
fp = fopen (filename, "r");
if (fp)
{
buf[0] = '\0';
fscanf (fp, "%s", buf);
rainbow_arg_state.output_filename = strdup (buf);
fclose (fp);
}
else
{
rainbow_arg_state.output_filename = NULL;
}
strcpy (fnp, VOCABULARY_FILENAME);
fp = bow_fopen (filename, "rb");
bow_words_read_from_fp (fp);
fclose (fp);
strcpy (fnp, CLASS_BARREL_FILENAME);
fp = bow_fopen (filename, "rb");
rainbow_class_barrel = bow_barrel_new_from_data_fp (fp);
/* Don't close it because bow_wi2dvf_dv will still need to read it. */
strcpy (fnp, DOC_BARREL_FILENAME);
fp = bow_fopen (filename, "rb");
rainbow_doc_barrel = bow_barrel_new_from_data_fp (fp);
/* Don't close it because bow_wi2dvf_dv will still need to read it. */
/* Only do this if the document barrel exists */
if (rainbow_doc_barrel && rainbow_doc_barrel->classnames == NULL)
{
int i;
bow_cdoc *cdoc;
rainbow_doc_barrel->classnames = bow_int4str_new (0);
rainbow_class_barrel->classnames = bow_int4str_new (0);
for (i = 0; i < rainbow_class_barrel->cdocs->length; i++)
{
cdoc = bow_array_entry_at_index (rainbow_class_barrel->cdocs, i);
bow_str2int (rainbow_doc_barrel->classnames,
filename_to_classname (cdoc->filename));
bow_str2int (rainbow_class_barrel->classnames,
filename_to_classname (cdoc->filename));
}
}
/* Don't want doc priors set equal - want class priors set equal */
if (bow_uniform_class_priors)
bow_barrel_set_cdoc_priors_to_class_uniform (rainbow_class_barrel);
/*bow_barrel_set_cdoc_priors_to_class_uniform (rainbow_doc_barrel);*/
}
/* Building the word/document stats. */
/* Traverse the directories CLASSDIR_NAMES, gathering word/document
stats, and write the stats to disk in BOW_DATA_DIRNAME. */
void
rainbow_index (int num_classes, const char *classdir_names[],
const char *exception_name)
{
int class_index;
void do_indexing ()
{
if (rainbow_doc_barrel)
bow_free_barrel (rainbow_doc_barrel);
/* Index all the documents. */
rainbow_doc_barrel = bow_barrel_new (0, 0, sizeof (bow_cdoc), NULL);
#if VPC_ONLY
if (rainbow_arg_state.vpc_only)
rainbow_doc_barrel->is_vpc = 1;
#endif VPC_ONLY
if (bow_argp_method)
rainbow_doc_barrel->method = (rainbow_method*)bow_argp_method;
else
rainbow_doc_barrel->method = rainbow_default_method;
for (class_index = 0; class_index < num_classes; class_index++)
{
bow_verbosify (bow_progress, "Class `%s'\n ",
filename_to_classname (classdir_names[class_index]));
#if HAVE_HDB
if (bow_hdb)
{
/* Gathers stats on all documents in HDB database */
if (bow_barrel_add_from_hdb
(rainbow_doc_barrel,
classdir_names[class_index],
exception_name,
filename_to_classname (classdir_names[class_index]))
== 0)
bow_verbosify (bow_quiet,
"No text files found in database `%s'\n",
classdir_names[class_index]);
}
else
#endif
/* This function traverses the class directory
gathering word/document stats. Return the number of
documents indexed. This gathers stats on individual
documents; we have yet to "sum together the word vectors
of all documents for each particular class". */
if (bow_barrel_add_from_text_dir
(rainbow_doc_barrel,
classdir_names[class_index],
exception_name,
filename_to_classname (classdir_names[class_index]))
== 0)
bow_verbosify (bow_quiet,
"No text files found in directory `%s'\n",
classdir_names[class_index]);
}
if (bow_uniform_class_priors)
bow_barrel_set_cdoc_priors_to_class_uniform (rainbow_doc_barrel);
}
/* Do all the parsing to build a barrel with word counts. */
if (bow_prune_vocab_by_occur_count_n)
{
/* Parse all the documents to get word occurrence counts. */
for (class_index = 0; class_index < num_classes; class_index++)
{
bow_verbosify (bow_progress,
"Class `%s'\n ",
filename_to_classname
(classdir_names[class_index]));
#if HAVE_HDB
if (bow_hdb)
bow_words_add_occurrences_from_hdb
(classdir_names[class_index], "");
else
#endif
bow_words_add_occurrences_from_text_dir
(classdir_names[class_index], "");
}
/* xxx This should be (bow_prune_vocab_by_occur_count_n+1) !! */
bow_words_remove_occurrences_less_than
(bow_prune_vocab_by_occur_count_n);
/* Now insist that future calls to bow_word2int*() will not
register new words. */
bow_word2int_do_not_add = 1;
}
do_indexing ();
if (bow_prune_vocab_by_infogain_n
|| bow_prune_words_by_doc_count_n)
{
if (0)
{
/* Change barrel by removing words with small information gain. */
bow_barrel_keep_top_words_by_infogain
(bow_prune_vocab_by_infogain_n, rainbow_doc_barrel, num_classes);
}
else
{
/* Change vocabulary to remove words with small information gain */
bow_wi2dvf_hide_words_by_doc_count (rainbow_doc_barrel->wi2dvf,
bow_prune_words_by_doc_count_n);
/* The doc count pruning must be before the infogain pruning,
because this function below is the one that re-assigns
the word-indices. */
bow_words_keep_top_by_infogain (bow_prune_vocab_by_infogain_n,
rainbow_doc_barrel,
num_classes);
/* Now insist that future calls to bow_word2int*() will not
register new words. */
bow_word2int_do_not_add = 1;
do_indexing ();
}
}
#if VPC_ONLY
/* Weights have been calculated - all that is left to do is to calculate
* priors */
if (rainbow_arg_state.vpc_only)
{
bow_cdoc *cdocp;
double prior_sum = 0.0;
int num_classes = bow_barrel_num_classes (rainbow_doc_barrel);
int ci;
/* Normalize the class priors */
for (ci=0; ci < num_classes; ci++)
{
cdocp = bow_array_entry_at_index (rainbow_doc_barrel->cdocs, ci);
prior_sum += cdocp->prior;
}
if (prior_sum)
for (ci=0; ci < num_classes; ci++)
{
cdocp = bow_array_entry_at_index (rainbow_doc_barrel->cdocs, ci);
cdocp->prior = cdocp->prior / prior_sum;
}
else
bow_verbosify (bow_progress, "WARNING: All classes have zero prior\n");
/* Recalculate word counts for each class */
{
bow_wv *wv = NULL;
int wvi;
bow_cdoc *cdoc;
int di;
bow_dv_heap *heap = bow_test_new_heap (rainbow_doc_barrel);
while ((di = bow_heap_next_wv (heap, rainbow_doc_barrel, &wv,
bow_cdoc_yes)) != -1)
{
cdoc = bow_array_entry_at_index (rainbow_doc_barrel->cdocs, di);
cdoc->word_count = 0;
for (wvi = 0; wvi < wv->num_entries; wvi++)
{
if (bow_wi2dvf_dv (rainbow_doc_barrel->wi2dvf,
wv->entry[wvi].wi))
cdoc->word_count += wv->entry[wvi].count;
}
}
}
/* We have been (secretly) using the doc_barrel as a class barrel
* all along. Set doc_barrel to NULL so that an empty file is
* written to disk. This will keep future executions from
* attempting to recalculate the class_barrel */
rainbow_class_barrel = rainbow_doc_barrel;
rainbow_doc_barrel = NULL;
return;
}
#endif
/* Combine the documents into class statistics. */
rainbow_class_barrel =
bow_barrel_new_vpc_with_weights (rainbow_doc_barrel);
}
void
rainbow_index_printed_barrel (const char *filename)
{
rainbow_doc_barrel =
bow_barrel_new_from_printed_barrel_file
(filename, rainbow_arg_state.barrel_printing_format);
/* Combine the documents into class statistics. */
rainbow_class_barrel =
bow_barrel_new_vpc_with_weights (rainbow_doc_barrel);
}
/* Index each line of ARCHER_ARG_STATE.DIRNAME as if it were a
separate file, named after the line number. Does not deal with labels.*/
void
rainbow_index_lines (const char *filename)
{
static const int max_line_length = 40000;
char *buf;
int n, classindex, nchars;
FILE *fp;
bow_cdoc cdoc;
int di;
char docname[BOW_MAX_WORD_LENGTH];
char classname[BOW_MAX_WORD_LENGTH];
buf = alloca (max_line_length);
rainbow_doc_barrel = bow_barrel_new (0, 0, sizeof (bow_cdoc), NULL);
fp = bow_fopen (filename, "r");
bow_verbosify (bow_progress, "Indexing lines: ");
di = 0;
while (fgets (buf, max_line_length, fp))
{
if (buf[0] == '%')
continue;
n = sscanf (buf, "%s %d %n", docname, &classindex, &nchars);
assert (n >= 2);
if (classindex < 0)
classindex = 0;
sprintf (classname, "class%d", classindex);
if (!(rainbow_doc_barrel->classnames))
rainbow_doc_barrel->classnames = bow_int4str_new (0);
classindex = bow_str2int (rainbow_doc_barrel->classnames, classname);
cdoc.type = bow_doc_train;
cdoc.class = classindex;
/* Set to one so bow_infogain_per_wi_new() works correctly
by default. */
cdoc.prior = 1.0f;
assert (cdoc.class >= 0);
cdoc.filename = strdup (docname);
assert (cdoc.filename);
cdoc.class_probs = NULL;
/* Add the CDOC to CDOCS, and determine the "index" of this
document. */
di = bow_array_append (rainbow_doc_barrel->cdocs, &cdoc);
if (strlen (buf+nchars))
bow_wi2dvf_add_di_text_str (&(rainbow_doc_barrel->wi2dvf), di,
buf+nchars, docname);
di++;
if (di % 100 == 0)
bow_verbosify(bow_progress, "\b\b\b\b\b\b%6d", di);
}
fclose (fp);
bow_verbosify (bow_progress, "\n");
/* Combine the documents into class statistics. */
rainbow_class_barrel =
bow_barrel_new_vpc_with_weights (rainbow_doc_barrel);
}
/* Perform a query. */
/* Print the contents of file FILENAME to stdout. */
static inline void
print_file (const char *filename)
{
FILE *fp;
int byte;
if ((fp = fopen (filename, "r")) == NULL)
bow_error ("Couldn't open file `%s' for reading", filename);
while ((byte = fgetc (fp)) != EOF)
fputc (byte, stdout);
fclose (fp);
}
int iBrokenPipe = 0; /* drapp-2/10 */
jmp_buf env; /* drapp-2/10 */
/* Get some query text, and print its best-matching documents among
those previously indexed. The number of matching documents is
NUM_HITS_TO_SHOW. If QUERY_FILENAME is non-null, the query text
will be obtained from that file; otherwise it will be prompted for
and read from stdin. */
int
rainbow_query (FILE *in, FILE *out)
{
/* Show as many hits as there are classes. */
int num_hits_to_show;
bow_score *hits;
int actual_num_hits;
int i;
bow_wv *query_wv = NULL;
num_hits_to_show = bow_barrel_num_classes (rainbow_class_barrel);
hits = alloca (sizeof (bow_score) * num_hits_to_show);
/* Commented out for WhizBang --query-server */
#if 0
/* (Re)set the weight-setting method, if requested with a `-m' on
the command line. */
/* If we don't have the document barrel, we can't do this... */
if (rainbow_doc_barrel)
{
if (bow_argp_method)
rainbow_doc_barrel->method = (rainbow_method*)bow_argp_method;
else
rainbow_doc_barrel->method = rainbow_default_method;
}
if (bow_prune_vocab_by_infogain_n
&& rainbow_doc_barrel)
{
/* Change barrel by removing words with small information gain. */
bow_barrel_keep_top_words_by_infogain
(bow_prune_vocab_by_infogain_n, rainbow_doc_barrel,
bow_barrel_num_classes (rainbow_class_barrel));
}
/* Infogain pruning must be done before this vocab_map pruning, because
infogain pruning first unhides all words! */
if (rainbow_arg_state.vocab_map)
{
if (rainbow_doc_barrel)
/* Remove words not in the VOCAB_MAP. */
bow_barrel_prune_words_not_in_map (rainbow_doc_barrel,
rainbow_arg_state.vocab_map);
if (rainbow_class_barrel)
/* Remove words not in the VOCAB_MAP. */
bow_barrel_prune_words_not_in_map (rainbow_class_barrel,
rainbow_arg_state.vocab_map);
}
if (rainbow_arg_state.hide_vocab_map
&& rainbow_doc_barrel)
{
bow_barrel_prune_words_in_map (rainbow_doc_barrel,
rainbow_arg_state.hide_vocab_map);
}
/* Re-build the rainbow_class_barrel, if necessary */
/* Make sure that we have the document barrel */
if (rainbow_doc_barrel &&
(rainbow_doc_barrel->method != rainbow_class_barrel->method
|| rainbow_arg_state.vocab_map
|| rainbow_arg_state.hide_vocab_map
|| bow_prune_vocab_by_infogain_n))
{
bow_free_barrel (rainbow_class_barrel);
rainbow_class_barrel =
bow_barrel_new_vpc_with_weights (rainbow_doc_barrel);
}
#endif
/* Get the query text, and create a "word vector" from the query text. */
query_again:
if (rainbow_arg_state.query_filename)
{
FILE *fp;
fp = bow_fopen (rainbow_arg_state.query_filename, "r");
query_wv = bow_wv_new_from_text_fp (fp,
rainbow_arg_state.query_filename);
fclose (fp);
}