use of jcog.list.FasterList in project narchy by automenta.
the class TaskLinkCurveBag method compress.
private void compress(Conj e, byte punc, NAR nar) {
int maxVol = nar.termVolumeMax.intValue();
e.event.forEachKeyValue((when, what) -> {
int eventCount = Conj.eventCount(what);
if (eventCount > 1 && eventCount < MAX_EVENTS) /* TODO allow choosing subset of events from a single time */
{
Term c = e.term(when);
if (c.volume() < maxVol && Task.validTaskTerm(c, punc, true)) {
FasterList<TaskLink.GeneralTaskLink> removed = new FasterList(eventCount);
final float[] pri = { 0 };
synchronized (items) {
e.forEachTerm(what, (Term t) -> {
TaskLink.GeneralTaskLink key = new TaskLink.GeneralTaskLink(t, punc, when, 0);
TaskLink.GeneralTaskLink r = (TaskLink.GeneralTaskLink) remove(key);
if (r != null) {
pri[0] += r.priElseZero();
removed.addIfNotNull(r);
}
});
if (removed.size() > 1) {
Concept cc = nar.conceptualize(c);
if (cc != null) {
put(new TaskLink.GeneralTaskLink(c, punc, Tense.dither(when, nar), pri[0]));
// SUCCESS
return;
}
}
// FAIL
// re-insert, sorry to waste your time
removed.forEach(this::put);
}
}
}
});
}
use of jcog.list.FasterList in project narchy by automenta.
the class ArithmeticIntroduction method apply.
public static Term apply(Term x, @Nullable Anon anon, Random rng) {
if ((anon == null && !x.hasAny(INT)) || x.complexity() < 3)
return x;
// find all unique integer subterms
IntHashSet ints = new IntHashSet();
x.recurseTerms((t) -> {
Int it = null;
if (t instanceof Anom) {
Anom aa = ((Anom) t);
Term ta = anon.get(aa);
if (ta.op() == INT)
it = ((Int) ta);
} else if (t instanceof Int) {
it = (Int) t;
}
if (it == null)
return;
ints.add((it.id));
});
// Set<Term> ints = ((Compound) x).recurseTermsToSet(INT);
int ui = ints.size();
if (ui <= 1)
// nothing to do
return x;
// increasing so that relational comparisons can assume that 'a' < 'b'
int[] ii = ints.toSortedArray();
// potential mods to select from
// FasterList<Supplier<Term[]>> mods = new FasterList(1);
IntObjectHashMap<List<Supplier<Term[]>>> mods = new IntObjectHashMap(ii.length);
Variable v = $.varDep("x");
// test arithmetic relationships
for (int a = 0; a < ui; a++) {
int ia = ii[a];
for (int b = a + 1; b < ui; b++) {
int ib = ii[b];
assert (ib > ia);
if (ib - ia < ia && (ia != 0)) {
mods.getIfAbsentPut(ia, FasterList::new).add(() -> new Term[] { Int.the(ib), $.func("add", v, $.the(ib - ia)) });
mods.getIfAbsentPut(ib, FasterList::new).add(() -> new Term[] { Int.the(ia), $.func("add", v, $.the(ia - ib)) });
} else if ((ia != 0 && ia != 1) && (ib != 0 && ib != 1) && Util.equals(ib / ia, (((float) ib) / ia), Float.MIN_NORMAL)) {
mods.getIfAbsentPut(ia, FasterList::new).add(() -> new Term[] { Int.the(ib), $.func("mul", v, $.the(ib / ia)) });
} else if (ia == -ib) {
// negation (x * -1)
mods.getIfAbsentPut(ia, FasterList::new).add(() -> new Term[] { Int.the(ib), $.func("mul", v, $.the(-1)) });
mods.getIfAbsentPut(ib, FasterList::new).add(() -> new Term[] { Int.the(ia), $.func("mul", v, $.the(-1)) });
}
}
}
if (mods.isEmpty())
return x;
// TODO fair select randomly if multiple of the same length
RichIterable<IntObjectPair<List<Supplier<Term[]>>>> mkv = mods.keyValuesView();
int ms = mkv.maxBy(e -> e.getTwo().size()).getTwo().size();
mkv.reject(e -> e.getTwo().size() < ms);
// convention: choose lowest base
MutableList<IntObjectPair<List<Supplier<Term[]>>>> mmm = mkv.toSortedListBy(IntObjectPair::getOne);
IntObjectPair<List<Supplier<Term[]>>> m = mmm.get(0);
int base = m.getOne();
Term baseTerm = Int.the(base);
if (anon != null)
baseTerm = anon.put(baseTerm);
Term yy = x.replace(baseTerm, v);
for (Supplier<Term[]> s : m.getTwo()) {
Term[] mm = s.get();
if (anon != null)
mm[0] = anon.put(mm[0]);
yy = yy.replace(mm[0], mm[1]);
}
Term y = CONJ.the(yy, SIM.the(baseTerm, v));
if (y.op() != CONJ) {
// something happened
return null;
}
if (x.isNormalized()) {
y = y.normalize();
}
return y;
}
use of jcog.list.FasterList in project narchy by automenta.
the class TimeGraph method solveDT.
boolean solveDT(Term x, Predicate<Event> each) {
assert (x.dt() == XTERNAL);
Subterms xx = x.subterms();
// FasterList<Event> events = new FasterList<>(byTerm.get(x.root()));
// for (int i = 0, eventsSize = events.size(); i < eventsSize; i++) {
// Event r = events.get(i);
// if (r instanceof Absolute) {
// if (r.id.subterms().equals(xx)) {
// if (!each.test(r))
// return false; //done
// }
// }
//
// }
int subs = xx.subs();
if (subs == 2) {
Term a = xx.sub(0);
Term b = xx.sub(1);
boolean aEqB = a.equals(b);
if (!a.hasXternal() && !b.hasXternal() && (aEqB || !commonSubEventsWithMultipleOccurrences(a, b))) {
UnifiedSet<Event> ae = new UnifiedSet(2);
solveOccurrence(event(a, TIMELESS), ax -> {
if (ax instanceof Absolute)
ae.add(ax);
return true;
});
int aes = ae.size();
if (aes > 0) {
if (aEqB) {
// same term, must have >1 absolute timepoints
if (aes > 1) {
Event[] ab = ae.toArray(new Event[aes]);
// Arrays.sort(ab, Comparator.comparingLong(Event::when));
for (int i = 0; i < ab.length; i++) {
Event abi = ab[i];
for (int j = 0; j < ab.length; j++) {
if (i == j)
continue;
if (!solveDT(x, abi.when(), dt(x, abi, ab[j]), each))
return false;
}
}
}
} else {
UnifiedSet<Event> be = new UnifiedSet(2);
solveOccurrence(event(b, TIMELESS), bx -> {
if (bx instanceof Absolute)
be.add(bx);
return true;
});
int bes = be.size();
if (bes > 0) {
// if (aes == 1 || bes == 1) {
if (!ae.allSatisfy(ax -> be.allSatisfyWith((bx, axx) -> solveDT(x, axx.when(), dt(x, axx, bx), each), ax)))
return false;
// }
}
}
}
}
// UnifiedSet<Event>[] abs = new UnifiedSet[2]; //exact occurrences of each subterm
FasterList<Event> rels = new FasterList<>(4);
// int[] phase = new int[]{0};
// int p = phase[0];
// if (z instanceof Absolute) {
// if (abs[p] == null) abs[p] = new UnifiedSet(2);
// abs[p].add(z);
// //}
// }
Consumer<Event> collect = rels::add;
byTerm.get(a).forEach(collect);
if (aEqB) {
// abs[1] = abs[0];
} else {
// phase[0] = 1;
byTerm.get(b).forEach(collect);
// if (abs[1] == null)
// byTerm.get(b.neg()).forEach(collect); //if nothing, look for negations
}
// if (abs[0] != null && abs[1] != null) {
// known exact occurrences for both subterms
// iterate all possibilities
// TODO order in some way
// TODO other simple cases: 1 -> N
// if (abs[0].size() == 1 && abs[1].size() == 1) {
// //simple case:
// Event aa = abs[0].iterator().next();
// Event bb = abs[1].iterator().next();
// if (!solveDT(x, each, aa, bb))
// return false;
// } else {
// if (!abs[0].allSatisfy(ae ->
// abs[1].allSatisfyWith((be, aaee) ->
// solveDT(x, each, aaee, be), ae)))
// return false;
// }
// }
int ns = rels.size();
if (ns > 0) {
if (ns > 1) {
// sort by volume
rels.sortThisByInt(s -> s.id.volume());
}
return bfs(rels, new CrossTimeSolver() {
@Override
protected boolean next(BooleanObjectPair<ImmutableDirectedEdge<Event, TimeSpan>> move, Node<nars.derive.time.TimeGraph.Event, nars.derive.time.TimeGraph.TimeSpan> next) {
// System.out.println(path);
long[] startDT = pathDT(next, a, b, path);
if (startDT == null)
// nothing at this step
return true;
long start = startDT[0];
long ddt = startDT[1];
return TimeGraph.this.solveDT(x, start, ddt, each);
}
});
}
// } else {
// assert (x.op() == CONJ);
// List<LongObjectPair<Term>> when = $.newArrayList();
// for (int ix = 0; ix < subs; ix++) {
// //assert(!z.hasXternal());
// solveOccurrence(event(xx.sub(ix), TIMELESS), (ze) -> {
// if (ze.when() == TIMELESS)
// return true; //keep trying
// when.add(pair(ze.when(), ze.id));
// return false; //just one, for now //TODO see if there are any others
// });
// }
// if (when.size() == subs) {
// when.sort(Comparator.comparingLong(LongObjectPair::getOne));
// long base = when.get(0).getOne();
// Term zz = when.get(0).getTwo();
// for (int i = 1; i < subs; i++) {
// LongObjectPair<Term> wgi = when.get(i);
// zz = Op.conjMerge(zz, 0, wgi.getTwo(), wgi.getOne() - base);
// if (zz instanceof Bool)
// return true; //failure
// }
// return each.test(event(zz, base));
// }
}
// last resort
return each.test(event(x, TIMELESS));
}
use of jcog.list.FasterList in project narchy by automenta.
the class AtomicExec method update.
public void update(NAR n) {
// if (!busy.compareAndSet(false, true))
// return; //in-progress
// probe all active concepts.
// remove any below desire threshold
// execute any above desire-belief threshold
// if no active remain, disable update service
long[] focus = n.timeFocus();
// List<Task> evoke = $.newArrayList(0);
float exeThresh = this.exeThresh.floatValue();
List<Term> dispatch = new FasterList(active.size());
active.forEach(x -> {
Term xx = x.get();
Concept c = n.concept(xx);
if (c == null) {
// concept disappeared
x.delete();
return;
}
Truth goalTruth = c.goals().truth(focus, n);
if (goalTruth == null || goalTruth.expectation() < exeThresh) {
x.delete();
// undesired
return;
}
Truth beliefTruth = c.beliefs().truth(focus, n);
/* assume false with no evidence */
if (beliefTruth != null && beliefTruth.expectation() > exeThresh) {
// satisfied
return;
}
logger.info("{} EVOKE (b={},g={}) {}", n.time(), beliefTruth, goalTruth, xx);
dispatch.add(xx);
x.delete();
// MetaGoal.learn(MetaGoal.Action, goal.cause(), g, n);
});
dispatch.forEach(tt -> {
exe.accept(tt, n);
});
active.commit();
if (active.isEmpty()) {
disable();
}
}
use of jcog.list.FasterList in project narchy by automenta.
the class Time method exeScheduled.
@Nullable
private List<SchedTask> exeScheduled() {
// now = now();
// SchedTask firstQuick = scheduled.peek(); //it's safe to call this outside synchronized block for speed
// if (firstQuick == null || firstQuick.when > now)
// return null; //too soon for the next one
long now = now();
long nextScheduled = scheduledNext.get();
if ((now < nextScheduled) || !(scheduledNext.compareAndSet(nextScheduled, Long.MAX_VALUE)))
return null;
try {
// preSched.drainTo(scheduled);
List<SchedTask> pending = // new LinkedList();
new FasterList(8);
int s = 0;
SchedTask p;
while ((p = preSched.poll()) != null && s++ <= MAX_PRE_SCHED) {
// limit by MAX in case the preSched continues filling while this is being processed
if (p.when <= now)
// bypass the queue
pending.add(p);
else
scheduled.offer(p);
}
SchedTask next;
while (((next = scheduled.peek()) != null) && (next.when <= now)) {
SchedTask actualNext = scheduled.poll();
assert (next == actualNext);
pending.add(next);
}
// if emptied the priority queue, delay indefintely. otherwise delay until the time of the next item not dequeued now
long nextNextWhen = next != null ? next.when : Long.MAX_VALUE;
scheduledNext.updateAndGet(z -> Math.min(z, nextNextWhen));
return pending.isEmpty() ? null : pending;
} catch (Throwable t) {
// logger.error() //TODO
t.printStackTrace();
// try again immediately
scheduledNext.set(now);
return null;
}
}
Aggregations