Code Monkey home page Code Monkey logo

opencog / link-grammar Goto Github PK

View Code? Open in Web Editor NEW
383.0 42.0 116.0 38.64 MB

The CMU Link Grammar natural language parser

License: GNU Lesser General Public License v2.1

CMake 0.28% Shell 0.35% AutoIt 0.85% C 54.15% Java 1.99% Common Lisp 0.76% OCaml 0.53% Perl 3.34% Python 3.98% C++ 14.73% HTML 0.27% TeX 0.18% Tcl 0.03% Makefile 1.55% M4 15.94% Batchfile 0.26% Lex 0.31% Dockerfile 0.16% JavaScript 0.08% CoffeeScript 0.26%
english russian nlp parser grammar natural-language natural-language-processing link-grammar

link-grammar's Introduction

Link Grammar Parser

Version 5.12.4

Main node.js

The Link Grammar Parser exhibits the linguistic (natural language) structure of English, Thai, Russian, Arabic, Persian and limited subsets of a half-dozen other languages. This structure is a graph of typed links (edges) between the words in a sentence. One may obtain the more conventional HPSG (constituent) and dependency style parses from Link Grammar by applying a collection of rules to convert to these different formats. This is possible because Link Grammar goes a bit "deeper" into the "syntactico-semantic" structure of a sentence: it provides considerably more fine-grained and detailed information than what is commonly available in conventional parsers.

The theory of Link Grammar parsing was originally developed in 1991 by Davy Temperley, John Lafferty and Daniel Sleator, at the time professors of linguistics and computer science at the Carnegie Mellon University. The three initial publications on this theory provide the best introduction and overview; since then, there have been hundreds of publications further exploring, examining and extending the ideas.

Although based on the original Carnegie-Mellon code base, the current Link Grammar package has dramatically evolved and is profoundly different from earlier versions. There have been innumerable bug fixes; performance has improved by several orders of magnitude. The package is fully multi-threaded, fully UTF-8 enabled, and has been scrubbed for security, enabling cloud deployment. Parse coverage of English has been dramatically improved; other languages have been added (most notably, Thai and Russian). There is a raft of new features, including support for morphology, dialects, and a fine-grained weight (cost) system, allowing vector-embedding-like behaviour. There is a new, sophisticated tokenizer tailored for morphology: it can offer alternative splittings for morphologically ambiguous words. Dictionaries can be updated at run-time, enabling systems that perform continuous learning of grammar to also parse at the same time. That is, dictionary updates and parsing are mutually thread-safe. Classes of words can be recognized with regexes. Random planar graph parsing is fully supported; this allows uniform sampling of the space of planar graphs. A detailed report of what has changed can be found in the ChangeLog.

This code is released under the LGPL license, making it freely available for both private and commercial use, with few restrictions. The terms of the license are given in the LICENSE file included with this software.

Please see the main web page for more information. This version is a continuation of the original CMU parser.

New!

As of version 5.9.0, the system include an experimental system for generating sentences. These are specified using a "fill in the blanks" API, where words are substituted into wild-card locations, whenever the result is a grammatically valid sentence. Additional details are in the man page: man link-generator (in the man subdirectory).

This generator is used in the OpenCog Language Learning project, which aims to automatically learn Link Grammars from corpora, using brand-new and innovative information theoretic techniques, somewhat similar to those found in artificial neural nets (deep learning), but using explicitly symbolic representations.

Quick Overview

The parser includes API's in various different programming languages, as well as a handy command-line tool for playing with it. Here's some typical output:

linkparser> This is a test!
	Linkage 1, cost vector = (UNUSED=0 DIS= 0.00 LEN=6)

    +-------------Xp------------+
    +----->WV----->+---Ost--+   |
    +---Wd---+-Ss*b+  +Ds**c+   |
    |        |     |  |     |   |
LEFT-WALL this.p is.v a  test.n !

(S (NP this.p) (VP is.v (NP a test.n)) !)

            LEFT-WALL    0.000  Wd+ hWV+ Xp+
               this.p    0.000  Wd- Ss*b+
                 is.v    0.000  Ss- dWV- O*t+
                    a    0.000  Ds**c+
               test.n    0.000  Ds**c- Os-
                    !    0.000  Xp- RW+
           RIGHT-WALL    0.000  RW-

This rather busy display illustrates many interesting things. For example, the Ss*b link connects the verb and the subject, and indicates that the subject is singular. Likewise, the Ost link connects the verb and the object, and also indicates that the object is singular. The WV (verb-wall) link points at the head-verb of the sentence, while the Wd link points at the head-noun. The Xp link connects to the trailing punctuation. The Ds**c link connects the noun to the determiner: it again confirms that the noun is singular, and also that the noun starts with a consonant. (The PH link, not required here, is used to force phonetic agreement, distinguishing 'a' from 'an'). These link types are documented in the English Link Documentation.

The bottom of the display is a listing of the "disjuncts" used for each word. The disjuncts are simply a list of the connectors that were employed to form the links. They are particularly interesting because they serve as an extremely fine-grained form of a "part of speech". Thus, for example: the disjunct S- O+ indicates a transitive verb: its a verb that takes both a subject and an object. The additional markup above indicates that 'is' is not only being used as a transitive verb, but it also indicates finer details: a transitive verb that took a singular subject, and was used (is usable as) the head verb of a sentence. The floating-point value is the "cost" of the disjunct; it very roughly captures the idea of the log-probability of this particular grammatical usage. Much as parts-of-speech correlate with word-meanings, so also fine-grains parts-of-speech correlate with much finer distinctions and gradations of meaning.

The link-grammar parser also supports morphological analysis. Here is an example in Russian:

linkparser> это теста
	Linkage 1, cost vector = (UNUSED=0 DIS= 0.00 LEN=4)

             +-----MVAip-----+
    +---Wd---+       +-LLCAG-+
    |        |       |       |
LEFT-WALL это.msi тест.= =а.ndnpi

The LL link connects the stem 'тест' to the suffix 'а'. The MVA link connects only to the suffix, because, in Russian, it is the suffixes that carry all of the syntactic structure, and not the stems. The Russian lexis is documented here.

The Thai dictionary is now fully developed, effectively covering the entire language. An example in Thai:

linkparser> นายกรัฐมนตรี ขึ้น กล่าว สุนทรพจน์
	Linkage 1, cost vector = (UNUSED=0 DIS= 2.00 LEN=2)

    +---------LWs--------+
    |           +<---S<--+--VS-+-->O-->+
    |           |        |     |       |
LEFT-WALL นายกรัฐมนตรี.n ขึ้น.v กล่าว.v สุนทรพจน์.n

The VS link connects two verbs 'ขึ้น' and 'กล่าว' in a serial verb construction. A summary of link types is documented here. Full documentation of Thai Link Grammar can be found here.

Thai Link Grammar also accepts POS-tagged and named-entity-tagged inputs. Each word can be annotated with the Link POS tag. For example:

linkparser> เมื่อวานนี้.n มี.ve คน.n มา.x ติดต่อ.v คุณ.pr ครับ.pt
Found 1 linkage (1 had no P.P. violations)
	Unique linkage, cost vector = (UNUSED=0 DIS= 0.00 LEN=12)

                          +---------------------PT--------------------+
    +---------LWs---------+---------->VE---------->+                  |
    |           +<---S<---+-->O-->+       +<--AXw<-+--->O--->+        |
    |           |         |       |       |        |         |        |
LEFT-WALL เมื่อวานนี้.n[!] มี.ve[!] คน.n[!] มา.x[!] ติดต่อ.v[!] คุณ.pr[!] ครับ.pt[!]

Full documentation for the Thai dictionary can be found here.

The Thai dictionary accepts LST20 tagsets for POS and named entities, to bridge the gap between fundamental NLP tools and the Link Parser. For example:

linkparser> linkparser> วันที่_25_ธันวาคม@DTM ของ@PS ทุก@AJ ปี@NN เป็น@VV วัน@NN คริสต์มาส@NN
Found 348 linkages (348 had no P.P. violations)
	Linkage 1, cost vector = (UNUSED=0 DIS= 1.00 LEN=10)

    +--------------------------------LWs--------------------------------+
    |               +<------------------------S<------------------------+
    |               |                +---------->PO--------->+          |
    |               +----->AJpr----->+            +<---AJj<--+          +---->O---->+------NZ-----+
    |               |                |            |          |          |           |             |
LEFT-WALL วันที่_25_ธันวาคม@DTM[!] ของ@PS[!].pnn ทุก@AJ[!].jl ปี@NN[!].n เป็น@VV[!].v วัน@NN[!].na คริสต์มาส@NN[!].n

Note that each word above is annotated with LST20 POS tags and NE tags. Full documentation for both the Link POS tags and the LST20 tagsets can be found here. More information about LST20, e.g. annotation guideline and data statistics, can be found here.

The any language supports uniformly-sampled random planar graphs:

linkparser> asdf qwer tyuiop fghj bbb
Found 1162 linkages (1162 had no P.P. violations)

             +-------ANY------+-------ANY------+
    +---ANY--+--ANY--+        +---ANY--+--ANY--+
    |        |       |        |        |       |
LEFT-WALL asdf[!] qwer[!] tyuiop[!] fghj[!] bbb[!]

The ady language does likewise, performing random morphological splittings:

linkparser> asdf qwerty fghjbbb
Found 1512 linkages (1512 had no P.P. violations)

                                  +------------------ANY-----------------+
    +-----ANY----+-------ANY------+                  +---------LL--------+
    |            |                |                  |                   |
LEFT-WALL asdf[!ANY-WORD] qwerty[!ANY-WORD] fgh[!SIMPLE-STEM].= =jbbb[!SIMPLE-SUFF]

Theory and Documentation

An extended overview and summary can be found in the Link Grammar Wikipedia page, which touches on most of the import, primary aspects of the theory. However, it is no substitute for the original papers published on the topic:

There are many more papers and references listed on the primary Link Grammar website

See also the C/C++ API documentation. Bindings for other programming languages, including python3, java and node.js, can be found in the bindings directory. (There are two sets of javascript bindings: one set for the library API, and another set for the command-line parser.)

Contents

Content Description
LICENSE The license describing terms of use
link-grammar/*.c The program. (Written in ANSI-C)
---- ----
bindings/autoit/ Optional AutoIt language bindings.
bindings/java/ Optional Java language bindings.
bindings/js/ Optional JavaScript language bindings.
bindings/lisp/ Optional Common Lisp language bindings.
bindings/node.js/ Optional node.js language bindings.
bindings/ocaml/ Optional OCaML language bindings.
bindings/python/ Optional Python3 language bindings.
bindings/python-examples/ Link-grammar test suite and Python language binding usage example.
bindings/swig/ SWIG interface file, for other FFI interfaces.
bindings/vala/ Optional Vala language bindings.
---- ----
data/en/ English language dictionaries.
data/en/4.0.dict The file containing the dictionary definitions.
data/en/4.0.knowledge The post-processing knowledge file.
data/en/4.0.constituents The constituent knowledge file.
data/en/4.0.affix The affix (prefix/suffix) file.
data/en/4.0.regex Regular expression-based morphology guesser.
data/en/tiny.dict A small example dictionary.
data/en/words/ A directory full of word lists.
data/en/corpus*.batch Example corpora used for testing.
---- ----
data/ru/ A full-fledged Russian dictionary
data/th/ A full-fledged Thai dictionary (100,000+ words)
data/ar/ A fairly complete Arabic dictionary
data/fa/ A Persian (Farsi) dictionary
data/de/ A small prototype German dictionary
data/lt/ A small prototype Lithuanian dictionary
data/id/ A small prototype Indonesian dictionary
data/vn/ A small prototype Vietnamese dictionary
data/he/ An experimental Hebrew dictionary
data/kz/ An experimental Kazakh dictionary
data/tr/ An experimental Turkish dictionary
---- ----
morphology/ar/ An Arabic morphology analyzer
morphology/fa/ An Persian morphology analyzer
---- ----
LICENSE The license for this code and data
ChangeLog A compendium of recent changes.
configure The GNU configuration script
autogen.sh Developer's configure maintenance tool
debug/ Information about debugging the library
msvc/ Microsoft Visual-C project files
mingw/ Information on using MinGW under MSYS or Cygwin

UNPACKING and signature verification

The system is distributed using the conventional tar.gz format; it can be extracted using the tar -zxf link-grammar.tar.gz command at the command line.

A tarball of the latest version can be downloaded from:
https://www.gnucash.org/link-grammar/downloads/

The files have been digitally signed to make sure that there was no corruption of the dataset during download, and to help ensure that no malicious changes were made to the code internals by third parties. The signatures can be checked with the gpg command:

gpg --verify link-grammar-5.12.4.tar.gz.asc

which should generate output identical to (except for the date):

gpg: Signature made Thu 26 Apr 2012 12:45:31 PM CDT using RSA key ID E0C0651C
gpg: Good signature from "Linas Vepstas (Hexagon Architecture Patches) <[email protected]>"
gpg:                 aka "Linas Vepstas (LKML) <[email protected]>"

Alternately, the md5 check-sums can be verified. These do not provide cryptographic security, but they can detect simple corruption. To verify the check-sums, issue md5sum -c MD5SUM at the command line.

Tags in git can be verified by performing the following:

gpg --recv-keys --keyserver keyserver.ubuntu.com EB6AA534E0C0651C
git tag -v link-grammar-5.10.5

CREATING the system

To compile the link-grammar shared library and demonstration program, at the command line, type:

./configure
make
make check

To install, change user to "root" and say

make install
ldconfig

This will install the liblink-grammar.so library into /usr/local/lib, the header files in /usr/local/include/link-grammar, and the dictionaries into /usr/local/share/link-grammar. Running ldconfig will rebuild the shared library cache. To verify that the install was successful, run (as a non-root user)

make installcheck

Optional system libraries

The link-grammar library has optional features that are enabled automatically if configure detects certain libraries. These libraries are optional on most of the systems and if the feature they add is desired, corresponding libraries need to be installed before running configure.

The library package names may vary on various systems (consult Google if needed...). For example, the names may include -devel instead of -dev, or be without it altogether. The library names may be without the prefix lib.

  • libsqlite3-dev (for SQLite-backed dictionary)
  • libz1g-dev or libz-devel (currently needed for the bundled minisat2)
  • libedit-dev (see Editline)
  • libhunspell-dev or libaspell-dev (and the corresponding English dictionary).
  • libtre-dev or libpcre2-dev (much faster than the libc REGEX implementation, and needed for correctness on FreeBSD and Cygwin).
    Using libpcre2-dev is strongly recommended. It must be used on certain systems (as specified in their BUILDING sections).

Note: BSD-derived operating systems (including macOS) need the argp-standalone library in order to build the link-generator program.

Editline

If libedit-dev is installed, then the arrow keys can be used to edit the input to the link-parser tool; the up and down arrow keys will recall previous entries. You want this; it makes testing and editing much easier.

Node.js Bindings

Two versions of node.js bindings are included. One version wraps the library; the other uses emscripten to wrap the command-line tool. The library bindings are in bindings/node.js while the emscripten wrapper is in bindings/js.

These are built using npm. First, you must build the core C library. Then do the following:

   cd bindings/node.js
   npm install
   npm run make

This will create the library bindings and also run a small unit test (which should pass). An example can be found in bindings/node.js/examples/simple.js.

For the command-line wrapper, do the following:

   cd bindings/js
   ./install_emsdk.sh
   ./build_packages.sh

Python3 Bindings

The Python3 bindings are built by default, providing that the corresponding Python development packages are installed. (Python2 bindings are no longer supported.)

These packages are:

NOTE: Before issuing configure (see below) you have to validate that the required python versions can be invoked using your PATH.

The use of the Python bindings is OPTIONAL; you do not need these if you do not plan to use link-grammar with Python. If you like to disable Python bindings, use:

./configure --disable-python-bindings

The linkgrammar.py module provides a high-level interface in Python. The example.py and sentence-check.py scripts provide a demo, and tests.py runs unit tests.

  • macOS:
    • Due to file permissions settings, macOS users may need to install python bindindings into custom directory locations. This can be done by saying make install pythondir=/where/to/install

Java Bindings

By default, the Makefiles attempt to build the Java bindings. The use of the Java bindings is OPTIONAL; you do not need these if you do not plan to use link-grammar with Java. You can skip building the Java bindings by disabling as follows:

./configure --disable-java-bindings

If jni.h isn't found, or if ant isn't found, then the java bindings will not be built.

Notes about finding jni.h:
Some common java JVM distributions (most notably, the ones from Sun) place this file in unusual locations, where it cannot be automatically found. To remedy this, make sure that environment variable JAVA_HOME is set correctly. The configure script looks for jni.h in $JAVA_HOME/Headers and in $JAVA_HOME/include; it also examines corresponding locations for $JDK_HOME. If jni.h still cannot be found, specify the location with the CPPFLAGS variable: so, for example,

export CPPFLAGS="-I/opt/jdk1.5/include/:/opt/jdk1.5/include/linux"

or

export CPPFLAGS="-I/c/java/jdk1.6.0/include/ -I/c/java/jdk1.6.0/include/win32/"

Please note that the use of /opt is non-standard, and most system tools will fail to find packages installed there.

Install location

The /usr/local install target can be over-ridden using the standard GNU configure --prefix option; so, for example:

./configure --prefix=/opt/link-grammar

By using pkg-config (see below), non-standard install locations can be automatically detected.

Custom builds

Additional config options are printed by

./configure --help

The system has been tested and works well on 32 and 64-bit Linux systems, FreeBSD, macOS, as well as on Microsoft Windows systems. Specific OS-dependent notes follow.

BUILDING from the GitHub repository

End users should download the tarball (see UNPACKING and signature verification).

The current GitHub version is intended for developers (including anyone who is willing to provide a fix, a new feature or an improvement). The tip of the master branch is often unstable, and can sometimes have bad code in it as it is under development. It also needs installing of development tools that are not installed by default. Due to these reason the use of the GitHub version is discouraged for regular end users.

Installing from GitHub

Clone it: git clone https://github.com/opencog/link-grammar.git
Or download it as a ZIP:
https://github.com/opencog/link-grammar/archive/master.zip

Prerequisite tools

Tools that may need installation before you can build link-grammar:

make (the gmake variant may be needed)
m4
gcc or clang
autoconf
libtool
autoconf-archive
pkg-config (may be named pkgconf or pkgconfig)
pip3 (for the Python bindings)

Optional:
swig (for language bindings)
flex
Apache Ant (for Java bindings)
graphviz (if you wish to use the word-graph display feature)

The GitHub version doesn't include a configure script. To generate it, use:

autogen.sh

If you get errors, make sure you have installed the above-listed development packages, and that your system installation is up to date. Especially, missing autoconf or autoconf-archive may cause strange and misleading errors.

For more info about how to proceed, continue at the section CREATING the system and the relevant sections after it.

Additional notes for developers

To configure debug mode, use:

configure --enable-debug

It adds some verification debug code and functions that can pretty-print several data structures.

A feature that may be useful for debugging is the word-graph display. It is enabled by default. For more details on this feature, see Word-graph display.

BUILDING on FreeBSD

The current configuration has an apparent standard C++ library mixing problem when gcc is used (a fix is welcome). However, the common practice on FreeBSD is to compile with clang, and it doesn't have this problem. In addition, the add-on packages are installed under /usr/local.

So here is how configure should be invoked:

env LDFLAGS=-L/usr/local/lib CPPFLAGS=-I/usr/local/include \
CC=clang CXX=clang++ configure

Note that pcre2 is a required package as the existing libc regex implementation doesn't have the needed level of regex support.

Some packages have different names than the ones mentioned in the previous sections:

minisat (minisat2) pkgconf (pkg-config)

BUILDING on macOS

Plain-vanilla Link Grammar should compile and run on Apple macOS just fine, as described above. At this time, there are no reported issues.

If you do NOT need the java bindings, you should almost surely configure with:

./configure --disable-java-bindings

By default, java requires a 64-bit binary, and not all macOS systems have a 64-bit devel environment installed.

If you do want Java bindings, be sure to set the JDK_HOME environment variable to wherever <Headers/jni.h> is. Set the JAVA_HOME variable to the location of the java compiler. Make sure you have ant installed.

If you would like to build from GitHub (see BUILDING from the GitHub repository) you can install the tools that are listed there using HomeBrew.

BUILDING on Windows

There are three different ways in which link-grammar can be compiled on Windows. One way is to use Cygwin, which provides a Linux compatibility layer for Windows. Another way is use the MSVC system. A third way is to use the MinGW system, which uses the Gnu toolset to compile windows programs. The source code supports Windows systems from Vista on.

The Cygwin way currently produces the best result, as it supports line editing with command completion and history and also supports word-graph displaying on X-windows. (MinGW currently doesn't have libedit, and the MSVC port currently doesn't support command completion and history, and also spelling.

BUILDING on Windows (Cygwin)

The easiest way to have link-grammar working on MS Windows is to use Cygwin, a Linux-like environment for Windows making it possible to port software running on POSIX systems to Windows. Download and install Cygwin.

Note that the installation of the pcre2 package is required because the libc REGEX implementation is not capable enough.

For more details See mingw/README-Cygwin.md.

BUILDING on Windows (MinGW)

Another way to build link-grammar is to use MinGW, which uses the GNU toolset to compile POSIX-compliant programs for Windows. Using MinGW/MSYS2 is probably the easiest way to obtain workable Java bindings for Windows. Download and install MinGW/MSYS2 from msys2.org.

Note that the installation of the pcre2 package is required because the libc REGEX implementation is not capable enough.

For more details see mingw/README-MinGW64.md.

BUILDING and RUNNING on Windows (MSVC)

Microsoft Visual C/C++ project files can be found in the msvc directory. For directions see the README.md file there.

RUNNING the program

To run the program issue the command (supposing it is in your PATH):

link-parser [arguments]

This starts the program. The program has many user-settable variables and options. These can be displayed by entering !var at the link-parser prompt. Entering !help will display some additional commands.

The dictionaries are arranged in directories whose name is the 2-letter language code. The link-parser program searches for such a language directory in that order, directly or under a directory names data:

  1. Under your current directory.
  2. Unless compiled with MSVC or run under the Windows console: At the installed location (typically in /usr/local/share/link-grammar).
  3. If compiled on Windows: In the directory of the link-parser executable (may be in a different location than the link-parser command, which may be a script).

If link-parser cannot find the desired dictionary, use verbosity level 4 to debug the problem; for example:

link-parser ru -verbosity=4

Other locations can be specified on the command line; for example:

link-parser ../path/to-my/modified/data/en

When accessing dictionaries in non-standard locations, the standard file-names are still assumed (i.e. 4.0.dict, 4.0.affix, etc.).

The Russian dictionaries are in data/ru. Thus, the Russian parser can be started as:

link-parser ru

If you don't supply an argument to link-parser, it searches for a language according to your current locale setup. If it cannot find such a language directory, it defaults to "en".

If you see errors similar to this:

Warning: The word "encyclop" found near line 252 of en/4.0.dict
matches the following words:
encyclop
This word will be ignored.

then your UTF-8 locales are either not installed or not configured. The shell command locale -a should list en_US.utf8 as a locale. If not, then you need to dpkg-reconfigure locales and/or run update-locale or possibly apt-get install locales, or combinations or variants of these, depending on your operating system.

TESTING the system

There are several ways to test the resulting build. If the Python bindings are built, then a test program can be found in the file ./bindings/python-examples/tests.py -- When run, it should pass. For more details see README.md in the bindings/python-examples directory.

There are also multiple batches of test/example sentences in the language data directories, generally having the names corpus-*.batch The parser program can be run in batch mode, for testing the system on a large number of sentences. The following command runs the parser on a file called corpus-basic.batch;

link-parser < corpus-basic.batch

The line !batch near the top of corpus-basic.batch turns on batch mode. In this mode, sentences labeled with an initial * should be rejected and those not starting with a * should be accepted. This batch file does report some errors, as do the files corpus-biolg.batch and corpus-fixes.batch. Work is ongoing to fix these.

The corpus-fixes.batch file contains many thousands of sentences that have been fixed since the original 4.1 release of link-grammar. The corpus-biolg.batch contains biology/medical-text sentences from the BioLG project. The corpus-voa.batch contains samples from Voice of America; the corpus-failures.batch contains a large number of failures.

The following numbers are subject to change, but, at this time, the number of errors one can expect to observe in each of these files are roughly as follows:

en/corpus-basic.batch:      88 errors
en/corpus-fixes.batch:     371 errors
lt/corpus-basic.batch:      15 errors
ru/corpus-basic.batch:      47 errors

The bindings/python directory contains a unit test for the Python bindings. It also performs several basic checks that stress the link-grammar libraries.

USING the system

There is an API (application program interface) to the parser. This makes it easy to incorporate it into your own applications. The API is documented on the web site.

USING CMake

The FindLinkGrammar.cmake file can be used to test for and set up compilation in CMake-based build environments.

USING pkg-config

To make compiling and linking easier, the current release uses the pkg-config system. To determine the location of the link-grammar header files, say pkg-config --cflags link-grammar To obtain the location of the libraries, say pkg-config --libs link-grammar Thus, for example, a typical makefile might include the targets:

.c.o:
   cc -O2 -g -Wall -c $< `pkg-config --cflags link-grammar`

$(EXE): $(OBJS)
   cc -g -o $@ $^ `pkg-config --libs link-grammar`

Using JAVA

This release provides java files that offer three ways of accessing the parser. The simplest way is to use the org.linkgrammar.LinkGrammar class; this provides a very simple Java API to the parser.

The second possibility is to use the LGService class. This implements a TCP/IP network server, providing parse results as JSON messages. Any JSON-capable client can connect to this server and obtain parsed text.

The third possibility is to use the org.linkgrammar.LGRemoteClient class, and in particular, the parse() method. This class is a network client that connects to the JSON server, and converts the response back to results accessible via the ParseResult API.

The above-described code will be built if Apache ant is installed.

Using the JSON Network Server

The network server can be started by saying:

java -classpath linkgrammar.jar org.linkgrammar.LGService 9000

The above starts the server on port 9000. It the port is omitted, help text is printed. This server can be contacted directly via TCP/IP; for example:

telnet localhost 9000

(Alternately, use netcat instead of telnet). After connecting, type in:

text:  this is an example sentence to parse

The returned bytes will be a JSON message providing the parses of the sentence. By default, the ASCII-art parse of the text is not transmitted. This can be obtained by sending messages of the form:

storeDiagramString:true, text: this is a test.

Spell Guessing

The parser will run a spell-checker at an early stage, if it encounters a word that it does not know, and cannot guess, based on morphology. The configure script looks for the aspell or hunspell spell-checkers; if the aspell devel environment is found, then aspell is used, else hunspell is used.

Spell guessing may be disabled at runtime, in the link-parser client with the !spell=0 flag. Enter !help for more details.

Caution: aspell version 0.60.8 and possibly others have a memory leak. The use of spell-guessing in production servers is strongly discouraged. Keeping spell-guessing disabled (=0) in Parse_Options is safe.

Multi-threading

It is safe to use link-grammar in multiple threads. Threads may share the same dictionary. Parse options can be set on a per-thread basis, with the exception of verbosity, which is a global, shared by all threads. It is the only global.

Linguistic Commentary

Phonetics

A/An phonetic determiners before consonants/vowels are handled by a new PH link type, linking the determiner to the word immediately following it. Status: Introduced in version 5.1.0 (August 2014). Mostly done, although many special-case nouns are unfinished.

Directional Links

Directional links are needed for some languages, such as Lithuanian, Turkish and other free word-order languages. The goal is to have a link clearly indicate which word is the head word, and which is the dependent. This is achieved by prefixing connectors with a single lower case letter: h,d, indicating 'head' and 'dependent'. The linkage rules are such that h matches either nothing or d, and d matches h or nothing. This is a new feature in version 5.1.0 (August 2014). The website provides additional documentation.

Although the English-language link-grammar links are un-oriented, it seems that a defacto direction can be given to them that is completely consistent with standard conceptions of a dependency grammar.

The dependency arrows have the following properties:

  • Anti-reflexive (a word cannot depend on itself; it cannot point at itself.)

  • Anti-symmetric (if Word1 depends on Word2, then Word2 cannot depend on Word1) (so, e.g. determiners depend on nouns, but never vice-versa)

  • The arrows are neither transitive, nor anti-transitive: a single word may be ruled by several heads. For example:

    +------>WV------->+
    +-->Wd-->+<--Ss<--+
    |        |        |
LEFT-WALL   she    thinks.v

That is, there is a path to the subject, "she", directly from the left wall, via the Wd link, as well as indirectly, from the wall to the root verb, and thence to the subject. Similar loops form with the B and R links. Such loops are useful for constraining the possible number of parses: the constraint occurs in conjunction with the "no links cross" meta-rule.

  • The graphs are planar; that is, no two edges may cross. See, however, the "link-crossing" discussion below.

There are several related mathematical notions, but none quite capture directional LG:

  • Directional LG graphs resemble DAGS, except that LG allows only one wall (one "top" element).

  • Directional LG graphs resemble strict partial orders, except that the LG arrows are usually not transitive.

  • Directional LG graphs resemble catena except that catena are strictly anti-transitive -- the path to any word is unique, in a catena.

Link Crossing

The foundational LG papers mandate the planarity of the parse graphs. This is based on a very old observation that dependencies almost never cross in natural languages: humans simply do not speak in sentences where links cross. Imposing planarity constraints then provides a strong engineering and algorithmic constraint on the resulting parses: the total number of parses to be considered is sharply reduced, and thus the overall speed of parsing can be greatly increased.

However, there are occasional, relatively rare exceptions to this planarity rule; such exceptions are observed in almost all languages. A number of these exceptions are given for English, below.

Thus, it seems important to relax the planarity constraint, and find something else that is almost as strict, but still allows infrequent exceptions. It would appear that the concept of "landmark transitivity" as defined by Richard Hudson in his theory of "Word Grammar", and then advocated by Ben Goertzel, just might be such a mechanism.

ftp://ftp.phon.ucl.ac.uk/pub/Word-Grammar/ell2-wg.pdf
http://www.phon.ucl.ac.uk/home/dick/enc/syntax.htm
http://goertzel.org/ProwlGrammar.pdf

Planarity: Theory vs. Practice

In practice, the planarity constraint allows very efficient algorithms to be used in the implementation of the parser. Thus, from the point of view of the implementation, we want to keep planarity. Fortunately, there is a convenient and unambiguous way to have our cake and eat it, too. A non-planar diagram can be drawn on a sheet of paper using standard electrical-engineering notation: a funny symbol, wherever wires cross. This notation is very easily adapted to LG connectors; below is an actual working example, already implemented in the current LG English dictionary. All link crossings can be implemented in this way! So we do not have to actually abandon the current parsing algorithms to get non-planar diagrams. We don't even have to modify them! Hurrahh!

Here is a working example: "I want to look at and listen to everything." This wants two J links pointing to 'everything'. The desired diagram would need to look like this:

    +---->WV---->+
    |            +--------IV---------->+
    |            |           +<-VJlpi--+
    |            |           |    +---xxx------------Js------->+
    +--Wd--+-Sp*i+--TO-+-I*t-+-MVp+    +--VJrpi>+--MVp-+---Js->+
    |      |     |     |     |    |    |        |      |       |
LEFT-WALL I.p want.v to.r look.v at and.j-v listen.v to.r everything

The above really wants to have a Js link from 'at' to 'everything', but this Js link crosses (clashes with - marked by xxx) the link to the conjunction. Other examples suggest that one should allow most links to cross over the down-links to conjunctions.

The planarity-maintaining worked-around is to split the Js link into two: a Jj part and a Jk part; the two are used together to cross over the conjunction. This is currently implemented in the English dictionary, and it works.

This work-around is in fact completely generic, and can be extended to any kind of link crossing. For this to work, a better notation would be convenient; perhaps uJs- instead of Jj- and vJs- instead of Jk-, or something like that ... (TODO: invent better notation.) (NB: This is a kind of re-invention of "fat links", but in the dictionary, not in the code.)

Landmark Transitivity: Theory

Given that non-planar parses can be enabled without any changes to the parser algorithm, all that is required is to understand what sort of theory describes link-crossing in a coherent grounding. That theory is Dick Hudson's Landmark Transitivity, explained here.

This mechanism works as follows:

  • First, every link must be directional, with a head and a dependent. That is, we are concerned with directional-LG links, which are of the form x--A-->y or y<--A--x for words x,y and LG link type A.

  • Given either the directional-LG relation x--A-->y or y<--A--x, define the dependency relation x-->y. That is, ignore the link-type label.

  • Heads are landmarks for dependents. If the dependency relation x-->y holds, then x is said to be a landmark for y, and the predicate land(x,y) is true, while the predicate land(y,x) is false. Here, x and y are words, while --> is the landmark relation.

  • Although the basic directional-LG links form landmark relations, the total set of landmark relations is extended by transitive closure. That is, if land(x,y) and land(y,z) then land(x,z). That is, the basic directional-LG links are "generators" of landmarks; they generate by means of transitivity. Note that the transitive closure is unique.

  • In addition to the above landmark relation, there are two additional relations: the before and after landmark relations. (In English, these correspond to left and right; in Hebrew, the opposite). That is, since words come in chronological order in a sentence, the dependency relation can point either left or right. The previously-defined landmark relation only described the dependency order; we now introduce the word-sequence order. Thus, there are are land-before() and land-after() relations that capture both the dependency relation, and the word-order relation.

  • Notation: the before-landmark relation land-B(x,y) corresponds to x-->y (in English, reversed in right-left languages such as Hebrew), whereas the after-landmark relation land-A(x,y) corresponds to y<--x. That is, land(x,y) == land-B(x,y) or land-A(x,y) holds as a statement about the predicate form of the relations.

  • As before, the full set of directional landmarks are obtained by transitive closure applied to the directional-LG links. Two different rules are used to perform this closure:

-- land-B(x,y) and land(y,z) ==> land-B(x,y)
-- land-A(x,y) and land(y,z) ==> land-A(x,y)

Parsing is then performed by joining LG connectors in the usual manner, to form a directional link. The transitive closure of the directional landmarks are then computed. Finally, any parse that does not conclude with the "left wall" being the upper-most landmark is discarded.

Here is an example where landmark transitivity provides a natural solution to a (currently) broken parse. The "to.r" has a disjunct "I+ & MVi-" which allows "What is there to do?" to parse correctly. However, it also allows the incorrect parse "He is going to do". The fix would be to force "do" to take an object; however, a link from "do" to "what" is not allowed, because link-crossing would prevent it.

Fixing this requires only a fix to the dictionary, and not to the parser itself.

Link-crossing Examples

Examples where the no-links-cross constraint seems to be violated, in English:

  "He is either in the 105th or the 106th battalion."
  "He is in either the 105th or the 106th battalion."

Both seem to be acceptable in English, but the ambiguity of the "in-either" temporal ordering requires two different parse trees, if the no-links-cross rule is to be enforced. This seems un-natural. Similarly:

  "He is either here or he is there."
  "He either is here or he is there."

A different example involves a crossing to the left wall. That is, the links LEFT-WALL--remains crosses over here--found:

  "Here the remains can be found."

Other examples, per And Rosta:

The allowed--by link crosses cake--that:

He had been allowed to eat a cake by Sophy that she had made him specially

a--book, very--indeed

"a very much easier book indeed"

an--book, easy--to

"an easy book to read"

a--book, more--than

"a more difficult book than that one"

that--have crosses remains--of

"It was announced that remains have been found of the ark of the covenant"

There is a natural crossing, driven by conjunctions:

"I was in hell yesterday and heaven on Tuesday."

the "natural" linkage is to use MV links to connect "yesterday" and "on Tuesday" to the verb. However, if this is done, then these must cross the links from the conjunction "and" to "heaven" and "hell". This can be worked around partly as follows:

              +-------->Ju--------->+
              |    +<------SJlp<----+
+<-SX<-+->Pp->+    +-->Mpn->+       +->SJru->+->Mp->+->Js->+
|      |      |    |        |       |        |      |      |
I     was    in  hell   yesterday  and    heaven    on  Tuesday

but the desired MV links from the verb to the time-prepositions "yesterday" and "on Tuesday" are missing -- whereas they are present, when the individual sentences "I was in hell yesterday" and "I was in heaven on Tuesday" are parsed. Using a conjunction should not wreck the relations that get used; but this requires link-crossing.

"Sophy wondered up to whose favorite number she should count"

Here, "up_to" must modify "number", and not "whose". There's no way to do this without link-crossing.

Type Theory

Link Grammar can be understood in the context of type theory. A simple introduction to type theory can be found in chapter 1 of the HoTT book. This book is freely available online and strongly recommended if you are interested in types.

Link types can be mapped to types that appear in categorial grammars. The nice thing about link-grammar is that the link types form a type system that is much easier to use and comprehend than that of categorial grammar, and yet can be directly converted to that system! That is, link-grammar is completely compatible with categorial grammar, and is easier-to-use. See the paper "Combinatory Categorial Grammar and Link Grammar are Equivalent" for details.

The foundational LG papers make comments to this effect; however, see also work by Bob Coecke on category theory and grammar. Coecke's diagramatic approach is essentially identical to the diagrams given in the foundational LG papers; it becomes abundantly clear that the category theoretic approach is equivalent to Link Grammar. See, for example, this introductory sketch http://www.cs.ox.ac.uk/people/bob.coecke/NewScientist.pdf and observe how the diagrams are essentially identical to the LG jigsaw-puzzle piece diagrams of the foundational LG publications.

ADDRESSES

If you have any questions, please feel free to send a note to the mailing list.

The source code of link-parser and the link-grammar library is located at GitHub.
For bug reports, please open an issue there.

Although all messages should go to the mailing list, the current maintainers can be contacted at:

  Linas Vepstas - <[email protected]>
  Amir Plivatsky - <[email protected]>
  Dom Lachowicz - <[email protected]>

A complete list of authors and copyright holders can be found in the AUTHORS file. The original authors of the Link Grammar parser are:

  Daniel Sleator                    [email protected]
  Computer Science Department       412-268-7563
  Carnegie Mellon University        www.cs.cmu.edu/~sleator
  Pittsburgh, PA 15213

  Davy Temperley                    [email protected]
  Eastman School of Music           716-274-1557
  26 Gibbs St.                      www.link.cs.cmu.edu/temperley
  Rochester, NY 14604

  John Lafferty                     [email protected]
  Computer Science Department       412-268-6791
  Carnegie Mellon University        www.cs.cmu.edu/~lafferty
  Pittsburgh, PA 15213

TODO -- Working Notes

Some working notes.

Easy to fix: provide a more uniform API to the constituent tree. i.e provide word index. Also, provide a better word API, showing word extent, subscript, etc.

Capitalized first words:

There are subtle technical issues for handling capitalized first words. This needs to be fixed. In addition, for now these words are shown uncapitalized in the result linkages. This can be fixed.

Maybe capitalization could be handled in the same way that a/an could be handled! After all, it's essentially a nearest-neighbor phenomenon!

See also issue 690

Capitalization-mark tokens:

The proximal issue is to add a cost, so that Bill gets a lower cost than bill.n when parsing "Bill went on a walk". The best solution would be to add a 'capitalization-mark token' during tokenization; this token precedes capitalized words. The dictionary then explicitly links to this token, with rules similar to the a/an phonetic distinction. The point here is that this moves capitalization out of ad-hoc C code and into the dictionary, where it can be handled like any other language feature. The tokenizer includes experimental code for that.

Corpus-statistics-based parse ranking:

The old for parse ranking via corpus statistics needs to be revived. The issue can be illustrated with these example sentences:

"Please the customer, bring in the money"
"Please, turn off the lights"

In the first sentence, the comma acts as a conjunction of two directives (imperatives). In the second sentence, it is much too easy to mistake "please" for a verb, the comma for a conjunction, and come to the conclusion that one should please some unstated object, and then turn off the lights. (Perhaps one is pleasing by turning off the lights?)

Bad grammar:

When a sentence fails to parse, look for:

  • confused words: its/it's, there/their/they're, to/too, your/you're ... These could be added at high cost to the dicts.
  • missing apostrophes in possessives: "the peoples desires"
  • determiner agreement errors: "a books"
  • aux verb agreement errors: "to be hooks up"

Poor agreement might be handled by giving a cost to mismatched lower-case connector letters.

Elision/ellipsis/zero/phantom words:

An common phenomenon in English is that some words that one might expect to "properly" be present can disappear under various conditions. Below is a sampling of these. Some possible solutions are given below.

Expressions such as "Looks good" have an implicit "it" (also called a zero-it or phantom-it) in them; that is, the sentence should really parse as "(it) looks good". The dictionary could be simplified by admitting such phantom words explicitly, rather than modifying the grammar rules to allow such constructions. Other examples, with the phantom word in parenthesis, include:

  • I ate all (of) the cookies.
  • I've known him only (for) a week.
  • I taught him (how) to swim.
  • I told him (that) it was gone.
  • It stopped me (from) flying off the cliff.
  • (It) looks good.
  • (You) go home!
  • (You) do tell (me).
  • (That is) enough!
  • (I) heard that he's giving a test.
  • (Are) you all right?
  • He opened the door and (he) went in.
  • Emma was the younger (daughter) of two daughters.

This can extend to elided/unvoiced syllables:

  • (I'm a)'fraid so.

Elided punctuation:

  • God (,) give me strength.

Normally, the subjects of imperatives must always be offset by a comma: "John, give me the hammer", but here, in muttering an oath, the comma is swallowed (unvoiced).

Some complex phantom constructions:

  • They play billiards but (they do) not (play) snooker.
  • I know Ringo, but (I do) not (know) his brother.
  • She likes Indian food, but (she does) not (like) Chinese (food).
  • If this is true, then (you should) do it.
  • Perhaps he will (do it), if he sees enough of her.

See also github issue #224.

Actual ellipsis:

  • At first, it seemed like ...
  • It became clear that ...

Here, the ellipsis stands for a subordinate clause, which attaches with not one, but two links: C+ & CV+, and thus requires two words, not one. There is no way to have the ellipsis word to sink two connectors starting from the same word, and so some more complex mechanism is needed. The solution is to infer a second phantom ellipsis:

  • It became clear that ... (...)

where the first ellipsis is a stand in for the subject of a subordinate clause, and the second stands in for an unknown verb.

Elision of syllables

Many (unstressed) syllables can be elided; in modern English, this occurs most commonly in the initial unstressed syllable:

  • (a)'ccount (a)'fraid (a)'gainst (a)'greed (a)'midst (a)'mongst
  • (a)'noint (a)'nother (a)'rrest (at)'tend
  • (be)'fore (be)'gin (be)'havior (be)'long (be)'twixt
  • (con)'cern (e)'scape (e)'stablish And so on.

Punctuation, zero-copula, zero-that:

Poorly punctuated sentences cause problems: for example:

"Mike was not first, nor was he last."
"Mike was not first nor was he last."

The one without the comma currently fails to parse. How can we deal with this in a simple, fast, elegant way? Similar questions for zero-copula and zero-that sentences.

Context-dependent zero phrases.

Consider an argument between a professor and a dean, and the dean wants the professor to write a brilliant review. At the end of the argument, the dean exclaims: "I want the review brilliant!" This is a predicative adjective; clearly it means "I want the review [that you write to be] brilliant." However, taken out of context, such a construction is ungrammatical, as the predictiveness is not at all apparent, and it reads just as incorrectly as would "*Hey Joe, can you hand me that review brilliant?"

Imperatives as phantoms:

"Push button"
"Push button firmly"

The subject is a phantom; the subject is "you".

Handling zero/phantom words by explicitly inserting them:

One possible solution is to perform a one-point compactification. The dictionary contains the phantom words, and their connectors. Ordinary disjuncts can link to these, but should do so using a special initial lower-case letter (say, 'z', in addition to 'h' and 'd' as is currently implemented). The parser, as it works, examines the initial letter of each connector: if it is 'z', then the usual pruning rules no longer apply, and one or more phantom words are selected out of the bucket of phantom words. (This bucket is kept out-of-line, it is not yet placed into sentence word sequence order, which is why the usual pruning rules get modified.) Otherwise, parsing continues as normal. At the end of parsing, if there are any phantom words that are linked, then all of the connectors on the disjunct must be satisfied (of course!) else the linkage is invalid. After parsing, the phantom words can be inserted into the sentence, with the location deduced from link lengths.

Handling zero/phantom words as re-write rules.

A more principled approach to fixing the phantom-word issue is to borrow the idea of re-writing from the theory of operator grammar. That is, certain phrases and constructions can be (should be) re-written into their "proper form", prior to parsing. The re-writing step would insert the missing words, then the parsing proceeds. One appeal of such an approach is that re-writing can also handle other "annoying" phenomena, such as typos (missing apostrophes, e.g. "lets" vs. "let's", "its" vs. "it's") as well as multi-word rewrites (e.g. "let's" vs. "let us", or "it's" vs. "it is").

Exactly how to implement this is unclear. However, it seems to open the door to more abstract, semantic analysis. Thus, for example, in Meaning-Text Theory (MTT), one must move between SSynt to DSynt structures. Such changes require a graph re-write from the surface syntax parse (e.g. provided by link-grammar) to the deep-syntactic structure. By contrast, handling phantom words by graph re-writing prior to parsing inverts the order of processing. This suggests that a more holistic approach is needed to graph rewriting: it must somehow be performed "during" parsing, so that parsing can both guide the insertion of the phantom words, and, simultaneously guide the deep syntactic rewrites.

Another interesting possibility arises with regards to tokenization. The current tokenizer is clever, in that it splits not only on whitespace, but can also strip off prefixes, suffixes, and perform certain limited kinds of morphological splitting. That is, it currently has the ability to re-write single-words into sequences of words. It currently does so in a conservative manner; the letters that compose a word are preserved, with a few exceptions, such as making spelling correction suggestions. The above considerations suggest that the boundary between tokenization and parsing needs to become both more fluid, and more tightly coupled.

Poor linkage choices:

Compare "she will be happier than before" to "she will be more happy than before." Current parser makes "happy" the head word, and "more" a modifier w/EA link. I believe the correct solution would be to make "more" the head (link it as a comparative), and make "happy" the dependent. This would harmonize rules for comparatives... and would eliminate/simplify rules for less,more.

However, this idea needs to be double-checked against, e.g. Hudson's word grammar. I'm confused on this issue ...

Stretchy links:

Currently, some links can act at "unlimited" length, while others can only be finite-length. e.g. determiners should be near the noun that they apply to. A better solution might be to employ a 'stretchiness' cost to some connectors: the longer they are, the higher the cost. (This eliminates the "unlimited_connector_set" in the dictionary).

Opposing (repulsing) parses:

Sometimes, the existence of one parse should suggest that another parse must surely be wrong: if one parse is possible, then the other parses must surely be unlikely. For example: the conjunction and.j-g allows the "The Great Southern and Western Railroad" to be parsed as the single name of an entity. However, it also provides a pattern match for "John and Mike" as a single entity, which is almost certainly wrong. But "John and Mike" has an alternative parse, as a conventional-and -- a list of two people, and so the existence of this alternative (and correct) parse suggests that perhaps the entity-and is really very much the wrong parse. That is, the mere possibility of certain parses should strongly disfavor other possible parses. (Exception: Ben & Jerry's ice cream; however, in this case, we could recognize Ben & Jerry as the name of a proper brand; but this is outside of the "normal" dictionary (?) (but maybe should be in the dictionary!))

More examples: "high water" can have the connector A joining high.a and AN joining high.n; these two should either be collapsed into one, or one should be eliminated.

WordNet hinting:

Use WordNet to reduce the number for parses for sentences containing compound verb phrases, such as "give up", "give off", etc.

Sliding-window (Incremental) parsing:

To avoid a combinatorial explosion of parses, it would be nice to have an incremental parsing, phrase by phrase, using a sliding window algorithm to obtain the parse. Thus, for example, the parse of the last half of a long, run-on sentence should not be sensitive to the parse of the beginning of the sentence.

Doing so would help with combinatorial explosion. So, for example, if the first half of a sentence has 4 plausible parses, and the last half has 4 more, then currently, the parser reports 16 parses total. It would be much more useful if it could instead report the factored results: i.e. the four plausible parses for the first half, and the four plausible parses for the last half. This would ease the burden on downstream users of link-grammar.

This approach has at psychological support. Humans take long sentences and split them into smaller chunks that "hang together" as phrase- structures, viz compounded sentences. The most likely parse is the one where each of the quasi sub-sentences is parsed correctly.

This could be implemented by saving dangling right-going connectors into a parse context, and then, when another sentence fragment arrives, use that context in place of the left-wall.

This somewhat resembles the application of construction grammar ideas to the link-grammar dictionary. It also somewhat resembles Viterbi parsing to some fixed depth. Viz. do a full backward-forward parse for a phrase, and then, once this is done, take a Viterbi-step. That is, once the phrase is done, keep only the dangling connectors to the phrase, place a wall, and then step to the next part of the sentence.

Caution: watch out for garden-path sentences:

  The horse raced past the barn fell.
  The old man the boat.
  The cotton clothing is made of grows in Mississippi.

The current parser parses these perfectly; a viterbi parser could trip on these.

Other benefits of a Viterbi decoder:

  • Less sensitive to sentence boundaries: this would allow longer, run-on sentences to be parsed far more quickly.
  • Could do better with slang, hip-speak.
  • Support for real-time dialog (parsing of half-uttered sentences).
  • Parsing of multiple streams, e.g. from play/movie scripts.
  • Would enable (or simplify) co-reference resolution across sentences (resolve referents of pronouns, etc.)
  • Would allow richer state to be passed up to higher layers: specifically, alternate parses for fractions of a sentence, alternate reference resolutions.
  • Would allow plug-in architecture, so that plugins, employing some alternate, higher-level logic, could disambiguate (e.g. by making use of semantic content).
  • Eliminate many of the hard-coded array sizes in the code.

One may argue that Viterbi is a more natural, biological way of working with sequences. Some experimental, psychological support for this can be found at http://www.sciencedaily.com/releases/2012/09/120925143555.htm per Morten Christiansen, Cornell professor of psychology.

Registers, sociolects, dialects (cost vectors):

Consider the sentence "Thieves rob bank" -- a typical newspaper headline. LG currently fails to parse this, because the determiner is missing ("bank" is a count noun, not a mass noun, and thus requires a determiner. By contrast, "thieves rob water" parses just fine.) A fix for this would be to replace mandatory determiner links by (D- or {[[()]] & headline-flag}) which allows the D link to be omitted if the headline-flag bit is set. Here, "headline-flag" could be a new link-type, but one that is not subject to planarity constraints.

Note that this is easier said than done: if one simply adds a high-cost null link, and no headline-flag, then all sorts of ungrammatical sentences parse, with strange parses; while some grammatical sentences, which should parse, but currently don't, become parsable, but with crazy results.

More examples, from And Rosta:

   "when boy meets girl"
   "when bat strikes ball"
   "both mother and baby are well"

A natural approach would be to replace fixed costs by formulas. This would allow the dialect/sociolect to be dynamically changeable. That is, rather than having a binary headline-flag, there would be a formula for the cost, which could be changed outside of the parsing loop. Such formulas could be used to enable/disable parsing specific to different dialects/sociolects, simply by altering the network of link costs.

A simpler alternative would be to have labeled costs (a cost vector), so that different dialects assign different costs to various links. A dialect would be specified during the parse, thus causing the costs for that dialect to be employed during parse ranking.

This has been implemented; what's missing is a practical tutorial on how this might be used.

Hand-refining verb patterns:

A good reference for refining verb usage patterns is: "COBUILD GRAMMAR PATTERNS 1: VERBS from THE COBUILD SERIES", from THE BANK OF ENGLISH, HARPER COLLINS. Online at https://arts-ccr-002.bham.ac.uk/ccr/patgram/ and http://www.corpus.bham.ac.uk/publications/index.shtml

Quotations:

Currently tokenize.c tokenizes double-quotes and some UTF8 quotes (see the RPUNC/LPUNC class in en/4.0.affix - the QUOTES class is not used for that, but for capitalization support), with some very basic support in the English dictionary (see "% Quotation marks." there). However, it does not do this for the various "curly" UTF8 quotes, such as ‘these’ and “these”. This results is some ugly parsing for sentences containing such quotes. (Note that these are in 4.0.affix).

A mechanism is needed to disentangle the quoting from the quoted text, so that each can be parsed appropriately. It's somewhat unclear how to handle this within link-grammar. This is somewhat related to the problem of morphology (parsing words as if they were "mini-sentences",) idioms (phrases that are treated as if they were single words), set-phrase structures (if ... then ... not only... but also ...) which have a long-range structure similar to quoted text (he said ...).

See also github issue #42.

Semantification of the dictionary:

"to be fishing": Link grammar offers four parses of "I was fishing for evidence", two of which are given low scores, and two are given high scores. Of the two with high scores, one parse is clearly bad. Its links "to be fishing.noun" as opposed to the correct "to be fishing.gerund". That is, I can be happy, healthy and wise, but I certainly cannot be fishing.noun. This is perhaps not just a bug in the structure of the dictionary, but is perhaps deeper: link-grammar has little or no concept of lexical units (i.e. collocations, idioms, institutional phrases), which thus allows parses with bad word-senses to sneak in.

The goal is to introduce more knowledge of lexical units into LG.

Different word senses can have different grammar rules (and thus, the links employed reveal the sense of the word): for example: "I tend to agree" vs. "I tend to the sheep" -- these employ two different meanings for the verb "tend", and the grammatical constructions allowed for one meaning are not the same as those allowed for the other. Yet, the link rules for "tend.v" have to accommodate both senses, thus making the rules rather complex. Worse, it potentially allows for non-sense constructions. If, instead, we allowed the dictionary to contain different rules for "tend.meaning1" and "tend.meaning2", the rules would simplify (at the cost of inflating the size of the dictionary).

Another example: "I fear so" -- the word "so" is only allowed with some, but not all, lexical senses of "fear". So e.g. "I fear so" is in the same semantic class as "I think so" or "I hope so", although other meanings of these verbs are otherwise quite different.

[Sin2004] "New evidence, new priorities, new attitudes" in J. Sinclair, (ed) (2004) How to use corpora in language teaching, Amsterdam: John Benjamins

See also: Pattern Grammar: A Corpus-Driven Approach to the Lexical Grammar of English
Susan Hunston and Gill Francis (University of Birmingham)
Amsterdam: John Benjamins (Studies in corpus linguistics, edited by Elena Tognini-Bonelli, volume 4), 2000
Book review.

“The Molecular Level of Lexical Semantics”, EA Nida, (1997) International Journal of Lexicography, 10(4): 265–274. Online

"holes" in collocations (aka "set phrases" of "phrasemes"):

The link-grammar provides several mechanisms to support circumpositions or even more complicated multi-word structures. One mechanism is by ordinary links; see the V, XJ and RJ links. The other mechanism is by means of post-processing rules. (For example, the "filler-it" SF rules use post-processing.) However, rules for many common forms have not yet been written. The general problem is of supporting structures that have "holes" in the middle, that require "lacing" to tie them together.

For a general theory, see catena.

For example, the adposition:

... from [xxx] on.
    "He never said another word from then on."
    "I promise to be quiet from now on."
    "Keep going straight from that point on."
    "We went straight from here on."

... from there on.
    "We went straight, from the house on to the woods."
    "We drove straight, from the hill onwards."

Note that multiple words can fit in the slot [xxx]. Note the tangling of another prepositional phrase: "... from [xxx] on to [yyy]"

More complicated collocations with holes include

 "First.. next..."
 "If ... then ..."

'Then' is optional ('then' is a 'null word'), for example:

"If it is raining, stay inside!"
"If it is raining, [then] stay inside!"


"if ... only ..." "If there were only more like you!"
"... not only, ... but also ..."


"As ..., so ..."  "As it was commanded, so it shall be done"


"Either ... or ..."
"Both ... and  ..."  "Both June and Tom are coming"
"ought ... if ..." "That ought to be the case, if John is not lying"


"Someone ... who ..."
"Someone is outside who wants to see you"


"... for ... to ..."
"I need for you to come to my party"

The above are not currently supported. An example that is supported is the "non-referential it", e.g.

"It ... that ..."
"It seemed likely that John would go"

The above is supported by means of special disjuncts for 'it' and 'that', which must occur in the same post-processing domain.

See also:
http://www.phon.ucl.ac.uk/home/dick/enc2010/articles/extraposition.htm
http://www.phon.ucl.ac.uk/home/dick/enc2010/articles/relative-clause.htm

"...from X and from Y" "By X, and by Y, ..." Here, X and Y might be rather long phrases, containing other prepositions. In this case, the usual link-grammar linkage rules will typically conjoin "and from Y" to some preposition in X, instead of the correct link to "from X". Although adding a cost to keep the lengths of X and Y approximately equal can help, it would be even better to recognize the "...from ... and from..." pattern.

The correct solution for the "Either ... or ..." appears to be this:

---------------------------+---SJrs--+
       +------???----------+         |
       |     +Ds**c+--SJls-+    +Ds**+
       |     |     |       |    |    |
   either.r the lorry.n or.j-n the van.n

The wrong solution is

--------------------------+
     +-----Dn-----+       +---SJrs---+
     |      +Ds**c+--SJn--+     +Ds**+
     |      |     |       |     |    |
 neither.j the lorry.n nor.j-n the van.n

The problem with this is that "neither" must coordinate with "nor". That is, one cannot say "either.. nor..." "neither ... or ... " "neither ...and..." "but ... nor ..." The way I originally solved the coordination problem was to invent a new link called Dn, and a link SJn and to make sure that Dn could only connect to SJn, and nothing else. Thus, the lower-case "n" was used to propagate the coordination across two links. This demonstrates how powerful the link-grammar theory is: with proper subscripts, constraints can be propagated along links over large distances. However, this also makes the dictionary more complex, and the rules harder to write: coordination requires a lot of different links to be hooked together. And so I think that creating a single, new link, called ???, will make the coordination easy and direct. That is why I like that idea.

The ??? link should be the XJ link, which-see.

More idiomatic than the above examples: "...the chip on X's shoulder" "to do X a favour" "to give X a look"

The above are all examples of "set phrases" or "phrasemes", and are most commonly discussed in the context of MTT or Meaning-Text Theory of Igor Mel'cuk et al (search for "MTT Lexical Function" for more info). Mel'cuk treats set phrases as lexemes, and, for parsing, this is not directly relevant. However, insofar as phrasemes have a high mutual information content, they can dominate the syntactic structure of a sentence.

Preposition linking:

The current parse of "he wanted to look at and listen to everything." is inadequate: the link to "everything" needs to connect to "and", so that "listen to" and "look at" are treated as atomic verb phrases.

Lexical functions:

MTT suggests that perhaps the correct way to understand the contents of the post-processing rules is as an implementation of 'lexical functions' projected onto syntax. That is, the post-processing rules allow only certain syntactical constructions, and these are the kinds of constructions one typically sees in certain kinds of lexical functions.

Alternately, link-grammar suffers from a combinatoric explosion of possible parses of a given sentence. It would seem that lexical functions could be used to rule out many of these parses. On the other hand, the results are likely to be similar to that of statistical parse ranking (which presumably captures such quasi-idiomatic collocations at least weakly).

Ref. I. Mel'cuk: "Collocations and Lexical Functions", in ''Phraseology: theory, analysis, and applications'' Ed. Anthony Paul Cowie (1998) Oxford University Press pp. 23-54.

More generally, all of link-grammar could benefit from a MTT-izing of infrastructure.

Morphology:

Compare the above commentary on lexical functions to Hebrew morphological analysis. To quote Wikipedia:

This distinction between the word as a unit of speech and the root as a unit of meaning is even more important in the case of languages where roots have many different forms when used in actual words, as is the case in Semitic languages. In these, roots are formed by consonants alone, and different words (belonging to different parts of speech) are derived from the same root by inserting vowels. For example, in Hebrew, the root gdl represents the idea of largeness, and from it we have gadol and gdola (masculine and feminine forms of the adjective "big"), gadal "he grew", higdil "he magnified" and magdelet "magnifier", along with many other words such as godel "size" and migdal "tower".

Morphology printing:

Instead of hard-coding LL, declare which links are morpho links in the dict.

Assorted minor cleanup:

  • Should provide a query that returns compile-time consts, e.g. the max number of characters in a word, or max words in a sentence.
  • Should remove compile-time constants, e.g. max words, max length etc.

Version 6.0 TODO list:

Version 6.0 will change Sentence to Sentence*, Linkage to Linkage* in the API. But perhaps this is a bad idea...

link-grammar's People

Contributors

agayardo avatar ampli avatar carenas avatar chenrui333 avatar dhgutteridge avatar dijs avatar domlachowicz avatar equal-l2 avatar eugeneai avatar hedayat avatar jasonpaulos avatar jbicha avatar jon-turney avatar kaamanita avatar kmwallio avatar lamby avatar leungmanhin avatar linas avatar maxvyaznikov avatar mentegy avatar rseabra avatar rvignav avatar soapgentoo avatar stellarspot avatar tvbat avatar uwog avatar wally-mageia avatar wannaphong avatar williampma avatar zenflow avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

link-grammar's Issues

Crash when parsing a sentence -- Illegal instruction (core dumped)

Another weird sentence that causes the link-parser to crash:

"To" It's to let; there's a notice on the door

Got this error:

Assertion (0 < max_words--) failed at ../../link-grammar/tokenize.c:2715: Too many words (it may be an infinite loop)

Illegal instruction (core dumped)

ANY language has weird UTF8 bug!?

I get an error message, using the "any" language, on this sentence:

Phú Tân.

message is (as printed by relex) is:

Info: recv input: "Ph� T�n."
Info: sentence: "Ph� T�n."
link-grammar: Error: Sentence not in dictionary
The following words are not in the dictionary: "Ph�"
        Failing sentence was:
        LEFT-WALL Ph� T�n . 
Warning: No parses found for:
Ph� T�n.

English dict problem at commit 12c7437b

The following dict problem started at commit 12c7437.

Sentence:
Nobody, it seems, wants to be a liberal

Before this commit:
LEFT-WALL nobody , it seems.q , wants.v to.r be.v a liberal.n

After this commit, until now:
LEFT-WALL nobody , it seems.v [,] [wants] to.r be.v a liberal.n

realloc(): invalid next size error

A sentence from Simple English Wikipedia causes the link-parser to crash when parsing it:

In Buddhism there are 84 Mahasiddhas: Acinta, Ajogi, Anangapa, Aryadeva, Babhaha, Bhadrapa, Bhandepa, Bhiksanapa, Bhusuku, Camaripa, Campaka, Carbaripa, Catrapa, Caurangipa, Celukapa, Darikapa, Dengipa, Dhahulipa, Dharmapa, Dhilipa, Dhobipa, Dhokaripa Dombipa, Dukhandi, Ghantapa, Gharbari, Godhuripa, Goraksa, Indrabhuti, Jalandhara, Jayananda, Jogipa, Kalapa, Kamparipa, Kambala, Kanakhala, Kanhapa, Kankana, Kankaripa, Kantalipa, Kapalapa, Khadgapa, Kilakilapa, Kirapalapa, Kokilipa, Kotalipa, Kucipa, Kukkuripa, Kumbharipa, Laksminkara, Lilapa, Lucikapa, Luipa, Mahipa, Manibhadra, Medhini, Mekhala, Mekopa, Minapa, Nagabodhi, Nagarjuna, Nalinapa, Naropa, Nirgunapa, Pacaripa, Pankajapa, Putalipa, Rahula, Saraha, Sakara, Samudra, Santipa, Sarvabhaksa, Savaripa, Syalipa, Tantepa, Tantipa, Thaganapa, Tilopa, Udhilipa, Upanaha, Vinapa, Virupa, Vyalipa.

With this error:
*** Error in `/home/manhin/link-grammar-5.2.5/link-parser/.libs/lt-link-parser': realloc(): invalid next size: 0x0000000006b23e90 ***
Aborted (core dumped)

Preparing 5.3.0 for release

In continuation to what I wrote in #137:
I managed to run the tests directly ("make check" still has a problem).
It found the following new memory leak (on 4d7205f):

Direct leak of 212 byte(s) in 3 object(s) allocated from:
    #0 0x7f75777b4a0a in malloc (/lib64/libasan.so.2+0x98a0a)
    #1 0x7f756c2623bf in exalloc /usr/local/src/link-grammar-devel/master/link-grammar/utilities.c:504
    #2 0x7f756c239dd5 in string_copy /usr/local/src/link-grammar-devel/master/link-grammar/print-util.c:55
    #3 0x7f756c1ded4d in linkage_print_constituent_tree /usr/local/src/link-grammar-devel/master/link-grammar/constituents.c:1297
    #4 0x7f756c6099e7 in _wrap_linkage_print_constituent_tree ../../bindings/python/lg_python_wrap.cc:5229
    #5 0x3078ee28bd in PyEval_EvalFrameEx (/lib64/libpython2.7.so.1.0+0x3078ee28bd)

post_process() error with Russian and island_ok

linkparser> реактор это реактор
No complete linkages found.
Found 6 linkages (6 had no P.P. violations) at null count 1
link-grammar: Error: post_process(): Need an entry for S in LINK_TYPE_TABLE
    Linkage 1, cost vector = (UNUSED=0 DIS= 4.00 LEN=3)

    +-----Wd----+          +-----S----+
    |           |          |          |
LEFT-WALL реактор.ndmsi это.msi реактор.ndmsi 

Press RETURN for the next linkage.

domain and SIZE_MAX

In post_process.c we have:

static size_t find_domain_name(Postprocessor *pp, const char *link)
{
    size_t i, domain;
    StartingLinkAndDomain *sllt = pp->knowledge->starting_link_lookup_table;
    for (i=0;;i++)
    {
        domain = sllt[i].domain;
        if (domain == SIZE_MAX) return SIZE_MAX;  /* hit the end-of-list sentinel */ <---
        if (post_process_match(sllt[i].starting_link, link)) return domain;
    }
}

Note the check marked with <---.
Here is the definition of StartingLinkAndDomain (structures.h):

/* from pp_knowledge.c */
typedef struct StartingLinkAndDomain_s
{
    const char *starting_link;
    int   domain;       /* domain which the link belongs to (-1: terminator)*/
} StartingLinkAndDomain;

Note that sllt[i].domain is of type int, while SIZE_MAX is the naximum value of a size_t type variable (quoted from stdint.h):

/* Limit of `size_t' type.  */
# if __WORDSIZE == 64
#  define SIZE_MAX      (18446744073709551615UL)

On most 64-bit processors sizeof(size_t) > sizeof(int).
Edit: I was wrong, see my next message here.
So this check is always false on X86_64. It is not detected by the compiler because the assignment to a size_t variable hides the problem.

It is checked in many more places (from grep -R SIZE_MAX):

link-grammar/linkage.c :    if (!verify_link_index(linkage, index)) return SIZE_MAX;
link-grammar/linkage.c :    if (!verify_link_index(linkage, index)) return SIZE_MAX;
link-grammar/post-process.c    :        assert(sublinkage->link_array[i].lw != SIZE_MAX);
link-grammar/post-process.c    :        assert(sublinkage->link_array[j].lw != SIZE_MAX);
link-grammar/post-process.c    :        assert (sublinkage->link_array[link].lw != SIZE_MAX);
link-grammar/post-process.c    :        assert (sublinkage->link_array[link].lw != SIZE_MAX);
link-grammar/post-process.c    :        if (i == SIZE_MAX)
link-grammar/post-process.c    :        assert (sublinkage->link_array[link].lw != SIZE_MAX);
link-grammar/post-process.c    :        assert(linkage->link_array[i].lw != SIZE_MAX);
link-grammar/print.c   :        assert (linkage_get_link_lword(linkage, link) != SIZE_MAX);
link-grammar/print.c   :        assert (linkage_get_link_lword(linkage, link) != SIZE_MAX);
link-grammar/print.c   :        assert (ppla[link].lw != SIZE_MAX);
link-grammar/print.c   :            assert (ppla[j].lw != SIZE_MAX);

But in any case, nothing in the current sources tries to set it to SIZE_MAX!
There was once such a setting, in a discarded function merge_constituents, that has gone with the FAT-LINKS code.

Questions:

  1. Is such a setting somehow still needed, so it needs a fix?
  2. If not, can we discard all of these SIZE_MAX checks?

ANY/AMY languages are missing the LEFT-WALL

The first word in a new sentence should always link to the LEFT-WALL, so that sentence starts appear as a word-pair (LEFT-WALL, ) so that language learning can treat this as any other word pair.

Remove HIDE_MORPHO from compute_chosen_words

compute_chosen_words() should be factored to remove the HIDE_MORPHO stuff, and the HIDE_MORPHO should be a distinct step.

The current implementation of HIDE_MORPHO in compute_chosen_words is not quite right: it assumes that only the suffix has connectors attaching to other parts of the sentence, and so fails to merge the disjuncts correctly if this rule is broken.

configure: error: conditional "HAVE_WIDECHAR_EDITLINE" was never defined.

Hi.

link-grammar 5.2.2 fails to configure on OpenBSD (no problem with 5.2.1):

Using /usr/ports/pobj/link-grammar-5.2.2/config.site (generated)
configure: WARNING: unrecognized options: --disable-gtk-doc
configure: loading site script /usr/ports/pobj/link-grammar-5.2.2/config.site
checking for a BSD-compatible install... /usr/ports/pobj/link-grammar-5.2.2/bin/install -c 
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... mkdir -p
checking for gawk... (cached) awk
checking whether make sets $(MAKE)... (cached) yes
checking whether make supports nested variables... yes
checking whether to enable maintainer-specific portions of Makefiles... yes
checking whether make supports nested variables... (cached) yes
checking build system type... x86_64-unknown-openbsd5.6
checking host system type... x86_64-unknown-openbsd5.6
checking for gcc... cc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables... 
checking whether we are cross compiling... no
checking for suffix of object files... (cached) o
checking whether we are using the GNU C compiler... (cached) yes
checking whether cc accepts -g... (cached) yes
checking for cc option to accept ISO C89... none needed
checking whether cc understands -c and -o together... yes
checking for style of include used by make... GNU
checking dependency style of cc... gcc3
checking whether we are using the GNU C++ compiler... (cached) yes
checking whether c++ accepts -g... (cached) yes
checking dependency style of c++... gcc3
checking how to run the C preprocessor... cc -E
checking how to print strings... print -r
checking for a sed that does not truncate output... (cached) /usr/bin/sed
checking for grep that handles long lines and -e... (cached) /usr/bin/grep
checking for egrep... (cached) /usr/bin/egrep
checking for fgrep... (cached) /usr/bin/fgrep
checking for ld used by cc... /usr/bin/ld
checking if the linker (/usr/bin/ld) is GNU ld... yes
checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm -B
checking the name lister (/usr/bin/nm -B) interface... BSD nm
checking whether ln -s works... yes
checking the maximum length of command line arguments... (cached) 131072
checking whether the shell understands some XSI constructs... yes
checking whether the shell understands "+="... no
checking how to convert x86_64-unknown-openbsd5.6 file names to x86_64-unknown-openbsd5.6 format... func_convert_file_noop
checking how to convert x86_64-unknown-openbsd5.6 file names to toolchain format... func_convert_file_noop
checking for /usr/bin/ld option to reload object files... -r
checking for objdump... objdump
checking how to recognize dependent libraries... match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$
checking for dlltool... no
checking how to associate runtime and link libraries... print -r --
checking for ar... (cached) ar
checking for archiver @FILE support... no
checking for strip... (cached) strip
checking for ranlib... (cached) ranlib
checking command to parse /usr/bin/nm -B output from cc object... ok
checking for sysroot... no
checking for mt... mt
checking if mt is a manifest tool... no
checking for ANSI C header files... (cached) yes
checking for sys/types.h... (cached) yes
checking for sys/stat.h... (cached) yes
checking for stdlib.h... (cached) yes
checking for string.h... (cached) yes
checking for memory.h... (cached) yes
checking for strings.h... (cached) yes
checking for inttypes.h... (cached) yes
checking for stdint.h... (cached) yes
checking for unistd.h... (cached) yes
checking for dlfcn.h... (cached) yes
checking for objdir... .libs
checking if cc supports -fno-rtti -fno-exceptions... no
checking for cc option to produce PIC... -fPIC -DPIC
checking if cc PIC flag -fPIC -DPIC works... yes
checking if cc static flag -static works... yes
checking if cc supports -c -o file.o... yes
checking if cc supports -c -o file.o... (cached) yes
checking whether the cc linker (/usr/bin/ld) supports shared libraries... yes
checking whether -lc should be explicitly linked in... yes
checking dynamic linker characteristics... openbsd5.6 ld.so
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... yes
checking whether to build static libraries... yes
checking how to run the C++ preprocessor... c++ -E
checking for ld used by c++... /usr/bin/ld
checking if the linker (/usr/bin/ld) is GNU ld... yes
checking whether the c++ linker (/usr/bin/ld) supports shared libraries... yes
checking for c++ option to produce PIC... -fPIC -DPIC
checking if c++ PIC flag -fPIC -DPIC works... yes
checking if c++ static flag -static works... yes
checking if c++ supports -c -o file.o... yes
checking if c++ supports -c -o file.o... (cached) yes
checking whether the c++ linker (/usr/bin/ld) supports shared libraries... yes
checking dynamic linker characteristics... openbsd5.6 ld.so
checking how to hardcode library paths into programs... immediate
checking whether ln -s works... yes
checking whether make sets $(MAKE)... (cached) yes
checking for ANSI C header files... (cached) yes
checking for /proc/self/maps... no
checking whether everything is installed to the same prefix... no
checking whether binary relocation support should be enabled... no
checking for pkg-config... /usr/bin/pkg-config
checking pkg-config is at least version 0.9.0... yes
checking for an ANSI C-conforming const... (cached) yes
checking for towupper... yes
checking for size_t... (cached) yes
checking for working alloca.h... (cached) no
checking for alloca... (cached) yes
checking for pid_t... (cached) yes
checking vfork.h usability... no
checking vfork.h presence... no
checking for vfork.h... no
checking for fork... (cached) yes
checking for vfork... (cached) yes
checking for working fork... (cached) yes
checking for working vfork... (cached) yes
checking for prctl... no
checking for native Win32... no
checking for 64-bit Apple OSX... no
checking for stdio.h... (cached) yes
checking sqlite3.h usability... yes
checking sqlite3.h presence... yes
checking for sqlite3.h... yes
checking for SQLITE3... yes
checking for ASPELL... no
checking aspell.h usability... yes
checking aspell.h presence... yes
checking for aspell.h... yes
checking for new_aspell_config in -laspell... yes
checking for locale.h... (cached) yes
checking for LC_MESSAGES... yes
checking for LIBEDIT... no
checking for regex.h... (cached) yes
checking for regexec... yes
checking for jni.h... yes, will build java libs
checking for ant... yes
checking for swig... no
checking for swig2.0... no
checking for swig... no
/usr/libdata/perl5/amd64-openbsd/5.20.1
/usr/local/libdata/perl5/site_perl/amd64-openbsd
checking EXTERN.h usability... yes
checking EXTERN.h presence... yes
checking for EXTERN.h... yes
checking for supported warning flags... 
checking whether cc supports -Wstrict-prototypes... yes
checking whether cc supports -Wmissing-prototypes... yes
checking whether cc supports -Wnested-externs... yes
checking whether cc supports -Wdeclaration-after-statement... yes
checking whether cc supports -Wold-style-definition... yes
checking whether cc supports -Wall... yes
checking whether cc supports -Wextra... yes
checking whether cc supports -Wsign-compare... yes
checking whether cc supports -Werror-implicit-function-declaration... yes
checking whether cc supports -Wpointer-arith... yes
checking whether cc supports -Wwrite-strings... yes
checking whether cc supports -Wmissing-declarations... yes
checking whether cc supports -Wpacked... yes
checking whether cc supports -Wswitch-enum... yes
checking whether cc supports -Wmissing-format-attribute... yes
checking whether cc supports -Wstrict-aliasing=2... yes
checking whether cc supports -Winit-self... yes
checking whether cc supports -Wno-missing-field-initializers... yes
checking whether cc supports -Wno-unused-parameter... yes
checking whether cc supports -Wno-attributes... yes
checking whether cc supports -Wno-long-long... yes
checking whether cc supports -Winline... yes
checking which warning flags were supported...  -Wstrict-prototypes -Wmissing-prototypes -Wnested-externs -Wdeclaration-after-statement -Wold-style-definition
checking whether cc supports -fno-strict-aliasing... yes
checking that generated files are newer than configure... done
configure: error: conditional "HAVE_WIDECHAR_EDITLINE" was never defined.
Usually this means the macro was only invoked conditionally.

Crash in batch mode

It happens on a sentence from en/4.0.fixes.batch, but only in batch mode.

Repeat by:
link-parser -batch
They pillory whoever they want to.
^D

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff4da981d in compute_chosen_words (sent=0x601a00007bc0, linkage=0x0, opts=0x60180000be00)
at /usr/local/src/link-grammar-devel/test/link-grammar/linkage.c:93

The linkage argument is fine if not in batch mode.

Linkage processing broken in current git

The sentence вверху плыли редкие облачка. gives incorrect output, it should be

    +-------------------------Xp-------------------------+
    +---------Wd---------+----------SIp----------+       |
    |         +----EI----+           +----Api----+       |
    |         |          |           |           |       |
LEFT-WALL вверху.e плыли.vnndpp редкие.api облачка.ndnpi . 

Also get garbage print for above when !links=1

Memory leak in pp_lexer_get_next_group_of_tokens_of_label()

In the function below, the memory for tokens is not getting freed by the callers.
There is a free(tokens) in the function, but it is a noop since tokens is always NULL there.
The memory leak is small, but can become larger if the en dict is reopened in a loop.

Possible fixes:

  1. Add free(tokens) in the 7 places in which this functioned is invoked.
  2. Add a token field in PPLexTable_s (initialized to NULL), and free it when PPLexTable_s is freed. In addition, use realloc() here. The function can also be changed to return n_tokens.
const char **pp_lexer_get_next_group_of_tokens_of_label(PPLexTable *lt, size_t *n_tokens)
{ 
  /* all tokens until next comma, null-terminated */
  int n;
  pp_label_node *p;
  static const char **tokens = NULL;  
  static int extents=0;

  p=lt->current_node_of_active_label;      
  for (n=0; p!=NULL && strcmp(p->str,","); n++, p=p->next) {}
  if (n>extents) {
     extents = n;
     free (tokens);
     tokens = (const char **) malloc (extents * sizeof(const char*));
  }

... 

  *n_tokens = n;
  return tokens;
}

Link-grammar 5.2.1 fails to load dictionary (Windows)

Hello there.
I`m trying to launch link-grammar 5.2.1 on my Windows machine.
And it fails to load the dictionary file 4.0.dict.
Here are the error details:

Call stack:

link-grammar-x86.dll!read_dictionary(Dictionary_s * dict) Line 1773
link-grammar-x86.dll!dictionary_six_str(const char * lang, const char * input, const char * dict_name, const char * pp_name, const char * cons_name, const char * affix_name, const char * regex_name) Line 504
link-grammar-x86.dll!dictionary_six(const char * lang, const char * dict_name, const char * pp_name, const char * cons_name, const char * affix_name, const char * regex_name) Line 596
link-grammar-x86.dll!dictionary_create_from_file(const char * lang) Line 622 C
link-grammar-x86.dll!dictionary_create_lang(const char * lang) Line 78

To load the dictionary it reads the file line by line and on line 2982 it crashes like this:

capture

Here is the problematic line itself:

2982:  gells.v O.K.'s.v OK's.v O.K.’s OK’s:

Though if I rewrite it like this:

2982:  gells.v O.K.'s.v OK's.v O.K.’s.v OK’s:

it works perfectly. (I added '.v' pos to O.K.’s)
I assume it parses this '.’s' as a pos and fails on it. (is this a correct pos at all?)

Can this be fixed somehow?
Thanks is advance.

Update:
The problem appears to be in this function:

void patch_subscript(char * s)
{
    char *ds, *de;
    ds = strrchr(s, SUBSCRIPT_DOT);
    if (!ds) return;

    /* a dot at the end or a dot followed by a number is NOT
     * considered a subscript */
    de = ds + 1;
    if (*de == '\0') return;

    if (isdigit((int)*de)) return;
    *ds = SUBSCRIPT_MARK;
}

in dict-common.c.
On that line function is being called with parameter O.K.’s
’ stands for apostrophe `

After taking the subscript part we get
de = "’s"
and ((int)*de) which is passed to isdigit function results into -30.
So the inner assertion in it fails. Basicall that is how we get the error.

What about adding our own check like this to have the trouble fixed:

// man isdigit: The value of the argument must be representable as an unsigned char or the value of EOF.
int chr = *de;
if (chr >= -1 && chr <= 255 && isdigit(chr)) return;

?

crash parsing a sentence

Parsing the following text causes a segmentation fault in the parser:

92 Chapter 10.............................................................................................................................................

This is reproducible both on Windows and in the Linux command-line link-parser, and this happens every time when we try to parse a document containing a table of contents. We will amend our sentence splitting and filtering to work this around, but perhaps this is worth looking at on the parser side too.

List of missing words

I gathered words, mostly from LG source comments and from my posts, that are missing in the LG English dictionary. In many cases, all/some of their possible variants are missing two.

I included only words that are found in one of:
http://www.oxforddictionaries.com
http://www.merriam-webster.com
Many other words, like "racey" and "unoptimized" don't appear there so they are not included.

blender
post-process
splitter
indices
prepend
backslash
call-out
catenation
catena
deallocated
globalization
deletable
descenders
descender
disjunction
enqueue
dequeue
entropies
extern
initialization
optimizations
optimization
paren
parens
preprocessor
propagations
reentrant
relicense
splitter
sublicense
subsumption
Unicode
unordered
unreached
unuseful
unusefulness
breakpoint
checkpoint
identifier
disinformation

clang compilation issues

Compiling under clang has the following issues:

  1. WARNING: unknown warning option '-Wunsafe-loop-optimizations'
  2. WARNING: utilities.c:235:6: warning: no previous prototype for function 'lg_mbrtowc' [-Wmissing-prototypes]
    void lg_mbrtowc() {}
  3. ERROR: Undefined symbol "_analyze_thin_linkage" referenced from link-grammar.def
  4. WARNING: ../../bindings/perl/lg_perl_wrap.cc:529:7: warning: 'register' storage class specifier is deprecated [-Wdeprecated-register]
  5. ERROR: /opt/local/lib/perl5/5.16.3/darwin-thread-multi-2level/CORE/pad.h:236:17: error: invalid suffix on literal; C++11 requires a space between literal and
    identifier [-Wreserved-user-defined-literal]
    "Pad 0x%"UVxf"[0x%"UVxf"] set_cur depth=%d\n"
    NOTE: the perl binding compilation doesn't fail on version 5.2.1 using the same compilation environment.

The compiler version is the one that comes with the latest xcode,
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)

afdict_to_wide fails to read the dictionary files whlie called from Python bindings.

I tried to investigate the problem a little bit, and modified the error message to output more info:

        wchar_t wstr[3];
    w = mbsrtowcs(wstr, &pqs, 3, &mbs);
    if (0 > (int) w) /* mbsrtowcs returns ((size_t) -1) on error */
    {

        prt_error("Error: Affix dictionary: %s: (%d) (%s) (%d) "
                  "Invalid utf8 character\n", afdict_classname[classno], 
                  (int)w, pqs, wstr[0]);
        return false;
    }

This is the part of the function that fails, and here's an example Python code that calls it:

>>> foo = linkgrammar.Sentence(u"This is a test sentence", linkgrammar.Dictionary(), linkgrammar.ParseOptions())
link-grammar: Info: Dictionary found at ./data/en/4.0.dict
link-grammar: Error: Affix dictionary: QUOTES: (-1) («»《》【】『』`„“) (34) Invalid utf8 character

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/linkgrammar/linkgrammar.py", line 341, in __init__
    self._obj = clg.sentence_create(self.text, self.dict._obj)
TypeError: in method 'sentence_create', argument 1 of type 'char *'

If I remove the line with the quotes from the dictionary, the code will choke on the next entry (the bullets) and so on. The file isn't corrupt and the angle quotes are a perfectly valid Unicode characters. If I copy the bytes and they try to interpret them as UTF-8 encoded text, it works (in Python):

>>> quotes = b"\x22\x22\xc2\xab\xc2\xbb\xe3\x80\x8a\xe3\x80\x8b\xe3\x80\x90\xe3\x80\x91\xe3\x80\x8e\xe3\x80\x8f\x60\xe2\x80\x9e\xe2\x80\x9c\x22\x3a\x20\x51\x55\x4f\x54\x45\x53\x2b\x3b"
>>> quotes.decode('utf-8')
'""«»《》【】『』`„“": QUOTES+;'

path_found is not getting freed, and also can be incorrectly resued

  • It is not getting freed when the dictionary is closed .
  • Reusing this variable may cause a mess if a chdir() or dictionary_set_data_dir() is invoked between dictionary opens.

So I propose to free and nullify it in dictionary_delete() and dictionary_six().
I thought of 2 ways to do that:

  1. Make it a non-static global, and use extern to access it in the needed 2 other places.
  2. Make it a private static in a new function cache_data_path(), that will be used to get/free/set this variable.

Linas, I can send a fix if you tell me which way to choose.

/* XXX static global variable used during dictionary open */
static char *path_found = NULL;

static void * dict_file_open(const char * fullname, void * user_data)
{
    const char * how = (const char *) user_data;
    FILE * fh =  fopen(fullname, how);
    if (fh && NULL == path_found)
    {
        path_found = strdup (fullname);
        prt_error("Info: Dictionary found at %s", fullname);
    }
    return (void *) fh;
}

Installing link-grammar on RaspberryPi

I'm installing the link-grammar library on my RaspberryPi, and everything looks ok except Python bindings.
When configuring, I enabled the option for python binding but Python says
"/usr/local/lib/python2.7/dist-packages/linkgrammar/_clinkgrammar.so: undefined symbol: parse_options_set_display_morphology" after importing linkgrammr module.
Is there anything that I missed when installing the library?

Crash when creating a linkage diagrams of extra-long sentences

I started to modify linkage_print_diagram_ctxt() in order to allow long link names between words (that are now truncated). While doing that, I found the said crash problem.

The problem is the fixed size of the picture array, which its bounds are not checked.
Possible solutions:

  1. On out-of-bounds, return an empty string, an error message, or even a NULL, and also print an error message.
  2. Truncate the picture on out-of-bounds + print an error message.
  3. alloca() picture/xpicture using line_len as the MAX_LINE dimension. However, I cannot see how to easily find, in advance, the MAX_HEIGHT (max. top_row) dimension. This can be solved with a realloc() in case of an out-of-bound top_row. (alloca() of an arary of pointers is needed.)

I think there is no point to implement (2) (it is just a complexity with no added value - there is no benefit in providing a truncated diagram).

The easy fix is (1). The remaining questions are the returned value in case of an error, and if an error message is printed, whether to print it only in verbosity>0.

I'm for returning NULL (current programs that are not careful to check returned UI values may crash on it, but they would crash anyway on extra-long sentences if they use the current library) plus an error message when verbosity>0.

Linas, please tell me which way to choose and I will send a pull request.

Problem running tests.py

I am trying to run tests.py without installing.

I have set PYTHONPATH to the location of linkgrmmar.py and to the location of _clinkgrammar.so, as follows:

export PYTHONPATH=/usr/local/src/link-grammar-devel/master/bindings/python:/tmp/link-grammar/master/bindings/python/.libs
ls /usr/local/src/link-grammar-devel/master/bindings/python /tmp/link-grammar/master/bindings/python/.libs

/tmp/link-grammar/master/bindings/python/.libs:
_clinkgrammar.a   _clinkgrammar.lai                  _clinkgrammar.so    _clinkgrammar.so.5.2.5
_clinkgrammar.la  _clinkgrammar_la-lg_python_wrap.o  _clinkgrammar.so.5

/usr/local/src/link-grammar-devel/master/bindings/python:
AUTHORS  __init__.py.in  LICENSE  linkgrammar.py  linkgrammar.pyc  Makefile  Makefile.am  Makefile.in  README.md

However, I get an ImportError:

python2.7 /usr/local/src/link-grammar-devel/master/bindings/python-examples/tests.py
Traceback (most recent call last):
  File "/usr/local/src/link-grammar-devel/master/bindings/python-examples/tests.py", line 12, in <module>
    import linkgrammar._clinkgrammar as clg
ImportError: No moduIs there a way tole named _clinkgrammar
Exit 1

I can fix this import error by a change in tests.py:

-import linkgrammar._clinkgrammar as clg
+import _clinkgrammar as clg

Now it runs fine:


python2.7 /usr/local/src/link-grammar-devel/master/bindings/python-examples/tests.py
............................link-grammar: Info: Dictionary found at /tmp/link-grammar/master/data/en/4.0.dict
.....................
----------------------------------------------------------------------
Ran 49 tests in 8.183s

OK

So how can I run the current tests.py without installing?
(I would like to fix "make check" to do that.)

conjoined pronouns broken in link-grammar

This was previously reported as a relex bug, here: opencog/relex#127 but its a link-grammar bug.

There is no way to conjoin "his or her" as determiners.

"each of the clerks does a good deal of work around his or her office"

Note, BTW, this is closely related to the determiner problem facing "he is either in the 105th or the 106th regiment".

This suggests maybe using the AJ links, which could the D+ to the noun. ???

Perl installation ignores --prefix option

I'm trying to install link-grammar into virtualenv (This is a Python way of creating a kind of isolated environment.) While Java bindings seem to honor the --prefix option, Perl tries to install into system-level directory. I don't really need Perl bindings, but I also couldn't find a way to disable them.

Here's how I've configured the project:

./configure --enable-python-bindings \
            --prefix=$(readlink -f ../bin) \
            --includedir=$(readlink -f ../includes)

The relevant output from running this is:

link-grammar-5.3.0  build configuration settings

    prefix:                         /home/wvxvw/Projects/auntie-rem/bin
    C compiler:                     gcc  -DUSE_SAT_SOLVER=1 -DHAVE_SQLITE=1 -g -O2 -O3 -std=c99 -D_BSD_SOURCE -D_SVID_SOURCE -D_GNU_SOURCE -D_DEFAULT_SOURCE
    C++ compiler:                   g++  -DUSE_SAT_SOLVER=1 -DHAVE_SQLITE=1 -g -O2 -O3 -Wall -std=c++03
    autopackage relocatable binary: no
    Posix threads:                  no
    Editline command-line history:  no
    UTF8 editline support:          no
    Java libraries:                 no
    Java interfaces:                yes
    Swig interfaces generator:      yes
    Perl interfaces:                yes
    Perl install location:          /usr/local/lib64/perl5
    Python interfaces:              yes
    ASpell spell checker:           no
    HunSpell spell checker:         no
    HunSpell dictionary location:   
    Boolean SAT parser:             yes
    SQLite-backed dictionary:       yes
    Viterbi algorithm parser:       no
    Corpus statistics database:     no
    Anysplit word splitter:         
    RegEx tokenizer:                no

When I run make install it breaks on:

make[2]: Entering directory '/home/wvxvw/Projects/auntie-rem/link-grammar/bindings/perl'
make  install-am
make[3]: Entering directory '/home/wvxvw/Projects/auntie-rem/link-grammar/bindings/perl'
make[4]: Entering directory '/home/wvxvw/Projects/auntie-rem/link-grammar/bindings/perl'
make[4]: Nothing to be done for 'install-exec-am'.
 /usr/bin/mkdir -p '/usr/local/lib64/perl5'
 /usr/bin/install -c ../../bindings/perl/clinkgrammar.pm '/usr/local/lib64/perl5'
/usr/bin/install: cannot remove ‘/usr/local/lib64/perl5/clinkgrammar.pm’: Permission denied
Makefile:496: recipe for target 'install-dist_pkgperlSCRIPTS' failed
make[4]: *** [install-dist_pkgperlSCRIPTS] Error 1
make[4]: Leaving directory '/home/wvxvw/Projects/auntie-rem/link-grammar/bindings/perl'
Makefile:676: recipe for target 'install-am' failed
make[3]: *** [install-am] Error 2
make[3]: Leaving directory '/home/wvxvw/Projects/auntie-rem/link-grammar/bindings/perl'
Makefile:670: recipe for target 'install' failed
make[2]: *** [install] Error 2
make[2]: Leaving directory '/home/wvxvw/Projects/auntie-rem/link-grammar/bindings/perl'
Makefile:407: recipe for target 'install-recursive' failed
make[1]: *** [install-recursive] Error 1
make[1]: Leaving directory '/home/wvxvw/Projects/auntie-rem/link-grammar/bindings'
Makefile:531: recipe for target 'install-recursive' failed
make: *** [install-recursive] Error 1

Bugs/issues listed at googlecode

There are currently eleven open issues listed at googlecode:

https://code.google.com/p/link-parser/issues/list?cursor=link-parser%3A58&ts=1419717174

A cut-n-paste shows:

10  Defect      Accepted    Medium  ----     Construction: "[Verb] like [phrase].    
14  Defect      Accepted    Medium  ----     Questions involving comparatives    
15  Defect      Accepted    Medium  ----     "If ..., then ..." fails to parse   
27  Defect      Accepted    Medium  ----     incomplete constituent tree     
28  Defect      Accepted    Medium  ----    ldouble dashes are mis-parsed    
31  Enhancement     Assigned    Medium  ----    add support for circumpositions      
34  Enhancement     Assigned    Low     ----    Elegent normal form      
50  Defect      New     Medium  ----    to pattern: "I have to reading books." is accepted   
58  Enhancement     Started     High    ----    Head word links needed.      
62  Defect      Accepted    Medium  ----    Russian capitalization broken    
63  Defect      Accepted    Medium  ----    Imperatives, commands broken 

Error while building

Hi guys, I'm facing the following error while issuing make command with latest version of linkgrammar

make[1]: Entering directory/home/misgana/OPENCOG/link-grammar/link-parser'
CC link-parser.o
CC command-line.o
CC lg_readline.o
CCLD link-parser
../link-grammar/.libs/liblink-grammar.so: undefined reference to print_hier_position' collect2: error: ld returned 1 exit status make[1]: *** [link-parser] Error 1 make[1]: Leaving directory /home/misgana/OPENCOG/link-grammar/link-parser'
make: *** [all-recursive] Error 1
`

major cause seems print_hier_position is not being resolved.

Broke clause modifiers

Most of these are broken

He emerged, spirit unbroken
He was set free, spirit unbroken.
He laughed, at last set free <-- works now

He cried, heart heavy
He cried, his heart heavy
He cried, heavy-hearted
Heart heavy, he cried
He cried, his heart heavy with sadness
He winced, pain shooting up his arm <-- works now
He reddened, angered by their words
He reddened, embarrassed by their words <-- works, MVg link
He shuffled, sad in his heart < -- works now
He shuffled, aching limbs hanging heavy
He sneezed, eyes red and itchy
He nodded, eyelids drooping with sleep
He coughed, clearing his throat < -- works now
He stumbled, eyes blinded by the sudden light <-- works Xx
He stumbled, blinded by the sudden light

Fixing the word-graph display feature

While it works fine on Linux, and even works on Windows when compiling with MSVC if it runs under Cygwin/X, it doesn't work on pure Windows. It also has some design problems. All of these can be fixed.

I would like to send two sets of pull requests:

  1. Fixes for the design problems.
  2. Fixes for compiling and and running under pure Windows (when Graphviz for Windows is installed - it has a turnkey installation package).

Fixing the SAT solver

Hi Linas!

I mostly finished the full integration of the SAT solver.
In addition to the previous fixes, that are listed in the comment in #187, I have fixed several more aspects of the SAT solver:

  1. Initialized the domain array so it doesn't crash on !links.
  2. It now works fine on Hebrew too.
  3. It frees properly all memory.
  4. I rearranged some of the code to be more similar to that of the standard resolver.
  5. It now works fine on batches!
  • It gives exactly the same number of errors on all the languages.
  • From first glance, differences in diagrams of errors are due to different linkages order.
  • Initial batch runtime comparisons to the regular solver:
    • Slightly slower on en/4.0/batch.
    • Definitely faster on en/4.0/fixes.batch.
    • About twice faster on the Russian batch.

​6. The maximum number of shown linkages is now !limit instead of the arbitrary 222.


Remained to fix:

  1. Different costs are shown in !disjuncts.
  2. The DIS= cost in the status message is always 0.
  3. It still checks only alternative[0] in in guiding.cpp. I need to check if fixing this will help finding linkages faster for the affected sentences.
  4. More code can be made similar, and more code can be shared (i.e. the SAT solver code can call more functions from the regular LG lib).
    However, this will need adding more functions to link-grammar.def (I already added many).
    Alternatively, and maybe better, the shared functions can be moved to the corresponding .h files, and be removed from link-grammar.def. This will solve the problem of the many non-API symbols that are exported by the LG lib.
  5. It may be interesting to replace the current MiniSAT code (an old release) by the latest release (version 2.2). Github: niklasso/minisat.
  6. Please add more issues if I forgot something...

Need SQLite3-backed dictionary

Need to complete work on an sqlite3-backed dictionary. The design goals are that the contents of 4.0.dict and of the word lists, should be available by SQL. At this time, having post-processing and regex, is NOT important -- these can stay in plain files.

(The implementation goals are "common-sense" avoid duplicated code, avoid a spaghetti of header include files, avoid stove-pipe design patterns, etc.)

The meta-goal of the sqlite DB is to allow language-learning code to create data which LG can then access, and an sql db seems like the best, simplest way to achieve this portability, right now. (there are other ways, too... worth exploring...)

DB design would be one disjunct per row. viz. each row of the DB is a (word-n-suffix, plain-word-wo-suffix, disjunct, float-pt-cost) where the disjunct is either a string A+ & B+ & C- or an ordered list [A+, B+, C-].

The ideal interface to the DB is to be able to ask for a word, and get all expressions for it. Unlike the file-backed dict, the sql dict should NOT be loaded into LG RAM. This is because, in some future version, LG needs to be able to ask some other authority about a word, and get expressions back. That "other authority" might be a running version of opencog.

So, in fact, an even better design goal might be this: provide a network interface, e.g. ZMQ, (or, god help us, ROS) that allows a word to be queried, and all the word-expressions to be returned. Then, on the other side of that interface, we could have any of several servers: a file-backed dict server, an sqlite-backed dict-server, and opencg-backed dict-server ...

The final end-goal is to eventually have a networked dictionary-server. Perhaps having sqlite3 as a stepping stone is easier/better...

Argument "dir" of match_in_connector_set()

Here is the code of this funtion:

bool match_in_connector_set(Connector_set *conset, Connector * c, int dir)
{
    size_t h;
    Connector * c1;
    if (conset == NULL) return false;
    h = connector_set_hash(conset, c->string, dir);
    for (c1 = conset->hash_table[h]; c1 != NULL; c1 = c1->next)
    {
        if (easy_match(c1->string, c->string) && (dir == c1->word)) return true; <---
    }
    return false;
}

Note the line marked with <---.
Since this function appears as 1.4% in the profiling, I tried to speed it up by reversing the order of the && check. However, it only increased its CPU usage. It turns out (dir == c1->word) is always true, because this function is now only invoked with dir=='+'.

The only place in which it got invoked with dir=='-' was in the file and.c, which has gone with the FAT-LINKS code.
So I guess it is OK to simplify it by removing the dir argument from it.

Merging strategy for the wordgraph code

Hi Linas,
I have just rebased my wordgraph branch on the current opencog/master.
It replaces my previous branch with the same name, that once got a trashed commit history, and because nobody was supposed to use anything from it up to now, I did the unusual thing of overwriting it on github.

If you once have fetched it, I guess that fetching it again now may cause a mess (because it is a different branch with the same name), so you may need to first delete the remote tracking wordgraph branch if you have one.

Alternatively I can rename it to some other name, like wordgraph2.
In any case, the pull request from this branch can now be cleanly merged.
Just tell me if to leave the branch name as is (wordgraph) or rename it and I will then send you this pull request.

I also have some new fixes for 5.2.5 (that are not applied yet to the wordgraph branch). One is the Windows project file fix (the I discribed in may last post to the group).
Another one is the dictopen fix (that I still need to test on Windows, now that I succeeded to compile LG on it).
The other two are not tested yet. One fixes a potential memory corruption problem on sent->lang.
The other fixes potential incorrect language setup on Windows.

I mention this because I wonder in which order we should continue: should I first send you these relatively small fixes (but then I'm not totally sure that the wordgraph pull request will remain "clean"), or maybe the wordgraph merge should be done first (since the said fixes are not very urgent) and then we will apply them on top of the merged version.

Handling quotation marks

In the current code, quotation marks are removed from the sentence.
Actually, they are converted to whitespace. This means they serve as a word separator.
For example:
This"is a test"
is converted to:
This is a test

In addition, a word just after quotation mark is considered to be in a capitalizable position.
This is true even for closing quotation mark... including when it is a "right mark".

In my new tokenization code, quotes are tokenized. They are defined in RPUNC and LPUNC, thus they get strip off words from their LHS and RHS. However, this doesn't preserve its "separator" behavior that exit in the current code.

In English (and I guess some other languages, maybe many) this seems to be a desired behavior,
because if we see qwerty"yuiop" we may guess it is actually qwerty "yuiop".

However, to generally do this in Hebrew will be wrong, as double quote U+0022 is a de facto replacement for the Hebrew character "gershayim" that can be an integral part of Hebrew words (as
gershayim is not found on the Hebrew keyboard). It is also a de facto replacement for Hebrew quotation marks (form the same reason). So a general tokenization code cannot blindly use it as a word separator.

In order to solve this, I would like to introduce an affix-class WORDSEP, which will be a list of characters to be used as a word separator, when blank would be the default. Character listed there will still be able to be listed in other affix classes and thus serve as tokens.
Is this solution sensible?
Another option is just not to use it as a word separator, at least in the first version of "quotation mark as token" (this is what my current code does).

Regarding the capitalizable position after closing quote, meanwhile I will mostly preserve this behavior in the hard-coded capitalization handling, because we are going to try to implement capitalization using the dict.

islands_ok flag should not be true

There was a problem to make a direct detailed comparison of run batches with these 2 different versions of the program, because the dicts are slightly different, 5.3.0 prints long labels and has defaults to island_ok=1

So I ran both on the dict of 5.2.x, both with with -island_ok=0, and commented out producing long labels in 5.3.0. I also added -constituents=1 to both. I used en/4.0.batch. I did this check to validate that the latest fixes didn't break it. Previously (before the above mentioned changes between the versions) I checked it in a similar manner on the other batch files.

There was only two changes in the output (differences in blank lines ignored and their reason has not been investigated):

Expected:

< /tmp/link-grammar/link-grammar-5.2.5-maintenance

---
> /tmp/link-grammar/linkage
...
< LEFT-WALL [But] why did.v-d you send.v him that.j-d nasty.a note.n 

---
> LEFT-WALL [but] why did.v-d you send.v him that.j-d nasty.a note.n 
...
< (S {But} why did.v-d

---
> (S {but} why did.v-d

Minor tokenizing difference - Corp. got broken also to Corp . and the dict accepted both:

< Found 12 linkages (12 had no P.P. violations)

---
> Found 24 linkages (24 had no P.P. violations)
...
< Alfred.m Baird[!] , formerly vice.n-u president.t of Beevil[!] Corp..y , has.v been.v appointed.v-d as.e president.t 

> Alfred.m Baird[!] , formerly vice.n-u president.t of Beevil[!] Corp.y . , has.v been.v appointed.v-d as.e president.t 

Making connector handling much faster

Hi Linas,
I did profiling and found several "hot spots" in the regular parser (I will discuss the profiling of the SAT parser in another post).

Among them are connector comparisons.
post_process_match() is now the no. 1 CPU consumer.
easy_match() is no. 2.
(I neglect for now malloc/realloc/free, which take about 35% of the CPU...).

It turned out it is possible to speed-up these functions by much.
With these modifications, the batch benchmarks run much faster (~15% speed-up on fixes.batch).

The only drawback is that the new code is maybe less straight-forward (but adding appropriate comments may mitigate that).
The speed-up is based on these ideas:

  1. Assume that the connector syntax is valid. Thus, it is possible to assume that after the optional head/dependent marking, there is at least one uppercase letter. 2imilarly, it is possible to assume that the uppercase letters, if there are more than one, are consecutive.
  2. Use all the info we have at each point, in order to have the "shortest path" from entry to exit in each function.
  3. Use islower()/isupper() as few times as possible, since they are more costly than regular comparisons.
  4. Use !isupper() instead of islower(), to prevent cache trashing by an additional memory reference (yields a slight but yet an observable speed-up).

Here is how the faster post_process_match() looks like (still subject to change):

bool post_process_match(const char *s, const char *t)
{
    if (NULL == t) return false;
    if (!isupper((int)*t)) t++; /* Skip head-dependent indicator */

    if (*s != *t) return false;
    while (*++s == *++t)
    {
        if (*s == '\0') return true;
    }
    /* Ensure all the uppercase letters have matched. */
    if (*s == '\0') return !isupper((int)*t);
    if (isupper((int)*s)) return false;
    if ((*s == '#') && isupper((int)*t)) return false;

    do
    {
        if ((*s != '#') && (*s != ((*t == '\0') ? '*' : *t))) return false;
        if (*t != '\0') t++;
    } while (*++s != '\0');
    return true;
}

Here is some benchmark:
Average of 25 runs, each 5G iterations (interleaving runs of current and modified code).
(The times include the C program invocation and the loop overhead.)

A A A B AX BY ABc ABd hA dA hA hA AB# ABcv*b Pa##j Pabcj C# C*
current 27.2 19.9 20.0 33.6 20.6 19.5 35.7 41.0 33.8
modified 15.8 10.5 10.5 22.1 9.93 9.46 25.2 33.3 22.2

Here is a similar benchmark for the new easy_match():
Average of 12 runs, each 5G iterations (interleaving runs of current and modified code).
(The times include the C program invocation and the loop overhead.)

A A A B AX BY ABc ABd ABx ABx hA dA hA hA ABC*b ABCab Aab A*b A_b A_bc BA B* B* BA LLCMC LLCMD ABc AB AB ABc ABc ABce hA dAB
current 11.6 6.32 6.32 30.2 31.5 11.6 3.79 41.8 31.7 31.8 8.86 10.2 31.5 14.8 14.8 31.7 11.7
modified 7.59 5.05 5.06 12.9 11.6 10.1 3.78 31.7 18.3 11.4 12.6 11.4 17.9 10.2 9.02 11.5 8.86

I have an idea how to further speed-up these function, and also speed-up the connector hash calculation: When reading the dict, calculate the following for each connector: uppercase start offset, uppercase end offset, and maybe also total length and whether there is a wildcard. I intend to check if this can provide an additional significant speed-up.

Meanwhile, if the idea of improving the speed-up of easy_match() and post_process_match() this way seems to you fine, I can send a pull request.

I also did numerous other speed-up modifications, which their accumulated effect is still unknown. Maybe I will include them in the same pull request (as separate commits of course.)

Is libaspell not thread-safe?

Usually the multi-thread test runs fine. However, one time I got this:

Making check in tests
  CXX      dict-reopen.o
  CXX      multi-thread.o
  CXX      mem-leak.o
  CXXLD    mem-leak
  CXXLD    dict-reopen
  CXXLD    multi-thread
PASS: mem-leak
*** Error in `/tmp/link-grammar/linkage/tests/.libs/lt-multi-thread': double free or corruption (!prev): 0x00007f25bc0846c0 ***
======= Backtrace: =========
/lib64/libc.so.6[0x3069277e9d]
/lib64/libc.so.6[0x306927f53c]
/lib64/libc.so.6(cfree+0x4c)[0x3069283e9c]
/lib64/libaspell.so.15(_ZNSt6vectorIN7acommon10FilterCharESaIS1_EE13_M_insert_auxEN9__gnu_cxx17__normal_iteratorIPS1_S3_EERKS1_+0x13a)[0x34348561ba]
/lib64/libaspell.so.15(_ZNK7acommon10DecodeUtf86decodeEPKciRNS_16FilterCharVectorE+0x172)[0x34348563a2]
/lib64/libaspell.so.15(aspell_speller_suggest+0x19e)[0x34348a367e]
/tmp/link-grammar/linkage/link-grammar/.libs/liblink-grammar.so.5(+0x39b9b)[0x7f25f1c3fb9b]
/tmp/link-grammar/linkage/link-grammar/.libs/liblink-grammar.so.5(+0x3e0a8)[0x7f25f1c440a8]
/tmp/link-grammar/linkage/link-grammar/.libs/liblink-grammar.so.5(+0x3e7c6)[0x7f25f1c447c6]
/tmp/link-grammar/linkage/link-grammar/.libs/liblink-grammar.so.5(sentence_split+0x12)[0x7f25f1c0cfb2]
/tmp/link-grammar/linkage/tests/.libs/lt-multi-thread[0x40178a]
/lib64/libstdc++.so.6[0x3430eb9360]
/lib64/libpthread.so.0[0x3069a07555]
/lib64/libc.so.6(clone+0x6d)[0x3069301f3d]
======= Memory map: ========
00400000-00403000 r-xp 00000000 00:22 2588455                            /tmp/link-grammar/linkage/tests/.libs/lt-multi-thread

Edit:
Inddeed it is not thread-safe, for now, and hence shouldn't be configured by default.
On the other hand, hunspell is mostly thread-safe (beside compounds in Hungarian).

From http://aspell.net:

There are several areas of Aspell that that are potently thread unsafe (such as accessing a global pool) and several classes which have the potential of being used by more than one thread (such as the personal dictionary). [In Progress].

memory leak parsing a sentence

Hi,

The following code (taken from the API example pages and having an infinite loop added) leaks memory:

#include <locale.h>
#include <stdio.h>
#include "link-grammar/link-includes.h"

int main()
{
    Dictionary    dict;
    Parse_Options opts;
    Sentence      sent;
    Linkage       linkage;
    char *        diagram;
    int           i, num_linkages;
    char *        input_string[] = {
       "Grammar is useless because there is nothing to say -- Gertrude Stein.",
       "Computers are useless; they can only give you answers -- Pablo Picasso."};

    setlocale(LC_ALL, "en_US.UTF-8");
    opts = parse_options_create();
    dict = dictionary_create_lang("en");
    if (!dict) {
        printf ("Fatal error: Unable to open the dictionary\n");
        return 1;
    }

    while(1) // infinite loop to demonstrate memory leaking
    for (i=0; i<2; ++i) {
        sent = sentence_create(input_string[i], dict);
        sentence_split(sent, opts);
        num_linkages = sentence_parse(sent, opts);
        if (num_linkages > 0) {
            linkage = linkage_create(0, sent, opts);
            diagram = linkage_print_diagram(linkage, true, 800);
            linkage_free_diagram(diagram);
            linkage_delete(linkage);
        }
        sentence_delete(sent);
    }

    dictionary_delete(dict);
    parse_options_delete(opts);
    return 0;
}

I have already fixed another memory leak in the clear_pp_node() function only to find it is already fixed in the latest git version, but now I found there is another memory leak.

I tracked it down to the add_empty_word() function which is called every time, the new words are constantly added to dict->exp_list, and this list is never cleaned unless you do dictionary_delete(), which kind of works around the problem.

Any insights on how to fix this leak?

BTW, re-creating the dictionary is not perfect either because there is another (much smaller) memory leak doing so -- 549 xallocs are still leaking on every dictionary re-creation, but this will become rather minor after there is a fix for the actual parse leaking memory since normally you don't want to re-create dictionaries every time.

parse count is off-by-1 in a corner case.

While running in Windows, I encountered an alloca() out of bound when there is only 1 word in the linkage.
In that case (at least) an assignment is done to pctx->row_starts[1] while only 1 element is allocated.

I did these printouts:

char * linkage_print_diagram(const Linkage linkage, bool display_walls, size_t screen_width)
{
    ps_ctxt_t ctx;
    if (!linkage) return NULL;

    ctx.link_heights = (int *) alloca(linkage->num_links * sizeof(int));
    ctx.row_starts = (int *) alloca(linkage->num_words * sizeof(int));
printf("linkage->num_words=%zu\n", linkage->num_words);
    return linkage_print_diagram_ctxt(linkage, display_walls, screen_width, &ctx);
}
linkage_print_diagram_ctxt(const Linkage linkage, ...
...
        pctx->row_starts[pctx->N_rows] = i - (!print_word_0);    /* PS junk */
    printf("pctx->N_rows=%d\n", pctx->N_rows);
        if (i < N_words_to_print) pctx->N_rows++;     /* same */

I got this:

$ link-parser he
linkparser> x
Found 1 linkage (1 had no P.P. violations)
    Unique linkage, cost vector = (UNUSED=1 DIS= 0.00 LEN=0)
linkage->num_words=1
pctx->N_rows=1

[x] 

Valgrind and ASAN (on Linux) don't catch this problem.
I don't yet understand this code... But maybe allocating one more element will be enough to avoid it.

(BTW, I don't understand why this is a "linkage", and why no null word count is reported.)

Crash when parsing a lot of sentences continuously

When parsing sentences from Simple English Wikipedia via RelEx continuously, it crashed at some point with this error:

*** Error in `java': free(): invalid pointer: 0x00007f63ea9403f0 ***

A memory leak perhaps...?

memory leak parsing a sentence (new one)

The following code leaks memory:

#include <locale.h>
#include <stdio.h>
#include "link-grammar/link-includes.h"

int main()
{
    Dictionary    dict;
    Parse_Options opts;
    Sentence      sent;
    Linkage       linkage;
    char *        diagram;
    int           i, num_linkages;
    char *        input_string[] = {"Perhaps it is and perhaps it isnt."};

    setlocale(LC_ALL, "en_US.UTF-8");
    opts = parse_options_create();
    parse_options_set_max_null_count(opts, 10);
    parse_options_set_display_morphology(opts, 1);

    dict = dictionary_create_lang("en");
    if (!dict) {
        printf ("Fatal error: Unable to open the dictionary\n");
        return 1;
    }
    int qq = 0;
    while(++qq < 100)
    for (i=0; i<1; ++i) {
        sent = sentence_create(input_string[i], dict);
        sentence_split(sent, opts);
        num_linkages = sentence_parse(sent, opts);
        if (num_linkages > 0) {
            linkage = linkage_create(0, sent, opts);
            diagram = linkage_print_diagram(linkage, true, 800);
            linkage_free_diagram(diagram);
            linkage_delete(linkage);
        }
        sentence_delete(sent);
    }

    dictionary_delete(dict);
    parse_options_delete(opts);
    return 0;
}

The memory leak is specific to the parse_options_set_max_null_count(opts, 10); option and to the sentence being parsed -- note the missing apostrophe in "Perhaps it is and perhaps it isnt." -- imagine the time it took me to find this one in a large .NET project with various native code mixed in :)

Varlgrid's output is the following:

==36481== 415,008 (65,184 direct, 349,824 indirect) bytes in 97 blocks are definitely lost in loss record 6 of 6
==36481==    at 0x4C28BED: malloc (vg_replace_malloc.c:263)
==36481==    by 0x4E5C618: exalloc (utilities.c:505)
==36481==    by 0x4E35777: sentence_parse (api.c:409)
==36481==    by 0x400C88: main (in /home/dev/link-grammar-5.2.1/a.out)

Speaking of the parse options, could you please suggest the options that provide an optimal balance between performance and precision for offline parsing? The default linkage_limit of 1000 seems to provide rather different random results every time, which doesn't seem right. Could you suggest if there are any other options worth tweaking? The documentation is not very clear about what the various options mean unless you are very knowledgeable with the way the parser works.

A strange problem after removing the empty words before post_process_linkages()

I compared the en/4.0.batch and en/4.0.fixes.batch results (parse/no parse) between the current git version and my version with remove_empty_words() (which is called in compute_chosen_disjuncts() - before post_process_linkages() is called).

The only difference is in this sentence:
Should I attempt to call you, or you me?

As a test, when I remove remove_empty_words(), there is no difference also in this sentence (i.e. this problem disappears).

In the git version, this is the parsing of this sentence:

linkparser> Should I attempt to call you, or you me?
Found 4 linkages (2 had no P.P. violations)
    Linkage 1, cost vector = (UNUSED=0 DIS= 0.00 LEN=18)

    +-----------------------------Xp-----------------------------+
    |         +------I-----+------IV---->+-----VJd----+---Oxn--+ |
    +----Qd---+SIp*i+      +---TO--+-I*t-+-Ox-+  +-Xd-+-Ox-+   | |
    |         |     |      |       |     |    |  |    |    |   | |
LEFT-WALL should.v I.p attempt.v to.r call.v you , or.j-o you me ? 

               LEFT-WALL      Xp            ----Xp-----  Xp              ?
               LEFT-WALL      Qd            ----Qd-----  Qd              should.v
               should.v       I             ----I------  I               attempt.v
               should.v       SI            ----SIp*i--  SIp*i           I.p
 (v) (t) (v)   attempt.v      IV            ----IV---->  dIV             call.v
 (v)           attempt.v      TO            ----TO-----  TO              to.r
 (v) (t)       to.r           I*t           ----I*t----  I               call.v
 (v) (t) (v)   call.v         VJd           ----VJd----  VJd             or.j-o
 (v) (t) (v)   call.v         O             ----Ox-----  Ox              you
 (v) (t) (v)   ,              Xd            ----Xd-----  Xd              or.j-o
 (v) (t) (v)   or.j-o         O*n           ----Oxn----  Ox              me
 (v) (t) (v)   or.j-o         O             ----Ox-----  Ox              you
               ?              RW            ----RW-----  RW              RIGHT-WALL

            LEFT-WALL    0.000  Qd+ Xp+ 
             should.v    0.000  Qd- SI+ I+ 
                  I.p    0.000  SIp*i- 
            attempt.v    0.000  I- TO+ IV+ 
                 to.r    0.000  TO- I*t+ 
               call.v    0.000  I- dIV- ZZZ+ O+ VJd+ 
       EMPTY-WORD.zzz    0.000  ZZZ- 
                  you    0.000  Ox- 
                    ,    0.000  Xd+ 
               or.j-o    0.000  Xd- VJd- O+ O*n+ 
                  you    0.000  Ox- 
                   me    0.000  Ox- 
                    ?    0.000  Xp- RW+ 

When using remove_empty_words(), there is no valid parses due to a postprocessing error:

linkparser> Should I attempt to call you, or you me?
Found 4 linkages (0 had no P.P. violations)
    Linkage 1 (bad), cost vector = (UNUSED=0 DIS= 0.00 LEN=15)
"Bad use of pronoun66"

    +-----------------------------Xp-----------------------------+
    |         +------I-----+------IV---->+-----VJd----+---Oxn--+ |
    +----Qd---+SIp*i+      +---TO--+-I*t-+-Ox-+  +-Xd-+-Ox-+   | |
    |         |     |      |       |     |    |  |    |    |   | |
LEFT-WALL should.v I.p attempt.v to.r call.v you , or.j-o you me ? 

               LEFT-WALL      Xp            ----Xp-----  Xp              ?
               LEFT-WALL      Qd            ----Qd-----  Qd              should.v
               should.v       I             ----I------  I               attempt.v
               should.v       SI            ----SIp*i--  SIp*i           I.p
 (v) (t) (v)   attempt.v      IV            ----IV---->  dIV             call.v
 (v)           attempt.v      TO            ----TO-----  TO              to.r
 (v) (t)       to.r           I*t           ----I*t----  I               call.v
 (v) (t) (v)   call.v         VJd           ----VJd----  VJd             or.j-o
 (v) (t) (v)   call.v         O             ----Ox-----  Ox              you
 (v) (t) (v)   ,              Xd            ----Xd-----  Xd              or.j-o
 (v) (t) (v)   or.j-o         O*n           ----Oxn----  Ox              me
 (v) (t) (v)   or.j-o         O             ----Ox-----  Ox              you
               ?              RW            ----RW-----  RW              RIGHT-WALL

            LEFT-WALL    0.000  Qd+ Xp+ 
             should.v    0.000  Qd- SI+ I+ 
                  I.p    0.000  SIp*i- 
            attempt.v    0.000  I- TO+ IV+ 
                 to.r    0.000  TO- I*t+ 
               call.v    0.000  I- dIV- ZZZ+ O+ VJd+ 
                  you    0.000  Ox- 
                    ,    0.000  Xd+ 
               or.j-o    0.000  Xd- VJd- O+ O*n+ 
                  you    0.000  Ox- 
                   me    0.000  Ox- 
                    ?    0.000  Xp- RW+ 
           RIGHT-WALL    0.000  RW- 

In 5.0.8, it also doesn't parse due to the same postprocessing error, and also inversion1.

I looks it has something to do with the last line of these lines in en/4.0.knowledge:

; There's no ZZZ connector, which means that Ixd and Oxn
; are prohibited from ever occuring. 4.0.batch covers this.
 Ixd   ,  ZZZ                               , "Can't use 'do' with that verb" ,
 Oxn   ,  ZZZ                               , "Bad use of pronoun66" ,
 MVh   ,  EExk   EAxk   D##k                , "Incorrect use of that67" ,

The assumption that there is no ZZZ connector is not correct any more in the latest versions.

At this point I got lost.
I guess you can make sense of these findings much more than me...

/* XXX FIXME in the future, linkage->num_words might not match sent->length */

In which situations such a thing can happen?

  1. When the parser processes the current word-array, it seems there should be one linkage word for each sentence word, so they must be equal.
  2. If the parser is changed to process the word graph, sent->length will not exist then.

Did I miss something? Is there another situation?

Double crash: Error: Illegal domain:

The current version aborts on the start of running en/4.0.batch and also on tests.py.
It prints:
link-grammar: Error: Illegal domain:
(Nothing is printed after the colon. Most probably it is '\0'.)
It then crashes in error.c:83, because of invalid alternatives array (I haven't tried yet to find out why).

The last good version seems to be c1f504c.
It is from 6 days ago, so it is strange that I didn't notice it before. So I cleared the compilation cache, recompiled from scratch, and even rebooted the computer, but the problem persists.

size_t format conversion specifyer on MSVC

While checking MSVC-compiled wordgraph version code on Windows (it needs some portability changes), I found that it crashes when verbosity > 1.

It turned out this happens when the code encounters a printf() that has %zu format. MSVC just doesn't support it and prints "zu" instead (without the leading %). A format argument mismatch then often happens and causes a crash. In MSVC, the supported format for size_t is %Iu.

There are 55 code lines which have %zu in them. They are used for Postscript generation, debug, assert, Info messages and verbosity > 1 problem messages.

Since not using size_t variables - to make the code portable to MSVC, is not a good option, I propose to solve the problem in one of these ways:

  1. Use a macro ZU that usually expands to "zu" but on MSVC expands to "Iu".
  2. Use macros (with the same names of the printf variants) that invoke functions that convert the formats and call the real printf variants).
  3. Use %lu and convert each size_t variable with a cast (unsigned long) directly of via a macro UL(s) ((unsigned long)(s)).

Using solution 1 is simple, but the result is not so nice:
For example, the following line from build_linkage_postscript_string()
append_string(string,"[%zu %zu %d",
is to be written in this way:
append_string(string,"[%"ZU" %"ZU" %d",

(I don't even want to consider (2)...).

Using solution (3) seems to be the most normal way. I'm for using a macro UL(s), to make less likely the need to break the printing calls to several lines.

Linas, if this is fine by you, I will send you a pull request.
I will then be able to proceed with other MSVC portability fixes.

Improving the speed of the SAT solver

Hi Linas,
I investigated the potential to improve the speed of the SAT solver (and to make it better in other aspects, but this for a yet another issue, later).

  1. Improve the speed for short sentences, with the goal to beat the standard parser speed.
    This will also improve the speed for long sentences. Currently the most CPU intensive SAT-encoding functions are for handling the variable name trie. I have some ideas how to improve it.
  2. Improve the speed for long sentences, by improving the SAT encoding CNF generation.
    As a proof-of-concept, I used PBLIB (free-of-use license) to improve the XOR encoding. This sole change resulted in a speed up of about 50% when running 4.0.fix-long.batch! Next, I would like to try to improve the AND and OR encoding (this is much less straight forward).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.