fuzzy_dl_owl2.fuzzydl.parser.dl_parser_fast

Faster drop-in replacement for fuzzy_dl_owl2.fuzzydl.parser.dl_parser.DLParser.

It uses a hand-rolled tokenizer plus a deterministic recursive-descent parser. The grammar accepted is identical to the legacy parser. All semantic actions are reused: this module imports the DLParser class from dl_parser_clean and invokes every _parse_* callback with a plain token list so the knowledge base / queries are populated exactly the same way.

The file is written so that it can be compiled with Cython using setup_dl_parser.py for an additional native-code speedup. When run as plain Python it still parses 5-10x faster than the legacy parser because backtracking, packrat caching and the bounded-recursion machinery are gone.

A high-performance recursive-descent parser that acts as a drop-in replacement for the legacy FuzzyDL parser by reusing semantic actions while eliminating backtracking and caching overhead.

Description

Designed as a high-speed alternative to the original implementation, this software employs a hand-rolled tokenizer combined with a deterministic recursive-descent strategy to process FuzzyDL syntax. Instead of reimplementing the logic for building the knowledge base, it imports the legacy DLParser class and invokes its semantic action callbacks with pre-processed token lists, ensuring identical behavior while drastically reducing computational overhead. The architecture eliminates the need for backtracking, packrat caching, and complex recursion limits found in the older version, resulting in a significant performance increase even when run as standard Python code. To handle large inputs efficiently, the implementation supports streaming the source text in bounded chunks, which keeps memory usage proportional to the chunk size rather than the total file size. Additionally, the code is structured to allow compilation with Cython for native-code execution, further accelerating the parsing of complex fuzzy description logic ontologies.

Attributes

_APPROX_KW

_AXIOM_KW

_CMP_KW

_CONCEPT_OP_AND_OR_IMPL

_FEATURE_TYPE_KW

_FUZZY_NUMBER_OP_BIN

_FUZZY_NUMBER_OP_PAIR

_K

_OWA_INTEGRAL_KW

_QUERY_KW

_SHOW_KW

_STATEMENT_KW

_WEIGHTED_KW

Classes

DLParserFast

Drop-in replacement for DLParser using the hand-rolled parser.

_KW

Namespace of every FuzzyDLKeyword token literal used in dispatch.

_Parser

Single-pass recursive descent over a pre-lexed token stream.

Functions

_kn(→ str)

Returns the source-text literal (spelling) that a given FuzzyDLKeyword matches in input.

Module Contents

UML Class Diagram for DLParserFast

UML Class Diagram for DLParserFast

class DLParserFast

Bases: object

Drop-in replacement for DLParser using the hand-rolled parser.

Public API is intentionally identical: get_kb(), main(), parse_string(), parse_string_opt(), load_config(). The knowledge-base / queries-list class attributes live on DLParser so parse-action callbacks (which still reference DLParser.kb directly) continue to work without modification.

static _parse_chunk(text: str) None

Tokenizes the given text and parses every top-level form it contains. The token list is local, so it is reclaimed as soon as this returns — bounding peak token memory to one chunk when called by the streaming path above.

Parameters:

text (str) – A chunk of fuzzy-DL source text to tokenize and parse.

static get_kb(
file_path: str,
**kwargs: Any,
) Tuple[fuzzy_dl_owl2.fuzzydl.knowledge_base.KnowledgeBase, List[fuzzy_dl_owl2.fuzzydl.query.query.Query]]

Parses a fuzzy-DL file and returns the populated knowledge base together with the list of parsed queries. This is the fast-parser mirror of DLParser.get_kb() so callers can swap implementations without changing their call site.

Parameters:
  • file_path (str) – Path to the fuzzy-DL source file.

  • kwargs (Any) – Configuration overrides forwarded to load_config().

Raises:

FuzzyOntologyException – if parsing fails or the file is not found.

Returns:

The parsed knowledge base and the list of queries.

Return type:

Tuple[KnowledgeBase, List[Query]]

static load_config(**kwargs: Any) None

Loads reasoner/parser configuration by delegating to DLParser.load_config(), so the fast parser shares the exact same configuration handling as the legacy one. Any keyword overrides are forwarded unchanged; the call updates global configuration state and returns nothing.

Parameters:

kwargs (Any) – Configuration overrides forwarded to DLParser.load_config().

static main(
file_path: str,
**kwargs: Any,
) dict[fuzzy_dl_owl2.fuzzydl.query.query.Query, fuzzy_dl_owl2.fuzzydl.milp.solution.Solution]

Runs the full fast-parser pipeline for a fuzzy-DL file: it parses the file into a knowledge base, solves the TBox, and answers every parsed query, collecting the per-query solutions into a dictionary. all-instances queries short-circuit to an informational message when the KB has no individuals. The cyclic garbage collector is disabled for the duration (and restored afterwards) since the run builds a large acyclic object graph that would otherwise be scanned repeatedly; an inconsistent ontology is reported as the answer 1.0 rather than propagated.

Parameters:
  • file_path (str) – Path to the fuzzy-DL source file to run.

  • kwargs (Any) – Configuration overrides forwarded to get_kb().

Returns:

A mapping from each parsed query to its computed solution.

Return type:

dict[Query, Solution]

static parse_string(instring: str) None

Parses a complete fuzzy-DL source string. The constructed knowledge base and queries are accumulated as side effects in DLParser.kb and DLParser.queries_list; the method itself returns nothing.

Small sources are tokenized and parsed in a single pass. Sources above _STREAM_THRESHOLD are streamed form-by-form in bounded chunks so the live token set stays proportional to one chunk rather than the whole file; the resulting knowledge base is identical either way.

Parameters:

instring (str) – The fuzzy-DL source text to parse.

static parse_string_opt(filename: str) None

Parses an entire fuzzy-DL file using the fastest available path. When the compiled re2c/flex backend is present, the file is mmap-ed and tokenized in C and parsed form-by-form so peak token memory stays bounded even for large inputs (timing is logged per chunk). Otherwise it falls back to reading the whole file into a string and delegating to parse_string(). Parsing populates the shared knowledge base as a side effect and returns nothing.

Parameters:

filename (str) – Path to the fuzzy-DL source file to parse.

UML Class Diagram for _KW

UML Class Diagram for _KW

class _KW

Namespace of every FuzzyDLKeyword token literal used in dispatch.

ALL_INSTANCES_QUERY
BINARY
BNP_QUERY
CONSTRAINTS
CRISP_CONCEPT
CRISP_ROLE
DEFINE_CONCEPT
DEFINE_FUZZY_CONCEPT
DEFINE_FUZZY_EQUIVALENCE
DEFINE_FUZZY_LOGIC
DEFINE_FUZZY_NUMBER
DEFINE_FUZZY_NUMBER_RANGE
DEFINE_FUZZY_SIMILARITY
DEFINE_MODIFIER
DEFINE_PRIMITIVE_CONCEPT
DEFINE_TRUTH_CONSTANT
DEFUZZIFY_LOM_QUERY
DEFUZZIFY_MOM_QUERY
DEFUZZIFY_SOM_QUERY
DISJOINT
DISJOINT_UNION
DOMAIN
EQ
EQUIVALENT_CONCEPTS
FREE
FUNCTIONAL
GE
GOEDEL_IMPLIES
HAS_VALUE
IMPLIES
IMPLIES_ROLE
INSTANCE
INVERSE
INVERSE_FUNCTIONAL
KLEENE_DIENES_IMPLIES
LE
LUKASIEWICZ_IMPLIES
MAX_G_SUBS_QUERY
MAX_INSTANCE_QUERY
MAX_KD_SUBS_QUERY
MAX_L_SUBS_QUERY
MAX_SAT_QUERY
MAX_SUBS_QUERY
MAX_VAR_QUERY
MIN_G_SUBS_QUERY
MIN_INSTANCE_QUERY
MIN_KD_SUBS_QUERY
MIN_L_SUBS_QUERY
MIN_SAT_QUERY
MIN_SUBS_QUERY
MIN_VAR_QUERY
MUL
NOT
Q_OWA
RANGE
REFLEXIVE
RELATED
SAT_QUERY
SELF
SHOW_ABSTRACT_FILLERS
SHOW_ABSTRACT_FILLERS_FOR
SHOW_CONCEPTS
SHOW_CONCRETE_FILLERS
SHOW_CONCRETE_FILLERS_FOR
SHOW_CONCRETE_INSTANCE_FOR
SHOW_INSTANCES
SHOW_LANGUAGE
SHOW_VARIABLES
SIGMA_COUNT
SOME
SUB
SUM
SYMMETRIC
TRANSITIVE
ZADEH_IMPLIES
UML Class Diagram for _Parser

UML Class Diagram for _Parser

class _Parser(tokens: List[fuzzy_dl_owl2.fuzzydl.parser.tokenizer.tokenizer_handler.Token])

Bases: object

Single-pass recursive descent over a pre-lexed token stream.

Every parse_* method mirrors one non-terminal of the original grammar. There is no backtracking: once a method commits to a branch it consumes tokens greedily. This is safe because the fuzzy-DL grammar is LL(1) at the top level and the tokenizer has already disambiguated numbers, identifiers and punctuation.

_advance() fuzzy_dl_owl2.fuzzydl.parser.tokenizer.tokenizer_handler.Token

Consumes the current token and advances the cursor by one. The token at the old position is returned, so callers can read and step in a single call.

Returns:

The token that was at the cursor before advancing.

Return type:

Token

_eat(kind: int) bool

Conditionally consumes the current token if it matches the given type code. Unlike _expect(), a mismatch is not an error: the cursor is advanced and True returned only on a match, otherwise the cursor stays put and False is returned.

Parameters:

kind (int) – The token type code to consume if present.

Returns:

True if a matching token was consumed, False otherwise.

Return type:

bool

_expect(kind: int) fuzzy_dl_owl2.fuzzydl.parser.tokenizer.tokenizer_handler.Token

Requires the current token to have the given type code, consuming and returning it on a match. If the token’s kind does not match, a FuzzyOntologyException is raised with the byte offset and the offending token, and the cursor is left unmoved.

Parameters:

kind (int) – The expected token type code.

Raises:

FuzzyOntologyException – if the current token is not of the expected kind.

Returns:

The consumed token of the expected kind.

Return type:

Token

_parse_weighted_part_inline() Any

Parses an inline weighted part, matching the grammar rule weighted_part ::= "(" number concept ")". The weight and concept are consumed and forwarded as a flat list.

Returns:

The parsed weighted part.

Return type:

Any

_peek(offset: int = 0) fuzzy_dl_owl2.fuzzydl.parser.tokenizer.tokenizer_handler.Token

Returns the token at pos + offset without advancing the cursor. Lookahead past the end of the stream is clamped to the last token (the EOF sentinel), so callers can peek freely without bounds checks.

Parameters:

offset (int) – How many tokens ahead of the current position to look.

Returns:

The token at the requested position, or the final token if out of range.

Return type:

Token

parse_approx_concept() Any

Parses an approximation concept, matching the grammar rule approx_concept ::= "(" approx_op role concept ")". The approximation operator, role, and inner concept are consumed and forwarded as a flat list.

Returns:

The parsed approximation concept.

Return type:

Any

parse_axioms() None

Parses an axiom, matching the grammar rule covering instance assertions, role assertions, implications, concept definitions, equivalent concepts, disjoint unions, range/domain declarations, role characteristics, and inverse role declarations. The keyword after ( selects the branch; the branch-specific tokens are consumed and forwarded as a flat list to DLParser._parse_axioms.

Raises:

FuzzyOntologyException – if the axiom keyword is unrecognised.

parse_concept() Any
concept ::=

variable

“top” | “bottom”
“(” datatype_restriction “)”
“(” number concept “)” – weighted part
“(” “[” (“<=” | “>=”) number|variable “]” concept “)”
“(” binary_connective concept+ “)”
“(” “some” role (concept | variable) “)”
“(” “has-value” role individual “)”
“(” approx_op role concept “)”
“(” “not” concept “)”
“(” “self” variable “)”
“(” weighted_op weighted_part+ “)”
“(” “q-owa” variable concept+ “)”
“(” owa_integral_op “(” number+ “)” “(” concept+ “)” “)”
“(” “sigma-count” role concept “{” individual* “}” fuzzy_name “)”
“(” modifier_name concept “)”

Dispatches on the leading token (a bare identifier yields a variable / top / bottom; otherwise the keyword after ( selects the concept sub-parser) and consumes the whole concept form.

Raises:

FuzzyOntologyException – if the tokens do not form a valid concept.

Returns:

The parsed concept node.

Return type:

Any

parse_constraints() None

constraints ::= “(” “constraints”

( “(” (“binary” | “free”) variable “)” | “(” expression cmp_op number “)” )+

“)”

parse_crisp_declarations() None

crisp_declarations ::= “(” (“crisp-concept” | “crisp-role”) name+ “)”

parse_datatype_restriction() Any

Parses a datatype restriction, matching the grammar rule datatype_restriction ::= "(" cmp_op role (fuzzy_number_expr | datatype_restriction_function | variable) ")". The comparison operator, role, and third operand are consumed and forwarded as a flat list. Feature-type dispatch for STRING values lives in DLParser._parse_datatype_restriction so both fast and slow parsers share one source of truth.

Returns:

The parsed datatype restriction.

Return type:

Any

parse_datatype_restriction_function() Any

Parses a datatype restriction function, matching the grammar rule datatype_restriction_function ::= datatype_restriction_operand ( "+" datatype_restriction_operand )*. The first operand is parsed, then a chain of +-separated operands is consumed if present. The flat operand list is forwarded to the callback.

Returns:

The parsed restriction function.

Return type:

Any

parse_datatype_restriction_function_or_fuzzy_number() Any

Parses a datatype-restriction function or a fuzzy number expression, disambiguating by lookahead. Uses 1-token lookahead on the token after ( to decide among:

  • (f+ ...) / (f- ...) / (f* ...) / (f/ ...) → fuzzy number expression

  • (num num num) → simple triangular fuzzy number

  • (num [*] fn) or (fn - fn) → datatype restriction function

Returns:

The parsed restriction function or fuzzy number expression.

Return type:

Any

parse_datatype_restriction_operand() Any

Parses a datatype restriction operand, matching the grammar rule datatype_restriction_operand ::= number | variable | "(" number ["*"] datatype_restriction_function ")" | "(" datatype_restriction_function ("-"|"+") datatype_restriction_function ")". Disambiguation is done by 1-token lookahead after the opening parenthesis.

Returns:

The parsed restriction operand.

Return type:

Any

parse_degree() Any

Parses a degree, matching the grammar rule degree ::= number | expression | variable. A number becomes a numeric degree, a parenthesised expression is parsed as a degree expression, and a bare variable becomes a variable degree.

Returns:

The parsed degree.

Return type:

Any

parse_expression() Any

Parses a linear expression, matching the grammar rule expression ::= term ( "+" term )*. One or more terms separated by + are consumed and forwarded as a flat list with explicit + separators inserted.

Returns:

The parsed expression.

Return type:

Any

parse_features() None

features ::= “(” “range” variable type_kw number* “)”

parse_fuzzy_concept() None

fuzzy_concept ::= “(” “define-fuzzy-concept” name shape “(” (number|variable)* “)” “)”

parse_fuzzy_equivalence() None

fuzzy_equivalence ::= “(” “define-fuzzy-equivalence” name “)”

parse_fuzzy_logic() None

fuzzy_logic ::= “(” “define-fuzzy-logic” logic_name “)”

parse_fuzzy_number_def() None

fuzzy_number_def ::= “(” “define-fuzzy-number” name (fuzzy_number_expr | simple_fuzzy_number) “)”

parse_fuzzy_number_expr() Any

Parses a fuzzy number expression, matching the grammar rule fuzzy_number_expr ::= simple_fuzzy_number | "(" ("f+"|"f*") fuzzy_number_expr+ ")" | "(" ("f-"|"f/") fuzzy_number_expr fuzzy_number_expr ")". Compound forms (f+, f*, f-, f/) are returned as raw flat lists [op, *operands] for the consuming callback to handle.

Raises:

FuzzyOntologyException – if a compound form is malformed (e.g. f+/f* with fewer than one operand or an unknown operator).

Returns:

The parsed fuzzy number expression.

Return type:

Any

parse_fuzzy_range() None

fuzzy_range ::= “(” “define-fuzzy-number-range” number number “)”

parse_fuzzy_similarity() None

fuzzy_similarity ::= “(” “define-fuzzy-similarity” name “)”

parse_gformula() Any

Parses a top-level gformula, matching the grammar rule gformula ::= statement | axiom | query | show_statement | concept. The first token must be (; the keyword (or number / bracket) immediately after ( is peeked and the stream is dispatched to the appropriate sub-parser. The consumed form is forwarded to the corresponding DLParser._parse_* callback.

Raises:

FuzzyOntologyException – if the first token is not ( or the inner keyword is unrecognised.

Returns:

The parsed result (concept, axiom, statement, etc.) forwarded from the sub-parser.

Return type:

Any

parse_has_value_concept() Any

Parses a value restriction concept, matching the grammar rule has_value_concept ::= "(" "has-value" role individual ")". The role and individual name are consumed and forwarded as a flat list.

Returns:

The parsed value restriction concept.

Return type:

Any

parse_implies_like_concept() Any

Parses a binary connective concept (AND, OR, IMPLIES variants), matching the grammar rule implies_like_concept ::= "(" op concept+ ")". The operator keyword and all operand concepts are consumed and forwarded as a flat list to DLParser._parse_binary_concept.

Returns:

The parsed binary connective concept.

Return type:

Any

parse_modifier() None

modifier ::= “(” “define-modifier” name modifier_kind “(” number* “)” “)”

parse_modifier_concept() Any

Parses a modifier application concept, matching the grammar rule modifier_concept ::= "(" modifier_name concept ")". The modifier name and inner concept are consumed and forwarded as a flat list.

Returns:

The parsed modified concept.

Return type:

Any

parse_number() int | float

Parses a numeric literal, matching the grammar rule number ::= [+-]? ( \d+ [ . \d* ] | . \d+ ) ( [eE] [+-]? \d+ )?. The current token must be a number; it is consumed and converted to an int or float via DLParser._to_number.

Raises:

FuzzyOntologyException – if the current token is not a numeric literal.

Returns:

The parsed numeric value.

Return type:

Union[int, float]

parse_owa_integral_concept() Any

Parses an OWA / Choquet / Sugeno / quasi-Sugeno integral concept, matching the grammar rule owa_integral_concept ::= "(" op "(" number+ ")" "(" concept+ ")" ")". The operator keyword, the parenthesised weight list, and the parenthesised concept list are consumed and forwarded as a single flat list (the callback locates the weights/concepts boundary via element types).

Returns:

The parsed OWA-integral concept.

Return type:

Any

parse_program() None

program ::= gformula*

parse_q_owa_concept() Any

Parses a quantifier-guided OWA concept, matching the grammar rule q_owa_concept ::= "(" "q-owa" variable concept+ ")". The quantifier variable and one or more operand concepts are consumed and forwarded as a flat list.

Returns:

The parsed quantifier-guided OWA concept.

Return type:

Any

parse_queries() None

Parses a query, matching the grammar rule covering all query types (all-instances, satisfiability, instance / subsumption / related / variable max/min, defuzzify, and BNP). The query keyword after ( selects the branch; branch-specific arguments are consumed and forwarded as a flat list to DLParser._parse_queries.

Raises:

FuzzyOntologyException – if the query keyword is unrecognised.

parse_show_statement() None

show_statement ::= “(” show_kw (concept | variable)* “)”

parse_sigma_count_concept() Any

Parses a sigma-count concept, matching the grammar rule sigma_count_concept ::= "(" "sigma-count" role concept "{" individual* "}" fuzzy_name ")". The role, concept, brace-enclosed individual list, and fuzzy name are consumed and forwarded as a flat list.

Returns:

The parsed sigma-count concept.

Return type:

Any

parse_simple_fuzzy_number() Any

Parses a simple fuzzy number literal, matching the grammar rule simple_fuzzy_number ::= "(" number number number ")" | number | variable. A parenthesised triple produces a triangular fuzzy number; a bare number or variable is wrapped as a scalar fuzzy number.

Raises:

FuzzyOntologyException – if a triangular literal does not contain exactly three numbers.

Returns:

The parsed fuzzy number literal.

Return type:

Any

parse_some_concept() Any

Parses an existential restriction concept, matching the grammar rule some_concept ::= "(" "some" role (concept | variable) ")". The role and second argument (either a nested concept or a bare variable) are consumed and forwarded as a flat list.

Returns:

The parsed existential restriction concept.

Return type:

Any

parse_term() Any

Parses a linear term, matching the grammar rule term ::= number | variable | "(" number "*" variable ")" | number "*" variable. Bare numbers, bare variables, and parenthesised or infix num * var forms are consumed and forwarded as a flat list.

Returns:

The parsed term.

Return type:

Any

parse_threshold_concept_wrapped() Any

Parses a threshold concept wrapper, matching the grammar rule threshold_concept_wrapped ::= "(" "[" ("<=" | ">=") number|variable "]" concept ")".

The tokenizer may merge the operator and its operand into a single identifier (e.g. >=0.4), so the method splits off the inline operator and operand before forwarding the pieces to the callback.

Raises:

FuzzyOntologyException – if a threshold operator is not found or the inline operand is malformed.

Returns:

The parsed threshold concept.

Return type:

Any

parse_truth_constants() None

truth_constants ::= “(” “define-truth-constant” name number “)”

parse_unary_concept() Any

Parses a unary concept (negation or self-restriction), matching the grammar rule unary_concept ::= "(" "not" concept ")" | "(" "self" variable ")". The keyword after the opening parenthesis selects which form to parse.

Returns:

The parsed unary concept.

Return type:

Any

parse_variable() str

Parses a variable, matching the grammar rule variable ::= identifier. The current token must be a bare identifier; it is consumed and its source text returned.

Raises:

FuzzyOntologyException – if the current token is not an identifier.

Returns:

The variable name.

Return type:

str

parse_weighted_concept() Any

Parses a weighted aggregation concept, matching the grammar rule weighted_concept ::= "(" ("w-sum-zero"|"w-sum"|"w-max"|"w-min") weighted_part+ ")". The operator keyword and one or more weighted parts are consumed and forwarded as a flat list.

Returns:

The parsed weighted aggregation concept.

Return type:

Any

parse_weighted_concept_part() Any

Parses a weighted concept part, matching the grammar rule weighted_concept_part ::= "(" number concept ")". The three inner elements are consumed and forwarded to the callback as a flat list.

Returns:

The parsed weighted concept part.

Return type:

Any

__slots__ = ('tokens', 'pos', 'n')
n
pos = 0
tokens
_kn(k: fuzzy_dl_owl2.fuzzydl.util.constants.FuzzyDLKeyword) str

Returns the source-text literal (spelling) that a given FuzzyDLKeyword matches in input.

Parameters:

k (FuzzyDLKeyword) – The keyword whose literal spelling is needed.

Returns:

The keyword’s source-text literal.

Return type:

str

_APPROX_KW
_AXIOM_KW
_CMP_KW
_CONCEPT_OP_AND_OR_IMPL
_FEATURE_TYPE_KW
_FUZZY_NUMBER_OP_BIN
_FUZZY_NUMBER_OP_PAIR
_K
_OWA_INTEGRAL_KW
_QUERY_KW
_SHOW_KW
_STATEMENT_KW
_WEIGHTED_KW