use of jcog.list.FasterList in project narchy by automenta.
the class Int method intersect.
// public static Term[] intersect(Term[] u) {
//
// TreeSet<Intlike> integers = new TreeSet();
// for (Term x : u) {
// if (x.op() == INT) {
// integers.add((Intlike) x);
// }
// }
//
// int ii = integers.size();
// if (ii < 2)
// return u; //one or less integers, do nothing about it
//
//
// TreeSet<Term> v = new TreeSet<>();
// for (Term uu : u)
// v.add(uu);
//
// Intlike a = integers.pollFirst();
// Intlike b = integers.pollFirst();
// Range ar = a.range();
// Range br = b.range();
// if (ar.isConnected(br)) {
// Intlike combined = Int.the(ar.span(br));
// v.remove(a);
// v.remove(b);
// v.add(combined);
// }
//
//
// return v.toArray(new Term[v.size()]);
//
// }
/**
* TODO permute other arrangements
*/
public static Term[] intersect(final Term... _subs) {
RoaringBitmap factoring = new RoaringBitmap();
int equalVolume = -1, equalStructure = -1;
int pureInts = 0;
for (int i = 0, subsLength = _subs.length; i < subsLength; i++) {
Term x = _subs[i];
if (!x.hasAny(Op.INT)) {
continue;
}
if (x.op() == INT)
pureInts++;
if (equalVolume != -1) {
if (x.volume() != equalVolume) {
// a term with non-matching volume
continue;
}
}
if (equalStructure != -1) {
if (x.structure() != equalStructure) {
continue;
}
}
equalVolume = x.volume();
equalStructure = x.structure();
factoring.add(i);
}
int ff = factoring.getCardinality();
if (ff < 2)
return sorted(_subs);
Term[] subs;
if (ff < _subs.length) {
subs = new Term[ff];
int j = 0;
for (int i = 0; i < _subs.length; i++) {
if (factoring.contains(i))
subs[j++] = _subs[i];
}
assert (j == ff);
} else {
subs = _subs;
}
if (subs.length == 3) {
Term[] rr;
// HACK try permutations to combine some but not all
Term[] ab = intersect(subs[0], subs[1]);
if (ab.length == 1) {
rr = intersect(ab[0], subs[2]);
} else {
Term[] bc = intersect(subs[1], subs[2]);
if (bc.length == 1) {
rr = intersect(bc[0], subs[0]);
} else {
Term[] ac = intersect(subs[0], subs[2]);
if (ac.length == 1) {
rr = intersect(ac[0], subs[1]);
} else {
rr = null;
}
}
}
if (rr != null) {
return intersectResult(factoring, ff, new FasterList(rr), _subs);
}
}
FasterList<Term> yAux = new FasterList(0);
if (pureInts == ff) {
// avoid the path stuff, just merge the int terms
SimpleIntSet s = new SimpleIntSet(ff);
for (Term x : subs) {
((Intlike) x).forEachInt(s::add);
}
int ns = s.size();
assert (ns > 1);
if (ns == 2) {
// simple case
Iterator<Integer> si = s.iterator();
int a = si.next();
int b = si.next();
if (Math.abs(a - b) > 1) {
yAux.add(Int.the(a));
yAux.add(Int.the(b));
} else {
if (a > b) {
int c = b;
b = a;
a = c;
}
yAux.add(Int.range(a, b));
}
} else {
features(s.iterator(), -1).forEachRemaining(yAux::add);
}
} else {
// paths * extracted sequence of numbers at given path for each subterm
Map<ByteList, Object> /*SimpleIntSet*/
data = new LinkedHashMap<>(subs.length);
// if a subterm is not an integer, check for equality of atoms (structure already compared abovec)
final boolean[] valid = { true };
subs[0].pathsTo(x -> x, d -> true, (p, x) -> {
// if (p.isEmpty())
// return true; //continue past root, of course the root term will be unique
ImmutableByteList path = null;
SimpleIntSet c = null;
int xVol = x.volume();
int xStruct = x.structure();
for (int others = 1; others < subs.length; others++) {
Term y = subs[others].subPath(p);
if (x.equals(y))
continue;
if (!x.hasAny(INT)) {
// and we expect differences but only in the INT
if (!y.equals(x)) {
valid[0] = false;
return false;
}
} else if (x.op() == INT) {
if (y.op() != INT) {
valid[0] = false;
return false;
}
if (path == null)
path = p.toImmutable();
// store the path to the integer(s)
if (c == null)
c = (SimpleIntSet) data.computeIfAbsent(path, (pp) -> new SimpleIntSet(2));
((Intlike) y).forEachInt(c::add);
} else {
// this is a term containing an INT but is not an INT; the structure must still match
if (xVol != y.volume() || xStruct != y.structure()) {
valid[0] = false;
return false;
}
}
}
if (x.op() == INT) {
if (c == null) {
if (path == null)
path = p.toImmutable();
data.put(path, c = new SimpleIntSet(1));
}
((Intlike) x).forEachInt(c::add);
}
return true;
});
if (!valid[0])
return _subs;
Iterator<Map.Entry<ByteList, Object>> entries = data.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<ByteList, Object> /*SimpleIntSet*/
e = entries.next();
SimpleIntSet s = (SimpleIntSet) e.getValue();
if (s.size() < 2) {
entries.remove();
// same integer value in each
continue;
}
// for each path where the other numerics are uniformly equal (only one unique value)
/*if (new HashSet(nn).size()==1)*/
Iterator<Integer> si = s.iterator();
if (e.getKey().isEmpty()) {
// root level, get as many as possible
features(si, -1).forEachRemaining(yAux::add);
entries.remove();
} else {
Iterator<Intlike> iii = features(si, 1);
if (iii == null || !iii.hasNext())
// discontiguous or otherwise ununifiable
return _subs;
e.setValue(iii.next());
}
}
Term y;
if (!data.isEmpty()) {
y = subs[0];
for (Map.Entry<ByteList, Object> /*Intlike*/
e : data.entrySet()) {
Object v = e.getValue();
y = y.transform(e.getKey(), (Term) v);
}
} else {
y = null;
}
if (subs.length == _subs.length && yAux.isEmpty()) {
if (y == null)
// ??
return _subs;
return new Term[] { y };
} else {
yAux.add(y);
}
}
return intersectResult(factoring, ff, yAux, _subs);
// int ffs = ff.size();
// if (ffs == 0 || ffs >= numInvolved) {
// //nothing would be gained; dont bother
// continue;
// }
//
// for (Intlike f : ff) {
// byte j = 0;
// for (Term x : subs) {
//
// if (!involved.contains(j)) {
// result.add(x);
// //System.out.println("1: " + result);
// } else {
//
//
// //x is contained within range expression p
// Term xpp = x.subs() > 0 ? x.subPath(pp) : x;
//
// boolean connected;
// if (xpp.op() == INT) {
// connected = (f.range().isConnected(((Intlike) xpp).range()));
// } else {
// connected = false;
// }
//
// if (connected) {
// Term y = x instanceof Compound ?
// x.transform(pp, f)
// : f;
// //if (!y.equals(x)) {
//
// if (!x.equals(y)) {
// subsumed.add(x);
// }
// result.add(y);
// //System.out.println(x + " 3: " + result + "\t + " + y);
// //}
// } else {
// result.add(x);
// }
// }
// j++;
// }
//
//
// }
//
// int results = result.size();
// if ((results == 1) /*|| (results > resultLimit * subCount)*/) {
// break; //reduced to one or exploded, go no further
// }
// }
// result.removeAll(subsumed);
//
// if (result.isEmpty()) {
// return subs;
// } else {
//
// Term[] rr = result.toArray(new Term[result.size()]);
// if (Arrays.equals(rr, subs))
// return rr;
// else
// return intersect(rr); //changed, recompress
//
// }
}
use of jcog.list.FasterList in project narchy by automenta.
the class Conj method term.
// private byte id(long w) {
//
// int i = times.indexOf(w);
// if (i!=-1) {
// return (byte) i;
// } else {
// int s = times.size();
// assert(s < Byte.MAX_VALUE);
// times.add(w);
// return (byte)s;
// }
// }
//
// short id(Term t, long w) {
// byte tb = id(t);
// byte wb = id(w);
// return (short) ((tb << 8) | wb);
// }
//
// byte termIndex(short s) {
// return (byte) ((s >> 8) & 0xff);
// }
// byte timeIndex(short s) {
// return (byte) (s & 0xff);
// }
public Term term() {
if (term != null)
return term;
int numTimes = event.size();
switch(numTimes) {
case 0:
return Null;
case 1:
break;
default:
break;
}
event.compact();
IntPredicate validator = null;
Object eternalWhat = event.get(ETERNAL);
Term eternal = term(ETERNAL, eternalWhat);
if (eternal != null) {
if (eternal instanceof Bool)
// override and terminates
return this.term = eternal;
if (numTimes > 1) {
if (eternal.op() == CONJ) {
// Subterms eteSub = eternal.subterms();
if (eternalWhat instanceof byte[]) {
byte[] b = (byte[]) eternalWhat;
validator = (i) -> indexOfZeroTerminated(b, (byte) -i) == -1;
} else {
RoaringBitmap b = (RoaringBitmap) eternalWhat;
validator = (i) -> !b.contains(-i);
}
} else {
Term finalEternal = eternal;
validator = (t) -> !finalEternal.equalsNeg(termsIndex.get(Math.abs(t - 1)).negIf(t < 0));
}
}
}
if (eternal != null && numTimes == 1)
// done
return eternal;
FasterList<LongObjectPair<Term>> e = new FasterList(numTimes - (eternal != null ? 1 : 0));
Iterator<LongObjectPair> ii = event.keyValuesView().iterator();
while (ii.hasNext()) {
LongObjectPair next = ii.next();
long when = next.getOne();
if (when == ETERNAL)
// already handled above
continue;
Term wt = term(when, next.getTwo(), validator);
if (wt == True) {
// canceled out
continue;
} else if (wt == False) {
// short-circuit false
return this.term = False;
} else if (wt == Null) {
// short-circuit null
return this.term = Null;
}
e.add(pair(when, wt));
}
assert (!e.isEmpty());
Term temporal;
if (e.size() > 1) {
e.sortThisBy(LongObjectPair::getOne);
temporal = conjSeq(e);
if (temporal instanceof Bool)
return temporal;
} else {
temporal = e.get(0).getTwo();
}
return eternal != null ? // Op.instance(CONJ, DTERNAL, sorted(eternal, temporal))
CONJ.the(DTERNAL, sorted(eternal, temporal)) : temporal;
}
use of jcog.list.FasterList in project narchy by automenta.
the class AIMATests method assertBelief.
static void assertBelief(NAR n, boolean expcted, String x, int time) {
final int metricPeriod = 150;
PairedStatsAccumulator timeVsConf = new PairedStatsAccumulator();
float symConf = 0;
Task y = null;
List<Float> evis = new FasterList();
for (int i = 0; i < time; i += metricPeriod) {
n.run(metricPeriod);
y = n.belief($.the(x));
if (y != null) {
symConf = y.conf();
}
evis.add(c2wSafe(symConf, 1));
timeVsConf.add(n.time(), symConf);
}
assertNotNull(y);
assertTrue(y.isPositive() == expcted && y.polarity() > 0.5f);
for (char c : "ABLMPQ".toCharArray()) {
Term t = $.the(String.valueOf(c));
Task cc = n.belief($.the(c));
System.out.println(cc);
}
System.out.println(timeVsConf.yStats());
System.out.println(SparkLine.renderFloats(evis, 8));
}
use of jcog.list.FasterList in project narchy by automenta.
the class HullLibrary method createConvexHull.
/**
* Converts point cloud to polygonal representation.
*
* @param desc describes the input request
* @param result contains the result
* @return whether conversion was successful
*/
public boolean createConvexHull(HullDesc desc, HullResult result) {
boolean ret = false;
PHullResult hr = new PHullResult();
int vcount = desc.vcount;
if (vcount < 8)
vcount = 8;
FasterList<v3> vertexSource = new FasterList<>();
MiscUtil.resize(vertexSource, vcount, v3.class);
v3 scale = new v3();
int[] ovcount = new int[1];
// normalize point cloud, remove duplicates!
boolean ok = cleanupVertices(desc.vcount, desc.vertices, desc.vertexStride, ovcount, vertexSource, desc.normalEpsilon, scale);
if (ok) {
// if ( 1 ) // scale vertices back to their original size.
for (int i = 0; i < ovcount[0]; i++) {
// return array[index];
v3 v = vertexSource.get(i);
VectorUtil.mul(v, v, scale);
}
ok = computeHull(ovcount[0], vertexSource, hr, desc.maxVertices);
if (ok) {
// re-index triangle mesh so it refers to only used vertices, rebuild a new vertex table.
FasterList<v3> vertexScratch = new FasterList<>();
MiscUtil.resize(vertexScratch, hr.vcount, v3.class);
bringOutYourDead(hr.vertices, hr.vcount, vertexScratch, ovcount, hr.indices, hr.indexCount);
ret = true;
if (desc.hasHullFlag(HullFlags.TRIANGLES)) {
// if he wants the results as triangle!
result.polygons = false;
result.numOutputVertices = ovcount[0];
MiscUtil.resize(result.outputVertices, ovcount[0], v3.class);
result.numFaces = hr.faceCount;
result.numIndices = hr.indexCount;
MiscUtil.resize(result.indices, hr.indexCount, 0);
for (int i = 0; i < ovcount[0]; i++) {
// return array[index];
// return array[index];
result.outputVertices.get(i).set(vertexScratch.get(i));
}
if (desc.hasHullFlag(HullFlags.REVERSE_ORDER)) {
IntArrayList source_ptr = hr.indices;
int source_idx = 0;
IntArrayList dest_ptr = result.indices;
int dest_idx = 0;
for (int i = 0; i < hr.faceCount; i++) {
dest_ptr.set(dest_idx + 0, source_ptr.get(source_idx + 2));
dest_ptr.set(dest_idx + 1, source_ptr.get(source_idx + 1));
dest_ptr.set(dest_idx + 2, source_ptr.get(source_idx + 0));
dest_idx += 3;
source_idx += 3;
}
} else {
for (int i = 0; i < hr.indexCount; i++) {
result.indices.set(i, hr.indices.get(i));
}
}
} else {
result.polygons = true;
result.numOutputVertices = ovcount[0];
MiscUtil.resize(result.outputVertices, ovcount[0], v3.class);
result.numFaces = hr.faceCount;
result.numIndices = hr.indexCount + hr.faceCount;
MiscUtil.resize(result.indices, result.numIndices, 0);
for (int i = 0; i < ovcount[0]; i++) {
// return array[index];
// return array[index];
result.outputVertices.get(i).set(vertexScratch.get(i));
}
// if ( 1 )
IntArrayList source_ptr = hr.indices;
int source_idx = 0;
IntArrayList dest_ptr = result.indices;
int dest_idx = 0;
for (int i = 0; i < hr.faceCount; i++) {
dest_ptr.set(dest_idx + 0, 3);
if (desc.hasHullFlag(HullFlags.REVERSE_ORDER)) {
dest_ptr.set(dest_idx + 1, source_ptr.get(source_idx + 2));
dest_ptr.set(dest_idx + 2, source_ptr.get(source_idx + 1));
dest_ptr.set(dest_idx + 3, source_ptr.get(source_idx + 0));
} else {
dest_ptr.set(dest_idx + 1, source_ptr.get(source_idx + 0));
dest_ptr.set(dest_idx + 2, source_ptr.get(source_idx + 1));
dest_ptr.set(dest_idx + 3, source_ptr.get(source_idx + 2));
}
dest_idx += 4;
source_idx += 3;
}
}
releaseHull(hr);
}
}
return ret;
}
use of jcog.list.FasterList in project narchy by automenta.
the class ExeCharts method metaGoalChart.
private static Surface metaGoalChart(NAgent a) {
return new TreeChart<Cause>() {
final DurService on;
final FasterList<ItemVis<Cause>> cache = new FasterList();
final Function<Cause, TreeChart.ItemVis<Cause>> builder = ((i) -> {
short id = i.id;
ItemVis<Cause> item;
if (cache.capacity() - 1 < id)
cache.ensureCapacity(id + 16);
else {
item = cache.get(id);
if (item != null)
return item;
}
String str = i.toString();
if (str.startsWith("class nars."))
// skip default toString
str = str.substring("class nars.".length());
if (str.startsWith("class "))
// skip default toString
str = str.substring(5);
item = new CauseVis(i, str);
cache.set(id, item);
return item;
});
{
on = a.onFrame(() -> {
update(a.nar().causes, (c, i) -> {
float v = c.value();
float r, g, b;
if (v < 0) {
r = 0.75f * Math.max(0.1f, Math.min(1f, -v));
g = 0;
} else {
g = 0.75f * Math.max(0.1f, Math.min(1f, +v));
r = 0;
}
float t = Util.sum(((FloatFunction<Traffic>) (p -> Math.abs(p.last))), c.goal);
b = Math.max(r, g) / 2f * Util.unitize(t);
i.update(v, r, g, b);
// i.updateMomentum(
// //0.01f + Util.sqr(Util.tanhFast(v)+1),
// //Math.signum(v) *(1+Math.abs(v))*(t),
// //Math.signum(v) * t,
// v,
// 0.25f,
// r, g, b);
}, builder);
});
}
@Override
public void stop() {
super.stop();
on.off();
}
};
}
Aggregations