nltk.sem.logic module

A version of first order predicate logic, built on top of the typed lambda calculus.

class nltk.sem.logic.Tokens[source]

Bases: object

LAMBDA = '\\'
LAMBDA_LIST = ['\\']
EXISTS = 'exists'
EXISTS_LIST = ['some', 'exists', 'exist']
ALL = 'all'
ALL_LIST = ['all', 'forall']
DOT = '.'
OPEN = '('
CLOSE = ')'
COMMA = ','
NOT = '-'
NOT_LIST = ['not', '-', '!']
AND = '&'
AND_LIST = ['and', '&', '^']
OR = '|'
OR_LIST = ['or', '|']
IMP = '->'
IMP_LIST = ['implies', '->', '=>']
IFF = '<->'
IFF_LIST = ['iff', '<->', '<=>']
EQ = '='
EQ_LIST = ['=', '==']
NEQ = '!='
NEQ_LIST = ['!=']
BINOPS = ['and', '&', '^', 'or', '|', 'implies', '->', '=>', 'iff', '<->', '<=>']
QUANTS = ['some', 'exists', 'exist', 'all', 'forall']
PUNCT = ['.', '(', ')', ',']
TOKENS = ['and', '&', '^', 'or', '|', 'implies', '->', '=>', 'iff', '<->', '<=>', '=', '==', '!=', 'some', 'exists', 'exist', 'all', 'forall', '\\', '.', '(', ')', ',', 'not', '-', '!']
SYMBOLS = ['&', '^', '|', '->', '=>', '<->', '<=>', '=', '==', '!=', '\\', '.', '(', ')', ',', '-', '!']
nltk.sem.logic.boolean_ops()[source]

Boolean operators

nltk.sem.logic.equality_preds()[source]

Equality predicates

nltk.sem.logic.binding_ops()[source]

Binding operators

class nltk.sem.logic.LogicParser[source]

Bases: object

A lambda calculus expression parser.

__init__(type_check=False)[source]
Parameters

type_check (bool) – should type checking be performed to their types?

type_check

A list of tuples of quote characters. The 4-tuple is comprised of the start character, the end character, the escape character, and a boolean indicating whether the quotes should be included in the result. Quotes are used to signify that a token should be treated as atomic, ignoring any special characters within the token. The escape character allows the quote end character to be used within the quote. If True, the boolean indicates that the final token should contain the quote and escape characters. This method exists to be overridden

parse(data, signature=None)[source]

Parse the expression.

Parameters
  • data – str for the input to be parsed

  • signaturedict<str, str> that maps variable names to type strings

Returns

a parsed Expression

process(data)[source]

Split the data into tokens

process_quoted_token(data_idx, data)[source]
get_all_symbols()[source]

This method exists to be overridden

inRange(location)[source]

Return TRUE if the given location is within the buffer

token(location=None)[source]

Get the next waiting token. If a location is given, then return the token at currentIndex+location without advancing currentIndex; setting it gives lookahead/lookback capability.

isvariable(tok)[source]
process_next_expression(context)[source]

Parse the next complete expression from the stream and return it.

handle(tok, context)[source]

This method is intended to be overridden for logics that use different operators or expressions

attempt_adjuncts(expression, context)[source]
handle_negation(tok, context)[source]
make_NegatedExpression(expression)[source]
handle_variable(tok, context)[source]
get_next_token_variable(description)[source]
handle_lambda(tok, context)[source]
handle_quant(tok, context)[source]
get_QuantifiedExpression_factory(tok)[source]

This method serves as a hook for other logic parsers that have different quantifiers

make_QuanifiedExpression(factory, variable, term)[source]
handle_open(tok, context)[source]
attempt_EqualityExpression(expression, context)[source]

Attempt to make an equality expression. If the next token is an equality operator, then an EqualityExpression will be returned. Otherwise, the parameter will be returned.

make_EqualityExpression(first, second)[source]

This method serves as a hook for other logic parsers that have different equality expression classes

attempt_BooleanExpression(expression, context)[source]

Attempt to make a boolean expression. If the next token is a boolean operator, then a BooleanExpression will be returned. Otherwise, the parameter will be returned.

get_BooleanExpression_factory(tok)[source]

This method serves as a hook for other logic parsers that have different boolean operators

make_BooleanExpression(factory, first, second)[source]
attempt_ApplicationExpression(expression, context)[source]

Attempt to make an application expression. The next tokens are a list of arguments in parens, then the argument expression is a function being applied to the arguments. Otherwise, return the argument expression.

make_ApplicationExpression(function, argument)[source]
make_VariableExpression(name)[source]
make_LambdaExpression(variable, term)[source]
has_priority(operation, context)[source]
assertNextToken(expected)[source]
assertToken(tok, expected)[source]
nltk.sem.logic.read_logic(s, logic_parser=None, encoding=None)[source]

Convert a file of First Order Formulas into a list of {Expression}s.

Parameters
  • s (str) – the contents of the file

  • logic_parser (LogicParser) – The parser to be used to parse the logical expression

  • encoding (str) – the encoding of the input string, if it is binary

Returns

a list of parsed formulas.

Return type

list(Expression)

class nltk.sem.logic.Variable[source]

Bases: object

__init__(name)[source]
Parameters

name – the name of the variable

substitute_bindings(bindings)[source]
nltk.sem.logic.unique_variable(pattern=None, ignore=None)[source]

Return a new, unique variable.

Parameters
  • patternVariable that is being replaced. The new variable must be the same type.

  • term – a set of Variable objects that should not be returned from this function.

Return type

Variable

nltk.sem.logic.skolem_function(univ_scope=None)[source]

Return a skolem function over the variables in univ_scope param univ_scope

class nltk.sem.logic.Type[source]

Bases: object

classmethod fromstring(s)[source]
class nltk.sem.logic.ComplexType[source]

Bases: nltk.sem.logic.Type

__init__(first, second)[source]
matches(other)[source]
resolve(other)[source]
str()[source]
class nltk.sem.logic.BasicType[source]

Bases: nltk.sem.logic.Type

matches(other)[source]
resolve(other)[source]
class nltk.sem.logic.EntityType[source]

Bases: nltk.sem.logic.BasicType

str()[source]
class nltk.sem.logic.TruthValueType[source]

Bases: nltk.sem.logic.BasicType

str()[source]
class nltk.sem.logic.EventType[source]

Bases: nltk.sem.logic.BasicType

str()[source]
class nltk.sem.logic.AnyType[source]

Bases: nltk.sem.logic.BasicType, nltk.sem.logic.ComplexType

__init__()[source]
property first
property second
matches(other)[source]
resolve(other)[source]
str()[source]
nltk.sem.logic.read_type(type_string)[source]
exception nltk.sem.logic.TypeException[source]

Bases: Exception

__init__(msg)[source]
exception nltk.sem.logic.InconsistentTypeHierarchyException[source]

Bases: nltk.sem.logic.TypeException

__init__(variable, expression=None)[source]
exception nltk.sem.logic.TypeResolutionException[source]

Bases: nltk.sem.logic.TypeException

__init__(expression, other_type)[source]
exception nltk.sem.logic.IllegalTypeException[source]

Bases: nltk.sem.logic.TypeException

__init__(expression, other_type, allowed_type)[source]
nltk.sem.logic.typecheck(expressions, signature=None)[source]

Ensure correct typing across a collection of Expression objects. :param expressions: a collection of expressions :param signature: dict that maps variable names to types (or string representations of types)

class nltk.sem.logic.SubstituteBindingsI[source]

Bases: object

An interface for classes that can perform substitutions for variables.

substitute_bindings(bindings)[source]
Returns

The object that is obtained by replacing each variable bound by bindings with its values. Aliases are already resolved. (maybe?)

Return type

(any)

variables()[source]
Returns

A list of all variables in this object.

class nltk.sem.logic.Expression[source]

Bases: nltk.sem.logic.SubstituteBindingsI

This is the base abstract object for all logical expressions

classmethod fromstring(s, type_check=False, signature=None)[source]
applyto(other)[source]
negate()[source]

If this is a negated expression, remove the negation. Otherwise add a negation.

equiv(other, prover=None)[source]

Check for logical equivalence. Pass the expression (self <-> other) to the theorem prover. If the prover says it is valid, then the self and other are equal.

Parameters
  • other – an Expression to check equality against

  • prover – a nltk.inference.api.Prover

substitute_bindings(bindings)[source]
Returns

The object that is obtained by replacing each variable bound by bindings with its values. Aliases are already resolved. (maybe?)

Return type

(any)

typecheck(signature=None)[source]

Infer and check types. Raise exceptions if necessary.

Parameters

signature – dict that maps variable names to types (or string representations of types)

Returns

the signature, plus any additional type mappings

findtype(variable)[source]

Find the type of the given variable as it is used in this expression. For example, finding the type of “P” in “P(x) & Q(x,y)” yields “<e,t>”

Parameters

variable – Variable

replace(variable, expression, replace_bound=False, alpha_convert=True)[source]

Replace every instance of ‘variable’ with ‘expression’ :param variable: Variable The variable to replace :param expression: Expression The expression with which to replace it :param replace_bound: bool Should bound variables be replaced? :param alpha_convert: bool Alpha convert automatically to avoid name clashes?

normalize(newvars=None)[source]

Rename auto-generated unique variables

visit(function, combinator)[source]

Recursively visit subexpressions. Apply ‘function’ to each subexpression and pass the result of each function application to the ‘combinator’ for aggregation:

return combinator(map(function, self.subexpressions))

Bound variables are neither applied upon by the function nor given to the combinator. :param function: Function<Expression,T> to call on each subexpression :param combinator: Function<list<T>,R> to combine the results of the function calls :return: result of combination R

visit_structured(function, combinator)[source]

Recursively visit subexpressions. Apply ‘function’ to each subexpression and pass the result of each function application to the ‘combinator’ for aggregation. The combinator must have the same signature as the constructor. The function is not applied to bound variables, but they are passed to the combinator. :param function: Function to call on each subexpression :param combinator: Function with the same signature as the constructor, to combine the results of the function calls :return: result of combination

variables()[source]

Return a set of all the variables for binding substitution. The variables returned include all free (non-bound) individual variables and any variable starting with ‘?’ or ‘@’. :return: set of Variable objects

free()[source]

Return a set of all the free (non-bound) variables. This includes both individual and predicate variables, but not constants. :return: set of Variable objects

constants()[source]

Return a set of individual constants (non-predicates). :return: set of Variable objects

predicates()[source]

Return a set of predicates (constants, not variables). :return: set of Variable objects

simplify()[source]
Returns

beta-converted version of this expression

make_VariableExpression(variable)[source]
class nltk.sem.logic.ApplicationExpression[source]

Bases: nltk.sem.logic.Expression

This class is used to represent two related types of logical expressions.

The first is a Predicate Expression, such as “P(x,y)”. A predicate expression is comprised of a FunctionVariableExpression or ConstantExpression as the predicate and a list of Expressions as the arguments.

The second is a an application of one expression to another, such as “(x.dog(x))(fido)”.

The reason Predicate Expressions are treated as Application Expressions is that the Variable Expression predicate of the expression may be replaced with another Expression, such as a LambdaExpression, which would mean that the Predicate should be thought of as being applied to the arguments.

The logical expression reader will always curry arguments in a application expression. So, “x y.see(x,y)(john,mary)” will be represented internally as “((x y.(see(x))(y))(john))(mary)”. This simplifies the internals since there will always be exactly one argument in an application.

The str() method will usually print the curried forms of application expressions. The one exception is when the the application expression is really a predicate expression (ie, underlying function is an AbstractVariableExpression). This means that the example from above will be returned as “(x y.see(x,y)(john))(mary)”.

__init__(function, argument)[source]
Parameters
  • functionExpression, for the function expression

  • argumentExpression, for the argument

simplify()[source]
Returns

beta-converted version of this expression

property type
findtype(variable)[source]

:see Expression.findtype()

constants()[source]
See

Expression.constants()

predicates()[source]
See

Expression.predicates()

visit(function, combinator)[source]
See

Expression.visit()

uncurry()[source]

Uncurry this application expression

return: A tuple (base-function, arg-list)

property pred

Return uncurried base-function. If this is an atom, then the result will be a variable expression. Otherwise, it will be a lambda expression.

property args

Return uncurried arg-list

is_atom()[source]

Is this expression an atom (as opposed to a lambda expression applied to a term)?

class nltk.sem.logic.AbstractVariableExpression[source]

Bases: nltk.sem.logic.Expression

This class represents a variable to be used as a predicate or entity

__init__(variable)[source]
Parameters

variableVariable, for the variable

simplify()[source]
Returns

beta-converted version of this expression

replace(variable, expression, replace_bound=False, alpha_convert=True)[source]
See

Expression.replace()

findtype(variable)[source]

:see Expression.findtype()

predicates()[source]
See

Expression.predicates()

class nltk.sem.logic.IndividualVariableExpression[source]

Bases: nltk.sem.logic.AbstractVariableExpression

This class represents variables that take the form of a single lowercase character (other than ‘e’) followed by zero or more digits.

property type
free()[source]
See

Expression.free()

constants()[source]
See

Expression.constants()

class nltk.sem.logic.FunctionVariableExpression[source]

Bases: nltk.sem.logic.AbstractVariableExpression

This class represents variables that take the form of a single uppercase character followed by zero or more digits.

type = ?
free()[source]
See

Expression.free()

constants()[source]
See

Expression.constants()

class nltk.sem.logic.EventVariableExpression[source]

Bases: nltk.sem.logic.IndividualVariableExpression

This class represents variables that take the form of a single lowercase ‘e’ character followed by zero or more digits.

type = v
class nltk.sem.logic.ConstantExpression[source]

Bases: nltk.sem.logic.AbstractVariableExpression

This class represents variables that do not take the form of a single character followed by zero or more digits.

type = e
free()[source]
See

Expression.free()

constants()[source]
See

Expression.constants()

nltk.sem.logic.VariableExpression(variable)[source]

This is a factory method that instantiates and returns a subtype of AbstractVariableExpression appropriate for the given variable.

class nltk.sem.logic.VariableBinderExpression[source]

Bases: nltk.sem.logic.Expression

This an abstract class for any Expression that binds a variable in an Expression. This includes LambdaExpressions and Quantified Expressions

__init__(variable, term)[source]
Parameters
  • variableVariable, for the variable

  • termExpression, for the term

replace(variable, expression, replace_bound=False, alpha_convert=True)[source]
See

Expression.replace()

alpha_convert(newvar)[source]

Rename all occurrences of the variable introduced by this variable binder in the expression to newvar. :param newvar: Variable, for the new variable

free()[source]
See

Expression.free()

findtype(variable)[source]

:see Expression.findtype()

visit(function, combinator)[source]
See

Expression.visit()

visit_structured(function, combinator)[source]
See

Expression.visit_structured()

class nltk.sem.logic.LambdaExpression[source]

Bases: nltk.sem.logic.VariableBinderExpression

property type
class nltk.sem.logic.QuantifiedExpression[source]

Bases: nltk.sem.logic.VariableBinderExpression

property type
class nltk.sem.logic.ExistsExpression[source]

Bases: nltk.sem.logic.QuantifiedExpression

getQuantifier()[source]
class nltk.sem.logic.AllExpression[source]

Bases: nltk.sem.logic.QuantifiedExpression

getQuantifier()[source]
class nltk.sem.logic.NegatedExpression[source]

Bases: nltk.sem.logic.Expression

__init__(term)[source]
property type
findtype(variable)[source]

Find the type of the given variable as it is used in this expression. For example, finding the type of “P” in “P(x) & Q(x,y)” yields “<e,t>”

Parameters

variable – Variable

visit(function, combinator)[source]
See

Expression.visit()

negate()[source]
See

Expression.negate()

class nltk.sem.logic.BinaryExpression[source]

Bases: nltk.sem.logic.Expression

__init__(first, second)[source]
property type
findtype(variable)[source]

:see Expression.findtype()

visit(function, combinator)[source]
See

Expression.visit()

class nltk.sem.logic.BooleanExpression[source]

Bases: nltk.sem.logic.BinaryExpression

class nltk.sem.logic.AndExpression[source]

Bases: nltk.sem.logic.BooleanExpression

This class represents conjunctions

getOp()[source]
class nltk.sem.logic.OrExpression[source]

Bases: nltk.sem.logic.BooleanExpression

This class represents disjunctions

getOp()[source]
class nltk.sem.logic.ImpExpression[source]

Bases: nltk.sem.logic.BooleanExpression

This class represents implications

getOp()[source]
class nltk.sem.logic.IffExpression[source]

Bases: nltk.sem.logic.BooleanExpression

This class represents biconditionals

getOp()[source]
class nltk.sem.logic.EqualityExpression[source]

Bases: nltk.sem.logic.BinaryExpression

This class represents equality expressions like “(x = y)”.

getOp()[source]
exception nltk.sem.logic.LogicalExpressionException[source]

Bases: Exception

__init__(index, message)[source]
exception nltk.sem.logic.UnexpectedTokenException[source]

Bases: nltk.sem.logic.LogicalExpressionException

__init__(index, unexpected=None, expected=None, message=None)[source]
exception nltk.sem.logic.ExpectedMoreTokensException[source]

Bases: nltk.sem.logic.LogicalExpressionException

__init__(index, message=None)[source]
nltk.sem.logic.is_indvar(expr)[source]

An individual variable must be a single lowercase character other than ‘e’, followed by zero or more digits.

Parameters

expr – str

Returns

bool True if expr is of the correct form

nltk.sem.logic.is_funcvar(expr)[source]

A function variable must be a single uppercase character followed by zero or more digits.

Parameters

expr – str

Returns

bool True if expr is of the correct form

nltk.sem.logic.is_eventvar(expr)[source]

An event variable must be a single lowercase ‘e’ character followed by zero or more digits.

Parameters

expr – str

Returns

bool True if expr is of the correct form

nltk.sem.logic.demo()[source]
nltk.sem.logic.demo_errors()[source]
nltk.sem.logic.demoException(s)[source]
nltk.sem.logic.printtype(ex)[source]