Skip to content

Commit 2aebcc6

Browse files
committed
Code cleaning
1 parent 96f1355 commit 2aebcc6

9 files changed

Lines changed: 280 additions & 181 deletions

File tree

‎InputChannel.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ def process_visual_sensory_input(input_string):
134134
#remove line endings
135135
input_string = input_string.replace("\n", "")
136136
input_string = input_string.replace("\r", "")
137+
input_string = input_string[1:-1]
137138

138139
subject_str = "V" + str(Global.Global.NARS.memory.get_next_percept_id())
139140
predicate_term = NALGrammar.Term.from_string("[BRIGHT]")

‎NALGrammar.py‎

Lines changed: 86 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ def __init__(self, dimensions, truth_values = None, occurrence_time=None):
1919
provides a granularity = 2.0/(dim_length - 1)
2020
"""
2121
self.is_array = dimensions is not None
22+
self.truth_values = None
2223
if not self.is_array: return
24+
self.truth_values = truth_values
2325
self.dimensions = dimensions
2426
self.num_of_dimensions = len(dimensions)
2527
assert self.num_of_dimensions <= 3, "ERROR: Does not support more than 3 dimensions"
@@ -54,12 +56,33 @@ def __init__(self, dimensions, truth_values = None, occurrence_time=None):
5456
formatted_indices = [x, y, z]
5557

5658
if isinstance(self, StatementTerm):
57-
array_term: ArrayTerm = self.get_subject_term().subterms[0]
58-
atomic_element = array_term[formatted_indices] # get atomic array element
59-
element = StatementTerm(subject_term=CompoundTerm(subterms=[atomic_element],
60-
term_connector=NALSyntax.TermConnector.ExtensionalSetStart),
61-
predicate_term=self.get_predicate_term(),
62-
copula=NALSyntax.Copula.Inheritance)
59+
subject_is_array = isinstance(self.get_subject_term(), CompoundTerm) and isinstance(self.get_subject_term().subterms[0], ArrayTerm)
60+
predicate_is_array = isinstance(self.get_predicate_term(), CompoundTerm) and isinstance(self.get_predicate_term().subterms[0], ArrayTerm)
61+
if subject_is_array and predicate_is_array:
62+
subject_array_term = self.get_subject_term().subterms[0]
63+
subject_atomic_element = subject_array_term[formatted_indices] # get atomic array element
64+
predicate_array_term = self.get_predicate_term().subterms[0]
65+
predicate_atomic_element = predicate_array_term[formatted_indices] # get atomic array element
66+
element = StatementTerm(subject_term=CompoundTerm(subterms=[subject_atomic_element],
67+
term_connector=NALSyntax.TermConnector.ExtensionalSetStart),
68+
predicate_term=CompoundTerm(subterms=[predicate_atomic_element],
69+
term_connector=NALSyntax.TermConnector.ExtensionalSetStart),
70+
copula=self.get_copula())
71+
elif subject_is_array:
72+
array_term = self.get_subject_term().subterms[0]
73+
atomic_element = array_term[formatted_indices] # get atomic array element
74+
element = StatementTerm(subject_term=CompoundTerm(subterms=[atomic_element],
75+
term_connector=NALSyntax.TermConnector.ExtensionalSetStart),
76+
predicate_term=self.get_predicate_term(),
77+
copula=self.get_copula())
78+
elif predicate_is_array:
79+
array_term = self.get_predicate_term().subterms[0]
80+
atomic_element = array_term[formatted_indices] # get atomic array element
81+
element = StatementTerm(subject_term=self.get_subject_term(),
82+
predicate_term=CompoundTerm(subterms=[atomic_element],
83+
term_connector=NALSyntax.TermConnector.ExtensionalSetStart),
84+
copula=self.get_copula())
85+
6386
elif isinstance(self, Judgment):
6487
truth_value: TruthValue = truth_values[len(z_array)][len(y_array)][len(x_array)]
6588
statement_element: StatementTerm = self.statement[formatted_indices] # get atomic array element
@@ -136,15 +159,18 @@ def __init__(self, statement, value, punctuation, occurrence_time=None):
136159
self.punctuation: NALSyntax.Punctuation = punctuation
137160
self.stamp = Stamp(self_sentence=self,occurrence_time=occurrence_time)
138161

139-
if statement.is_array:
162+
if statement.is_array and hasattr(value, '__iter__') and value[1] is not None:
140163
if isinstance(self,Judgment) or isinstance(self,Goal):
141164
Array.__init__(self,statement.get_dimensions(),truth_values=value[1])
142165
self.value = value[0]
143166
else:
144167
Array.__init__(self, statement.get_dimensions())
145168
self.value = None
146169
else:
170+
#not an array
147171
Array.__init__(self, None)
172+
if hasattr(value, '__iter__'): # if its iterable, only use the primary truth-value
173+
value = value[0]
148174
self.value = value # truth-value (for Judgment) or desire-value (for Goal) or None (for Question)
149175

150176
def __str__(self):
@@ -209,32 +235,41 @@ def new_sentence_from_string(cls, sentence_string: str):
209235
# create the statement
210236
statement_string = sentence_string[start_idx:end_idx + 1]
211237

212-
if punctuation != NALSyntax.Punctuation.Question and sentence_string[2] == NALSyntax.TermConnector.Array.value:
238+
# create standard statement from string
239+
statement = StatementTerm.from_string(statement_string)
240+
241+
if punctuation == NALSyntax.Punctuation.Judgment:
213242
if freq is None:
214243
# No truth value, use default truth value
215244
freq = Config.DEFAULT_JUDGMENT_FREQUENCY
216245
conf = Config.DEFAULT_JUDGMENT_CONFIDENCE
217-
sentence = cls.new_percept_from_string(statement_string, TruthValue(freq, conf))
246+
truth_values = None
247+
if statement.is_array:
248+
dims = list(statement.get_dimensions())
249+
while len(dims) < 3:
250+
dims.append(1)
251+
truth_values = []
252+
for z in range(dims[2]):
253+
layer = []
254+
for y in range(dims[1]):
255+
row = []
256+
for x in range(dims[0]):
257+
element = TruthValue(freq, conf)
258+
row.append(element)
259+
layer.append(row)
260+
truth_values.append(layer)
261+
262+
sentence = Judgment(statement, (TruthValue(freq, conf),truth_values))
263+
elif punctuation == NALSyntax.Punctuation.Question:
264+
sentence = Question(statement)
265+
elif punctuation == NALSyntax.Punctuation.Goal:
266+
if freq is None:
267+
# No truth value, use default truth value
268+
freq = Config.DEFAULT_GOAL_FREQUENCY
269+
conf = Config.DEFAULT_GOAL_CONFIDENCE
270+
sentence = Goal(statement, DesireValue(freq,conf))
218271
else:
219-
# create standard statement from string
220-
statement = StatementTerm.from_string(statement_string)
221-
222-
if punctuation == NALSyntax.Punctuation.Judgment:
223-
if freq is None:
224-
# No truth value, use default truth value
225-
freq = Config.DEFAULT_JUDGMENT_FREQUENCY
226-
conf = Config.DEFAULT_JUDGMENT_CONFIDENCE
227-
sentence = Judgment(statement, TruthValue(freq, conf))
228-
elif punctuation == NALSyntax.Punctuation.Question:
229-
sentence = Question(statement)
230-
elif punctuation == NALSyntax.Punctuation.Goal:
231-
if freq is None:
232-
# No truth value, use default truth value
233-
freq = Config.DEFAULT_GOAL_FREQUENCY
234-
conf = Config.DEFAULT_GOAL_CONFIDENCE
235-
sentence = Goal(statement, DesireValue(freq,conf))
236-
else:
237-
assert False,"Error: No Punctuation!"
272+
assert False,"Error: No Punctuation!"
238273

239274
# Find Tense, if it exists
240275
# otherwise mark it as eternal
@@ -366,13 +401,14 @@ class Stamp:
366401
when it was created, its occurrence time (when is its truth value valid),
367402
evidential base, etc.
368403
"""
369-
def __init__(self, self_sentence, occurrence_time=None):
404+
def __init__(self, self_sentence, occurrence_time=None, derived_by=None):
370405
self.id = Global.Global.NARS.memory.get_next_stamp_id()
371406
self.creation_time = Global.Global.get_current_cycle_number() # when was this stamp created (in inference cycles)?
372407
self.occurrence_time = occurrence_time
373408
self.sentence = self_sentence
374409
self.evidential_base = EvidentialBase(self_sentence=self_sentence)
375410
self.interacted_sentences = [] # list of sentence this sentence has already interacted with
411+
self.derived_by = derived_by
376412
self.from_one_premise_inference = False # is this sentence derived from one-premise inference?
377413

378414
def get_tense(self):
@@ -439,6 +475,7 @@ class Term:
439475
"""
440476
Base class for all terms.
441477
"""
478+
term_dict = {} # a dictionary of existing terms to prevent duplicate term creation. Key: term string ; Value: term
442479

443480
def __init__(self, term_string):
444481
assert isinstance(term_string, str), term_string + " must be a str"
@@ -480,6 +517,9 @@ def from_string(cls, term_string):
480517
:returns Term constructed using the string
481518
"""
482519

520+
if term_string in cls.term_dict:
521+
return cls.term_dict[term_string]
522+
483523
if term_string[0] == NALSyntax.StatementSyntax.Start.value:
484524
"""
485525
Compound or Statement Term
@@ -513,6 +553,8 @@ def from_string(cls, term_string):
513553
else:
514554
term = AtomicTerm(term_string)
515555

556+
cls.term_dict[term_string] = term
557+
516558
return term
517559

518560
@classmethod
@@ -792,13 +834,23 @@ def __init__(self, subject_term: Term, predicate_term = None, copula=None, state
792834

793835
CompoundTerm.__init__(self,subterms, statement_connector)
794836

795-
is_perceptual_term = isinstance(subject_term, CompoundTerm) \
837+
subject_is_array_term = isinstance(subject_term, CompoundTerm) \
796838
and subject_term.is_extensional_set() \
797839
and isinstance(subject_term.subterms[0], Array) \
798-
and subject_term.subterms[0].is_array \
799-
and isinstance(predicate_term, CompoundTerm) \
800-
and predicate_term.is_intensional_set()
801-
dimensions = subject_term.subterms[0].get_dimensions() if is_perceptual_term else None
840+
and subject_term.subterms[0].is_array
841+
predicate_is_array_term = isinstance(predicate_term, CompoundTerm) \
842+
and predicate_term.is_extensional_set() \
843+
and isinstance(predicate_term.subterms[0], Array) \
844+
and predicate_term.subterms[0].is_array
845+
846+
dimensions = None
847+
if subject_is_array_term and predicate_is_array_term:
848+
dimensions = subject_term.subterms[0].get_dimensions()
849+
elif subject_is_array_term:
850+
dimensions = subject_term.subterms[0].get_dimensions()
851+
elif predicate_is_array_term:
852+
dimensions = predicate_term.subterms[0].get_dimensions()
853+
802854
Array.__init__(self, dimensions=dimensions)
803855

804856

‎NALInferenceRules/Immediate.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ def Conversion(j):
7272

7373
if isinstance(j, NALGrammar.Judgment):
7474
result_truth = TruthValueFunctions.F_Conversion(j.value.frequency, j.value.confidence)
75-
result = NALGrammar.Judgment(result_statement, result_truth, occurrence_time=occurrence_time)
75+
truth_values = TruthValueFunctions.TruthFunctionOnArray(j.truth_values,None,truth_value_function=TruthValueFunctions.F_Conversion)
76+
result = NALGrammar.Judgment(result_statement, (result_truth, truth_values), occurrence_time=occurrence_time)
7677
elif isinstance(j, NALGrammar.Question):
7778
result = NALGrammar.Question(result_statement)
7879

‎NALInferenceRules/Syllogistic.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,6 @@ def Abduction(j1, j2):
216216
if isinstance(j1, NALGrammar.Judgment):
217217
# Get Truth Value
218218
(f1, c1), (f2, c2) = getevidentialvalues_from2sentences(j1, j2)
219-
220219
result_truth = TruthValueFunctions.F_Abduction(f1, c1, f2, c2)
221220
result = NALGrammar.Judgment(result_statement, result_truth, occurrence_time=j1.stamp.occurrence_time)
222221
elif isinstance(j1, NALGrammar.Question):
@@ -351,8 +350,14 @@ def Comparison(j1, j2):
351350
if isinstance(j1, NALGrammar.Judgment):
352351
# Get Truth Value
353352
(f1, c1), (f2, c2) = getevidentialvalues_from2sentences(j1, j2)
354-
result_truth = TruthValueFunctions.F_Comparison(f1, c1, f2, c2)
355-
result = NALGrammar.Judgment(result_statement, result_truth, occurrence_time=j1.stamp.occurrence_time)
353+
if j1.is_array and j2.is_array:
354+
result_truths = TruthValueFunctions.TruthFunctionOnArray(j1.truth_values, j2.truth_values,truth_value_function=TruthValueFunctions.F_Comparison)
355+
result_truth = TruthValueFunctions.ReviseArray(result_truths)
356+
else:
357+
result_truths = None
358+
result_truth = TruthValueFunctions.F_Comparison(f1, c1, f2, c2)
359+
360+
result = NALGrammar.Judgment(result_statement, (result_truth,result_truths), occurrence_time=j1.stamp.occurrence_time)
356361
elif isinstance(j1, NALGrammar.Question):
357362
result = NALGrammar.Question(result_statement)
358363

‎NALInferenceRules/TruthValueFunctions.py‎

Lines changed: 55 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212
import Config
1313
import Global
1414
import NALGrammar
15-
from NALInferenceRules import HelperFunctions, ExtendedBooleanOperators
16-
from NALInferenceRules.HelperFunctions import get_truthvalue_from_evidence
15+
import NALInferenceRules
16+
from NALInferenceRules import ExtendedBooleanOperators
1717

1818

1919
def F_Revision(wp1, wn1, wp2, wn2):
@@ -24,7 +24,7 @@ def F_Revision(wp1, wn1, wp2, wn2):
2424
wp = wp1 + wp2
2525
wn = wn1 + wn2
2626
w = wp + wn
27-
f_rev, c_rev = HelperFunctions.get_truthvalue_from_evidence(wp, w)
27+
f_rev, c_rev = NALInferenceRules.HelperFunctions.get_truthvalue_from_evidence(wp, w)
2828
return NALGrammar.TruthValue(f_rev, c_rev)
2929

3030

@@ -39,14 +39,13 @@ def F_Negation(f, c):
3939

4040
def F_Conversion(f, c):
4141
"""
42-
wp = AND(f, c)
43-
wn = AND(NOT(f), c)
42+
f_cnv = 1
43+
c_cnv = (f*c)/(f*c+k)
4444
:return: F_cnv: Truth-Value (f,c)
4545
"""
4646
# compute values of combined evidence
47-
wp = ExtendedBooleanOperators.band(f, c)
48-
w = wp
49-
f_cnv, c_cnv = get_truthvalue_from_evidence(wp, w)
47+
f_cnv = 1.0
48+
c_cnv = (f*c)/(f*c+Config.k)
5049
return NALGrammar.TruthValue(f_cnv, c_cnv)
5150

5251

@@ -59,7 +58,7 @@ def F_Contraposition(f, c):
5958
wp = 0
6059
wn = ExtendedBooleanOperators.band(ExtendedBooleanOperators.bnot(f), c)
6160
w = wn
62-
f_cnt, c_cnt = get_truthvalue_from_evidence(wp, w)
61+
f_cnt, c_cnt = NALInferenceRules.Helperfunctions.get_truthvalue_from_evidence(wp, w)
6362

6463
return NALGrammar.TruthValue(f_cnt, c_cnt)
6564

@@ -112,7 +111,7 @@ def F_Abduction(f1, c1, f2, c2):
112111
# compute values of combined evidence
113112
wp = ExtendedBooleanOperators.band(f1, f2, c1, c2)
114113
w = ExtendedBooleanOperators.band(f1, c1, c2)
115-
f_abd, c_abd = get_truthvalue_from_evidence(wp, w)
114+
f_abd, c_abd = NALInferenceRules.HelperFunctions.get_truthvalue_from_evidence(wp, w)
116115
return NALGrammar.TruthValue(f_abd, c_abd)
117116

118117

@@ -123,7 +122,7 @@ def F_Induction(f1, c1, f2, c2):
123122
# compute values of combined evidence
124123
wp = ExtendedBooleanOperators.band(f1, f2, c1, c2)
125124
w = ExtendedBooleanOperators.band(f2, c1, c2)
126-
f_ind, c_ind = get_truthvalue_from_evidence(wp, w)
125+
f_ind, c_ind = NALInferenceRules.HelperFunctions.get_truthvalue_from_evidence(wp, w)
127126
return NALGrammar.TruthValue(f_ind, c_ind)
128127

129128

@@ -134,7 +133,7 @@ def F_Exemplification(f1, c1, f2, c2):
134133
# compute values of combined evidence
135134
wp = ExtendedBooleanOperators.band(f1, f2, c1, c2)
136135
w = wp
137-
f_exe, c_exe = get_truthvalue_from_evidence(wp, w)
136+
f_exe, c_exe = NALInferenceRules.HelperFunctions.get_truthvalue_from_evidence(wp, w)
138137
return NALGrammar.TruthValue(f_exe, c_exe)
139138

140139

@@ -145,7 +144,7 @@ def F_Comparison(f1, c1, f2, c2):
145144
# compute values of combined evidence
146145
wp = ExtendedBooleanOperators.band(f1, f2, c1, c2)
147146
w = ExtendedBooleanOperators.band(ExtendedBooleanOperators.bor(f1, f2), c1, c2)
148-
f3, c3 = get_truthvalue_from_evidence(wp, w)
147+
f3, c3 = NALInferenceRules.HelperFunctions.get_truthvalue_from_evidence(wp, w)
149148
return NALGrammar.TruthValue(f3, c3)
150149

151150

@@ -211,3 +210,46 @@ def Expectation(f, c):
211210
expectation value
212211
"""
213212
return c * (f - 0.5) + 0.5
213+
214+
def TruthFunctionOnArray(truth_value_array_1, truth_value_array_2, truth_value_function):
215+
"""
216+
Performs a truth value function element-wise on the array
217+
:param truth_value_array_1:
218+
:param truth_value_array_2:
219+
:param truth_value_function:
220+
:return:
221+
"""
222+
if truth_value_array_1 is None and truth_value_array_2 is None: return None
223+
truth_values = []
224+
for z, layer in enumerate(truth_value_array_1):
225+
truth_values_layer = []
226+
for y, row in enumerate(layer):
227+
truth_values_row = []
228+
for x, value in enumerate(row):
229+
if truth_value_array_2 is None:
230+
# single truth value
231+
truth_values_row.append(truth_value_function(value.frequency, value.confidence))
232+
else:
233+
truth_values_row.append(truth_value_function(value.frequency, value.confidence,truth_value_array_2[z][y][x].frequency, truth_value_array_2[z][y][x].confidence))
234+
truth_values_layer.append(truth_values_row)
235+
truth_values.append(truth_values_layer)
236+
return truth_values
237+
238+
239+
def ReviseArray(array_to_iterate):
240+
"""
241+
Performs a truth value function element-wise on the array
242+
and revises it into a single truth-value
243+
"""
244+
final_truth_value = None
245+
246+
for z, layer in enumerate(array_to_iterate):
247+
for y, row in enumerate(layer):
248+
for x, value in enumerate(row):
249+
if final_truth_value is None:
250+
final_truth_value = value
251+
else:
252+
wp1, w1, wn1 = NALInferenceRules.HelperFunctions.get_evidence_fromfreqconf(final_truth_value.frequency, final_truth_value.confidence)
253+
wp2, w2, wn2 = NALInferenceRules.HelperFunctions.get_evidence_fromfreqconf(value.frequency, value.confidence)
254+
final_truth_value = F_Revision(wp1,wn1,wp2,wn2)
255+
return final_truth_value

0 commit comments

Comments
 (0)