script/order2vec.pl untested

filter: Statementstmt 0.0% 0 / 318 Branchbran 0.0% 0 / 138 Conditioncond 0.0% 0 / 22 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 501 CC 1 SCAR 6.9
CC
1
Cov
0%
showminimal
2.0
showhelp
2.0
showversion
2.0
CRAP 2.0
1 #!/usr/local/bin/perl -w
2  
3 =head1 NAME
4  
5 order2vec.pl - Convert Senseval-2 contexts into second order context vectors in Cluto format
6  
7 =head1 SYNOPSIS
8  
9 order2vec.pl [OPTIONS] SVAL2 WORDVEC FEATURE_REGEX
10  
11 Type C<order2vec.pl --help> for a quick summary of options.
12  
13 =head1 DESCRIPTION
14  
15 Creates second order context vectors by averaging word or feature vectors of
16 the contextual features.
17  
18 =head1 INPUT
19  
20 =head2 Required Arguments:
21  
22 =head3 SVAL2
23  
24 A tokenized, preprocessed and well formatted Senseval-2 instance file
25 showing instances whose context vectors are to be generated.
26  
27 order2vec creates a context vector for each instance in the given SVAL2 file
28 by averaging the word or feature vectors of the features that appear in the
29 context.
30  
31 =head3 WORDVEC
32  
33 Should be one of the following type of files:
34  
35 =over
36  
37 =item 1.
38  
39 A file containing word vectors as created by program wordvec.pl
40  
41 =item 2.
42  
43 A file containing feature vectors as created by order1vec.pl, using its
44 --transpose option.
45  
46 =back
47  
48 Each line in WORDVEC should show a word or feature vector of the feature
49 represented by the corresponding line in the FEATURE_REGEX file.
50  
51 order2vec accepts WORDVEC in both sparse and dense formats. If WORDVEC is
52 in dense format, switch --dense should be selected.
53  
54 =head3 FEATURE_REGEX
55  
56 Should be one of the following type of files:
57  
58 =over
59  
60 =item 1.
61  
62 The output file generated by running nsp2regex.pl on the FEATURE file as
63 generated by program wordvec.pl while creating the WORDVEC file.
64  
65 =item 2.
66  
67 The TEST_REGEX file created by order1vec.pl using its --testregex option, while
68 creating the feature-by-context output file using the --transpose option.
69  
70 =back
71  
72 Each line in FEATURE_REGEX file should show a regular expression for a feature
73 whose feature vector appears on the corresponding line in the WORDVEC file.
74 FEATURE_REGEX should be formatted like the output of the nsp2regex.pl program.
75  
76 Sample FEATURE_REGEX files:
77  
78 =over
79  
80 =item 1.
81  
82 A file output by nsp2regex.pl when it is run on the file produced by --feats
83 option of wordvec.pl:
84  
85 /\s(<[^>]*>)*details(<[^>]*>)*\s/ @name = details
86 /\s(<[^>]*>)*weather(<[^>]*>)*\s/ @name = weather
87 /\s(<[^>]*>)*test(<[^>]*>)*\s/ @name = test
88 /\s(<[^>]*>)*cloth(<[^>]*>)*\s/ @name = cloth
89 /\s(<[^>]*>)*health(<[^>]*>)*\s/ @name = health
90 /\s(<[^>]*>)*art(<[^>]*>)*\s/ @name = art
91  
92 =item 2.
93  
94 A TEST_REGEX file output by order1vec.pl using its --testregex option:
95  
96 /\s(<[^>]*>)*polygonal(<[^>]*>)*\s/ @name = polygonal
97 /\s(<[^>]*>)*ectoderm(<[^>]*>)*\s/ @name = ectoderm
98 /\s(<[^>]*>)*fluid(<[^>]*>)*\s/ @name = fluid
99 /\s(<[^>]*>)*CEMx174(<[^>]*>)*\s/ @name = CEMx174
100 /\s(<[^>]*>)*adjacent(<[^>]*>)*\s/ @name = adjacent
101 /\s(<[^>]*>)*mutant(<[^>]*>)*\s/ @name = mutant
102 /\s(<[^>]*>)*progenitor(<[^>]*>)*\s/ @name = progenitor
103 /\s(<[^>]*>)*Ganglion(<[^>]*>)*\s/ @name = Ganglion
104 /\s(<[^>]*>)*MLS(<[^>]*>)*\s/ @name = MLS
105 /\s(<[^>]*>)*male(<[^>]*>)*\s/ @name = male
106 /\s(<[^>]*>)*mother(<[^>]*>)*\s/ @name = mother
107  
108 =back
109  
110 =head2 Optional Arguments:
111  
112 =head3 --binary
113  
114 Select this switch to create binary context vectors. Binary vectors are
115 computed by taking the binary OR of the word vectors of features that are
116 found in the context. By default, order2vec creates frequency score vectors
117 that show arithmatic avearge of the word vectors of contextual features.
118  
119 =head3 --dense
120  
121 By default, word vectors in WORDVEC are assumed to be in sparse format. Also,
122 the context vectors displayed by order2vec are in sparse format.
123  
124 Select --dense if the word vectors are in dense format. This will automatically
125 create output vectors in dense format as well.
126  
127 **************** IMPORTANT NOTE ************
128  
129 Dense word vectors (when --dense is ON) should be formatted i.e. each entry
130 of WORDVEC should be represented using the same numeric format and should
131 occupy exactly same number of spaces. Use --format option to specify the
132 format of dense word vectors.
133  
134 =head3 --rlabel RLABELFILE
135  
136 Creates a RLABELFILE containing row labels for Cluto's --rlabelfile option.
137 Each line in RLABELFILE shows an instance id of the instance whose context
138 vector appears on the corresponding line on STDOUT.
139  
140 Instance ids are extracted from the SVAL2 file by matching regex
141  
142 /<instance id\s*=\s*"IID"/>/
143  
144 where 'IID' is an instance id of the <context> that follows this <instance>
145 tag.
146  
147 =head3 --rclass RCLASSFILE
148  
149 Creates RCLASSFILE for Cluto's --rclassfile option. Each line in the
150 RCLASSFILE shows the true sense id of the instance whose context vector
151 appears on the corresponding line on STDOUT.
152  
153 Sense ids are extracted from the SVAL2 file by matching regex
154  
155 /sense\s*id\s*=\s*"SID"\/>/
156  
157 where SID shows the true sense tag of the instance whose IID is recently
158 extracted by matching
159  
160 /<instance id\s*=\s*"IID"/>/
161  
162 =head3 --showkey
163  
164 Displays the name of the system generated KEY file on the first line of STDOUT.
165 KEY file preserves the instance ids and sense tags of the instances in the
166 given SVAL2 file. This information will be automatically used by some of the
167 clustering and evaluation programs in SenseClusters that operate on purely
168 numeric instance formats. The option should be selected if the user is planning
169 to run SenseClusters' clustering code.
170  
171 =head2 Other Options :
172  
173 =head3 --format FORM
174  
175 If --dense is ON, input WORD VECtors need to be formatted i.e. should be
176 represented using same numeric format and occupy same number of digit spaces.
177 If wordvec.pl was run using its --format option, then the value of --format
178 to order2vec.pl should be same as that specified in wordvec.pl's --format
179 option.
180  
181 Format should be represented as
182  
183 iN -> integer format where each entry occupies total N bytes/digits
184  
185 fN.M -> floating point format where each entry occupies total N bytes/digits
186 of which last M digits show the fractional part
187  
188 When --binary is ON, default format is i2 that assumes 2 digit space for each
189 entry. When --binary is OFF, default format is f16.10 that assumes each
190 entry is fractional occupying total 16 digit equivalent spaces of which last 10
191 digits show the fractional part.
192  
193 Output context vectors (sparse or dense) will be represented using the
194 specified format value or default f16.10.
195  
196 =head3 --help
197  
198 Displays this message.
199  
200 =head3 --version
201  
202 Displays the version information.
203  
204 =head1 OUTPUT
205  
206 Output shows a single context vector on each line.
207 Context vectors represent instances in the same order as they appear in the
208 given SVAL2 file i.e. each ith vector on STDOUT shows a context vector of the
209 ith instance in the SVAL2 file.
210  
211 Each context vector is an average of the WORD VECtors of the features
212 that are found in the context using FEATURE_REGEX.
213  
214 =head2 Sample Sparse Output
215  
216 Input Sval2 file => test.sval2
217  
218 <corpus lang="english">
219 <lexelt item="LEXELT">
220 <instance id="hard-a.sjm-098_3:">
221 <answer instance="hard-a.sjm-098_3:" senseid="HARD1"/>
222 <context>
223 someone has to kill him to defeat him and that s <head>HARD</head> to do
224 </context>
225 </instance>
226 <instance id="hard-a.w8_038:">
227 <answer instance="hard-a.w8_038:" senseid="HARD3"/>
228 <context>
229 I find it <head>HARD</head> to believe that you don't believe me
230 </context>
231 </instance>
232 <instance id="hard-a.sjm-255_13:">
233 <answer instance="hard-a.sjm-255_13:" senseid="HARD3"/>
234 <context>
235 when you get bad credit data or are confused with another person your life gets <head>HARD</head>
236 </context>
237 </instance>
238 <instance id="hard-a.sjm-231_3:">
239 <answer instance="hard-a.sjm-231_3:" senseid="HARD2"/>
240 <context>
241 Our life is <head>HARDER</head> now yes but it is better to live hungry and free life
242 </context>
243 </instance>
244 <instance id="hard-a.sjm-096_2:">
245 <answer instance="hard-a.sjm-096_2:" senseid="HARD1"/>
246 <context>
247 Ray who told his colleagues We have to face the <head>HARD</head> facts of life due to bad credit
248 </context>
249 </instance>
250 </lexelt>
251 </corpus>
252  
253 Input FEATURE_REGEX file => test.regex
254  
255 /\s(<[^>]*>)*<head>HARD<\/head>(<[^>]*>)*\s/ @name = <head>HARD</head>
256 /\s(<[^>]*>)*to(<[^>]*>)*\s/ @name = to
257 /\s(<[^>]*>)*defeat(<[^>]*>)*\s/ @name = defeat
258 /\s(<[^>]*>)*believe(<[^>]*>)*\s/ @name = believe
259 /\s(<[^>]*>)*credit(<[^>]*>)*\s/ @name = credit
260 /\s(<[^>]*>)*life(<[^>]*>)*\s/ @name = life
261 /\s(<[^>]*>)*facts(<[^>]*>)*\s/ @name = facts
262 /\s(<[^>]*>)*kill(<[^>]*>)*\s/ @name = kill
263  
264 Input Saprse Word Vectors => test.sparse_wordvec
265  
266 8 10 41
267 1 4.977 4 7.813 8 9.114 10 1.431
268 1 5.944 2 5.728 3 2.978 5 5.604 7 9.444 9 3.680
269 2 3.984 3 8.306 4 6.632 5 4.514 7 1.785 9 7.609
270 2 9.147 4 3.086 5 0.325 9 1.456
271 1 0.741 4 3.450 6 2.363
272 1 9.549 2 3.921 3 8.131 4 4.301 5 9.059 6 8.607 10 1.138
273 2 8.203 4 7.297 5 1.095 7 4.362 8 2.963 10 7.264
274 2 4.296 4 9.802 7 9.268 9 8.856 10 9.723
275  
276 Command =>
277  
278 order2vec.pl --format f9.4 test.sval2 test.sparse_wordvec test.regex
279  
280 Output =>
281  
282 5 10 45
283 1 3.8015 2 4.2440 3 2.8733 4 4.0412 5 3.5543 7 6.5642 8 1.5190 9 4.5842 10 1.8590
284 1 2.7302 2 6.0055 3 0.7445 4 3.4962 5 1.5635 7 2.3610 8 2.2785 9 1.6480 10 0.3578
285 1 5.0890 2 1.3070 3 2.7103 4 5.1880 5 3.0197 6 3.6567 8 3.0380 10 0.8563
286 1 8.3473 2 4.5233 3 6.4133 4 2.8673 5 7.9073 6 5.7380 7 3.1480 9 1.2267 10 0.7587
287 1 4.5258 2 3.9300 3 2.3478 4 3.8102 5 3.5603 6 1.8283 7 3.8750 8 2.0128 9 1.2267 10 1.6388
288  
289 Explanation =>
290  
291 First instance <hard-a.sjm-098_3:> contains features
292  
293 '<head>HARD</head>' once,
294 'to' thrice,
295 'defeat' once,
296 'kill' once.
297  
298 Hence, the context vector of instance <hard-a.sjm-098_3:> shown on Line 2
299 on STDOUT is an average of sparse word vectors ->
300  
301 [1 4.977 4 7.813 8 9.114 10 1.431]
302 3 * [1 5.944 2 5.728 3 2.978 5 5.604 7 9.444 9 3.680]
303 [2 3.984 3 8.306 4 6.632 5 4.514 7 1.785 9 7.609]
304 [2 4.296 4 9.802 7 9.268 9 8.856 10 9.723]
305  
306 OR
307  
308 [1 4.977 4 7.813 8 9.114 10 1.431]
309 [1 17.832 2 17.184 3 8.934 5 16.812 7 28.332 9 11.04]
310 [2 3.984 3 8.306 4 6.632 5 4.514 7 1.785 9 7.609]
311 [2 4.296 4 9.802 7 9.268 9 8.856 10 9.723]
312  
313 The Sum of above vectors is a sparse vector =>
314  
315 [1 22.809 2 25.464 3 17.24 4 24.247 5 21.326 7 39.385 8 9.114 9 27.505 10 11.154]
316  
317 And the average is =>
318  
319 [1 3.8015 2 4.2440 3 2.8733 4 4.0412 5 3.5543 7 6.5642 8 1.5190 9 4.5842 10 1.8590]
320  
321 Similarly, all context vectors are computed by averaging the word vectors of
322 features that match in the context.
323  
324  
325 =head2 Sample Dense Output
326  
327 In the above example, if WORDVEC is dense => test.dense_wordvec
328  
329 8 10
330 4.9770 0.0000 0.0000 7.8130 0.0000 0.0000 0.0000 9.1140 0.0000 1.4310
331 5.9440 5.7280 2.9780 0.0000 5.6040 0.0000 9.4440 0.0000 3.6800 0.0000
332 0.0000 3.9840 8.3060 6.6320 4.5140 0.0000 1.7850 0.0000 7.6090 0.0000
333 0.0000 9.1470 0.0000 3.0860 0.3250 0.0000 0.0000 0.0000 1.4560 0.0000
334 0.7410 0.0000 0.0000 3.4500 0.0000 2.3630 0.0000 0.0000 0.0000 0.0000
335 9.5490 3.9210 8.1310 4.3010 9.0590 8.6070 0.0000 0.0000 0.0000 1.1380
336 0.0000 8.2030 0.0000 7.2970 1.0950 0.0000 4.3620 2.9630 0.0000 7.2640
337 0.0000 4.2960 0.0000 9.8020 0.0000 0.0000 9.2680 0.0000 8.8560 9.7230
338  
339 Command =>
340  
341 order2vec.pl --format f9.4 --dense test.sval2 test.dense_wordvec test.feat
342  
343 Output =>
344  
345 5 10
346 3.8015 4.2440 2.8733 4.0412 3.5543 0.0000 6.5642 1.5190 4.5842 1.8590
347 2.7302 6.0055 0.7445 3.4962 1.5635 0.0000 2.3610 2.2785 1.6480 0.3578
348 5.0890 1.3070 2.7103 5.1880 3.0197 3.6567 0.0000 3.0380 0.0000 0.8563
349 8.3473 4.5233 6.4133 2.8673 7.9073 5.7380 3.1480 0.0000 1.2267 0.7587
350 4.5258 3.9300 2.3478 3.8102 3.5603 1.8283 3.8750 2.0128 1.2267 1.6388
351  
352 Shows same context vectors as shown in Sample Sparse Output section only
353 with --dense ON.
354  
355 Note that, if --dense is ON, --format has to be used and must specify
356 the format of dense word vectors.
357  
358 =head1 SYSTEM REQUIREMENTS
359  
360 =over
361  
362 =item PDL - L<http://search.cpan.org/dist/PDL/>
363  
364 =back
365  
366 =head1 AUTHORS
367  
368 Ted Pedersen, University of Minnesota, Duluth
369 tpederse at d.umn.edu
370  
371 Amruta Purandare, University of Pittsburgh
372  
373 Mahesh Joshi, Carnegie-Mellon University
374  
375 =head1 COPYRIGHT
376  
377 Copyright (c) 2002-2008, Ted Pedersen, Amruta Purandare, Mahesh Joshi
378  
379 This program is free software; you can redistribute it and/or modify it under
380 the terms of the GNU General Public License as published by the Free Software
381 Foundation; either version 2 of the License, or (at your option) any later
382 version.
383  
384 This program is distributed in the hope that it will be useful, but WITHOUT
385 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
386 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
387  
388 You should have received a copy of the GNU General Public License along with
389 this program; if not, write to
390  
391 The Free Software Foundation, Inc.,
392 59 Temple Place - Suite 330,
393 Boston, MA 02111-1307, USA.
394  
395 =cut
396  
397 ###############################################################################
398  
399 # ==============================
400 # THE CODE STARTS HERE
401 # ==============================
402  
403 #$0 contains the program name along with
404 #the complete path. Extract just the program
405 #name and use in error messages
406 $0=~s/.*\/(.+)/$1/;
407  
408 # use PDL for dense vectors
409 use PDL;
410 use PDL::NiceSlice;
411 use PDL::Primitive;
412  
413 # use Math::SparseVector module for sparse vectors
414 use Math::SparseVector;
415  
416 ###############################################################################
417  
418 # ================================
419 # COMMAND LINE OPTIONS AND USAGE
420 # ================================
421  
422 # command line options
423 use Getopt::Long;
424 GetOptions ("help","version","format=s","binary","showkey","rlabel=s","rclass=s","dense");
425 # show help option
426 if(defined $opt_help)
427 {
428 $opt_help=1;
429 &showhelp();
430 exit;
431 }
432  
433 # show version information
434 if(defined $opt_version)
435 {
436 $opt_version=1;
437 &showversion();
438 exit;
439 }
440  
441 # show minimal usage message if fewer arguments
442 if($#ARGV<2)
443 {
444 &showminimal();
445 exit 1;
446 }
447  
448 #############################################################################
449  
450 # ================================
451 # INITIALIZATION AND INPUT
452 # ================================
453  
454 # ------------
455 # SVAL2 file
456 # ------------
457 if(!defined $ARGV[0])
458 {
459 print STDERR "ERROR($0):
460 Please specify the input SVAL2 file.\n";
461 exit 1;
462 }
463 #accept the SVAL2 file name
464 $infile=$ARGV[0];
465 if(!-e $infile)
466 {
467 print STDERR "ERROR($0):
468 SVAL2 file <$infile> doesn't exist...\n";
469 exit 1;
470 }
471 open(IN,$infile) || die "Error($0):
472 Error(code=$!) in opening the SVAL2 file <$infile>.\n";
473  
474 # -------------
475 # Wordvec file
476 # -------------
477 if(!defined $ARGV[1])
478 {
479 print STDERR "ERROR($0):
480 Please specify the WORDVEC file.\n";
481 exit 1;
482 }
483  
484 #accept the wordvec file name
485 $wordvec_file=$ARGV[1];
486 if(!-e $wordvec_file)
487 {
488 print STDERR "ERROR($0):
489 WORDVEC file <$wordvec_file> doesn't exist...\n";
490 exit 1;
491 }
492 open(WM,$wordvec_file) || die "Error($0):
493 Error(code=$!) in opening WORDVEC file <$wordvec_file>.\n";
494  
495 # word vectors in dense format
496 if(defined $opt_dense)
497 {
498 # first line
499 $line1=<WM>;
500 if($line1 !~ /^\s*(\d+)\s+(\d+)\s*$/)
501 {
502 print STDERR "ERROR($0):
503 Line1 in WORDVEC file <$wordvec_file> should show #rows #cols
504 when --dense is ON.\n";
505 exit 1;
506 }
507 else
508 {
509 $header+=length($line1);
510 $rows=$1;
511 $cols=$2;
512 }
513 }
514 # word vectors in sparse format
515 else
516 {
517 # first line
518 $line1=<WM>;
519 if($line1 !~ /^\s*(\d+)\s+(\d+)\s+(\d+)\s*$/)
520 {
521 print STDERR "ERROR($0):
522 Line1 in WORDVEC file <$wordvec_file> should show #rows #cols #nnz.\n";
523 exit 1;
524 }
525 else
526 {
527 $rows=$1;
528 $cols=$2;
529 $nnz1=$3;
530 }
531  
532 $line_num=1;
533 while(<WM>)
534 {
535 $line_num++;
536 chomp;
537 s/^\s*//;
538 s/\s*$//;
539 $word_vector=Math::SparseVector->new;
540 @pairs=split(/\s+/);
541 for($i=0; $i<$#pairs; $i=$i+2)
542 {
543 $index=$pairs[$i];
544 if($index > $cols)
545 {
546 print STDERR "ERROR($0):
547 Index $index found at line <$line_num> in WORDVEC file <$wordvec_file>
548 exceeds the total number of columns $cols shown on the 1st line.\n";
549 exit 1;
550 }
551 $value=$pairs[$i+1];
552 $word_vector->set($index,$value);
553 $nnz++;
554 }
555 # $word_vector->free;
556 push @word_vectors,$word_vector;
557 }
558 close WM;
559 if(scalar(@word_vectors) != $rows)
560 {
561 print STDERR "ERROR($0):
562 1st line of WORDVEC file <$wordvec_file> shows #vectors = $rows while
563 the actual #vectors found in the file = " . scalar(@word_vectors) . "\n";
564 exit 1;
565 }
566  
567 if($nnz != $nnz1)
568 {
569 print STDERR "ERROR($0):
570 1st line of WORDVEC file <$wordvec_file> shows #nnz = $nnz1 while
571 the actual #nnz found in the file = $nnz.\n";
572 exit 1;
573 }
574 }
575  
576 # ------------------
577 # Feature Regex file
578 # ------------------
579 if(!defined $ARGV[2])
580 {
581 print STDERR "ERROR($0):
582 Please specify the Feature Regex file.\n";
583 exit 1;
584 }
585 #accept the feature regex file name
586 $featfile=$ARGV[2];
587 if(!-e $featfile)
588 {
589 print STDERR "ERROR($0):
590 Feature file <$featfile> doesn't exist...\n";
591 exit 1;
592 }
593 open(FEAT,$featfile) || die "Error($0):
594 Error(code=$!) in opening Feature file <$featfile>.\n";
595 while(<FEAT>)
596 {
597 $line_num++;
598 chomp;
599 s/^\s*//;
600 s/\s*$//;
601  
602 if(/(.*)\s*\@name\s*=\s*.*/)
603 {
604 $feature_regex=$1;
605  
606 # removing leading and lagging blank spaces
607 $feature_regex=~s/^\s*//;
608 $feature_regex=~s/\s*$//;
609  
610 # removing the starting and ending slashes //
611 if($feature_regex=~/^\//) { $feature_regex=~s/^\///; }
612 else
613 {
614 print STDERR "ERROR($0):
615 Feature regex <$feature_regex>
616 at line <$line_num> in Feature Regex file <$featfile> should start
617 with '/'\n";
618 exit;
619 }
620 if($feature_regex=~/\/$/) { $feature_regex=~s/\/$//; }
621 else
622 {
623 print STDERR "ERROR($0):
624 Feature regex <$feature_regex>
625 at line <$line_num> in Feature Regex file <$featfile> should end
626 with '/'\n";
627 exit;
628 }
629
630 push @feature_regexes,$feature_regex;
631 }
632 }
633 close FEAT;
634  
635 if (scalar(@feature_regexes) != $rows) {
636 print STDERR "ERROR($0):
637 Unequal number of feature vectors and features provided in
638 input files. WORDVEC file <$wordvec_file>
639 specifies $rows vectors whereas FEATURE_REGEX
640 file <$featfile> contains " .
641 scalar(@feature_regexes) . " features.\n";
642 exit 1;
643 }
644  
645 # -----------
646 # Formatting
647 # -----------
648 # if --format is specified
649 if(defined $opt_format)
650 {
651 # integer
652 if($opt_format=~/^i(\d+)$/)
653 {
654 if(defined $opt_dense)
655 {
656 $bytein=$1;
657 }
658 $format="%$1d";
659  
660 $lower_format="-";
661 while(length($lower_format)<($1-1))
662 {
663 $lower_format.="9";
664 }
665 if($lower_format eq "-")
666 {
667 $lower_format="0";
668 }
669 $upper_format="";
670 while(length($upper_format)<($1-1))
671 {
672 $upper_format.="9";
673 }
674 }
675 # float
676 elsif($opt_format=~/^f(\d+)\.(\d+)$/)
677 {
678 if(defined $opt_dense)
679 {
680 $bytein=$1;
681 }
682 $format="%$1.$2f";
683  
684 $lower_format="-";
685 while(length($lower_format)<($1-$2-2))
686 {
687 $lower_format.="9";
688 }
689 $lower_format.=".";
690 while(length($lower_format)<($1-1))
691 {
692 $lower_format.="9";
693 }
694  
695 $upper_format="";
696 while(length($upper_format)<($1-$2-2))
697 {
698 $upper_format.="9";
699 }
700 $upper_format.=".";
701 while(length($upper_format)<($1-1))
702 {
703 $upper_format.="9";
704 }
705 }
706 else
707 {
708 print STDERR "ERROR($0):
709 Wrong format value --format=$opt_format.\n";
710 exit 1;
711 }
712 }
713 # default format is f16.10
714 else
715 {
716 if(defined $opt_binary)
717 {
718 if(defined $opt_dense)
719 {
720 $bytein=2;
721 }
722 $format="%2d";
723  
724 $lower_format="0";
725 $upper_format="1";
726 }
727 else
728 {
729 if(defined $opt_dense)
730 {
731 $bytein=16;
732 }
733 $format="%16.10f";
734  
735 $lower_format="-999.9999999999";
736 $upper_format="9999.9999999999";
737 }
738 }
739  
740 ##############################################################################
741  
742 ##############################################################################
743  
744 # =================================================
745 # Read Context words and create Context Vectors
746 # =================================================
747  
748 # context vectors are temporarily written into a
749 # TEMP file
750  
751 # if the program finishes sucessfully, this TEMP file
752 # is printed to STDOUT and is deleted
753  
754 # otherwise TEMP file is retained and stores the partial
755 # program output
756  
757 $tempfile="tempfile" . time() . ".order2vec";
758  
759 if(-e $tempfile)
760 {
761 print STDERR "ERROR($0):
762 Temporary file <$tempfile> should not already exist.\n";
763 exit 1;
764 }
765  
766 open(TEMP,">$tempfile") || die "ERROR($0):
767 Error(code=$!) in opening internal temporary file <$tempfile>.\n";
768  
769 # reading the SVAL2 file
770 $line_num=0;
771 if(defined $opt_dense)
772 {
773 $context_vector=zeroes($cols);
774 $word_vector=zeroes($cols);
775 }
776 else
777 {
778 $context_vector=Math::SparseVector->new;
779 $nnz=0;
780 }
781 while(<IN>)
782 {
783 $line_num++;
784
785 if(/instance id\s*=\s*\"([^"]+)\"/)
786 {
787 $instance=$1;
788 if(defined $instance_ids{$instance})
789 {
790 print STDERR "ERROR($0):
791 Instance Id <$instance> is repeated in the SVAL2 file <$infile>.\n";
792 exit 1;
793 }
794 push @instances,$instance;
795 $instance_ids{$instance}=1;
796 }
797  
798 if(/<\/instance>/)
799 {
800 undef $instance;
801 }
802  
803 if(/sense\s*id\s*=\s*\"([^"]+)\"/)
804 {
805 # no <instance> open
806 if(!defined $instance)
807 {
808 print STDERR "ERROR($0):
809 Missing <instance> tag before the <sense> tag at line <$line_num>
810 in SVAL2 file <$infile>.\n";
811 exit 1;
812 }
813 $sense=$1;
814 if(defined $key_table{$instance}{$sense})
815 {
816 print STDERR "ERROR($0):
817 <instance-id, sense-tag> pair <$instance, $sense> is repeated in the
818 SVAL2 file <$infile>.\n";
819 exit 1;
820 }
821 $key_table{$instance}{$sense}=1;
822 }
823  
824 if(/<\/context>/)
825 {
826 undef $data_start;
827 # printing the context vector
828 if(defined $opt_dense)
829 {
830 foreach $col (0..$cols-1)
831 {
832 $value=sprintf $format, $context_vector->at($col);
833 if($value<$lower_format)
834 {
835 print STDERR "ERROR($0):
836 Floating point underflow.
837 Value <$value> can't be represented using the specified format $format.\n";
838 exit 1;
839 }
840 if($value>$upper_format)
841 {
842 print STDERR "ERROR($0):
843 Floating point overflow.
844 Value <$value> can't be represented using the specified format $format.\n";
845 exit 1;
846 }
847 print TEMP "$value";
848 }
849 }
850 else
851 {
852 foreach $index ($context_vector->keys)
853 {
854 $value=sprintf $format, $context_vector->get($index);
855  
856 if($value != 0)
857 {
858 print TEMP "$index $value ";
859 $nnz++;
860 }
861 }
862 }
863 print TEMP "\n";
864 }
865  
866 # context data
867 if(defined $data_start)
868 {
869 # handling blank lines
870 if(/^\s*$/)
871 {
872 next;
873 }
874  
875 # nsp2regex features have format
876 # /\sFEATURE\s/ which requires a space
877 # on each side of the token
878 s/^(\S)/ $1/;
879 s/(\S)$/$1 /;
880 # ---------------------------------------------------
881 # the logic of matching feature regex/s is borrowed
882 # from the xml2arff.pl program from the SenseTools
883 # package by Satanjeev Banerjee and Ted Pedersen
884 # ---------------------------------------------------
885 foreach $index (0..$#feature_regexes)
886 {
887 $feature_regex=$feature_regexes[$index];
888 if(defined $opt_binary)
889 {
890 # match or not
891 if(/$feature_regex/)
892 {
893 # offset of feature in FEATURE file
894 $feature_offset=$index;
895  
896 # read word vector from WORDVEC file
897 if(defined $opt_dense)
898 {
899 # offset of word vector in WORDVEC file
900 $wordvec_offset=($cols*$feature_offset*$bytein)+$feature_offset+$header;
901 seek(WM,$wordvec_offset,0);
902 $word_vector->inplace->zeroes;
903 # read cols number of elements
904 foreach $col (0..$cols-1)
905 {
906 read(WM,$value,$bytein);
907 # print STDERR "<$value>\n";
908 if(!defined $value)
909 {
910 print STDERR "ERROR($0):
911 Insufficient column entries in Word Vector at index=$feature_offset
912 in WORD VECtor file <$wordvec_file>.\n";
913 exit 1;
914 }
915 if($value != 0)
916 {
917 set($word_vector,$col,1);
918 }
919 else
920 {
921 set($word_vector,$col,0);
922 }
923 }
924
925 $context_vector->inplace->or2($word_vector,0);
926 }
927 # sparse word vectors are loaded in @word_vectors
928 else
929 {
930 $context_vector->binadd($word_vectors[$feature_offset]);
931 }
932 }
933 }
934 else
935 # not binary
936 {
937 # number of matches
938 while(/$feature_regex/g)
939 {
940 # offset of feature in FEATURE file
941 $feature_offset=$index;
942  
943 # read word vector from WORDVEC file
944 if(defined $opt_dense)
945 {
946 # offset of word vector in WORDVEC file
947 $wordvec_offset=($cols*$feature_offset*$bytein)+$feature_offset+$header;
948 seek(WM,$wordvec_offset,0);
949 $word_vector->inplace->zeroes;
950 # read cols number of elements
951 foreach $col (0..$cols-1)
952 {
953 read(WM,$value,$bytein);
954 # print STDERR "<$value>\n";
955 if(!defined $value)
956 {
957 print STDERR "ERROR($0):
958 Insufficient column entries in Word Vector at index=$feature_offset
959 in WORD VECtor file <$wordvec_file>.\n";
960 exit 1;
961 }
962 set($word_vector,$col,$value);
963 }
964 $context_vector->inplace->plus($word_vector,0);
965 $words++;
966 }
967 # sparse word vectors are loaded in @word_vectors
968 else
969 {
970 $context_vector->add($word_vectors[$feature_offset]);
971 $words++;
972 }
973 }
974 }
975 }
976  
977 if(!defined $opt_binary)
978 {
979 if($words != 0)
980 {
981 if(defined $opt_dense)
982 {
983 $context_vector.=$context_vector/$words;
984 }
985 else
986 {
987 $context_vector->div($words);
988 }
989 }
990 }
991 }
992
993 # <context> start
994 if(/<context>/)
995 {
996 # no <instance> open
997 if(!defined $instance)
998 {
999 print STDERR "ERROR($0):
1000 Missing <instance> tag before the <context> tag at line <$line_num>
1001 in SVAL2 file <$infile>.\n";
1002 exit 1;
1003 }
1004  
1005 # no sense tag for this instance
1006 if(!defined $key_table{$instance})
1007 {
1008 $sense="NOTAG";
1009 $key_table{$instance}{$sense}=1;
1010 }
1011 $data_start=1;
1012 if(defined $opt_dense)
1013 {
1014 $context_vector->inplace->zeroes;
1015 }
1016 else
1017 {
1018 $context_vector->free;
1019 }
1020 $words=0;
1021 }
1022 }
1023  
1024 close TEMP;
1025  
1026  
1027 ##############################################################################
1028  
1029 # =========================
1030 # OUTPUT SECTION
1031 # =========================
1032  
1033 # =====================
1034 # Creating KEY file
1035 # =====================
1036  
1037 # KEY file is automatically created by the program
1038 # and preserves the instance ids and sense tags of the
1039 # SVAL-2 instances
1040  
1041 $keyfile="keyfile" . time() . ".key";
1042 if(-e $keyfile)
1043 {
1044 print STDERR "ERROR($0):
1045 System generated KEY file <$keyfile> should not already exist.\n";
1046 exit 1;
1047 }
1048  
1049 open(KEY,">$keyfile") || die "ERROR($0):
1050 Error(code=$!) in opening system generated KEY file <$keyfile>.\n";
1051  
1052 foreach $instance (@instances)
1053 {
1054 print KEY "<instance id=\"$instance\"\/> ";
1055 foreach $sense (sort keys %{$key_table{$instance}})
1056 {
1057 print KEY "<sense id=\"$sense\"\/> ";
1058 }
1059 print KEY "\n";
1060 }
1061  
1062  
1063 # =========================
1064 # Printing output vectors
1065 # =========================
1066  
1067 # first line should show the KEY filename if --showkey is ON
1068 if(defined $opt_showkey)
1069 {
1070 print "<keyfile name=\"$keyfile\"\/>\n";
1071 undef $opt_showkey;
1072 }
1073  
1074 print scalar(@instances) . " $cols";
1075  
1076 if(!defined $opt_dense)
1077 {
1078 print " $nnz";
1079 }
1080 print "\n";
1081  
1082 # this is followed by the actual context vectors
1083  
1084 open(TEMP,$tempfile) || die "ERROR($0):
1085 Error(code=$!) in opening internal temporary file <$tempfile>.\n";
1086  
1087 while(<TEMP>)
1088 {
1089 print;
1090 }
1091 close TEMP;
1092  
1093 # deleting TEMP as the program is sucessfully finished
1094 unlink "$tempfile";
1095  
1096 ##############################################################################
1097  
1098 # ==========================
1099 # Creating Cluto files
1100 # ==========================
1101  
1102 # opening rlabel file
1103 if(defined $opt_rlabel)
1104 {
1105 $rlabel=$opt_rlabel;
1106 if(-e $rlabel)
1107 {
1108 print STDERR "Warning($0):
1109 Row label file <$rlabel> already exists, overwrite (y/n)? ";
1110 $ans=<STDIN>;
1111 }
1112 if(!-e $rlabel || $ans=~/Y|y/)
1113 {
1114 open(RLAB,">$rlabel") || die "Error($0):
1115 Error(code=$!) in opening the Row Label file <$rlabel>.\n";
1116 }
1117 else
1118 {
1119 undef $rlabel;
1120 }
1121 }
1122  
1123 # opening rclass file
1124 if(defined $opt_rclass)
1125 {
1126 $rclass=$opt_rclass;
1127 if(-e $rclass)
1128 {
1129 print STDERR "Warning($0):
1130 Class label file <$rclass> already exists, overwrite (y/n)? ";
1131 $ans=<STDIN>;
1132 }
1133 if(!-e $rclass || $ans=~/Y|y/)
1134 {
1135 open(RCL,">$rclass") || die "Error($0):
1136 Error(code=$!) in opening the Class Label file <$rclass>.\n";
1137 }
1138 else
1139 {
1140 undef $rclass;
1141 }
1142 }
1143  
1144 # printing rlabels and rclasses
1145 foreach $instance (@instances)
1146 {
1147 if(defined $rlabel)
1148 {
1149 print RLAB "$instance\n";
1150 }
1151 if(defined $rclass)
1152 {
1153 @senses=sort keys %{$key_table{$instance}};
1154 if(scalar(@senses) > 1)
1155 {
1156 print STDERR "ERROR($0):
1157 Instance <$instance> can not have multiple senses in RCLASSFILE.\n";
1158 exit 1;
1159 }
1160 print RCL "$senses[0]\n";
1161 }
1162 }
1163  
1164 ##############################################################################
1165  
1166 # ==========================
1167 # SUBROUTINE SECTION
1168 # ==========================
1169  
1170 #-----------------------------------------------------------------------------
1171 #show minimal usage message
1172 sub showminimal()
1173 {
1174 print "Usage: order2vec.pl [OPTIONS] SVAL2 WORDVEC FEATURE_REGEX";
1175 print "\nTYPE order2vec.pl --help for help\n";
1176 }
1177  
1178 #-----------------------------------------------------------------------------
1179 #show help
1180 sub showhelp()
1181 {
1182 print "Usage: order2vec.pl [OPTIONS] SVAL2 WORDVEC FEATURE_REGEX
1183  
1184 Creates second order context vectors for the instances in the given SVAL2
1185 file by averaging WORD VECtors of FEATUREs that appear in the contexts.
1186  
1187 SVAL2
1188 A tokenized, preprocessed and well formatted Senseval-2 instance file
1189 containing instances whose context vectors are to be generated.
1190  
1191 WORDVEC
1192 Word vectors as created by program wordvec.pl
1193
1194 OR
1195
1196 Feature vectors as created by using the --transpose option of
1197 order1vec.pl
1198  
1199 FEATURE_REGEX
1200 A file created by running nsp2regex.pl on wordvec.pl's --feats option
1201 output while creating the WORDVEC file
1202
1203 OR
1204
1205 A file created by using the --testregex option of order1vec.pl, when
1206 the WORDVEC file is created using its --transpose option.
1207  
1208 OPTIONS:
1209  
1210 --binary
1211 Creates binary context vectors by taking binary OR of the WORD VECtors
1212 of FEATUREs matched in the context. By default, order2vec takes
1213 arithmatic average of the WORD VECtors.
1214  
1215 --dense
1216 By default, order2vec assumes WORDVEC in sparse format and creates
1217 output context vectors in sparse format as well. Select --dense if WORD
1218 VECtors are in dense format. --dense will also create output context
1219 vectors in dense format.
1220  
1221 --format FORM
1222 Specifies the numeric format for dense WORD VECtors. If --dense is
1223 selected, WORDVEC has to be formatted, meaning, all WORDVEC entries
1224 should be represented using exactly same numeric format and should
1225 occupy same number of digit spaces. Sparse word vectors need not be
1226 formatted.
1227  
1228 --format can also be used to specify the format for output vectors
1229 (sparse or dense).
1230  
1231 Default format is f16.10 when --binary is OFF and i2 when --binary
1232 is ON.
1233  
1234 --showkey
1235 Displays the system generated KEY file name on the first line of
1236 STDOUT.
1237  
1238 --rlabel RLABELFILE
1239 Writes row labels to RLABELFILE which can be given to vcluster's
1240 --rlabelfile option.
1241
1242 --rclass RCLASSFILE
1243 Writes sense ids to RCLASSFILE which can be given to vcluster's
1244 --rclassfile option.
1245  
1246 --help
1247 Displays this message.
1248  
1249 --version
1250 Displays the version information.
1251  
1252 Type 'perldoc order2vec.pl' to view detailed documentation of order2vec.\n";
1253 }
1254  
1255 #------------------------------------------------------------------------------
1256 #version information
1257 sub showversion()
1258 {
1259 print '$Id: order2vec.pl,v 1.33 2008/03/30 23:31:16 tpederse Exp $';
1260 print "\nConvert Senseval-2 contexts into second order feature vectors\n";
1261 # print "\nCopyright (c) 2002-2006, Ted Pedersen, Amruta Purandare, & Mahesh Joshi\n";
1262 # print "order2vec.pl - Version 0.3\n";
1263 # print "Creates second order context vectors.\n";
1264 # print "Date of Last Update: 07/29/2006\n";
1265 }
1266  
1267 #############################################################################
1268