File: crossbow.c

package info (click to toggle)
bow 19991122-4
  • links: PTS
  • area: main
  • in suites: woody
  • size: 2,544 kB
  • ctags: 2,987
  • sloc: ansic: 38,660; lisp: 1,072; makefile: 594; perl: 492; yacc: 149; sh: 91
file content (1195 lines) | stat: -rw-r--r-- 34,299 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
/* A clustering front-end to libbow. */

/* Copyright (C) 1997, 1998, 1999 Andrew McCallum

   Written by:  Andrew Kachites McCallum <mccallum@cs.cmu.edu>

   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 */

/* Some naming conventions:

   Use x_count; not num_x or x_size.

   func_x_all() is the same as func_x(), except that is iterates over
   all nodes in the tree.

*/

#include <bow/libbow.h>
#include <argp.h>
#include <bow/crossbow.h>

/* For mkdir() and stat() */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

/* For opendir */
#include <dirent.h>

#define SHRINKAGE 1
#define CLASSES_FROM_DIRS 1

extern void crossbow_hem_cluster ();
extern void crossbow_hem_full_em ();
extern void crossbow_hem_fienberg ();
extern int crossbow_hem_deterministic_horizontal;
extern int crossbow_hem_restricted_horizontal;
extern int crossbow_hem_shrinkage;

/* The version number of this program. */
#define CROSSBOW_MAJOR_VERSION 0
#define CROSSBOW_MINOR_VERSION 0




/* Global variables. */

/* The top of the hierarchy */
treenode *crossbow_root;

/* The list of documents */
bow_array *crossbow_docs;

/* A hashtable from doc filenames to document indices */
bow_int4str *crossbow_filename2di;

/* The number of classes in a "supervised" setting */
int crossbow_classes_count;

/* A mapping between classnames and class indices */
bow_int4str *crossbow_classnames;

/* FILE* to file containing WV's of the documents */
FILE *crossbow_wv_fp;

/* Access to the arguments of main() */
int crossbow_argc;
char **crossbow_argv;


struct crossbow_arg_state
{
  /* What this invocation of crossbow to do? */
  void (*what_doing)();
  int non_option_argi;
  const char *server_port_num;
  int serve_with_forking;
  const char *cluster_output_dir;
  int build_hier_from_dir;
  const char *print_file_prefix;
  const char *printing_tag;
  const char *classify_files_dirname;
  const char *multiclass_list_filename;
  bow_int4str *vocab_map;
} crossbow_arg_state;




/* Functions for creating, reading, writing a crossbow_doc */

int
crossbow_doc_write (crossbow_doc *doc, FILE *fp)
{
  int ret;
  int i;

  ret = bow_fwrite_string (doc->filename, fp);
  ret += bow_fwrite_int (doc->tag, fp);
  ret += bow_fwrite_int (doc->word_count, fp);
  ret += bow_fwrite_int (doc->wv_seek_pos, fp);
  ret += bow_fwrite_int (doc->di, fp);
  ret += bow_fwrite_int (doc->ci, fp);
  if (bow_file_format_version >= 7)
    {
      ret += bow_fwrite_int (doc->cis_size, fp);
      for (i = 0; i < doc->cis_size; i++)
	ret += bow_fwrite_int (doc->cis[i], fp);
    }
  return ret;
}

int
crossbow_doc_read (crossbow_doc *doc, FILE *fp)
{
  int ret;
  int tag;
  int i;

  ret = bow_fread_string ((char**)&(doc->filename), fp);
  ret += bow_fread_int (&tag, fp);
  doc->tag = tag;
  ret += bow_fread_int (&(doc->word_count), fp);
  ret += bow_fread_int (&(doc->wv_seek_pos), fp);
  ret += bow_fread_int (&(doc->di), fp);
  ret += bow_fread_int (&(doc->ci), fp);
  if (bow_file_format_version >= 7)
    {
      ret += bow_fread_int (&(doc->cis_size), fp);
      if (doc->cis_size)
	{
	  doc->cis = bow_malloc (doc->cis_size
				 * sizeof (typeof (doc->cis[0])));
	  for (i = 0; i < doc->cis_size; i++)
	    ret += bow_fread_int (&(doc->cis[i]), fp);
	}
      else
	doc->cis = NULL;
    }
  doc->wv = NULL;
  doc->cis_mixture = NULL;
  return ret;
}

void
crossbow_doc_free (crossbow_doc *doc)
{
  if (doc->filename)
    free ((void*)doc->filename);
}





/* Return the WV of the DI'th document */
bow_wv *
crossbow_wv_at_di (int di)
{
  crossbow_doc *doc;
  
  doc = bow_array_entry_at_index (crossbow_docs, di);
  if (!doc->wv)
    {
      fseek (crossbow_wv_fp, doc->wv_seek_pos, SEEK_SET);
      doc->wv = bow_wv_new_from_data_fp (crossbow_wv_fp);
    }
  return doc->wv;
}

/* Load all the document WV's into their DOC's */
void
crossbow_load_doc_wvs ()
{
  int di;
  crossbow_doc *doc;

  fseek (crossbow_wv_fp, 0, SEEK_SET);
  for (di = 0; di < crossbow_docs_count; di++)
    {
      doc = bow_array_entry_at_index (crossbow_docs, di);
      assert (doc->wv == NULL);
      assert (doc->wv_seek_pos == ftell (crossbow_wv_fp));
      doc->wv = bow_wv_new_from_data_fp (crossbow_wv_fp);
    }
}

/* Convert the array of log-probabilities into a normalized array of
   probabilities. */
void
crossbow_convert_log_probs_to_probs (double *log_probs, int num_entries)
{
  double max_log_prob;
  int i;
  double normalizer;
  
  /* Renormalize by adding a constant to the LOG_PROBS */
  max_log_prob = -DBL_MAX;
  for (i = 0; i < num_entries; i++)
    {
      assert (log_probs[i] <= 0);
      if (log_probs[i] > max_log_prob)
	max_log_prob = log_probs[i];
    }
  assert (max_log_prob != -DBL_MAX);
  for (i = 0; i < num_entries; i++)
    log_probs[i] -= max_log_prob;

  /* Exponentiate the log_probs to get probabilities, and renormalize
     by dividing by their sum. */
  normalizer = 0;
  for (i = 0; i < num_entries; i++)
    {
      log_probs[i] = exp (log_probs[i]);
      normalizer += log_probs[i];
    }
  for (i = 0; i < num_entries; i++)
    {
      log_probs[i] /= normalizer;
      assert (log_probs[i] >= 0);
      assert (log_probs[i] <= 1);
    }
}

/* Print the filenames of the documents that are most probable in each
   leaf. */
void
crossbow_leaf_document_probs_print (int num_to_print)
{
  int num_leaves;
  treenode *iterator, *leaf;
  double *leaf_membership;
  int li, di, i;
  bow_wa **was;			/* being used with di's instead of wi's */
  bow_wv *wv;
  crossbow_doc *doc;

  num_leaves = bow_treenode_leaf_count (crossbow_root);
  leaf_membership = alloca (num_leaves * sizeof (double));
  was = alloca (num_leaves * sizeof (void*));
  for (li = 0; li < num_leaves; li++)
    was[li] = bow_wa_new (crossbow_root->words_capacity+2);

  for (di = 0; di < crossbow_docs->length; di++)
    {
      wv = crossbow_wv_at_di (di);
      for (iterator = crossbow_root, li = 0;
	   (leaf = bow_treenode_iterate_leaves (&iterator)); 
	   li++)
	{
	  leaf_membership[li] = (log (leaf->prior)
				 + bow_treenode_log_prob_of_wv (leaf, wv));
	  leaf_membership[li] /= bow_wv_word_count (wv);
	  //leaf_membership[li] = 1.0 / leaf_membership[li];
	}
      //crossbow_convert_log_probs_to_probs (leaf_membership, num_leaves);
      for (li = 0; li < num_leaves; li++)
	bow_wa_append (was[li], di, leaf_membership[li]);
    }
  for (iterator = crossbow_root, li = 0;
       (leaf = bow_treenode_iterate_leaves (&iterator)); 
       li++)
    {
      bow_wa_sort (was[li]);
      fprintf (stdout, "%s\n", leaf->name);
      for (i = 0; i < num_to_print; i++)
	{
	  char buf[1024];
	  doc = bow_array_entry_at_index (crossbow_docs, was[li]->entry[i].wi);
	  fprintf (stdout, "%20.10f %s\n",
		   was[li]->entry[i].weight,
		   strrchr (doc->filename, '/') + 1);
	  //fflush (stdout);
	  sprintf (buf, "/net/server1/cora/bin/spit-info %s", doc->filename);
	  assert (strlen (buf) < 1024);
	  //system (buf);
	}
    }

  /* Free the WAS */
  for (li = 0; li < num_leaves; li++)
    bow_wa_free (was[li]);

}



/* Write CROSSBOW_ROOT to disk in directory DIRNAME */
void 
crossbow_archive (const char *dirname)
{
  FILE *fp;
  char buf[1024];
#if 0
  struct stat st;
  int e;

  /* Create the data directory, if it doesn't exist already. */
  e = stat (crossbow_arg_state.cluster_output_dir, &st);
  if (e == 0)
    {
      /* Assume this means the file exists. */
      if (!S_ISDIR (st.st_mode))
	bow_error ("`%s' already exists, but is not a directory");
    }
  else
    {
      if (mkdir (crossbow_arg_state.cluster_output_dir, 0777) == 0)
	bow_verbosify (bow_quiet, "Created directory `%s'.\n", 
		       dirname);
      else if (errno != EEXIST)
	bow_error ("Couldn't create default data directory `%s'",
		   dirname);
    }
#endif
      
  /* Write archive file format version */
  sprintf (buf, "%s/version", dirname);
  bow_write_format_version_to_file (buf);

  /* Write the tree */
  sprintf (buf, "%s/tree", dirname);
  fp = bow_fopen (buf, "wb");
  bow_treenode_write (crossbow_root, fp);
  fclose (fp);

  /* Write the list of info about documents */
  sprintf (buf, "%s/docs", dirname);
  fp = bow_fopen (buf, "wb");
  bow_array_write (crossbow_docs, (int(*)(void*,FILE*))crossbow_doc_write, fp);
  fclose (fp);

  /* Write the classnames map. */
  sprintf (buf, "%s/classnames", dirname);
  fp = bow_fopen (buf, "w");
  bow_int4str_write (crossbow_classnames, fp);
  fclose (fp);

  /* Write the vocabulary */
  sprintf (buf, "%s/vocabulary", dirname);
  fp = bow_fopen (buf, "wb");
  bow_words_write (fp);
  fclose (fp);

  /* Write the map from doc filenames to document indices */
  sprintf (buf, "%s/filename2di", dirname);
  fp = bow_fopen (buf, "w");
  bow_int4str_write (crossbow_filename2di, fp);
  fclose (fp);

  /* Write the CROSSBOW_CLASSES_COUNT */
  sprintf (buf, "%s/classes-count", dirname);
  fp = bow_fopen (buf, "wb");
  bow_fwrite_int (crossbow_classes_count, fp);
  fclose (fp);
}

/* Read CROSSBOW_ROOT from disk in directory DIRNAME */
void
crossbow_unarchive (const char *dirname)
{
  FILE *fp;
  char buf[1024];
  int di;
  crossbow_doc *doc;

  /* Read the archive file format version */
  sprintf (buf, "%s/version", dirname);
  bow_read_format_version_from_file (buf);

  /* Read the hierarchy */
  sprintf (buf, "%s/tree", dirname);
  fp = bow_fopen (buf, "rb");
  crossbow_root = bow_treenode_new_from_fp (fp);
  fclose (fp);

  /* Read the list of info about documents */
  sprintf (buf, "%s/docs", dirname);
  fp = bow_fopen (buf, "rb");
  crossbow_docs = 
    bow_array_new_with_entry_size_from_data_fp
    (sizeof (crossbow_doc), 
     (int(*)(void*,FILE*))crossbow_doc_read,
     crossbow_doc_free, fp);
  fclose (fp);

  /* Read the classnames map */
  sprintf (buf, "%s/classnames", dirname);
  fp = bow_fopen (buf, "r");
  crossbow_classnames = bow_int4str_new_from_fp (fp);
  fclose (fp);

  /* Read the vocabulary */
  sprintf (buf, "%s/vocabulary", dirname);
  fp = bow_fopen (buf, "rb");
  bow_words_read_from_fp (fp);
  fclose (fp);

  /* Read the mapping from doc filenames to document indices */
  sprintf (buf, "%s/filename2di", dirname);
  fp = bow_fopen (buf, "r");
  crossbow_filename2di = bow_int4str_new_from_fp (fp);
  fclose (fp);

  /* Open the document FP so it is ready for later reading. */
  sprintf (buf, "%s/wvs", dirname);
  crossbow_wv_fp = bow_fopen (buf, "rb");

  /* Load all the WV's of the documents into memory. */
  crossbow_load_doc_wvs ();

  /* Initialize CROSSBOW_CLASSES_COUNT. */
  if (bow_file_format_version >= 7)
    {
      sprintf (buf, "%s/classes-count", dirname);
      fp = bow_fopen (buf, "rb");
      bow_fread_int (&crossbow_classes_count, fp);
      fclose (fp);
    }
  else
    {
      crossbow_classes_count = 0;
      /* Step through all the documents, and record the largest class index */
      for (di = 0; di < crossbow_docs->length; di++)
	{
	  doc = bow_array_entry_at_index (crossbow_docs, di);
	  if (doc->ci + 1 > crossbow_classes_count)
	    crossbow_classes_count = doc->ci + 1;
	}
    }
}


treenode *
crossbow_new_root_from_dir (const char *dirname0, treenode *parent)
{
  DIR *dir;
  struct dirent *dirent_p;
  struct stat st;
  char dirname[PATH_MAX];
  char child_dirname[PATH_MAX];
  treenode *ret;
  const char *basename;
  int i;

  /* Make DIRNAME be a copy of DIRNAME0, but without any trailing / */
  strcpy (dirname, dirname0);
  i = strlen (dirname);
  if (dirname[i-1] == '/')
    dirname[i-1] = '\0';

  if ((basename = strrchr (dirname, '/')))
    basename++;
  else
    basename = dirname;

  if (parent)
    bow_verbosify (bow_progress, "Building tree for %s%s\n", 
		   parent->name, basename);
  else
    bow_verbosify (bow_progress, "Building root for %s\n", 
		   basename);

  ret = bow_treenode_new (parent, 8, basename);

  if (!(dir = opendir (dirname)))
    bow_error ("Couldn't open directory `%s'", dirname);
  while ((dirent_p = readdir (dir)))
    {
      sprintf (child_dirname, "%s/%s", dirname, dirent_p->d_name);
      stat (child_dirname, &st);
      if (S_ISDIR (st.st_mode)
	  && strcmp (dirent_p->d_name, ".")
	  && strcmp (dirent_p->d_name, ".."))
	{
	  /* This directory entry is a subdirectory.  Recursively 
	     descend into it and append its files also. */
	  crossbow_new_root_from_dir (child_dirname, ret);
	}
      else if (S_ISREG (st.st_mode))
	{
	  bow_verbosify (bow_verbose,
			 "Ignoring file in hier non-leaf `%s'\n",
			 dirent_p->d_name);
	}
    }
  closedir (dir);

  return ret;
}


/* Forward declare this function */
void crossbow_index_multiclass_list ();

static int text_file_count;

/* CONTEXT points to the class index CI */
int crossbow_index_filename (const char *filename, void *context)
{
  FILE *fp;
  bow_wv *wv;
  crossbow_doc doc;
  int i;
  char dir[1024];
  char *last_slash;
      
  fp = fopen (filename, "r");
  if (fp == NULL)
    {
      perror ("crossbow_index_filename");
      fprintf (stderr, "Couldn't open `%s' for reading\n", filename);
      return 0;
    }

  if (bow_fp_is_text (fp))
    {
      text_file_count++;
      wv = bow_wv_new_from_text_fp (fp, filename);
      if (wv)
	{
	  /* Create and add an entry for the doc-info array */
	  doc.filename = strdup (filename);
	  assert (doc.filename);
	  doc.tag = bow_doc_train;
	  doc.word_count = bow_wv_word_count (wv);
	  doc.wv_seek_pos = ftell (crossbow_wv_fp);
	  doc.di = bow_array_next_index (crossbow_docs);
	  /* Make DIR be the directory portion of FILENAME.
	     It will be used as a classname. */
	  strcpy (dir, filename);
	  last_slash = strrchr (dir, '/');
	  *last_slash = '\0';
	  if (crossbow_arg_state.what_doing == crossbow_index_multiclass_list)
	    {
	      doc.ci = -1;
	    }
	  else
	    {
#if CLASSES_FROM_DIRS
	    doc.ci = bow_str2int (crossbow_classnames, dir);
#else
	    doc.ci = *(int*)context;
#endif
	    }
	  doc.cis_size = 0;
	  doc.cis = NULL;
	  i = bow_array_append (crossbow_docs, &doc);
	  assert (i == doc.di);
	  i = bow_str2int (crossbow_filename2di, filename);
	  assert (i == doc.di);
	  /* Write the WV to disk. */
	  bow_wv_write (wv, crossbow_wv_fp);
	}
      else
	bow_verbosify (bow_progress, "Empty WV in file `%s'\n", filename);
      bow_wv_free (wv);
    }
  fclose (fp);
  bow_verbosify (bow_progress,
		 "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b"
		 "%6d : %6d", 
		 text_file_count, bow_num_words ());
  return 1;
}

void
crossbow_index_multiclass_list ()
{
  FILE *listfp;
  char fn[BOW_MAX_WORD_LENGTH];
  char line[BOW_MAX_WORD_LENGTH];
  char *lineptr;
  char *classptr, *fileptr;
  crossbow_doc *doc;
  int ci, cisi;
  treenode *tn;

  bow_random_set_seed ();
  listfp = bow_fopen (crossbow_arg_state.multiclass_list_filename, "r");

  /* Create some empty recepticals */
  assert (crossbow_docs == NULL);
  crossbow_docs = bow_array_new (0, sizeof (crossbow_doc), crossbow_doc_free);
  crossbow_filename2di = bow_int4str_new (0);
  crossbow_classnames = bow_int4str_new (0);

  /* Create a root */
  crossbow_root = bow_treenode_new_root (10);

  /* Open the file to which we will write the WV's for each indexed file. */
  sprintf (fn, "%s/wvs", bow_data_dirname);
  crossbow_wv_fp = bow_fopen (fn, "wb");

  /* If we are pruning the vocabulary by occurrence count, then read
     all the documents to get the word counts, and limit the
     vocabulary appropriately. */
  if (bow_prune_vocab_by_occur_count_n)
    {
      bow_verbosify (bow_progress, "Scanning files to remove words "
		     "occurring less than %d times...", 
		     bow_prune_vocab_by_occur_count_n);
      while (fgets (line, BOW_MAX_WORD_LENGTH, listfp)) 
	{
	  /* Skip empty lines (LINE[] includes the newline. */
	  if (strlen (line) <= 1) 
	    continue;
	  assert (strlen (line) < BOW_MAX_WORD_LENGTH-1);
	  lineptr = line;
	  fileptr = strsep (&lineptr, " \t\n\r");
	  assert (fileptr);
	  bow_words_add_occurrences_from_file (fileptr);
	}
      /* Rewind the file back to the beginning so we can read it again. */
      fseek (listfp, 0, SEEK_SET);
      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;
      bow_verbosify (bow_progress, "Done.\n");
    }

  /* From all the lines, read the filenames, one per line, until
     there are no more left. */
  while (fgets (line, BOW_MAX_WORD_LENGTH, listfp)) 
    {
      /* Skip empty lines (LINE[] includes the newline. */
      if (strlen (line) <= 1) 
	continue;
      assert (strlen (line) < BOW_MAX_WORD_LENGTH-1);
      lineptr = line;
      fileptr = strsep (&lineptr, " \t\n\r");
      assert (fileptr);
      crossbow_index_filename (fileptr, NULL);
      /* Get the DOC just created by CROSSBOW_INDEX_FILENAME */
      doc = bow_array_entry_at_index (crossbow_docs, crossbow_docs->length-1);
      /* Grab all the classnames, and set their CLASSPROBS to non-zero */
      while ((classptr = strsep (&lineptr, " \t\n\r")))
	{
	  if (strlen (classptr) == 0)
	    continue;
	  /* No good reason, just a silly check: */
	  assert (strlen (classptr) > 2);
	  if (bow_str2int_no_add (crossbow_classnames, classptr) == -1)
	    {
	      /* This class hasn't been seen before; create a node for it */
	      tn = bow_treenode_new (crossbow_root, 2, classptr);
	      ci = bow_str2int (crossbow_classnames, classptr);
	      assert (tn->ci_in_parent == ci);
	    }
	  if (doc->cis == NULL)
	    {
	      doc->cis_size = 1;
	      doc->cis = bow_malloc (sizeof (typeof (doc->cis[0]))
				     * doc->cis_size);
	    }
	  else 
	    {
	      doc->cis_size++;
	      doc->cis = bow_realloc (doc->cis, (sizeof (typeof (doc->cis[0]))
						 * doc->cis_size));
	    }
	  ci = bow_str2int (crossbow_classnames, classptr);
	  /* Be that the same class isn't listed twice for the same file */
	  for (cisi = 0; cisi < doc->cis_size-1; cisi++)
	    assert (doc->cis[cisi] != ci);
	  doc->cis[doc->cis_size-1] = ci;
	}
      /* Set DOC->CI from a randomly-selected entry in DOC->CIS so that
	 the test/train splitting routines in split.c will work. */
      doc->ci = doc->cis[random() % doc->cis_size];
    }

  /* Reallocate space for WORDS and NEW_WORDS distributions now that
     we have indexed all the files and know what the complete
     vocabulary size is */
  bow_treenode_realloc_words_all (crossbow_root);

  crossbow_classes_count = crossbow_classnames->str_array_length;
  fclose (crossbow_wv_fp);
  crossbow_wv_fp = NULL;
  fclose (listfp);

  crossbow_archive (bow_data_dirname);
}

void
crossbow_index ()
{
  char fn[1024];
  int argi;
  int ci;

  text_file_count = 0;
  /* If we are pruning the vocabulary by occurrence count, then read
     all the documents to get the word counts, and limit the
     vocabulary appropriately. */
  if (bow_prune_vocab_by_occur_count_n)
    {
      /* Parse all the documents to get word occurrence counts. */
      for (argi = crossbow_arg_state.non_option_argi; 
	   argi < crossbow_argc; 
	   argi++)
	bow_words_add_occurrences_from_text_dir (crossbow_argv[argi], "");
      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;
    }
  if (crossbow_arg_state.vocab_map)
    {
      /* Set the vocabulary to be the vocab map. */
      bow_words_set_map (crossbow_arg_state.vocab_map, 1);
      /* Now insist that future calls to bow_word2int*() will not
	 register new words. */
      bow_word2int_do_not_add = 1;
    }      

  assert (crossbow_docs == NULL);
  crossbow_docs = bow_array_new (0, sizeof (crossbow_doc), crossbow_doc_free);
  crossbow_filename2di = bow_int4str_new (0);
  crossbow_classnames = bow_int4str_new (0);

  /* Read all the documents and write them as bow_wv's to the
     appropriate file in the model directory.  Also add entries to the
     CROSSBOW_CLASSNAMES map.  This must be done before creating
     TREENODE's so that we know how big to make the their vocabulary
     distributions. */
  sprintf (fn, "%s/wvs", bow_data_dirname);
  crossbow_wv_fp = bow_fopen (fn, "wb");
  for (argi = crossbow_arg_state.non_option_argi; argi < crossbow_argc; argi++)
    {
      ci = argi - crossbow_arg_state.non_option_argi;
      bow_map_filenames_from_dir (crossbow_index_filename, &ci,
				  crossbow_argv[argi], "");
#if !CLASSES_FROM_DIRS
      bow_str2int (crossbow_classnames, crossbow_argv[argi]);
#endif
    }
  fclose (crossbow_wv_fp);
  crossbow_wv_fp = NULL;
  bow_verbosify (bow_progress, "\n");

#if CLASSES_FROM_DIRS
  /* The number of classes equals the number of entries in the
     classname -> class index map. */
  crossbow_classes_count = crossbow_classnames->str_array_length;
#else
  /* Remember the number of topic class tags */
  crossbow_classes_count = crossbow_argc - crossbow_arg_state.non_option_argi;
#endif

  /* Build the hierarchy of treenode's.  This must be done after the
     documents have been read so that the treenode's know how big to
     make their vocabulary distributions. */
  if (crossbow_arg_state.build_hier_from_dir)
    {
      /* xxx This scheme currently makes it difficult to have a class
	 distribution in each node, and to set the hierarchy from a
	 directory structure. */
      assert (crossbow_argc - crossbow_arg_state.non_option_argi == 1);
      crossbow_root = crossbow_new_root_from_dir
	(crossbow_argv[crossbow_arg_state.non_option_argi], NULL);
      bow_treenode_set_classes_uniform (crossbow_root, crossbow_classes_count);
    }
  else
    {
      /* Create just a single root node */
      crossbow_root = bow_treenode_new_root (10);
      /* If there was more than one directory specified on command-line
	 allocate space to hold a class distribution */
      if (crossbow_classes_count > 1)
	bow_treenode_set_classes_uniform (crossbow_root, 
					  crossbow_classes_count);
    }

  crossbow_archive (bow_data_dirname);
}

int
crossbow_classify_doc (crossbow_doc *doc, int verbose, FILE *out)
{
  int li, leaf_count;
  double leaf_membership;
  treenode **leaves, *iterator, *leaf;
  bow_wv *wv;
  bow_wa *wa;
  int ret;
#if 0
  double inverse_rank_sum = 0;
  int rank;
  double score_diff_sum = 0;
#endif

  /* Classify the documents in the TAG-set */
  leaf_count = bow_treenode_leaf_count (crossbow_root);
  leaves = alloca (leaf_count * sizeof (void*));

  wv = crossbow_wv_at_di (doc->di);
  assert (wv);

  wa = bow_wa_new (leaf_count);

  /* Get the membership probability of each leaf */
  for (iterator = crossbow_root, li = 0;
       (leaf = bow_treenode_iterate_leaves (&iterator)); 
       li++)
    {
      if (crossbow_hem_shrinkage)
	leaf_membership = bow_treenode_log_prob_of_wv (leaf, wv);
      else
	leaf_membership = bow_treenode_log_local_prob_of_wv (leaf, wv);
      leaf_membership += log (leaf->prior);
      bow_wa_append (wa, li, leaf_membership);
      leaves[li] = leaf;
    }

  /* Print the results. */
  assert (wa->length == leaf_count);
  bow_wa_sort (wa);
  leaf = bow_treenode_descendant_matching_name (crossbow_root, 
						doc->filename);
  if (leaf && !strcmp (leaf->name, leaves[wa->entry[0].wi]->name))
    ret = 1;
  else
    ret = 0;

#if 0
  for (rank = 0; rank < wa->length; rank++)
    if (! strcmp (leaf->name, leaves[wa->entry[rank].wi]->name))
      {
	inverse_rank_sum += 1.0 / (rank + 1);
	score_diff_sum += wa->entry[0].weight - wa->entry[rank].weight;
	break;
      }
#endif
  if (verbose)
    {
      fprintf (out, "%s %s ", doc->filename, leaf ? leaf->name : "<unknown>");
      if (verbose >= 2)
	for (li = 0; li < leaf_count; li++)
	  fprintf (out, "%s:%g ", 
		   leaves[wa->entry[li].wi]->name,
		   wa->entry[li].weight);
      else
	fprintf (out, "%s", leaves[wa->entry[0].wi]->name);
      fprintf (out, "\n");
    }
  bow_wa_free (wa);
  return (ret);
}


void
crossbow_classify_tagged_docs (int tag, int verbose, FILE *out)
{
  int di;
  int doc_count = 0;
  int correct_count = 0;
  crossbow_doc *doc;
  
  for (di = 0; di < crossbow_docs->length; di++)
    {
      doc = bow_array_entry_at_index (crossbow_docs, di);
      if (tag != -1 && doc->tag != tag)
	continue;
      doc_count++;
      if ((((crossbow_method*)bow_argp_method)->classify_doc)
	  (doc, verbose, out))
	correct_count++;
    }

  if (!verbose)
    {
      fprintf (out, "Fraction correct %f (%d/%d)\n",
	       ((double)correct_count) / doc_count,
	       correct_count, doc_count);
#if 0
      fprintf (out, "Average Inverse Rank %f\n",
	       inverse_rank_sum / doc_count);
      fprintf (out, "Average Score Difference %f\n",
	       score_diff_sum / doc_count);
#endif
    }
}

void
crossbow_classify_docs_in_dirname (const char *dirname, int verbose)
{
  int classify_filename (const char *filename, void *context)
    {
      crossbow_doc doc;
      bow_wv *wv;
      FILE *fp;

      fp = bow_fopen (filename, "r");
      if (!bow_fp_is_text (fp))
	return 0;
      wv = bow_wv_new_from_text_fp (fp, filename);
      fclose (fp);
      if (!wv) 
	return 0;
      doc.tag = bow_doc_test;
      doc.ci = -1;
      doc.filename = filename;
      doc.word_count = bow_wv_word_count (wv);
      doc.wv_seek_pos = -1;
      doc.di = -1;
      doc.wv = wv;
      doc.cis_size = -1;
      doc.cis = NULL;
      ((((crossbow_method*)bow_argp_method)->classify_doc)
       (&doc, verbose, stdout));
      return 0;
    }

  bow_map_filenames_from_dir (classify_filename, NULL, dirname, "");
}



void
crossbow_cluster ()
{
  bow_verbosify (bow_progress, "Starting clustering\n");
  assert (((crossbow_method*)bow_argp_method)->cluster);
  ((crossbow_method*)bow_argp_method)->cluster ();
}

void
crossbow_classify ()
{
  bow_verbosify (bow_progress, "Starting classification\n");

  /* Train the vertical mixture model with EM. */
  if (!crossbow_hem_restricted_horizontal)
    crossbow_hem_deterministic_horizontal = 1;

  ((crossbow_method*)bow_argp_method)->train_classifier ();

  /* Classify the test documents and output results */
  if (crossbow_arg_state.classify_files_dirname)
    crossbow_classify_docs_in_dirname
      (crossbow_arg_state.classify_files_dirname, 1);
  else
    crossbow_classify_tagged_docs (bow_doc_test, 2, stdout);
}

void
crossbow_print_word_probabilities ()
{
  bow_error ("Not implemented");
}

void
crossbow_print_doc_names ()
{
  int di;
  int tag = -1;
  crossbow_doc *doc;

  if (crossbow_arg_state.printing_tag)
    {
      tag = bow_str2type (crossbow_arg_state.printing_tag);
      if (tag == -1)
	bow_error ("Argument to --print-doc-names, `%s', is not a tag\n"
		   "Try `train', `test', `unlabeled', etc");
    }
  for (di = 0; di < crossbow_docs->length; di++)
    {
      doc = bow_array_entry_at_index (crossbow_docs, di);
      if (crossbow_arg_state.printing_tag == NULL
	  || (tag >= 0 && doc->tag == tag))
	printf ("%s\n", doc->filename);
    }
}

void
crossbow_print_matrix ()
{
  int di, wvi;
  crossbow_doc *doc;
  bow_wv *wv;
  for (di = 0; di < crossbow_docs->length; di++)
    {
      doc = bow_array_entry_at_index (crossbow_docs, di);
      printf ("%s ", doc->filename);
      wv = crossbow_wv_at_di (di);
      for (wvi = 0; wvi < wv->num_entries; wvi++)
	printf ("%s %d ", 
		bow_int2word (wv->entry[wvi].wi), wv->entry[wvi].count);
      printf ("\n");
    }
}


/* Definitions for using argp command-line processing */

const char *argp_program_version =
"crossbow " STRINGIFY(CROSSBOW_MAJOR_VERSION) "." STRINGIFY(CROSSBOW_MINOR_VERSION);

const char *argp_program_bug_address = "<mccallum@cs.cmu.edu>";

static char crossbow_argp_doc[] =
"Crossbow -- a document clustering front-end to libbow";

static char crossbow_argp_args_doc[] = "[ARG...]";

enum {
  PRINT_IDF_KEY = 13000,
  QUERY_SERVER_KEY,
  QUERY_FORK_SERVER_KEY,
  CLUSTER_OUTPUT_DIR_KEY,
  BUILD_HIER_FROM_DIR_KEY,
  CLASSIFY_KEY,
  CLASSIFY_FILES_KEY,
  PRINT_WORD_PROBABILITIES_KEY,
  PRINT_DOC_NAMES_KEY,
  INDEX_MULTICLASS_LIST_KEY,
  PRINT_MATRIX_KEY,
  USE_VOCAB_IN_FILE_KEY,
};

static struct argp_option crossbow_options[] =
{
  {0, 0, 0, 0,
   "For building data structures from text files:", 1},
  {"index", 'i', 0, 0,
   "tokenize training documents found under ARG..., build weight vectors, "
   "and save them to disk"},
  {"index-multiclass-list", INDEX_MULTICLASS_LIST_KEY, "FILE", 0,
   "Index the files listed in FILE.  Each line of FILE should contain "
   "a filenames followed by a list of classnames to which that file belongs."},
  {"cluster", 'c', 0, 0,
   "cluster the documents, and write the results to disk"},
  {"cluster-output-dir", CLUSTER_OUTPUT_DIR_KEY, "DIR", 0,
   "After clustering is finished, write the cluster to directory DIR"},
  {"build-hier-from-dir", BUILD_HIER_FROM_DIR_KEY, 0, 0,
   "When indexing a single directory, use the directory structure to build "
   "a class hierarchy"},
  {"classify", CLASSIFY_KEY, 0, 0,
   "Split the data into train/test, and classify the test data, outputing "
   "results in rainbow format"},
  {"classify-files", CLASSIFY_FILES_KEY, "DIRNAME", 0,
   "Classify documents in DIRNAME, outputing `filename classname' pairs "
   "on each line."},
  {"print-word-probabilities", PRINT_WORD_PROBABILITIES_KEY, "FILEPREFIX", 0,
   "Print the word probability distribution in each leaf to files named "
   "FILEPREFIX-classname"},
  {"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."},
  {"print-matrix", PRINT_MATRIX_KEY, 0, 0,
   "Print the word/document count matrix in an awk- or perl-accessible "
   "format.  Format is sparse and includes the words and the counts."},
  {"use-vocab-in-file", USE_VOCAB_IN_FILE_KEY, "FILENAME", 0,
   "Limit vocabulary to just those words read as space-separated strings "
   "from FILE."},

  { 0 }
};

static error_t
crossbow_parse_opt (int key, char *arg, struct argp_state *state)
{
  switch (key)
    {
    case 'i':
      crossbow_arg_state.what_doing = crossbow_index;
      break;
    case INDEX_MULTICLASS_LIST_KEY:
      crossbow_arg_state.what_doing = crossbow_index_multiclass_list;
      crossbow_arg_state.multiclass_list_filename = arg;
      break;
    case 'c':
      crossbow_arg_state.what_doing = crossbow_cluster;
      break;
    case CLUSTER_OUTPUT_DIR_KEY:
      crossbow_arg_state.cluster_output_dir = arg;
      break;
    case BUILD_HIER_FROM_DIR_KEY:
      crossbow_arg_state.build_hier_from_dir = 1;
      break;
    case CLASSIFY_FILES_KEY:
      crossbow_arg_state.classify_files_dirname = arg;
    case CLASSIFY_KEY:
      crossbow_arg_state.what_doing = crossbow_classify;
      break;
    case PRINT_WORD_PROBABILITIES_KEY:
      crossbow_arg_state.what_doing = crossbow_print_word_probabilities;
      break;
    case PRINT_DOC_NAMES_KEY:
      crossbow_arg_state.what_doing = crossbow_print_doc_names;
      crossbow_arg_state.printing_tag = arg;
      break;
    case PRINT_MATRIX_KEY:
      crossbow_arg_state.what_doing = crossbow_print_matrix;
      break;
    case USE_VOCAB_IN_FILE_KEY:
      crossbow_arg_state.vocab_map = bow_int4str_new_from_text_file (arg);
      bow_verbosify (bow_progress,
		     "Using vocab with %d words from file `%s'\n",
		     crossbow_arg_state.vocab_map->str_array_length, arg);
      break;

    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.  */
      crossbow_arg_state.non_option_argi = state->next - 1;
      if (crossbow_arg_state.what_doing == crossbow_index
	  && state->next > state->argc)
	{
	  /* Zero directory names is not enough. */
	  fprintf (stderr, "Need at least one directory to index.\n");
	  argp_usage (state);
	}
      state->next = state->argc;
      break;

    default:
      return ARGP_ERR_UNKNOWN;
    }
  return 0;
}

static struct argp crossbow_argp = 
{ crossbow_options, crossbow_parse_opt, crossbow_argp_args_doc,
  crossbow_argp_doc, bow_argp_children};

/* This method structure is defined in hem.c, 
   and is the default bow_argp_method */
extern crossbow_method hem_cluster_method;


int
main (int argc, char *argv[])
{
  /* Default command-line argument values */
  crossbow_arg_state.what_doing = crossbow_cluster;
  crossbow_arg_state.cluster_output_dir = NULL;
  crossbow_arg_state.build_hier_from_dir = 0;
  crossbow_arg_state.print_file_prefix = NULL;
  crossbow_arg_state.printing_tag = NULL;
  crossbow_arg_state.classify_files_dirname = NULL;
  crossbow_arg_state.vocab_map = NULL;
  bow_argp_method = (bow_method*)&hem_cluster_method;

  /* bow_lexer_toss_words_longer_than = 20; */

  /* Parse the command-line arguments. */
  argp_parse (&crossbow_argp, argc, argv, 0, 0, &crossbow_arg_state);

  crossbow_argv = argv;
  crossbow_argc = argc;

  if (*crossbow_arg_state.what_doing != crossbow_index
      && *crossbow_arg_state.what_doing != crossbow_index_multiclass_list)
    {
      crossbow_unarchive (bow_data_dirname);

      /* Do test/train splits. */
      bow_set_doc_types (crossbow_docs, crossbow_classes_count,
			 crossbow_classnames);
    }

  (*crossbow_arg_state.what_doing) ();

  if (crossbow_arg_state.cluster_output_dir
      && *crossbow_arg_state.what_doing != crossbow_index)
    crossbow_archive (bow_data_dirname);

  exit (0);
}