Search in sources :

Example 11 with Variable

use of nars.term.var.Variable in project narchy by automenta.

the class NarseseBaseTest method testVar.

@NotNull
protected Variable testVar(char prefix) throws Narsese.NarseseException {
    Term x = term(prefix + "x");
    assertNotNull(x);
    assertTrue(x instanceof Variable);
    Variable i = (Variable) x;
    assertEquals(prefix + "x", i.toString());
    return i;
}
Also used : Variable(nars.term.var.Variable) Term(nars.term.Term) NotNull(org.jetbrains.annotations.NotNull)

Example 12 with Variable

use of nars.term.var.Variable 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;
}
Also used : Variable(nars.term.var.Variable) Term(nars.term.Term) FileNotFoundException(java.io.FileNotFoundException) Bool(nars.term.atom.Bool)

Example 13 with Variable

use of nars.term.var.Variable in project narchy by automenta.

the class PrologToNAL method N.

private static nars.term.Term N(alice.tuprolog.Term t) {
    if (t instanceof alice.tuprolog.Term) {
        Struct s = (Struct) t;
        String name = s.name();
        switch(name) {
            case ":-":
                assert (s.subs() == 2);
                // reverse, prolog is backwards
                nars.term.Term pre = N(s.sub(1));
                nars.term.Term post = N(s.sub(0));
                // convert to implication first, then promote variables on the resulting pre/post
                Term impl = $.impl(pre, post);
                pre = impl.sub(0);
                post = impl.sub(1);
                if (pre.varQuery() > 0 && post.varQuery() > 0) {
                    MutableSet<nars.term.var.Variable> prev = new UnifiedSet();
                    pre.recurseTerms(Termlike::hasVarQuery, (a) -> {
                        if (a.op() == Op.VAR_QUERY)
                            prev.add((Variable) a);
                        return true;
                    }, null);
                    MutableSet<nars.term.var.Variable> posv = new UnifiedSet();
                    post.recurseTerms(Termlike::hasVarQuery, (a) -> {
                        if (a.op() == Op.VAR_QUERY)
                            posv.add((Variable) a);
                        return true;
                    }, null);
                    MutableSet<nars.term.var.Variable> common = prev.intersect(posv);
                    int cs = common.size();
                    if (cs > 0) {
                        Map<nars.term.Term, nars.term.Term> x = new UnifiedMap(cs);
                        for (nars.term.var.Variable c : common) {
                            x.put(c, $.varIndep(c.toString().substring(1)));
                        }
                        impl = impl.replace(x);
                    }
                }
                return impl;
            case ",":
                return CONJ.the(N(s.sub(0)), N(s.sub(1)));
            default:
                nars.term.Term atom = $.the(name);
                int arity = s.subs();
                if (arity == 0) {
                    return atom;
                } else {
                    return $.inh($.p((nars.term.Term[]) Util.map(0, arity, i -> N(s.sub(i)), nars.term.Term[]::new)), atom);
                }
        }
    } else if (t instanceof Var) {
        return $.varQuery(((Var) t).name());
    // throw new RuntimeException(t + " untranslated");
    } else if (t instanceof NumberTerm.Int) {
        return $.the(((NumberTerm.Int) t).intValue());
    } else {
        throw new TODO(t + " (" + t.getClass() + ") untranslatable");
    }
}
Also used : Struct(alice.tuprolog.Struct) NumberTerm(alice.tuprolog.NumberTerm) Iterables(com.google.common.collect.Iterables) UnifiedMap(org.eclipse.collections.impl.map.mutable.UnifiedMap) CONJ(nars.Op.CONJ) Var(alice.tuprolog.Var) nars.$(nars.$) Theory(alice.tuprolog.Theory) Util(jcog.Util) Variable(nars.term.var.Variable) MutableSet(org.eclipse.collections.api.set.MutableSet) TODO(jcog.TODO) Op(nars.Op) Termlike(nars.term.Termlike) Map(java.util.Map) Term(nars.term.Term) UnifiedSet(org.eclipse.collections.impl.set.mutable.UnifiedSet) TODO(jcog.TODO) Variable(nars.term.var.Variable) NumberTerm(alice.tuprolog.NumberTerm) UnifiedMap(org.eclipse.collections.impl.map.mutable.UnifiedMap) Var(alice.tuprolog.Var) NumberTerm(alice.tuprolog.NumberTerm) Term(nars.term.Term) Struct(alice.tuprolog.Struct) Termlike(nars.term.Termlike) Variable(nars.term.var.Variable) UnifiedSet(org.eclipse.collections.impl.set.mutable.UnifiedSet) Term(nars.term.Term)

Example 14 with Variable

use of nars.term.var.Variable 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;
}
Also used : Variable(nars.term.var.Variable) IntObjectHashMap(org.eclipse.collections.impl.map.mutable.primitive.IntObjectHashMap) FasterList(jcog.list.FasterList) IntHashSet(org.eclipse.collections.impl.set.mutable.primitive.IntHashSet) Term(nars.term.Term) Int(nars.term.atom.Int) IntObjectPair(org.eclipse.collections.api.tuple.primitive.IntObjectPair) Anom(nars.term.anon.Anom) FasterList(jcog.list.FasterList) MutableList(org.eclipse.collections.api.list.MutableList) List(java.util.List) Supplier(java.util.function.Supplier)

Example 15 with Variable

use of nars.term.var.Variable in project narchy by automenta.

the class CommonVariableTest method CommonVariableDirectionalityPreserved.

@Test
public void CommonVariableDirectionalityPreserved() {
    // different lengths
    Variable c12_reverse = CommonVariable.common(p2, p1);
    assertEquals(c12, c12_reverse);
    assertEquals(0, c12.compareTo(c12_reverse));
    assertEquals(0, c12_reverse.compareTo(c12));
}
Also used : Variable(nars.term.var.Variable) CommonVariable(nars.term.var.CommonVariable) Test(org.junit.jupiter.api.Test)

Aggregations

Variable (nars.term.var.Variable)17 Term (nars.term.Term)12 Test (org.junit.jupiter.api.Test)6 CommonVariable (nars.term.var.CommonVariable)4 Op (nars.Op)3 FileNotFoundException (java.io.FileNotFoundException)2 TODO (jcog.TODO)2 FasterList (jcog.list.FasterList)2 Concept (nars.concept.Concept)2 Subterms (nars.subterm.Subterms)2 Compound (nars.term.Compound)2 Bool (nars.term.atom.Bool)2 Int (nars.term.atom.Int)2 MutableSet (org.eclipse.collections.api.set.MutableSet)2 UnifiedMap (org.eclipse.collections.impl.map.mutable.UnifiedMap)2 IntObjectHashMap (org.eclipse.collections.impl.map.mutable.primitive.IntObjectHashMap)2 NotNull (org.jetbrains.annotations.NotNull)2 NumberTerm (alice.tuprolog.NumberTerm)1 Struct (alice.tuprolog.Struct)1 Theory (alice.tuprolog.Theory)1