use of nars.NAR in project narchy by automenta.
the class Termify method test.
@Override
public final boolean test(Derivation d) {
NAR nar = d.nar;
nar.emotion.deriveEval.increment();
// d.xyDyn.clear();
Term c1 = pattern.eval(d);
if (!Taskify.valid(c1)) {
Term c1e = c1;
d.nar.emotion.deriveFailEval.increment(() -> {
return rule + " |\n\t" + d.xy + "\n\t -> " + c1e;
});
return false;
}
if (c1.volume() > d.termVolMax) {
d.nar.emotion.deriveFailVolLimit.increment();
return false;
}
if (c1.op() == NEG) {
c1 = c1.unneg();
if (// belief or goal
d.concTruth != null)
d.concTruth = d.concTruth.neg();
}
d.concEviFactor = 1f;
final long[] occ = d.concOcc;
occ[0] = occ[1] = ETERNAL;
Term c2;
if (d.temporal) {
boolean singleTime = d.task.isEternal() ? d.belief == null : d.single;
// d.single;
DeriveTime dt = singleTime ? d.dtSingle : d.dtDouble;
if (dt == null) {
dt = new DeriveTime(d, singleTime);
if (singleTime)
d.dtSingle = dt;
else
d.dtDouble = dt;
}
DeriveTime dtt = dt.get();
// dtt.print();
c2 = dtt.solve(c1);
// only should eliminate XTERNAL from beliefs and goals. ok if it's in questions/quests since it's the only way to express indefinite temporal repetition
if ((c1 != c2 && !Taskify.valid(c2)) || ((d.concPunc == BELIEF || d.concPunc == GOAL) && c2.hasXternal())) {
Term c1e = c1;
d.nar.emotion.deriveFailTemporal.increment(() -> {
return rule + "\n\t" + d + "\n\t -> " + c1e + "\t->\t" + c2;
});
return false;
}
if (occ[0] > occ[1]) {
// HACK swap the reversed occ
long x = occ[0];
occ[0] = occ[1];
occ[1] = x;
}
if (d.concPunc == GOAL && d.taskPunc == GOAL && !d.single && Op.values()[d._beliefOp].temporal) // d._beliefOp == IMPL.ordinal() //impl only
{
long derivedGoalStart = occ[0];
if (derivedGoalStart != ETERNAL) {
long taskWants = d.task.start();
if (taskWants == ETERNAL) {
// now
taskWants = d.time;
}
if (derivedGoalStart < taskWants) {
// derived goal occurrs before task goal, so shift to task start
long gdur = occ[1] - derivedGoalStart;
occ[0] = taskWants;
occ[1] = taskWants + gdur;
}
}
}
} else {
if (d.concPunc == BELIEF || d.concPunc == GOAL) {
c2 = c1.temporalize(Retemporalize.retemporalizeXTERNALToDTERNAL);
if (c1 != c2 && !Taskify.valid(c2)) {
d.nar.emotion.deriveFailTemporal.increment();
return false;
}
} else {
c2 = c1;
}
}
return d.derivedTerm.set(c2) != null;
}
use of nars.NAR in project narchy by automenta.
the class Premise method match.
/**
* resolve the most relevant belief of a given term/concept
* <p>
* patham9 project-eternalize
* patham9 depending on 4 cases
* patham9 https://github.com/opennars/opennars2/blob/a143162a559e55c456381a95530d00fee57037c4/src/nal/deriver/projection_eternalization.clj
* sseehh__ ok ill add that in a bit
* patham9 you need project-eternalize-to
* sseehh__ btw i disabled immediate eternalization entirely
* patham9 so https://github.com/opennars/opennars2/blob/a143162a559e55c456381a95530d00fee57037c4/src/nal/deriver/projection_eternalization.clj#L31
* patham9 especially try to understand the "temporal temporal" case
* patham9 its using the result of higher confidence
* <p>
* returns ttl used, -1 if failed before starting
*
* @param matchTime - temporal focus control: determines when a matching belief or answer should be projected to
*/
@Nullable
public Derivation match(Derivation d, long[] focus, int matchTTL) {
NAR n = d.nar;
if (task == null || task.isDeleted()) {
// }
return null;
}
// n.conceptualize(task.term(), (c)->{});
int dur = d.dur;
Term beliefTerm = term();
Term taskTerm = task.term();
Term taskConcept = task.term().concept();
final boolean[] beliefConceptCanAnswerTaskConcept = { false };
boolean unifiedBelief = false;
Op to = taskTerm.op();
Op bo = beliefTerm.op();
if (to == bo) {
if (taskConcept.equals(beliefTerm.concept())) {
beliefConceptCanAnswerTaskConcept[0] = true;
} else {
if ((bo.conceptualizable) && (beliefTerm.hasAny(var) || taskTerm.hasAny(var))) {
Term _beliefTerm = beliefTerm;
final Term[] unifiedBeliefTerm = new Term[] { null };
UnifySubst u = new UnifySubst(/*null*/
VAR_QUERY, n, (y) -> {
if (y.op().conceptualizable) {
y = y.normalize();
beliefConceptCanAnswerTaskConcept[0] = true;
if (!y.equals(_beliefTerm)) {
unifiedBeliefTerm[0] = y;
// stop
return false;
}
}
// keep going
return true;
}, matchTTL);
u.varSymmetric = true;
u.varCommonalize = true;
u.unify(taskTerm, beliefTerm, true);
if (unifiedBeliefTerm[0] != null) {
beliefTerm = unifiedBeliefTerm[0];
unifiedBelief = true;
}
}
}
}
// HACK ?? assert(beliefTerm.op()!=NEG);
beliefTerm = beliefTerm.unneg();
// QUESTION ANSWERING and TERMLINK -> TEMPORALIZED BELIEF TERM projection
Task belief = null;
// float timeFocus = n.timeFocus.floatValue();
// int fRad = Math.round(Math.max(1,dur * timeFocus));
final Concept beliefConcept = beliefTerm.op().conceptualizable ? // conceptualize in case of dynamic concepts
n.conceptualize(beliefTerm) : null;
if (beliefConcept != null) {
if (!beliefTerm.hasVarQuery()) {
// doesnt make sense to look for a belief in a term with query var, it will have none
final BeliefTable bb = beliefConcept.beliefs();
if (task.isQuestOrQuestion()) {
if (beliefConceptCanAnswerTaskConcept[0]) {
final BeliefTable answerTable = (task.isGoal() || task.isQuest()) ? beliefConcept.goals() : bb;
// //see if belief unifies with task (in reverse of previous unify)
// if (questionTerm.varQuery() == 0 || (unify((Compound)beliefConcept.term(), questionTerm, nar) == null)) {
//
// } else {
//
// }
Task match = answerTable.answer(task.start(), task.end(), dur, task, beliefTerm, n, d::add);
if (match != null) {
assert (task.isQuest() || match.punc() == BELIEF) : "quest answered with a belief but should be a goal";
@Nullable Task answered = task.onAnswered(match, n);
if (answered != null) {
n.emotion.onAnswer(task, answered);
}
if (match.isBelief()) {
belief = match;
}
}
}
}
if ((belief == null) && !bb.isEmpty()) {
belief = bb.match(focus[0], focus[1], beliefTerm, n, taskConcept.equals(beliefConcept.term()) ? x -> !x.equals(task) : null);
}
}
if (unifiedBelief) {
Concept originalBeliefConcept = n.conceptualize(term());
if (originalBeliefConcept != null)
linkVariable(originalBeliefConcept, beliefConcept);
}
}
if (belief != null) {
// use the belief's actual possibly-temporalized term
beliefTerm = belief.term().unneg();
// if (belief.equals(task)) { //do not repeat the same task for belief
// belief = null; //force structural transform; also prevents potential inductive feedback loop
// }
}
if (beliefTerm instanceof Bool) {
// logger.warn("{} produced Bool beliefTerm", this);
return null;
}
if (!d.reset().proto(task, belief, beliefTerm))
return null;
return d;
}
use of nars.NAR in project narchy by automenta.
the class Exec method executeNow.
/**
* inline, synchronous
*/
final void executeNow(Object t) {
try {
if (t instanceof ITask) {
ITask x = (ITask) t;
NAR nar = this.nar;
while ((x = x.run(nar)) != null) ;
} else if (t instanceof Runnable)
((Runnable) t).run();
else
// if (t instanceof Consumer)
((Consumer) t).accept(nar);
// else {
// throw new UnsupportedOperationException(t + " unexecutable");
// }
} catch (Throwable e) {
logger.error("{} {}", t, Param.DEBUG ? e : e.getMessage());
}
}
use of nars.NAR in project narchy by automenta.
the class DeriveRuleSet method rules.
public static DeriveRuleSet rules(NAR nar, Collection<String> filename) {
PatternIndex p = new PatternIndex();
p.nar = nar;
return new DeriveRuleSet(filename.stream().flatMap(n -> ruleCache.apply(n).stream()), p, nar);
}
use of nars.NAR in project narchy by automenta.
the class ConjClustering method conjoinCentroid.
// /**
// * produces a parallel conjunction term consisting of all the task's terms
// */
// public Stream<List<Task>> chunk(Stream<Task> input, int maxComponentsPerTerm, int maxVolume) {
// final int[] group = {0};
// final int[] subterms = {0};
// final int[] currentVolume = {0};
// final float[] currentConf = {1};
// return input.filter(x -> !x.isDeleted())
// .collect(Collectors.groupingBy(x -> {
//
// int v = x.volume();
// float c = x.conf();
//
// if ((subterms[0] >= maxComponentsPerTerm) || (currentVolume[0] + v >= maxVolume) || (currentConf[0] * c < confMin)) {
// //next group
// group[0]++;
// subterms[0] = 1;
// currentVolume[0] = v;
// currentConf[0] = c;
// } else {
// subterms[0]++;
// currentVolume[0] += v;
// currentConf[0] *= c;
// }
//
// return group[0];
// }))
// .entrySet().stream()
// .map(c -> {
// List<Task> v = c.getValue();
// return c.getKey() >= 0 && //only batches of >1
// v.size() > 1 ? v : null; //ignore the -1 discard group
// })
// .filter(Objects::nonNull);
//
// }
// static final BiFunction<Task, Task, Task> termPointMerger = (prevZ, newZ) -> ((prevZ == null) || (newZ.conf() >= prevZ.conf())) ?
// newZ : prevZ;
private List<Task> conjoinCentroid(Stream<VLink<Task>> group, Pair<NAR, List<Task>> narAndTarget) {
NAR nar = narAndTarget.getOne();
// get only the maximum confidence task for each term at its given starting time
// in.input(
// chunk(group.filter(Objects::nonNull).takeWhile(kontinue)
// .map(x -> x.id), maxConjSize, volMax).takeWhile(kontinue).map(tasks -> {
Iterator<VLink<Task>> gg = group.filter(x -> x != null && !x.isDeleted()).iterator();
// Iterators.peekingIterator();
Map<LongObjectPair<Term>, Task> vv = new HashMap<>();
FasterList<Task> actualTasks = new FasterList();
int centroidGen = 0;
List<Task> gen = narAndTarget.getTwo();
main: while (gg.hasNext() && centroidGen < taskLimitPerCentroid) {
vv.clear();
actualTasks.clear();
long end = Long.MIN_VALUE;
long start = Long.MAX_VALUE;
int dur = nar.dur();
float freq = 1f;
float conf = 1f;
float priMax = Float.NEGATIVE_INFINITY, priMin = Float.POSITIVE_INFINITY;
int vol = 0;
int maxVolume = 0;
do {
if (!gg.hasNext())
break;
Task t = gg.next().id;
// gg.peek().id;
Term xt = t.term();
long zs = Tense.dither(t.start(), ditherTime);
long ze = Tense.dither(t.end(), ditherTime);
// assert (end >= start);
Truth tx = t.truth();
Term xtn = xt.neg();
if (tx.isNegative()) {
xt = xtn;
}
int xtv = xt.volume();
maxVolume = Math.max(maxVolume, xt.volume());
if (vol + xtv + 1 >= volMax || conf * tx.conf() < confMin) {
// cant go any further with this task
continue;
}
boolean involved = false;
LongObjectPair<Term> ps = pair(zs, xt);
Term xtNeg = xt.neg();
if (!vv.containsKey(pair(zs, xtNeg)) && null == vv.putIfAbsent(ps, t)) {
vol += xtv;
if (start > zs)
start = zs;
if (end < zs)
end = zs;
involved = true;
}
if (ze - zs >= dur) {
// endpoint
if (vol + xtv + 1 < volMax) {
LongObjectPair<Term> pe = pair(ze, xt);
if (!vv.containsKey(pair(ze, xtNeg)) && null == vv.putIfAbsent(pe, t)) {
// end point, if different from start
vol += xtv;
if (end < ze)
end = ze;
involved = true;
}
}
}
if (involved) {
actualTasks.add(t);
conf *= tx.conf();
float tf = tx.freq();
// since it will appear as a negated subterm
freq *= tx.isNegative() ? (1f - tf) : tf;
float p = t.priElseZero();
if (p < priMin)
priMin = p;
if (p > priMax)
priMax = p;
}
} while (vol < volMax - 1 && conf > confMin);
int vs = actualTasks.size();
if (vs < 2)
continue;
// the tasks which are actually involved
Task[] uu = actualTasks.toArrayRecycled(Task[]::new);
// TODO discount based on evidential overlap? needs N-way overlapFraction function
ObjectFloatPair<long[]> evidence = Stamp.zip(actualTasks, Param.STAMP_CAPACITY);
float overlap = evidence.getTwo();
float e = c2w(conf) * Param.overlapFactor(overlap);
if (e > 0) {
final Truth t = Truth.theDithered(freq, e, nar);
if (t != null) {
Term cj = Conj.conj(vv.keySet());
if (cj != null) {
cj = cj.normalize();
if (Math.abs(cj.dtRange() - (end - start)) < ditherTime) {
// test if merge collapse occurred and occurrence time needs recalculated
ObjectBooleanPair<Term> cp = Task.tryContent(cj, punc, true);
if (cp != null) {
// TODO use a truth calculated specific to this fixed-size batch, not all the tasks combined
NALTask m = new STMClusterTask(cp, t, start, start, evidence.getOne(), punc, now);
// if (evidence.getTwo() > 0) m.setCyclic(true);
m.cause = Cause.sample(Param.causeCapacity.intValue(), uu);
float p = // priMax;
priMin;
// (priMin + priMax) / 2f;
// complexity deduction
// how much more complex the conjunction is than the most complex of its ingredients
int v = cp.getOne().volume();
float cmplFactor = ((float) v) / (v + maxVolume);
m.priSet(Priority.fund(p * cmplFactor, true, uu));
gen.add(m);
centroidGen++;
}
} else {
// System.out.println("merge collapse, recalcu");
}
}
}
}
}
return gen.isEmpty() ? null : gen;
}
Aggregations