use of nars.language.Product in project opennars by opennars.
the class TemporalRules method temporalInduction.
// TODO maybe split &/ case into own function
public static List<Task> temporalInduction(final Sentence s1, final Sentence s2, final nars.control.DerivationContext nal, boolean SucceedingEventsInduction, boolean addToMemory, boolean allowSequence) {
if ((s1.truth == null) || (s2.truth == null) || s1.punctuation != Symbols.JUDGMENT_MARK || s2.punctuation != Symbols.JUDGMENT_MARK || s1.isEternal() || s2.isEternal())
return Collections.EMPTY_LIST;
Term t1 = s1.term;
Term t2 = s2.term;
boolean deriveSequenceOnly = (!addToMemory) || Statement.invalidStatement(t1, t2, true);
if (Statement.invalidStatement(t1, t2, false))
return Collections.EMPTY_LIST;
Term t11 = null;
Term t22 = null;
if (!deriveSequenceOnly && termForTemporalInduction(t1) && termForTemporalInduction(t2)) {
Statement ss1 = (Statement) t1;
Statement ss2 = (Statement) t2;
Variable var1 = new Variable("$0");
Variable var2 = new Variable("$1");
if (ss2.containsTermRecursively(ss1.getSubject())) {
HashMap<Term, Term> subs = new HashMap();
subs.put(ss1.getSubject(), var1);
if (ss2.containsTermRecursively(ss1.getPredicate())) {
subs.put(ss1.getPredicate(), var2);
}
t11 = ss1.applySubstitute(subs);
t22 = ss2.applySubstitute(subs);
}
if (ss1.containsTermRecursively(ss2.getSubject())) {
HashMap<Term, Term> subs = new HashMap();
subs.put(ss2.getSubject(), var1);
if (ss1.containsTermRecursively(ss2.getPredicate())) {
subs.put(ss2.getPredicate(), var2);
}
t11 = ss1.applySubstitute(subs);
t22 = ss2.applySubstitute(subs);
}
// allow also temporal induction on operator arguments:
if (ss2 instanceof Operation ^ ss1 instanceof Operation) {
if (ss2 instanceof Operation && !(ss2.getSubject() instanceof Variable)) {
// it is an operation, let's look if one of the arguments is same as the subject of the other term
Term comp = ss1.getSubject();
Term ss2_term = ((Operation) ss2).getSubject();
boolean applicableVariableType = !(comp instanceof Variable && ((Variable) comp).hasVarIndep());
if (ss2_term instanceof Product) {
Product ss2_prod = (Product) ss2_term;
if (applicableVariableType && Terms.contains(ss2_prod.term, comp)) {
// only if there is one and it isnt a variable already
Term[] ars = ss2_prod.cloneTermsReplacing(comp, var1);
t11 = Statement.make(ss1, var1, ss1.getPredicate());
Operation op = (Operation) Operation.make(new Product(ars), ss2.getPredicate());
t22 = op;
}
}
}
if (ss1 instanceof Operation && !(ss1.getSubject() instanceof Variable)) {
// it is an operation, let's look if one of the arguments is same as the subject of the other term
Term comp = ss2.getSubject();
Term ss1_term = ((Operation) ss1).getSubject();
boolean applicableVariableType = !(comp instanceof Variable && ((Variable) comp).hasVarIndep());
if (ss1_term instanceof Product) {
Product ss1_prod = (Product) ss1_term;
if (applicableVariableType && Terms.contains(ss1_prod.term, comp)) {
// only if there is one and it isnt a variable already
Term[] ars = ss1_prod.cloneTermsReplacing(comp, var1);
t22 = Statement.make(ss2, var1, ss2.getPredicate());
Operation op = (Operation) Operation.make(new Product(ars), ss1.getPredicate());
t11 = op;
}
}
}
}
}
int durationCycles = Parameters.DURATION;
long time1 = s1.getOccurenceTime();
long time2 = s2.getOccurenceTime();
long timeDiff = time2 - time1;
Interval interval = null;
if (!concurrent(time1, time2, durationCycles)) {
interval = new Interval(Math.abs(timeDiff));
if (timeDiff > 0) {
t1 = Conjunction.make(t1, interval, ORDER_FORWARD);
if (t11 != null) {
t11 = Conjunction.make(t11, interval, ORDER_FORWARD);
}
} else {
t2 = Conjunction.make(t2, interval, ORDER_FORWARD);
if (t22 != null) {
t22 = Conjunction.make(t22, interval, ORDER_FORWARD);
}
}
}
int order = order(timeDiff, durationCycles);
TruthValue givenTruth1 = s1.truth;
TruthValue givenTruth2 = s2.truth;
// This code adds a penalty for large time distance (TODO probably revise)
Sentence s3 = s2.projection(s1.getOccurenceTime(), nal.memory.time());
givenTruth2 = s3.truth;
// Truth and priority calculations
TruthValue truth1 = TruthFunctions.induction(givenTruth1, givenTruth2);
TruthValue truth2 = TruthFunctions.induction(givenTruth2, givenTruth1);
TruthValue truth3 = TruthFunctions.comparison(givenTruth1, givenTruth2);
TruthValue truth4 = TruthFunctions.intersection(givenTruth1, givenTruth2);
BudgetValue budget1 = BudgetFunctions.forward(truth1, nal);
budget1.setPriority(budget1.getPriority() * Parameters.TEMPORAL_INDUCTION_PRIORITY_PENALTY);
BudgetValue budget2 = BudgetFunctions.forward(truth2, nal);
budget2.setPriority(budget2.getPriority() * Parameters.TEMPORAL_INDUCTION_PRIORITY_PENALTY);
BudgetValue budget3 = BudgetFunctions.forward(truth3, nal);
budget3.setPriority(budget3.getPriority() * Parameters.TEMPORAL_INDUCTION_PRIORITY_PENALTY);
// this one is sequence in sequenceBag, no need to reduce here
BudgetValue budget4 = BudgetFunctions.forward(truth4, nal);
Statement statement1 = Implication.make(t1, t2, order);
Statement statement2 = Implication.make(t2, t1, reverseOrder(order));
Statement statement3 = Equivalence.make(t1, t2, order);
Term statement4 = null;
switch(order) {
case TemporalRules.ORDER_FORWARD:
statement4 = Conjunction.make(t1, interval, s2.term, order);
break;
case TemporalRules.ORDER_BACKWARD:
statement4 = Conjunction.make(s2.term, interval, t1, reverseOrder(order));
break;
default:
statement4 = Conjunction.make(t1, s2.term, order);
break;
}
// "Perception Variable Introduction Rule" - https://groups.google.com/forum/#!topic/open-nars/uoJBa8j7ryE
if (!deriveSequenceOnly && statement2 != null) {
// there is no general form
// ok then it may be the (&/ =/> case which
// is discussed here: https://groups.google.com/forum/#!topic/open-nars/uoJBa8j7ryE
Statement st = statement2;
if (st.getPredicate() instanceof Inheritance && (st.getSubject() instanceof Conjunction || st.getSubject() instanceof Operation)) {
Term precon = (Term) st.getSubject();
Inheritance consequence = (Inheritance) st.getPredicate();
Term pred = consequence.getPredicate();
Term sub = consequence.getSubject();
// look if subject is contained in precon:
boolean SubsSub = precon.containsTermRecursively(sub);
boolean SubsPred = precon.containsTermRecursively(pred);
Variable v1 = new Variable("$91");
Variable v2 = new Variable("$92");
HashMap<Term, Term> app = new HashMap<Term, Term>();
if (SubsSub || SubsPred) {
if (SubsSub)
app.put(sub, v1);
if (SubsPred)
app.put(pred, v2);
Term res = ((CompoundTerm) statement2).applySubstitute(app);
if (res != null) {
// ok we applied it, all we have to do now is to use it
t22 = ((Statement) res).getSubject();
t11 = ((Statement) res).getPredicate();
}
}
}
}
List<Task> success = new ArrayList<Task>();
if (!deriveSequenceOnly && t11 != null && t22 != null) {
Statement statement11 = Implication.make(t11, t22, order);
Statement statement22 = Implication.make(t22, t11, reverseOrder(order));
Statement statement33 = Equivalence.make(t11, t22, order);
if (!tooMuchTemporalStatements(statement11)) {
List<Task> t = nal.doublePremiseTask(statement11, truth1, budget1, true, false);
if (t != null) {
success.addAll(t);
}
}
if (!tooMuchTemporalStatements(statement22)) {
List<Task> t = nal.doublePremiseTask(statement22, truth2, budget2, true, false);
if (t != null) {
success.addAll(t);
}
}
if (!tooMuchTemporalStatements(statement33)) {
List<Task> t = nal.doublePremiseTask(statement33, truth3, budget3, true, false);
if (t != null) {
success.addAll(t);
}
}
}
if (!deriveSequenceOnly && !tooMuchTemporalStatements(statement1)) {
List<Task> t = nal.doublePremiseTask(statement1, truth1, budget1, true, false);
if (t != null) {
success.addAll(t);
for (Task task : t) {
// we assume here that this function is used for observable events currently
task.setObservablePrediction(true);
}
}
}
if (!deriveSequenceOnly && !tooMuchTemporalStatements(statement2)) {
List<Task> t = nal.doublePremiseTask(statement2, truth2, budget2, true, false);
if (t != null) {
success.addAll(t);
for (Task task : t) {
// we assume here that this function is used for observable events currently
task.setObservablePrediction(true);
}
}
}
if (!deriveSequenceOnly && !tooMuchTemporalStatements(statement3)) {
List<Task> t = nal.doublePremiseTask(statement3, truth3, budget3, true, false);
if (t != null) {
for (Task task : t) {
// we assume here that this function is used for observable events currently
task.setObservablePrediction(true);
}
success.addAll(t);
}
}
if (!tooMuchTemporalStatements(statement4)) {
if (!allowSequence) {
return success;
}
List<Task> tl = nal.doublePremiseTask(statement4, truth4, budget4, true, false, addToMemory);
if (tl != null) {
for (Task t : tl) {
// fill sequenceTask buffer due to the new derived sequence
if (addToMemory && t.sentence.isJudgment() && !t.sentence.isEternal() && t.sentence.term instanceof Conjunction && ((Conjunction) t.sentence.term).getTemporalOrder() != TemporalRules.ORDER_NONE && ((Conjunction) t.sentence.term).getTemporalOrder() != TemporalRules.ORDER_INVALID) {
TemporalInferenceControl.addToSequenceTasks(nal, t);
}
success.add(t);
}
}
}
return success;
}
use of nars.language.Product in project opennars by opennars.
the class Counting method setEnabled.
@Override
public boolean setEnabled(NAR n, boolean enabled) {
Memory memory = n.memory;
if (obs == null) {
obs = new EventObserver() {
@Override
public void event(Class event, Object[] a) {
if ((event != Events.TaskDerive.class && event != Events.TaskAdd.class))
return;
Task task = (Task) a[0];
if (task.getPriority() < InternalExperience.MINIMUM_PRIORITY_TO_CREATE_WANT_BELIEVE_ETC) {
return;
}
if (task.sentence.punctuation == Symbols.JUDGMENT_MARK) {
// lets say we have <{...} --> M>.
if (task.sentence.term instanceof Inheritance) {
Inheritance inh = (Inheritance) task.sentence.term;
if (inh.getSubject() instanceof SetExt) {
SetExt set_term = (SetExt) inh.getSubject();
// this gets the cardinality of M
int cardinality = set_term.size();
// now create term <(*,M,cardinality) --> CARDINALITY>.
Term[] product_args = new Term[] { inh.getPredicate(), Term.get(cardinality) };
// TODO CARDINATLITY can be a static final instance shared by all
Term new_term = Inheritance.make(new Product(product_args), /* --> */
CARDINALITY);
if (new_term == null) {
// this usually happens when product_args contains the term CARDINALITY in which case it is an invalid Inheritance statement
return;
}
TruthValue truth = task.sentence.truth.clone();
Stamp stampi = task.sentence.stamp.clone();
Sentence j = new Sentence(new_term, Symbols.JUDGMENT_MARK, truth, stampi);
BudgetValue budg = task.budget.clone();
Task newTask = new Task(j, budg, true);
memory.addNewTask(newTask, "Derived (Cardinality)");
}
}
}
}
};
}
memory.event.set(obs, enabled, Events.TaskDerive.class);
return true;
}
use of nars.language.Product in project opennars by opennars.
the class InternalExperience method beliefReason.
/**
* used in full internal experience mode only
*/
protected void beliefReason(Sentence belief, Term beliefTerm, Term taskTerm, DerivationContext nal) {
Memory memory = nal.memory;
if (Memory.randomNumber.nextDouble() < INTERNAL_EXPERIENCE_RARE_PROBABILITY) {
// the operators which dont have a innate belief
// also get a chance to reveal its effects to the system this way
Operator op = memory.getOperator(nonInnateBeliefOperators[Memory.randomNumber.nextInt(nonInnateBeliefOperators.length)]);
Product prod = new Product(new Term[] { belief.term });
if (op != null && prod != null) {
Term new_term = Inheritance.make(prod, op);
Sentence sentence = new Sentence(new_term, Symbols.GOAL_MARK, // a naming convension
new TruthValue(1, Parameters.DEFAULT_JUDGMENT_CONFIDENCE), new Stamp(memory));
float quality = BudgetFunctions.truthToQuality(sentence.truth);
BudgetValue budget = new BudgetValue(Parameters.DEFAULT_GOAL_PRIORITY * INTERNAL_EXPERIENCE_PRIORITY_MUL, Parameters.DEFAULT_GOAL_DURABILITY * INTERNAL_EXPERIENCE_DURABILITY_MUL, quality);
Task newTask = new Task(sentence, budget, true);
nal.derivedTask(newTask, false, false, false);
}
}
if (beliefTerm instanceof Implication && Memory.randomNumber.nextDouble() <= INTERNAL_EXPERIENCE_PROBABILITY) {
Implication imp = (Implication) beliefTerm;
if (imp.getTemporalOrder() == TemporalRules.ORDER_FORWARD) {
// 1. check if its (&/,term,+i1,...,+in) =/> anticipateTerm form:
boolean valid = true;
if (imp.getSubject() instanceof Conjunction) {
Conjunction conj = (Conjunction) imp.getSubject();
if (!conj.term[0].equals(taskTerm)) {
// the expected needed term is not included
valid = false;
}
for (int i = 1; i < conj.term.length; i++) {
if (!(conj.term[i] instanceof Interval)) {
valid = false;
break;
}
}
} else {
if (!imp.getSubject().equals(taskTerm)) {
valid = false;
}
}
if (valid) {
Operator op = memory.getOperator("^anticipate");
if (op == null)
throw new RuntimeException(this + " requires ^anticipate operator");
Product args = new Product(new Term[] { imp.getPredicate() });
Term new_term = Operation.make(args, op);
Sentence sentence = new Sentence(new_term, Symbols.GOAL_MARK, // a naming convension
new TruthValue(1, Parameters.DEFAULT_JUDGMENT_CONFIDENCE), new Stamp(memory));
float quality = BudgetFunctions.truthToQuality(sentence.truth);
BudgetValue budget = new BudgetValue(Parameters.DEFAULT_GOAL_PRIORITY * INTERNAL_EXPERIENCE_PRIORITY_MUL, Parameters.DEFAULT_GOAL_DURABILITY * INTERNAL_EXPERIENCE_DURABILITY_MUL, quality);
Task newTask = new Task(sentence, budget, true);
nal.derivedTask(newTask, false, false, false);
}
}
}
}
use of nars.language.Product in project opennars by opennars.
the class StructuralRules method transformPredicatePI.
/**
* Equivalent transformation between products and images when the predicate
* is a compound {<(*, S, M) --> P>, S@(*, S, M)} |- <S --> (/, P, _, M)>
* {<S --> (/, P, _, M)>, P@(/, P, _, M)} |- <(*, S, M) --> P> {<S --> (/,
* P, _, M)>, M@(/, P, _, M)} |- <M --> (/, P, S, _)>
*
* @param subject The subject term
* @param predicate The predicate term
* @param nal Reference to the memory
*/
private static void transformPredicatePI(short index, Term subject, CompoundTerm predicate, DerivationContext nal) {
TruthValue truth = nal.getCurrentTask().sentence.truth;
BudgetValue budget;
Inheritance inheritance;
Term newSubj, newPred;
if (predicate instanceof Product) {
Product product = (Product) predicate;
short i = index;
/*for (short i = 0; i < product.size(); i++)*/
{
newSubj = ImageInt.make(product, subject, i);
newPred = product.term[i];
inheritance = Inheritance.make(newSubj, newPred);
if (inheritance != null) {
if (truth == null) {
budget = BudgetFunctions.compoundBackward(inheritance, nal);
} else {
budget = BudgetFunctions.compoundForward(truth, inheritance, nal);
}
nal.singlePremiseTask(inheritance, truth, budget);
}
}
} else if (predicate instanceof ImageExt) {
ImageExt image = (ImageExt) predicate;
int relationIndex = image.relationIndex;
for (short i = 0; i < image.size(); i++) {
if (i == relationIndex) {
newSubj = Product.make(image, subject, relationIndex);
newPred = image.term[relationIndex];
} else {
newSubj = image.term[i];
newPred = ImageExt.make(image, subject, i);
}
if (newSubj instanceof CompoundTerm && (newPred.equals(Term.SEQ_TEMPORAL) || newPred.equals(Term.SEQ_SPATIAL))) {
Term seq = Conjunction.make(((CompoundTerm) newSubj).term, TemporalRules.ORDER_FORWARD, newPred.equals(Term.SEQ_SPATIAL));
if (truth == null) {
budget = BudgetFunctions.compoundBackward(seq, nal);
} else {
budget = BudgetFunctions.compoundForward(truth, seq, nal);
}
nal.singlePremiseTask(seq, truth, budget);
return;
}
inheritance = Inheritance.make(newSubj, newPred);
if (inheritance != null) {
// jmv <<<<<
if (truth == null) {
budget = BudgetFunctions.compoundBackward(inheritance, nal);
} else {
budget = BudgetFunctions.compoundForward(truth, inheritance, nal);
}
nal.singlePremiseTask(inheritance, truth, budget);
}
}
}
}
use of nars.language.Product in project opennars by opennars.
the class StructuralRules method transformProductImage.
/* -------------------- products and images transform -------------------- */
/**
* Equivalent transformation between products and images {<(*, S, M) --> P>,
* S@(*, S, M)} |- <S --> (/, P, _, M)> {<S --> (/, P, _, M)>, P@(/, P, _,
* M)} |- <(*, S, M) --> P> {<S --> (/, P, _, M)>, M@(/, P, _, M)} |- <M -->
* (/, P, S, _)>
*
* @param inh An Inheritance statement
* @param oldContent The whole content
* @param indices The indices of the TaskLink
* @param task The task
* @param memory Reference to the memory
*/
static void transformProductImage(Inheritance inh, CompoundTerm oldContent, short[] indices, DerivationContext nal) {
final Memory memory = nal.mem();
Term subject = inh.getSubject();
Term predicate = inh.getPredicate();
short index = indices[indices.length - 1];
short side = indices[indices.length - 2];
if (inh.equals(oldContent)) {
if (subject instanceof CompoundTerm) {
transformSubjectPI(index, (CompoundTerm) subject, predicate, nal);
}
if (predicate instanceof CompoundTerm) {
transformPredicatePI(index, subject, (CompoundTerm) predicate, nal);
}
return;
}
Term compT = inh.term[side];
if (!(compT instanceof CompoundTerm))
return;
CompoundTerm comp = (CompoundTerm) compT;
if (comp instanceof Product) {
if (side == 0) {
subject = comp.term[index];
predicate = ImageExt.make((Product) comp, inh.getPredicate(), index);
} else {
subject = ImageInt.make((Product) comp, inh.getSubject(), index);
predicate = comp.term[index];
}
} else if ((comp instanceof ImageExt) && (side == 1)) {
if (index == ((ImageExt) comp).relationIndex) {
subject = Product.make(comp, inh.getSubject(), index);
predicate = comp.term[index];
} else {
subject = comp.term[index];
predicate = ImageExt.make((ImageExt) comp, inh.getSubject(), index);
}
} else if ((comp instanceof ImageInt) && (side == 0)) {
if (index == ((ImageInt) comp).relationIndex) {
subject = comp.term[index];
predicate = Product.make(comp, inh.getPredicate(), index);
} else {
subject = ImageInt.make((ImageInt) comp, inh.getPredicate(), index);
predicate = comp.term[index];
}
} else {
return;
}
CompoundTerm newInh = null;
if (predicate.equals(Term.SEQ_SPATIAL)) {
newInh = (CompoundTerm) Conjunction.make(((CompoundTerm) subject).term, TemporalRules.ORDER_FORWARD, true);
} else if (predicate.equals(Term.SEQ_TEMPORAL)) {
newInh = (CompoundTerm) Conjunction.make(((CompoundTerm) subject).term, TemporalRules.ORDER_FORWARD, false);
} else {
newInh = Inheritance.make(subject, predicate);
}
if (newInh == null)
return;
CompoundTerm content = null;
if (indices.length == 2) {
content = newInh;
} else if ((oldContent instanceof Statement) && (indices[0] == 1)) {
content = Statement.make((Statement) oldContent, oldContent.term[0], newInh, oldContent.getTemporalOrder());
} else {
Term[] componentList;
Term condition = oldContent.term[0];
if (((oldContent instanceof Implication) || (oldContent instanceof Equivalence)) && (condition instanceof Conjunction)) {
componentList = ((CompoundTerm) condition).cloneTerms();
componentList[indices[1]] = newInh;
Term newCond = Terms.term((CompoundTerm) condition, componentList);
content = Statement.make((Statement) oldContent, newCond, ((Statement) oldContent).getPredicate(), oldContent.getTemporalOrder());
} else {
componentList = oldContent.cloneTerms();
componentList[indices[0]] = newInh;
if (oldContent instanceof Conjunction) {
Term newContent = Terms.term(oldContent, componentList);
if (!(newContent instanceof CompoundTerm))
return;
content = (CompoundTerm) newContent;
} else if ((oldContent instanceof Implication) || (oldContent instanceof Equivalence)) {
content = Statement.make((Statement) oldContent, componentList[0], componentList[1], oldContent.getTemporalOrder());
}
}
}
if (content == null)
return;
Sentence sentence = nal.getCurrentTask().sentence;
TruthValue truth = sentence.truth;
BudgetValue budget;
if (sentence.isQuestion() || sentence.isQuest()) {
budget = BudgetFunctions.compoundBackward(content, nal);
} else {
budget = BudgetFunctions.compoundForward(truth, content, nal);
}
nal.singlePremiseTask(content, truth, budget);
}
Aggregations