potassco / clorm

🗃️ A Python ORM-like interface for the Clingo Answer Set Programming (ASP) reasoner
https://clorm.readthedocs.io
MIT License
52 stars 5 forks source link

Easy loading of clorm facts from a file #50

Closed daveraja closed 3 years ago

daveraja commented 3 years ago

A clorm.FactBase can be easily written to a file by using the FactBase.asp_str() function to generate an ASP parseable string and then writing it to a file. But currently there is no easy way to load a file of facts into a factbase.

Instead you have to use a clingo.Control object to load the file then to either call the solver to generate the model and extract the facts from the model or query the clingo.Control.symbolic_atoms property to extract the facts. This is a hacky process and not intuitive if all you want to do is to load a set of facts into a factbase.

It would be useful to have functions that directly parse a string or file into a factbase. So, the idea would be to use the existing clingo parse_files and parse_string functions to generate the AST and extract the facts from there.

There is however one complication. Since clorm 1.3.0, to deal with the issue of clingo.Symbol objects not being able to be freed from memory, there is a NOCLINGO mode where clorm facts use an internal proxy symbol object. I wouldn't want any new functions to break this new feature of clorm. So I think I would have to provide my own basic fact parser and depending on the mode use the real clingo parser or use the hacky internal fact parser. This is not ideal but is probably the only option.

daveraja commented 3 years ago

Created functions parse_fact_files() and parse_fact_string() to convert a list of facts (ground atoms) to a FactBase. You must specify the list of predicates to unify against. There are some flags that can be set to force an exception to be raised if there is no matching predicate for a fact or if there are more than facts in the file/string.

This should work reliably for reading a string/file that was written from a factbase. But it still needs to be made more robust for other cases. For example, it will break if there is an @-function. Also not resolved the issue of using clingo.Symbol objects.

daveraja commented 3 years ago

Added some more detection for facts containing @-function and some other things so should be more robust. Will be part of a v1.3.2 release soon.

Note: these functions currently only work for NOCLINGO mode and will throw a NotImplementedError if clorm is in NOCLINGO mode. Closing the issue for now.