PageRenderTime 55ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/nltk/grammar.py

https://github.com/BrucePHill/nltk
Python | 1514 lines | 1483 code | 10 blank | 21 comment | 14 complexity | 4d3a55db7460bcf1c43f8929b953b81e MD5 | raw file
Possible License(s): Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. # -*- coding: utf-8 -*-
  2. # Natural Language Toolkit: Context Free Grammars
  3. #
  4. # Copyright (C) 2001-2013 NLTK Project
  5. # Author: Steven Bird <stevenbird1@gmail.com>
  6. # Edward Loper <edloper@seas.upenn.edu>
  7. # Jason Narad <jason.narad@gmail.com>
  8. # Peter Ljunglรถf <peter.ljunglof@heatherleaf.se>
  9. # URL: <http://www.nltk.org/>
  10. # For license information, see LICENSE.TXT
  11. #
  12. """
  13. Basic data classes for representing context free grammars. A
  14. "grammar" specifies which trees can represent the structure of a
  15. given text. Each of these trees is called a "parse tree" for the
  16. text (or simply a "parse"). In a "context free" grammar, the set of
  17. parse trees for any piece of a text can depend only on that piece, and
  18. not on the rest of the text (i.e., the piece's context). Context free
  19. grammars are often used to find possible syntactic structures for
  20. sentences. In this context, the leaves of a parse tree are word
  21. tokens; and the node values are phrasal categories, such as ``NP``
  22. and ``VP``.
  23. The ``ContextFreeGrammar`` class is used to encode context free grammars. Each
  24. ``ContextFreeGrammar`` consists of a start symbol and a set of productions.
  25. The "start symbol" specifies the root node value for parse trees. For example,
  26. the start symbol for syntactic parsing is usually ``S``. Start
  27. symbols are encoded using the ``Nonterminal`` class, which is discussed
  28. below.
  29. A Grammar's "productions" specify what parent-child relationships a parse
  30. tree can contain. Each production specifies that a particular
  31. node can be the parent of a particular set of children. For example,
  32. the production ``<S> -> <NP> <VP>`` specifies that an ``S`` node can
  33. be the parent of an ``NP`` node and a ``VP`` node.
  34. Grammar productions are implemented by the ``Production`` class.
  35. Each ``Production`` consists of a left hand side and a right hand
  36. side. The "left hand side" is a ``Nonterminal`` that specifies the
  37. node type for a potential parent; and the "right hand side" is a list
  38. that specifies allowable children for that parent. This lists
  39. consists of ``Nonterminals`` and text types: each ``Nonterminal``
  40. indicates that the corresponding child may be a ``TreeToken`` with the
  41. specified node type; and each text type indicates that the
  42. corresponding child may be a ``Token`` with the with that type.
  43. The ``Nonterminal`` class is used to distinguish node values from leaf
  44. values. This prevents the grammar from accidentally using a leaf
  45. value (such as the English word "A") as the node of a subtree. Within
  46. a ``ContextFreeGrammar``, all node values are wrapped in the ``Nonterminal``
  47. class. Note, however, that the trees that are specified by the grammar do
  48. *not* include these ``Nonterminal`` wrappers.
  49. Grammars can also be given a more procedural interpretation. According to
  50. this interpretation, a Grammar specifies any tree structure *tree* that
  51. can be produced by the following procedure:
  52. | Set tree to the start symbol
  53. | Repeat until tree contains no more nonterminal leaves:
  54. | Choose a production prod with whose left hand side
  55. | lhs is a nonterminal leaf of tree.
  56. | Replace the nonterminal leaf with a subtree, whose node
  57. | value is the value wrapped by the nonterminal lhs, and
  58. | whose children are the right hand side of prod.
  59. The operation of replacing the left hand side (*lhs*) of a production
  60. with the right hand side (*rhs*) in a tree (*tree*) is known as
  61. "expanding" *lhs* to *rhs* in *tree*.
  62. """
  63. from __future__ import print_function, unicode_literals
  64. import re
  65. from nltk.util import transitive_closure, invert_graph
  66. from nltk.compat import (string_types, total_ordering, text_type,
  67. python_2_unicode_compatible, unicode_repr)
  68. from nltk.internals import raise_unorderable_types
  69. from nltk.probability import ImmutableProbabilisticMixIn
  70. from nltk.featstruct import FeatStruct, FeatDict, FeatStructParser, SLASH, TYPE
  71. #################################################################
  72. # Nonterminal
  73. #################################################################
  74. @total_ordering
  75. @python_2_unicode_compatible
  76. class Nonterminal(object):
  77. """
  78. A non-terminal symbol for a context free grammar. ``Nonterminal``
  79. is a wrapper class for node values; it is used by ``Production``
  80. objects to distinguish node values from leaf values.
  81. The node value that is wrapped by a ``Nonterminal`` is known as its
  82. "symbol". Symbols are typically strings representing phrasal
  83. categories (such as ``"NP"`` or ``"VP"``). However, more complex
  84. symbol types are sometimes used (e.g., for lexicalized grammars).
  85. Since symbols are node values, they must be immutable and
  86. hashable. Two ``Nonterminals`` are considered equal if their
  87. symbols are equal.
  88. :see: ``ContextFreeGrammar``, ``Production``
  89. :type _symbol: any
  90. :ivar _symbol: The node value corresponding to this
  91. ``Nonterminal``. This value must be immutable and hashable.
  92. """
  93. def __init__(self, symbol):
  94. """
  95. Construct a new non-terminal from the given symbol.
  96. :type symbol: any
  97. :param symbol: The node value corresponding to this
  98. ``Nonterminal``. This value must be immutable and
  99. hashable.
  100. """
  101. self._symbol = symbol
  102. self._hash = hash(symbol)
  103. def symbol(self):
  104. """
  105. Return the node value corresponding to this ``Nonterminal``.
  106. :rtype: (any)
  107. """
  108. return self._symbol
  109. def __eq__(self, other):
  110. """
  111. Return True if this non-terminal is equal to ``other``. In
  112. particular, return True if ``other`` is a ``Nonterminal``
  113. and this non-terminal's symbol is equal to ``other`` 's symbol.
  114. :rtype: bool
  115. """
  116. return type(self) == type(other) and self._symbol == other._symbol
  117. def __ne__(self, other):
  118. return not self == other
  119. def __lt__(self, other):
  120. if not isinstance(other, Nonterminal):
  121. raise_unorderable_types("<", self, other)
  122. return self._symbol < other._symbol
  123. def __hash__(self):
  124. return self._hash
  125. def __repr__(self):
  126. """
  127. Return a string representation for this ``Nonterminal``.
  128. :rtype: str
  129. """
  130. if isinstance(self._symbol, string_types):
  131. return '%s' % self._symbol
  132. else:
  133. return '%s' % unicode_repr(self._symbol)
  134. def __str__(self):
  135. """
  136. Return a string representation for this ``Nonterminal``.
  137. :rtype: str
  138. """
  139. if isinstance(self._symbol, string_types):
  140. return '%s' % self._symbol
  141. else:
  142. return '%s' % unicode_repr(self._symbol)
  143. def __div__(self, rhs):
  144. """
  145. Return a new nonterminal whose symbol is ``A/B``, where ``A`` is
  146. the symbol for this nonterminal, and ``B`` is the symbol for rhs.
  147. :param rhs: The nonterminal used to form the right hand side
  148. of the new nonterminal.
  149. :type rhs: Nonterminal
  150. :rtype: Nonterminal
  151. """
  152. return Nonterminal('%s/%s' % (self._symbol, rhs._symbol))
  153. def nonterminals(symbols):
  154. """
  155. Given a string containing a list of symbol names, return a list of
  156. ``Nonterminals`` constructed from those symbols.
  157. :param symbols: The symbol name string. This string can be
  158. delimited by either spaces or commas.
  159. :type symbols: str
  160. :return: A list of ``Nonterminals`` constructed from the symbol
  161. names given in ``symbols``. The ``Nonterminals`` are sorted
  162. in the same order as the symbols names.
  163. :rtype: list(Nonterminal)
  164. """
  165. if ',' in symbols: symbol_list = symbols.split(',')
  166. else: symbol_list = symbols.split()
  167. return [Nonterminal(s.strip()) for s in symbol_list]
  168. class FeatStructNonterminal(FeatDict, Nonterminal):
  169. """A feature structure that's also a nonterminal. It acts as its
  170. own symbol, and automatically freezes itself when hashed."""
  171. def __hash__(self):
  172. self.freeze()
  173. return FeatStruct.__hash__(self)
  174. def symbol(self):
  175. return self
  176. def is_nonterminal(item):
  177. """
  178. :return: True if the item is a ``Nonterminal``.
  179. :rtype: bool
  180. """
  181. return isinstance(item, Nonterminal)
  182. #################################################################
  183. # Terminals
  184. #################################################################
  185. def is_terminal(item):
  186. """
  187. Return True if the item is a terminal, which currently is
  188. if it is hashable and not a ``Nonterminal``.
  189. :rtype: bool
  190. """
  191. return hasattr(item, '__hash__') and not isinstance(item, Nonterminal)
  192. #################################################################
  193. # Productions
  194. #################################################################
  195. @total_ordering
  196. @python_2_unicode_compatible
  197. class Production(object):
  198. """
  199. A grammar production. Each production maps a single symbol
  200. on the "left-hand side" to a sequence of symbols on the
  201. "right-hand side". (In the case of context-free productions,
  202. the left-hand side must be a ``Nonterminal``, and the right-hand
  203. side is a sequence of terminals and ``Nonterminals``.)
  204. "terminals" can be any immutable hashable object that is
  205. not a ``Nonterminal``. Typically, terminals are strings
  206. representing words, such as ``"dog"`` or ``"under"``.
  207. :see: ``ContextFreeGrammar``
  208. :see: ``DependencyGrammar``
  209. :see: ``Nonterminal``
  210. :type _lhs: Nonterminal
  211. :ivar _lhs: The left-hand side of the production.
  212. :type _rhs: tuple(Nonterminal, terminal)
  213. :ivar _rhs: The right-hand side of the production.
  214. """
  215. def __init__(self, lhs, rhs):
  216. """
  217. Construct a new ``Production``.
  218. :param lhs: The left-hand side of the new ``Production``.
  219. :type lhs: Nonterminal
  220. :param rhs: The right-hand side of the new ``Production``.
  221. :type rhs: sequence(Nonterminal and terminal)
  222. """
  223. if isinstance(rhs, string_types):
  224. raise TypeError('production right hand side should be a list, '
  225. 'not a string')
  226. self._lhs = lhs
  227. self._rhs = tuple(rhs)
  228. self._hash = hash((self._lhs, self._rhs))
  229. def lhs(self):
  230. """
  231. Return the left-hand side of this ``Production``.
  232. :rtype: Nonterminal
  233. """
  234. return self._lhs
  235. def rhs(self):
  236. """
  237. Return the right-hand side of this ``Production``.
  238. :rtype: sequence(Nonterminal and terminal)
  239. """
  240. return self._rhs
  241. def __len__(self):
  242. """
  243. Return the length of the right-hand side.
  244. :rtype: int
  245. """
  246. return len(self._rhs)
  247. def is_nonlexical(self):
  248. """
  249. Return True if the right-hand side only contains ``Nonterminals``
  250. :rtype: bool
  251. """
  252. return all(is_nonterminal(n) for n in self._rhs)
  253. def is_lexical(self):
  254. """
  255. Return True if the right-hand contain at least one terminal token.
  256. :rtype: bool
  257. """
  258. return not self.is_nonlexical()
  259. def __str__(self):
  260. """
  261. Return a verbose string representation of the ``Production``.
  262. :rtype: str
  263. """
  264. result = '%s -> ' % unicode_repr(self._lhs)
  265. result += " ".join(unicode_repr(el) for el in self._rhs)
  266. return result
  267. def __repr__(self):
  268. """
  269. Return a concise string representation of the ``Production``.
  270. :rtype: str
  271. """
  272. return '%s' % self
  273. def __eq__(self, other):
  274. """
  275. Return True if this ``Production`` is equal to ``other``.
  276. :rtype: bool
  277. """
  278. return (type(self) == type(other) and
  279. self._lhs == other._lhs and
  280. self._rhs == other._rhs)
  281. def __ne__(self, other):
  282. return not self == other
  283. def __lt__(self, other):
  284. if not isinstance(other, Production):
  285. raise_unorderable_types("<", self, other)
  286. return (self._lhs, self._rhs) < (other._lhs, other._rhs)
  287. def __hash__(self):
  288. """
  289. Return a hash value for the ``Production``.
  290. :rtype: int
  291. """
  292. return self._hash
  293. @python_2_unicode_compatible
  294. class DependencyProduction(Production):
  295. """
  296. A dependency grammar production. Each production maps a single
  297. head word to an unordered list of one or more modifier words.
  298. """
  299. def __str__(self):
  300. """
  301. Return a verbose string representation of the ``DependencyProduction``.
  302. :rtype: str
  303. """
  304. result = '\'%s\' ->' % (self._lhs,)
  305. for elt in self._rhs:
  306. result += ' \'%s\'' % (elt,)
  307. return result
  308. @python_2_unicode_compatible
  309. class WeightedProduction(Production, ImmutableProbabilisticMixIn):
  310. """
  311. A probabilistic context free grammar production.
  312. A PCFG ``WeightedProduction`` is essentially just a ``Production`` that
  313. has an associated probability, which represents how likely it is that
  314. this production will be used. In particular, the probability of a
  315. ``WeightedProduction`` records the likelihood that its right-hand side is
  316. the correct instantiation for any given occurrence of its left-hand side.
  317. :see: ``Production``
  318. """
  319. def __init__(self, lhs, rhs, **prob):
  320. """
  321. Construct a new ``WeightedProduction``.
  322. :param lhs: The left-hand side of the new ``WeightedProduction``.
  323. :type lhs: Nonterminal
  324. :param rhs: The right-hand side of the new ``WeightedProduction``.
  325. :type rhs: sequence(Nonterminal and terminal)
  326. :param prob: Probability parameters of the new ``WeightedProduction``.
  327. """
  328. ImmutableProbabilisticMixIn.__init__(self, **prob)
  329. Production.__init__(self, lhs, rhs)
  330. def __str__(self):
  331. return Production.__unicode__(self) + ' [%.6g]' % self.prob()
  332. def __eq__(self, other):
  333. return (type(self) == type(other) and
  334. self._lhs == other._lhs and
  335. self._rhs == other._rhs and
  336. self.prob() == other.prob())
  337. def __ne__(self, other):
  338. return not self == other
  339. def __hash__(self):
  340. return hash((self._lhs, self._rhs, self.prob()))
  341. #################################################################
  342. # Grammars
  343. #################################################################
  344. @python_2_unicode_compatible
  345. class ContextFreeGrammar(object):
  346. """
  347. A context-free grammar. A grammar consists of a start state and
  348. a set of productions. The set of terminals and nonterminals is
  349. implicitly specified by the productions.
  350. If you need efficient key-based access to productions, you
  351. can use a subclass to implement it.
  352. """
  353. def __init__(self, start, productions, calculate_leftcorners=True):
  354. """
  355. Create a new context-free grammar, from the given start state
  356. and set of ``Production``s.
  357. :param start: The start symbol
  358. :type start: Nonterminal
  359. :param productions: The list of productions that defines the grammar
  360. :type productions: list(Production)
  361. :param calculate_leftcorners: False if we don't want to calculate the
  362. leftcorner relation. In that case, some optimized chart parsers won't work.
  363. :type calculate_leftcorners: bool
  364. """
  365. self._start = start
  366. self._productions = productions
  367. self._categories = set(prod.lhs() for prod in productions)
  368. self._calculate_indexes()
  369. self._calculate_grammar_forms()
  370. if calculate_leftcorners:
  371. self._calculate_leftcorners()
  372. def _calculate_indexes(self):
  373. self._lhs_index = {}
  374. self._rhs_index = {}
  375. self._empty_index = {}
  376. self._lexical_index = {}
  377. for prod in self._productions:
  378. # Left hand side.
  379. lhs = prod._lhs
  380. if lhs not in self._lhs_index:
  381. self._lhs_index[lhs] = []
  382. self._lhs_index[lhs].append(prod)
  383. if prod._rhs:
  384. # First item in right hand side.
  385. rhs0 = prod._rhs[0]
  386. if rhs0 not in self._rhs_index:
  387. self._rhs_index[rhs0] = []
  388. self._rhs_index[rhs0].append(prod)
  389. else:
  390. # The right hand side is empty.
  391. self._empty_index[prod.lhs()] = prod
  392. # Lexical tokens in the right hand side.
  393. for token in prod._rhs:
  394. if is_terminal(token):
  395. self._lexical_index.setdefault(token, set()).add(prod)
  396. def _calculate_leftcorners(self):
  397. # Calculate leftcorner relations, for use in optimized parsing.
  398. self._immediate_leftcorner_categories = dict((cat, set([cat])) for cat in self._categories)
  399. self._immediate_leftcorner_words = dict((cat, set()) for cat in self._categories)
  400. for prod in self.productions():
  401. if len(prod) > 0:
  402. cat, left = prod.lhs(), prod.rhs()[0]
  403. if is_nonterminal(left):
  404. self._immediate_leftcorner_categories[cat].add(left)
  405. else:
  406. self._immediate_leftcorner_words[cat].add(left)
  407. lc = transitive_closure(self._immediate_leftcorner_categories, reflexive=True)
  408. self._leftcorners = lc
  409. self._leftcorner_parents = invert_graph(lc)
  410. nr_leftcorner_categories = sum(map(len, self._immediate_leftcorner_categories.values()))
  411. nr_leftcorner_words = sum(map(len, self._immediate_leftcorner_words.values()))
  412. if nr_leftcorner_words > nr_leftcorner_categories > 10000:
  413. # If the grammar is big, the leftcorner-word dictionary will be too large.
  414. # In that case it is better to calculate the relation on demand.
  415. self._leftcorner_words = None
  416. return
  417. self._leftcorner_words = {}
  418. for cat in self._leftcorners:
  419. lefts = self._leftcorners[cat]
  420. lc = self._leftcorner_words[cat] = set()
  421. for left in lefts:
  422. lc.update(self._immediate_leftcorner_words.get(left, set()))
  423. def start(self):
  424. """
  425. Return the start symbol of the grammar
  426. :rtype: Nonterminal
  427. """
  428. return self._start
  429. # tricky to balance readability and efficiency here!
  430. # can't use set operations as they don't preserve ordering
  431. def productions(self, lhs=None, rhs=None, empty=False):
  432. """
  433. Return the grammar productions, filtered by the left-hand side
  434. or the first item in the right-hand side.
  435. :param lhs: Only return productions with the given left-hand side.
  436. :param rhs: Only return productions with the given first item
  437. in the right-hand side.
  438. :param empty: Only return productions with an empty right-hand side.
  439. :return: A list of productions matching the given constraints.
  440. :rtype: list(Production)
  441. """
  442. if rhs and empty:
  443. raise ValueError("You cannot select empty and non-empty "
  444. "productions at the same time.")
  445. # no constraints so return everything
  446. if not lhs and not rhs:
  447. if not empty:
  448. return self._productions
  449. else:
  450. return self._empty_index.values()
  451. # only lhs specified so look up its index
  452. elif lhs and not rhs:
  453. if not empty:
  454. return self._lhs_index.get(lhs, [])
  455. elif lhs in self._empty_index:
  456. return [self._empty_index[lhs]]
  457. else:
  458. return []
  459. # only rhs specified so look up its index
  460. elif rhs and not lhs:
  461. return self._rhs_index.get(rhs, [])
  462. # intersect
  463. else:
  464. return [prod for prod in self._lhs_index.get(lhs, [])
  465. if prod in self._rhs_index.get(rhs, [])]
  466. def leftcorners(self, cat):
  467. """
  468. Return the set of all nonterminals that the given nonterminal
  469. can start with, including itself.
  470. This is the reflexive, transitive closure of the immediate
  471. leftcorner relation: (A > B) iff (A -> B beta)
  472. :param cat: the parent of the leftcorners
  473. :type cat: Nonterminal
  474. :return: the set of all leftcorners
  475. :rtype: set(Nonterminal)
  476. """
  477. return self._leftcorners.get(cat, set([cat]))
  478. def is_leftcorner(self, cat, left):
  479. """
  480. True if left is a leftcorner of cat, where left can be a
  481. terminal or a nonterminal.
  482. :param cat: the parent of the leftcorner
  483. :type cat: Nonterminal
  484. :param left: the suggested leftcorner
  485. :type left: Terminal or Nonterminal
  486. :rtype: bool
  487. """
  488. if is_nonterminal(left):
  489. return left in self.leftcorners(cat)
  490. elif self._leftcorner_words:
  491. return left in self._leftcorner_words.get(cat, set())
  492. else:
  493. return any(left in self._immediate_leftcorner_words.get(parent, set())
  494. for parent in self.leftcorners(cat))
  495. def leftcorner_parents(self, cat):
  496. """
  497. Return the set of all nonterminals for which the given category
  498. is a left corner. This is the inverse of the leftcorner relation.
  499. :param cat: the suggested leftcorner
  500. :type cat: Nonterminal
  501. :return: the set of all parents to the leftcorner
  502. :rtype: set(Nonterminal)
  503. """
  504. return self._leftcorner_parents.get(cat, set([cat]))
  505. def check_coverage(self, tokens):
  506. """
  507. Check whether the grammar rules cover the given list of tokens.
  508. If not, then raise an exception.
  509. :type tokens: list(str)
  510. """
  511. missing = [tok for tok in tokens
  512. if not self._lexical_index.get(tok)]
  513. if missing:
  514. missing = ', '.join('%r' % (w,) for w in missing)
  515. raise ValueError("Grammar does not cover some of the "
  516. "input words: %r." % missing)
  517. def _calculate_grammar_forms(self):
  518. """
  519. Pre-calculate of which form(s) the grammar is.
  520. """
  521. prods = self._productions
  522. self._is_lexical = all(p.is_lexical() for p in prods)
  523. self._is_nonlexical = all(p.is_nonlexical() for p in prods
  524. if len(p) != 1)
  525. self._min_len = min(len(p) for p in prods)
  526. self._max_len = max(len(p) for p in prods)
  527. self._all_unary_are_lexical = all(p.is_lexical() for p in prods
  528. if len(p) == 1)
  529. def is_lexical(self):
  530. """
  531. Return True if all productions are lexicalised.
  532. """
  533. return self._is_lexical
  534. def is_nonlexical(self):
  535. """
  536. Return True if all lexical rules are "preterminals", that is,
  537. unary rules which can be separated in a preprocessing step.
  538. This means that all productions are of the forms
  539. A -> B1 ... Bn (n>=0), or A -> "s".
  540. Note: is_lexical() and is_nonlexical() are not opposites.
  541. There are grammars which are neither, and grammars which are both.
  542. """
  543. return self._is_nonlexical
  544. def min_len(self):
  545. """
  546. Return the right-hand side length of the shortest grammar production.
  547. """
  548. return self._min_len
  549. def max_len(self):
  550. """
  551. Return the right-hand side length of the longest grammar production.
  552. """
  553. return self._max_len
  554. def is_nonempty(self):
  555. """
  556. Return True if there are no empty productions.
  557. """
  558. return self._min_len > 0
  559. def is_binarised(self):
  560. """
  561. Return True if all productions are at most binary.
  562. Note that there can still be empty and unary productions.
  563. """
  564. return self._max_len <= 2
  565. def is_flexible_chomsky_normal_form(self):
  566. """
  567. Return True if all productions are of the forms
  568. A -> B C, A -> B, or A -> "s".
  569. """
  570. return self.is_nonempty() and self.is_nonlexical() and self.is_binarised()
  571. def is_chomsky_normal_form(self):
  572. """
  573. Return True if the grammar is of Chomsky Normal Form, i.e. all productions
  574. are of the form A -> B C, or A -> "s".
  575. """
  576. return (self.is_flexible_chomsky_normal_form() and
  577. self._all_unary_are_lexical)
  578. def __repr__(self):
  579. return '<Grammar with %d productions>' % len(self._productions)
  580. def __str__(self):
  581. result = 'Grammar with %d productions' % len(self._productions)
  582. result += ' (start state = %r)' % self._start
  583. for production in self._productions:
  584. result += '\n %s' % production
  585. return result
  586. class FeatureGrammar(ContextFreeGrammar):
  587. """
  588. A feature-based grammar. This is equivalent to a
  589. ``ContextFreeGrammar`` whose nonterminals are all
  590. ``FeatStructNonterminal``.
  591. A grammar consists of a start state and a set of
  592. productions. The set of terminals and nonterminals
  593. is implicitly specified by the productions.
  594. """
  595. def __init__(self, start, productions):
  596. """
  597. Create a new feature-based grammar, from the given start
  598. state and set of ``Productions``.
  599. :param start: The start symbol
  600. :type start: FeatStructNonterminal
  601. :param productions: The list of productions that defines the grammar
  602. :type productions: list(Production)
  603. """
  604. ContextFreeGrammar.__init__(self, start, productions)
  605. # The difference with CFG is that the productions are
  606. # indexed on the TYPE feature of the nonterminals.
  607. # This is calculated by the method _get_type_if_possible().
  608. def _calculate_indexes(self):
  609. self._lhs_index = {}
  610. self._rhs_index = {}
  611. self._empty_index = {}
  612. self._empty_productions = []
  613. self._lexical_index = {}
  614. for prod in self._productions:
  615. # Left hand side.
  616. lhs = self._get_type_if_possible(prod._lhs)
  617. if lhs not in self._lhs_index:
  618. self._lhs_index[lhs] = []
  619. self._lhs_index[lhs].append(prod)
  620. if prod._rhs:
  621. # First item in right hand side.
  622. rhs0 = self._get_type_if_possible(prod._rhs[0])
  623. if rhs0 not in self._rhs_index:
  624. self._rhs_index[rhs0] = []
  625. self._rhs_index[rhs0].append(prod)
  626. else:
  627. # The right hand side is empty.
  628. if lhs not in self._empty_index:
  629. self._empty_index[lhs] = []
  630. self._empty_index[lhs].append(prod)
  631. self._empty_productions.append(prod)
  632. # Lexical tokens in the right hand side.
  633. for token in prod._rhs:
  634. if is_terminal(token):
  635. self._lexical_index.setdefault(token, set()).add(prod)
  636. def productions(self, lhs=None, rhs=None, empty=False):
  637. """
  638. Return the grammar productions, filtered by the left-hand side
  639. or the first item in the right-hand side.
  640. :param lhs: Only return productions with the given left-hand side.
  641. :param rhs: Only return productions with the given first item
  642. in the right-hand side.
  643. :param empty: Only return productions with an empty right-hand side.
  644. :rtype: list(Production)
  645. """
  646. if rhs and empty:
  647. raise ValueError("You cannot select empty and non-empty "
  648. "productions at the same time.")
  649. # no constraints so return everything
  650. if not lhs and not rhs:
  651. if empty:
  652. return self._empty_productions
  653. else:
  654. return self._productions
  655. # only lhs specified so look up its index
  656. elif lhs and not rhs:
  657. if empty:
  658. return self._empty_index.get(self._get_type_if_possible(lhs), [])
  659. else:
  660. return self._lhs_index.get(self._get_type_if_possible(lhs), [])
  661. # only rhs specified so look up its index
  662. elif rhs and not lhs:
  663. return self._rhs_index.get(self._get_type_if_possible(rhs), [])
  664. # intersect
  665. else:
  666. return [prod for prod in self._lhs_index.get(self._get_type_if_possible(lhs), [])
  667. if prod in self._rhs_index.get(self._get_type_if_possible(rhs), [])]
  668. def leftcorners(self, cat):
  669. """
  670. Return the set of all words that the given category can start with.
  671. Also called the "first set" in compiler construction.
  672. """
  673. raise NotImplementedError("Not implemented yet")
  674. def leftcorner_parents(self, cat):
  675. """
  676. Return the set of all categories for which the given category
  677. is a left corner.
  678. """
  679. raise NotImplementedError("Not implemented yet")
  680. def _get_type_if_possible(self, item):
  681. """
  682. Helper function which returns the ``TYPE`` feature of the ``item``,
  683. if it exists, otherwise it returns the ``item`` itself
  684. """
  685. if isinstance(item, dict) and TYPE in item:
  686. return FeatureValueType(item[TYPE])
  687. else:
  688. return item
  689. @total_ordering
  690. @python_2_unicode_compatible
  691. class FeatureValueType(object):
  692. """
  693. A helper class for ``FeatureGrammars``, designed to be different
  694. from ordinary strings. This is to stop the ``FeatStruct``
  695. ``FOO[]`` from being compare equal to the terminal "FOO".
  696. """
  697. def __init__(self, value):
  698. self._value = value
  699. self._hash = hash(value)
  700. def __repr__(self):
  701. return '<%s>' % self._value
  702. def __eq__(self, other):
  703. return type(self) == type(other) and self._value == other._value
  704. def __ne__(self, other):
  705. return not self == other
  706. def __lt__(self, other):
  707. if not isinstance(other, FeatureValueType):
  708. raise_unorderable_types("<", self, other)
  709. return self._value < other._value
  710. def __hash__(self):
  711. return self._hash
  712. @python_2_unicode_compatible
  713. class DependencyGrammar(object):
  714. """
  715. A dependency grammar. A DependencyGrammar consists of a set of
  716. productions. Each production specifies a head/modifier relationship
  717. between a pair of words.
  718. """
  719. def __init__(self, productions):
  720. """
  721. Create a new dependency grammar, from the set of ``Productions``.
  722. :param productions: The list of productions that defines the grammar
  723. :type productions: list(Production)
  724. """
  725. self._productions = productions
  726. def contains(self, head, mod):
  727. """
  728. :param head: A head word.
  729. :type head: str
  730. :param mod: A mod word, to test as a modifier of 'head'.
  731. :type mod: str
  732. :return: true if this ``DependencyGrammar`` contains a
  733. ``DependencyProduction`` mapping 'head' to 'mod'.
  734. :rtype: bool
  735. """
  736. for production in self._productions:
  737. for possibleMod in production._rhs:
  738. if(production._lhs == head and possibleMod == mod):
  739. return True
  740. return False
  741. def __contains__(self, head, mod):
  742. """
  743. Return True if this ``DependencyGrammar`` contains a
  744. ``DependencyProduction`` mapping 'head' to 'mod'.
  745. :param head: A head word.
  746. :type head: str
  747. :param mod: A mod word, to test as a modifier of 'head'.
  748. :type mod: str
  749. :rtype: bool
  750. """
  751. for production in self._productions:
  752. for possibleMod in production._rhs:
  753. if(production._lhs == head and possibleMod == mod):
  754. return True
  755. return False
  756. # # should be rewritten, the set comp won't work in all comparisons
  757. # def contains_exactly(self, head, modlist):
  758. # for production in self._productions:
  759. # if(len(production._rhs) == len(modlist)):
  760. # if(production._lhs == head):
  761. # set1 = Set(production._rhs)
  762. # set2 = Set(modlist)
  763. # if(set1 == set2):
  764. # return True
  765. # return False
  766. def __str__(self):
  767. """
  768. Return a verbose string representation of the ``DependencyGrammar``
  769. :rtype: str
  770. """
  771. str = 'Dependency grammar with %d productions' % len(self._productions)
  772. for production in self._productions:
  773. str += '\n %s' % production
  774. return str
  775. def __repr__(self):
  776. """
  777. Return a concise string representation of the ``DependencyGrammar``
  778. """
  779. return 'Dependency grammar with %d productions' % len(self._productions)
  780. @python_2_unicode_compatible
  781. class StatisticalDependencyGrammar(object):
  782. """
  783. """
  784. def __init__(self, productions, events, tags):
  785. self._productions = productions
  786. self._events = events
  787. self._tags = tags
  788. def contains(self, head, mod):
  789. """
  790. Return True if this ``DependencyGrammar`` contains a
  791. ``DependencyProduction`` mapping 'head' to 'mod'.
  792. :param head: A head word.
  793. :type head: str
  794. :param mod: A mod word, to test as a modifier of 'head'.
  795. :type mod: str
  796. :rtype: bool
  797. """
  798. for production in self._productions:
  799. for possibleMod in production._rhs:
  800. if(production._lhs == head and possibleMod == mod):
  801. return True
  802. return False
  803. def __str__(self):
  804. """
  805. Return a verbose string representation of the ``StatisticalDependencyGrammar``
  806. :rtype: str
  807. """
  808. str = 'Statistical dependency grammar with %d productions' % len(self._productions)
  809. for production in self._productions:
  810. str += '\n %s' % production
  811. str += '\nEvents:'
  812. for event in self._events:
  813. str += '\n %d:%s' % (self._events[event], event)
  814. str += '\nTags:'
  815. for tag_word in self._tags:
  816. str += '\n %s:\t(%s)' % (tag_word, self._tags[tag_word])
  817. return str
  818. def __repr__(self):
  819. """
  820. Return a concise string representation of the ``StatisticalDependencyGrammar``
  821. """
  822. return 'Statistical Dependency grammar with %d productions' % len(self._productions)
  823. class WeightedGrammar(ContextFreeGrammar):
  824. """
  825. A probabilistic context-free grammar. A Weighted Grammar consists
  826. of a start state and a set of weighted productions. The set of
  827. terminals and nonterminals is implicitly specified by the productions.
  828. PCFG productions should be ``WeightedProductions``.
  829. ``WeightedGrammars`` impose the constraint that the set of
  830. productions with any given left-hand-side must have probabilities
  831. that sum to 1.
  832. If you need efficient key-based access to productions, you can use
  833. a subclass to implement it.
  834. :type EPSILON: float
  835. :cvar EPSILON: The acceptable margin of error for checking that
  836. productions with a given left-hand side have probabilities
  837. that sum to 1.
  838. """
  839. EPSILON = 0.01
  840. def __init__(self, start, productions, calculate_leftcorners=True):
  841. """
  842. Create a new context-free grammar, from the given start state
  843. and set of ``WeightedProductions``.
  844. :param start: The start symbol
  845. :type start: Nonterminal
  846. :param productions: The list of productions that defines the grammar
  847. :type productions: list(Production)
  848. :raise ValueError: if the set of productions with any left-hand-side
  849. do not have probabilities that sum to a value within
  850. EPSILON of 1.
  851. :param calculate_leftcorners: False if we don't want to calculate the
  852. leftcorner relation. In that case, some optimized chart parsers won't work.
  853. :type calculate_leftcorners: bool
  854. """
  855. ContextFreeGrammar.__init__(self, start, productions, calculate_leftcorners)
  856. # Make sure that the probabilities sum to one.
  857. probs = {}
  858. for production in productions:
  859. probs[production.lhs()] = (probs.get(production.lhs(), 0) +
  860. production.prob())
  861. for (lhs, p) in probs.items():
  862. if not ((1-WeightedGrammar.EPSILON) < p <
  863. (1+WeightedGrammar.EPSILON)):
  864. raise ValueError("Productions for %r do not sum to 1" % lhs)
  865. #################################################################
  866. # Inducing Grammars
  867. #################################################################
  868. # Contributed by Nathan Bodenstab <bodenstab@cslu.ogi.edu>
  869. def induce_pcfg(start, productions):
  870. """
  871. Induce a PCFG grammar from a list of productions.
  872. The probability of a production A -> B C in a PCFG is:
  873. | count(A -> B C)
  874. | P(B, C | A) = --------------- where \* is any right hand side
  875. | count(A -> \*)
  876. :param start: The start symbol
  877. :type start: Nonterminal
  878. :param productions: The list of productions that defines the grammar
  879. :type productions: list(Production)
  880. """
  881. # Production count: the number of times a given production occurs
  882. pcount = {}
  883. # LHS-count: counts the number of times a given lhs occurs
  884. lcount = {}
  885. for prod in productions:
  886. lcount[prod.lhs()] = lcount.get(prod.lhs(), 0) + 1
  887. pcount[prod] = pcount.get(prod, 0) + 1
  888. prods = [WeightedProduction(p.lhs(), p.rhs(),
  889. prob=float(pcount[p]) / lcount[p.lhs()])
  890. for p in pcount]
  891. return WeightedGrammar(start, prods)
  892. #################################################################
  893. # Parsing Grammars
  894. #################################################################
  895. # Parsing CFGs
  896. def parse_cfg_production(input):
  897. """
  898. Return a list of context-free ``Productions``.
  899. """
  900. return parse_production(input, standard_nonterm_parser)
  901. def parse_cfg(input, encoding=None):
  902. """
  903. Return the ``ContextFreeGrammar`` corresponding to the input string(s).
  904. :param input: a grammar, either in the form of a string or
  905. as a list of strings.
  906. """
  907. start, productions = parse_grammar(input, standard_nonterm_parser,
  908. encoding=encoding)
  909. return ContextFreeGrammar(start, productions)
  910. # Parsing Probabilistic CFGs
  911. def parse_pcfg_production(input):
  912. """
  913. Return a list of PCFG ``WeightedProductions``.
  914. """
  915. return parse_production(input, standard_nonterm_parser, probabilistic=True)
  916. def parse_pcfg(input, encoding=None):
  917. """
  918. Return a probabilistic ``WeightedGrammar`` corresponding to the
  919. input string(s).
  920. :param input: a grammar, either in the form of a string or else
  921. as a list of strings.
  922. """
  923. start, productions = parse_grammar(input, standard_nonterm_parser,
  924. probabilistic=True, encoding=encoding)
  925. return WeightedGrammar(start, productions)
  926. # Parsing Feature-based CFGs
  927. def parse_fcfg_production(input, fstruct_parser):
  928. """
  929. Return a list of feature-based ``Productions``.
  930. """
  931. return parse_production(input, fstruct_parser)
  932. def parse_fcfg(input, features=None, logic_parser=None, fstruct_parser=None,
  933. encoding=None):
  934. """
  935. Return a feature structure based ``FeatureGrammar``.
  936. :param input: a grammar, either in the form of a string or else
  937. as a list of strings.
  938. :param features: a tuple of features (default: SLASH, TYPE)
  939. :param logic_parser: a parser for lambda-expressions,
  940. by default, ``LogicParser()``
  941. :param fstruct_parser: a feature structure parser
  942. (only if features and logic_parser is None)
  943. """
  944. if features is None:
  945. features = (SLASH, TYPE)
  946. if fstruct_parser is None:
  947. fstruct_parser = FeatStructParser(features, FeatStructNonterminal,
  948. logic_parser=logic_parser)
  949. elif logic_parser is not None:
  950. raise Exception('\'logic_parser\' and \'fstruct_parser\' must '
  951. 'not both be set')
  952. start, productions = parse_grammar(input, fstruct_parser.partial_parse,
  953. encoding=encoding)
  954. return FeatureGrammar(start, productions)
  955. # Parsing generic grammars
  956. _ARROW_RE = re.compile(r'\s* -> \s*', re.VERBOSE)
  957. _PROBABILITY_RE = re.compile(r'( \[ [\d\.]+ \] ) \s*', re.VERBOSE)
  958. _TERMINAL_RE = re.compile(r'( "[^"]+" | \'[^\']+\' ) \s*', re.VERBOSE)
  959. _DISJUNCTION_RE = re.compile(r'\| \s*', re.VERBOSE)
  960. def parse_production(line, nonterm_parser, probabilistic=False):
  961. """
  962. Parse a grammar rule, given as a string, and return
  963. a list of productions.
  964. """
  965. pos = 0
  966. # Parse the left-hand side.
  967. lhs, pos = nonterm_parser(line, pos)
  968. # Skip over the arrow.
  969. m = _ARROW_RE.match(line, pos)
  970. if not m: raise ValueError('Expected an arrow')
  971. pos = m.end()
  972. # Parse the right hand side.
  973. probabilities = [0.0]
  974. rhsides = [[]]
  975. while pos < len(line):
  976. # Probability.
  977. m = _PROBABILITY_RE.match(line, pos)
  978. if probabilistic and m:
  979. pos = m.end()
  980. probabilities[-1] = float(m.group(1)[1:-1])
  981. if probabilities[-1] > 1.0:
  982. raise ValueError('Production probability %f, '
  983. 'should not be greater than 1.0' %
  984. (probabilities[-1],))
  985. # String -- add terminal.
  986. elif line[pos] in "\'\"":
  987. m = _TERMINAL_RE.match(line, pos)
  988. if not m: raise ValueError('Unterminated string')
  989. rhsides[-1].append(m.group(1)[1:-1])
  990. pos = m.end()
  991. # Vertical bar -- start new rhside.
  992. elif line[pos] == '|':
  993. m = _DISJUNCTION_RE.match(line, pos)
  994. probabilities.append(0.0)
  995. rhsides.append([])
  996. pos = m.end()
  997. # Anything else -- nonterminal.
  998. else:
  999. nonterm, pos = nonterm_parser(line, pos)
  1000. rhsides[-1].append(nonterm)
  1001. if probabilistic:
  1002. return [WeightedProduction(lhs, rhs, prob=probability)
  1003. for (rhs, probability) in zip(rhsides, probabilities)]
  1004. else:
  1005. return [Production(lhs, rhs) for rhs in rhsides]
  1006. def parse_grammar(input, nonterm_parser, probabilistic=False, encoding=None):
  1007. """
  1008. Return a pair consisting of a starting category and a list of
  1009. ``Productions``.
  1010. :param input: a grammar, either in the form of a string or else
  1011. as a list of strings.
  1012. :param nonterm_parser: a function for parsing nonterminals.
  1013. It should take a ``(string, position)`` as argument and
  1014. return a ``(nonterminal, position)`` as result.
  1015. :param probabilistic: are the grammar rules probabilistic?
  1016. :type probabilistic: bool
  1017. :param encoding: the encoding of the grammar, if it is a binary string
  1018. :type encoding: str
  1019. """
  1020. if encoding is not None:
  1021. input = input.decode(encoding)
  1022. if isinstance(input, string_types):
  1023. lines = input.split('\n')
  1024. else:
  1025. lines = input
  1026. start = None
  1027. productions = []
  1028. continue_line = ''
  1029. for linenum, line in enumerate(lines):
  1030. line = continue_line + line.strip()
  1031. if line.startswith('#') or line=='': continue
  1032. if line.endswith('\\'):
  1033. continue_line = line[:-1].rstrip()+' '
  1034. continue
  1035. continue_line = ''
  1036. try:
  1037. if line[0] == '%':
  1038. directive, args = line[1:].split(None, 1)
  1039. if directive == 'start':
  1040. start, pos = nonterm_parser(args, 0)
  1041. if pos != len(args):
  1042. raise ValueError('Bad argument to start directive')
  1043. else:
  1044. raise ValueError('Bad directive')
  1045. else:
  1046. # expand out the disjunctions on the RHS
  1047. productions += parse_production(line, nonterm_parser, probabilistic)
  1048. except ValueError as e:
  1049. raise ValueError('Unable to parse line %s: %s\n%s' %
  1050. (linenum+1, line, e))
  1051. if not productions:
  1052. raise ValueError('No productions found!')
  1053. if not start:
  1054. start = productions[0].lhs()
  1055. return (start, productions)
  1056. _STANDARD_NONTERM_RE = re.compile('( [\w/][\w/^<>-]* ) \s*', re.VERBOSE)
  1057. def standard_nonterm_parser(string, pos):
  1058. m = _STANDARD_NONTERM_RE.match(string, pos)
  1059. if not m: raise ValueError('Expected a nonterminal, found: '
  1060. + string[pos:])
  1061. return (Nonterminal(m.group(1)), m.end())
  1062. #################################################################
  1063. # Parsing Dependency Grammars
  1064. #################################################################
  1065. _PARSE_DG_RE = re.compile(r'''^\s* # leading whitespace
  1066. ('[^']+')\s* # single-quoted lhs
  1067. (?:[-=]+>)\s* # arrow
  1068. (?:( # rhs:
  1069. "[^"]+" # doubled-quoted terminal
  1070. | '[^']+' # single-quoted terminal
  1071. | \| # disjunction
  1072. )
  1073. \s*) # trailing space
  1074. *$''', # zero or more copies
  1075. re.VERBOSE)
  1076. _SPLIT_DG_RE = re.compile(r'''('[^']'|[-=]+>|"[^"]+"|'[^']+'|\|)''')
  1077. def parse_dependency_grammar(s):
  1078. productions = []
  1079. for linenum, line in enumerate(s.split('\n')):
  1080. line = line.strip()
  1081. if line.startswith('#') or line=='': continue
  1082. try: productions += parse_dependency_production(line)
  1083. except ValueError:
  1084. raise ValueError('Unable to parse line %s: %s' % (linenum, line))
  1085. if len(productions) == 0:
  1086. raise ValueError('No productions found!')
  1087. return DependencyGrammar(productions)
  1088. def parse_dependency_production(s):
  1089. if not _PARSE_DG_RE.match(s):
  1090. raise ValueError('Bad production string')
  1091. pieces = _SPLIT_DG_RE.split(s)
  1092. pieces = [p for i,p in enumerate(pieces) if i%2==1]
  1093. lhside = pieces[0].strip('\'\"')
  1094. rhsides = [[]]
  1095. for piece in pieces[2:]:
  1096. if piece == '|':
  1097. rhsides.append([])
  1098. else:
  1099. rhsides[-1].append(piece.strip('\'\"'))
  1100. return [DependencyProduction(lhside, rhside) for rhside in rhsides]
  1101. #################################################################
  1102. # Demonstration
  1103. #################################################################
  1104. def cfg_demo():
  1105. """
  1106. A demonstration showing how ``ContextFreeGrammars`` can be created and used.
  1107. """
  1108. from nltk import nonterminals, Production, parse_cfg
  1109. # Create some nonterminals
  1110. S, NP, VP, PP = nonterminals('S, NP, VP, PP')
  1111. N, V, P, Det = nonterminals('N, V, P, Det')
  1112. VP_slash_NP = VP/NP
  1113. print('Some nonterminals:', [S, NP, VP, PP, N, V, P, Det, VP/NP])
  1114. print(' S.symbol() =>', repr(S.symbol()))
  1115. print()
  1116. print(Production(S, [NP]))
  1117. # Create some Grammar Productions
  1118. grammar = parse_cfg("""
  1119. S -> NP VP
  1120. PP -> P NP
  1121. NP -> Det N | NP PP
  1122. VP -> V NP | VP PP
  1123. Det -> 'a' | 'the'
  1124. N -> 'dog' | 'cat'
  1125. V -> 'chased' | 'sat'
  1126. P -> 'on' | 'in'
  1127. """)
  1128. print('A Grammar:', repr(grammar))
  1129. print(' grammar.start() =>', repr(grammar.start()))
  1130. print(' grammar.productions() =>', end=' ')
  1131. # Use string.replace(...) is to line-wrap the output.
  1132. print(repr(grammar.productions()).replace(',', ',\n'+' '*25))
  1133. print()
  1134. toy_pcfg1 = parse_pcfg("""
  1135. S -> NP VP [1.0]
  1136. NP -> Det N [0.5] | NP PP [0.25] | 'John' [0.1] | 'I' [0.15]
  1137. Det -> 'the' [0.8] | 'my' [0.2]
  1138. N -> 'man' [0.5] | 'telescope' [0.5]
  1139. VP -> VP PP [0.1] | V NP [0.7] | V [0.2]
  1140. V -> 'ate' [0.35] | 'saw' [0.65]
  1141. PP -> P NP [1.0]
  1142. P -> 'with' [0.61] | 'under' [0.39]
  1143. """)
  1144. toy_pcfg2 = parse_pcfg("""
  1145. S -> NP VP [1.0]
  1146. VP -> V NP [.59]
  1147. VP -> V [.40]
  1148. VP -> VP PP [.01]
  1149. NP -> Det N [.41]
  1150. NP -> Name [.28]
  1151. NP -> NP PP [.31]
  1152. PP -> P NP [1.0]
  1153. V -> 'saw' [.21]
  1154. V -> 'ate' [.51]
  1155. V -> 'ran' [.28]
  1156. N -> 'boy' [.11]
  1157. N -> 'cookie' [.12]
  1158. N -> 'table' [.13]
  1159. N -> 'telescope' [.14]
  1160. N -> 'hill' [.5]
  1161. Name -> 'Jack' [.52]
  1162. Name -> 'Bob' [.48]
  1163. P -> 'with' [.61]
  1164. P -> 'under' [.39]
  1165. Det -> 'the' [.41]
  1166. Det -> 'a' [.31]
  1167. Det -> 'my' [.28]
  1168. """)
  1169. def pcfg_demo():
  1170. """
  1171. A demonstration showing how a ``WeightedGrammar`` can be created and used.
  1172. """
  1173. from nltk.corpus import treebank
  1174. from nltk import treetransforms
  1175. from nltk import induce_pcfg
  1176. from nltk.parse import pchart
  1177. pcfg_prods = toy_pcfg1.productions()
  1178. pcfg_prod = pcfg_prods[2]
  1179. print('A PCFG production:', repr(pcfg_prod))
  1180. print(' pcfg_prod.lhs() =>', repr(pcfg_prod.lhs()))
  1181. print(' pcfg_prod.rhs() =>', repr(pcfg_prod.rhs()))
  1182. print(' pcfg_prod.prob() =>', repr(pcfg_prod.prob()))
  1183. print()
  1184. grammar = toy_pcfg2
  1185. print('A PCFG grammar:', repr(grammar))
  1186. print(' grammar.start() =>', repr(grammar.start()))
  1187. print(' grammar.productions() =>', end=' ')
  1188. # Use .replace(...) is to line-wrap the output.

Large files files are truncated, but you can click here to view the full file