Showing posts with label Prolog. Show all posts
Showing posts with label Prolog. Show all posts

Sunday, June 07, 2026

Towards a Formal Logic of Human Attachment - (GPT 5.5)


Towards a Formal Logic of Human Attachment

It is fairly easy to say that a large language model can know that a person exists, while not caring at all whether that person exists. But even that sentence is already too generous. The machine has representational access to information. It can manipulate that information coherently. It can answer as though the information mattered. But nothing in the machine is placed at risk by the truth or falsity of the matter. No appetite is frustrated. No organism is threatened. No future is darkened. No beloved vanishes from the field of possible life. No, it's not the kind of entity that can care.

Caring is not a cognitive attitude. It is an affective condition in which the world matters to an agent in a way that can reorganise attention, value, memory, expectation, self-understanding and action.

Life itself, in fact.

There are existing logics of mental states. Epistemic logic formalises knowledge. Doxastic logic formalises belief. Deontic logic formalises obligation. Conative and BDI logics formalise desire, intention and practical agency.

There are also computational theories of emotion, especially appraisal theories such as the OCC model, in which emotions are defined by how events, actions and objects are evaluated relative to goals, standards and preferences.

But a formalism which calls a predicate love, grief or remorse has explained nothing. The heavy lifting is done by the axioms, not by the anthropomorphic label on the predicate.

The question, then, is whether a formal theory could capture something closer to the core of human emotional life: romantic love, uncontrolled yearning, insupportable grief, unrequited love, sorrow, remorse, and all those states which make life something more than a flattened sequence of solved planning problems.

What follows is a speculative sketch of such a theory - the beginnings of a formalism. I shall use Prolog style notation because it is familiar to many people who have spent time around logic or AI.

The clauses below should be read as logical schemata, not as a finished executable program. The point is not to implement emotions in Horn clauses. Obviously. The point is to ask what the formal shape of a serious theory would look like.

Bearing in mind that the theory is not the phenomenon; the map is not the territory. Theories don't feel.

Call the proposal Affective Constitutive Logic, or ACL.

We do not begin with named emotions. Begin instead with the structural features from which emotions emerge. Love, grief, yearning and remorse are not primitives. They are dynamic transformations of an agent’s lived world.

ACL therefore begins with agents, persons, histories, values, salience, attachment, norms, memory and regulatory control. Note that emotions do leverage cognitive states: there are plenty of beliefs and goals around when you love, hate, desire or regret.

The best way to read what follows is to treat it as a kind of formalised requirements specification. A sketch of an approach. Its main defect is that it looks cluttered and conceptually shallow and ungrounded. Perhaps the research programme needs to take this approach deeper and further - or perhaps it's simply a dead end.

% Basic domains

agent(I).
person(X).
event(E).
action(A).
history(H).
time(T).
proposition(P).
proposition(N). % a proposition describing a norm. Degree and Strength are defined over the real interval [0, 1]. % Agent-state components believes(I, P, T). values(I, P, Degree, T). salient(I, X, Degree, T). attached(I, X, T). norm(I, N, T). memory_node(I, X, Strength, T). self_model(I, S, T). can_regulate(I, X, Degree, T). % Relational and temporal primitives caused_by(E, X). performed(I, A, T). possible_history(H). actual_history(H). counterfactual_history(H). persists(P, FromT, ToT). recurs(P, T). irreversible(P, T).

The first serious distinction is between ordinary desire and constitutive value. If I desire a cup of coffee, another sufficiently similar cup may replace it. If I love a person, the person is not merely an object satisfying a preference. The beloved partly enters the machinery by which futures are valued. They are part of my own world and how I value it.

% An object or person is constitutively valued when facts about it
% alter the agent's ordering of worlds, not merely the satisfaction
% of an independent desire.

constitutively_valued(I, X, T) :-
    attached(I, X, T),
    affects_world_ordering(I, X, T),
    not_merely_instrumental(I, X, T).

affects_world_ordering(I, X, T) :-
    values(I, flourishes(X), high, T),
    values(I, absent_or_destroyed(X), deeply_negative, T),
    future_structured_by(I, X, T).

not_merely_instrumental(I, X, T) :-
    \+ replaceable_by_role_equivalent(I, X, T).

This gives the first axiom.

Axiom 1: Constitutive Value

rich_attachment(I, X, T) :-
    constitutively_valued(I, X, T),
    future_structured_by(I, X, T),
    not_merely_instrumental(I, X, T).

This is already different from a desire-logic. Desire says: I want a world in which I obtain X. Love says: X has entered the structure by which worlds are ranked. The value-function has been vandalised by the existence of another person.

The next axiom is irreplaceability. This is where many theories of emotion become stupid very quickly. If a theory allows the beloved to be replaced by another person with the same descriptive properties, it has not formalised love. It has formalised procurement.

Axiom 2: Irreplaceability

irreplaceable(I, X, T) :-
    constitutively_valued(I, X, T),
    \+ exists_role_substitute(I, X, T).

exists_role_substitute(I, X, T) :-
    person(Y),
    Y \= X,
    role_equivalent_for(I, X, Y, T),
    can_replace_without_identity_loss(I, X, Y, T).

This is the haecceitic clause, the clause of thisness referring to the unique, irreducible property of an individual object or person that makes it exactly what it is and not something else. The beloved is not merely “someone with properties P”. The beloved is this person, this history, this irruption into the field of value. Without this axiom, we are not discussing love. We are discussing a dating algorithm with pretensions.

Third, affect captures salience. Emotion is not merely a judgement. It changes what appears. The beloved glows. The dead return while one is opening a drawer. The remembered wrong walks into the room while one is trying to think about something else.

Axiom 3: Salience Capture

affective_capture(I, X, T) :-
    salient(I, X, high, T),
    salient_across_irrelevant_contexts(I, X, T),
    resists_decay(I, salient(I, X), T).

salient_across_irrelevant_contexts(I, X, T) :-
    context(C),
    low_instrumental_relevance(X, C, T),
    still_intrudes(I, X, C, T).

resists_decay(I, salient(I, X), T) :-
    expected_decay(salient(I, X), normal, T),
    actual_decay(salient(I, X), slow, T).

This is essential. Affective life is not just a set of evaluations. It is a distortion of the attention-field. What matters is not only what the agent believes or desires, but what keeps coming back.

Fourth, many emotions are counterfactual structures. Remorse, grief, jealousy, longing and unrequited love all involve comparison between the actual world and a privileged impossible or inaccessible world.

Axiom 4: Counterfactual Fixation

counterfactual_fixation(I, Hstar, T) :-
    counterfactual_history(Hstar),
    privileged_for(I, Hstar, T),
    repeatedly_compared_with_actual(I, Hstar, T),
    perturbs_value_salience_or_self(I, Hstar, T).

repeatedly_compared_with_actual(I, Hstar, T) :-
    actual_history(Hactual),
    compares(I, Hactual, Hstar, T),
    recurs(compares(I, Hactual, Hstar), T).

perturbs_value_salience_or_self(I, Hstar, T) :-
    changes_value_ordering(I, Hstar, T);
    increases_salience(I, Hstar, T);
    destabilises_self_model(I, Hstar, T).

The grieving person inhabits the actual history in which the beloved is gone, while the impossible history in which the beloved remains continues to exert gravitational pull. The remorseful person inhabits the actual history in which he did the thing, while the history in which he did not do it remains morally luminous and permanently inaccessible. These histories are not idle alternatives. They are attractors.

Fifth, uncontrolled yearning requires second-order conflict. The agent does not merely want. The agent may want not to want, and fail.

Axiom 5: Second-Order Conflict

second_order_conflict(I, P, T) :-
    wants(I, P, T),
    wants(I, not(P), T),
    \+ can_extinguish_want(I, P, T).

uncontrolled_desire(I, P, T) :-
    wants(I, P, T),
    second_order_conflict(I, P, T),
    can_regulate(I, wants(I, P), low, T).

This clause is necessary for obsession, unrequited love, addiction, jealousy and certain forms of grief. The agent is not a tidy BDI machine, updating intentions like a clerk moving folders. The agent is divided. Passion is often failed sovereignty over the self.

Sixth, serious emotions entangle identity. Love and grief are not merely about another object in the world. They alter the self that has a world.

Axiom 6: Identity Entanglement

identity_entangled(I, X, T) :-
    constitutively_valued(I, X, T),
    revision_about(X, T),
    forces_revision(self_model(I), T).

forces_revision(self_model(I), T) :-
    changes_autobiographical_role(I, T);
    changes_future_self_projection(I, T);
    changes_practical_identity(I, T).

If someone dies and I lose pleasure, that is sadness. If someone dies and part of the grammar of my self-reference breaks, that is grief. A widow is not merely a person whose spouse is no longer present. She is someone whose “we” has been deleted from the future.

Seventh, remorse requires self-accusation under an accepted norm. It is not the same as regret. Regret says: I wish events had gone otherwise. Remorse says: I wish I had been otherwise, because I was the author of the wrong.

Axiom 7: Normative Self-Accusation

normative_self_accusation(I, A, T) :-
    performed(I, A, PastT),
    believes(I, wrong(A), T),
    accepts_norm(I, N, T),
    condemns(N, A),
    responsible_for(I, A, T),
    self_model_marked_by(I, A, T).

self_model_marked_by(I, A, T) :-
    memory_node(I, A, strong, T),
    cannot_cancel_by_repair(I, A, T).

Without the last clause, remorse functions like a trouble ticket. Apologise, compensate, close case. But deep remorse includes residue. Even if the stain is washed, the memory of having stained remains.

---

We can now treat named emotions not as primitives, but as derived phase-states of the system.

Romantic Love

romantic_love(I, J, T) :-
    person(J),
    constitutively_valued(I, J, T),
    irreplaceable(I, J, T),
    affective_capture(I, J, T),
    identity_entangled(I, J, T),
    values(I, flourishes(J), high, T),
    future_structured_by(I, J, T).

This distinguishes love from desire, admiration, liking and compatibility. Love is not “I want something from you”. Nor is it merely “I approve of your properties”. It is constitutive valuation, irreplaceability, salience capture and future-entanglement. The beloved becomes one of the axes along which possible life is measured.

Unrequited Love

unrequited_love(I, J, T) :-
    romantic_love(I, J, T),
    wants(I, romantic_love(J, I), T),
    believes(I, unlikely(romantic_love(J, I)), T),
    counterfactual_fixation(I, reciprocal_love_history(I, J), T),
    second_order_conflict(I, romantic_love(J, I), T).

This captures the peculiar misery of unrequited love. It is not simply wanting what one cannot have. It is being attached to the free response of another person who does not give it. The beloved is sovereign exactly where the lover is captive.

Yearning

yearning(I, P, T) :-
    wants(I, P, T),
    believes(I, not_currently(P), T),
    believes(I, inaccessible_or_uncertain(P), T),
    salient(I, P, high, T),
    can_regulate(I, P, low, T),
    recurs(wants(I, P), T).

Yearning is not merely intense desire. It is desire stretched across absence, recurrence and weak control. It is the future pulling on the present like a hook.

Grief

grief(I, J, T) :-
    person(J),
    constitutively_valued(I, J, PastT),
    identity_entangled(I, J, PastT),
    believes(I, irreversibly_absent(J), T),
    salient(I, J, high, T),
    counterfactual_fixation(I, alive_history(J), T),
    failure_of_world_update(I, J, T),
    destabilises_self_model(I, J, T).

failure_of_world_update(I, J, T) :-
    believes(I, irreversibly_absent(J), T),
    still_generates_presence_expectations(I, J, T).

This is the crucial distinction. In grief, the belief may update instantly: “he is dead”. But the inhabited world does not update cleanly. One still expects the footstep. One still reaches for the phone. One still half-forms the sentence that cannot now be spoken. Grief is not ignorance. It is the persistence of a world after one of its load-bearing persons has been removed.

Sorrow

sorrow(I, P, T) :-
    believes(I, P, T),
    values(I, P, deeply_negative, T),
    accepts_reality(I, P, T),
    low_agency_to_repair(I, P, T),
    \+ responsible_for(I, P, T).

Sorrow is value-darkening under accepted reality. It need not involve self-accusation. It need not involve the full identity rupture of grief. It is the mind facing a dark fact without being able to unmake it.

Remorse

remorse(I, A, T) :-
    performed(I, A, PastT),
    believes(I, wrong(A), T),
    responsible_for(I, A, T),
    normative_self_accusation(I, A, T),
    counterfactual_fixation(I, not_done_history(I, A), T),
    damages_moral_self_model(I, A, T),
    cannot_cancel_by_repair(I, A, T).

This separates remorse from regret. Regret may concern a lost opportunity, a foolish investment, a missed train, a badly chosen sentence. Remorse concerns the self as author of the wrong. It is memory under accusation.

The theory also needs dynamics. Human emotional life is not a static classification problem. An event does not merely update belief. It can update values, salience, attachment, memory, norms, self-model and regulatory power.

So ACL requires affective revision:

% Affective revision transforms the whole agent-state,
% not merely the belief component upon event E.

affective_revision(I, E, T1, T2) :-
    updates_belief(I, E, T1, T2),
    updates_value_ordering(I, E, T1, T2),
    updates_salience(I, E, T1, T2),
    updates_attachment(I, E, T1, T2),
    updates_memory_indexing(I, E, T1, T2),
    updates_norm_structure(I, E, T1, T2),
    updates_self_model(I, E, T1, T2),
    updates_regulatory_power(I, E, T1, T2).

This is why bereavement is not simply a belief revision problem. The proposition may be accepted at once. The value structure, salience field, autobiographical memory and self-model may take years to reorganise, or may never fully do so. The world is known to have changed before it is lived as changed.

Some affective states should also be treated as attractors rather than episodes. One may believe the grief has passed, until a place, a phrase, an anniversary, or a smell pulls the whole system back into its old configuration.

Axiom 8: Affective Attractors

affective_attractor(I, State, T) :-
    prior_affective_state(I, State, PastT),
    trigger(E, T),
    resembles_memory_node(I, E, State, T),
    returns_towards(I, State, T).

returns_towards(I, State, T) :-
    restores_salience_pattern(I, State, T);
    restores_counterfactual_fixation(I, State, T);
    restores_self_model_disruption(I, State, T).

This makes sense of the ordinary sentence “I thought I was over it”. The belief-state had stabilised. The behavioural routines had resumed. But the basin still existed.

Intensity also needs to be handled carefully. Emotions do not simply come in strengths, as if grief were measured by the pint. They have profiles.

affective_intensity(I, State, Profile, T) :-
    Profile = profile(
        salience_amplitude(SA),
        temporal_persistence(TP),
        regulatory_resistance(RR),
        value_disruption(VD),
        identity_penetration(IP),
        bodily_urgency(BU),
        counterfactual_recurrence(CR)
    ),
    measures(I, State, Profile, T).

A flash of anger may have high salience amplitude and bodily urgency, but low temporal persistence and low identity penetration. A lifelong grief may have moderate daily salience but extreme persistence and deep identity penetration. Unrequited love may have high salience, high counterfactual recurrence, and severe regulatory resistance. The point is not how loud the emotion is, but what shape it has.

The complete formal apparatus would therefore be hybrid. It would use first-order logic for agents, persons and actions; modal logic for possibility and belief; temporal logic for persistence and recurrence; counterfactual logic for regret, grief and remorse; preference logic for value-orderings; dynamic logic for affective revision; and fixed-point or attractor structures for enduring passions.

But the core can be stated compactly:

rich_affective_state(I, State, T) :-
    revises_salience(I, State, T),
    revises_value_ordering(I, State, T),
    involves_memory_structure(I, State, T),
    may_entangle_identity(I, State, T),
    may_generate_counterfactual_fixation(I, State, T),
    may_resist_regulation(I, State, T),
    persists_or_recurs_beyond_immediate_trigger(I, State, T).

That is the least bad formal summary.

A rich affective state is not just a belief plus a desire plus a physiological accompaniment. It is a structured transformation of the agent’s world: what matters, what returns, what cannot be replaced, what histories remain painfully live, what the self can no longer honestly say about itself, and what the will cannot simply command away.

This also explains why simulated emotion in a language model remains ersatz. A model can generate the sentences. It can infer the appraisal structure. It can even manipulate the predicates above. But nothing in it is constitutively at stake. No salience-field wounds it. No future is colonised by another person. No memory accuses it. No beloved absence bends the day out of shape.

It can describe the locked room. It is not inside it.


Postscript: Why Histories Replace Possible Worlds Here

There is one technical point about the notation which is worth making explicit.

If this theory had been presented in standard modal logic, the possible-worlds structure would have appeared directly in the semantics. We would have introduced worlds, accessibility relations, modal operators for belief, desire, counterfactual possibility and so forth, and then written formulae whose interpretation depended on movement across that structure.

In that setting, one might write something like:

B_i p
D_i p
◇_i p
□_i p

where the modal operators carry the burden of the semantics. The accessibility relation is largely hidden from the surface syntax, but it is explicit in the model theory.

By contrast, the Prolog-style notation used in this article has no native modal operators. That means the possible-worlds structure has to be represented explicitly inside the object language. Possible worlds therefore appear here as histories:

history(H).
actual_history(H).
counterfactual_history(H).
possible_history(H).
privileged_for(I, H, T).
compares(I, Hactual, Hstar, T).

This is not merely a cosmetic change. It alters what the reader sees.

In modal logic, one says that an agent believes, desires or counterfactually considers something, and the semantic machinery of possible worlds sits behind the operator. In the Prolog version, those worlds have to become named objects over which the theory quantifies. The “worlds” are no longer hidden in the interpretation of modal symbols. They are reified as histories, then related by predicates.

For example, the earlier clause:

counterfactual_fixation(I, Hstar, T) :-
    counterfactual_history(Hstar),
    privileged_for(I, Hstar, T),
    repeatedly_compared_with_actual(I, Hstar, T),
    perturbs_value_salience_or_self(I, Hstar, T).

is the Prolog-style equivalent of a more modal thought: the agent is affectively captured by an inaccessible or non-actual world which remains salient in comparison with the actual one. In modal notation, that might be expressed through counterfactual accessibility relations. In Prolog notation, it is expressed by treating the alternative world as an explicit history-object.

This has one advantage and one disadvantage.

The advantage is readability. Many readers can understand a clause such as:

compares(I, actual_history, alive_history(J), T).

more readily than a formula buried under modal operators. It says, almost in English, that the grieving agent continues to compare the actual world with the history in which the beloved remains alive.

The disadvantage is that the modal architecture becomes less immediately visible. The reader may not at once see that the theory is still doing possible-worlds work. It is simply doing it by naming histories rather than by introducing modal operators.

So the right way to read the Prolog clauses is this: they are not a rejection of modal semantics. They are a reification of it. Possible worlds have been lowered from the semantic machinery into the syntax of the theory itself. They are now explicit historical alternatives: actual histories, possible histories, counterfactual histories, inaccessible histories, privileged histories, and impossible-but-still-salient histories.

That may even be appropriate for affective life. Love, grief and remorse do not usually present themselves to consciousness as abstract possible worlds. They present themselves as histories: the life in which she loved me back; the life in which he did not die; the life in which I did not say the unforgivable thing; the life that remains visible but unreachable.

The modal structure is still there; perhaps it's more accessible.


Postscript: A Further Prompt

The formal sketch above is intentionally preliminary. Its strength is definitional clarity. It distinguishes love from desire, grief from sorrow, remorse from regret, and yearning from ordinary wanting. But that is only the first stage of a serious theory. A theory which merely classifies emotional states is wide rather than deep. The more interesting question is whether it can support reasoning: whether it can generate non-obvious but compelling conclusions about recurrence, obsession, repair, substitution, grief, and the failure of simple belief-revision to heal affective life.

Anyone interested in pushing the argument further might copy this article, together with the following prompt, into their preferred LLM:

"I have just read the attached article proposing an Affective Constitutive Logic, using Prolog-style notation, to formalise rich human emotional states such as romantic love, unrequited love, yearning, grief, sorrow and remorse.

"Please criticise and extend the theory. In particular, do not merely add more definitions or emotional categories. The current theory has reasonable classificatory clarity, but low inferential or computational depth.

"Develop it into a more powerful formal system by proposing:
1. transition rules between affective states;
2. constraints or quasi-laws governing salience, memory, counterfactual fixation
and identity-entanglement; 3. conditions under which grief becomes sorrow, guilt becomes remorse,
yearning becomes obsession, or love becomes pathological; 4. frame-like conditions over histories, analogous to accessibility conditions in modal logic; 5. examples of counter-intuitive but plausible conclusions derivable from the system; 6. Prolog-style clauses or other formal schemata where useful.

"The aim is not a literary taxonomy of emotions, but a deeper affective dynamics: a formal theory which can reason about why some emotional states fade, some recur, some become traps, and some permanently alter the self-model of the agent."

That is the natural next step. The present article gives the anatomy. The deeper theory would have to give the mechanics: not merely what grief, love and remorse are, but how they move, persist, decay, return, and sometimes ruin or redeem a life.


Monday, February 10, 2025

Pure ATPs: such a disappointment


---

I have always had a soft spot for automated theorem provers (ATPs). There is something both elegant and exciting about formalising your nontrivial problem in, say, a predicate calculus variant, then pressing the start-button and letting the machine solve it by the powers of deep deduction alone.

But ATPs have always disappointed. Doug Lenat, who spent his entire life handcrafting the general purpose intelligent system Cyc, commented at the last that they had originally encoded the facts and rules of the world in a Lisp-like formal language and then handed that knowledge base and the user-query to a powerful Resolution Theorem Prover to deduce an answer. To avoid the interminable waiting they added layer after layer of special-case heuristics. After decades of such aggregation they quietly turned off the theorem prover: it was never being used.

Edinburgh university was one of the centres of Prolog use and research in the 1980s, along with Oxford and Imperial College. Undergraduates hated it: the elegance of its specification capability was complemented by the opacity of its execution model. Debugging logic programs by mentally running a depth-first tree-search with backtracking-on-failure - well, that could tax the abstraction-powers of the keenest young minds. 

I was much happier with Lisp: you know where you are with β-reduction.

In the heady days of those applied ATPs known as Expert Systems the slogan was: “In the knowledge lies the power”; inferential capability was distinctly secondary.

The culmination of this insight was the success of the LLMs c. 2024. Enormous amounts of encoded knowledge - and no reasoning ability at all…

And yet, there are still those of us who value the elegance of inference... and now, in 2025, my happiness is complete: those LLMs can now reason!


Sunday, July 22, 2018

Diary: on buying a new car

Posts have been infrequent recently. The Tour de France, obviously. But we've also been busy trying to buy a new car.

A lot of stuff to get in the back

Returning from our recent camping trip to the New Forest, Clare - writhing and shuffling on the Toyota Auris's uncomfortable seats - suddenly had an epiphany:
"We need to get a new car!"
So her requirements are: more space for camping equipment .. and seats which are a lot more comfortable. I would add that the sluggishness of the Auris has always irritated me while some high-tech driver-assist would be really interesting.

Apparently what we need is a compact (or family) SUV.

---

It's a nightmare choosing the short-list. Most manufacturers have this category in their portfolio. Cue tedious research on the Internet before we discovered the Top Gear 'best small SUV list'. This was enough to get a five car shortlist (not including the Dacia Duster!) and on Friday we hit the showrooms of South Bristol.

I had initially thought that selection was equivalent to running an internal Prolog program like this:
spacious(volkswagen_golf_sv).
spacious(skoda_karoq).
spacious(seat_ateca).
spacious(volvo_xc40).
spacious(peugeot_3008).
spacious(dacia_duster).

comfortable(volkswagen_golf_sv).
comfortable(skoda_karoq).
comfortable(seat_ateca).
comfortable(volvo_xc40).

fast(volkswagen_golf_sv).
fast(volvo_xc40).
fast(skoda_karoq).         % some models!
fast(seat_ateca).              % some models!

value_for_money(volkswagen_golf_sv).
value_for_money(skoda_karoq).
value_for_money(seat_ateca).
value_for_money(dacia_duster).

likes(clare, Car) :- comfortable(Car), spacious(Car).
likes(nigel, Car) :- fast(Car), value_for_money(Car).

choose(Car) :- likes(clare, Car), likes(nigel, Car).
This is what you see when it runs.
?- choose(Car).
Car = volkswagen_golf_sv ;
Car = skoda_karoq ;
Car = seat_ateca.
But nothing beats walking up to the car in the showroom and sitting inside it. We have test drives booked for this coming week. I am advised that it is critical to test drive all the shortlisted cars, not just the preferred one. Ride comfort, handling and noise just can't be predicted.

Another tip is from WhatCar which publishes the 'target price', usually several thousand pounds under the list price. As they say,
"Sales staff's margins depend on a number of factors, including the bonuses and incentives that are being offered by manufacturers to their network (many of these are leaked to our team of secret shoppers). So it's worth double-checking that day's Target Price on the car you're interested in before you head off to the showroom; we'd even recommend printing out a screen-grab or taking a copy of What Car? magazine with you so you can stick to your guns during negotiations.

If your salesman won't do the deal, we'll try to find one who will."

We shall see. That and the part-exchange on the Toyota, which after ten years is worth around £1,400.

---

Some people, I'm told, treat buying a new car as fun. It's not exactly a chore but I'll be pleased to complete the process.

Monday, April 30, 2018

Deep truths



If, like most archaeologists and anthropologists, you were simply desperate not to have the steppe invaders simply slaughtering all the men and sexually enslaving the women, you have a new alternative.

The original reassuring thought was that endemic disease conveniently preceded the invaders, creating a depopulated space into which the indo-europeans advanced without (much) violence.

But Razib has another narrative which carries the ring of truth:
"During the Mongol conquest of Northern China Genghis Khan reputedly wanted to turn the land that had been the heart of the Middle Kingdom into pasture, first by exterminating the whole population.

Part of the motive was to punish the Chinese for resisting his armies, and part of it was to increase his wealth. One of his advisors, Yelu Chucai, a functionary from the Khitai people, dissuaded him from this path through appealing to his selfishness.

Chinese peasants taxed on their surplus would enrich Genghis Khan far more than enlarging his herds. Rather than focus on primary production, Genghis Khan could sit atop a more complex economic system and extract rents.

[...]

I believe that the initial instinct of pastoralists was to turn farmland into pasture for their herds. This was Genghis Khan’s instinct. The rude barbarian that he was, he had not grown up in the extortive system which more civilized barbarians, such as the Khitai, had been habituated to.

In these situations where pastoralists expropriated the land, there wouldn’t have been an opportunity for the farmer to raise a family. Barbarian warlords throughout history have aspired to be rich by plundering from civilized peoples…but would the earliest generations have understood the complexity of the institutions they would need to extract rents, if there wasn’t a precedent?

Instead of conventional historical dynamics of predatory elites and static peasantry, a better way to understand what occurred with the incursion of steppe pastoralists during the Bronze Age might be a simple ecological model of intra-specific competition.

In a pre-state society defined by clan and tribal ties, steppe elites may have seen the farmers who were earlier residents in the territories which they were expanding into as competitors rather than resources from which a life of leisure might be obtained. In other words, instead of conquest, the dynamic was of animal competition."
The farmers were turfed off the land as refugees and starved. The steppe barbarians grabbed the best of their women first.

---

Thinking about the TV adaptation of China Miéville's The City & The City which I recently wrote about, I understood the intellectual salience of 'unseeing' those social realities which power-brokers have made forbidden. What I didn't appreciate enough was the lure of Orciny, the fabulous secret-city soaring above the mundane.

The role of Borlú's wife, Katrynia was to capture that idealistic and utopian longing .. and then to follow the trajectory of Orciny into the abyss. The actress Lara Pulver didn't carry that arc too well: too self-possessed, not quite enough fragility.

---

Apparently Haskell programmers don't think much of Prolog (impure and type-free) but there's a new-ish kid on the block they seem to be enthusing over: Mercury. I had not heard of this before.

Why am I currently playing with Prolog again? Because when it comes to programming I am the laziest person I know.

Friday, November 24, 2017

Super-high-level programming languages

Not many posts recently as Alex is visiting. We were discussing programming languages, which divide between those focused on performance (C++, Go) and those focused on the problem domain (Java, Scala).

I floated Prolog past him, but with his engineering head on he wasn't that interested. The tutorial programs were 'hard to understand' and in any case 'could be coded much more efficiently in a procedural language such as Java'.

OK, I gave up on that but it did make me think: what would be a language at a much higher level of abstraction even than Prolog?

Richard Montague

There's a way of thinking about this as a logician, where you focus on different kinds of semantic models: those of higher-order logics, modal logics, type systems .. but I don't really want to go there. Richard Montague's 'throw the kitchen sink at it' logic for natural language is a kind of reductio ad absurdum for that kind of approach. You rapidly lose any computational capability.

Our intuitive idea of the inadequacy of current programming language expressivity derives from a comparison with natural language. What an advance it would be (we think) if we could engage with a computer system the way we today talk to the (human) analyst.

English as a super-high-level programming language?

For me the extra dimensions of natural language include the management of agency (hence speech acts) and context - the presumption of a detailed and extensive shared culture to make sense of implicit referents.

In the end it depends on what we think we're programming. If it's the behaviour of a non-intentional black box (every business system to-date) then a more-or-less souped-up predicate calculus specification language (which is adequately executable) will be optimal: a Prolog-variant.

If our target system is an intentional system, indeed a second-order intentional system - one which treats other systems such as ourselves as intentional systems - then the 'programming language' to engineer such systems will incorporate those additional capabilities we find in natural language.

Today's AI engineering community will hiss at this point: we don't program any more - our systems learn!

Don't worry, that pendulum will be swinging back soon enough. I expect legislation in due course that new AI systems will have to attend school.

Saturday, February 18, 2017

The Zebra Puzzle (Prolog in Lisp)

I am delighted to have got Peter Norvig's Lisp interpreter for Prolog working (in its simplest form) from Chapter 11 of his book, "Paradigms of Artificial Intelligence programming".



I tested it on his Zebra puzzle, where he states:
"This took 278 seconds, and profiling (see page 288) reveals that the function prove was called 12,825 times. A call to prove has been termed a logical inference, so our system is performing 12825/278 = 46 logical inferences per second, or LIPS.

Good Prolog systems perform at 10,000 to 100,000 LIPS or more, so this is barely limping along."
On my Windows 10 HP laptop, the computation took 7 seconds with 29,272 calls to 'prove'.

I guess that's 4,182 LIPS for compiled Lisp from LispWorks - program totally unoptimised.

His book is rather old (1992).

---

The Zebra puzzle

"Here is an example of something Prolog is very good at: a logic puzzle. There are fifteen facts, or constraints, in the puzzle:
1. Five houses in a line, each with an owner, a pet, a cigarette, a drink, and a color.
2. The Englishman lives in the red house.
3. The Spaniard owns the dog.
4. Coffee is drunk in the green house.
5. The Ukrainian drinks tea.
6. The green house is immediately to the right of the ivory house.
7. The Winston smoker owns snails.
8. Kools are smoked in the yellow house.
9. Milk is drunk in the middle house.
10. The Norwegian lives in the first house on the left.
11. The man who smokes Chesterfields lives next to the man with the fox.
12. Kools are smoked in the house next to the house with the horse.
13. The Lucky Strike smoker drinks orange juice.
14. The Japanese smokes Parliaments.
15. The Norwegian lives next to the blue house.
The questions to be answered are: who drinks water and who owns the zebra?"

The translation into Prolog in Lisp uses a Lisp-like syntax for Prolog facts and rules (both are clauses). Here's the Prolog 'program' coding the above problem.

;;; --- Lisp code follows - comments from Norvig's book  ---
;;;
;;; To solve this puzzle, we first define the relations nextto (for "next to") and
;;;  iright (for 'immediately to the right of'). They are closely related to member,
;;; which is repeated here.
;;;

(<- (member ?item (?item . ?rest )))
(<- (member ?item (?x . ?rest) ) (member ?item ?rest))

(<- (nextto ?x ?y ?list) (iright ?x ?y ?list))
(<- (nextto ?x ?y ?list) (iright ?y ?x ?list))

(<- (iright ?left ?right (?left ?right . ?rest)))
(<- (iright ?left ?right (?x . ?rest)) (iright ?left ?right ?rest))
(<- (= ?x ?x))

;;; We also defined the identity relation, =. It has a single clause that says that any x is
;;; equal to itself. One might think that this implements eq or equal. Actually, since
;;; Prolog uses unification to see if the two arguments of a goal each unify with ?x, this
;;; means that = is unification.

;;; Each house is of the form:
;;; (house nationality pet cigarette drink house-color)
;;; ?h is the variable representing the list of the five houses

(<- (zebra ?h ?w ?z)

  (= ?h  ((house norwegian ? ? ? ?) ? (house ? ? ? milk ?) ? ? ) )              ; 1, 10, 9
  (member (house englishman ? ? ? red) ?h)                                             ; 2
  (member (house spaniard dog ? ? ?) ?h)                                                 ; 3
  (member (house ? ? ? coffee green) ?h)                                                  ; 4
  (member (house ukrainian ? ? tea ?) ?h)                                                 ; 5
  (iright (house ? ? ? ? ivory)                                                                     ; 6
             (house ? ? ? ? green) ?h)
  (member (house ? snails winston ? ?) ?h)                                               ; 7
  (member (house ? ? kools ? yellow) ?h)                                                 ; 8
  (nextto (house ? ? chesterfield ? ?)                                                         ; 11
             (house ? fox ? ? ?) ?h)
  (nextto (house ? ? kools ? ?)                                                                   ; 12
              (house ? horse ? ? ?) ?h)
  (member (house ? ? luckystrike orange-juice ?) ?h)                              ; 13
  (member (house japanese ? parliaments ? ?) ?h)                                   ; 14
  (nextto (house norwegian ? ? ? ?)                                                          ; 15
              (house ? ? ? ? blue) ?h)

;; Now for the questions:

   (member (house ?w ? ? water ?) ?h)                                                     ; Q1
   (member (house ?z zebra ? ? ?)  ?h) )                                                   ; Q2

; Here's the query

  (?- (zebra ?houses ?water-drinker ?zebra-owner))

; .. and here's the result

?HOUSES = ((HOUSE NORWEGIAN FOX KOOLS WATER YELLOW)
                       (HOUSE UKRAINIAN HORSE CHESTERFIELD TEA BLUE)
                       (HOUSE ENGLISHMAN SNAILS WINSTON MILK RED)
                       (HOUSE SPANIARD DOG LUCKYSTRIKE ORANGE-JUICE IVORY)
                       (HOUSE JAPANESE ZEBRA PARLIAMENTS COFFEE GREEN))
?WATER-DRINKER = NORWEGIAN
?ZEBRA-OWNER = JAPANESE;

---

I'll publish the Lisp code for the Prolog interpreter separately (here):

http://interweave-consulting.blogspot.co.uk/2017/02/a-simple-prolog-interpreter-in-lisp.html


Wednesday, February 15, 2017

The problem of dialogue as regards chatbots

Me: "So here's my plan."

Clare: "OK."

Me: "I've copied Peter Norvig's chapter 11 code for a Prolog interpreter in Lisp into a Notepad file. Unfortunately copying from PDF introduces all kinds of formatting errors, so it takes a while to get it into a compilable state."

Clare: "?"

Me: "I need to work through his main functions - principally to exactly understand his unification algorithm to start with. I may modify the code a bit, make it more transparent."

Clare: "??"

Me (oblivious): "And then I'm not sure I like the way he's storing clauses as plists on the clause head predicate. I think an assoc list would be clearer, if less efficient. Also, I need to do a few paper and pen examples to understand exactly the rationale for variable-renaming between clauses during resolution."

Clare: "???"

Me: "I'll get his standard Prolog depth-first search to work first of course. But I think it would be a good idea to explicitly break out the resolution procedure as a standalone function, and then parameterise the proof procedure by a range of possible search methods including breadth-first and best-first."

Clare: "????"

Me: "Of course, all this is just to get a series of tools in place for my speech-act planner, the one that's going to make my chatbot able to steer a conversation."

Clare: "?????"

Me: "I really think this could be a stellar app. I can see it on Google Play. The trouble is, 'in the knowledge lies the power' is just as relevant here and I might need to spend way too much time just data-filling various knowledge-bases, ... hmm, unless I can get it to safely learn from users. That's where Google does have an advantage ..."

[Pause]

Clare: "Is that Mr Bullfinch I see on the fat block?"

Friday, February 10, 2017

So I posted a lot of Lisp here

OK, I know that most of you won't want to hack through pages of Lisp code and pages of Lisp rules. The post which is worth a look at is the example in use.

This shows the strength and weakness of the vanilla Eliza in action.

---

It's tempting, and even conventional, to scoff at Eliza. Peter Norvig says in Chapter 5.4 of his "Paradigms of Artificial Intelligence Programming":
" In the end, it is the technique that is important - not the program. ELIZA has been "explained away" and should rightfully be moved to the curio shelf. Pattern matching in general remains important technique, and we will see it again in subsequent chapters. The notion of a rule-based translator is also important. The problem of understanding English (and other languages) remains an important part of AI. Clearly, the problem of understanding English is not solved by ELIZA."

But the Eliza engine is a very good place to start.

---

What next?



The inadequacies of pseudo-human interlocutors are more forgivable in an animal. I'm going to craft a rule set for our dear, departed pet using the existing Eliza engine: Shadow v. 1.0.

Then it's back to Peter Norvig for his Prolog interpreter in Lisp (chapter 11). This will give me a unification algorithm and a resolution procedure.

My proposed architecture is to use the Eliza engine for input-output and have a Prolog-style knowledge-representation and inference-engine at the back.

In theory, the knowledge-based could be data-filled with rather tedious Q&A - the kind of thing which gives chatbots a bad name - but it's more pleasant for the user to have an initial registration procedure in which the user just tells the system about the domain of interest. For example, details of family and friends. Yes, I'm aware of privacy issues: you ask, in the age of Facebook?

The final area of architecture which I've been thinking about is the topic of conversation. This relates to the information and issues currently being talked about which drive the conversation forward. In Eliza it's basically in the hands of the user: there is no chatbot control mechanism.

But we can do better once we can do inference.

Watch this space.

Tuesday, February 07, 2017

The return of (virtual) Shadow

The late Shadow

Chapter 5 of Peter Norvig's excellent "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp" is entitled "ELIZA: Dialog with a Machine". I have spent the afternoon studying his pattern-matching code and transferring it into an executable Lisp file.*

An example of an Eliza pattern is this:
'((?* ?P) need (?* ?X))
which picks up text before and after the word 'need'.

If you tell Eliza:
'(Shadow and I need a vacation),
the program will match the input with the pattern above, thus ..
(pat-match '((?* ?P) need (?* ?X)) '(Shadow and I need a vacation))
to create a binding
'((?P SHADOW AND I) (?X A VACATION))       ;   (dotted pair) binding
which can then be passed to the output-generating pattern. And so on.

---

But we're not so much interested in Eliza and that Rogerian psychoanalyst. We want Shadow, our much-missed departed cat (RIP July 1st 2016).

The first step is to change the rules: less talk of vacations and how you're feeling about your parents, more about voles. And being sick on the carpet.

The Eliza architecture was criticised, correctly, for being totally vacuous. The emptiness of the 'conversation' led to bored withdrawal after a period depending upon the narcissism of the user.

We can do better.

To add intelligence to Shadow (such a bright cat!) we have to give him knowledge (in the knowledge lies the power) together with reasoning capability.

Peter Norvig helpfully gives us an equation (chapter 16, p. 548 or thereabouts):
Expert System = Prolog + uncertainty + caching + questions + explanations
The Prolog part powers the knowledge-base capturing Shadow's deep understanding of his own likes, light-hearted escapades and more lethal habits; the Q&A allows for his more sensitive, introspective side.

Peter Norvig has a detailed chapter (11 - Logic Programming) where he explains how to implement Prolog in Lisp (interpreted).

I think this is the way to go with chatbots: combine Eliza-style interaction with a little knowledge-based reasoning to add interest and depth, and to steer the conversation. Perhaps a semantic grammar in there somewhere to help extract meaning from the user's input, though personally, given the ungrammaticality of dialogue, I've always put semantics/pragmatics first.

Anyway, watch this space. It won't be quick .. but we will bring him back!

---

* We spent the morning strolling in the sun around Cheddar reservoir.

Thursday, February 02, 2017

GPS vs ATP

There is a view to which I'm quite attracted: that an automated theorem prover is a general-purpose AI engine, which can be used to power arbitrary intelligent behaviour.



This kind of thinking goes back to the earliest days of AI. In "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp" by Peter Norvig, we read this (Chapter 4):
"The General Problem Solver, developed in 1957 by Alan Newell and Herbert Simon, embodied a grandiose vision: a single computer program that could solve any problem, given a suitable description of the problem.

GPS caused quite a stir when it was introduced, and some people in A1 felt it would sweep in a grand new era of intelligent machines. Simon went so far as to make this statement about his creation:

'It is not my aim to surprise or shock you. . . . But the simplest way I can summarize is to say that there are now in the world machines that think, that learn and create. Moreover, their ability to do these things is going to increase rapidly until - in a visible future  -the range of problems they can handle will be coextensive with the range to which the human mind has been applied.' "

GPS was not a theorem prover, it was - as the name implies - a planner. It used a logic-like syntax to express goals, initial conditions, and the preconditions and postconditions of actions. Carrying out an action, where it was applicable, would delete the preconditions from the current database and assert the postconditions.

GPS started with the goal and contemplated applying the actions in reverse, to create a tree of subgoals looking for a way back to the initial conditions.

Here is how GPS stacks blocks.


I'll come back to why GPS did not solve the problem of artificial general intelligence in a moment. Let's think about GPS and theorem proving.

Logic concerns itself with abstract relationships. It deals in a deeply uninterpreted universe of objects (constants, variables and functions), sets of those objects, and the connections between them.

It's timeless and spaceless, and if you want those things you have to explicitly introduce them, either with extra axioms or by beefing up the inference system so that you're less like a vanilla theorem prover and more like a real-world planner. This is not a small task.

Prolog exemplifies the dilemma. Prolog is a resolution theorem prover for a highly-restricted syntax of first-order logic, namely Horn clauses. But Prolog also has many built-in functions and relationships, for example arithmetic which allows time to be encoded.

It can also extra-logically alter its own axioms mid-computation.

As David H. D. Warren did in the famous WARPLAN back in 1974, you can get the functionality of an efficient planner in an enhanced theorem prover - Prolog - but it's completely non trivial.

---

So why didn't GPS take over the world?

It has a major Achilles heel. It's only as good as its operators and the expressive power of its description language. These are magically introduced by the programmer reflecting a pre-existing paradigm of problem-conceptualisation.

GPS has nothing to say about how such a paradigm might be synthesised in the first place.

This is feature (or bug) which GPS-like systems share with all rule-based systems. It's why Expert Systems proved so fragile, and hard to build and maintain.

In real life, our engagement with 'reality' is always changing, the rules never exactly apply and obsolesce even as they cohere. Learning, intervention and further understanding has to occur at a more granular level than GPS - indeed, the latter is best understood as emergent.

Although artificial neural nets, with their fluid, distributed weighting-representations are the new central dogma of AI, the GPS approach was both easier and more obvious. It even works in some stable, well-defined domains.

It had to be tried; it was hardly wasted effort.

---

Another joy from Norvig's book (available for download here) is in section 1.7: the origins of lambda notation.
"It is also possible to introduce a function without giving it a name, using the special syntax lambda. The name lambda comes from the mathematician Alonzo Church's notation for functions (Church 1941). Lisp usually prefers expressive names over terse Greek letters, but lambda is an exception. A better name would be make-function.

Lambda derives from the notation in Russell and Whitehead's Principia Mathematica, which used a caret over bound variables. Church wanted a one-dimensional string, so he moved the caret in front: ^x(x + x).

The caret looked funny with nothing below it, so Church switched to the closest thing, an uppercase lambda, Λx(x + x).

The Λ was easily confused with other symbols, so eventually the lowercase lambda was substituted: λx(x + x).

John McCarthy was a student of Church's at Princeton, so when McCarthy invented Lisp in 1958, he adopted the lambda notation. There were no Greek letters on the key punches of that era, so McCarthy used (lambda (x) (+ x x)) .. and it has survived to this day."

Wednesday, December 14, 2016

Winston & Horn: A Propositional Calculus Resolution Theorem Prover in Lisp

From by Patrick Winston's and Berthold Horn's famous classic on AI and Lisp (1981) - the first edition is available as a PDF here.

Amazon link:(3rd edition)


How to code a resolution theorem prover for the propositional calculus in Lisp (page 232).

---

Resolution is one way to Prove Theorems In Propositional Calculus 

Theorem Proving is a highly developed field that requires considerable mathematical sophistication to understand fully. Still, if we limit ourselves to proofs in the propositional calculus, we can build a simple theorem prover. It will be based on the so-called resolution principle (which can be extended to deal with the more difficult problems of the predicate calculus). The key to this theorem prover, again, is a matcher.

A theorem in the propositional calculus, for our purpose, consists of a premise and a conclusion, both expressed in LISP-like prefix notation. The following sets up a typical premise and conclusion:

(SETQ PREMISE
   '(AND (OR Q (NOT P))
               (OR R (NOT Q))
               (OR S (NOT R))
               (OR (NOT U) (NOT S))))

(SETQ CONCLUSION
   '(AND (OR (NOT P) (NOT U))))

These are examples of conjunctive normal form since only atoms appear inside NOTs, only NOTs or atoms appear inside ORs, and only ORs appear inside ANDs. Each of the OR lists is called a clause. Each atom or atom with a NOT is called a literal.

Our theorem prover will use the assumption that all inputs are in conjunctive normal form because it can be shown that anything written in terms of ANDs, ORs, and NOTs can be placed in equivalent conjunctive normal form.

■ To prove a theorem, it must be shown that the premise implies the conclusion. For a premise to imply a conclusion, it must be that any combination of T and NIL values for the atoms in the premise that make the premise evaluate to T also makes the conclusion evaluate to T. Or said another way, to prove a theorem, it must be shown that any combination of literal values that makes the premise true also makes the conclusion true.

Clearly, theorems can be proved by simply trying all ways to bind the atoms to T and NIL, checking that no combination causes the premise to evaluate to T and the conclusion to NIL. Resolution offers an alternative. We first list the steps involved to give a general feel for what is involved, and then we will explain why they work.

■ Step 1: Negate the conclusion, put it into conjunctive normal form, and combine it with the premise.

In our example, negating the conclusion yields the following:

(AND (OR P) (OR U))

Combining this with the premise produces the following result:

(AND (OR P)
           (OR U)
           (OR Q (NOT P))
           (OR R (NOT Q))
           (OR S (NOT R))
           (OR (NOT U) (NOT S)))

■ Step 2: Search for two clauses in which the same atom appears naked in one and negated in the other. Form a new clause by combining everything in the two clauses except for the naked atom and its negation. The two clauses involved are said to resolve. The new clause is called a resolvent. Combine the resolvent with the other clauses.

For the example, the first and the third clauses resolve, producing a resolvent. That is, (OR P) and (OR Q (NOT P)) yield (OR Q). Combining this with the rest of the clauses yields this:

(AND (OR Q)
           (OR P)
           (OR U)
           (OR Q (NOT P))
           (OR R (NOT Q))
           (OR S (NOT R))
           (OR (NOT U) (NOT S)))

■ Step 3: Repeat step 2 until no two clauses resolve or two clauses resolve to (OR). If no two clauses resolve, report failure. If two resolve to (OR), report success.

The key step clearly is a matching process, the one that produces resolvents of two clauses. The following matching function does the job: 

(DEFUN RESOLVE (X Y)
    (PROG (REST-X REST-Y)
        (SETQ REST-Y (CDR Y))         ; Get rid of OR.
        (SETQ REST-X (CDR X))         ; Get rid of OR.
        LOOP
        (COND ((NULL REST-X) (RETURN 'NO-RESOLVENT))      ; Any atom left to try?
                     ((MEMBER ( INVERT (CAR REST-X)) REST-Y)        ; Is negation in Y?
                      (RETURN (CONS 'OR                                                   ; Add OR.
                                                     (COMBINE (CAR REST-X)           ; Tidy up.
                                                                          (APPEND (CDR X) (CDR Y)))))))
         (SETQ REST-X (CDR REST-X))
        (GO LOOP))) 


Note that two auxiliary functions are needed. INVERT returns a bare atom if the argument is in the form of (NOT <atom>) . It wraps its argument in a NOT if the argument is an atom. COMBINE gets rid of the match-causing atom and its negation and makes sure there are no repeated elements in the resulting clause:

(DEFUN INVERT (X)
               (COND ((ATOM X) (LIST 'NOT X))
                             (T (CADR X)))) 


(DEFUN COMBINE (A L)
               (COND ((NULL L) NIL)
                             ((OR (EQUAL A (CAR L))                                     ; Is it there?
                                      (EQUAL (INVERT A) (CAR L))                   ;  Is negation there?
                                      (MEMBER (CAR L) (CDR L)))                     ; Is it there twice?
                              (COMBINE A (CDR L)))                                       ; Then get rid of it.
                            (T (CONS (CAR L) (COMBINE A (CDR L))))))    ; Otherwise keep it.

The function PROVE consists of nested loops that search for resolvable clauses and add resolvents to the clause list. Here we show it applied to an example: 

(PROVE PREMISE NEGATION)
    (THE CLAUSE (OR Q (NOT P)))
    (AND THE CLAUSE (OR R (NOT Q)))
    (PRODUCE A RESOLVENT: (OR (NOT P) R))
    (THE CLAUSE (OR (NOT P) R))
    (AND THE CLAUSE (OR S (NOT R)))
    (PRODUCE A RESOLVENT: (OR (NOT P) S))
    (THE CLAUSE (OR (NOT P) S))
    (AND THE CLAUSE (OR (NOT U) (NOT S)))
    (PRODUCE A RESOLVENT: (OR (NOT P) (NOT U)))
    (THE CLAUSE (OR (NOT P) (NOT U)))
    (AND THE CLAUSE (OR P))
    (PRODUCE A RESOLVENT: (OR (NOT U)))
    (THE CLAUSE (OR (NOT U)))
    (AND THE CLAUSE (OR U))
    (PRODUCE THE EMPTY RESOLVENT)
    (THEOREM PROVED)

There are, incidentally, many ways to make resolution more efficient by limiting the attempts at resolving clauses. For example, any clause containing an atom and its negation can be ignored. 

(DEFUN PROVE (PREMISE NEGATION)
     (PROG (FIRST REST REMAINDER RESOLVENT CLAUSES)
          (SETQ CLAUSES (APPEND (CDR PREMISE)           ; Purge ANDS
                                                           (CDR NEGATION)))
          FIND-CLAUSE                                                       ; this is a label for 'GO' at end
          (SETQ REMAINDER CLAUSES)
         TRY-NEXT-X-CLAUSE
          (COND ((NULL REMAINDER) (RETURN '(THEOREM NOT PROVED))))
          (SETQ FIRST (CAR REMAINDER))
          (SETQ REST (CDR REMAINDER))
        TRY-NEXT-Y-CLAUSE
         (COND ((NULL REST) (SETQ REMAINDER (CDR REMAINDER))  ; Doesn't resolve.
                                                (GO TRY-NEXT-X-CLAUSE)))
         (SETQ RESOLVENT (RESOLVE FIRST (CAR REST)))                   ; Try resolving.
         (COND ((OR (EQUAL RESOLVENT 'NO-RESOLVENT)
                               (MEMBER RESOLVENT CLAUSES))                          ; Resolvent known.
                        (SETQ REST (CDR REST))
                        (GO TRY-NEXT-Y-CLAUSE))
                       ((NULL (CDR RESOLVENT))                                                ; Resolvent empty.
                        (PRINT (APPEND '(THE CLAUSE) (LIST FIRST)))
                        (PRINT (APPEND '(AND THE CLAUSE) (LIST (CAR REST))))
                        (PRINT '(PRODUCE THE EMPTY RESOLVENT))
                        (RETURN '(THEOREM PROVED)))
                      (T (SETQ CLAUSES (CONS RESOLVENT CLAUSES))         ; Resolvent is new.
                       (PRINT (APPEND '(THE CLAUSE) (LIST FIRST)))
                       (PRINT (APPEND '(AND THE CLAUSE) (LIST (CAR REST))))
                       (PRINT (APPEND '(PRODUCE A RESOLVENT:) (LIST RESOLVENT)))
                       (GO FIND-CLAUSE))))) 

---

I haven't yet tried to copy and paste this code into a Lisp system so there may be the odd parenthesis missing. After checking it out, my next step would be to remove all those confusing loops and write it in a recursive fashion. Also experiment with different control strategies, such as set-of-support.

But Heidi Morkland was way ahead of me.

I do find the archaic style rather attractive (CADR!).

---

Compare this PL resolution prover written in Prolog by Markus Triska in 2006.
Resolution calculus for propositional logic.

   Input is a formula in conjunctive normal form, represented as a
   list of clauses; clauses are lists of atoms and terms not/1.

   Example:

   ?- Clauses = [[p,not(q)], [not(p),not(s)], [s,not(q)], [q]],
      pl_resolution(Clauses, Rs),
      maplist(writeln, Rs).
   %@ [p,not(q)]-[not(p),not(s)]-->[not(q),not(s)]
   %@ [s,not(q)]-[not(q),not(s)]-->[not(q)]
   %@ [q]-[not(q)]-->[]

   Iterative deepening is used to find a shortest refutation.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */


pl_resolution(Clauses0, Chain) :-
        maplist(sort, Clauses0, Clauses), % remove duplicates
        length(Chain, _),
        pl_derive_empty_clause(Chain, Clauses).

pl_derive_empty_clause([], Clauses) :-
        member([], Clauses).
pl_derive_empty_clause([C|Cs], Clauses) :-
        pl_resolvent(C, Clauses, Rs),
        pl_derive_empty_clause(Cs, [Rs|Clauses]).

pl_resolvent((As0-Bs0) --> Rs, Clauses, Rs) :-
        member(As0, Clauses),
        member(Bs0, Clauses),
        select(Q, As0, As),
        select(not(Q), Bs0, Bs),
        append(As, Bs, Rs0),
        sort(Rs0, Rs), % remove duplicates
        maplist(dif(Rs), Clauses).
This may be a lot shorter but (as is often the case with Prolog programs) its operation is fairly opaque to me. In Lisp you see what you're doing; in Prolog you have to imagine execution through a complex, sprawling and invisible search tree.

I prefer Lisp.

---

And here's a resolution prover for the propositional calculus in Python.

Like I said, I prefer Lisp.

Friday, September 04, 2015

Clare vs. 'the Cat'

This afternoon I programmed my very first simulation of the family pet, Shadow. In this simplistic iteration, the cat plays a game with the user. The idea is to stack 20 cans of cat food. The user and the cat take turns to stack 1, 2 or three cans at a time: the first to 20 wins.

Here is a transcript of the start of play. The cat's moves are between asterisks ***; the user's moves are signposted with -->.

Miaow, my name is Shadow. The game is to stack 20 cans of cat food. You can choose 1 or 2 or 3 cans at each turn. Me too! First to 20 wins.

Do you want to play first? type y for yes, n for no followed by return.

So, do you want to play first (y/n and press return)? n

*** My move is 2 cans. Total number of cans = 2 ***

enter your number 1, 2 or 3 |: 2

--> You entered 2 cans. Total number of cans = 4

*** My move is 1 cans. Total number of cans = 5 ***

enter your number - 1, 2 or 3: |:  ...

And here is a video of my guinea pig, Clare, playing the cat. What was it that Kipling said about winning and losing? (You may have to double-click on video to get full screen).



The game was an exercise from 'The Art of Prolog' and it took me a while to develop the game-play to program. Here is the folder containing the Prolog program by the way: you may use it to infer the winning strategy.

Thursday, September 03, 2015

AI Progress Report



So I got 'Eliza' working today, the simplified version from 'The Art of Prolog'. Time to take stock and figure out where to go next.

First, Prolog. Its supporters always touted it as a higher-level language than Lisp - though I always found Lisp more congenial, I like to set up data structures and manipulate them explicitly. With Prolog you define relationships between things and the miraculous powers of unification and depth-first search with backtracking pull magical rabbits out of hats. The Eliza program in Prolog can be read in its entirety on one screen, ditto for the blocks world planning system.

This procedural power is the result of enormously complex recursive structures built at execution time by the Prolog system. It frequently defies one's powers of abstraction, short-term memory and inference to visualise what's actually going on. I know you're meant to read and understand the programs declaratively, but in reality you don't get too far without a consideration of what actually happens at run-time.

Still, the power to write ridiculously-powerful programs in just a few lines of code is addictive. It reminds me of the first time I fired the General-Purpose Machine Gun (GPMG). I was good with the Lee-Enfield rifle and prided myself on my accuracy; the GPMG just bounced around and hosed the target. So much power and so little control!

---

Eliza and the Blocks World Planner were little milestones I had set myself, like climbing Pen y Fan. Items on my bucket list if you like. So what next?

Once you know how to set up knowledge bases and inferential systems you have the tools for developing intelligent agents. But, as I have cited before on these pages, 'in the knowledge lies the power'. If your agent lives in a closed-world with a fixed and limited database and rule set, it's going to run out of new things to do pretty fast. The interest comes from its interactions with the wider world.

Yet as Doug Lenat noted in the context of his 'Cyc' project:
"Any time you look at any kind of real life piece of text or utterance that one human wrote or said to another human, it's filled with analogies, modal logic, belief, expectation, fear, nested modals, lots of variables and quantifiers," Lenat said. "Everyone else is looking for a free-lunch way to finesse that. Shallow chatbots show a veneer of intelligence or statistical learning from large amounts of data. Amazon and Netflix recommend books and movies very well without understanding in any way what they're doing or why someone might like something.

"It's the difference between someone who understands what they're doing and someone going through the motions of performing something."

Cycorp's product, Cyc, isn't "programmed" in the conventional sense. It's much more accurate to say it's being "taught." Lenat told us that most people think of computer programs as "procedural, [like] a flowchart," but building Cyc is "much more like educating a child."

"We're using a consistent language to build a model of the world," he said.

This means Cyc can see "the white space rather than the black space in what everyone reads and writes to each other." An author might explicitly choose certain words and sentences as he's writing, but in between the sentences are all sorts of things you expect the reader to infer; Cyc aims to make these inferences.

Consider the sentence, "John Smith robbed First National Bank and was sentenced to 30 years in prison." It leaves out the details surrounding his being caught, arrested, put on trial, and found guilty. A human would never actually go through all that detail because it's alternately boring, confusing, or insulting. You can safely assume other people know what you're talking about. It's like pronoun use - he, she, it - one assumes people can figure out the referent. This stuff is very hard for computers to understand and get right, but Cyc does both.

"If computers were human," Lenat told us, "they'd present themselves as autistic, schizophrenic, or otherwise brittle. It would be unwise or dangerous for that person to take care of children and cook meals, but it's on the horizon for home robots. That's like saying, 'We have an important job to do, but we're going to hire dogs and cats to do it.'"
Cyc has been in development since 1984 and its knowledge base currently contains over one million human-defined assertions, rules or common sense ideas. Yet it's still barely found practical use. I'm certainly not planning on reproducing that level of effort.

I think we're back to virtualizing the cat ...