PSTree.java 15.1 KB
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
/**
 *
 */
package is2.data;

import java.util.ArrayList;
import java.util.Collections;

import is2.util.DB;

/**
 * @author Dr. Bernd Bohnet, 17.01.2011
 *
 *
 */
public class PSTree {

	int wordCount = 0;
	public String entries[];
	public String lemmas[];
	public int head[];
	public String pos[];
	public int[] ok;
	public int non;
	public int terminalCount;
	public String[] morph;

	public int[] forms;
	public int[] phrases;
	public int[][] psfeats;
	public int[] ppos;

	/**
	 * @param d
	 */
	public PSTree(SentenceData09 d) {
		create(d.length() - 1, d.length() * 20);
		for (int i = 1; i < d.length(); i++) {
			entries[i - 1] = d.forms[i];
			pos[i - 1] = d.ppos[i];
		}
	}

	/**
	 * Create an undefined phrase tree
	 */
	public PSTree() {
	}

	/**
	 * @param terminals
	 * @param nonTerminals
	 */
	public void create(int terminals, int nonTerminals) {
		entries = new String[terminals + nonTerminals];
		pos = new String[terminals + nonTerminals];
		head = new int[terminals + nonTerminals];
		lemmas = new String[terminals + nonTerminals];
		morph = new String[terminals + nonTerminals];
		non = terminals;
		wordCount = terminals;

		for (int i = terminals + 1; i < head.length; i++)
			head[i] = -1;
	}

	@Override
	public String toString() {

		StringBuffer s = new StringBuffer();

		for (int i = 0; i < entries.length; i++) {
			if (head[i] == -1 && entries[i] == null)
				break;

			s.append(i + "\t" + pos[i] + "\t" + entries[i] + "\t" + head[i] + (ok == null ? "" : ("\t" + (ok[i] == 1)))
					+ " \n");

		}
		// DB.println("entries "+entries.length);
		return s.toString();
	}

	/**
	 * @return
	 */
	public boolean containsNull() {
		for (int k = 0; k < wordCount - 1; k++) {
			if (entries[k] == null)
				return true;
		}
		return false;
	}

	public int equals(SentenceData09 s) {

		int j = 1; // starts with root
		for (int i = 0; i < terminalCount - 1; i++) {

			// if (s.forms[j].equals("erschrekkend")) s.forms[j]="erschreckend";

			if (s.forms.length < j) {
				DB.println("" + s + " " + this.toString());
				return i;

			}

			if (!entries[i].equals(s.forms[j])) {
				// System.out.println("ps "+entries[i]+" != ds "+s.forms[j]);
				// Rolls-Royce
				if (entries[i].startsWith(s.forms[j]) && s.forms.length > i + 2 && s.forms[j + 1].equals("-")) {
					j += 2;
					if (entries[i].contains(s.forms[j - 1]) && s.forms.length > i + 3 && s.forms[j + 1].equals("-")) {
						j += 2; // &&
						// System.out.println("s.forms[j] "+s.forms[j]+"
						// s.forms[j-1] "+s.forms[j-1]+" "+entries[i]);
						if (entries[i].contains(s.forms[j - 1]) && s.forms.length > i + 3
								&& s.forms[j + 1].equals("-")) {
							j += 2; // &&
							// System.out.println("s.forms[j] "+s.forms[j]+"
							// s.forms[j-1] "+s.forms[j-1]+" "+entries[i]);
						}
					}
					// Interstate\/Johnson
				} else if (entries[i].startsWith(s.forms[j]) && s.forms.length > i + 2 && s.forms[j + 1].equals("/")) {
					j += 2;
					if (entries[i].contains(s.forms[j - 1]) && s.forms.length > i + 3 && s.forms[j + 1].equals("/")) {
						j += 2; // &&
						// System.out.println("s.forms[j] "+s.forms[j]+"
						// s.forms[j-1] "+s.forms[j-1]+" "+entries[i]);
					}

					// U.S.-Japan -> U . S . - Japan
				} else if (entries[i].startsWith(s.forms[j]) && s.forms.length > i + 2 && s.forms[j + 1].equals(".")) {
					j += 2;
					if (entries[i].contains(s.forms[j - 1]) && s.forms.length > i + 3 && s.forms[j + 1].equals(".")) {
						j += 2; // &&
						// System.out.println("s.forms[j] "+s.forms[j]+"
						// s.forms[j-1] "+s.forms[j-1]+" "+entries[i]);
					}
				} else if (entries[i].startsWith(s.forms[j]) && s.forms.length > i + 1 && s.forms[j + 1].equals("'S")) {
					j += 1;

				} else {

					// chech those !!!
					// System.out.print("entry "+entries[i]+" form
					// "+s.forms[j]+" ");
					return j;
				}

			}
			j++;

		}

		// without root
		return s.length();
		// return j;

	}

	/**
	 * @param dn
	 * @return
	 */
	public int getPS(int dn) {

		return this.head[dn - 1];
	}

	/**
	 * @param dn
	 * @param n
	 * @param commonHead
	 *            the common head in the phrase structure
	 * @return
	 */
	public String getChain(int dn, int n, int commonHead) {

		int pdn = dn - 1;
		// int phraseHead =head[pdh];

		// System.out.println("phrase head "+phraseHead+" common head
		// "+commonHead);

		int[] ch = new int[20];
		int head = this.head[pdn];
		int i = 0;
		ch[i++] = head;
		while (commonHead != head && head != 0) {

			head = this.head[head];
			ch[i++] = head;
		}
		StringBuffer chain = new StringBuffer();

		for (int k = 0; k < i; k++) {
			chain.append(entries[ch[k]]).append(" ");
		}
		return chain.toString();
	}

	/**
	 * @param dn
	 * @param n
	 * @return
	 */
	public int getCommonHead(int d, int dh) {
		int pdh = this.getPS(dh), pd = this.getPS(d);

		ArrayList<Integer> path2root = getPath2Root(pdh);

		// System.out.println("path 2 root "+path2root+" pdh "+pdh);

		for (int n : path2root) {
			int candidateHead = pd;
			while (candidateHead != 0 && candidateHead != -1) {
				if (n == candidateHead)
					return n;
				candidateHead = this.head[candidateHead];
			}
		}
		return -1;
	}

	/**
	 * @param pdh
	 */
	private ArrayList<Integer> getPath2Root(int pdh) {
		ArrayList<Integer> path = new ArrayList<Integer>();

		// restrict the number in case its a cycle which should never be
		for (int k = 0; k < 100; k++) {
			if (pdh == -1)
				break;
			path.add(pdh);
			pdh = this.head[pdh];
			if (pdh == 0)
				break;
		}
		return path;
	}

	/**
	 * Get operations to create root see operation in method getOperation
	 * 
	 * @param pr
	 */
	public String getOperationRoot(int pr) {

		StringBuffer o = new StringBuffer();
		int h = pr;
		int[] path = new int[10];
		// System.out.println(" start node "+pr);
		int k = 0;
		for (; k < 10; k++) {
			h = head[h];
			if (h == -1) {
				break;
			}
			path[k] = h;
			if (h == 0) {
				break;
			}

		}
		k -= 2;

		boolean first = true;
		for (; k >= 0; k--) {

			// create phrase
			if (first) {
				o.append("c:").append(entries[path[k]]);
				first = false;
			}

			// insert and create phrase
			else {
				o.append(":ci:").append(entries[path[k]]);
			}
		}

		// insert dependent node
		// if (o.length()>0)
		o.append(":in:d");
		// else o.append("in:d"); // insert root into nothing
		return o.toString();
	}

	/**
	 * Create operation to include dependency edges in phrase structure
	 * Operations: c - create ; i - insert ; in - insert (dependent) node ; up:X
	 * go the (phrase) X up ci create and insert ...
	 *
	 * @param dn
	 * @param n
	 * @param commonHead
	 * @return
	 */
	public String getOperation(int dn, int n, int commonHead) {

		StringBuffer o = new StringBuffer();

		// from n move up to common head, if needed
		int ph = n - 1, pd = dn - 1;

		int[] path = new int[20];
		int h = ph;

		boolean nth = false;
		for (int k = 0; k < 10; k++) {
			h = head[h];
			path[k] = h;
			if (nth)
				o.append(':');
			o.append("up:" + entries[h]);
			nth = true;
			if (h == commonHead)
				break;
		}

		// from common head to the node
		int k = 0;
		h = pd;
		for (; k < 10; k++) {
			h = head[h];
			path[k] = h;
			if (h == commonHead) {
				break;
			}

		}
		k -= 1;

		// boolean first=true;
		for (; k >= 0; k--) {

			// create phrase
			if (!nth) {
				o.append("ci:").append(entries[path[k]]);
				nth = true;
			}

			// insert and create phrase
			else {
				o.append(":ci:").append(entries[path[k]]);
			}
		}

		// insert dependent node
		o.append(":in:d");

		return o.toString();
	}

	/**
	 * @param ph
	 *            node in the phrase structure corresponding to the head in the
	 *            dependency structure
	 * @param pt
	 *            node in the prhase structure corresponding to the dependent in
	 *            the ds.
	 * @param check
	 * @return rules was applicable
	 */
	public boolean exec(String r, int ph, int pt, boolean check) {

		String o[] = r.split(":");

		int last = -1, headP = -1;

		// create root node

		// System.out.println("operation "+r+" "+ph+" "+pt);
		boolean done = true;
		for (int i = 0; i < o.length; i++) {

			if (o[i].equals("c")) {
				if (check)
					return true;

				if (ph < 0) {
					last = non++;
				}

				entries[non] = o[++i]; // create
				head[pt] = non;
				head[non] = last; // insert into root
				last = non++;
			} else if (o[i].equals("ci")) {
				if (check)
					return true;
				entries[non] = o[++i]; // create
				head[non] = last; // insert
				last = non;
				non++;
			} else if (o[i].equals("in") && o[i + 1].equals("d")) {
				if (check)
					return true;
				head[pt] = last; // insert
				i++; // move forward because of 'd'
			} else if (o[i].equals("up")) {

				if (ph == -1) {
					// System.out.println("ph is -1 please check this "+ph+"
					// there is a bug ");
					return false;
				}

				if (headP == -1)
					headP = head[ph];
				else
					headP = head[headP];

				try {
					if (headP == -1 || entries[headP] == null || !entries[headP].equals(o[i + 1]))
						return false;

				} catch (Exception e) {
					e.printStackTrace();
					System.out.println(
							"" + entries[headP] + " o[i+1] " + o[i + 1] + " " + headP + " " + this.terminalCount);
					// System.out.println(""+ this.toString());
					System.exit(0);
				}

				i++;
				last = headP;
			} else {
				done = false;
			}

		}

		return done;
	}

	/**
	 * More tolerant mapping
	 *
	 * @param ph
	 *            node in the phrase structure corresponding to the head in the
	 *            dependency structure
	 * @param pt
	 *            node in the prhase structure corresponding to the dependent in
	 *            the ds.
	 * @param check
	 * @return rules was applicable
	 */
	public boolean execT(String r, int ph, int pt, boolean check) {

		String o[] = r.split(":");

		int last = -1, headP = -1;

		int up = 0;

		boolean done = true;
		for (int i = 0; i < o.length; i++) {

			if (o[i].equals("c")) {
				if (check)
					return true;

				// create root node
				if (ph < 0) {
					last = non++;
				}

				entries[non] = o[++i]; // create
				head[pt] = non;
				head[non] = last; // insert into root
				last = non++;
			} else if (o[i].equals("ci")) {

				if (check)
					return true;
				entries[non] = o[++i]; // create
				head[non] = last; // insert
				last = non;
				non++;
			} else if (o[i].equals("in") && o[i + 1].equals("d")) {
				if (check)
					return true;

				// DB.println("hallo");

				if (last != -1)
					head[pt] = last; // insert

				// i am not sure if this does much good?

				// if (last ==-1)

				// done=true;

				i++; // move forward because of 'd'

			} else if (o[i].equals("up")) {
				up++;
				if (ph == -1) {
					return false;
				}

				if (headP == -1)
					headP = head[ph];
				else
					headP = head[headP];

				try {

					// tolerant mapping
					if (headP == -1 || entries[headP] == null || ((!entries[headP].equals(o[i + 1])) && up > 1))
						return false; // >1
					// && entries[headP].charAt(0)!=o[i+1].charAt(0)
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println(
							"" + entries[headP] + " o[i+1] " + o[i + 1] + " " + headP + " " + this.terminalCount);
				}

				i++;
				last = headP;
			} else {
				done = false;
			}

		}

		return done;
	}

	public final static boolean INSERT_NEWLINE = true;

	/**
	 * Convert to bracket format
	 * 
	 * @param newLine
	 * @return
	 */
	public String toPennBracket(boolean newLine) {

		StringBuffer b = new StringBuffer();
		ArrayList<Integer> current = null;// = new ArrayList<Integer>();
		int open = 0;
		for (int i = 0; i < terminalCount; i++) {
			ArrayList<Integer> path = getPathToRoot(i);

			ArrayList<Integer> diff = getDiffPath(path, current);

			boolean spaces = false;

			ArrayList<Integer> common = this.getDiffCommon(path, current);

			if (current != null && (current.size() > common.size())) {

				// close brackets
				for (int bc = 0; bc < current.size() - common.size(); bc++) {
					b.append(")");
					open--;
				}
				if (diff.size() == 0 && newLine)
					b.append("\n");
				spaces = true;
			}

			if (i != 0 && diff.size() > 0 && newLine)
				b.append("\n").append(createSpaces(open));

			for (int k = diff.size() - 1; k >= 0; k--) {
				open++;
				b.append("(" + (entries[path.get(k)] == null ? " " : entries[path.get(k)]));
				if (k != 0 && path.size() - 1 != k && newLine)
					b.append("\n").append(createSpaces(open));
				spaces = false;
			}
			if (spaces)
				b.append(createSpaces(open));
			else
				b.append(" ");

			String term = entries[i];
			if (term.equals("("))
				term = "-LRB-";
			if (term.equals(")"))
				term = "-RRB-";
			if (term.equals("{"))
				term = "-LCB-";
			if (term.equals("}"))
				term = "-RCB-";

			String ps = pos[i];
			if (ps.equals("("))
				ps = "-LRB-";
			if (ps.equals("$("))
				ps = "-LRB-";

			if (ps.equals(")"))
				ps = "-RRB-";
			if (ps.equals("{"))
				ps = "-LCB-";
			if (ps.equals("}"))
				ps = "-RCB-";

			b.append("(").append(ps).append(" ").append(term).append(')');
			current = path;
			// break;
		}
		for (; open > 0; open--) {
			b.append(")");
		}
		// b.append("\n");

		return b.toString();
	}

	static int cnt = 0;

	/**
	 * @param path
	 * @param current
	 * @return
	 */
	private ArrayList<Integer> getDiffPath(ArrayList<Integer> path, ArrayList<Integer> current) {
		if (current == null)
			return path;

		ArrayList<Integer> common = new ArrayList<Integer>();

		int pindex = path.size() - 1;
		int cindex = current.size() - 1;

		while (cindex >= 0 && pindex >= 0) {

			if (path.get(pindex) == current.get(cindex)) {
				cindex--;
				pindex--;
			} else
				break;
		}

		for (int k = 0; k <= pindex; k++) {
			common.add(path.get(k));
		}

		return common;
	}

	private ArrayList<Integer> getDiffCommon(ArrayList<Integer> path, ArrayList<Integer> current) {
		if (current == null)
			return path;

		ArrayList<Integer> common = new ArrayList<Integer>();

		int pindex = path.size() - 1;
		int cindex = current.size() - 1;

		while (cindex >= 0 && pindex >= 0) {

			if (path.get(pindex) == current.get(cindex)) {
				common.add(path.get(pindex));
				cindex--;
				pindex--;
			} else
				break;
		}

		Collections.reverse(common);
		// System.out.println("common "+pindex+" "+common);

		return common;
	}

	/**
	 * @param i
	 * @return
	 */
	private StringBuffer createSpaces(int i) {
		StringBuffer s = new StringBuffer();
		for (int k = 0; k < i; k++)
			s.append("  ");
		return s;
	}

	/**
	 * @param i
	 * @return
	 */
	private ArrayList<Integer> getPathToRoot(int i) {

		ArrayList<Integer> path = new ArrayList<Integer>();

		int h = i;
		while (true) {
			h = this.head[h];
			if (h < this.terminalCount || path.contains(h))
				break;
			path.add(h);
		}

		// Collections.reverse(list)

		return path;
	}

	public String conll09() {

		StringBuilder s = new StringBuilder();
		for (int i = 0; i < this.terminalCount; i++) {
			if (head[i] == -1 && entries[i] == null)
				break;

			s.append((i + 1)).append('\t').append(entries[i]).append("\t_\t_\t").append(pos[i])
					.append("\t_\t_\t_\t_\t_\t_\t_\t_\n");

		}

		return s.toString();
	}

	/**
	 * @param phead
	 * @return
	 */
	public int[] getChilds(int head) {

		int count = 0;
		for (int i = 0; i < this.entries.length; i++) {
			if (this.head[i] == head)
				count++;
		}

		int[] clds = new int[count];
		count = 0;
		for (int i = 0; i < this.entries.length; i++) {
			if (this.head[i] == head)
				clds[count++] = i;
		}

		return clds;
	}

}