Metadata-Version: 2.4
Name: clingexplaid
Version: 1.5.1
Summary: Tools to aid the development of explanation systems using clingo
Author-email: Hannes Weichelt <hweichelt@uni-potsdam.de>, Susana Hahn <susuhahnml@yahoo.com.mx>
Maintainer-email: Hannes Weichelt <hweichelt@uni-potsdam.de>
License: MIT License
        
        Copyright (c) 2024 Hannes Weichelt
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/potassco/clingo-explaid
Project-URL: Source, https://github.com/potassco/clingo-explaid
Project-URL: Issues, https://github.com/potassco/clingo-explaid/issues
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: clingo>=5.7.1
Requires-Dist: musclingo>=0.1
Provides-Extra: lint
Requires-Dist: ruff; extra == "lint"
Provides-Extra: typecheck
Requires-Dist: pytest; extra == "typecheck"
Requires-Dist: ty; extra == "typecheck"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Requires-Dist: coverage[toml]; extra == "test"
Provides-Extra: doc
Requires-Dist: mkdocs; extra == "doc"
Requires-Dist: mkdocs-material; extra == "doc"
Requires-Dist: mkdocstrings>=1.0.4; extra == "doc"
Requires-Dist: mkdocstrings-python>=2.0; extra == "doc"
Requires-Dist: clindocs>=1.5.1; extra == "doc"
Requires-Dist: mkdocs-literate-nav; extra == "doc"
Requires-Dist: pygments_clingo; extra == "doc"
Provides-Extra: dev
Requires-Dist: clingexplaid[lint,lint_pylint,test,typecheck]; extra == "dev"
Dynamic: license-file

[![badge-docs]][text-docs] [![badge-license]][text-license]
[![badge-pypi]][text-pypi]

# 💡 clingexplaid

<!-- --8<-- [start:description] -->

This library collects tools for explaining why an ASP program is unsatisfiable.
We build on top of the [clingo](https://potassco.org/clingo/) API to offer
preprocessing, subset computation, and constraint analysis helpers for building
explanation systems. This repository is part of the
[Potassco](https://potassco.org/) suite.

<!-- --8<-- [end:description] -->

## 📦 Installation

<!-- --8<-- [start:installation] -->

Clingo-Explaid can easily be installed with `pip`:

```bash
pip install clingexplaid
```

Requirements : _python_ >= `3.11` & _clingo_ >= `5.7.1`

<!-- --8<-- [end:installation] -->

### Building from Source

Please refer to
[DEVELOPEMENT](https://github.com/potassco/clingo-explaid/blob/master/DEPLOYMENT.md)

## 🚀 Getting Started

The following Examples show use-cases for `clingexplaid`'s API.

### Pre-Processing

<!-- --8<-- [start:example-pre-simple] -->

#### Transforming facts to Assumptions

```python
from clingexplaid.preprocessors import AssumptionPreprocessor
from clingexplaid.preprocessors import (
    FilterSignature,
    FilterPattern,
)

PROGRAM = """
a(book;magazine;video).
b(test).
c(1..10).
d(1..3).
"""

ap = AssumptionPreprocessor(filters=[FilterSignature("a", 1), FilterPattern("d(2)")])
result = ap.process(PROGRAM)
# You can either use the return value of `ap.process`
print(result)
# Or use `ap.control` with your transformed program already added
print(ap.control)
```

<!-- --8<-- [end:example-pre-simple] -->

<!-- --8<-- [start:example-pre-control] -->

#### Transforming facts to Assumptions with custom Control

```python
import clingo
from clingexplaid.preprocessors import AssumptionPreprocessor, FilterSignature, FilterPattern

FILE = "local/encoding.lp"

ctl = clingo.Control("0")
ap = AssumptionPreprocessor(control=ctl, filters=[FilterSignature("a", 1), FilterPattern("d(2)")])
ap.process_files([FILE])

# The transformed files are added to ctl so it can be directly used
ctl.ground([("base", [])])
ctl.solve()
```

<!-- --8<-- [end:example-pre-control] -->

### Computing relevant subsets (MUS, MSS, MCS)

<!-- --8<-- [start:example-mus-single] -->

#### Finding a single MUS

```python
from clingexplaid.preprocessors import AssumptionPreprocessor, FilterSignature
from clingexplaid.unsat import SubsetComputer

PROGRAM = """
a(1..3).
{b(4..6)}.

a(X) :- b(X).

:- a(X), X>=3.
"""

ap = AssumptionPreprocessor(filters={FilterSignature("a", 1)})
ap.process(PROGRAM)
ap.control.ground([("base", [])])
sc = SubsetComputer(ap.control, ap.assumptions)


def shrink_on_core(core) -> None:
    mus = sc.mus(core)
    print(mus)


ap.control.solve(assumptions=list(ap.assumptions), on_core=shrink_on_core)
```

The `SubsetComputer.mus()` method can simple be swapped with
`SubsetComputer.mss()` or `SubsetComputer.mcs()` to compute the respective
other subset types

<!-- --8<-- [end:example-mus-single] -->

<!-- --8<-- [start:example-mus-multiple] -->

#### Finding multiple MUSs

```python
from clingexplaid.preprocessors import AssumptionPreprocessor
from clingexplaid.unsat import SubsetComputer

PROGRAM = """
a(1..3).
b(1..3).

:- a(X), b(X).
"""

ap = AssumptionPreprocessor()
ap.process(PROGRAM)
ap.control.ground([("base", [])])
sc = SubsetComputer(ap.control, ap.assumptions)

for i, mus in enumerate(sc.multiple()):
    print(f"{i}:", mus)
```

<!-- --8<-- [end:example-mus-multiple] -->

<!-- --8<-- [start:example-mus-multiple-lattice] -->

#### Finding multiple MUSs with a custom Lattice

Clingo-Explaid's `SubsetComputer` uses an internal `Lattice` to decide the
order in which subset candidates are explored. By default it uses the
`AssumptionLattice`, which is defined in this MUS core utilities repository
[`musclingo`](https://github.com/potassco/musclingo). You can also use your own
lattice, by defining a custom `LatticeFactory` that provides it to the
`SubsetComputer`. The following is an example showing this by re-implementing
the `AssumptionLattice`.

```python
from clingexplaid.preprocessors import AssumptionPreprocessor
from clingexplaid.unsat import SubsetComputer
from clingexplaid.unsat.lattice import LatticeFactory

PROGRAM = """
a(1..3).
b(1..3).

:- a(X), b(X).
"""


class MyLatticeFactory(LatticeFactory):
    def __init__(self, bias: bool):
        super().__init__()
        self._bias = bias

    def new(self, literals: set[int]):
        return AssumptionLattice(literals, bias=self._bias)


ap = AssumptionPreprocessor()
ap.process(PROGRAM)
ap.control.ground([("base", [])])
sc = SubsetComputer(ap.control, ap.assumptions, lattice_factory=MyLatticeFactory(True))

for i, mus in enumerate(sc.multiple()):
    print(f"{i}:", mus)
```

<!-- --8<-- [end:example-mus-multiple-lattice] -->

<!-- --8<-- [start:example-mus-multiple-any] -->

#### Finding multiple relevant subsets (MUS, MSS, and MCS)

```python
from clingexplaid.preprocessors import AssumptionPreprocessor
from clingexplaid.unsat import SubsetComputer
from clingexplaid.unsat.sets import [
    MinimalUnsatisfiableSubset,
    MaximalSatisfiableSubset,
    MinimalCorrectionSet
]

PROGRAM = """
a(1..3).
b(1..3).

:- a(X), b(X).
"""

ap = AssumptionPreprocessor()
ap.process(PROGRAM)
ap.control.ground([("base", [])])
sc = SubsetComputer(ap.control, ap.assumptions)

types = [MinimalUnsatisfiableSubset, MaximalSatisfiableSubset, MinimalCorrectionSet]
for i, subset in enumerate(sc.multiple(types)):
    print(f"{i}:", subset)
```

<!-- --8<-- [end:example-mus-multiple-any] -->

### Unsatisfiable Constraints

<!-- --8<-- [start:example-constraints] -->

```python
from clingexplaid.unsat_constraints import UnsatConstraintComputer

PROGRAM = """
a(1..3).
{b(4..6)}.

a(X) :- b(X).

:- a(X), X>=3.
"""

ucc = UnsatConstraintComputer()
ucc.parse_string(PROGRAM)
unsat_constraints = ucc.get_unsat_constraints()

for uc_id, unsat_constraint in unsat_constraints.items():
    print(f"Unsat Constraint {uc_id}:", unsat_constraint)
```

<!-- --8<-- [end:example-constraints] -->

[badge-docs]: https://img.shields.io/badge/docs-potassco.org-blue
[badge-license]: https://img.shields.io/github/license/potassco/clingo-explaid
[badge-pypi]: https://img.shields.io/pypi/v/clingexplaid
[text-docs]: https://docs.potassco.org/clingo-explaid/
[text-license]: LICENSE
[text-pypi]: https://pypi.org/project/clingexplaid/
