# vector-logic: A Lightweight Python Rules Engine
[](https://badge.fury.io/py/vector-logic)
[](https://pepy.tech/project/vector-logic)
[](https://github.com/dmitry-lesnik/vector-logic/actions/workflows/ci.yml)
[](https://opensource.org/licenses/MIT)
A fast, transparent, and extensible Python library for running inference on a generic system of logical rules.
This library is for developers who need a simple and powerful way to manage business logic without the overhead of more
complex systems like BDDs or SAT solvers. It provides an intuitive, algebraic approach to propositional logic, making it
easy to define rules, add evidence, and infer outcomes.
## Why Use vector-logic?
- **Expressive Rule Syntax:** Define complex rules with a natural, human-readable syntax (e.g. `(sky_is_grey &&
humidity_is_high) => it_will_rain`).
- **Powerful Inference:** Combine multiple rules and evidence into a single, consolidated knowledge base to make
predictions and check for contradictions.
- **State Analysis:** Query the state of any variable to determine if it is always true, always false, or can vary based
on the known rules.
- **Lightweight & Transparent:** A small, focused codebase with minimal dependencies, making it easy to understand,
extend, and integrate into any project.
## Installation
This project is managed with Poetry. It can be installed from PyPI:
```bash
pip install vector-logic
```
## Quick Start
There is a minimal example of defining rules and making a prediction.
```python
from vectorlogic import Engine
# 1. Define the variables for your system
variables = ["sky_is_grey", "humidity_is_high", "it_will_rain", "take_umbrella"]
# 2. Create an Engine instance
engine = Engine(variables=variables)
# 3. Add your logical rules
engine.add_rule("sky_is_grey && humidity_is_high => it_will_rain")
engine.add_rule("it_will_rain => take_umbrella")
# 4. Make a prediction based on new evidence
evidence = {"sky_is_grey": True, "humidity_is_high": True}
result = engine.predict(evidence)
# 5. Check the result
if result:
take_umbrella = result.get_value("take_umbrella")
print(f"Should I take an umbrella? Prediction: {take_umbrella}")
# Should I take an umbrella? Prediction: True
```
## Detailed Example
This example demonstrates more advanced features, including compiling the engine for faster repeated predictions.
```python
from vectorlogic import Engine
# 1. Define variables and create the engine
variables = ["x1", "x2", "x3", "x4"]
engine = Engine(variables=variables, name="My Logic Engine")
# 2. Add rules and initial evidence
engine.add_rule("x1 = (x2 && x3)")
engine.add_rule("x2 <= (!x3 || !x4)")
engine.add_evidence({"x4": False})
# 3. Compile the rules into a single 'valid set'
# (See the performance section below for when to use this)
engine.compile()
# 4. Inspect the compiled state
print("--- Compiled Valid Set ---")
engine.valid_set.print(indent=4)
# 5. Query the compiled knowledge base directly
x2_value = engine.get_variable_value("x2")
print(f"\nConsolidated value of 'x2' in the valid set: {x2_value}")
# 6. Run a fast prediction using the compiled engine
print("\n--- Prediction ---")
evidence = {"x1": False, "x2": True}
print(f"Predicting with evidence: {evidence}")
result = engine.predict(evidence)
if result:
x3_value = result.get_value("x3")
print(f"Inferred value of 'x3': {x3_value}")
else:
print("Evidence contradicts the knowledge base.")
```
## Performance: To Compile or Not to Compile?
The `vector-logic` engine offers two approaches for inference, and the best choice depends on your use case.
1. **Pre-compiling for Repeated Use** (`engine.compile()`)
- **What it does:** Multiplies all added rules together to create a single, optimised `StateVector` called the "valid
set".
- **When to use it:** When you need to run multiple predictions against the same set of rules.
- **Trade-off:** The initial compilation can be slow if the valid set is very large, but subsequent `predict()` calls
will
be extremely fast because they only need to multiply with this single, pre-computed valid set.
2. **On-the-Fly Prediction**
- **What it does:** Multiplies all rules from scratch every time you call `.predict()`, including the evidence for that
specific prediction.
- **When to use it:** When you need to run one or a few predictions.
- **Trade-off:** This can be faster for a single query because a restrictive piece of evidence can cause the
intermediate `StateVectors` to become very small, avoiding the creation of a potentially huge valid set.
> **A Note on Performance:** The efficiency of this algorithm relies on heuristic optimisations for the order of rule
> multiplication. This implementation includes a basic but effective heuristic that performs well for systems with up to
> ~100 variables and a similar number of rules. For more challenging tasks, performance can be improved by implementing
> more advanced optimisation heuristics.
## Installation from source
This project uses Poetry for dependency management.
1. Install Poetry:
Follow the instructions on the [official Poetry website](https://python-poetry.org/docs/#installation).
2. Clone the repository:
```bash
git clone https://github.com/dmitry-lesnik/vector-logic.git
cd vector-logic
```
3. Install dependencies:
```bash
poetry install
```
## Running Tests
To run the test suite, use pytest through Poetry:
```bash
poetry install --with dev
poetry run pytest
```
## Further Reading & Theoretical Foundations
The `vector-logic` library is a practical implementation of an algebraic approach to propositional logic called **State
Algebra**. If you're interested in the concepts behind the engine, these resources provide a great starting point:
* **Building a Rules Engine from First Principles**: A high-level, practical
explanation of the main building blocks of State Algebra. This TDS article is the best place to start for
understanding the core ideas: https://towardsdatascience.com/building-a-rules-engine-from-first-principles/
* **State Algebra for Propositional Logic**: For those who want a more formal and rigorous treatment, this paper on
arXiv offers a deep, theoretical dive into the mathematics of State Algebra: https://arxiv.org/abs/2509.10326
Raw data
{
"_id": null,
"home_page": "https://github.com/dmitry-lesnik/vector-logic",
"name": "vector-logic",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.9",
"maintainer_email": null,
"keywords": "rules-engine, rules, business-rules, logic, state-vector, state-algebra",
"author": "Dmitry Lesnik",
"author_email": "dmitry@stratyfy.com",
"download_url": "https://files.pythonhosted.org/packages/6d/c2/c5eec93439b3dc04da4dccd837f0d4dcaf8b5c6f9f247b83db7cae43b6ae/vector_logic-0.4.1.tar.gz",
"platform": null,
"description": "# vector-logic: A Lightweight Python Rules Engine\n\n[](https://badge.fury.io/py/vector-logic)\n[](https://pepy.tech/project/vector-logic)\n[](https://github.com/dmitry-lesnik/vector-logic/actions/workflows/ci.yml)\n[](https://opensource.org/licenses/MIT)\n\nA fast, transparent, and extensible Python library for running inference on a generic system of logical rules.\n\nThis library is for developers who need a simple and powerful way to manage business logic without the overhead of more\ncomplex systems like BDDs or SAT solvers. It provides an intuitive, algebraic approach to propositional logic, making it\neasy to define rules, add evidence, and infer outcomes.\n\n## Why Use vector-logic?\n\n- **Expressive Rule Syntax:** Define complex rules with a natural, human-readable syntax (e.g. `(sky_is_grey &&\n humidity_is_high) => it_will_rain`).\n\n- **Powerful Inference:** Combine multiple rules and evidence into a single, consolidated knowledge base to make\n predictions and check for contradictions.\n\n- **State Analysis:** Query the state of any variable to determine if it is always true, always false, or can vary based\n on the known rules.\n\n- **Lightweight & Transparent:** A small, focused codebase with minimal dependencies, making it easy to understand,\n extend, and integrate into any project.\n\n## Installation\n\nThis project is managed with Poetry. It can be installed from PyPI:\n\n```bash\n pip install vector-logic\n ```\n\n## Quick Start\n\nThere is a minimal example of defining rules and making a prediction.\n\n```python\nfrom vectorlogic import Engine\n\n# 1. Define the variables for your system\nvariables = [\"sky_is_grey\", \"humidity_is_high\", \"it_will_rain\", \"take_umbrella\"]\n\n# 2. Create an Engine instance\nengine = Engine(variables=variables)\n\n# 3. Add your logical rules\nengine.add_rule(\"sky_is_grey && humidity_is_high => it_will_rain\")\nengine.add_rule(\"it_will_rain => take_umbrella\")\n\n# 4. Make a prediction based on new evidence\nevidence = {\"sky_is_grey\": True, \"humidity_is_high\": True}\nresult = engine.predict(evidence)\n\n# 5. Check the result\nif result:\n take_umbrella = result.get_value(\"take_umbrella\")\n print(f\"Should I take an umbrella? Prediction: {take_umbrella}\")\n\n# Should I take an umbrella? Prediction: True\n```\n\n## Detailed Example\n\nThis example demonstrates more advanced features, including compiling the engine for faster repeated predictions.\n\n```python\nfrom vectorlogic import Engine\n\n# 1. Define variables and create the engine\nvariables = [\"x1\", \"x2\", \"x3\", \"x4\"]\nengine = Engine(variables=variables, name=\"My Logic Engine\")\n\n# 2. Add rules and initial evidence\nengine.add_rule(\"x1 = (x2 && x3)\")\nengine.add_rule(\"x2 <= (!x3 || !x4)\")\nengine.add_evidence({\"x4\": False})\n\n# 3. Compile the rules into a single 'valid set'\n# (See the performance section below for when to use this)\nengine.compile()\n\n# 4. Inspect the compiled state\nprint(\"--- Compiled Valid Set ---\")\nengine.valid_set.print(indent=4)\n\n# 5. Query the compiled knowledge base directly\nx2_value = engine.get_variable_value(\"x2\")\nprint(f\"\\nConsolidated value of 'x2' in the valid set: {x2_value}\")\n\n# 6. Run a fast prediction using the compiled engine\nprint(\"\\n--- Prediction ---\")\nevidence = {\"x1\": False, \"x2\": True}\nprint(f\"Predicting with evidence: {evidence}\")\nresult = engine.predict(evidence)\n\nif result:\n x3_value = result.get_value(\"x3\")\n print(f\"Inferred value of 'x3': {x3_value}\")\nelse:\n print(\"Evidence contradicts the knowledge base.\")\n```\n\n## Performance: To Compile or Not to Compile?\n\nThe `vector-logic` engine offers two approaches for inference, and the best choice depends on your use case.\n\n1. **Pre-compiling for Repeated Use** (`engine.compile()`)\n\n- **What it does:** Multiplies all added rules together to create a single, optimised `StateVector` called the \"valid\n set\".\n\n- **When to use it:** When you need to run multiple predictions against the same set of rules.\n\n- **Trade-off:** The initial compilation can be slow if the valid set is very large, but subsequent `predict()` calls\n will\n be extremely fast because they only need to multiply with this single, pre-computed valid set.\n\n2. **On-the-Fly Prediction**\n\n- **What it does:** Multiplies all rules from scratch every time you call `.predict()`, including the evidence for that\n specific prediction.\n\n- **When to use it:** When you need to run one or a few predictions.\n\n- **Trade-off:** This can be faster for a single query because a restrictive piece of evidence can cause the\n intermediate `StateVectors` to become very small, avoiding the creation of a potentially huge valid set.\n\n> **A Note on Performance:** The efficiency of this algorithm relies on heuristic optimisations for the order of rule\n> multiplication. This implementation includes a basic but effective heuristic that performs well for systems with up to\n> ~100 variables and a similar number of rules. For more challenging tasks, performance can be improved by implementing\n> more advanced optimisation heuristics.\n\n## Installation from source\n\nThis project uses Poetry for dependency management.\n\n1. Install Poetry:\n Follow the instructions on the [official Poetry website](https://python-poetry.org/docs/#installation).\n\n2. Clone the repository:\n\n ```bash\n git clone https://github.com/dmitry-lesnik/vector-logic.git\n cd vector-logic\n ```\n\n3. Install dependencies:\n ```bash\n poetry install\n ```\n\n## Running Tests\n\nTo run the test suite, use pytest through Poetry:\n\n```bash\n poetry install --with dev\n poetry run pytest\n ```\n\n## Further Reading & Theoretical Foundations\n\nThe `vector-logic` library is a practical implementation of an algebraic approach to propositional logic called **State\nAlgebra**. If you're interested in the concepts behind the engine, these resources provide a great starting point:\n\n* **Building a Rules Engine from First Principles**: A high-level, practical\n explanation of the main building blocks of State Algebra. This TDS article is the best place to start for\n understanding the core ideas: https://towardsdatascience.com/building-a-rules-engine-from-first-principles/\n\n* **State Algebra for Propositional Logic**: For those who want a more formal and rigorous treatment, this paper on\n arXiv offers a deep, theoretical dive into the mathematics of State Algebra: https://arxiv.org/abs/2509.10326\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A library for a simple rules engine.",
"version": "0.4.1",
"project_urls": {
"Homepage": "https://github.com/dmitry-lesnik/vector-logic",
"Repository": "https://github.com/dmitry-lesnik/vector-logic"
},
"split_keywords": [
"rules-engine",
" rules",
" business-rules",
" logic",
" state-vector",
" state-algebra"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "9062e657217fff0e510a9ddd329d813fc41c56703e6b2c64e2e221eda3eacc78",
"md5": "d1b4294981bb7040bd6e0f167adf8bf8",
"sha256": "e20d49cbfca78b17d56303533ad55c7f7f851f3387e7e1f0340d3fa64c2e1c26"
},
"downloads": -1,
"filename": "vector_logic-0.4.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "d1b4294981bb7040bd6e0f167adf8bf8",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.9",
"size": 32358,
"upload_time": "2025-11-05T09:40:15",
"upload_time_iso_8601": "2025-11-05T09:40:15.934094Z",
"url": "https://files.pythonhosted.org/packages/90/62/e657217fff0e510a9ddd329d813fc41c56703e6b2c64e2e221eda3eacc78/vector_logic-0.4.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "6dc2c5eec93439b3dc04da4dccd837f0d4dcaf8b5c6f9f247b83db7cae43b6ae",
"md5": "dca39e54bc7eb862eaa0211f0528beb1",
"sha256": "a2e5fcdab4a3f87a80c032fac79e42521eadd4bded2a35f85d6421b29c447ce9"
},
"downloads": -1,
"filename": "vector_logic-0.4.1.tar.gz",
"has_sig": false,
"md5_digest": "dca39e54bc7eb862eaa0211f0528beb1",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.9",
"size": 30377,
"upload_time": "2025-11-05T09:40:17",
"upload_time_iso_8601": "2025-11-05T09:40:17.052267Z",
"url": "https://files.pythonhosted.org/packages/6d/c2/c5eec93439b3dc04da4dccd837f0d4dcaf8b5c6f9f247b83db7cae43b6ae/vector_logic-0.4.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-11-05 09:40:17",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "dmitry-lesnik",
"github_project": "vector-logic",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "vector-logic"
}