Git Product home page Git Product logo

clingo-rs's Introduction

clingo-rs Build Status Latest Version Rust Documentation

Rust idiomatic bindings to the clingo library. Clingo version 5.6.2.

Usage

Default - dynamic linking

Per default the crate uses the clingo library via dynamic linking. It is assumed that a clingo dynamic library is installed on the system. While compile time the environment variable CLINGO_LIBRARY_PATH must be set. For example:

export CLINGO_LIBRARY_PATH=/scratch/miniconda3/envs/test/lib

And for running the code that dynamically links to clingo make sure to have the clingo library in your LD_LIBRARY_PATH.

Have a look a at the clingo Readme for different ways of obtaining the binary releases of clingo.

Using static-linking

You can also use the clingo library via static linking. The build system will attempt to compile clingo for static linking on your system. To build clingo for static linking you need the following tools installed:

  • a C++14 conforming compiler
    • at least GCC version 4.9
    • Clang version 3.1 (using either libstdc++ provided by gcc 4.9 or libc++)
    • at least MSVC 15.0 (Visual Studio 2017)
    • other compilers might work
  • the cmake build system
    • at least version 3.18 is recommended
    • at least version 3.1 is required

The recommended way to use the optional static linking support is as follows.

[dependencies]
clingo = { version = "0.8.0", features = ["static-linking"] }

Using derive macro

The crate provides a derive macro to help ease the use of rust data types as facts.

In your Cargo.toml add:

[dependencies]
clingo = { version = "0.8.0", features = ["derive"] }

In your source write:

use clingo::{ClingoError, FactBase, Symbol, ToSymbol};

#[derive(ToSymbol)]
struct MyPoint {
    x: i32,
    y: i32,
}

let p = MyPoint { x: 4, y: 2 };
let mut fb = FactBase::new();
fb.insert(&p);

The macro performs a conversion to snake case. This means the corresponding fact for MyPoint{x:4,y:2} is my_point(4,2).

Examples

cargo run --example=ast 0
cargo run --example=backend 0
cargo run --example=configuration
cargo run --example=control 0
cargo run --example=model 0
cargo run --example=propagator 0
cargo run --example=solve-async 0
cargo run --example=statistics 0
cargo run --example=symbol 0
cargo run --example=symbolic-atoms 0
cargo run --example=theory-atoms 0
cargo run --example=inject-terms 0
cargo run --example=version

Contribution

How to make a contribution to clingo-rs?

Any contribution intentionally submitted for inclusion in the work by you, shall be licensed under the terms of the MIT license without any additional terms or conditions.

clingo-rs's People

Contributors

aurelien-naldi avatar maltet avatar peacememories avatar pluehne avatar samuelpilz avatar sthiele avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

clingo-rs's Issues

Add information about timeout

I'm trying to use the wait function on SolveHandle, but can't figure out what unit the timeout is expected to have. Additional information about the parameter might be nice. Alternatively, timeout's type could be changed to std::time::Duration, but that would mean an api change.

clingo-rs/src/lib.rs

Lines 4783 to 4795 in 7cd4f8b

/// Wait for the specified amount of time to check if the next result is ready.
///
/// If the time is set to zero, this function can be used to poll if the search is still active.
/// If the time is negative, the function blocks until the search is finished.
///
/// # Arguments
///
/// * `timeout` - the maximum time to wait
pub fn wait(&mut self, timeout: f64) -> bool {
let mut result = false;
unsafe { clingo_solve_handle_wait(self.theref, timeout, &mut result) }
result
}

Thanks!

(With some information, I could assemble a PR for either solution, if that helps)

Plans for the next release?

First of all, thanks for taking the time to look over the recent pull requests that I submitted ๐Ÿ‘.

I know that this isnโ€™t a popular type of question, but can you share when you plan to publish the next release of clingo-rs? Iโ€™m close to finishing a new version of anthem that depends on the recent fixes I submitted to clingo-rs (and I can use the version in the master branch just fine for development), but I wonโ€™t be able to publish my crate to crates.io until a new clingo-rs release containing these fixes is tagged.

Iโ€™m just asking so that I can decide whether itโ€™s worth waiting for a release or whether I should just bundle with my crate a patch for clingo-rs 0.6.0 that applies the fixes in question ๐Ÿ™‚.

Consider adding error type or error variant for unrecognized Symbol

While thinking about how to implement more complex FromSymbol implementations, especially for enums I think there should be some kind of "unrecognized symbol" error type, especially if a library user wants to ignore extraneous symbols.
A workaround for this could of course be to have an Unrecognized(Symbol) variant in every enum where you want to ignore unrecognized symbols, so I'm not sure which method to handle this is nicer.

Background

Let's say you want to convert symbols to a data structure like:

enum Foo {
    Bar(&'static str, u16),
    Baz(i32)
}

to parse symbols like bar("asdf", 5) and baz(-3), but you also expect other symbols in the input, like other(el23, "somestr")

One method would be to have from_symbol return an error type that can be compared to something like UnrecognizedSymbol and actively ignoring that case.
Another would be to write the enum as:

enum Foo {
    Bar(&'static str, u16),
    Baz(i32),
    Unrecognized(Symbol)
}

And actively ignoring the Unrecognized variants in your result.

impl Drop for SolveHandle?

Background: On my way of figuring out how multi-shot works, I stumbled across this issue: ClingoError(InternalError { msg: "Call to clingo_control_solve() failed", code: Logic, last: "logic error: check(\'config_ && program() && !solving()\') failed" }). The error happens when control.solve(...) is called but the returned handle is not closed/cancelled.

When using the question-mark operator all over the place, it is not trivial to reason about all code paths and which should cancel the solve handle and when. Rust has no finally control block, which would be the typical place for closing the handle. Drop would provide a similar feature in Rust.

To write a correct call to solve that extracts the symbols of a single model and releases the solve handle, I now have to write the following code (I suppose)

fn get_first_model(ctrl: &mut Control) -> Result<Vec<Symbol>, MyError> {
    let mut solve_handle = ctrl.solve(clingo::SolveMode::YIELD, &[])?;

    let model = solve_handle
        .model()
        .map_err(Into::into)
        .and_then(|m| m.ok_or(MyError::NoModel))
        .and_then(|m| m.symbols(clingo::ShowType::SHOWN).map_err(Into::into));
    solve_handle.close()?;
    let model = model?;
    Ok(model)
}

With a Drop impl, the code could look like this (which I had before I knew about close):

fn get_first_model_with_drop(ctrl: &mut Control) -> Result<Vec<Symbol>, MyError> {
    let mut solve_handle = ctrl.solve(clingo::SolveMode::YIELD, &[])?;
    let model = solve_handle
        .model()?
        .ok_or(MyError::NoModel)?
        .symbols(clingo::ShowType::SHOWN)?;
    Ok(model)
}

I know that the issue with impl Drop is that a possible error would be discarded. Also the documentation seems to hint that cancel blocks on the finishing of the solver.

Any ideas?

Error on Windows

Hello,
This may be a Clingo problem, not a clingo-rs problem, but running the command:

cargo run --example=control 0

produces a long string of errors. I've attached the end of the stream here:

clingo/libclingo/src/control.cc(1526): error C2491: 'clingo_register_script_': definition of dllimport function not allowed
clingo/libclingo/src/control.cc(1531): error C2491: 'clingo_script_version_': definition of dllimport function not allowed
clingo/libclingo/src/control.cc(1535): error C2491: 'clingo_main_': definition of dllimport function not allowed
clingo/libclingo/src/control.cc(1617): error C2491: 'clingo_options_add': definition of dllimport function not allowed
clingo/libclingo/src/control.cc(1624): error C2491: 'clingo_options_add_flag': definition of dllimport function not allowed
clingo/libclingo/src/control.cc(1629): error C2491: 'clingo_main': definition of dllimport function not allowed
exit code: 2

--- stderr


error occurred: Command "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.22.27905\\bin\\HostX64\\x64\\cl.exe" "-nologo" "-MD" "-Z7" "-Brepro" "-I" "clingo/libclingo" "-I" "clingo/libgringo" "-I" "clingo/clasp/libpotassco" "-I" "clingo/clasp" "-I" "clingo/clasp/app" "-I" "generated" "-O3" "-std=c++14" "-DNDEBUG=1" "-DWITH_THREADS=0" "-FoC:\\Users\\d4hin\\repos\\clingo-rs\\target\\debug\\build\\clingo-sys-f51e29c07891a25e\\out\\clingo/libclingo/src\\control.o" "-c" "clingo/libclingo/src/control.cc" with args "cl.exe" did not execute successfully (status code exit code: 2).

Any advice on this? Have you successfully built/run on Windows?

Creating `Atom`s

We're using the rust clingo bindings to generate grounded programs that we would then like to solve with a few facts added as assumptions. the assumptions argument of Control::solve seems like the way to go, but I can't find any way to generate a Literal or Atom, from a Symbol or otherwise. I would greatly appreciate any advice :)

building with stable rust instead of nightly

I would like to use this crate without having to rely on the nightly toolchain. I could build clingo-rs with the stable toolchain (using rust 1.31) after replacing std::ptr::Unique with std::ptr::NonNull (according to rust-lang/rust#27730, Unique will remain unstable for ever).

After this change, "cargo test" fails (but it was already failing before) but all examples seem to run properly.

Do you think it is a valid change or is there something which can be corrupted by using NonNull instead of Unique?

Return `&'static str` instead of `&str` in `Symbol` functions

As far as I can tell, clingo internally does not free allocated strings ( taken from here ). On one hand this can be an issue with long running applications, on the other hand this would mean all functions in this library that return string slices could correctly return &static str.
Besides being correct this would have the benefit of allowing consumers of the library to store the slices without first allocating a string.

PS:

This has the additional benefit of stating up front what the memory behavior of the library is going to be. Because strings were bound to the lifetime of symbols, which themselves were only ids, my first worry was that there would be a soundness bug somewhere ๐Ÿ˜…

ast example fails to compile

Dear All

Most probably the issue is at my end but I wonder if you have any ideas.

cargo build works and all but one of the examples runs, but the ast example fails with 12 warnings and this error:

$ cargo run --example=ast 0
... 12 warnings
error: linking with `cc` failed: exit status: 1
  |
  = note: env ...
  = note: Undefined symbols for architecture x86_64:
      "_clingo_program_builder_init", referenced from:
          clingo::ast::ProgramBuilder::from::hf7d9290884ba38a9 in ast-77276d986174349c.9q7shmipeyu9bfa.rcgu.o
    ld: symbol(s) not found for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)

error: could not compile `clingo` (example "ast") due to previous error

cargo test fails with a similar error:

...
error: could not compile `clingo` (test "integration_test") due to previous error

My clingo works normally as far as I can tell. I have CLINGO_LIBRARY_PATH set.

This is the version of clingo I have:

$ clingo -v
clingo version 5.5.0
Address model: 64-bit

libclingo version 5.5.0
Configuration: without Python, without Lua

libclasp version 3.3.6 (libpotassco version 1.1.0)
Configuration: WITH_THREADS=1
Copyright (C) Benjamin Kaufmann

License: The MIT License <https://opensource.org/licenses/MIT>

Am I missing something?

With thanks and best wishes

Ivan

Add new rule that does not introduce new Atoms

I am trying to avoid grounding, while adding new rules to the underlying logic program, which means adding a new program that extends the old program by the new rules is not an option.

I was planning to use rule, which accepts &[Atom] for the head-parameter. Among the examples I could only find cases where the head of the added rule
is either empty, or introducing new atoms.

  1. How do I add rules that do not introduce new atoms in the head?
  2. Is there a way to convert a Symbol or a Literal to an Atom?

I might just fail to see it.

clingo-rs versions 0.7.x unable to locate libclingo

Hi,

I have some problems building & rust program with clingo-rs version 0.7.2 and 0.7.3.

Environment :

  • Debian linux 11.
  • Clingo is installed via anaconda in a dedicated environment (clingo 5.5.0, as the clingo-rs 0.7.x crates claim to rely on this version)
  • environment CLINGO_LIBRARY_PATH is initialized to the lib directory in the environment where libclingo.so.4.0 and the two symbolic links liblingo.so.4 and libclingo.so are present.
  • cargo build complains that, during linking, it cannot find the libclingo library.

I saw that clingo-rs is depending on clingo-sys version 0.7.1. Is it normal ?

I have no problem with the 0.6 version of clingo-rs.

Any clues ?

(sorry if creating an issue is a bit overkill for such a problem, but the mailing list sign-up process on sourceforge seems to be stucked : I never receive the confirmation email.)

Assign external variables

I would like to use clingo in Multi-shot mode. This seems possible via the use of external atoms and assign_external. However, how do I get the literal or atom for the correct external symbol?

Idea:

asp file contains #external p(1;2;3).
rust program: control.assign_external(<description of "p(1)">, TruthValue::True);

Solve with mut ref to Control object

As far as I can tell versions <0.7 used a SolveHandle object based on a mutable reference to clingo_solve-handle_t.

impl<'a> SolveHandle<'a> {

As opposed to

pub struct GenericSolveHandle<

SolveHandle does not move the underlying Control object. This is in particular useful, as one's not forced to construct a new Control object whenever enumerating answer sets by means of solve or all_models.

This is why I propose to add the old SolveHandle implementation.

Question about clingo::parse_program_with_logger function

Hello! I am trying to fix the following issue in the Anthem source code:
Given a program "p(X) :- X >= 1." Anthem is translating the >= into a >. A correct string ("p(X) :- X >= 1") is being passed to the clingo function parse_program_with_logger, but an incorrect clingo::ast::Statement is being returned. Anthem does provide custom implementations of the Logger and StatementHandler traits, but I'm pretty sure the bug is not being introduced within these as the incorrect clingo::ast::Statement is produced prior to being passed to the only function within StatementHandler (on_statement). Do you have any recommendations? Thank you!

Remove 3.0.1 release tag?

I stumbled upon the v3.0.1 tag, which appears to be made in error. The tag is for a commit made almost two years ago and behind the master branch by more than 100 commits. The latest release, v0.6.0, is more recent despite its lower version number.

Iโ€™d suggest removing the v3.0.1 tag. Itโ€™s not been published on crates.io as far as I can tell, so the risk of others depending on the v3.0.1 version is low. However, I think that the tag is still problematic because it takes precedence over actually newer tags (such as v0.6.0) according to semantic versioning.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.