3#include <clingo/control/config.hh>
4#include <clingo/control/grounder.hh>
6#include <clingo/output/backend.hh>
8#include <potassco/basic_types.h>
10#include <clasp/clasp_facade.h>
11#include <clasp/cli/clasp_options.h>
13namespace CppClingo::Control {
31 virtual void do_exec(std::string_view
code) = 0;
49 void do_exec(
Location const &loc,
Logger &log, std::string_view name, std::string_view
code)
override;
50 auto do_callable(std::string_view name,
size_t args) ->
bool override;
53 std::vector<std::pair<std::string, UScript>> scripts_;
99 std::optional<size_t>
imax = std::nullopt;
149 auto [it, ins] = map_.emplace(sym, 0);
151 it.value() = std::invoke(std::forward<F>(fun));
163 if (!map_.emplace(sym,
id).second) {
164 throw std::runtime_error(
"collision of term ids");
174 return map_.nth(i).value();
176 throw std::range_error{
"index out of range"};
185 return *map_.nth(i).key();
187 throw std::range_error{
"index out of range"};
197 [[nodiscard]]
auto index(
Symbol sym)
const ->
size_t {
return map_.find(sym) - map_.begin(); }
202 [[nodiscard]]
auto size() const ->
size_t {
return map_.size(); }
208 [[nodiscard]]
auto begin() const ->
Map::const_iterator {
return map_.cbegin(); }
214 [[nodiscard]]
auto end() const ->
Map::const_iterator {
return map_.cend(); }
226 [[nodiscard]]
auto bases() const -> Ground::Bases const & {
return do_bases(); }
230 [[nodiscard]]
auto clasp_program() const -> Clasp::Asp::LogicProgram const & {
return do_clasp_program(); }
235 [[nodiscard]]
virtual auto do_bases() const -> Ground::Bases const & = 0;
236 [[nodiscard]] virtual auto do_term_base() const ->
TermBaseMap const & = 0;
237 [[nodiscard]] virtual auto do_clasp_program() const -> Clasp::Asp::LogicProgram const & = 0;
247 virtual void do_add_clause(
PrgLitSpan lits) = 0;
253 virtual ~Model() =
default;
263 [[nodiscard]]
auto number() const -> uint64_t {
return do_number(); }
272 [[nodiscard]]
auto contains(
Symbol sym)
const ->
bool {
return do_contains(sym); }
286 [[nodiscard]]
auto costs() const -> std::span<
prg_sum_t const> {
return do_costs(); }
309 [[nodiscard]]
virtual auto do_number() const -> uint64_t = 0;
310 [[nodiscard]] virtual auto do_type() const ->
ModelType = 0;
311 [[nodiscard]] virtual auto do_contains(
Symbol sym) const ->
bool = 0;
312 virtual
void do_extend(
SymbolSpan symbols) = 0;
313 [[nodiscard]] virtual auto do_is_true(
prg_lit_t lit) const ->
bool = 0;
315 [[nodiscard]] virtual auto do_costs() const -> std::span<
prg_sum_t const> = 0;
316 [[nodiscard]] virtual auto do_priorities() const -> std::span<
prg_weight_t const> = 0;
317 [[nodiscard]] virtual auto do_optimality_proven() const ->
bool = 0;
318 [[nodiscard]] virtual auto do_thread_id() const ->
prg_id_t = 0;
319 [[nodiscard]] virtual auto do_control() ->
SolveControl & = 0;
392 auto wait(
double timeout) ->
bool {
return do_wait(timeout); }
396 virtual void do_cancel() = 0;
397 virtual void do_resume() = 0;
398 virtual auto do_model() ->
Model const * = 0;
399 virtual auto do_last() ->
Model const * = 0;
401 virtual auto do_wait(
double timeout) ->
bool = 0;
425 void on_stats(Potassco::AbstractStatistics &stats) { do_on_stats(stats); }
432 void on_unsat(Clasp::SumView bound) { do_on_unsat(bound); }
437 void on_core(Potassco::LitSpan core) { do_on_core(core); }
447 virtual auto do_on_model([[maybe_unused]]
Model &mdl) ->
bool {
return true; }
448 virtual void do_on_stats([[maybe_unused]] Potassco::AbstractStatistics &stats) {}
449 virtual void do_on_unsat([[maybe_unused]] Clasp::SumView bound) {}
450 virtual void do_on_core([[maybe_unused]] Potassco::LitSpan core) {}
451 virtual void do_on_finish([[maybe_unused]] SolveResult result) {}
484 [[nodiscard]]
auto program() -> Clasp::Asp::LogicProgram & {
return do_program(); }
509 virtual auto do_program() -> Clasp::Asp::LogicProgram & = 0;
513 virtual void do_close() = 0;
519class Propagator :
public Potassco::AbstractPropagator,
public Potassco::AbstractHeuristic {
556 std::optional<std::mutex> mut_;
583 auto out() -> std::ostream & {
return *out_; }
590 size_t index : (8 *
sizeof(size_t)) - 2 = 0;
596 std::ostream *out_ =
nullptr;
598 std::vector<size_t> buf_;
610 : Event(this, subsystem_load, verbosity_quiet), params(params) {}
612 std::span<Input::ProgramParamVec::value_type const>
params;
632 virtual void do_finish([[maybe_unused]]
GroundResult result)
noexcept {}
670 [[nodiscard]] auto wait(
double timeout) ->
bool;
683 std::unique_ptr<Impl> impl_;
696 void main(std::span<std::string_view const>
const &files);
710 void parse(std::span<std::string_view const>
const &files);
757 [[nodiscard]]
auto clasp_facade() -> Clasp::ClaspFacade & {
return *clasp_; }
760 [[nodiscard]]
auto clasp_facade() const -> Clasp::ClaspFacade const & {
return *clasp_; }
766 [[nodiscard]]
auto clasp_stats() -> Potassco::AbstractStatistics
const & {
767 auto const *stats = clasp_->getStats();
768 return stats !=
nullptr ? *stats :
throw std::runtime_error(
"not in solving mode");
792 [[nodiscard]] auto get_parts() -> std::optional<Input::StmParts> const & {
return grd_.get_parts(); }
795 void set_parts(std::optional<Input::StmParts> parts) { grd_.set_parts(std::move(parts)); }
798 auto pos =
Position{*grd_.store().string(
"<cmd>"), 1, 1};
800 grd_.set_parts(std::make_optional<Input::StmParts>(loc, Input::Precedence::override_, std::move(parts)));
809 sym_tab_ = std::make_unique<SymbolTable>();
832 enum class State : uint8_t {
848 auto make_output_(
SymbolStore &store, AppMode mode, BackendType backend_type, ReifyFlags reify_flags) ->
UOutputStm;
857 void enable_updates_();
859 [[nodiscard]]
auto do_bases() const -> Ground::Bases const &
override {
return grd_.base(); }
861 [[nodiscard]]
auto do_term_base() const -> TermBaseMap const &
override {
return terms_; }
863 [[nodiscard]]
auto do_clasp_program() const -> Clasp::Asp::LogicProgram const &
override {
864 return clasp_->asp() !=
nullptr ? *clasp_->asp() :
throw std::runtime_error(
"not in solving mode");
870 std::vector<UPropagator> propagators_;
872 Clasp::ClaspFacade *clasp_;
873 ClingoConfig config_;
874 Util::OutputStream stream_;
876 std::unique_ptr<Output::TheoryData> theory_;
877 std::unique_ptr<Potassco::AbstractProgram> output_program_;
878 std::unique_ptr<Potassco::AbstractProgram> program_;
884 State state_ = State::initial;
887 void *data_ =
nullptr;
888 bool block_main_ =
false;
Object to provide access to the backend.
Definition solver.hh:479
auto store() -> SymbolStore &
The symbol store.
Definition solver.hh:492
auto theory() -> Output::TheoryData &
Get the theory.
Definition solver.hh:488
void close()
Close the handle.
Definition solver.hh:504
auto program() -> Clasp::Asp::LogicProgram &
Get the logic program.
Definition solver.hh:484
virtual ~BackendHandle()=default
Destroy the handle.
auto add_atom(Symbol atom) -> prg_lit_t
Add a literal for the given symbol.
Definition solver.hh:499
Interface providing the necessary data to inspect atom, term, and theory bases.
Definition solver.hh:221
auto clasp_theory() const -> Potassco::TheoryData const &
Get a reference to the underlying facade.
Definition solver.hh:232
virtual ~BaseView()=default
The default destructor.
auto bases() const -> Ground::Bases const &
Get a reference to the underlying atom bases.
Definition solver.hh:226
auto term_base() const -> TermBaseMap const &
Get a reference to the underlying term bases.
Definition solver.hh:228
auto clasp_program() const -> Clasp::Asp::LogicProgram const &
Get a reference to the underlying facade.
Definition solver.hh:230
This lock ensures that callbacks during solving are called in lock-step.
Definition solver.hh:531
void enable(bool state)
Enable or disable the lock.
Definition solver.hh:546
void unlock()
Release the lock.
Definition solver.hh:540
void lock()
Acquire the lock.
Definition solver.hh:534
This class provides a hierarchical configuration interface for clingo.
Definition config.hh:24
This callback interface provides grounding events.
Definition solver.hh:621
void finish(GroundResult result) noexcept
Callback to inform that the grounding has finished.
Definition solver.hh:629
A handle for asynchronous grounding.
Definition solver.hh:641
GroundHandle(Solver &solver, Input::ProgramParamVec params, UGroundEventHandler handler)
Start grounding with the given params and context.
~GroundHandle() noexcept
Destroy the ground handle.
Event emitted by a solver after the program is grounded.
Definition solver.hh:606
std::span< Input::ProgramParamVec::value_type const > params
The program parts that have been grounded.
Definition solver.hh:612
Grounded(Input::ProgramParamVec const ¶ms)
Construct a grounded event.
Definition solver.hh:609
A grounder for logic programs.
Definition grounder.hh:18
The model class.
Definition solver.hh:251
auto contains(Symbol sym) const -> bool
Check if the model contains a (symbolic) atom.
Definition solver.hh:272
auto context() -> SolveControl &
Get the context object to control the search.
Definition solver.hh:302
auto is_true(prg_lit_t lit) const -> bool
Check if a program literal is true in a model.
Definition solver.hh:277
auto is_consequence(prg_lit_t lit) const -> ConsequenceType
Check whether the given literal is a consequence.
Definition solver.hh:282
auto number() const -> uint64_t
Get the running number of the model.
Definition solver.hh:263
auto optimality_proven() const -> bool
Check if the model corresponds to an optimal solution.
Definition solver.hh:294
auto thread_id() const -> prg_id_t
Get the solver/thread id the model was found in.
Definition solver.hh:298
auto type() const -> ModelType
Get the type of the model.
Definition solver.hh:267
auto priorities() const -> std::span< prg_weight_t const >
get the priorities of the costs.
Definition solver.hh:290
virtual void extend(SymbolSpan symbols)
Extend the model with the given symbols.
Definition solver.hh:305
void symbols(SymbolSelectFlags type, SymbolVec &res) const
Get the selected symbols in the model.
Definition solver.hh:259
auto costs() const -> std::span< prg_sum_t const >
Get the costs associated with a model.
Definition solver.hh:286
The propagator interface.
Definition solver.hh:519
virtual auto hasHeuristic() const -> bool=0
Can return false to not also register the propagator as a heuristic.
Script providing code execution, main, and callbacks.
Definition solver.hh:23
void main(Solver &slv)
Run the main function.
Definition solver.hh:26
void exec(std::string_view code)
Execute the given code.
Definition solver.hh:28
Helper to run specific code and callbacks.
Definition solver.hh:41
void register_script(std::string_view name, UScript script)
Register the given script.
void main(Solver &slv)
Run the main function.
Simple control class to add clauses while enumerating models.
Definition solver.hh:241
void add_clause(PrgLitSpan lits)
Add a clause over the given literal.
Definition solver.hh:244
The event handler interface.
Definition solver.hh:407
void on_unsat(Clasp::SumView bound)
Callback to intercept lower bounds.
Definition solver.hh:432
void on_finish(SolveResult result)
Callback to inform that the search has finished.
Definition solver.hh:444
auto on_model(Model &mdl) -> bool
Callback to intercept models.
Definition solver.hh:417
void on_core(Potassco::LitSpan core)
The unsatisfiable core of the current problem.
Definition solver.hh:437
void on_stats(Potassco::AbstractStatistics &stats)
Callback to update statistics.
Definition solver.hh:425
A handle to control a running search.
Definition solver.hh:339
auto last() -> Model const *
Get the last model after the search has finished.
Definition solver.hh:375
void resume()
Resume search after a model has been found to start search for the next one.
Definition solver.hh:359
auto wait(double timeout) -> bool
Wait for the given amount of time or until the next result is ready.
Definition solver.hh:392
auto get() -> SolveResult
Get the result of a search.
Definition solver.hh:349
auto model() -> Model const *
Get the current model or a nullptr if there is none.
Definition solver.hh:369
auto core() -> PrgLitSpan
Get a subset of the assumptions that made the problem unsatisfiable.
Definition solver.hh:382
virtual ~SolveHandle()=default
The default destructor.
void cancel()
Cancel the current search.
Definition solver.hh:353
A grounder and solver for logic programs.
Definition solver.hh:689
void parse(std::string_view str)
Parse a program from the given string.
void output_program(std::ostream &out)
Output the current program.
void join(Input::UnprocessedProgram const &prg)
Join with the given program.
void parse_with(std::function< void(ProgramBackend *, TheoryBackend *)> cb)
Parse with optional backends.
void set_parts(Input::ProgramParamVec parts)
Set the program parts to ground.
Definition solver.hh:797
void main(std::span< std::string_view const > const &files)
Parse, ground, and solve a program.
auto stream() -> Util::OutputStream &
Get the text buffer.
Definition solver.hh:748
auto clasp_facade() -> Clasp::ClaspFacade &
Get a pointer to the underlying clasp facade.
Definition solver.hh:757
void interrupt() noexcept
Interrupt the running (or next search).
void parse(std::span< std::string_view const > const &files)
Parse the given files.
auto backend() -> UBackendHandle
Get a handle that provides access to the backend to add atoms and rules.
void block_main(bool block)
Block execution of the main function in scripts.
Definition solver.hh:780
auto buf() -> Util::OutputBuffer &
Get the output buffer.
Definition solver.hh:745
void main()
Ground and solve a program.
auto const_map() -> Input::ConstMap const &
Get the const map.
auto print_summary(bool final)
Print per step summaries.
Definition solver.hh:817
void join_includes(BuiltinIncludes includes)
Enable the given includes.
auto ground(ProgramParamVec const ¶ms, Ground::ScriptCallback *ctx, Util::StopFlag *stop=nullptr) -> GroundResult
Ground the program.
auto clasp_stats() -> Potassco::AbstractStatistics const &
Get the statistics.
Definition solver.hh:766
auto get_lock() -> CallbackLock &
Get the solvers callback lock.
Definition solver.hh:777
void accept(Ground::ProfileNode::Visitor const &visit) const
Accept a visitor for the profile nodes.
Definition solver.hh:820
void add_const(String name, Symbol value)
Define a constant.
auto sym_tab() -> SymbolTable &
Get the symbol table.
Definition solver.hh:807
Solver(Clasp::ClaspFacade &clasp, Clasp::Cli::ClaspCliConfig &config, Logger &log, SymbolStore &store, Scripts &scripts, Input::RewriteOptions ropts, SolverOptions sopts, FILE *out=stdout)
Create a solver object.
auto clasp_facade() const -> Clasp::ClaspFacade const &
Get a pointer to the underlying clasp facade.
Definition solver.hh:760
void set_parts(std::optional< Input::StmParts > parts)
Set the program parts to ground.
Definition solver.hh:795
void register_propagator(UPropagator propagator)
Register the given propagator with the control object.
auto map_model(Clasp::Model const &mdl) -> Model &
Map the given clasp model to the clingo one.
auto config() -> ClingoConfig &
Only non-null in solving mode.
Definition solver.hh:763
auto solve(USolveEventHandler handler={}, PrgLitSpan assumptions={}, SolveMode mode=SolveMode::none) -> USolveHandle
Solve the program.
void show(Input::SharedSig const &sig)
Show the given signature.
Definition solver.hh:804
void output_unprocessed_program(std::ostream &out)
Output the current unprocessed program.
auto start_ground(ProgramParamVec params, UGroundEventHandler handler) -> GroundHandle
Ground the program asynchronously.
auto user_data() -> void *&
Get user data for C integration.
Definition solver.hh:786
auto get_mode() const -> AppMode
Get the application mode.
Definition solver.hh:783
Helper to output symbols.
Definition solver.hh:574
void init(CppClingo::Control::BaseView &view, std::ostream &out)
Initialize the table before output.
void end_step()
Output atoms in extended aspif format.
auto out() -> std::ostream &
Get the underlying output stream.
Definition solver.hh:583
void begin_step()
Output ids of shown terms in extended aspif format.
Map from symbols to show term ids.
Definition solver.hh:135
auto size() const -> size_t
Get the number of mapped symbols.
Definition solver.hh:202
auto add(Symbol sym, F &&fun) -> prg_id_t
Add a new symbol to the map.
Definition solver.hh:148
auto end() const -> Map::const_iterator
Get an iterator over the symbol id pairs in the map pointing to the end of the sequence.
Definition solver.hh:214
void add(Symbol sym, prg_id_t id)
Add a symbol with the given id.
Definition solver.hh:162
auto index(Symbol sym) const -> size_t
Get the index of the symbol.
Definition solver.hh:197
auto term_id(size_t i) const -> prg_id_t
Get the id at the given index.
Definition solver.hh:172
auto begin() const -> Map::const_iterator
Get an iterator over the symbol id pairs in the map pointing to the beginning of the sequence.
Definition solver.hh:208
Util::ordered_map< SharedSymbol, prg_id_t > Map
The container storing the mapping (internal).
Definition solver.hh:138
auto symbol(size_t i) const -> Symbol
Get the symbol at the given index.
Definition solver.hh:183
RAII helper to unlock a mutex.
Definition solver.hh:560
unlock_guard(const unlock_guard &)=delete
Destructor re-locking the mutex.
unlock_guard(M &mut)
Constructor unlocking the mutex.
Definition solver.hh:563
std::function< void(std::variant< std::pair< std::string_view, bool >, std::pair< ProfileStats const *, ProfileType > >, size_t)> Visitor
The type of visitor function to use for visiting profile nodes.
Definition profile.hh:106
Interface to call functions during parsing/grounding.
Definition script.hh:28
void call(Location const &loc, std::string_view name, SymbolSpan args, SymbolVec &out)
Call the function with the given name and arguments.
Definition script.hh:35
Interface to execute code in source files.
Definition script.hh:12
The Location of an expression in an input source.
Definition location.hh:44
Simple logger to report message to stderr or via a callback.
Definition logger.hh:63
Class similar to Potassco::TheoryData but with automatic id generation.
Definition backend.hh:17
A point in an input source.
Definition location.hh:15
Abstract class connecting grounder and solver.
Definition backend.hh:54
Reference to a string stored in a symbol store.
Definition symbol.hh:18
A store for symbols.
Definition symbol.hh:454
Variant-like class to store symbols stored in a symbol store.
Definition symbol.hh:225
Abstract class connecting grounder and theory data.
Definition backend.hh:232
Create an output buffer that bears some similarities with C++'s iostreams.
Definition print.hh:26
Output stream with an underlying OutputBuffer.
Definition print.hh:202
Helper class to signal stopping of grounding.
Definition sync.hh:11
std::unique_ptr< Propagator > UPropagator
A unique pointer to a propagator.
Definition solver.hh:525
std::unique_ptr< SolveHandle > USolveHandle
A unique pointer for a solve handle.
Definition solver.hh:404
ModelType
Enumeration of available model flags.
Definition solver.hh:121
ReifyFlags
Enumeration of available options for the reification backend.
Definition solver.hh:81
IStop
Stop condition for incremental mode.
Definition solver.hh:57
SolveMode
The available solve modes.
Definition solver.hh:459
BuiltinIncludes
Bitset of enabled builtin includes.
Definition parse.hh:23
SymbolSelectFlags
A bit set of symbol selection flags.
Definition solver.hh:109
AppMode
Enumeration of available application modes.
Definition solver.hh:65
std::unique_ptr< SymbolTable > USymbolTable
A unique pointer to a symbol table.
Definition solver.hh:602
std::unique_ptr< SolveEventHandler > USolveEventHandler
A unique pointer for an event handler.
Definition solver.hh:454
SolveResult
The solve result.
Definition solver.hh:328
std::unique_ptr< Model > UModel
A unique pointer to a model.
Definition solver.hh:322
ConsequenceType
Enumeration of available consequence types.
Definition solver.hh:128
std::unique_ptr< BackendHandle > UBackendHandle
A unique pointer to a backend handle.
Definition solver.hh:516
BackendType
Enumeration of available output formats when in solving mode.
Definition solver.hh:73
std::unique_ptr< Script > UScript
A unique pointer to a script.
Definition solver.hh:35
std::unique_ptr< GroundEventHandler > UGroundEventHandler
A unique pointer to a ground event handler.
Definition solver.hh:636
@ cautious_consequences
The model represents a set of cautious consequences.
@ model
The model represents a stable model.
@ brave_consequences
The model represents a set of brave consequences.
@ reify_scc
Compute and print SCCs.
@ reify_step
Add step numbers.
@ none
Do not consider solve result.
@ sat
Stop when satisfiable.
@ unknown
Stop when interrupted.
@ async
Solve asynchronously in background threads.
@ yield
Yield models while solving via SolveHandle::model().
@ shown
Select shown atoms and terms.
@ theory
Select symbols added by theory.
@ parse
Stop processing after parsing.
@ ground
Stop processing after grounding.
@ rewrite
Stop processing after rewriting.
@ solve
Stop processing after solving.
@ satisfiable
The search produced at least one model.
@ exhausted
The search has been exhausted.
@ true_
The literal is a consequence.
@ false_
The literal is not a consequence.
@ smodels
Print program in smodels format.
@ clasp
Standard solving mode: use the normal backend (Clasp)
@ aspif
Print program in ASP intermediate format.
@ reify
Print program as reified facts.
int32_t prg_lit_t
A program literal.
Definition backend.hh:27
std::unique_ptr< OutputStm > UOutputStm
Unique pointer for statement output.
Definition output.hh:253
std::span< prg_lit_t const > PrgLitSpan
A span of program literals.
Definition backend.hh:37
int32_t prg_weight_t
A weight used in weight and minimize constraints.
Definition backend.hh:33
int64_t prg_sum_t
Type to represent sums of weights.
Definition backend.hh:35
uint32_t prg_id_t
An id to refer to elements of a logic program.
Definition backend.hh:16
std::unique_ptr< ProgramBackend > UProgramBackend
A unique pointer for a program backend.
Definition backend.hh:229
std::span< Symbol const > SymbolSpan
A span of symbols.
Definition symbol.hh:218
std::vector< Symbol > SymbolVec
A vector of symbols.
Definition symbol.hh:220
GroundResult
Available grounding results.
Definition core.hh:187
@ unsatisfiable
The grounding was successful but an inconsistency was derived.
@ interrupted
The grounding was interrupted.
tsl::ordered_map< Key, T, Hash, KeyEqual, Allocator, ValueTypeContainer, IndexType > ordered_map
Alias for ordered maps.
Definition ordered_map.hh:16
tsl::hopscotch_map< Key, T, Hash, KeyEqual, Allocator, NeighborhoodSize, StoreHash, GrowthPolicy > unordered_map
Alias for unordered maps.
Definition unordered_map.hh:17
#define CLINGO_ENABLE_BITSET_ENUM(E,...)
Opt-in macro for enabling bit operations for a given enum type.
Definition enum.hh:18
Options for the solver.
Definition solver.hh:89
std::string iquery
The name of the query atom.
Definition solver.hh:103
BackendType backend_type
Output format to use when in solving mode.
Definition solver.hh:93
size_t imin
The minimum number of incremental steps.
Definition solver.hh:97
bool single_shot
Restrict to single shot-solving.
Definition solver.hh:105
AppMode mode
Operation mode of the solver.
Definition solver.hh:91
std::optional< size_t > imax
The maximum number of incremental steps.
Definition solver.hh:99
ReifyFlags reify_flags
Reification flags.
Definition solver.hh:95
IStop istop
The stop condition for the incremental mode.
Definition solver.hh:101