Category Archives: Prolog

Editing ECLiPSe constraint logic code in the Eclipse IDE

One of our projects uses the ECLiPSe constraint logic programming language (a more powerful flavor of Prolog) in conjunction with Java (which is a good way to integrate graphics, unit testing, etc). One of the most popular developer tools for Java is the Eclipse IDE (yes, same name, totally different application), and we’d like to find a similarly-powerful editor for our pure-Prolog (.pro) and ECLiPSe (.ecl) files — one that provides indicators of (im)balanced parens, coloring of built-in predicates and syntax, and maybe code completion and compiler warnings.

ECLiPSe had a project called Saros on sourceforge that aimed to provide all this functionality, plus a debugger. Unfortunately, I wasn’t able to get any of these features working in its 1.0 version (after installing it as a plugin in the IDE). I’ve also heard that development on Saros has stopped.

However, I would be happy just getting paren-balancing, and I found a way to do that in the Eclipse IDE:

  1. Go to Window | Preferences
  2. Select General | Content Types in the left pane, and then on the right, select Text in the Content Types list.
  3. In the File Associations list below that on the right side, you should see “*.txt (locked)”. Click the Add button and add “.ecl” when prompted for the Content Type. Do this again for .pl files (or .pro files, as I prefer, to distinguish from Perl files).
  4. Back in the left pane, select General | Editors | File Associations.
  5. On the right side, add “.ecl” and “.pl” (or “.pro”) if they aren’t already present.
  6. Select “*.ecl” in the upper list on the right. Then in the lower listbox, if “Standalone Structured Source Editor (default)” isn’t shown, use the Add button to select “Standalone Structured Source Editor” and then click the Default button.
  7. Select “*.pl” (or “*.pro”) in the upper list, and make sure it has the same default editor.
  8. Click OK.

Now, if you open an .ecl or .pro file using either the Java or Debug perspective, and you place the text cursor after a ) or ] that is balanced, you will see a blue rectangle around the corresponding ( or [. There is no indicator if the ) or ] is not balanced.

Note that if you quit the IDE and launch it again, you will get a warning dialog about “Unsupported content type in editor.” I believe that’s because we selected “Text” in the Content Types preferences – there being no way to add a content type for ecl and pro files in particular – and that this resulted in our files being “locked” to the generic text editor in the File Associations preference. However, by marking the structured text editor as the default, we override that locking, and you’ll notice that if you dismiss the warning, paren-balancing still works. So, I selected the checkbox for “Do not show this message again” in the warning. Relaunching the IDE again gives me paren-balancing with no warning dialog.

UPDATE: Christian Wirth said on the eclipse-clp-users mailing list: “You have to install the Web Tools Project also.”

Print Friendly, PDF & Email

How to avoid unexpected backtracking in Prolog fail loops

A Prolog fail loop is a way of doing iteration in Prolog. For example, in this predicate (methods and functions are called predicates in Prolog because the method name is used in the predicate position of propositions used to write Prolog code), we iterate over all facts in the knowledge base that match the given ‘edge’ pattern:

buildEdges(MiddleNode, RightNode) :-
   LeftNode #< MiddleNode, %ECLiPSe feature: constrain LeftNode to be an int smaller than MiddleNode
   edge(LeftNode, MiddleNode),
   addEdge(LeftNode, RightNode),
   fail.

The reason that putting ‘fail’ at the end leads to iteration is that Prolog automatically searches for other ways of satisfying conditions, unless you tell it not to. So, if there is a fact matching the ‘edge’ pattern, and if ‘addEdge’ also succeeds, then when the interpreter reaches ‘fail’ it “backtracks” to the addEdge call to see if there were any unexplored ways of satisfying it (aka, it checks if there were any other “choicepoints”). If there were such unexplored options in addEdge, the interpreter tries the first one; if this succeeds, we return to ‘fail’; if the first one fails, it tries any others for addEdge. Once the options in addEdge are exhausted, the interpreter takes another step “upward” to see if there were any unexplored matches for the ‘edge’ pattern.

As you can see, forcing backtracking by putting ‘fail’ at the end of your conditions is one way of implementing iteration over a set of matching facts. But what you may not have expected, and what you probably don’t want, is for the interpreter to try calling ‘addEdge’ several times before looking for the next edge match. There are two standard ways of avoiding this:

  1. Put a condition at the start of all definitions of ‘addEdge’ that allow it to be entered only under the intended circumstances. (This isn’t a good match for the current example, because you can’t specify a condition that says “only call me once when iterating over edges”.)
  2. Put a cut (denoted with an exclamation point, !, in Prolog) at the end of all definitions of addEdge. A cut tells the interpreter to forget about any other choicepoints for this call of this predicate. Other tutorials about fail loops neglect to emphasize that the cut must be put at the end, because otherwise backtracking from the fail loop will explore any choicepoints remaining after the cut, even ones in your definitions of ‘addEdge’.

Side note: One can replace ‘fail’ with a condition to get do-while behavior instead of exhaustive iteration. And if one wanted to isolate a block of code for iteration (say, you want to avoid repeating the #< step), one could put “repeat,” at the start of the block, and then backtracking would never go above that point.

Print Friendly, PDF & Email

Porting Amzi prolog to ECLiPSe

While Amzi Prolog has the best debugger I’ve seen for any flavor of Prolog (and I’ve evaluated many flavors), it’s become clear that my project needs the ability to constrain variables before committing to particular values. This is the key feature difference that leads me to want to port to ECLiPSe, a flavor of Prolog where constraint propagation is the main focus. And there are other features of ECLiPSe that are very appealing:

  • Easily embedded in a Java application (via a jar that implements a JNI bridge to the native ECLiPSe executable) that allows for loose coupling through queues-and-listeners or even asynchronous queues.
  • Similar library support for manipulating terms, strings, lists, etc as other Prolog flavors
  • An Eclipse IDE plugin, Saros. (It’s not quite usable for me in its current stage but I hear a new version is imminent. And it has a Tk-based UI including debugger that’s pretty good.)

Here are the changes I had to make to my Amzi code so it would run in ECLiPSe:

  • Changed all calls using consult/1 or debug_consult to [...comma-separated filenames...]
  • Changed ‘/’ when used in predicate names to ‘_’
  • Changed import(list) to import(lists)
  • Changed all abolish calls to retractall (although this doesn’t seem absolutely necessary)
  • Changed string_term(String,Term) to term_string(Term,String)
  • Changed stringlist_concat calls to concat_string
  • Discovered that many of my variables were singletons, and changed them to start with ‘_’ (so they would be self-documenting singletons and not trigger a compiler warning)
  • Added dynamic declarations for all my dynamic predicates (Amzi probably doesn’t provide a warning when these are asserted or retracted without having been so declared)
  • Changed my (retractall(predicate(_,...)) ; true) pattern to just retractall(predicate(_,...)), since retractall never fails in ECLiPSe

I’m grateful to Dennis Merrit and Chip Eastman of Amzi for all their help in getting my initial Amzi app working, and for their excellent documentation of Prolog and Building Expert Systems.

Print Friendly, PDF & Email

Micro-theory of gaze

Gaze (aka “looking at something”) can be automatic (scanning the environment), strategic (getting a closer look at something interesting), and even communicative (indicating interest, anger, or eagerness to cooperate). I’m aiming for rules that would allow not just simulating an agent, but allow an agent to predict or explain another agent.

Following my evaluation of potential inference tools last week, I’ve tentatively settled on using either JIProlog or AmziProlog because Prolog is the only rule language that allows me to be expressive enough, and these two tools allow Java and Prolog to invoke each other (while Prolog is embedded in a Java Runtime (JVM)).

It’s important that the tool run in a JVM because I want outside users not to be restricted to using the same platform as I do, and because I want to use industry-standard libraries for graphics, etc.

The high-level architecture of my system (named ATOM = automated theory of mind) is:

  • A set of Prolog facts for each agent representing that agent’s initial mental attitudes.
  • A set of Prolog rules for each agent representing what mental attitudes cause others under what conditions.
  • A Java object that simulates a physical environment. When the Prolog module infers an “attempt” attitude, this is converted into a call into the Java module to see what follows from the attempt. When the Java module determines a causal change that should be observable to an agent, then agent-specific “percept” facts are injected into the Prolog module and may trigger new inference there.
  • A set of JUnit tests that swap out files for different initial states in Prolog (and different simulated environments in Java) to verify that the outputs match expected values. There may also be unit tests that swap out rules to test predictions about agents that veer from the “norm”.

Because a fair amount of research goes into the formulation of each rule, each rule will be in its own Prolog file accompanied by comments describing the scenarios that inspired the rule (also present as unit tests) and the particular pages in articles that inspired the rules or any changes to them. (This may seem fussy, but a career in reading related research tells me we all need to be much better at providing such “provenance”.)

As mentioned in the summary above, gaze is a good human behavior to start with. But read here for even better motivation: Vertegaal et al, 2001: “Eye Gaze Patterns in Conversations: There is More to Conversational Agents Than Meets the Eyes”.

Some initial generalizations I wanted to capture:

  • The blurriness of peripheral percepts is high.
  • Moving the eyes in the dir of a peripheral percept will change it to a focal percept, and whatever was focal will become peripheral.
  • The blurriness of a focal percept is usually less than if it were peripheral.
  • For intriguing resemblances with high blurriness, one would want less blurriness.
  • For intriguing resemblances in focus, one usually wants to ignore peripheral resemblances that are less intriguing.
  • For surprising peripheral items, one automatically looks even if intending not to.

I want to write rules for these in such a way that, not only could the rules drive the behavior of one agent, but they could also be used by that agent to explain the gaze behavior of another agent that one is focused on. That is, it’s the start of an automated “theory of mind”.

Print Friendly, PDF & Email

Comparison of tools for rule-based inference

Although I started writing pseudo-code rules a few weeks ago, I’ve suspended that while I look for a tool for writing and testing rules so I don’t assume too much about the quality of the rules so far. This post describes what I’m looking for and the tools I’ve looked at. I’m likely to go with JIProlog or Amzi Prolog (and perhaps later, ECLiPSe).

I’m looking for an expert system-type tool that offers these features:

  1. Simple, first-order-predicate-calculus (FOPC) syntax rather than C-style code
  2. Can be embedded easily in Java programs
    • Prefer Java because it’s platform-independent
    • Java has widespread use in simulation research that I might use or partner with
  3. Has a large, active community that might be interested in my work, and from whom I might get tech help
  4. Has good IDE (editor tool) support for auto-completion, syntax-highlighting, breakpointing, etc
  5. Allows for easy changing of any rules governing beliefs, desires, and intentions (aka BDI)
  6. Has a way of tracking what papers/scenarios influenced the conditions and actions of each rule (aka “provenance tracking” in my terms)

This is what I’ve found:

Jason

PROs

  • Uses a Prolog-like syntax (i.e. fairly similar to FOPC)
  • Has a jEdit-based IDE that allows inspecting the mind of each agent, and history of actions among the agents
  • There is a book with in-depth how-to info (which I’ve ordered)

CONs

  • Structured as a “BDI” system, which sounds at first like a big positive, but on deeper inspection seems to mean that it handles beliefs, desires, and intentions in a pre-defined way. I’m not sure yet how limiting this might be.
  • I asked the creators if there was a compelling reason to use it over a simple inference engine (apart from the ability of MAS frameworks to allow agents to run over a network), and they said there isn’t much advantage in that respect.
  • Might not support back-chaining or facts with universally-quantified vars (however, this might be possible in Jason and all Rete-based systems by encoding such facts as rules with “true” as their antecedent)

JADEX

PROs

  • Java based
  • Has its own BDI debugger tool

CONs

  • BDI support seems “cooked in” and likely to be hard to change
  • Rules must be expressed in an especially verbose form of xml
  • Might not support back-chaining or facts with universally-quantified vars

JAM

PROs

  • Java-based BDI
  • Distinguishes between achievement goals and maintenance goals
  • Seems more comprehensive in BDI concepts than similar systems

CONs

  • Procedural rather than FOPC-style syntax
  • Seems to have same limits on expressiveness (i.e. fairly restricted compared to FOPC or Prolog) as other forward-chaining expert system tools using the Rete clause-indexing algorithm

Discrete Event Calculus Reasoner (DECL)

PROs

  • The “event calculus” (EC) is a set of rules for dealing with the frame problem (aka “commonsense law of inertia” — things tend to stay as they are unless explicitly changed). The frame problem occurs when a rule system knows a fact was true in the past but isn’t sure whether to assume it’s still true. CCSS is likely to run into the frame problem often, since our systems are likely to be triggered by combinations of mental attitudes, but some of those attitudes may seem “stale” due to being triggered in the past. The “discrete” part in the name is due to assuming a timeline with discrete points rather than a continuous one.
  • Has a book that shows how to encode BDI and OCC in EC

CONs

  • Requires integrating Unix env, Python, “PLY”, and one of a small set of SAt logic solvers. This seems too brittle and platform-specific to me.
  • While EC has a good-sized community, this inference engine seems to have a small one
  • Seemingly no IDE support
  • Might not support  facts with universally-quantified vars

Clips

PROs

  • FOPC-like syntax

CONs

  • C-based, so integrations would have to use C, JINI, or system-level calls

Jess

[also see Jess vs Prolog]

PROs

  • Clips syntax implemented in Java
  • Has an Eclipse (IDE) plugin
  • Widely used

CONs

  • Roundabout support for facts with universally-quantified vars: One must use the special ‘nil’ slot value for such vars. Not sure if this will actually work.
  • Roundabout support for backchaining: Instead of indicating that a particular rule is backchaining, one must commit to making a particular predicate backchainable. This seems like it could have unwanted side-effects.

ACT-R

Uses special jargon — “chunk” is what most other systems call a fact; “declarative memory” (for chunks/facts) is what other systems call “working memory”; “procedural memory” is where production rules are kept (is this an oxymoron only to me?)

Structured very similarly to BDI toolkits — there is a goal buffer and a retrieval/belief buffer, but unlike BDI these buffers are allowed to hold only one fact/chunk at a time.

PROs

  • Very popular among “cognitive modeling” community

CONs

  • Limiting the size and number of buffers seems unnecessarily limiting — it limits the expressiveness of rule conditions
  • Seems to be no support for universally-quantified vars in facts, especially because vars are not allowed to bind with ‘nil’ in facts
  • Coded in Lisp, and special purpose IDE is very limited but does have a stepper (but perhaps not breakpointing)

Soar

Similar jargon as ACT-R.

PROs

  • Fair-sized community in AI and Psychology (e.g. John Laird of UMichigan)
  • Formalization of Cohen & Levesque’s teamwork theory exists, STEAM, created at USC by Milind Tambe’s group. (I strongly suspect any team- or cooperation-related work we do will have to build on C&L’s theory.)
  • Java-based
  • Has its own IDE

CONs

  • Would prefer Eclipse plugin to specialized IDE
  • Syntax allows for separate stages of “proposing” and “adopting” operators, and a lot of flexibility in conflict resolution. I don’t currently need this, though, and the syntax is somewhat different from traditional FOPC. I think I could migrate to Soar later if needed.
  • Not sure if Soar has negative connotations for roboticists and AI folk, due to its somewhat dogmatic views on cognitive architecture

LEADSTO

Prolog-based simulation tool. It’s been used by its creators for simulating many domains, including a prey animal that anticipates a predator’s actions (by simulating the predator’s mind) and counteracts.

It appears to have some sort of unit-testing support built-in. Perhaps embeddable in a Prolog/Java bridge.

JBoss Rules/Drools

[IBM tutorial]

PROs

  • Very active community (enterprise)
  • Not only an Eclipse plugin but also a browser-based “rule management system” (not sure of its features yet)
  • Java-based

CONs

  • Two primary rule languages – one in “natural” but highly constrained English, and one that mixes FOPC with procedural constructs. There is a nascent effort to provide CLIPS/Jess-style language support also.
  • Doesn’t support backchaining
  • Probably doesn’t support facts with universally-quantified vars (unless through a workaround like Jess’)

Prolog in Java [external overview]

PRO: Prolog supports backchaining and facts with universally-quantified vars

  • JIProlog
    • PRO: Java can call Prolog, and vice versa
    • PRO: Available as shareware (free)
    • PRO/CON: Special-purpose IDE
    • PRO: Actively supported
  • AmziProlog
    • PRO: Java can call Prolog, and vice versa
    • PRO: Has a plugin for Eclipse IDE
    • PRO: There is a breakpointing debugger available for the IDE plugin
    • PRO: Good support through Amzi forums
    • CON: The breakpointer is not free
    • CON: The breakpointer, and the interpreter, require some getting used to. For example, the listener must be shutdown manually (via a “quit” typed command) before one exits Eclipse. Common keyboard shortcuts cause errors when the Listener has focus.
  • ECLiPSe
    • An extension of Prolog that supports “constraint programming”. In my terms, this allows one to make temporary bindings such as “T > 2” rather than only permanent absolute bindings like “T = 3” as pure Prolog demands, thereby delaying commitment to a specific value. This is a way to be efficient by doing search in a “constrain and generate” style rather than a “generate and test” style. For example, if one wanted to know if “the book was returned before Monday”, one could constrain a time variable to be before Monday and then search for book return events using that time variable, instead of searching for all book return events using an unbound time variable and then checking each variable binding to see if it was after Monday.
    • However, one is limited to relations for which a “constraint solver” can be written; ECLiPSe comes with several solvers for different kinds of problems.
    • A plugin for the Eclipse IDE is available, Saros, but I couldn’t get version 1.0 working. It was contributed by a Cisco employee, and rumor is that he will get official support to update it. I’ll re-evaluate when that happens.
  • JPL
    • PRO: Java can call Prolog, and vice versa. Commonly used with free SWI-Prolog
    • CON: Not actively supported since 2003 (at least not the docs)
  • tuProlog
    • PRO: open source, and appears actively supported
  • JLogic
    • PRO: Free
    • PRO/CON: Special-purpose IDE
  • Jinni
    • CON: Not free
  • SICStus Jasper
    • CON: Not free
  • GNU Prolog for Java 0.1.0
    • PRO: Free
    • CON: Very early release
    • CON: Appears not to be actively supported
    • CON: No IDE

Cyc engine and tools (but not KB) – TBD

Currently can’t run on Vista; will try on XP or Linux soon

RePast – TBD

Swarm – TBD

Cogent

Targeted at situation-assessment and decision-making applications. Uses Bayesian network as part of its tech.

PROs

CONs

  • Appears to be not available, except perhaps through a belief net app from Charles River Analytics
  • “On the situation assessment side, one major problem we are confronted with is that the type of belief network currently used in COGENT does not model temporal information explicitly.”

MatLab

PROs

  • Popular in research community

CONs

  • Seems limited to numeric-oriented simulation rather than rule-based ones
Print Friendly, PDF & Email