PyReason

repository·main·Indexed 43 days ago

https://github.com/lab-v2/pyreason

An explainable inference tool for neuro-symbolic reasoning over graph structures using logical rules and facts. It supports annotated, real-valued, graph-based, and temporal logic under an open-world assumption. PyReason integrates with NetworkX for knowledge base representation and provides a Python library for defining rules, adding facts, and executing reasoning engines.

Tokens
34.1K
Snippets
107
Records
136
Agent score
56%

What's inside PyReason

  1. Overview of PyReason

    main

    PyReason is an explainable inference software designed to reason over graph structures using a set of logical rules and facts (initial conditions). It supports:

    • Annotated logic
    • Real-valued logic
    • Graph-based logic
    • Temporal logic
  2. What is PyReason and when to use it

    main

    PyReason is a Python-based framework for open-world temporal logic reasoning using generalized annotated logic. It is designed for neuro-symbolic reasoning tasks that require differentiable logics and temporal extensions.

    Use PyReason when you need to:

    • Perform reasoning over graphical structures (Knowledge Graphs, social networks, biological networks).
    • Implement temporal logic (e.g., rules like "if A, then B after $n$ time steps").
    • Handle incomplete information using an Open World assumption (where unknowns are treated as valid states rather than being assumed false).
    • Require fully explainable inference (the framework maintains a trace of all inference steps).
    • Work with annotated logic, including fuzzy logic and real-valued intervals.
  3. Introduction to PyReason

    main

    PyReason is an optimized Python tool designed for Reasoning over Graphs. It supports multiple logic systems, including:

    • Propositional Logic
    • First Order Logic
    • Annotated Logic

    It is intended for users performing complex reasoning tasks on graph-structured data.

  4. What is a Rule in PyReason

    main
    A Rule is a statement that establishes a relationship between premises (the body) and a conclusion (the head). If the premises in the body are true, the rule allows for the derivation of the conclusion in the head. The head determines what changes in the knowledge graph when the rule is triggered.
  5. How to integrate Machine Learning with logical reasoning

    main

    Integrating Machine Learning (ML) with PyReason follows a specific workflow that combines probabilistic predictions with symbolic logic:

    1. ML Inference: Run a model (e.g., PyTorch) to get class probabilities for specific events (like a transaction).
    2. Fact Conversion: Use LogicIntegratedClassifier to convert these probabilities into logical facts (e.g., fraud_detector(fraud)) based on a defined threshold and snap_value.
    3. Knowledge Graph Construction: Load a graph (e.g., via networkx) containing entities and their relationships (e.g., associated(AccountA, AccountB)) using pr.load_graph(G).
    4. Rule Definition: Define logical rules that use the ML-generated facts as predicates. For example, a rule can state that if an ML model predicts fraud AND a certain context exists, then an entity requires_investigation.
    5. Reasoning: Execute pr.reason() to propagate these findings through the graph.

    Note: To use facts generated directly from ML models in your rules, you must set pr.settings.allow_ground_rules = True before calling pr.reason().

    # Example workflow snippet
    pr.add_fact(pr.Fact("suspicious_location(AccountA)", "transaction_fact"))
    
    # Rule using ML fact 'fraud_detector(fraud)'
    pr.add_rule(pr.Rule("requires_investigation(acc) <- account(acc), fraud_detector(fraud), suspicious_location(acc)", "investigation_rule"))
    
    # Enable ground rules to allow ML facts in rules
    pr.settings.allow_ground_rules = True
    interpretation = pr.reason()
  6. How custom thresholds work in rules

    main

    When adding a rule to PyReason, custom_thresholds allow you to enforce quantitative requirements on the clauses in the rule's body.

    In a rule like ViewedByAll(y) <- HaveAccess(x,y), Viewed(x), if you provide two thresholds, PyReason maps them to the clauses in the body sequentially:

    1. The first threshold applies to the first clause (HaveAccess(x,y)).
    2. The second threshold applies to the second clause (Viewed(x)).

    This allows for complex logic, such as requiring that at least one person has access AND that 100% of those with access have viewed the item before the head (ViewedByAll(y)) is satisfied.

    import pyreason as pr
    
    # Example rule with thresholds applied to body clauses
    pr.add_rule(
        pr.Rule(
            "ViewedByAll(y) <- HaveAccess(x,y), Viewed(x)",
            "viewed_by_all_rule",
            custom_thresholds=user_defined_thresholds,
        )
    )
  7. Understand the structure of PyReason Interpretations output

    main

    The output of a PyReason reasoning process is structured as a dictionary of Interpretations. Each interpretation is indexed by an integer (representing the step or version of the reasoning) and contains a mapping of entities and relationships to their associated values.

    Key Components of an Interpretation:

    1. Entities: Single keys (e.g., 'Car_0', 'customer_1', 'Pet_2') represent the state or properties of specific objects. If the value is an empty dictionary {}, it typically indicates the entity exists in that interpretation without additional specific attribute values assigned in that step.
    2. Relationships (Tuples): Keys formatted as tuples (e.g., ('customer_0', 'customer_1')) represent relationships between two entities. The value associated with these tuples is a dictionary of relationship types and their corresponding values (e.g., {'same_color_car': (1.0, 1.0)}).
    3. Attribute Values: Values are often represented as tuples, such as (1.0, 1.0), which typically correspond to probability/confidence and weight/strength in the reasoning engine.
    4. Multi-step Reasoning: The top-level dictionary keys (0, 1, 2, etc.) allow you to track how the state of the world and the relationships between entities evolve over successive reasoning steps.
    Interpretations:
    {
        0: {
            'Car_0': {},
            'customer_0': {},
            ('customer_0', 'customer_1'): {'same_color_car': (1.0, 1.0)},
            ... 
        },
        1: {
            'customer_3': {'cool_pet': (1.0, 1.0)},
            'customer_4': {'cool_car': (1.0, 1.0), 'trendy': (1.0, 1.0)},
            ... 
        }
    }
  8. How graphs work in PyReason

    main
    PyReason reasons over knowledge graphs, which serve as a knowledge base. Graphs contain initial conditions assigned to nodes and edges. These initial conditions are used in conjunction with PyReason rules to infer new relations or attributes. Once a graph is loaded, its attributes are converted into static facts that do not change over time (unless specified otherwise in PyReason settings).