Metadata-Version: 2.4
Name: ting-reasoner
Version: 0.9.0
Summary: A standalone, deterministic, non-neural expert-system library with readable .ting source and portable Compact-IR.
Author: Ting Reasoner contributors
License-Expression: MIT
Keywords: expert-system,rules,symbolic-ai,reasoning,compact-ir
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: ide
Requires-Dist: PySide6<7,>=6.8; extra == "ide"
Dynamic: license-file

<img src="https://res.cloudinary.com/vppzdwxg/image/upload/v1790592017/ting-reasoner-icon.png" alt="Ting Reasoner" width="96" height="96">

[Read the Ting Reasoner HTML manual](https://empty-tree-6676.rcttcr5.workers.dev/ting-reasoner-library)

# Ting Reasoner

**Reason from facts. Keep the explanation.**

Ting Reasoner is a deterministic symbolic reasoning and decision library written
entirely in Python. Define the knowledge your application needs, provide the
facts, and inspect both the conclusions and the evidence behind them.

**Pure Python core · Zero base runtime dependencies · Python 3.11+ · Optional desktop IDE**

Current release: `0.9.0` (pre-1.0)

Ting combines typed facts, declarative rules, explainable decisions, changing
observations, and independent-session multiprocessing in one standalone package.
Its compiler and reasoning runtime are pure Python. Installing the base Ting package requires no
C compiler, native extension, Cython, NumPy, model download, or external service.

## Pure Python, measured performance

Ting combines indexed matching, retained reasoning state and prepared rule
checks in pure Python. Against Ting 0.8.4, matching ran **1.2–4.7× as fast** in
five measured workloads. Total time, including engine construction, fact loading
and inference, fell about **4–29%**. Results and matching counters were identical;
peak traced memory was effectively unchanged.

Measurements used Python 3.12.14 on Linux and medians of six trials per release,
including first-use preparation. Cases covered wide bindings, scalar conditions,
constant membership filters, composite joins and range joins. Separate small
input-update controls had mixed results, so gains depend on the workload.
Structured execution budgets retain their existing evaluation path. Reproducible
benchmarks and full measurements are included in `docs/performance.json`.

## What Ting provides

| Capability | What you can do |
| --- | --- |
| Typed, immutable facts | Define named schemas with exact scalar types, nullable fields, type unions, bytes, and fixed-shape array values. Duplicate input facts reuse their handle within a session. |
| Declarative rules and joins | Match facts, bind values, compare fields across patterns, and apply equality, membership, ordering, and range conditions. Set rule priority with `salience`. |
| Boolean and quantified conditions | Combine `all_of`, `any_of`, `not_`, `test`, `exists`, and `for_all`. Negation and universal conditions follow explicit stratification rules. |
| Deterministic forward reasoning | Derive additional facts, emit conclusions, and follow recursive rule chains in a defined order. Repeated runs resume within documented firing and work limits. |
| Mutable sessions with immutable views | Declare, replace, and retract input facts; inspect handles, facts, conclusions, traces, and snapshots; reset a session for another case. |
| Atomic transactions | Stage several input changes and commit them together. Expected epochs detect stale transactions; commit receipts resolve staged handles and describe the committed changes. |
| Explanations and provenance | Inspect the rules, bindings, and supporting facts behind a conclusion or derived fact. Retained source information adds rule locations, schema origins, and fixed-knowledge origins. |
| Fixed program knowledge | Include named seed facts in Python or readable source. Seeds survive session resets and are protected against direct and transactional modification. |
| Classifications and inheritance | Declare named classifications over typed records, including multiple parents, and reason over their inherited memberships. |
| Support maintenance | Keep grounded facts and conclusions across supported positive-rule input updates. Alternative justifications survive; losing the final valid support removes its consequences, including unsupported cycles. Inspect support-change reports and bounded fallback behavior. |
| Explicit decision assessment | Evaluate named candidates against hard requirements. Distinguish supported, refuted, unknown, and conflicting evidence; preserve ties; select an option only when the decision policy permits it. Use `decide()` for a fresh case or `assess_decision()` for an existing session. |
| Portable named decisions | Define decision requests in Python or `.ting` source, save them in compiled programs or libraries, and retrieve or selectively import them by name. |
| Readable rule source | Parse, format, analyze, and compile UTF-8 `.ting` modules. Use explicit imports, typed conclusions, named knowledge, classifications, decisions, and embedded tests. Diagnostics identify source locations when available. |
| Verified compiled programs | Save and load `.tingir` artifacts with format, type, and structural validation. Reuse a verified program across independent engines. Load supported historical binary `.ting` files with the dedicated loader. |
| Compiled knowledge libraries | Export reusable schemas, rules, classifications, seeds, conclusions, and decisions. `CompiledCatalog` links selected exports with their declared dependencies from explicitly supplied files. |
| Fixed-shape multidimensional values | Store immutable `bool`, signed `i64`, and finite `f64` arrays with exact shape and value identity. Match and pass whole arrays through rules without NumPy. |
| Bounded work and observable costs | Limit candidate rows, constraint evaluations, activations, and firings with `ExecutionBudget`. Separate policies bound authoring, loading, explanations, decisions, support maintenance, and batch work. Inspect matching, optimization, and store metrics. |
| Matching and storage optimizations | Use indexed lookups, shared filtering, composite joins, range pruning, retained activations, and incremental matching. Inspect physical storage counts and explicitly compact tombstones while preserving public state. |
| Independent cases in parallel | Use `run_batch()` or ordered `iter_batch()` streams. Choose inline execution, Ting-owned processes, or a supplied executor; control chunking, in-flight work, shared submission permits, and cooperative cancellation. Results retain their explanations. |
| Command-line tools and project history | Use `ting-build` for readable-source checks and compilation, or the separate RuleSpec JSON builder. Validate, test, inspect, and verify artifacts; checkpoint, compare, export, and restore RuleSpec revisions. Use `ting-reasoner` or `ting-console` to inspect and exercise reasoning sessions interactively or through scripts. |
| Complete offline documentation | Read the searchable HTML manual for beginner-friendly Python explanations, complete examples, supported behavior, error handling, and the full public API reference. |

## Install and verify

Use Python 3.11 or later. Run installation commands in a terminal, using the
Python environment that will run your application.

Install the release from PyPI:

```console
python -m pip install ting-reasoner==0.8.5
```

To install a downloaded wheel, run this from the folder containing the file:

```console
python -m pip install ting_reasoner-0.8.5-py3-none-any.whl
```

To install from a source bundle, extract it, open a terminal in the folder
containing `pyproject.toml`, and run:

```console
python -m pip install .
```

Source installation may download Python build tools. These are separate from
Ting's zero-dependency runtime.

After installation, check the installed package:

```console
python -m ting_reasoner.selftest
```

The self-test prints a JSON report. Look for `"ok": true`. It checks compiled
programs, explanations, decisions, changing inputs, recursive support handling,
and agreement between inline execution and spawned workers. Run it from a
terminal because it starts worker processes.

## Optional Ting IDE and compiler

A light, frameless PySide6 workspace edits one `.ting` file through six section
tabs: General, Data, Knowledge, Rules, Decisions and Tests. The top toolbar keeps
New, Open, Save, Check, Test and Compile visible; Stop appears during a build.

```console
python -m pip install "ting-reasoner[ide]"
ting-ide
```

For the downloaded wheel, use
`python -m pip install "./ting_reasoner-0.9.0-py3-none-any.whl[ide]"`.
From extracted source, use `python -m pip install ".[ide]"`.
`python -m ting_reasoner.ide` is an equivalent launcher.

The desktop extra installs PySide6 and its Qt dependencies. The base package
still has no runtime dependencies, and importing Ting does not import Qt.
No separate Qt SDK or C compiler is needed for the supported PySide6 wheels.

The custom Open dialog previews source structure on its right side. Each tab
has a short explanation, tooltips, and a link to bundled offline IDE help.
Source loading, previews and builds run in separate processes. Tests and full
verification must succeed before compiled output is published. Cancelled or
failed builds keep the previous output. The last saved/opened source and its
local library mappings reopen at startup; `ting-ide --fresh` bypasses restoration.

The IDE preserves source comments and unedited sections. Imports are configured
under General → Libraries. Core APIs, formats and the 0.8.5 performance changes
remain intact. The supplied v0.8.3 language manual remains valid and unchanged;
IDE help is a separate small document.

See [the IDE notes](docs/TING_IDE.md) and
[Windows review checklist](docs/TING_IDE_WINDOWS_CHECKLIST.md).

## Open the HTML manual

Ting provides one language HTML manual. Identical copies are included with the source
bundle and the installed package so you can read it before or after installing
Ting. It works offline and includes search, code-copy buttons, complete examples,
and an API reference.

| Distribution | Manual location |
| --- | --- |
| Extracted source ZIP or source distribution | `docs/index.html` inside the extracted project folder |
| Installed Python package | `docs/index.html` inside the installed `ting_reasoner` package directory |
| Separate downloadable manual | `ting-reasoner-library.html` |

For the source bundle, open `docs/index.html` in your browser. To locate and open
the installed copy, save the following as `open_ting_manual.py` and run
`python open_ting_manual.py`:

```python
from pathlib import Path
import webbrowser
import ting_reasoner

manual = Path(ting_reasoner.__file__).resolve().parent / "docs" / "index.html"
print(manual)
webbrowser.open(manual.as_uri())
```

The printed path also lets you open the file manually. Start with **Install and
verify**, **Understand the Python calls**, and **Your first reasoner**. Later
sections cover changing inputs, source files, reusable knowledge, decisions,
explanations, arrays, and parallel cases.

## A complete Python example

This example requests an inspection when an equipment reading reaches 70.
It then replaces the observation and checks that the obsolete conclusion is
removed.

Save it as `inspection_example.py` and run `python inspection_example.py` in
the environment where you installed Ting.

```python
from ting_reasoner import (
    Engine, FactSchema, KnowledgeBase, MaintenancePolicy,
    Rule, bind, emit, ge, use,
)

Reading = FactSchema("reading", device=str, temperature=int)

inspection_rule = Rule(
    "inspect_hot_equipment",
    when=(Reading.pattern(device=bind("device"), temperature=ge(70)),),
    then=(emit("inspection_needed", device=use("device")),),
)

knowledge = KnowledgeBase(rules=(inspection_rule,))
engine = Engine(knowledge, maintenance=MaintenancePolicy())

handle = engine.declare(Reading(device="pump_a", temperature=85))
engine.run()

conclusion = engine.conclusions[0]
print(conclusion["device"])                   # pump_a
print(engine.explain(conclusion)[0].rule)     # default.inspect_hot_equipment@1

engine.replace(handle, Reading(device="pump_a", temperature=40))
engine.run()
assert engine.conclusions == ()
```

`FactSchema` defines the accepted fields and types. `bind()` names a matched
value, `ge(70)` means greater than or equal to 70, and `use()` passes the bound
value into the conclusion. `run()` applies the rules. `explain()` identifies the
supporting rule and facts. Your application decides how to act on the results.

`MaintenancePolicy()` enables support retention for eligible positive rules.
Call `run()` after changing observations to discover any new consequences.
The manual explains alternative supports, policy limits, and recomputation for
rules containing negation or quantified conditions.

## Scope and execution behavior

Ting is a symbolic rule system. It derives conclusions from explicit knowledge
and observations; it does not train a neural model or require an AI service.

The decision API evaluates hard requirements over an explicit candidate list.
It preserves unknowns, conflicts, and multiple feasible choices. Preference
ranking, aggregate operators, temporal reasoning, backward chaining, and entity
reference fields are outside the current API. Array support concerns immutable
whole values; broadcasting, slicing, and numerical reductions are unavailable.

Batch multiprocessing runs independent sessions. A single live `Engine` is not
split across processes. Inline execution is the default; processes are created
only when explicitly requested. Process-launching calls belong inside an
`if __name__ == "__main__":` guard in a Python file. Logical work limits do not
represent exact memory ceilings or wall-clock deadlines.

## License and application scope

Ting Reasoner is distributed under the MIT License; the complete license is in
`LICENSE`. The project's supported application scope excludes banking and
financial use. License and project distribution policies are described in
`LICENSING.md`; this application policy is separate from the MIT license text.
