tuto.md 13.2 KB
Newer Older
Bruno Guillaume's avatar
Bruno Guillaume committed
1

2
# Running the Grew Python library
Bruno Guillaume's avatar
Bruno Guillaume committed
3

4
Examples below are taken from first chapter of the book [*Application of Graph Rewriting to Natural Language Processing*](https://www.wiley.com/en-fr/Application+of+Graph+Rewriting+to+Natural+Language+Processing-p-9781119522348).
5
This chapter can be [downloaded in PDF from the editor website](https://media.wiley.com/product_data/excerpt/66/17863009/1786300966-587.pdf).
Bruno Guillaume's avatar
Bruno Guillaume committed
6

7 8
Since section 1.5, examples given use the Grew Python library.
If necessary, follow [installation page](../install).
Bruno Guillaume's avatar
Bruno Guillaume committed
9

10
:warning: Make sure that your version of `grewpy` and of the `grew` Python lib are updated.
Bruno Guillaume's avatar
Bruno Guillaume committed
11

12
## 1.1. Creating a graph
Bruno Guillaume's avatar
Bruno Guillaume committed
13

14
Create an empty graph:
Bruno Guillaume's avatar
Bruno Guillaume committed
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
```python
g = dict()
```
---

Add a node `W1` labelled _the_ to `g`:

```python
g['W1'] = ('the', [])
```
---

Add a second and a third node, with the edges which connect them

```python
g['W2'] = ('child', [])
g['W3'] = ('plays', [])
g['W3'][1].append(('suj', 'W2'))
g['W2'][1].append(('det', 'W1'))
```
---

Print the result

```python
g
```

```
{'W2': ('child', [('det', 'W1')]), 'W3': ('plays', [('suj', 'W2')]), 'W1': ('the', [])}
```

![thechildplays](/examples/book/thechildplays.svg)

---
Define construction functions
```python
def add_node(g, u, a):
  #Add a node u labeled a in graph g
  g[u] = (a, [])

def add_edge(g, u, e, v):
  # Add an edge labeled e from u to v in graph g
  if (e, v) not in g[u][1]:
    g[u][1].append( (e, v) )
```

---
add two more nodes
```python
add_node(g, 'W4', 'the')
add_node(g, 'W5', 'fool')
add_edge(g, 'W3', 'obj', 'W5')
add_edge(g, 'W5', 'det', 'W4')
```

![thechildplays](/examples/book/thechildplaysthefool.svg)

---
Using NLTK to build a flat graph (See [NLTK installation page](http://www.nltk.org/install.html) if necessary)

```python
import nltk
word_list = nltk.word_tokenize("She takes a glass")
word_graph = dict()
for i in range(len(word_list)):
    add_node(word_graph, 'W%s' %  i, word_list[i])

for i in range(len(word_list) - 1):
    add_edge(word_graph, 'W%s' % i, 'SUC', 'W%s' % (i + 1))

word_graph
```

```
{'W2': ('a', [('SUC', 'W3')]), 'W0': ('She', [('SUC', 'W1')]), 'W3': ('glass', []), 'W1': ('takes', [('SUC', 'W2')])}
```
![thechildplays](/examples/book/sheistakingaglass.svg)

## 1.2. Features structures

Build a feature structure

```python
fs_plays = {'phon' : 'plays', 'cat' : 'V'}
```

---
and read in it
```python
fs_plays['cat']
```

```
'V'
```

---
Rebuild previous example with feature structures

```python
g = dict()
add_node(g, 'W1', {'phon' : 'the', 'cat' : 'DET'} )
add_node(g, 'W2', {'phon' : 'child', 'cat' : 'N'} )
add_node(g, 'W3', {'phon' : 'plays', 'cat' : 'V'} )
add_node(g, 'W4', {'phon' : 'the', 'cat' : 'DET'})
add_node(g, 'W5', {'phon' : 'fool', 'cat' : 'N'})
add_edge(g, 'W2', 'det', 'W1')
add_edge(g, 'W3', 'suj', 'W2')
add_edge(g, 'W3', 'obj', 'W5')
add_edge(g, 'W5', 'det', 'W4')
```

![thechildplaysthefool_fs](/examples/book/thechildplaysthefool_fs.svg)


---
Use the basic POS-tagger provided with NLTK
```python
import nltk
word_list = nltk.word_tokenize("She takes a glass")
tag_list = nltk.pos_tag(word_list)
feat_list = [{'phon':n[0], 'cat':n[1]} for n in tag_list]
t_graph = {'W%s' % i : (feat_list[i], []) for i in range(len(tag_list))}
for i in range(len(tag_list)-1):
    add_edge(t_graph, 'W%s' % i, 'SUC', 'W%s' % (i+1))

t_graph
```

```
{'W2': ({'phon': 'a', 'cat': 'DT'}, [('SUC', 'W3')]), 'W0': ({'phon': 'She', 'cat': 'PRP'}, [('SUC', 'W1')]), 'W3': ({'phon': 'glass', 'cat': 'NN'}, []), 'W1': ({'phon': 'takes', 'cat': 'VBZ'}, [('SUC', 'W2')])}
```

![sheistakingaglass_nltk](/examples/book/sheistakingaglass_nltk.svg)

## 1.3. Information searches

Find the label or feature structure of a node
```python
g['W4'][0]
```

```
{'phon': 'the', 'cat': 'DET'}
```

---

Functions to get label or the list of successors
```python
def get_label(g, u):
    return g[u][0]

def get_sucs(g, u):
    return g[u][1]
```

### 1.3.1. Access to nodes

Get the list of nodes identifiers
```python
nodes = g.keys()
```
---

Get the list of verbs
```python
verbs = []
for u in nodes:
  if get_label(g, u)['cat'] == 'V':
      verbs.append(u)
```
---

or, with comprehension
```python
verbs =  [ u for u in g if get_label(g, u)['cat'] == 'V' ]
```

### 1.3.2. Extracting edges

Get the list of edges
```python
triplets = [ (s, e, t) for s in g for (e, t) in get_sucs(g, s) ]
```

---
or the same with a loop:
```python
triplets = []
for s in g:
  for (e, t) in get_sucs(g, s):
    triplets.append( (s, e, t) )
```

---
Extract the pairs of nodes linked by a subject relationship
```python
subject_verbs = [ (s, v) for (v, e, s) in triplets if e=='suj' ]
```

---
A function to check if there is an edge between two nodes `u` and `v`
```python
def are_related(g, u, v):
  triplets = [(s, e, t) for s in g for (e, t) in get_sucs(g, s)]
  for (s, e, t) in triplets:
    if (s, t) == (u, v):
      return True
  return False
```

---
Check if a node is a root node (i.e. whitout incomoing edge)
```python
def is_root(g, u):
  triplets = [(s, e, t) for s in g for (e, t) in get_sucs(g, s)]
  for (s, e, t) in triplets:
    if t == u:
      return False
  return True
```

## 1.4. Recreating an order

Using the convention explained in the book, we can reconstruct the sentence corresponding to a graph using the following function

```python
def get_phonology(g):
    def get_idx(node): #gets the float after 'W' in node if any
        import re #for regular expressions
        word_id = re.search(r'W(\d+(\.\d+)?)', node)
        return word_id.group(1) if word_id else None
    words = {get_idx(node) : get_label(g, node)['phon']
                        for node in g if get_idx(node)}
    return ' '.join([ words[idx] for idx in sorted(words)])

get_phonology(g)
```

```
'the child plays the fool'
```

## 1.5. Using patterns with the Grew library
To run the next part of the chapter, the **Grew** library must be imported and the **Grew** tool must be started.
Bruno Guillaume's avatar
Bruno Guillaume committed
263 264 265 266 267 268 269
The two next lines are then required:

```python
import grew
grew.init()
```

270
---
Bruno Guillaume's avatar
Bruno Guillaume committed
271

272
Build a graph with Grew syntax
Bruno Guillaume's avatar
Bruno Guillaume committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286
```python
g = grew.graph('''graph {
  W1 [phon="the", cat=DET];
  W2 [phon="child", cat=N];
  W3 [phon="plays", cat=V];
  W4 [phon="the", cat=DET];
  W5 [phon="fool", cat=N];
  W2 -[det]->W1;
  W3 -[suj]->W2;
  W3 -[obj]->W5;
  W5 -[det]->W4;
}''')
```

287 288 289 290 291
![thechildplaysthefool_fs](/examples/book/thechildplaysthefool_fs.svg)
---

Search for a specific pattern;
each line below can be executed separately.
Bruno Guillaume's avatar
Bruno Guillaume committed
292 293 294 295 296 297 298 299

```python
grew.search ("pattern { X[cat=V] }", g)
grew.search ("pattern { X[cat=DET] }", g)
grew.search ("pattern { X[cat=ADJ] }", g)
grew.search ("pattern { X[cat=V]; Y[]; X -[suj]-> Y }", g)
grew.search ("pattern { X[cat=V]; X -[suj]-> Y }", g)
grew.search ("pattern { X[cat=V]; e:X -[suj]-> Y }", g)
300
grew.search ("pattern { X[] } without { *->X }", g)
Bruno Guillaume's avatar
Bruno Guillaume committed
301 302 303 304 305
```


### 1.5.2 Common pitfalls

306
#### 1.2.5.1. Multiple choice edge searches
Bruno Guillaume's avatar
Bruno Guillaume committed
307 308 309 310 311 312 313 314 315
```python
g0 = grew.graph('''graph {
  W1 [phon=ils, cat=PRO];
  W2 [phon="s'", cat=PRO];
  W3 [phon=aiment, cat=V];
  W3 -[suj]-> W1;
  W3 -[obj]-> W1;
}''')
```
316
![ilssaiment](/examples/book/ilssaiment.svg)
Bruno Guillaume's avatar
Bruno Guillaume committed
317

318
---
Bruno Guillaume's avatar
Bruno Guillaume committed
319 320 321 322
```python
grew.search ("pattern { X -[suj|obj]-> Y }", g0)
```

323 324 325 326 327
```
[{'__e_2__': 'W3/suj/W1', 'X': 'W3', 'Y': 'W1'}, {'__e_2__': 'W3/obj/W1', 'X': 'W3', 'Y': 'W1'}]
```

#### 1.5.2.2. Anonymous nodes
Bruno Guillaume's avatar
Bruno Guillaume committed
328 329 330 331 332 333
```python
m1 = 'pattern{ P[phon="en",cat=P]; V[cat=V]; V-[obj]-> *}'
m2 = 'pattern{ P[phon="en",cat=P]; V[cat=V]; V-[obj]-> O}'
```


334
---
Bruno Guillaume's avatar
Bruno Guillaume committed
335 336 337 338 339 340 341
```python
g1 = grew.graph('''graph{
W1 [phon="en", cat=P];
W2 [phon="prend", cat=V];
W2 -[obj]->W1;
}''')
```
342
![enprend](/examples/book/enprend.svg)
Bruno Guillaume's avatar
Bruno Guillaume committed
343 344


345
---
Bruno Guillaume's avatar
Bruno Guillaume committed
346 347 348 349 350 351
```python
grew.search(m1, g1)
grew.search(m2, g1)
```


352
---
Bruno Guillaume's avatar
Bruno Guillaume committed
353 354 355 356 357 358 359 360 361 362 363
```python
g2 = grew.graph('''graph{
W1 [phon="en", cat=P];
W2 [phon="connait", cat=V];
W3 [phon="la", cat=Det];
W4 [phon="fin", cat=N];
W2 -[det]->W3;
W2 -[mod]->W1;
W2 -[obj]->W4;
}''')
```
364
![enconnaitlafin](/examples/book/enconnaitlafin.svg)
Bruno Guillaume's avatar
Bruno Guillaume committed
365 366


367
---
Bruno Guillaume's avatar
Bruno Guillaume committed
368 369 370 371 372 373
```python
grew.search(m1, g2)
grew.search(m2, g2)
```


374
#### 1.5.2.3. Multiple `without` clauses
Bruno Guillaume's avatar
Bruno Guillaume committed
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

```python
g3 = grew.graph('''graph{
  W1 [phon=John, cat=NP];
  W2 [phon=reads, cat=V ];
  W3 [phon=the, cat=Det];
  W4 [phon=book, cat=N];
  W2 -[suj]-> W1;
  W2 -[obj]-> W4;
  W4 -[det]-> W3;
}''')

g4 = grew.graph('''graph{
  W1 [phon=John, cat=NP];
  W2 [phon=reads, cat=V ];
  W3 [phon=the, cat=Det];
  W4 [phon=book, cat=N];
  W5 [phon=today, cat=ADV];
  W2 -[suj]-> W1;
  W2 -[obj]-> W4;
  W4 -[det]-> W3;
  W2 -[mod]-> W5;
}''')
```

400 401 402
| ![johnreadsthebook](/examples/book/johnreadsthebook.svg) | ![johnreadsthebooktoday](/examples/book/johnreadsthebooktoday.svg) |
|:---:|:---:|

Bruno Guillaume's avatar
Bruno Guillaume committed
403 404 405 406 407 408 409 410 411 412 413 414 415

```python
m3 = "pattern{Y-[suj]->X} without{Y-[obj]->Z; Y-[mod]->T}"
m4 = "pattern{Y-[suj]->X} without{Y-[obj]->Z} without{Y-[mod]->T}"
```

```python
grew.search(m3, g3)
grew.search(m4, g3)
grew.search(m3, g4)
grew.search(m4, g4)
```

416
#### 1.5.2.4. Double negations
Bruno Guillaume's avatar
Bruno Guillaume committed
417 418 419 420 421 422
```python
g5 = grew.graph('''graph{
  W1 [phon=dors, cat=V, m=imp];
  W2 [phon="!", cat=PONCT];
}''')
```
423
![dors](/examples/book/dors.svg)
Bruno Guillaume's avatar
Bruno Guillaume committed
424 425 426 427 428 429 430 431 432 433 434 435

```python
m5 = "pattern { X[cat=V, t=fut] }"
m6 = "pattern { X[cat=V] } without{ X[t<>fut] }"
```

```python
grew.search(m5, g5)
grew.search(m6, g5)
```


436 437 438 439 440 441 442 443 444 445 446 447 448
#### 1.5.2.5. Double edges
```python
g0 = grew.graph('''graph {
  W1 [phon=ils, cat=PRO];
  W2 [phon="s'", cat=PRO];
  W3 [phon=aiment, cat=V];
  W3 -[suj]-> W1;
  W3 -[obj]-> W1;
}''')
```
![ilssaiment](/examples/book/ilssaiment.svg)

---
Bruno Guillaume's avatar
Bruno Guillaume committed
449 450 451 452 453

```python
grew.search("pattern { e : X -> Y ; f : X -> Y }", g0)
```

454
## 1.6. Graph rewriting
Bruno Guillaume's avatar
Bruno Guillaume committed
455

456
The syntactic structure for a French sentence with a passive agent
Bruno Guillaume's avatar
Bruno Guillaume committed
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
```python
g = grew.graph('''graph{
  W1 [phon="John",cat=NP];
  W2 [phon="est",cat=V ];
  W3 [phon="mordu", cat=V, m=pastp];
  W4 [phon="par",cat=P ];
  W5 [phon="le", cat=D];
  W6 [word="chien",cat=NP];

  W3 -[suj]-> W1;
  W3 -[aux.pass]-> W2;
  W3 -[p_obj.agt]-> W4;
  W6 -[det]-> W5;
  W4 -[obj.p]-> W6;
}''')
```
473
![john_est_mordu_par_le_chien](/examples/book/john_est_mordu_par_le_chien.svg)
Bruno Guillaume's avatar
Bruno Guillaume committed
474

475 476
---
Example of rule dealing with passive agent
Bruno Guillaume's avatar
Bruno Guillaume committed
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494

```python
r = """rule passiveAgt {
  pattern {
    V [cat=V, m=pastp];
    V -[aux.pass]-> AUX;
    e: V -[suj]-> SUJ;
    P [phon=par]; V -[p_obj.agt]-> P;
    P -[obj.p]-> A;
} commands {
    del_node P;
    del_node AUX;
    add_edge V -[suj]-> A;
    add_edge V -[obj]-> SUJ;
    del_edge e;
} }"""
```

495 496
---
Apply the rule to the graph
Bruno Guillaume's avatar
Bruno Guillaume committed
497 498 499 500
```python
grew.run(r, g, 'passiveAgt')
```

501 502 503 504 505 506 507 508 509 510
```
[{'W5': ('cat="D", phon="le"', []), 'W6': ('cat="NP", word="chien"', [('det', 'W5')]), 'W3': ('cat="V", m="pastp", phon="mordu"', [('obj', 'W1'), ('suj', 'W6')]), 'W1': ('cat="NP", phon="John"', [])}]
```

![john_est_mordu_par_le_chien_2](/examples/book/john_est_mordu_par_le_chien_2.svg)

### 1.6.2. From rules to strategies

In order to run examples for this section, we put the two rules `passiveAgt` and `du2dele` into the same rewriting system:

Bruno Guillaume's avatar
Bruno Guillaume committed
511
```python
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
rs = grew.grs ("""
rule passiveAgt {
  pattern {
    V [cat=V, m=pastp];
    V -[aux.pass]-> AUX;
    e: V -[suj]-> SUJ;
    P [phon=par]; V -[p_obj.agt]-> P;
    P -[obj.p]-> A;
  }
  commands {
    del_node P;
    del_node AUX;
    add_edge V -[suj]-> A;
    add_edge V -[obj]-> SUJ;
    del_edge e;
  }
}

rule du2dele {
Bruno Guillaume's avatar
Bruno Guillaume committed
531 532 533 534 535 536 537 538 539
  pattern {
    A [cat="P+D", phon="du"]; N [cat=N];
    A -[obj.p]-> N;
    }
  commands {
    add_node D:> A; D.cat=D ; D.phon="le" ;
    A.cat=P; A.phon="de";
    add_edge N -[det]-> D;
  }
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
}

strat S1 { du2dele }
""")
```

---

The code for the two French sentences is given below:

  * (1.1) _La porte du jardin du voisin_
  * (1.2) _Le chien du voisin est pris par John_

```python
sent_1_1 = grew.graph('''graph{
  W1 [phon=La, cat=D];
  W2 [phon=porte, cat=N];
  W3 [phon=du, cat="P+D"];
  W4 [phon=jardin, cat=N];
  W5 [phon=du, cat="P+D"];
  W6 [phon=voisin, cat=N];
  W2 -[det]-> W1;
  W2 -[dep]-> W3;
  W3 -[obj.p]-> W4;
  W4 -[dep]-> W5;
  W5 -[obj.p]-> W6;
}''')
```

![porte](/examples/book/porte.svg)


```python
sent_1_2 = grew.graph('''graph{
  W1 [phon=Le, cat=D];
  W2 [phon=chien, cat=N];
  W3 [phon=du, cat="P+D"];
  W4 [phon=voisin, cat=N];
  W5 [phon=est, cat=V];
  W6 [phon=pris, cat=V, m=pastp];
  W7 [phon=par, cat=P];
  W8 [phon=John, cat=N];
  W2 -[det]-> W1;
  W2 -[dep]-> W3;
  W3 -[obj.p]-> W4;
  W6 -[suj]-> W2;
  W6 -[aux.pass]-> W5;
  W6 -[p_obj.agt]-> W7;
  W7 -[obj.p]-> W8;
}''')
```

![lechienduvoisinestmangeparjohn](/examples/book/lechienduvoisinestmangeparjohn.svg)

---

#### Apply one rule to a graph

As the strategy `S1` is defined as one rule `du2dele`, we can apply the rule to the sentence (1.1) with one of the two equivalent commands below:

```python
grew.run(rs,sent_1_1,"S1")
grew.run(rs,sent_1_1,"du2dele")
Bruno Guillaume's avatar
Bruno Guillaume committed
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

The output contains two graphs resulting of the application of the rule to the first or the second *du* in the sentence.

#### 1.6.2.1. Alternative

```python
grew.run(rs,sent_1_2,"Alt (passiveAgt, du2dele)")
```

#### 1.6.2.2. Sequence

```python
grew.run(rs,sent_1_2,"Seq (du2dele, passiveAgt)")
```

#### 1.6.2.3. Pick

```python
grew.run(rs,sent_1_1,"Pick (S1)")
```

#### 1.6.2.4. Iteration

```python
grew.run(rs,sent_1_1,"Iter (S1)")
```

#### 1.6.2.5. Test
```python
grew.run(rs,sent_1_1,"If(passiveAgt,Seq(passiveAgt, Iter(du2dele)), Iter(du2dele))")
grew.run(rs,sent_1_2,"If(passiveAgt,Seq(passiveAgt, Iter(du2dele)), Iter(du2dele))")
```

#### 1.6.2.6 Try
```python
grew.run(rs,sent_1_1,"Try(passiveAgt)")
grew.run(rs,sent_1_2,"Try(passiveAgt)")
```

### 1.6.3 Using lexicons
This features will be available in an upcoming release of **Grew** which should appear soon!