Skip to content

Commit

Permalink
style(console): 🎨 Optimize the style of Console.py and add comments…
Browse files Browse the repository at this point in the history
… to each function
  • Loading branch information
ARCJ137442 committed Sep 21, 2023
1 parent 91f2f00 commit 91a8b86
Showing 1 changed file with 110 additions and 34 deletions.
144 changes: 110 additions & 34 deletions pynars/Console.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@


def info(title):
'''Print the info of module and process'''
print(f'''
============= {title} =============
module name: {__name__}
Expand All @@ -27,23 +28,32 @@ def info(title):


def run_line(nars: Reasoner, line: str):
''''''
'''Run one line of input'''
line = line.strip(' \n')
# `//` comment
if line.startswith("//"):
return None
# special notations
elif line.startswith("''"):
if line.startswith("''outputMustContain('"):
line = line[len("''outputMustContain('"):].rstrip("')\n")
if len(line) == 0: return
if len(line) == 0:
return
try:
content_check = Narsese.parser.parse(line)
print_out(PrintType.INFO, f'OutputContains({content_check.sentence.repr()})')
print_out(
PrintType.INFO,
f'OutputContains({content_check.sentence.repr()})')
except:
print_out(PrintType.ERROR, f'Invalid input! Failed to parse: {line}')
# out_print(PrintType.ERROR, f'{file}, line {i}, {line}')
print_out(
PrintType.ERROR,
f'Invalid input! Failed to parse: {line}')
# print_out(PrintType.ERROR, f'{file}, line {i}, {line}')
return
# `'` comment
elif line.startswith("'"):
return None
# digit -> run cycle
elif line.isdigit():
n_cycle = int(line)
print_out(PrintType.INFO, f'Run {n_cycle} cycles.')
Expand All @@ -52,16 +62,22 @@ def run_line(nars: Reasoner, line: str):
tasks_all = nars.cycle()
tasks_all_cycles.append(deepcopy(tasks_all))
return tasks_all_cycles
# narsese
else:
line = line.rstrip(' \n')
if len(line) == 0:
return None
try:
success, task, _ = nars.input_narsese(line, go_cycle=False)
if success:
print_out(PrintType.IN, task.sentence.repr(), *task.budget)
print_out(
PrintType.IN,
task.sentence.repr(),
*task.budget)
else:
print_out(PrintType.ERROR, f'Invalid input! Failed to parse: {line}')
print_out(
PrintType.ERROR,
f'Invalid input! Failed to parse: {line}')

tasks_all = nars.cycle()
return [deepcopy(tasks_all)]
Expand All @@ -70,57 +86,107 @@ def run_line(nars: Reasoner, line: str):


def handle_lines(nars: Reasoner, lines: str):
'''Handle inputs with NARS reasoner'''
tasks_lines = []
# run input line by line #
for line in lines.split('\n'):
if len(line) == 0: continue

# skip empty lines
if len(line) == 0:
continue
# run non-empty lines
tasks_line = run_line(nars, line)
if tasks_line is not None:
tasks_lines.extend(tasks_line)

tasks_lines: List[Tuple[List[Task], Task, Task, List[Task], Task, Tuple[Task, Task]]]
# print the output #
tasks_lines: List[
Tuple[
List[Task], Task,
Task, List[Task],
Task, Tuple[Task, Task]
]
]
for tasks_line in tasks_lines:
tasks_derived, judgement_revised, goal_revised, answers_question, answers_quest, (
task_operation_return, task_executed) = tasks_line
for task in tasks_derived: print_out(PrintType.OUT, task.sentence.repr(), *task.budget)

if judgement_revised is not None: print_out(PrintType.OUT, judgement_revised.sentence.repr(),
*judgement_revised.budget)
if goal_revised is not None: print_out(PrintType.OUT, goal_revised.sentence.repr(), *goal_revised.budget)
# unpack one of lines of tasks, and then print out
(
tasks_derived,
judgement_revised,
goal_revised,
answers_question,
answers_quest,
(task_operation_return, task_executed)
) = tasks_line
# while derived task(s)
for task in tasks_derived:
print_out(
PrintType.OUT,
task.sentence.repr(),
*task.budget)
# while revising a judgement
if judgement_revised is not None:
print_out(
PrintType.OUT,
judgement_revised.sentence.repr(),
*judgement_revised.budget)
# while revising a goal
if goal_revised is not None:
print_out(
PrintType.OUT,
goal_revised.sentence.repr(),
*goal_revised.budget)
# while answering a question for truth value
if answers_question is not None:
for answer in answers_question: print_out(PrintType.ANSWER, answer.sentence.repr(), *answer.budget)
for answer in answers_question:
print_out(
PrintType.ANSWER,
answer.sentence.repr(),
*answer.budget)
# while answering a quest for desire value
if answers_quest is not None:
for answer in answers_quest: print_out(PrintType.ANSWER, answers_quest.sentence.repr(),
*answers_quest.budget)
for answer in answers_quest:
print_out(
PrintType.ANSWER,
answers_quest.sentence.repr(),
*answers_quest.budget)
# while executing an operation
if task_executed is not None:
print_out(PrintType.EXE,
f'{task_executed.term.repr()} = {str(task_operation_return) if task_operation_return is not None else None}')
print_out(
PrintType.EXE,
f'''{task_executed.term.repr()} = {
str(task_operation_return)
if task_operation_return is not None
else None}''')


def run_file(nars: Reasoner, filepath: str = None):
'''Run the content of file'''
# handle the file
if filepath is not None:
filepath: Path = Path(filepath)
filename = filepath.name
print_out(PrintType.COMMENT, f'Run file <{filename}>.', comment_title='NARS')
# notify
print_out(
PrintType.COMMENT,
f'Run file <{filename}>.',
comment_title='NARS')
# open and run
with open(filepath, 'r') as f:
lines = f.read()
handle_lines(nars, lines)


def run_nars(filepath: str):
''''''
def run_nars(filepath: str, seed: int = 137, n_memory: int = 100, capacity: int = 100):
'''Load the datas and launch the NARS reasoner'''
# info('Console')
seed = 137
# init status #
rand_seed(seed)
print_out(PrintType.COMMENT, f'rand_seed={seed}', comment_title='Setup')
nars = Reasoner(100, 100)
nars = Reasoner(n_memory, capacity)
nars.register_operation('left', lambda *args: print('execute left.'))

# try to run file if exists
print_out(PrintType.COMMENT, 'Init...', comment_title='NARS')
print_out(PrintType.COMMENT, 'Run...', comment_title='NARS')
run_file(nars, filepath)
# console
# console #
print_out(PrintType.COMMENT, 'Console.', comment_title='NARS')
while True:
print_out(PrintType.COMMENT, '', comment_title='Input', end='')
Expand All @@ -129,18 +195,28 @@ def run_nars(filepath: str):


if __name__ == '__main__':
'''Main process'''
# parse arguments
parser = argparse.ArgumentParser(description='Parse NAL files.')
parser.add_argument('filepath', metavar='Path', type=str, nargs='*',
parser.add_argument('filepath',
metavar='Path',
type=str,
nargs='*',
help='file path of an *.nal file.')
args = parser.parse_args()
# try to load files
filepath: Union[list, None] = args.filepath
filepath = filepath[0] if (filepath is not None and len(filepath) > 0) else None

filepath = (
filepath[0]
if filepath is not None and len(filepath) > 0
else None)
# launch NARS
try:
run_nars(filepath)
# when stop
except KeyboardInterrupt:
print_out(PrintType.COMMENT, 'Stop...', comment_title='\n\nNARS')

# main process finish
print('Done.')

# if __name__ == '__main__':
Expand Down

0 comments on commit 91a8b86

Please sign in to comment.