Metadata-Version: 2.4
Name: ting-reasoner
Version: 0.10.0a21
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.14,>=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy<3,>=2.3.5
Requires-Dist: numba<1,>=0.63.1
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.

**Python compiler and reasoning core · NumPy and Numba runtime · Python 3.11–3.13 · Optional desktop IDE**

Current release: `0.10.0a21` (pre-1.0)

![Ting Reasoner IDE and compiler with section tabs, a quick-access toolbar, and compilation feedback](https://res.cloudinary.com/vppzdwxg/image/upload/v1790718079/ting_reasoner_ide_scrn1.png)

*The optional Ting IDE and compiler: edit one `.ting` file through clear section
tabs, inspect its full source, and check, test, save and compile from the toolbar.*

Ting combines typed facts, declarative rules, explainable decisions, changing
observations, and independent-session multiprocessing in one standalone package.
Ting's compiler and reasoning core are authored in Python. The base installation
includes NumPy and Numba for numerical execution. Numba installs compatible
llvmlite. These dependencies contain compiled components; supported binary
wheels install without building a native extension locally. No model download
or external service is required.

Base runtime dependencies: `numpy>=2.3.5,<2.4` and `numba>=0.63.1,<0.64`.

## 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. |
| Stable entity references | Declare typed entity keys and strong reference fields. Resolve identities and incoming links in the current session or a retained snapshot; coordinate redirection in a transaction. |
| Explicit reference traversal | Follow a bound entity reference in Python rules or `.ting` source. Match target properties with complete supporting facts, indexed keys and existing work limits. |
| Compiled entity libraries | Select entity types, rules and closed fixed graphs from indexed `.tingir` libraries. Identical closed graphs share compiled payloads; unrelated private facts remain unselected. |
| 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; use `array_sum()` for bounded integer and floating-point sums. |
| 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, 3.12 or 3.13. Run installation commands in a terminal, using the
Python environment that will run your application.

To install a release available on PyPI:

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

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

```console
python -m pip install ting_reasoner-0.10.0a21-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 in addition to the NumPy
and Numba runtime dependencies. Use compatible binary dependency wheels for
your Python version and operating system.

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.

Build and compile a file in three steps:

1. Choose **New** to start with a working example, or **Open** an existing `.ting` file.
2. Edit the relevant tabs. Each tab works on a section of the same file; the IDE
   supplies section headings and outer indentation for you.
3. Click **Save**, then **Compile**. The IDE checks the source, runs its embedded
   tests, and writes verified `.tingir` output beside the source. Build feedback
   shows the result; double-click a located error to return to its source.

**Full source** lets you inspect and edit the complete `.ting` document, including
imports and comments, then apply changes back to the tabs. A self-contained
program needs no separate IDE project file. Keep `.ting` for editing and use the
compiled `.tingir` with the Ting runtime in your application.

For a release available on PyPI, install the optional desktop dependencies
and launch the IDE:

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

For the downloaded wheel, use
`python -m pip install "./ting_reasoner-0.10.0a21-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 alongside NumPy
and Numba. PySide6 is optional for library use, and importing Ting does not
import Qt. No separate Qt SDK or C compiler is needed for supported PySide6
wheels.

The IDE code, icons and offline help are included in the same Ting wheel either
way. `[ide]` selects the optional dependencies; if you already have compatible
PySide6 and Qt dependencies installed, you can omit that suffix. On Windows,
`py -m ting_reasoner.ide` also launches the IDE; use `py` in place of `python`
in the installation commands if that is your usual Python launcher.

The custom Open dialog previews source structure on its right side. Each tab
has a short explanation and a link to bundled offline IDE help. Hover tooltips
are disabled. Full source has a compact editing toolbar for Undo/Redo, Cut,
Copy, Paste, Select all and Find.
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. The HTML language manual covers Python APIs, readable
source, numerical execution and compiled programs; bundled IDE help explains
the editing and compilation workflow.

Open **Help → IDE guide** in the app for the bundled offline instructions.
Each tab's **Tab help** opens its matching topic directly.

## 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, general fact aggregation, temporal reasoning, backward chaining, and
entity reference fields are outside the current API. Arrays support immutable
fixed-shape values and bounded whole-array sums; broadcasting, slicing and
axis-specific 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.

The IDE’s **File information** tab shows the saved `.ting` path, module identity, size, line details and counts by category. Unsaved edits are clearly marked while counts continue to describe the last successful open or save.


Typed references can be constructed in rule actions with
`Asset.ref(use("serial"))`; readable source uses
`ref Asset [{"use": "serial"}]` with the `entity-construction` feature.
Complete target keys and initialized exact scalar types are verified. A firing
can create the target and referring fact atomically. Construction itself adds
no target premise; use an explicit match or follow for target evidence.

The source release includes a scoped NASA-referenced assurance profile,
configuration baseline and strict evidence checker under `docs/assurance` and
`tools/assurance.py`. These controls support traceability and verification;
full NASA compliance, safety qualification and endorsement are not claimed.


Engine-created snapshots share immutable entity indexes by generation. Use
`engine.entity_storage_report` for lazy, shallow current/retained index sizes
and scope exclusions; it is not a whole-process or graph-byte admission bound.
See the main HTML manual's “Snapshot ownership and index storage” example.
The IDE includes outlined darker dialogs and restrained static control gradients.
