Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Permutation.cpp « mert - github.com/moses-smt/mosesdecoder.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b32a1ed0dc88b56d62700fb204a8debe630260d5 (plain)
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
/*
 *  Permutation.cpp
 *  met - Minimum Error Training
 *
 *  Created by Alexandra Birch 18/11/09.
 *
 */

#include <fstream>
#include <sstream>
#include <cmath>
#include "Permutation.h"
#include "Util.h"

using namespace std;

namespace MosesTuning
{


Permutation::Permutation(const string &alignment, const int sourceLength, const int targetLength )
{
  if (sourceLength > 0) {
    set(alignment, sourceLength);
  }
  m_targetLength = targetLength;
}

size_t Permutation::getLength() const
{
  return int(m_array.size());
}
void Permutation::dump() const
{
  int j=0;
  for (vector<int>::const_iterator i = m_array.begin(); i !=m_array.end(); i++) {
    cout << "(";
    cout << j << ":" << *i ;
    cout << "), ";
    j++;
  }
  cout << endl;
}


//Sent alignment string
//Eg: "0-1 0-0 1-2 3-0 4-5 6-7 "
// Inidiviual word alignments which can be one-one,
// or null aligned, or many-many. The format is sourcepos - targetpos
//Its the output of the berkley aligner subtracting 1 from each number
//sourceLength needed because last source words might not be aligned
void Permutation::set(const string & alignment,const int sourceLength)
{

  //cout << "******** Permutation::set :" << alignment << ": len : " << sourceLength <<endl;

  if(sourceLength <= 0) {
    //not found
    cerr << "Source sentence length not positive:"<< sourceLength << endl;
    exit(0);
  }

  if (alignment.length() <= 0) {
    //alignment empty - could happen but not good
    cerr << "Alignment string empty:"<< alignment << endl;
  }

  //Tokenise on whitespace
  string buf; // Have a buffer string
  stringstream ss(alignment); // Insert the string into a stream
  vector<string> tokens; // Create vector to hold our words
  while (ss >> buf)
    tokens.push_back(buf);

  vector<int> tempPerm(sourceLength, -1);
  //Set tempPerm to have one target position per source position
  for (size_t i=0; i<tokens.size(); i++) {
    string temp = tokens[i];
    int posDelimeter = temp.find("-");
    if(posDelimeter == int(string::npos)) {
      cerr << "Delimiter not found - :"<< tokens[i] << endl;
      exit(1);
    }
    int sourcePos = atoi((temp.substr(0, posDelimeter)).c_str());
    int targetPos = atoi((temp.substr(posDelimeter+1)).c_str());
    //cout << "SP:" << sourcePos << " TP:" << targetPos << endl;
    if (sourcePos > sourceLength) {
      cerr << "Source sentence length:" << sourceLength << " is smaller than alignment source position:" << sourcePos << endl;
      cerr << "******** Permutation::set :" << alignment << ": len : " << sourceLength <<endl;
      exit(1);
    }
    //If have multiple target pos aligned to one source,
    // then ignore all but first alignment
    if (tempPerm[sourcePos] == -1 || tempPerm[sourcePos] > targetPos) {
      tempPerm[sourcePos] = targetPos;
    }
  }

  //TODO
  //Set final permutation in m_array
  //Take care of: source - null
  //              multiple_source - one target
  //              unaligned target
  // Input: 1-9 2-1 4-3 4-4 5-6 6-6 7-6 8-8
  // Convert source: 1  2  3 4 5 6 7 8
  //         target: 9  1 -1 3 6 6 6 8 -> 8 1 2 3 4 5 6 7

  // 1st step: Add null aligned source to previous alignment
  //         target: 9  1 -1 3 6 6 6 8 -> 9  1 1 3 6 6 6 8
  int last=0;
  m_array.assign(sourceLength, -1);
  //get a searcheable index
  multimap<int, int> invMap;
  multimap<int, int>::iterator it;
  //cout << " SourceP  -> TargetP " << endl;
  for (size_t i=0; i<tempPerm.size(); i++) {
    if (tempPerm[i] == -1) {
      tempPerm[i] = last;
    } else {
      last = tempPerm[i];
    }
    //cout << i << " -> " << tempPerm[i] << endl;
    //Key is target pos, value is source pos
    invMap.insert(pair<int,int>(tempPerm[i],int(i)));
  }



  // 2nd step: Get target into index of multimap and sort
  // Convert source: 1  2  3 4 5 6 7 8
  //         target: 9  1  0 3 6 6 6 8 -> 0 1 3 6 6 6 8 9
  //         source:                      3 2 4 5 6 7 8 1
  int i=0;
  //cout << " TargetP  => SourceP : TargetIndex " << endl;
  for ( it=invMap.begin() ; it != invMap.end(); it++ ) {
    //cout << (*it).first << " => " << (*it).second << " : " << i << endl;
    //find source position
    m_array[(*it).second] = i;
    i++;
  }

  bool ok = checkValidPermutation(m_array);
  //dump();
  if (!ok) {
    throw runtime_error(" Created invalid permutation");
  }
}

//Static
vector<int> Permutation::invert(const vector<int> & inVector)
{
  vector<int> outVector(inVector.size());
  for (size_t i=0; i<inVector.size(); i++) {
    outVector[inVector[i]] = int(i);
  }
  return outVector;
}

//Static
//Permutations start at 0
bool Permutation::checkValidPermutation(vector<int> const  & inVector)
{
  vector<int> test(inVector.size(),-1);
  for (size_t i=0; i< inVector.size(); i++) {
    //No multiple entries of same value allowed
    if (test[inVector[i]] > -1) {
      cerr << "Permutation error: multiple entries of same value\n" << endl;
      return false;
    }
    test[inVector[i]] ++;
  }
  for (size_t i=0; i<inVector.size(); i++) {
    //No holes allowed
    if (test[inVector[i]] == -1) {
      cerr << "Permutation error: missing values\n" << endl;
      return false;
    }
  }
  return true;
}


//TODO default to HAMMING
//Note: it returns the distance that is not normalised
float Permutation::distance(const Permutation &permCompare, const distanceMetric_t &type) const
{
  float score=0;

  //bool debug= (verboselevel()>3); // TODO: fix verboselevel()
  bool debug=false;
  if (debug) {
    cout << "*****Permutation::distance" <<endl;
    cout << "Hypo:" << endl;
    dump();
    cout << "Ref: " << endl;
    permCompare.dump();
  }

  if (type == HAMMING_DISTANCE) {
    score = calculateHamming(permCompare);
  } else if (type == KENDALL_DISTANCE) {
    score = calculateKendall(permCompare);
  } else {
    throw runtime_error("Distance type not valid");
  }

  float brevityPenalty = 1.0 - (float) permCompare.getTargetLength()/getTargetLength()  ;//reflength divided by trans length
  if (brevityPenalty < 0.0) {
    score = score * exp(brevityPenalty);
  }

  if (debug) {
    cout << "Distance type:" <<  type << endl;
    cout << "Score: "<< score << endl;
  }
  return score;
}


float Permutation::calculateHamming(const Permutation & compare) const
{
  float score=0;
  vector<int> compareArray = compare.getArray();
  if (getLength() != compare.getLength()) {
    cerr << "1stperm: " << getLength() << " 2ndperm: " << compare.getLength() << endl;
    throw runtime_error("Length of permutations not equal");
  }
  if (getLength() == 0) {
    cerr << "Empty permutation" << endl;
    return 0;
  }
  for (size_t i=0; i<getLength(); i++) {
    if (m_array[i] != compareArray[i]) {
      score++;
    }

  }
  score = 1 - (score / getLength());
  return score;
}

float Permutation::calculateKendall(const Permutation & compare) const
{
  float score=0;
  vector<int> compareArray = compare.getArray();
  if (getLength() != compare.getLength()) {
    cerr << "1stperm: " << getLength() << " 2ndperm: " << compare.getLength() << endl;
    throw runtime_error("Length of permutations not equal");
  }
  if (getLength() == 0) {
    cerr << "Empty permutation" << endl;
    return 0;
  }
  if (getLength() == 1) {
    cerr << "One-word sentence. Kendall score = 1" << endl;
    return 1;
  }
  for (size_t i=0; i<getLength(); i++) {
    for (size_t j=0; j<getLength(); j++) {
      if ((m_array[i] < m_array[j]) && (compareArray[i] > compareArray[j])) {
        score++;
      }
    }
  }
  score = (score / ((getLength()*getLength() - getLength()) /2  ) );
  //Adjusted Kendall's tau correlates better with human judgements
  score = sqrt (score);
  score = 1 - score;

  return score;
}

vector<int> Permutation::getArray() const
{
  vector<int> ret = m_array;
  return ret;
}

//Static
//This function is called with test which is
// the 5th field in moses nbest output when called with -include-alignment-in-n-best
//eg. 0=0 1-2=1-2 3=3 4=4 5=5 6=6 7-9=7-8 10=9 11-13=10-11 (source-target)
string Permutation::convertMosesToStandard(string const & alignment)
{
  if (alignment.length() == 0) {
    cerr << "Alignment input string empty" << endl;
  }
  string working = alignment;
  string out;

  stringstream oss;
  while (working.length() > 0) {
    string align;
    getNextPound(working,align," ");

    //If found an alignment
    if (align.length() > 0) {
      size_t posDelimeter = align.find("=");
      if(posDelimeter== string::npos) {
        cerr << "Delimiter not found = :"<< align << endl;
        exit(0);
      }
      int firstSourcePos,lastSourcePos,firstTargetPos,lastTargetPos;
      string sourcePoss = align.substr(0, posDelimeter);
      string targetPoss = align.substr(posDelimeter+1);
      posDelimeter = sourcePoss.find("-");
      if(posDelimeter < string::npos) {
        firstSourcePos = atoi((sourcePoss.substr(0, posDelimeter)).c_str());
        lastSourcePos  = atoi((sourcePoss.substr(posDelimeter+1)).c_str());
      } else {
        firstSourcePos = atoi(sourcePoss.c_str());
        lastSourcePos = firstSourcePos;
      }
      posDelimeter = targetPoss.find("-");
      if(posDelimeter < string::npos) {
        firstTargetPos = atoi((targetPoss.substr(0, posDelimeter)).c_str());
        lastTargetPos  = atoi((targetPoss.substr(posDelimeter+1)).c_str());
      } else {
        firstTargetPos = atoi(targetPoss.c_str());
        lastTargetPos = firstTargetPos;
      }
      for (int i = firstSourcePos; i <= lastSourcePos; i++) {
        for (int j = firstTargetPos; j <= lastTargetPos; j++) {
          oss << i << "-" << j << " ";
        }
      }

    } //else case where two spaces ?
  }
  out = oss.str();
  //cout <<  "ConverttoStandard: " << out << endl;

  return out;
}

}