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
- class nltk.sem.logic.AllExpression[source]¶
Bases:
QuantifiedExpression
- class nltk.sem.logic.AndExpression[source]¶
Bases:
BooleanExpression
This class represents conjunctions
- class nltk.sem.logic.AnyType[source]¶
Bases:
BasicType
,ComplexType
- property first¶
- property second¶
- 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
orConstantExpression
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
function –
Expression
, for the function expressionargument –
Expression
, for the argument
- property args¶
Return uncurried arg-list
- 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.
- property type¶
- class nltk.sem.logic.BinaryExpression[source]¶
Bases:
Expression
- property type¶
- class nltk.sem.logic.BooleanExpression[source]¶
Bases:
BinaryExpression
- 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.
- type = e¶
- class nltk.sem.logic.EqualityExpression[source]¶
Bases:
BinaryExpression
This class represents equality expressions like “(x = y)”.
- 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
- exception nltk.sem.logic.ExpectedMoreTokensException[source]¶
Bases:
LogicalExpressionException
- class nltk.sem.logic.Expression[source]¶
Bases:
SubstituteBindingsI
This is the base abstract object for all logical expressions
- 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 againstprover – 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
- 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?
- 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 combinationR
- 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.
- type = ?¶
- class nltk.sem.logic.IffExpression[source]¶
Bases:
BooleanExpression
This class represents biconditionals
- exception nltk.sem.logic.IllegalTypeException[source]¶
Bases:
TypeException
- class nltk.sem.logic.ImpExpression[source]¶
Bases:
BooleanExpression
This class represents implications
- exception nltk.sem.logic.InconsistentTypeHierarchyException[source]¶
Bases:
TypeException
- 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.
- property type¶
- class nltk.sem.logic.IotaExpression[source]¶
Bases:
QuantifiedExpression
- 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?
- 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.
- 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
- handle(tok, context)[source]¶
This method is intended to be overridden for logics that use different operators or expressions
- make_EqualityExpression(first, second)[source]¶
This method serves as a hook for other logic parsers that have different equality expression classes
- parse(data, signature=None)[source]¶
Parse the expression.
- Parameters
data – str for the input to be parsed
signature –
dict<str, str>
that maps variable names to type strings
- Returns
a parsed Expression
- process_next_expression(context)[source]¶
Parse the next complete expression from the stream and return it.
- 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
- class nltk.sem.logic.NegatedExpression[source]¶
Bases:
Expression
- 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
- property type¶
- class nltk.sem.logic.OrExpression[source]¶
Bases:
BooleanExpression
This class represents disjunctions
- 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.
- 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', '-', '!']¶
- exception nltk.sem.logic.TypeResolutionException[source]¶
Bases:
TypeException
- exception nltk.sem.logic.UnexpectedTokenException[source]¶
Bases:
LogicalExpressionException
- 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
variable –
Variable
, for the variableterm –
Expression
, 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
- 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.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.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.skolem_function(univ_scope=None)[source]¶
Return a skolem function over the variables in univ_scope param univ_scope