use of nars.entity.Sentence in project opennars by opennars.
the class PerceptionAccel method perceive.
public void perceive(DerivationContext nal) {
// implement Peis idea here now
// we start with length 2 compounds, and search for patterns which are one longer than the longest observed one
boolean longest_result_derived_already = false;
for (int Len = cur_maxlen + 1; Len >= 2; Len--) {
// ok, this is the length we have to collect, measured from the end of event buffer
// there is a interval term for every event
Term[] relterms = new Term[2 * Len - 1];
// measuring its distance to the next event, but for the last event this is obsolete
// thus it are 2*Len-1] terms
Task newEvent = eventbuffer.get(eventbuffer.size() - 1);
TruthValue truth = newEvent.sentence.truth;
Stamp st = new Stamp(nal.memory);
ArrayList<Long> evBase = new ArrayList<Long>();
int k = 0;
for (int i = 0; i < Len; i++) {
// we go till to the end of the event buffer
int j = eventbuffer.size() - 1 - (Len - 1) + i;
if (j < 0) {
// but the mechanism already looks for length 2 patterns on the occurence of the first event
break;
}
Task current = eventbuffer.get(j);
for (long l : current.sentence.stamp.evidentialBase) {
evBase.add(l);
}
relterms[k] = current.sentence.term;
if (i != Len - 1) {
// if its not the last one, then there is a next one for which we have to put an interval
truth = TruthFunctions.deduction(truth, current.sentence.truth);
Task next = eventbuffer.get(j + 1);
relterms[k + 1] = new Interval(next.sentence.getOccurenceTime() - current.sentence.getOccurenceTime());
}
k += 2;
}
long[] evB = new long[evBase.size()];
int u = 0;
for (long l : evBase) {
evB[u] = l;
u++;
}
st.baseLength = evB.length;
st.evidentialBase = evB;
boolean eventBufferDidNotHaveSoMuchEvents = false;
for (int i = 0; i < relterms.length; i++) {
if (relterms[i] == null) {
eventBufferDidNotHaveSoMuchEvents = true;
}
}
if (eventBufferDidNotHaveSoMuchEvents) {
continue;
}
// decide on the tense of &/ by looking if the first event happens parallel with the last one
// Todo refine in 1.6.3 if we want to allow input of difference occurence time
boolean after = newEvent.sentence.stamp.after(eventbuffer.get(eventbuffer.size() - 1 - (Len - 1)).sentence.stamp, Parameters.DURATION);
// critical part: (not checked for correctness yet):
// we now have to look at if the first half + the second half already exists as concept, before we add it
Term[] firstHalf;
Term[] secondHalf;
if (relterms[Len - 1] instanceof Interval) {
// the middle can be a interval, for example in case of a,+1,b , in which case we dont use it
// so we skip the middle here
firstHalf = new Term[Len - 1];
// as well as here
secondHalf = new Term[Len - 1];
// make index mapping easier by counting
int h = 0;
for (int i = 0; i < Len - 1; i++) {
firstHalf[i] = relterms[h];
h++;
}
// we have to overjump the middle element this is why
h += 1;
for (int i = 0; i < Len - 1; i++) {
secondHalf[i] = relterms[h];
h++;
}
} else {
// it is a event so its fine
// 2*Len-1 in total
firstHalf = new Term[Len];
// but the middle is also used in the second one
secondHalf = new Term[Len];
// make index mapping easier by counting
int h = 0;
for (int i = 0; i < Len; i++) {
firstHalf[i] = relterms[h];
h++;
}
// we have to use the middle twice this is why
h--;
for (int i = 0; i < Len; i++) {
secondHalf[i] = relterms[h];
h++;
}
}
Term firstC = Conjunction.make(firstHalf, after ? ORDER_FORWARD : ORDER_CONCURRENT);
Term secondC = Conjunction.make(secondHalf, after ? ORDER_FORWARD : ORDER_CONCURRENT);
Concept C1 = nal.memory.concept(firstC);
Concept C2 = nal.memory.concept(secondC);
if (C1 == null || C2 == null) {
if (debugMechanism) {
System.out.println("one didn't exist: " + firstC.toString() + " or " + secondC.toString());
}
// the components were not observed, so don't allow creating this compound
continue;
}
if (C1.getPriority() < partConceptsPrioThreshold || C2.getPriority() < partConceptsPrioThreshold) {
// too less priority
continue;
}
Conjunction C = (Conjunction) Conjunction.make(relterms, after ? ORDER_FORWARD : ORDER_CONCURRENT);
// importance "summation"
Sentence S = new Sentence(C, Symbols.JUDGMENT_MARK, truth, st);
Task T = new Task(S, new BudgetValue(BudgetFunctions.or(C1.getPriority(), C2.getPriority()), Parameters.DEFAULT_JUDGMENT_DURABILITY, truth), true);
if (debugMechanism) {
System.out.println("success: " + T.toString());
}
if (longest_result_derived_already) {
T.setElemOfSequenceBuffer(false);
}
longest_result_derived_already = true;
// lets make the new event the parent task, and derive it
nal.derivedTask(T, false, false, false);
}
}
use of nars.entity.Sentence in project opennars by opennars.
the class GlobalAnticipation method temporalPredictionsAdapt.
// check all predictive statements, match them with last events
public void temporalPredictionsAdapt(DerivationContext nal) {
if (TEMPORAL_PREDICTION_FEEDBACK_ACCURACY_DIV == 0.0f) {
return;
}
ArrayList<Task> lastEvents = new ArrayList<Task>();
for (Task stmLast : stm) {
lastEvents.add(stmLast);
}
if (lastEvents.isEmpty()) {
return;
}
final long duration = Parameters.DURATION;
ArrayList<Task> derivetasks = new ArrayList<Task>();
for (final Task c : current_tasks) {
// a =/> b or (&/ a1...an) =/> b
boolean concurrent_conjunction = false;
Term[] args = new Term[1];
Implication imp = (Implication) c.sentence.term.clone();
boolean concurrent_implication = imp.getTemporalOrder() == TemporalRules.ORDER_CONCURRENT;
args[0] = imp.getSubject();
if (imp.getSubject() instanceof Conjunction) {
Conjunction conj = (Conjunction) imp.getSubject();
if (!conj.isSpatial) {
if (conj.temporalOrder == TemporalRules.ORDER_FORWARD || conj.temporalOrder == TemporalRules.ORDER_CONCURRENT) {
concurrent_conjunction = conj.temporalOrder == TemporalRules.ORDER_CONCURRENT;
// in case of &/ this are the terms
args = conj.term;
}
}
}
int i = 0;
boolean matched = true;
int off = 0;
long expected_time = lastEvents.get(0).sentence.getOccurenceTime();
for (i = 0; i < args.length; i++) {
// handling of intervals:
if (args[i] instanceof Interval) {
if (!concurrent_conjunction) {
expected_time += ((Interval) args[i]).time;
}
off++;
continue;
}
if (i - off >= lastEvents.size()) {
break;
}
if (!Variables.hasSubstitute(Symbols.VAR_INDEPENDENT, args[i], lastEvents.get(i - off).sentence.term)) {
// it didnt match, instead sth different unexpected happened
// whether intermediate events should be tolerated or not was a important question when considering this,
matched = false;
// if it should be allowed, the sequential match does not matter only if the events come like predicted.
break;
} else {
if (lastEvents.get(i - off).sentence.truth.getExpectation() <= 0.5f) {
// it matched according to sequence, but is its expectation bigger than 0.5? todo: decide how truth values of the expected events
// it didn't happen
matched = false;
break;
}
long occurence = lastEvents.get(i - off).sentence.getOccurenceTime();
boolean right_in_time = Math.abs(occurence - expected_time) < ((double) duration) / TEMPORAL_PREDICTION_FEEDBACK_ACCURACY_DIV;
if (!right_in_time) {
// it matched so far, but is the timing right or did it happen when not relevant anymore?
matched = false;
break;
}
}
if (!concurrent_conjunction) {
expected_time += duration;
}
}
if (concurrent_conjunction && !concurrent_implication) {
// implication is not concurrent
// so here we have to add duration
expected_time += duration;
} else if (!concurrent_conjunction && concurrent_implication) {
expected_time -= duration;
}
// ok it matched, is the consequence also right?
if (matched && lastEvents.size() > args.length - off) {
long occurence = lastEvents.get(args.length - off).sentence.getOccurenceTime();
boolean right_in_time = Math.abs(occurence - expected_time) < ((double) duration) / TEMPORAL_PREDICTION_FEEDBACK_ACCURACY_DIV;
if (right_in_time && Variables.hasSubstitute(Symbols.VAR_INDEPENDENT, imp.getPredicate(), lastEvents.get(args.length - off).sentence.term)) {
// it matched and same consequence, so positive evidence
// c.sentence.truth=TruthFunctions.revision(c.sentence.truth, new TruthValue(1.0f,Parameters.DEFAULT_JUDGMENT_CONFIDENCE));
Sentence s2 = new Sentence(c.sentence.term.clone(), Symbols.JUDGMENT_MARK, new TruthValue(1.0f, Parameters.DEFAULT_JUDGMENT_CONFIDENCE), new Stamp(nal.memory));
Task t = new Task(s2, new BudgetValue(Parameters.DEFAULT_JUDGMENT_PRIORITY, Parameters.DEFAULT_JUDGMENT_DURABILITY, s2.truth), true);
derivetasks.add(t);
} else {
// it matched and other consequence, so negative evidence
// c.sentence.truth=TruthFunctions.revision(c.sentence.truth, new TruthValue(0.0f,Parameters.DEFAULT_JUDGMENT_CONFIDENCE));
Sentence s2 = new Sentence(c.sentence.term.clone(), Symbols.JUDGMENT_MARK, new TruthValue(0.0f, Parameters.DEFAULT_JUDGMENT_CONFIDENCE), new Stamp(nal.memory));
Task t = new Task(s2, new BudgetValue(Parameters.DEFAULT_JUDGMENT_PRIORITY, Parameters.DEFAULT_JUDGMENT_DURABILITY, s2.truth), true);
derivetasks.add(t);
}
// todo use derived task with revision instead
}
}
for (Task t : derivetasks) {
if (nal.derivedTask(t, false, false, false)) {
boolean debug = true;
}
}
ArrayList<Task> toDelete = new ArrayList<Task>();
for (Task t : current_tasks) {
Concept w = nal.memory.concept(t.sentence.term);
if (w == null) {
// concept does not exist anymore, delete
toDelete.add(t);
}
}
for (Task t : toDelete) {
current_tasks.remove(t);
}
}
use of nars.entity.Sentence in project opennars by opennars.
the class SymRecognizer method jButton3ActionPerformed.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// GEN-FIRST:event_jButton3ActionPerformed
resetDetection();
StringBuilder build = new StringBuilder();
StringBuilder build2 = new StringBuilder();
build2.append("<(&|,");
for (int x = 0; x < SZ; x += 1) {
for (int y = 0; y < SZ; y += 1) {
int used_X = x;
int used_Y = y;
Color col1 = new Color(canvasIMG.getRGB(x, y));
float col = ((float) col1.getRed()) / 255.0f;
if (col > 0.0) {
float freq = 0.5f + (col - 0.5f);
if (invar.isSelected()) {
build.append("<p[" + String.valueOf(used_X) + "," + String.valueOf(used_Y) + "] --> [on]>. :|: %" + String.valueOf(freq) + "%");
build.append("\n");
build2.append("<p[" + String.valueOf(used_X) + "," + String.valueOf(used_Y) + "] --> [on]>,");
} else {
build.append("<p_" + String.valueOf(used_X) + "_" + String.valueOf(used_Y) + " --> [on]>. :|: %" + String.valueOf(freq) + "%");
build.append("\n");
build2.append("<p_" + String.valueOf(used_X) + "_" + String.valueOf(used_Y) + " --> [on]>,");
}
}
}
}
String s2 = build2.toString();
s2 = s2.substring(0, s2.length() - 1);
s2 = s2 + ")";
inputPanel.setText(build.toString());
if (evt == null) {
String question = "<{?what} --> [observed]>?";
additional[exid] = s2 + " ==> <{example" + exid + "} --> [observed]>>.";
inputPanel2.setText(additional[exid] + "\n" + question);
} else {
nar = new NAR();
if (invar1.isSelected()) {
gui = new NARSwing(nar);
}
int u = 0;
inputPanel2.setText("");
// for(String s : questions) {
String s = question;
{
if (s != null) {
AnswerHandler cur = new AnswerHandler() {
@Override
public void onSolution(Sentence belief) {
// System.out.println("solution: " + belief);
System.out.println(belief);
float howconf = belief.truth.getConfidence();
if (howconf > 0.1f) {
// only mark if above 0.1 confidence
// also mark image:
int maxu = Integer.valueOf(belief.getTerm().toString().split("example")[1].split("}")[0]);
clear();
for (int x = 0; x < SZ * scale_palette; x += 1) {
for (int y = 0; y < SZ * scale_palette; y += 1) {
Color col = new Color(canvasIMG.getRGB(x / scale_palette, y / scale_palette));
int k = getK[maxu];
int j = getJ[maxu];
exampleIMG.setRGB(x + k * scale_palette * SZ, y + (3 * j + 1) * scale_palette * SZ, new Color(col.getRed(), 0, 0).getRGB());
}
}
estimate.setIcon(new ImageIcon(fitimage(exampleIMG, estimate.getWidth(), estimate.getHeight())));
estimate.repaint();
}
}
};
q.add(cur);
try {
for (int h = 0; h < exid; h++) {
inputPanel2.setText(inputPanel2.getText() + additional[h] + "\n");
nar.addInput(additional[h]);
}
inputPanel2.setText(inputPanel2.getText() + s + "\n");
nar.ask(s.substring(0, s.length() - 1), cur);
} catch (Narsese.InvalidInputException ex) {
Logger.getLogger(SymRecognizer.class.getName()).log(Level.SEVERE, null, ex);
}
}
u++;
}
nar.param.noiseLevel.set(0);
nar.addInput(inputPanel.getText());
nar.start(0);
}
}
use of nars.entity.Sentence in project opennars by opennars.
the class SymRecognizerWithVisionChannel method jButton3ActionPerformed.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// GEN-FIRST:event_jButton3ActionPerformed
resetDetection();
StringBuilder build = new StringBuilder();
StringBuilder build2 = new StringBuilder();
build2.append("<(&|,");
for (int x = 0; x < SZ; x += 1) {
for (int y = 0; y < SZ; y += 1) {
int used_X = x;
int used_Y = y;
Color col1 = new Color(canvasIMG.getRGB(x, y));
float col = ((float) col1.getRed()) / 255.0f;
if (col > 0.0) {
float freq = 0.5f + (col - 0.5f);
if (invar.isSelected()) {
build.append("<p[" + String.valueOf(used_X) + "," + String.valueOf(used_Y) + "] --> [on]>. :|: %" + String.valueOf(freq) + "%");
build.append("\n");
build2.append("<p[" + String.valueOf(used_X) + "," + String.valueOf(used_Y) + "] --> [on]>,");
} else {
build.append("<p_" + String.valueOf(used_X) + "_" + String.valueOf(used_Y) + " --> [on]>. :|: %" + String.valueOf(freq) + "%");
build.append("\n");
build2.append("<p_" + String.valueOf(used_X) + "_" + String.valueOf(used_Y) + " --> [on]>,");
}
}
}
}
String s2 = build2.toString();
s2 = s2.substring(0, s2.length() - 1);
s2 = s2 + ")";
inputPanel.setText(build.toString());
if (evt == null) {
String question = "<{?what} --> [observed]>?";
additional[exid] = s2 + " ==> <{example" + exid + "} --> [observed]>>.";
inputPanel2.setText(additional[exid] + "\n" + question);
} else {
// add vision channel for [on] property
nar = new NAR();
// to the nar instance, and nar is also the "next higher" sensory channel
// to report the results to
nar.addSensoryChannel("[on]", new SpatialSamplingVisionChannel(nar, nar, SZ, SZ));
if (invar1.isSelected()) {
gui = new NARSwing(nar);
}
int u = 0;
inputPanel2.setText("");
// for(String s : questions) {
String s = question;
{
if (s != null) {
AnswerHandler cur = new AnswerHandler() {
@Override
public void onSolution(Sentence belief) {
// System.out.println("solution: " + belief);
System.out.println(belief);
float howconf = belief.truth.getConfidence();
if (howconf >= 0.001f) {
// only mark if above 0.1 confidence
// also mark image:
int maxu = Integer.valueOf(belief.getTerm().toString().split("example")[1].split("}")[0]);
clear();
for (int x = 0; x < SZ * scale_palette; x += 1) {
for (int y = 0; y < SZ * scale_palette; y += 1) {
Color col = new Color(canvasIMG.getRGB(x / scale_palette, y / scale_palette));
int k = getK[maxu];
int j = getJ[maxu];
exampleIMG.setRGB(x + k * scale_palette * SZ, y + (3 * j + 1) * scale_palette * SZ, new Color(col.getRed(), 0, 0).getRGB());
}
}
estimate.setIcon(new ImageIcon(fitimage(exampleIMG, estimate.getWidth(), estimate.getHeight())));
estimate.repaint();
}
}
};
q.add(cur);
try {
for (int h = 0; h < exid; h++) {
inputPanel2.setText(inputPanel2.getText() + additional[h] + "\n");
nar.addInput(additional[h]);
}
inputPanel2.setText(inputPanel2.getText() + s + "\n");
nar.ask(s.substring(0, s.length() - 1), cur);
} catch (Narsese.InvalidInputException ex) {
Logger.getLogger(SymRecognizerWithVisionChannel.class.getName()).log(Level.SEVERE, null, ex);
}
}
u++;
}
nar.param.noiseLevel.set(0);
nar.addInput(inputPanel.getText());
nar.start(0);
}
}
use of nars.entity.Sentence in project opennars by opennars.
the class ConceptMonitor method strongestProjectedInputEventBelief.
public static Sentence strongestProjectedInputEventBelief(NAR nar, String st) {
Concept c = ConceptMonitor.concept(nar, st);
if (c != null) {
for (Task t : c.beliefs) {
if (t.isInput() && !t.sentence.isEternal()) {
Sentence s = t.sentence;
Sentence projected = s.projection(nar.memory.time(), nar.memory.time());
if (!projected.isEternal()) {
return projected;
}
}
}
}
return null;
}
Aggregations