use of nars.term.var.Variable in project narchy by automenta.
the class KIFInput method impl.
// private Variable nextVar(Op v) {
// return $.v(v, nextVar());
// }
// private final AtomicInteger serial = new AtomicInteger(0);
// private String nextVar() {
// return Integer.toString(Math.abs(serial.incrementAndGet()), 36);
// }
// public final Set<Twin<Term>> impl = new HashSet();
public Term impl(Term a, Term b, boolean implOrEquiv) {
// reduce as implication first
Term tmp = IMPL.the(a, b);
if (tmp.unneg().op() != IMPL) {
logger.warn("un-impl: {} ==> {} ", a, b);
return null;
}
tmp = tmp.unneg();
a = tmp.sub(0);
b = tmp.sub(1);
MutableSet<Term> aVars = new VarOnlySet();
if (a instanceof Compound)
((Compound) a).recurseTermsToSet(Op.VariableBits, aVars, true);
else if (a.op().var)
aVars.add(a);
MutableSet<Term> bVars = new VarOnlySet();
if (b instanceof Compound)
((Compound) b).recurseTermsToSet(Op.VariableBits, bVars, true);
else if (b.op().var)
bVars.add(b);
Map<Term, Term> remap = new HashMap();
MutableSet<Term> common = aVars.intersect(bVars);
if (!common.isEmpty()) {
common.forEach(t -> {
Variable u = $.v(Op.VAR_INDEP, // Op.VAR_PATTERN,
t.toString().substring(1));
if (!t.equals(u))
remap.put(t, u);
});
}
for (MutableSet<Term> ab : new MutableSet[] { aVars, bVars }) {
ab.forEach(aa -> {
if (aa.op() == VAR_INDEP && !common.contains(aa)) {
remap.put(aa, $.v(Op.VAR_DEP, aa.toString().substring(1)));
}
});
}
if (!remap.isEmpty()) {
a = a.replace(remap);
if (a == null)
throw new NullPointerException("transform failure");
b = b.replace(remap);
if (b == null)
throw new NullPointerException("transform failure");
}
try {
return implOrEquiv ? IMPL.the(a, b) : equi(a, b);
} catch (Exception ignore) {
ignore.printStackTrace();
}
return null;
}
use of nars.term.var.Variable in project narchy by automenta.
the class Builtin method registerFunctors.
public static void registerFunctors(NAR nar) {
for (Concept t : Builtin.statik) {
nar.on(t);
}
nar.on(Functor.f1("varIntro", (x) -> {
Pair<Term, Map<Term, Term>> result = DepIndepVarIntroduction.the.apply(x, nar.random());
return result != null ? result.getOne() : Null;
}));
nar.on(Functor.f1((Atom) $.the("termlinkRandom"), (Term t) -> {
@Nullable Concept c = nar.conceptualize(t);
if (c == null)
return Null;
@Nullable PriReference<Term> tl = c.termlinks().sample(nar.random());
if (tl == null)
return Null;
return tl.get();
}));
// nar.on(Functor.f("service", (TermContainer c) ->
// $.sete(
// nar.services().map(
// (e) ->
// $.p(e, $.the(e.getValue().state())))
// .toArray(Term[]::new)
// )
// ));
/**
* subterm, but specifically inside an ellipsis. otherwise pass through
*/
nar.on(Functor.f("esubterm", (Subterms c) -> {
Term x = c.sub(0, null);
if (x == null)
return Null;
Term index = c.sub(1, Null);
if (index == Null)
return Null;
int which;
if (index != null) {
if (index instanceof Variable)
return Null;
which = $.intValue(index, -1);
if (which < 0) {
return Null;
}
} else {
// random
which = nar.random().nextInt(x.subs());
}
return x.sub(which);
}));
nar.on(Functor.f2((Atom) $.the("without"), (Term container, Term content) -> Op.without(container, x -> x.equals(content), nar.random())));
nar.on(Functor.f2((Atom) $.the("withoutPosOrNeg"), (Term container, Term content) -> Op.without(container, x -> x.unneg().equals(content), nar.random())));
/**
* TODO rename this to 'dropAnyCommutive'
* remove an element from a commutive conjunction (or set), at random, and try re-creating
* the compound. wont necessarily work in all situations.
* TODO move the type restriction to another functor to wrap this
*
* this also filter a single variable (depvar) from being a result
*/
nar.on(Functor.f1((Atom) $.the("dropAnySet"), (Term t) -> {
Op oo = t.op();
if (oo == INT) {
if (t instanceof Int.IntRange) {
// select random location in the int and split either up or down
Int.IntRange i = (Int.IntRange) t;
Random rng = nar.random();
if (i.min + 1 == i.max) {
// arity=2
return Int.the(rng.nextBoolean() ? i.min : i.max);
} else if (i.min + 2 == i.max) {
// arity=3
switch(rng.nextInt(4)) {
case 0:
return Int.the(i.min);
case 1:
return Int.range(i.min, i.min + 1);
case 2:
return Int.range(i.min + 1, i.min + 2);
case 3:
return Int.the(i.max);
default:
throw new UnsupportedOperationException();
}
} else {
int split = // midpoint, deterministic
(i.max + i.min) / 2;
// rng.nextInt(i.max-i.min-2);
return (rng.nextBoolean()) ? Int.range(i.min, split + 1) : Int.range(split + 1, i.max);
}
}
// cant drop int by itself
return Null;
}
if (!oo.in(SETi.bit | SETe.bit | SECTi.bit | SECTe.bit))
// returning the original value may cause feedback loop in callees expcting a change in value
return Null;
int size = t.subs();
switch(size) {
case 0:
assert (false) : "empty set impossible here";
return Null;
case 1:
return Null;
/* can't shrink below one element */
case 2:
int n = nar.random().nextInt(2);
return oo.the(t.sub(n));
default:
Term[] y = Terms.dropRandom(nar.random(), t.subterms());
return oo.the(y);
}
}));
/**
* depvar cleaning from commutive conj
*/
nar.on(Functor.f1((Atom) $.the("ifConjCommNoDepVars"), (Term t) -> {
if (!t.hasAny(VAR_DEP))
return t;
Op oo = t.op();
if (oo != CONJ)
return t;
SortedSet<Term> s = t.subterms().toSetSorted();
if (!s.removeIf(x -> x.unneg().op() == VAR_DEP))
return t;
return CONJ.the(t.dt(), s);
}));
/**
* drops a random contained event, whether at first layer or below
*/
nar.on(Functor.f1((Atom) $.the("dropAnyEvent"), (Term t) -> {
Op oo = t.op();
if (oo != CONJ)
// returning the original value may cause feedback loop in callees expcting a change in value
return Null;
FasterList<LongObjectPair<Term>> ee = Conj.eventList(t);
ee.remove(nar.random().nextInt(ee.size()));
return Conj.conj(ee);
// }
// if (r instanceof Variable /*&& r.op()!=VAR_DEP*/)
// return Null; //HACK dont allow returning a variable as an event during decomposition HACK TODO make more careful and return the only result if one subterm is a non-returnable variable
// return r;
}));
nar.on(Functor.f2((Atom) $.the("conjEvent"), (Term c, Term when) -> {
if (c.op() != CONJ || !(when instanceof Atom))
return Null;
// extract earliest or latest &| timeslice of events
throw new TODO();
// if (c.dt() == DTERNAL || c.dt() == 0) {
// return c.sub(nar.random().nextInt(c.subs())); //choose a subterm at random
// }
// assert (c.subs() == 2);
// int target;
// switch (when.toString()) {
// case "early":
// target = 0;
// break;
// case "late":
// target = 1;
// break;
// default:
// throw new UnsupportedOperationException();
// }
// if (c.dt() < 0)
// target = 1 - target;
// return c.sub(target);
}));
/**
* similar to without() but special handling for CONJ sub-events
*/
nar.on(Functor.f2((Atom) $.the("conjWithout"), (Term conj, Term event) -> {
if (conj.op() != CONJ || conj.impossibleSubTerm(event))
return Null;
FasterList<LongObjectPair<Term>> events = Conj.eventList(conj);
IntArrayList found = new IntArrayList(2);
int es = events.size();
assert (es > 1);
for (int i = 0; i < es; i++) {
if (event.equalsRoot(events.get(i).getTwo())) {
found.add(i);
}
}
int fs = found.size(), r;
switch(fs) {
case 0:
return Null;
case 1:
r = found.get(0);
break;
default:
r = found.get(nar.random().nextInt(fs));
break;
}
events.remove(r);
return Conj.conj(events);
// } else {
// return nullToNull(Op.without(conj, event::equalsRoot, nar.random()));
// }
}));
/**
* extracts only the events preceding the specified events
*/
nar.on(Functor.f2((Atom) $.the("conjDropIfLatest"), (Term conj, Term event) -> Conj.conjDrop(conj, event, false)));
nar.on(Functor.f2((Atom) $.the("conjDropIfEarliest"), (Term conj, Term event) -> Conj.conjDrop(conj, event, true)));
nar.on(Functor.f1Concept("belief", nar, (c, n) -> $.quote(n.belief(c, n.time()))));
nar.on(Functor.f1Concept("goal", nar, (c, n) -> $.quote(n.goal(c, n.time()))));
nar.on(f0("self", nar::self));
nar.on(Functor.f1("the", what -> {
if (what instanceof Atom) {
switch(what.toString()) {
case "sys":
return $.p($.quote(nar.emotion.summary()), $.quote(nar.concepts.summary()), $.quote(nar.emotion.summary()), $.quote(nar.exe.toString()));
}
}
Object x = nar.concept(what);
if (x == null)
x = what;
return $.quote($.p($.quote(x.getClass().toString()), $.quote(x.toString())));
}));
// /** slice(<compound>,<selector>)
// selector :-
// a specific integer value index, from 0 to compound size
// (a,b) pair of integers, a range of indices */
nar.on(Functor.f("slice", (args) -> {
if (args.subs() == 2) {
Term x = args.sub(0);
if (x.subs() > 0) {
int len = x.subs();
Term index = args.sub(1);
Op o = index.op();
if (o == INT) {
// specific index
int i = ((Int) index).id;
if (i >= 0 && i < len)
return x.sub(i);
else
return False;
} else if (o == PROD && index.subs() == 2) {
Term start = (index).sub(0);
if (start.op() == INT) {
Term end = (index).sub(1);
if (end.op() == INT) {
int si = ((Int) start).id;
if (si >= 0 && si < len) {
int ei = ((Int) end).id;
if (ei >= 0 && ei <= len) {
if (si == ei)
return Op.EmptyProduct;
if (si < ei) {
return $.p(Arrays.copyOfRange(x.subterms().arrayClone(), si, ei));
}
}
}
// TODO maybe reverse order will return reversed subproduct
return False;
}
}
}
}
}
return null;
}));
}
use of nars.term.var.Variable in project narchy by automenta.
the class CaffeineIndex2 method get.
@Override
public Termed get(Term x, boolean createIfMissing) {
if (x.volume() > nar.termVolumeMax.intValue())
// quick check to avoid creating a vector for a term that will be invalid anyway
return null;
assert (!(x instanceof Variable)) : "variables should not be stored in index";
Op op = x.op();
TermContainerToOpMap<Termed> v;
if (createIfMissing) {
v = vectors.get(vector(x), k -> {
TermContainerToOpMap<Termed> t = new TermContainerToOpMap<>(k);
Termed p = nar.conceptBuilder.apply(x, null);
if (p != null)
t.compareAndSet(op.id, null, p);
return t;
});
} else {
v = vectors.getIfPresent(vector(x));
}
return v != null ? v.get(op.id) : null;
}
use of nars.term.var.Variable in project narchy by automenta.
the class Subterms method compare.
// default int compareTo(/*@NotNull*/ Termlike o) {
// return compareTo(this, o);
// }
static int compare(/*@NotNull*/
Subterms a, /*@NotNull*/
Subterms b) {
if (a.equals(b))
return 0;
int s;
int diff;
if ((diff = Integer.compare((s = a.subs()), b.subs())) != 0)
return diff;
// return diff;
if ((diff = Integer.compare(a.structure(), b.structure())) != 0)
return diff;
// this inequalVariable stuff is so that the displayed order of variables is in increasing number. HACK
Term inequalVariableX = null, inequalVariableY = null;
for (int i = 0; i < s; i++) {
Term x = a.sub(i);
Term y = b.sub(i);
if (x instanceof Variable && y instanceof Variable) {
if (inequalVariableX == null && !x.equals(y)) {
// test after; allow differing non-variable terms to determine sort order first
inequalVariableX = x;
inequalVariableY = y;
}
} else {
int d = x.compareTo(y);
if (d != 0) {
return d;
}
}
}
// 2nd-stage:
if (inequalVariableX != null) {
return inequalVariableX.compareTo(inequalVariableY);
} else {
return 0;
}
}
use of nars.term.var.Variable in project narchy by automenta.
the class TaskRule method accept.
@Override
protected void accept(Task X, Map<Term, Term> xy) {
Term y = output.replace(xy);
if (y instanceof Variable || y instanceof Bool)
return;
// if (r == null)
// return null;
//
// //unnegate and check for an apparent atomic term which may need decompressed in order to be the task's content
// boolean negated;
// Term s = r;
// if (r.op() == NEG) {
// s = r.unneg();
// if (s instanceof Variable)
// return null; //throw new InvalidTaskException(r, "unwrapped variable"); //should have been prevented earlier
//
// negated = true;
// if (s instanceof Compound) {
// return (Compound) r; //its normal compound inside the negation, handle it in Task constructor
// }
// } else if (r instanceof Compound) {
// return (Compound) r; //do not uncompress any further
// } else if (r instanceof Variable) {
// return null;
// } else {
// negated = false;
// }
//
// if (!(s instanceof Compound)) {
// Compound t = compoundOrNull(nar.post(s));
// if (t == null)
// return null; //throw new InvalidTaskException(r, "undecompressible");
// else
// return (Compound) $.negIf(t, negated); //done
// // else
// // else if (s.op()==NEG)
// // return (Compound) $.negIf(post(s.unneg(), nar));
// // else
// // return (Compound) $.negIf(s, negated);
// }
// //its a normal negated compound, which will be unnegated in task constructor
// return (Compound) s;
y = compoundOrNull(y);
if (y == null)
return;
y = y.normalize();
if (y == null)
return;
if (!Task.validTaskTerm(y, X.punc(), false))
return;
Task Y = Task.clone(X, y);
if (Y != null) {
logger.info("{}\t{}", X, Y);
nar.input(Y);
}
}
Aggregations