use of nars.term.atom.Bool in project narchy by automenta.
the class KIFInput method formulaToTerm.
public Term formulaToTerm(final Formula x, int level) {
// if (x.theFormula.contains("@ROW"))
// return null; //HACK ignore @ROW stuff
String xCar = x.car();
// root operate
String root = xCar;
int l = x.listLength();
if (l == -1)
return atomic(x.theFormula);
List<String> sargs = IntStream.range(1, l).mapToObj(x::getArgument).collect(Collectors.toList());
List<Term> args = sargs != null ? sargs.stream().map((z) -> formulaToTerm(z, level + 1)).collect(Collectors.toList()) : Collections.emptyList();
if (args.contains(null)) {
throw new NullPointerException("in: " + args);
}
// should have been handled first
assert (!args.isEmpty());
/**
* https://github.com/opencog/opencog/blob/04db8e557a2d67da9025fe455095d2cda0261ea7/opencog/python/sumo/sumo.py
* def special_link_type(predicate):
* mapping = {
* '=>':types.ImplicationLink,
* '<=>':types.EquivalenceLink,
* 'and':types.AndLink,
* 'or':types.OrLink,
* 'not':types.NotLink,
* 'instance':types.MemberLink,
* # This might break some of the formal precision of SUMO, but who cares
* 'attribute':types.InheritanceLink,
* 'member':types.MemberLink,
* 'subclass':types.InheritanceLink,
* 'exists':types.ExistsLink,
* 'forall':types.ForAllLink,
* 'causes':types.PredictiveImplicationLink
*/
Term y = null;
switch(root) {
case "ListFn":
return $.p(args);
case "subrelation":
case "subclass":
case "subAttribute":
if (includeSubclass) {
if (args.size() != 2) {
System.err.println("subclass expects 2 arguments");
} else {
y = INH.the(args.get(0), args.get(1));
}
}
break;
case "instance":
if (includeInstance) {
if (args.size() != 2) {
System.err.println("instance expects 2 arguments");
} else {
// $.inst
y = $.inh(args.get(0), args.get(1));
}
}
break;
case "relatedInternalConcept":
/*(documentation relatedInternalConcept EnglishLanguage "Means that the two arguments are related concepts within the SUMO, i.e. there is a significant similarity of meaning between them. To indicate a meaning relation between a SUMO concept and a concept from another source, use the Predicate relatedExternalConcept.") */
if (includeRelatedInternalConcept) {
if (args.size() != 2) {
throw new UnsupportedOperationException("relatedInternalConcept expects 2 arguments");
} else {
y = $.sim(args.get(0), args.get(1));
}
}
break;
case "equal":
y = $.func("equal", args.get(0), args.get(1));
// y = $.sim(args.get(0), args.get(1));
break;
case "forall":
String forVar = sargs.get(0);
if (forVar.startsWith("(")) {
// remove parens
forVar = forVar.substring(1, forVar.length() - 1);
}
boolean missingAParamVar = false;
String[] forVars = forVar.split(" ");
for (String vv : forVars) {
if (!sargs.get(1).contains(vv)) {
missingAParamVar = true;
break;
}
}
if (!missingAParamVar) {
// skip over the for variables since it is contained in the expression
return args.get(1);
}
y = impl(args.get(0), args.get(1), true);
break;
case "exists":
// skip over the first parameter, since depvar is inherently existential
y = args.get(1);
break;
case "=>":
y = impl(args.get(0), args.get(1), true);
if (y == null)
return null;
break;
case "<=>":
y = impl(args.get(0), args.get(1), false);
if (y == null)
return null;
break;
case "termFormat":
String language = args.get(0).toString();
language = language.replace("Language", "");
Term term = args.get(1);
Term string = args.get(2);
y = $.inh($.p($.the(language), string), term);
break;
case "domain":
// TODO use the same format as Range, converting quantity > 1 to repeats in an argument list
if (level == 0) {
if (args.size() >= 3) {
Term subj = (args.get(0));
Term arg = (args.get(1));
Term type = (args.get(2));
FnDef d = fn.computeIfAbsent(subj, (s) -> new FnDef());
Term existing = d.domain.put(((Int) arg).id, type);
assert (existing == null || existing.equals(type));
} else {
throw new UnsupportedOperationException("unrecognized domain spec");
}
return null;
}
break;
case "range":
if (level == 0) {
if (args.size() == 2) {
Term subj = args.get(0);
Term range = args.get(1);
FnDef d = fn.computeIfAbsent(subj, (s) -> new FnDef());
d.range = range;
} else {
throw new UnsupportedOperationException("unrecognized range spec");
}
return null;
}
break;
case "disjointRelation":
case "disjoint":
case "inverse":
case "contraryAttribute":
// like n-ary disjoint
Variable v0 = $.varDep(1);
y = Op.INH.the(v0, Op.SECTe.the(args.toArray(new Term[0]))).neg();
break;
case "comment":
case "documentation":
if (includeDoc) {
if (args.size() == 2) {
Term subj = args.get(0);
Term lang = args.get(1);
Term desc = $.quote(args.get(2));
try {
y = $.inh($.p(subj, desc), lang);
} catch (Exception e) {
// e.printStackTrace();
y = null;
}
} else {
throw new UnsupportedOperationException();
}
}
break;
default:
// System.out.println("unknown: " + x);
break;
}
if (y == null) {
if (!includeDoc && (xCar.equals("documentation") || xCar.equals("comment")))
return null;
Term z = formulaToTerm(xCar, level + 1);
if (z != null) {
switch(z.toString()) {
case "and":
Term[] a = args.toArray(new Term[args.size()]);
y = CONJ.the(a);
break;
case "or":
y = $.disj(args.toArray(new Term[args.size()]));
break;
case "not":
y = args.get(0).neg();
break;
default:
if (!z.op().var)
// HACK
y = $.inh($.p(args), z);
else {
// re-attach
args.add(0, z);
y = $.p(args);
}
break;
}
}
}
if (y instanceof Bool)
throw new UnsupportedOperationException("Bool singularity: args=" + args);
return y;
}
use of nars.term.atom.Bool in project narchy by automenta.
the class IO method readCompound.
/**
* called by readTerm after determining the op type
* TODO make a version which reads directlyinto TermIndex
*/
@NotNull
static Term readCompound(DataInput in, /*@NotNull*/
Op o) throws IOException {
Term[] v = readTermContainer(in);
int dt;
if (o.temporal) {
dt = in.readInt();
} else {
dt = DTERNAL;
}
Term y = o.the(dt, v);
if (y instanceof Bool)
throw new Term.InvalidTermException(o, dt, v, "invalid term");
// return (Compound) t.normalize(key, true);
return y;
}
use of nars.term.atom.Bool 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 nars.term.atom.Bool in project narchy by automenta.
the class RelationClustering method link.
@Override
protected void link(Task tx, Task ty) {
// TODO abstract
assert (tx.isBelief() && ty.isBelief());
// TODO Allen interval
String relation;
if (tx.intersects(ty.start(), ty.end())) {
relation = "simul";
} else if (ty.isAfter(tx.end(), dur / 2)) {
relation = "seq";
} else if (tx.isAfter(ty.end(), dur / 2)) {
Task z = tx;
tx = ty;
ty = z;
relation = "seq";
} else {
relation = null;
}
if (relation != null) {
Term x = tx.term();
Truth truX = tx.truth();
if (truX.isNegative()) {
x = x.neg();
truX = truX.neg();
}
Term y = ty.term();
Truth truY = ty.truth();
if (truY.isNegative()) {
y = y.neg();
truY = truY.neg();
}
if (x.volume() + y.volume() < nar.termVolumeMax.intValue() - 2) {
Truth tru = TruthFunctions.intersection(truX, truY, nar.confMin.floatValue());
if (tru == null)
return;
// TODO enum
Term t;
switch(relation) {
case "simul":
t = $.inh(SETe.the(x, y), $.the("simul"));
break;
case "seq":
t = $.func(relation, x, y);
break;
default:
throw new UnsupportedOperationException();
}
if (t instanceof Bool)
return;
t = t.normalize();
long now = nar.time();
NALTask tt = new NALTask(t, BELIEF, tru, now, Math.min(tx.start(), ty.start()), Math.max(tx.end(), ty.end()), nar.time.nextStampArray());
tt.pri(tx.priElseZero() * ty.priElseZero());
in.input(tt);
}
}
}
Aggregations