Source

bllip-parser / first-stage / PARSE / oparseIt.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
/*
 * Copyright 1999, 2005 Brown University, Providence, RI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.  You may obtain
 * a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

#include <pthread.h>
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <math.h>
#include "GotIter.h"
#include "Wrd.h"
#include "InputTree.h"
#include "Bchart.h"
#include "ECArgs.h"
#include "MeChart.h"
#include "extraMain.h"
#include "AnsHeap.h"
#include "UnitRules.h"
#include "Params.h"
#include "TimeIt.h"
#include "ewDciTokStrm.h"
#include "Link.h"
#include "utils.h"
 
//-----------------------
// Definitions
//-----------------------

/* In order to print out the data in the correct order each
thread has it's own PrintStack which stores the output data
(printStrict) until it is time to print it out in order.
*/
typedef struct printStruct{
  int                sentenceCount;
  int                numDiff;
  vector<InputTree*> trees;
  vector<double>     probs;
  string             name;
} printStruct;
typedef list<printStruct> PrintStack;

//-----------------------
// Prototypes
//-----------------------

static void* mainLoop (void* arg);
static void printSkipped( SentRep *srp, MeChart *chart,PrintStack& pstk, printStruct& ps);
static void workOnPrintStack(PrintStack* printStack);

//-----------------------
// Constants
//-----------------------

static const unsigned int SLEEPTIME = 1;
static const int DEFAULT_NTHREAD = 2;
static const double log600 = log2(600.0);

//-----------------------
// Globals
//-----------------------

/* Syncronize two times for each sentence, one to read it in 
from a common file, and one to write it out to a common file. */
static pthread_mutex_t readlock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t writelock = PTHREAD_MUTEX_INITIALIZER;

int sentenceCount=0; // allow extern'ing for error messages
static int printCount=0;
static ewDciTokStrm* tokStream = NULL;
static istream* nontokStream = NULL;
static Params params;

//------------------------------

static void usage(const char *program) 
{
  cerr << "\n*** Usage information for " << program << " ***\n";

  cerr << "\nDefault use: " << program << " DATA/ [input file]\n";
  cerr << "If no input file supplied, stdin is assumed.\n";

  cerr << "\nRun mode:\n";
  cerr << "-M: language modeling flag\n";
  cerr << "-N: n-best parsing\n"; 

  cerr << "\nPerformance/Quality:\n";
  cerr << "-s: small training corpus flag\n";
  cerr << "-t: number of threads [2]\n";
  cerr << "-T: over-parsing level [210]\n";

  cerr << "\nInput:\n";
  cerr << "-C: case-insensitive flag\n";
  cerr << "-K: pre-tokenized data flag\n";
  cerr << "-l: skip sentences exceeding specified length [100]\n";
  cerr << "-L: language selection (En|Ch) [En]\n";
  cerr << "-n: process every Nth sentence only\n";

  cerr << "\nOutput:\n";
  cerr << "-d: print debug info at specified detail level\n";
  cerr << "-P: pretty-print flag\n";
  cerr << "-S: silent failure flag\n";

  //cerr << "-t: report timings\n"; // this was in comment at start of main but appears deprecated

  cerr << "\nSee README file for additional information.\n\n";
}

//------------------------------

int
main(int argc, char *argv[])
{
  if (argc==1) {
    usage(argv[0]);
    return 1;
  }

  ECArgs args( argc, argv );
  params.init( args );
  int numThreads=DEFAULT_NTHREAD;
  if(args.isset('t')) 
    numThreads = atoi(args.value('t').c_str());

  TimeIt timeIt;
  ECString  path( args.arg( 0 ) );
  generalInit(path);

  ECString flnm = "dummy";
  if(args.nargs()==2) flnm = args.arg(1);
  if(Bchart::tokenize)
    {
      tokStream = new ewDciTokStrm(flnm);
      if(args.nargs() ==1) tokStream->useCin = 1;
    }
  if(args.nargs()==2) nontokStream = new ifstream(args.arg(1).c_str());
  else nontokStream = &cin;

  pthread_t thread[MAXNUMTHREADS];
  int id[MAXNUMTHREADS];
  int i;
  for(i = 0 ; i < numThreads  ; i++){
    id[i]=i;
    pthread_create(&thread[i],0,mainLoop, &id[i]);
  }
  for(i=0; i<numThreads; i++){
    pthread_join(thread[i],0);
  }
  pthread_exit(0);
  return 0;
}

//------------------------------

static void*
mainLoop(void* arg)
{
  int *id = reinterpret_cast<int *>(arg);

  PrintStack printStack;
  for( ; ; )
    {
      SentRep* srp = new SentRep(params.maxSentLen);

      pthread_mutex_lock(&readlock);
      if(Bchart::tokenize)
	*tokStream >> *srp;
      else 
	*nontokStream >> *srp;
      int locCount = sentenceCount++;
      pthread_mutex_unlock(&readlock);

      if( !params.field().in(sentenceCount) ) continue;

      printStruct printS;
      printS.name = srp->getName();
      printS.sentenceCount = locCount;
      printS.numDiff = 0;

      int len = srp->length();
      if (len == 0) break;
      if (len > params.maxSentLen) 
	{
	  ECString msg("skipping sentence longer than specified limit of ");
	  msg += intToString(params.maxSentLen);
	  WARN( msg.c_str() );
	  printSkipped(srp,NULL,printStack,printS);
	  continue;
	}

      // handle input containing reserved word Bchart::HEADWORD_S1; could probably do 
      // better (like undo replacement before printing) but this seems sufficient.
      int i;
      for (i = 0; i < len; ++i) 
	{
	  ECString& w = ((*srp)[i]).lexeme();
	  if (w == Bchart::HEADWORD_S1) 
	    {
	      ECString msg = ECString("Replacing reserved token \"") + Bchart::HEADWORD_S1;
	      msg += "\" at index " + intToString(i) + " of input with token \"^^^\"";
	      WARN( msg.c_str() );
	      w = "^^^";
	    }
	}

      MeChart*	chart = new MeChart( *srp,*id );
       
      chart->parse( );

      Item* topS = chart->topS();
      if(!topS)
	{
	  WARN( "Parse failed: !topS" );
	  printSkipped(srp,chart,printStack,printS);
	  delete chart;
	  continue;
	}
      // compute the outside probabilities on the items so that we can
      // skip doing detailed computations on the really bad ones 
      chart->set_Alphas();

      Bst& bst = chart->findMapParse();
      if( bst.empty())
	{
	  WARN( "Parse failed: chart->findMapParse().empty()" );
	  printSkipped(srp,chart,printStack,printS);
	  delete chart;
	  continue;
	}
      if(Feature::isLM)
	{
	  double lgram = log2(bst.sum());
	  lgram -= (len*log600);
	  double pgram = pow(2,lgram);
	  double iptri =chart->triGram();;
	  double ltri = (log2(iptri)-len*log600);
	  double ptri = pow(2.0,ltri);
	  double pcomb = (0.667 * pgram)+(0.333 * ptri);
	  double lmix = log2(pcomb);
	  if(locCount%10==9)cout << lgram << "\t" << ltri << "\t" << lmix << "\n";
	}
      int numVersions = 0;
      Link diffs(0);
      //cerr << "Need num diff: " << Bchart::Nth << endl;
      for(numVersions = 0 ; ; numVersions++)
	{
	  short pos = 0;
	  Val* v = bst.next(numVersions);
	  if(!v) break;
	  double vp = v->prob();
	  if(vp == 0) break;
	  if(isnan(vp)) break;
	  if(isinf(vp)) break;
	  InputTree* mapparse=inputTreeFromBsts(v,pos,*srp);
	  bool isU;
	  int cnt = 0;
	  diffs.is_unique(mapparse, isU,cnt);
	  if(cnt != len)
	    {
	      cerr << "Bad length parse for: " << *srp << endl;
	      cerr << *mapparse << endl;
	      assert(cnt == len);
	    }
	  if(isU)
	    {
	      printS.probs.push_back(v->prob());
	      printS.trees.push_back(mapparse);
	      printS.numDiff++;
	    }
	  else
	    {
	      delete mapparse;
	    }
	  if(printS.numDiff >= Bchart::Nth) break;
	  if(numVersions > 20000) break;
	}
      if( printS.numDiff == 0)
	{
	  WARN( "Parse failed from 0, inf or nan probabililty" );
	  printSkipped(srp,chart,printStack,printS);
	  delete chart;
	  continue;
	}

      /* put the sentence with which we just finished at the end of the printStack*/
      printStack.push_back(printS);
      workOnPrintStack(&printStack);
      delete chart;
      delete srp;
    }
  while(!printStack.empty()){
    sleep(SLEEPTIME);
    workOnPrintStack(&printStack);
  }

  return 0;
}

//------------------------------

static const ECString& getPOS(Wrd& w, MeChart *chart)
{
  list<float>& wpl = chart->wordPlist(&w, w.loc());      
  list<float>::iterator wpli = wpl.begin();
  float max=-1.0;
  int termInt = (int)max;
  for( ; wpli != wpl.end() ; wpli++)
    {
      int term = (int)(*wpli);
      wpli++;
      // p*(pos|w) = argmax(pos){ p(w|pos) * p(pos) } 
      double prob = *wpli * chart->pT(term); 
      if (prob > max) {
	termInt = term;
	max = prob;
      }
    }
  const Term* nxtTerm = Term::fromInt(termInt);
  return nxtTerm->name();
}

//------------------------------
static void makeFlat(SentRep *srp, MeChart *chart, InputTree*& t)
{
  bool allocated=false;
  if (chart == NULL && srp->length() < MAXSENTLEN) 
    {
      chart = new MeChart( *srp,0);
      allocated=true;
    }

  // 05/30/06 ML: use something short for pretend POS tag
  const ECString UNK="NN"; 
  InputTrees dummy1;
  InputTree* st= new InputTree(0,srp->length(),"","S","",dummy1,NULL,NULL);
  InputTrees dummy2;
  dummy2.push_back(st);
  InputTree* s1 =new InputTree(0,srp->length(),"","S1","",dummy2,NULL,NULL);
  st->parentSet()=s1;
  InputTrees its;
  for (int xx = 0; xx < srp->length(); ++xx)
    {
      Wrd& w = (*srp)[xx];
      const ECString& pos = (chart!=NULL) ? getPOS(w,chart) : UNK;
      InputTree* nt= new InputTree(xx, xx+1, w.lexeme(), pos, "",
				   dummy1,st, NULL);
      its.push_back(nt);
    }
  st->subTrees()=its;
  t=s1;
}

//------------------------------

static void
printSkipped(SentRep *srp, MeChart *chart,PrintStack& printStack,printStruct& printS)
{
  // stderr
  if (!Bchart::silent) 
      cerr << *srp << "\n\n";

  // stdout
  // ML 05/04/06: Ensure every input sentence produces an output parse tree,
  // at least in 1-best mode. The default tree is just a flat S.
  if(Feature::isLM)
    {
      double veryLow=-1000;
      cout << veryLow << "\t" << veryLow << "\t" << veryLow << "\n";
    }
  InputTree* dummy;
  makeFlat(srp,chart,dummy);
  printS.probs.push_back(10e-200);
  printS.trees.push_back(dummy);
  printS.numDiff++;
  printStack.push_back(printS);
  workOnPrintStack(&printStack);
}

//------------------------------

static void
workOnPrintStack(PrintStack* printStack)
{
  int i;
  int numPrinted;
  PrintStack::iterator psi = printStack->begin();
  /* now look at each item from the front of the print stack
     to see if it should be printed now */
  pthread_mutex_lock(&writelock);
  for( numPrinted =0; psi != printStack->end(); numPrinted++ )
    {
      printStruct& pstr=(*psi);
      if(pstr.sentenceCount != printCount) break;
      if(Bchart::Nth > 1) {
	ECString index = pstr.name.empty() ? intToString(sentenceCount)
	  : pstr.name;
	cout << pstr.numDiff << "\t" << index <<"\n";
      }
      printCount++;
      for(i = 0 ; i < pstr.numDiff ; i++)
	{
	  InputTree*  mapparse = pstr.trees[i];
	  assert(mapparse);
	  double logP =log2(pstr.probs[i]);
	  logP -= (mapparse->length()*log600);
	  if (Bchart::Nth > 1) 
	    cout << logP << "\n";
	  else if (!pstr.name.empty())	
	    cout << "<" << pstr.name << "> "; 
	      
	  if (Bchart::prettyPrint) 
	    cout << *mapparse << "\n\n";
	  else
	    {
	      mapparse->printproper(cout);
	      cout << "\n";
	    }
	  delete mapparse;

	}
      psi++;
      cout << endl;
    }
  pthread_mutex_unlock(&writelock);
  for(i = 0 ; i < numPrinted ; i++) printStack->pop_front();
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.