nltk.sem.logic module

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

class nltk.sem.logic.AbstractVariableExpression[source]

Bases: Expression

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

__init__(variable)[source]
Parameters

variableVariable, for the variable

findtype(variable)[source]

:see Expression.findtype()

predicates()[source]
See

Expression.predicates()

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

Expression.replace()

simplify()[source]
Returns

beta-converted version of this expression

class nltk.sem.logic.AllExpression[source]

Bases: QuantifiedExpression

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

Bases: BooleanExpression

This class represents conjunctions

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

Bases: BasicType, ComplexType

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

Bases: 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

property args

Return uncurried arg-list

constants()[source]
See

Expression.constants()

findtype(variable)[source]

:see Expression.findtype()

is_atom()[source]

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

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.

predicates()[source]
See

Expression.predicates()

simplify()[source]
Returns

beta-converted version of this expression

property type
uncurry()[source]

Uncurry this application expression

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

visit(function, combinator)[source]
See

Expression.visit()

class nltk.sem.logic.BasicType[source]

Bases: Type

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

Bases: Expression

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

:see Expression.findtype()

property type
visit(function, combinator)[source]
See

Expression.visit()

class nltk.sem.logic.BooleanExpression[source]

Bases: BinaryExpression

class nltk.sem.logic.ComplexType[source]

Bases: Type

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

Bases: AbstractVariableExpression

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

constants()[source]
See

Expression.constants()

free()[source]
See

Expression.free()

type = e
class nltk.sem.logic.EntityType[source]

Bases: BasicType

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

Bases: BinaryExpression

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

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

Bases: BasicType

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

Bases: 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.ExistsExpression[source]

Bases: QuantifiedExpression

getQuantifier()[source]
exception nltk.sem.logic.ExpectedMoreTokensException[source]

Bases: LogicalExpressionException

__init__(index, message=None)[source]
class nltk.sem.logic.Expression[source]

Bases: SubstituteBindingsI

This is the base abstract object for all logical expressions

applyto(other)[source]
constants()[source]

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

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

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

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

classmethod fromstring(s, type_check=False, signature=None)[source]
make_VariableExpression(variable)[source]
negate()[source]

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

normalize(newvars=None)[source]

Rename auto-generated unique variables

predicates()[source]

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

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?

simplify()[source]
Returns

beta-converted version of this expression

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

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

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

class nltk.sem.logic.FunctionVariableExpression[source]

Bases: AbstractVariableExpression

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

constants()[source]
See

Expression.constants()

free()[source]
See

Expression.free()

type = ?
class nltk.sem.logic.IffExpression[source]

Bases: BooleanExpression

This class represents biconditionals

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

Bases: TypeException

__init__(expression, other_type, allowed_type)[source]
class nltk.sem.logic.ImpExpression[source]

Bases: BooleanExpression

This class represents implications

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

Bases: TypeException

__init__(variable, expression=None)[source]
class nltk.sem.logic.IndividualVariableExpression[source]

Bases: AbstractVariableExpression

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

constants()[source]
See

Expression.constants()

free()[source]
See

Expression.free()

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

Bases: QuantifiedExpression

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

Bases: VariableBinderExpression

property type
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?

assertNextToken(expected)[source]
assertToken(tok, expected)[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.

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.

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.

attempt_adjuncts(expression, context)[source]
get_BooleanExpression_factory(tok)[source]

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

get_QuantifiedExpression_factory(tok)[source]

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

get_all_symbols()[source]

This method exists to be overridden

get_next_token_variable(description)[source]
handle(tok, context)[source]

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

handle_lambda(tok, context)[source]
handle_negation(tok, context)[source]
handle_open(tok, context)[source]
handle_quant(tok, context)[source]
handle_variable(tok, context)[source]
has_priority(operation, context)[source]
inRange(location)[source]

Return TRUE if the given location is within the buffer

isvariable(tok)[source]
make_ApplicationExpression(function, argument)[source]
make_BooleanExpression(factory, first, second)[source]
make_EqualityExpression(first, second)[source]

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

make_LambdaExpression(variable, term)[source]
make_NegatedExpression(expression)[source]
make_QuanifiedExpression(factory, variable, term)[source]
make_VariableExpression(name)[source]
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_next_expression(context)[source]

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

process_quoted_token(data_idx, data)[source]
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.

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

exception nltk.sem.logic.LogicalExpressionException[source]

Bases: Exception

__init__(index, message)[source]
class nltk.sem.logic.NegatedExpression[source]

Bases: Expression

__init__(term)[source]
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

negate()[source]
See

Expression.negate()

property type
visit(function, combinator)[source]
See

Expression.visit()

class nltk.sem.logic.OrExpression[source]

Bases: BooleanExpression

This class represents disjunctions

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

Bases: VariableBinderExpression

property type
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.Tokens[source]

Bases: object

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

Bases: BasicType

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

Bases: object

classmethod fromstring(s)[source]
exception nltk.sem.logic.TypeException[source]

Bases: Exception

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

Bases: TypeException

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

Bases: LogicalExpressionException

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

Bases: object

__init__(name)[source]
Parameters

name – the name of the variable

substitute_bindings(bindings)[source]
class nltk.sem.logic.VariableBinderExpression[source]

Bases: 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

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

findtype(variable)[source]

:see Expression.findtype()

free()[source]
See

Expression.free()

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

Expression.replace()

visit(function, combinator)[source]
See

Expression.visit()

visit_structured(function, combinator)[source]
See

Expression.visit_structured()

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

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

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

Binding operators

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

Boolean operators

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

Equality predicates

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.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_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.printtype(ex)[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)

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

Return a skolem function over the variables in univ_scope param univ_scope

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)

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