diff --git a/.vscode/launch.json b/.vscode/launch.json
index 78baa17..1899ec0 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -249,7 +249,7 @@
]
},
{
- "name": "Python: Console Experimental Features",
+ "name": "Python: ex-console for experiments",
"type": "python",
"request": "launch",
"module": "Experiments.ExConsole.main",
diff --git a/Experiments/ExConsole/data2nal.py b/Experiments/ExConsole/data2nal.py
index 9a20f86..7073a61 100644
--- a/Experiments/ExConsole/data2nal.py
+++ b/Experiments/ExConsole/data2nal.py
@@ -24,14 +24,14 @@ def SIGN_TYPE_NAMES(type): return type.__name__
# Preset identification
-def isBasicType(obj: any) -> bool:
+def is_basic_type(obj: any) -> bool:
'''Determining whether a type is an "immutable type"
Note: Strings are counted'''
t = type(obj)
return obj == None or t == bool or t == int or t == float or t == str
-def verifyTermName(name: str) -> str | None:
+def verify_term_name(name: str) -> str | None:
try:
return (
name
@@ -43,50 +43,50 @@ def verifyTermName(name: str) -> str | None:
# term construction
-def termRel(A: str, B: str) -> str:
+def term_rel(A: str, B: str) -> str:
'''Construct the term "Relationship between A and B"'''
return f'(*,{A},{B})'
-def termName(A: any) -> str:
+def term_name(A: any) -> str:
'''Build term "object name"'''
t: type = type(A)
# test whether the object can be directly accepted as a lexical item, if it is attached, if not, no
- instanceWrapper: str = '%s' if isBasicType(A) else '{%s}'
+ instance_wrapper: str = '%s' if is_basic_type(A) else '{%s}'
# first format encapsulation: Fill "class name _ value /id"
- initName: str = verifyTermName(f'{t.__name__}_{str(A)}')
+ init_name: str = verify_term_name(f'{t.__name__}_{str(A)}')
# check: Whether the filled term is valid (cause: the array "first pass, second fail" problem)
- initName = verifyTermName(
- initName if initName else f'{t.__name__}_{id(A)}')
+ init_name = verify_term_name(
+ init_name if init_name else f'{t.__name__}_{id(A)}')
# second format encapsulation: Specifies whether an instance term is required
- finalName: str = instanceWrapper % initName
+ final_name: str = instance_wrapper % init_name
# return
- return finalName
+ return final_name
# sentence construction
-def sentenceInh(A: str, B: str, punct: Punctuation | str = Punctuation.Judgement) -> str:
+def sentence_inh(A: str, B: str, punct: Punctuation | str = Punctuation.Judgement) -> str:
'''Building relationships "A is B"'''
return f'<{A} --> {B}>{punct.value if isinstance(punct,Punctuation) else punct}' # B> default with "."
-def sentenceRel(A: str, r: str, B: str, punct: Punctuation = Punctuation.Judgement) -> str:
+def sentence_rel(A: str, r: str, B: str, punct: Punctuation = Punctuation.Judgement) -> str:
'''Construct relation "ArB" i.e. "The relation between A and B" is r"'''
- return sentenceInh(termRel(A, B), f'{r}', punct=punct) # <(*,A,B) --> r>. The "relationship" between A and B is r
+ return sentence_inh(term_rel(A, B), f'{r}', punct=punct) # <(*,A,B) --> r>. The "relationship" between A and B is r
-def sentenceTypeSign(name: str, type: type, punct: Punctuation = Punctuation.Judgement) -> str:
+def sentence_type_sign(name: str, type: type, punct: Punctuation = Punctuation.Judgement) -> str:
'''Name the name based on the type of the object'''
- return sentenceInh(name, SIGN_TYPE_NAMES(type), punct=punct) # name --> type
+ return sentence_inh(name, SIGN_TYPE_NAMES(type), punct=punct) # name --> type
-def sentenceTriRel(obj: str, key: str, value: str, relation: str = SIGN_RELATION_OBJ_PROPERTY_VALUE,
- punct: Punctuation = Punctuation.Judgement) -> str:
+def sentence_tri_rel(obj: str, key: str, value: str, relation: str = SIGN_RELATION_OBJ_PROPERTY_VALUE,
+ punct: Punctuation = Punctuation.Judgement) -> str:
'''Building a ternary relationship "Object [key] = value"
- Example: (*,{object},(*,{attribute},{value})) --> objectAttributeValue
+ Example: (*,{object},(*,{attribute},{value})) --> object_attribute_value
'''
- return sentenceRel(obj, relation, termRel(key, value), punct=punct) # (*,{obj},(*,{key},{value})) --> relation
+ return sentence_rel(obj, relation, term_rel(key, value), punct=punct) # (*,{obj},(*,{key},{value})) --> relation
# Main conversion module #
@@ -94,118 +94,118 @@ def sentenceTriRel(obj: str, key: str, value: str, relation: str = SIGN_RELATION
# Use kwargs to automatically pass "punctuation" information
-def none2NAL(n: None, specialName: str, **kwargs) -> list[str]:
+def none2NAL(n: None, special_name: str, **kwargs) -> list[str]:
'''None to NAL'''
- return [sentenceTypeSign(specialName, type(n), **kwargs)]
+ return [sentence_type_sign(special_name, type(n), **kwargs)]
-def bool2NAL(b: str, specialName: str, **kwargs) -> list[str]:
+def bool2NAL(b: str, special_name: str, **kwargs) -> list[str]:
'''boolean to NAL'''
- result: list[str] = [sentenceTypeSign(
- specialName, bool, **kwargs)] # preset type identification
+ result: list[str] = [sentence_type_sign(
+ special_name, bool, **kwargs)] # preset type identification
return result
-def int2NAL(i: int, specialName: str, **kwargs) -> list[str]:
+def int2NAL(i: int, special_name: str, **kwargs) -> list[str]:
'''Integer to NAL
TODO: Build an integer system'''
- result: list[str] = [sentenceTypeSign(
- specialName, int, **kwargs)] # preset type identification
+ result: list[str] = [sentence_type_sign(
+ special_name, int, **kwargs)] # preset type identification
return result
-def float2NAL(f: float, specialName: str, **kwargs) -> list[str]:
+def float2NAL(f: float, special_name: str, **kwargs) -> list[str]:
'''Floating-point number becomes NAL
TODO: Build a floating point number system and combine it with an integer system'''
- result: list[str] = [sentenceTypeSign(
- specialName, float, **kwargs)] # preset type identification
+ result: list[str] = [sentence_type_sign(
+ special_name, float, **kwargs)] # preset type identification
return result
-def str2NAL(s: str, specialName: str, **kwargs) -> list[str]:
+def str2NAL(s: str, special_name: str, **kwargs) -> list[str]:
'''Set to NAL
TODO: How does distinguish between "name" and "value" of a string?'''
# tests whether a string can be directly accepted as a term, appended if it is, unappended if it is not
# Try to use the string itself as a name for easy identification
- finalName = verifyTermName(s)
- finalName: str = specialName + \
- (f'「{s}」' if finalName else '') # Include itself if you can, do not add information otherwise
+ final_name = verify_term_name(s)
+ final_name: str = special_name + \
+ (f'「{s}」' if final_name else '') # Include itself if you can, do not add information otherwise
# preset type identification
- result: list[str] = [sentenceTypeSign(finalName, str, **kwargs)]
+ result: list[str] = [sentence_type_sign(final_name, str, **kwargs)]
return result
# containers
-def set2NAL(s: set, specialName: str, **kwargs) -> list[str]:
+def set2NAL(s: set, special_name: str, **kwargs) -> list[str]:
'''Set to NAL
Use the relative item "belong"
Import a collection name as the concept name, and then convert all elements within it to NAL
Return: A list of multiple NAL statements (easy to split)'''
- result: list[str] = [sentenceTypeSign(
- specialName, set, **kwargs)] # preset type identification
+ result: list[str] = [sentence_type_sign(
+ special_name, set, **kwargs)] # preset type identification
for item in s: # TODO: Implementing recursive logic @auto2NAL(item)
- result.append(sentenceRel(termName(item),
- SIGN_RELATION_BELONG, specialName, **kwargs))
+ result.append(sentence_rel(term_name(item),
+ SIGN_RELATION_BELONG, special_name, **kwargs))
return result
-def lisTuple2NAL(array: list | tuple, specialName: str, **kwargs) -> list[str]:
+def lis_tuple2NAL(array: list | tuple, special_name: str, **kwargs) -> List[str]:
'''List/tuple to NAL: Lists whose keys are integers'''
- result: list[str] = [sentenceTypeSign(
- specialName, type(array), **kwargs)] # preset type identification
+ result: list[str] = [sentence_type_sign(
+ special_name, type(array), **kwargs)] # preset type identification
for i in range(len(array)):
# get element
item: any = array[i]
- iName: str = termName(i)
- itemName: str = termName(item)
+ iName: str = term_name(i)
+ item_name: str = term_name(item)
# pre-add definitions for keys and values
- result.extend(auto2NAL(item, itemName, **kwargs))
+ result.extend(auto2NAL(item, item_name, **kwargs))
result.extend(auto2NAL(i, iName, **kwargs))
# bind objects, keys, and values
- result.append(sentenceTriRel(
- specialName,
+ result.append(sentence_tri_rel(
+ special_name,
iName,
- itemName,
- **kwargs)) # list[integerIndex] = value
+ item_name,
+ **kwargs)) # list[integer_index] = value
return result
-def dict2NAL(d: dict, specialName: str, **kwargs) -> list[str]:
+def dict2NAL(d: dict, special_name: str, **kwargs) -> list[str]:
'''dict to NAL
#! In fact, JSON is a dictionary, to achieve the dictionary↔NAL conversion, which is equivalent to NARS can read JSON
TODO models dictionaries using an index system'''
- result: list[str] = [sentenceTypeSign(
- specialName, dict, **kwargs)] # preset type identification
+ result: list[str] = [sentence_type_sign(
+ special_name, dict, **kwargs)] # preset type identification
for key, value in d.items():
- keyName: str = termName(key)
- valueName: str = termName(value)
+ key_name: str = term_name(key)
+ value_name: str = term_name(value)
# pre-add definitions for keys and values
- result.extend(auto2NAL(key, keyName, **kwargs))
- result.extend(auto2NAL(value, valueName, **kwargs))
+ result.extend(auto2NAL(key, key_name, **kwargs))
+ result.extend(auto2NAL(value, value_name, **kwargs))
# bind objects, keys, and values
- result.append(sentenceTriRel(
- specialName,
- keyName,
- valueName,
- **kwargs)) # dictionary[immutableDataIndex] = value
+ result.append(sentence_tri_rel(
+ special_name,
+ key_name,
+ value_name,
+ **kwargs)) # dictionary[immutable_data_index] = value
return result
-def type2NAL(t: type, specialName: str, **kwargs) -> list[str]:
+def type2NAL(t: type, special_name: str, **kwargs) -> list[str]:
'''Type to NAL
The "type" itself also needs to become NAL'''
- return [sentenceTypeSign(specialName, type, **kwargs)] # only type notations
+ return [sentence_type_sign(special_name, type, **kwargs)] # only type notations
# default values
-def default2NAL(obj: any, specialName: str, **kwargs) -> list[str]:
+def default2NAL(obj: any, special_name: str, **kwargs) -> list[str]:
'''Other objects become NAL
Temporarily occupy the one place, will later be separated from many types'''
print(f'WARNING: unsupported object {obj} with type {type(obj)}')
# only type notations
- return [sentenceTypeSign(specialName, type, **kwargs)]
+ return [sentence_type_sign(special_name, type, **kwargs)]
# Main function: Integrate all parts #
@@ -216,8 +216,8 @@ def default2NAL(obj: any, specialName: str, **kwargs) -> list[str]:
float: float2NAL,
bool: bool2NAL,
str: str2NAL,
- list: lisTuple2NAL,
- tuple: lisTuple2NAL,
+ list: lis_tuple2NAL,
+ tuple: lis_tuple2NAL,
set: set2NAL,
dict: dict2NAL,
type: type2NAL,
@@ -230,14 +230,14 @@ def auto2NAL(obj: any, name: str = None, punct: Punctuation = Punctuation.Judgem
Automatically identify the object type and call the corresponding conversion function'''
# get name
# If no, automatically generate
- name = name if name else termName(obj)
+ name = name if name else term_name(obj)
# get type
t = type(obj)
# select & Generate, with default values (all parameters must accept a "Narsese parsed name")
- narsSentences: list[str] = CONVERT_FUNCTIONS.get(
+ nars_sentences: list[str] = CONVERT_FUNCTIONS.get(
t, CONVERT_FUNCTIONS[None])(obj, name, punct=punct)
# verify
- for sentence in narsSentences:
+ for sentence in nars_sentences:
parser.parse(sentence)
# return
- return narsSentences
+ return nars_sentences
diff --git a/Experiments/ExConsole/main.py b/Experiments/ExConsole/main.py
index a24ecdd..e43a900 100644
--- a/Experiments/ExConsole/main.py
+++ b/Experiments/ExConsole/main.py
@@ -6,7 +6,7 @@
# Interface
from pynars.ConsolePlus import *
# need to report errors to ** timely detection of ** "invalid statement input" caused by the bug
-from pynars.Interface import NAL_Parse
+from pynars.Narsese import parser as NarseseParser
# PyNARS: Import internal modules
from pynars.NARS.DataStructures._py.Channel import *
@@ -19,51 +19,51 @@
# information
-def infBag(bag: Bag, sep: str = ',', indentCount: int = 1) -> str:
+def show_bag(bag: Bag, sep: str = ',', indent_count: int = 1) -> str:
'''Relation of extension: Channel -> Buffer -> Bag'''
- notNoneLevels: list[list] = [
- levelList for levelList in bag.levels if levelList]
- if notNoneLevels:
- sep = sep + '\n' + "\t"*indentCount
- return f'{repr(bag)} :\n' + "\t"*indentCount + sep.join(
+ not_none_levels: list[list] = [
+ level_list for level_list in bag.levels if level_list]
+ if not_none_levels:
+ sep = sep + '\n' + "\t"*indent_count
+ return f'{repr(bag)} :\n' + "\t"*indent_count + sep.join(
','.join(
repr(value)
for value in level)
- for level in notNoneLevels)
+ for level in not_none_levels)
return repr(bag)
-def infBuffer(buffer: Buffer) -> str:
+def show_buffer(buffer: Buffer) -> str:
item: Item = buffer.take_max(remove=False)
- return repr(buffer) + infBag(Bag(buffer)) + f' -> {item}'
+ return repr(buffer) + show_bag(Bag(buffer)) + f' -> {item}'
-def infChannel(channel: Channel) -> str:
+def show_channel(channel: Channel) -> str:
b = Buffer(channel)
- return repr(channel) + f'@{repr(infBuffer(buffer=b))}'
+ return repr(channel) + f'@{repr(show_buffer(buffer=b))}'
-def infMemory(memory: Memory, indentCount: int = 1) -> str:
- return repr(memory) + f'@{infBag(memory.concepts,indentCount=indentCount)}'
+def show_memory(memory: Memory, indent_count: int = 1) -> str:
+ return repr(memory) + f'@{show_bag(memory.concepts,indent_count=indent_count)}'
-def infReasoner(reasoner: Reasoner):
+def show_reasoner(reasoner: Reasoner):
return '\n\t'+"\n\t".join(f"{name}: {inf}" for name, inf in [
- ('Memory', infMemory(reasoner.memory, indentCount=2)),
+ ('Memory', show_memory(reasoner.memory, indent_count=2)),
('Channels', '\r\n\t\t'.join(
- infChannel(channel)
+ show_channel(channel)
for channel in reasoner.channels)),
# this section is a "temporary repository" of the knowledge NARS has acquired from the "channel".
- ('Overall Experience', infBuffer(reasoner.overall_experience)),
- ('Internal Experience', infBuffer(reasoner.internal_experience)),
- ('Sequence Buffer', infBuffer(reasoner.sequence_buffer)),
- ('Operations Buffer', infBuffer(reasoner.operations_buffer)),
+ ('Overall Experience', show_buffer(reasoner.overall_experience)),
+ ('Internal Experience', show_buffer(reasoner.internal_experience)),
+ ('Sequence Buffer', show_buffer(reasoner.sequence_buffer)),
+ ('Operations Buffer', show_buffer(reasoner.operations_buffer)),
])
-def printInf():
+def show_information():
print(
- f'''<{getCurrentReasonerName()}>: {infReasoner(currentNARSInterface.reasoner)}''')
+ f'''<{current_nar_name()}>: {show_reasoner(current_NARS_interface.reasoner)}''')
## Main program ##
@@ -71,13 +71,13 @@ def printInf():
EXPERIMENTAL_CMDS: dict[tuple[str]:tuple[any, tuple[str]]] = {}
-def expRegister(*cmdNames: tuple[str]):
- '''Mimic from `cmdRegister` in "Interface.py"
+def exp_register(*cmd_names: tuple[str]):
+ '''Mimic from `cmd_register` in "Interface.py"
It's no need of parameters because the experimental functions can utilize all of global variable'''
def decorator(func):
# register
global EXPERIMENTAL_CMDS
- EXPERIMENTAL_CMDS[cmdNames] = (func, )
+ EXPERIMENTAL_CMDS[cmd_names] = (func, )
'''
Core format & Structure: {Name: (handler function, ordinal and default list)}
! Tuples can be used as indexes: fixed type
@@ -98,27 +98,27 @@ def decorated(*args, **kwargs):
return decorator
-@expRegister('l')
-def listDetails_reasoner() -> None:
- return reasonerList()
+@exp_register('l')
+def list_details_reasoner() -> None:
+ return reasoner_list()
-@expRegister('t')
+@exp_register('t')
def test_simple_output() -> None:
- execInput(' B>.')
+ execute_input(' B>.')
-@expRegister('r')
+@exp_register('r')
def test_random_input_sentence() -> None:
- execInput(f' A{randint(1,9)}>.')
+ execute_input(f' A{randint(1,9)}>.')
-@expRegister('c')
+@exp_register('c')
def list_all_concepts() -> None:
- print(infBag((currentNARSInterface.reasoner.memory.concepts)))
+ print(show_bag((current_NARS_interface.reasoner.memory.concepts)))
-@expRegister('exec')
+@exp_register('exec')
def exec_multiline_python_code() -> None:
while (inp := input('Please input Python code (empty to cancel)')):
try:
@@ -127,7 +127,7 @@ def exec_multiline_python_code() -> None:
print(f'Error! {e}')
-@expRegister('v')
+@exp_register('v')
def list_variables() -> None:
print('locals\n\t'+'\n\t'.join(f'{k} : {v}' for k, v in locals().items()),
'globals\n\t' +
@@ -135,55 +135,55 @@ def list_variables() -> None:
sep='\n')
-@expRegister('r')
+@exp_register('r')
def list_histories() -> None:
- printHistory('')
- printHistory('1')
+ print_history('')
+ print_history('1')
-@expRegister('help')
+@exp_register('help')
def help_of_experiments() -> None:
print('''The backslash commands is used for feature experiments.\nto see the supported certain commands, may you should view `Experiments\ExConsole\main.py\_cmdExperiment`.''')
- help('', searchIn=EXPERIMENTAL_CMDS)
+ help('', search_in=EXPERIMENTAL_CMDS)
-@expRegister('ch')
+@exp_register('ch')
def channel_addition_test() -> None:
# add new channel
channel: Channel = Channel(capacity=5, n_buckets=5, max_duration=10000)
# [2023-09-21 23:51:23] PyNARS does not currently have a built-in "add channel" method
- currentNARSInterface.reasoner.channels.append(channel)
- print(infChannel(channel=channel))
+ current_NARS_interface.reasoner.channels.append(channel)
+ print(show_channel(channel=channel))
# test new channel
- [channel.put(NAL_Parse(testSentence_C)) # auto parse
- for testSentence_C in [
+ [channel.put(NarseseParser.parse(test_sentence_C)) # auto parse
+ for test_sentence_C in [
' cpt_channel_2>.',
' cpt_channel_3>.',
' cpt_channel_3>?',
]
] # ? multiple input at once
- printInf()
- execInput('/waitans')
- printInf()
+ show_information()
+ execute_input('/waitans')
+ show_information()
-@expRegister('cha')
+@exp_register('cha')
def shared_channel_test() -> None:
channel: Channel = NarseseChannel(
capacity=500, n_buckets=100, max_duration=1000)
# new reasoner
- rName1: str = '1'
- rName2: str = '2'
- r1: Reasoner = reasonerNew(name=rName1).reasoner
- r2: Reasoner = reasonerNew(name=rName2).reasoner
+ r_name1: str = '1'
+ r_name2: str = '2'
+ r1: Reasoner = reasoner_new(name=r_name1).reasoner
+ r2: Reasoner = reasoner_new(name=r_name2).reasoner
r1.narsese_channel = r2.narsese_channel = r1.channels[0] = r2.channels[0] = channel
- execInput(' B>.') # enter the NARS statement in r2
- reasonerGoto(rName1) # r1 also has channels in it
- execInput('10') # enter the NARS statement in r2
- reasonerList()
+ execute_input(' B>.') # enter the NARS statement in r2
+ reasoner_goto(r_name1) # r1 also has channels in it
+ execute_input('10') # enter the NARS statement in r2
+ reasoner_list()
-@expRegister('me')
+@exp_register('me')
def shared_memory_test() -> None:
memory: Memory = Memory(
capacity=1000,
@@ -191,53 +191,53 @@ def shared_memory_test() -> None:
# new reasoner
rName1: str = '1'
rName2: str = '2'
- r1: Reasoner = reasonerNew(name=rName1)._NARS
- r2: Reasoner = reasonerNew(name=rName2)._NARS
+ r1: Reasoner = reasoner_new(name=rName1)._NARS
+ r2: Reasoner = reasoner_new(name=rName2)._NARS
r1.memory = r2.memory = memory
# enter the NARS statement in r2
- execInput('A --> B.', 'B --> C.', 'A --> C?')
- reasonerGoto(rName1) # r1 also has channels in it
- execInput('1') # enter the NARS statement in r2
+ execute_input('A --> B.', 'B --> C.', 'A --> C?')
+ reasoner_goto(rName1) # r1 also has channels in it
+ execute_input('1') # enter the NARS statement in r2
print(r1.memory is r2.memory, r1.memory is memory)
- printInf()
+ show_information()
-@expRegister('op')
+@exp_register('op')
def operations_test() -> None:
- taskOp: Task = NAL_Parse(' result>.') # auto parse
+ task1: Task = NarseseParser.parse(' result>.') # auto parse
# term.type = TermType.STATEMENT # ! Only statements can be actions, not mandatory
- statementOp = taskOp.term # term of the task
+ statement1 = task1.term # term of the task
# * Force the term involved in the task to be set to "action", if is_executable = True
- statementOp.is_operation = True
- print(f'Is operation? {statementOp.is_executable}')
+ statement1.is_operation = True
+ print(f'Is operation? {statement1.is_executable}')
'''concept Concept: Concept = concept. _conceptualize( # Generate concept
- currentNARSInterface.reasoner.memory,
+ current_NARS_interface.reasoner.memory,
term=statement Operation statement,
Budget=budget(0.9, 0.9, 0.5)
)
- currentNARSInterface.reasoner.memory.concepts.put(concept)
+ current_NARS_interface.reasoner.memory.concepts.put(concept)
# into the concept, but it does not seem to be associated with the task, the reasoner will not use it.
# '''
# placing tasks directly into perceptual channels (Narsese channels can only pass text)
- currentNARSInterface.reasoner.perception_channel.put(taskOp)
+ current_NARS_interface.reasoner.perception_channel.put(task1)
# Automatic reasoning five steps, let NAS put "antecedent" and "result" into the memory area
- execInput('5')
+ execute_input('5')
# print concept list
- print(infBag(currentNARSInterface.reasoner.memory.concepts))
+ print(show_bag(current_NARS_interface.reasoner.memory.concepts))
-@expRegister('far', 'chain', 'chain_inference')
+@exp_register('far', 'chain', 'chain_inference')
def chain_inference_test() -> None:
n: int = int(input('Please enter the length of chain:'))
- [execInput(f' chainNo{i+1}>.')
+ [execute_input(f' chain_{i+1}>.')
for i in range(n)
]
- printInf()
- execInput(f' chainNo{n}>?')
- execInput('/waitans')
+ show_information()
+ execute_input(f' chain_{n}>?')
+ execute_input('/waitans')
-@expRegister('json')
+@exp_register('json')
def JSON_test() -> None:
'''Input a series of numbers and construct a set, allowing NARS to determine ownership'''
from data2nal import auto2NAL, SIGN_RELATION_BELONG
@@ -245,54 +245,54 @@ def JSON_test() -> None:
f: set = {x for x in range(n)}
sN: str = f'Num0to{n}'
s2: set = {sN, 'element2'}
- sN2: str = 'bigSet'
- execInput(*auto2NAL(f, sN), *auto2NAL(f, sN2),
- f'<(*,{1},{sN2}) --> {SIGN_RELATION_BELONG}>?')
- printInf()
- execInput('/waitans')
- printInf()
+ sN2: str = 'big_set'
+ execute_input(*auto2NAL(f, sN), *auto2NAL(f, sN2),
+ f'<(*,{1},{sN2}) --> {SIGN_RELATION_BELONG}>?')
+ show_information()
+ execute_input('/waitans')
+ show_information()
-@expRegister('json')
+@exp_register('json')
def JSON_test2() -> None:
'''Enter a custom dictionary and ask for relationships one by one'''
from data2nal import auto2NAL
print('JSON Test Part II:')
dic: dict = {
- 'smallestPositiveInteger': 1,
- 'evenNumberLT10': [
+ 'smallest_positive_integer': 1,
+ 'even_number_LT_10': [
2, 4, 6, 8
],
- 'is0notNeg': True,
+ 'is0not_neg': True,
1: {
- 'dictName': 'aNameOfDict'
+ 'dict_name': 'a_name_of_dict'
}
}
- execInput(*auto2NAL(dic, 'myDict'))
- printInf()
- execInput(*auto2NAL(dic, 'myDict', punct=Punctuation.Question))
- printInf()
- execInput('/waitans')
+ execute_input(*auto2NAL(dic, 'my_dict'))
+ show_information()
+ execute_input(*auto2NAL(dic, 'my_dict', punct=Punctuation.Question))
+ show_information()
+ execute_input('/waitans')
-@expRegister('json')
+@exp_register('json')
def JSON_test3() -> None:
'''Enter a Config.json object that acts as its own "system parameter"'''
print('JSON Test Part III')
from pynars.Interface import DEFAULT_CONFIG
from data2nal import auto2NAL
- printInf()
- execInput(*auto2NAL(DEFAULT_CONFIG, 'systemConfig',
- punct=Punctuation.Judgement))
- printInf()
- execInput(*auto2NAL(DEFAULT_CONFIG, 'systemConfig',
- punct=Punctuation.Question))
- printInf()
- execInput('/waitans')
-
-
-@expRegister('eval')
-def pyObject_loadIn() -> None:
+ show_information()
+ execute_input(*auto2NAL(DEFAULT_CONFIG, 'system_config',
+ punct=Punctuation.Judgement))
+ show_information()
+ execute_input(*auto2NAL(DEFAULT_CONFIG, 'system_config',
+ punct=Punctuation.Question))
+ show_information()
+ execute_input('/waitans')
+
+
+@exp_register('eval')
+def py_object_load_in() -> None:
'''Load any Python object into NARS'''
from data2nal import auto2NAL
obj: any = None
@@ -309,85 +309,85 @@ def pyObject_loadIn() -> None:
nals: list[str] = auto2NAL(
obj, punct=punct if punct else '.', name=name if name else None)
print(f'Input object: {repr(obj)}\nNAL text: \n' + "\n".join(nals))
- execInput(*nals)
+ execute_input(*nals)
-@expRegister('mcopyJ')
+@exp_register('mcopyJ')
def memory_copy_JSON() -> None:
'''Experiment: Memory copy & Localization retention'''
- nars = currentNARSInterface.reasoner
+ nars = current_NARS_interface.reasoner
import jsonpickle as jp # Use the JSON serialization library jsonpickle
- copiedMem: Memory = deepcopy(nars.memory)
- execInput('A-->B.', 'B-->C.', 'A-->C?', '/waitans')
- print(id(nars.memory), infMemory(nars.memory),
- 'copied:\n', id(copiedMem), infMemory(copiedMem))
- jpEmem = jp.encode(nars.memory)
- jpEcopied = jp.encode(copiedMem)
- print('pickle#Encode:\n', repr(jpEmem), 'copied:\n', repr(jpEcopied))
- decodedMem: Memory = jp.decode(jpEcopied)
- print(id(copiedMem), infMemory(copiedMem), 'decoded:\n',
- id(decodedMem), infMemory(decodedMem))
-
-
-@expRegister('rcopyJ')
+ copied_mem: Memory = deepcopy(nars.memory)
+ execute_input('A-->B.', 'B-->C.', 'A-->C?', '/waitans')
+ print(id(nars.memory), show_memory(nars.memory),
+ 'copied:\n', id(copied_mem), show_memory(copied_mem))
+ jp_emem = jp.encode(nars.memory)
+ jp_ecopied = jp.encode(copied_mem)
+ print('pickle#Encode:\n', repr(jp_emem), 'copied:\n', repr(jp_ecopied))
+ decoded_mem: Memory = jp.decode(jp_ecopied)
+ print(id(copied_mem), show_memory(copied_mem), 'decoded:\n',
+ id(decoded_mem), show_memory(decoded_mem))
+
+
+@exp_register('rcopyJ')
def reasoner_copy_JSON() -> None:
'''Make a deep copy of the entire reasoner'''
- nars = currentNARSInterface.reasoner
+ nars = current_NARS_interface.reasoner
import jsonpickle as jp # Use the JSON serialization library jsonpickle
import json
- copiedNar: Reasoner = deepcopy(nars) # deep copy
- jpEnar: str = jp.encode(copiedNar) # serialize to JSON string
- encodedNar: dict = json.loads(jpEnar) # JSON string to dict
- rStrDict: str = repr(encodedNar) # dict to str
- decodedNar: Reasoner = jp.decode(
- json.dumps(encodedNar)) # str to Reasoner
+ copied_nar: Reasoner = deepcopy(nars) # deep copy
+ jp_enar: str = jp.encode(copied_nar) # serialize to JSON string
+ encoded_nar: dict = json.loads(jp_enar) # JSON string to dict
+ rStr_dict: str = repr(encoded_nar) # dict to str
+ decoded_nar: Reasoner = jp.decode(
+ json.dumps(encoded_nar)) # str to Reasoner
print(
- f'Copied:\n{infReasoner(copiedNar)}\nEncoded:\n{rStrDict}\nDecoded:\n{infReasoner(decodedNar)}')
+ f'Copied:\n{show_reasoner(copied_nar)}\nEncoded:\n{rStr_dict}\nDecoded:\n{show_reasoner(decoded_nar)}')
-@expRegister('copyJ')
+@exp_register('copyJ')
def copy_JSON() -> None:
'''Copy the reasoner data to the clipboard'''
- nars = currentNARSInterface.reasoner
+ nars = current_NARS_interface.reasoner
# import module
from pyperclip import copy
import jsonpickle as jp
try:
- jpEnar: str = jp.encode(nars) # serialize to JSON string
+ jp_enar: str = jp.encode(nars) # serialize to JSON string
print(
- f'Source reasoner:\n{infReasoner(nars)}\n Serialized JSON string:\n{jpEnar}')
- copy(jpEnar) # copy to clipboard
+ f'Source reasoner:\n{show_reasoner(nars)}\n Serialized JSON string:\n{jp_enar}')
+ copy(jp_enar) # copy to clipboard
print('JSON data copied!')
except BaseException as e:
print(f'Save Failed! Error: {e.with_traceback(None) if e else e}')
-@expRegister('loadJ')
+@exp_register('loadJ')
def load_JSON() -> None:
'''load the clipboard reasoner data into the interface'''
# import module
import jsonpickle as jp
try:
- jsonPath: str = input(
+ json_path: str = input(
'Please enter your saved reasoner JSON path:') # get JSON path
from pathlib import Path
- jsonPath: Path = Path(jsonPath)
- with open(jsonPath, mode='r', encoding='utf-8') as jsonFile:
- jsonStr: str = jsonFile.read()
+ json_path: Path = Path(json_path)
+ with open(json_path, mode='r', encoding='utf-8') as json_file:
+ json_str: str = json_file.read()
try:
- decodedNAR: Reasoner = jp.decode(
- jsonStr) # deserialize from JSON string
+ decoded_NAR: Reasoner = jp.decode(
+ json_str) # deserialize from JSON string
try:
- interfaceName: str = input(
+ interface_name: str = input(
'Please enter a new interface name:') # accept the reasoner with a new interface
interface: NARSInterface = NARSInterface(
- NARS=decodedNAR) # create interface
- reasoners[interfaceName] = interface # directly add
- reasonerGoto(interfaceName) # goto
+ NARS=decoded_NAR) # create interface
+ reasoners[interface_name] = interface # directly add
+ reasoner_goto(interface_name) # goto
print(
- f"Import a reasoner named {interfaceName}, silent {'on' if interface.silentOutput else 'off'}.")
+ f"Import a reasoner named {interface_name}, silent {'on' if interface.silent_output else 'off'}.")
print(
- f'Pre-deserialized JSON string:\n{jsonStr}\nNew reasoner:\n{infReasoner(decodedNAR)}')
+ f'Pre-deserialized JSON string:\n{json_str}\nNew reasoner:\n{show_reasoner(decoded_NAR)}')
except BaseException as e:
print(
f'Import failed! \nError: {e.with_traceback(None) if e else e}')
@@ -398,19 +398,19 @@ def load_JSON() -> None:
print(f'Read failed! \nError: {e.with_traceback(None) if e else e}')
-@expRegister('copy', 'pickle')
+@exp_register('copy', 'pickle')
def copy_pickle() -> None:
'''Save the reasoner data to a file'''
- nars = currentNARSInterface.reasoner
+ nars = current_NARS_interface.reasoner
# import module
import pickle as p
# start to save
file_name: str = input(
'Please enter the file name to save reasoner (default is "[current reasoner name].pickle):')
try:
- with open(f'{file_name if file_name else getCurrentReasonerName()}.pickle', 'wb') as file:
+ with open(f'{file_name if file_name else current_nar_name()}.pickle', 'wb') as file:
print(
- f'Trying to save the reasoner "{getCurrentReasonerName()}" to file "{file_name}.pickle"...')
+ f'Trying to save the reasoner "{current_nar_name()}" to file "{file_name}.pickle"...')
# pickle reasoner to file
p.dump(nars, file)
print(f'Reasoner data saved as "{file_name}.pickle"!')
@@ -419,7 +419,7 @@ def copy_pickle() -> None:
# TODO: Failed with error "Can't pickle local object 'Bag.__init__..map_priority'"
-@expRegister('load', 'unpickle')
+@exp_register('load', 'unpickle')
def load_pickle() -> None:
'''load the reasoner data into the interface'''
# import module
@@ -434,19 +434,19 @@ def load_pickle() -> None:
print(
f'Trying to load reasoner from "{file_path}"...')
# deserialize from pickle file
- decodedNAR: Reasoner = p.load(file)
+ decoded_NAR: Reasoner = p.load(file)
try:
# accept the reasoner with a new interface
- interfaceName: str = input(
+ interface_name: str = input(
'Please enter a new interface name: ')
# create interface
- interface: NARSInterface = NARSInterface(NARS=decodedNAR)
- reasoners[interfaceName] = interface # directly add
- reasonerGoto(interfaceName) # goto
+ interface: NARSInterface = NARSInterface(NARS=decoded_NAR)
+ reasoners[interface_name] = interface # directly add
+ reasoner_goto(interface_name) # goto
print(
- f"Import a reasoner named {interfaceName}, silent {'on' if interface.silentOutput else 'off'}.")
+ f"Import a reasoner named {interface_name}, silent {'on' if interface.silent_output else 'off'}.")
print(
- f'New reasoner:\n{infReasoner(decodedNAR)}')
+ f'New reasoner:\n{show_reasoner(decoded_NAR)}')
except BaseException as e:
print(
f'Import failed! \nError: {e.with_traceback(None) if e else e}')
@@ -457,19 +457,19 @@ def load_pickle() -> None:
print(f'Read failed! \nError: {e.with_traceback(None) if e else e}')
-def _cmdExperiment(cmd: str):
+def _cmd_experiment(cmd: str):
'''Cmd experiment entry'''
- nars = currentNARSInterface.reasoner # current NARS reasoner
+ nars = current_NARS_interface.reasoner # current NARS reasoner
# [2023-09-22 16:34:55] Now reuse the multi-patch to run cmd respectfully
- autoExecuteCmdByName(cmd, [], EXPERIMENTAL_CMDS)
+ auto_execute_cmd_by_name(cmd, [], EXPERIMENTAL_CMDS)
# Main
if __name__ == '__main__':
while 1:
# enter preset format prompt "IN"
- printOutput(PrintType.COMMENT, '',
- comment_title='Input', end='') # force hint
+ print_output(PrintType.COMMENT, '',
+ comment_title='Input', end='') # force hint
# get input
inp: str = input()
@@ -481,15 +481,15 @@ def _cmdExperiment(cmd: str):
elif inp[0] == '\\': # Gives the current interface library information
cmd: str = inp[1:]
if not cmd:
- printInf()
+ show_information()
else:
- _cmdExperiment(cmd=cmd)
+ _cmd_experiment(cmd=cmd)
continue
# execute input
if 1:
pass
- execInput(inp=inp)
+ execute_input(inp=inp)
try:
pass
except BaseException as e:
diff --git a/pynars/ConsolePlus.py b/pynars/ConsolePlus.py
index ed898ed..cf7a63b 100644
--- a/pynars/ConsolePlus.py
+++ b/pynars/ConsolePlus.py
@@ -1,20 +1,22 @@
+from typing import List
import functools
import re
-from pynars.Interface import NAL_GrammarParse
+from pynars.Interface import narsese_parse_safe
from pynars.Interface import NARSInterface
from pynars.Interface import NARSOutput
from pynars.Interface import PrintType
from pynars.Interface import Reasoner
-from pynars.Interface import printOut
-printOutput = printOut
+from pynars.Interface import print_out_origin
+print_output = print_out_origin
## Cmd system ##
# Preset cmd functions & decorators #
-def checkExcept(handleFunc=None, formattedMessage=None): # -> function
+
+def check_except(handler=None, formatted_message=None): # -> function
'''Returns a decorator that handles the error/alarm in case of an error and returns a custom message'''
def decorator(func):
def wrapper(*args, **kwargs):
@@ -22,61 +24,61 @@ def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result
except BaseException as e:
- if handleFunc:
+ if handler:
# Return handled error (only one parameter e)
- return handleFunc(e)
- print((formattedMessage if formattedMessage else '%s') %
+ return handler(e)
+ print((formatted_message if formatted_message else '%s') %
str(e.with_traceback(None) if e else repr(e))
)
return wrapper
return decorator
-def prefixBrowse(toBrowse: list[str], *keywords: list[str]) -> list[str]:
+def prefix_browse(to_browse: list[str], *keywords: list[str]) -> list[str]:
'''Matches the content against the string prefix'''
return [string # returns cmd names
# find matching cmds by: do not repeat
- for string in toBrowse
+ for string in to_browse
# match the list of all cmds, as long as they match the search results - not necessarily in order
if any(
string.startswith(prefix)
for prefix in keywords)]
-def prefixCmdBrowse(cmdDict: dict[tuple:tuple], *keywords: list[str]) -> list[tuple[str]]:
+def prefix_cmd_browse(cmd_dict: dict[tuple:tuple], *keywords: list[str]) -> list[tuple[str]]:
'''Matches the content against the string prefix'''
- return [aliasIndices # returns cmd names
+ return [alias_indices # returns cmd names
# find matching cmds by: do not repeat
- for aliasIndices in cmdDict
+ for alias_indices in cmd_dict
if any(
any(
- aliasIndex.startswith(keyword)
- for aliasIndex in aliasIndices)
+ alias_index.startswith(keyword)
+ for alias_index in alias_indices)
for keyword in keywords)] # match the list of all cmds, as long as they match the search results - not necessarily in order
-def quickConvertCmdTypes(inp: list[str], type_N_default: list[tuple[type, any]]) -> list[str]:
+def quick_convert_cmd_types(inp: list[str], type_N_default: list[tuple[type, any]]) -> list[str]:
'''Constructs the parameter set of the final input cmd handler by specifying the type-default parameter list, combined with the input parameter list (using positional parameters)'''
if type_N_default:
result: list[any] = []
lp = len(inp)
for index in range(len(type_N_default)): # if has default values
- paramType, defaultValue = type_N_default[index]
+ param_type, default_value = type_N_default[index]
# if input not provided, uses default values
if index >= lp:
- result.append(defaultValue)
+ result.append(default_value)
continue
# If the type is None, return itself and all subsequent arguments (compatible with any long arguments).
- if not paramType:
+ if not param_type:
result.extend(inp[index:])
continue
arg: str = inp[index]
try: # Use the types defined here to convert the string parameters
- result.append(paramType(arg))
+ result.append(param_type(arg))
except: # error -> use default value
- result.append(defaultValue)
+ result.append(default_value)
print(
- f'Parsing error! Default values "{defaultValue}" have been used.')
+ f'Parsing error! Default values "{default_value}" have been used.')
return result
else: # If not required (may be a "no input/only str array" case)
return inp
@@ -89,16 +91,16 @@ def quickConvertCmdTypes(inp: list[str], type_N_default: list[tuple[type, any]])
2. Provide macro command function, allowing users to customize a set of commands and package them as macros, easy to repeat execution
The main functions of each function, and their respective types and roles of parameters and outputs:
-1. waitAns try to get the result: try to capture the output of the specified type, and stop when it appears
+1. wait_ans try to get the result: try to capture the output of the specified type, and stop when it appears
- Parameter: paras (list[str]), which contains the output type, maximum tolerance, and interval cmd
- Output: list[NARSOutput], captured output of the specified type
-2. toggleSilent switches silent mode: Switches the silent mode of the cmd, generally blocking NARSOutput information
+2. toggle_silent switches silent mode: Switches the silent mode of the cmd, generally blocking NARSOutput information
- Parameter: args (list[str]). No parameter is required
- The output is None
3. readfile Read files: Call API to read files
- Parameter: args (list[str]), which contains the file path
- The output is None
-4. printHistory Output history: Output user input history
+4. print_history Output history: Output user input history
- Parameter: args (list[str]), placeholder
- The output is None
5. exec execution command: Directly invoke Python's built-in exec command to execute a single line of code
@@ -115,34 +117,34 @@ def quickConvertCmdTypes(inp: list[str], type_N_default: list[tuple[type, any]])
1. PRE_CMD_ dict command index (dict) : Stores dictionaries of preset command functions. The key is the command name and the value is the corresponding function
# Main dependencies between functions:
-1. waitAns attempt to obtain results relying on the NAL_GrammarParse.NARS statement input
-2. toggleSilent switching silent mode depends on NAL_GrammarParse. Silent output and outPrint direct output
+1. wait_ans attempt to obtain results relying on the NAL_GrammarParse.NARS statement input
+2. toggle_silent switching silent mode depends on NAL_GrammarParse. Silent output and out_print direct output
3. readfile reads files dependent on NAL_GrammarParse.exec to run files
-4. printHistory output history depends on inputHistory input history and NAL_GrammarParse.cmdHistory cmd history
+4. print_history output history depends on input_history input history and NAL_GrammarParse.cmdHistory cmd history
5. The exec command depends on Python's built-in exec command
-6. parse toggle shorthand escape depends on parseNeedSlash escape requires slash and outPrint output directly
-7. The help help depends on the PRE_CMD_ preset cmd index and the helpDoc single cmd
+6. parse toggle shorthand escape depends on parse_needSlash escape requires slash and out_print output directly
+7. The help help depends on the PRE_CMD_PRESET cmd index and the helpDoc single cmd
'''
PRESET_CMDS: dict[tuple:tuple] = {}
-def cmdRegister(cmdName: str | tuple[str], *type_N_default: list[tuple[type, any]]):
+def cmd_register(cmd_name: str | tuple[str], *type_N_default: list[tuple[type, any]]):
'''Decorator: Used to encapsulate cmds
Automatically register cmds at function definition time through the specified Type - Default parameter list
! Encapsulated function becomes a "callable object"
TODO Maybe can generalize cmd matching: return a function that can determine whether the "cmd name" matches; If it is a string, it is automatically encapsulated
- if isinstance(cmdName,str):
- cmdName = lambda cmdName: cmdName == cmdName
+ if isinstance(cmd_name,str):
+ cmd_name = lambda cmd_name: cmd_name == cmd_name
'''
# the cmd name can be multiple aliases, and only one time bracket can be left unwritten
- if isinstance(cmdName, str):
- cmdName = (cmdName,) # automatically converts to tuples
+ if isinstance(cmd_name, str):
+ cmd_name = (cmd_name,) # automatically converts to tuples
def decorator(func):
# register
global PRESET_CMDS
- PRESET_CMDS[cmdName] = (func, type_N_default, cmdName)
+ PRESET_CMDS[cmd_name] = (func, type_N_default, cmd_name)
'''
Core format & Structure: {Name: (handler function, ordinal and default list)}
! Tuples can be used as indexes: fixed type
@@ -163,134 +165,135 @@ def decorated(*args, **kwargs):
return decorator
-@cmdRegister(('waitans', 'wait-answer', 'w-answer'), (str, 'ANSWER'), (int, 100), (None, '1'))
-def waitAnswer(outType: str, maxListens: int, *cmdInInterval: str) -> list[NARSOutput]:
+@cmd_register(('waitans', 'wait-answer', 'w-answer'), (str, 'ANSWER'), (int, 100), (None, '1'))
+def wait_answer(out_type: str, max_listens: int, *cmd_in_interval: str) -> list[NARSOutput]:
'''Format: waitans [Output type = ANSWER] [Maximum tolerance = 100] [Interval cmd = '1']
Attempts to capture output of a specified type and stops when it appears'''
# Parameter preprocessing: Concatenates cmds separated by Spaces
- cmdInInterval: str = ' '.join(cmdInInterval)
- outType = PrintType.__getattribute__(PrintType, outType)
+ cmd_in_interval: str = ' '.join(cmd_in_interval)
+ out_type = PrintType.__getattribute__(PrintType, out_type)
outs: list[NARSOutput]
- while maxListens < 0 or (maxListens := maxListens-1):
+ while max_listens < 0 or (max_listens := max_listens-1):
# Loop execute interval cmd (default is wait statement)
- outs = currentNARSInterface.inputNAL(cmdInInterval)
+ outs = current_NARS_interface.input_narsese(cmd_in_interval)
for out in outs:
- if out and out.type == outType:
- currentNARSInterface.printOutput(
+ if out and out.type == out_type:
+ current_NARS_interface.print_output(
PrintType.INFO, f'Answer "{out.content}" is caught!')
return out # catch once
-@cmdRegister(('waitres', 'wait-result', 'w-result'), (int, 100), (str, '1'), (None, ''))
-def waitResult(maxListens: int, cmdInInterval: str, *targetSentence: list[str]) -> list[NARSOutput]:
+@cmd_register(('waitres', 'wait-result', 'w-result'), (int, 100), (str, '1'), (None, ''))
+def wait_result(max_listens: int, cmd_in_interval: str, *target_sentences: list[str]) -> list[NARSOutput]:
'''Format: waitres [Maximum tolerance = 100] [Interval cmd = '1'] [sentences...]
Attempts to intercept output that matches the specified sentences (same NAL format) and stops when it appears'''
from pynars.Narsese import parser
# Parameter preprocessing ' '.join(str target statement)
# handles subsequent cases where whitespace is split
# (the change in the number of whitespace does not affect parsing for the time being)
- targetSentence: str = specialGrammarParse(' '.join(targetSentence))
+ target_sentences: str = special_narsese_parse(' '.join(target_sentences))
# Using special syntax +NAL parser, reconvert to NAL standard format
- targetSentence: str = parser.parse(targetSentence).sentence.repr()
+ target_sentences: str = parser.parse(target_sentences).sentence.repr()
# starting wait
outs: list[NARSOutput]
- while maxListens < 0 or (maxListens := maxListens-1):
+ while max_listens < 0 or (max_listens := max_listens-1):
# Loop execute interval cmd (default is wait statement)
- outs = currentNARSInterface.inputNAL(cmdInInterval)
+ outs = current_NARS_interface.input_narsese(cmd_in_interval)
for out in outs:
# compare with the statement's repr, 'task.sentence.repr()'
- if out and out.content == targetSentence:
- currentNARSInterface.printOutput(
- PrintType.INFO, f'Target sentence "{targetSentence}" is caught!')
+ if out and out.content == target_sentences:
+ current_NARS_interface.print_output(
+ PrintType.INFO, f'Target sentence "{target_sentences}" is caught!')
return out # caught once
- currentNARSInterface.printOutput(
- PrintType.INFO, f'Target sentence "{targetSentence}" is not caught!')
+ current_NARS_interface.print_output(
+ PrintType.INFO, f'Target sentence "{target_sentences}" is not caught!')
-@cmdRegister(('toggle-silent', 'silent'))
-def toggleSilent() -> None:
+@cmd_register(('toggle-silent', 'silent'))
+def toggle_silent() -> None:
'''Switching the silent mode of the cmd generally prevents NARSOutput messages'''
- currentNARSInterface.silentOutput = not currentNARSInterface.silentOutput
- currentNARSInterface.printOutput(
+ current_NARS_interface.silent_output = not current_NARS_interface.silent_output
+ current_NARS_interface.print_output(
type=PrintType.INFO, content=f'''Silent output {
"opened"
- if currentNARSInterface.silentOutput
+ if current_NARS_interface.silent_output
else "closed"
}.''')
-@cmdRegister(('toggle-color', 'color'))
-def toggleColor() -> None:
+@cmd_register(('toggle-color', 'color'))
+def toggle_color() -> None:
'''Toggle the color display of cmds (for terminals that do not support custom foreground/background colors)'''
- NARSInterface.showColor = not currentNARSInterface.showColor
- currentNARSInterface.printOutput(
+ NARSInterface.show_color = not current_NARS_interface.show_color
+ current_NARS_interface.print_output(
type=PrintType.INFO, content=f'''Color showing {
"opened"
- if currentNARSInterface.showColor
+ if current_NARS_interface.show_color
else "closed"
}.''')
-@cmdRegister('readfile', 'read-file')
-def readfile(*args: list[str]) -> None:
+@cmd_register('readfile', 'read-file')
+def read_file(*args: list[str]) -> None:
'''Format: readfile [... file path]
Call API to read file'''
for path in args:
- currentNARSInterface.executeFile(path)
+ current_NARS_interface.execute_file(path)
-@cmdRegister('history')
-def printHistory(*args: list[str]) -> None:
+@cmd_register('history')
+def print_history(*args: list[str]) -> None:
'''Format: history [... placeholder]
Output the user's input history
Default: The Narsese seen at the bottom of the system, not the actual input
User actual input cmd: input any parameters can be obtained'''
- global _inputHistory
- print('\n'.join(_inputHistory if args else currentNARSInterface.inputHistory))
+ global _input_history
+ print('\n'.join(_input_history if args else current_NARS_interface.input_history))
-@cmdRegister(('execute', 'exec'))
-def execCode(*args: list[str]) -> None:
+@cmd_register(('execute', 'exec'))
+def exec_code(*args: list[str]) -> None:
'''Format: exec
Directly invoke Python's built-in exec cmd to execute a single line of code'''
exec(' '.join(args))
-@cmdRegister(('execute', 'exec'))
-def execCode(*args: list[str]) -> None:
+@cmd_register(('evaluate', 'eval'))
+def eval_code(*args: list[str]) -> None:
'''Format: eval
Directly invoke Python's built-in eval cmd to evaluate a single line of code'''
print(f'eval result: {eval(" ".join(args))}')
-@cmdRegister(('simplify-parse', 'parse'))
-def toggleSimplifyParse() -> None:
+@cmd_register(('simplify-parse', 'parse'))
+def toggle_simplify_parse() -> None:
'''Toggle the "automatic shorthand parsing" function of the cmd (enabled by default),
If so, the Narsese input are automatically parsed in a simplified format'''
- global _parseNeedSlash
- _parseNeedSlash = not _parseNeedSlash
+ global _parse_need_slash
+ _parse_need_slash = not _parse_need_slash
print(
- f'Narsese automatic analytic simplification {"closed" if _parseNeedSlash else "opened"}.')
+ f'Narsese automatic analytic simplification {"closed" if _parse_need_slash else "opened"}.')
-@cmdRegister('help')
-def help(*keywords: list[str], searchIn: dict[tuple:tuple] = PRESET_CMDS) -> None:
+@cmd_register('help')
+def help(*keywords: list[str], search_in: dict[tuple:tuple] = PRESET_CMDS) -> None:
'''Format: help [... specific cmd]
Display this help document, or assist in retrieving help for additional cmds'''
# Core idea: Empty prefix = all cmds
keywords = keywords if keywords else ['']
# find a matching cmd name
- cmdNameAliases: list[tuple(str)] = prefixCmdBrowse(searchIn, *keywords)
+ cmd_name_aliases: list[tuple(str)] = prefix_cmd_browse(
+ search_in, *keywords)
# display "matching cmds" as follows
- if cmdNameAliases:
+ if cmd_name_aliases:
# match the list of all cmds, as long as they match the search results - not necessarily in order
- for cmdNameAlias in cmdNameAliases:
+ for cmd_name_alias in cmd_name_aliases:
# Structure: {Name: (handler, ordinal and default list)}
- cmdFunction = searchIn[cmdNameAlias][0]
+ cmd_function = search_in[cmd_name_alias][0]
print(
- f'''<{"/".join(cmdNameAlias)}>: {cmdFunction.__name__}\n{
- cmdFunction.__doc__
- if cmdFunction.__doc__
+ f'''<{"/".join(cmd_name_alias)}>: {cmd_function.__name__}\n{
+ cmd_function.__doc__
+ if cmd_function.__doc__
else "!!! This cmd don't have any description !!!"
}\n''')
return
@@ -305,141 +308,141 @@ def help(*keywords: list[str], searchIn: dict[tuple:tuple] = PRESET_CMDS) -> Non
A macro is a pre-defined set of cmds that can be executed with a simple macro name
# The main functions of each function, and their respective types and roles of parameters and outputs:
-# 1. macroDef Define macrodef: Define a macro that contains a set of predefined cmds
+# 1. macro_def Define macros: Define a macro that contains a set of predefined cmds
# - Parameter: args (list[str]), which contains the macro name and the number of cmds
# - Output: None
-# 2. macroQuery Query macros: Query defined macros and display their internal commands
+# 2. macro_query Query macros: Query defined macros and display their internal commands
# - Argument: args (list[str]), which contains the macro name
# - Output: None
-# 3. macroExec executes macros by name: Executes macros by name
+# 3. macro_exec executes macros by name: Executes macros by name
# - Argument: args (list[str]), which contains the macro name
# - Output: None
-# 4. macroRepeat: Repeat the execution of macros by name and number
+# 4. macro_repeat: Repeat the execution of macros by name and number
# - Parameter: args (list[str]), which contains the macro name and the number of executions
# - Output: None
# Externally defined variable types, meanings and relationships:
-# 1.storedMacros Stored macros (dict) : Stores defined macros. The key is the name of the macro, and the value is the corresponding cmd list
+# 1.stored_macros Stored macros (dict) : Stores defined macros. The key is the name of the macro, and the value is the corresponding cmd list
# Main dependencies between functions:
-# 1. macroDef defines macros that rely on execInput to execute input
-# 2. macroQuery query macros rely on show to display individual macros
-# 3. macroExec executes macros on a per-macro basis depending on execMacroSin
-# 4. macroRepeat execution of macros depends on execMacroSin to execute a single macro
-# 5.help The help depends on a single helpDoc cmd
+# 1. macro_def defines macros that rely on exec_input to execute input
+# 2. macro_query query macros rely on show to display individual macros
+# 3. macro_exec executes macros on a per-macro basis depending on exec_macro_sin
+# 4. macro_repeat execution of macros depends on exec_macro_sin to execute a single macro
+# 5.help The help depends on a single help_doc cmd
# 6. readfile reads files dependent on NAL_GrammarParse.executeFile
-# 7. ToggleSilent switch silent mode depends on the NAL_GrammarParse. SilentOutput
-# 8.printHistory output history depends on inputHistory input history and NAL_GrammarParse.cmdHistory cmd history
+# 7. Toggle_silent switch silent mode depends on the NAL_GrammarParse. Silent_output
+# 8.print_history output history depends on input_history input history and NAL_GrammarParse.cmdHistory cmd history
# 9.exec exec relies on Python's built-in exec directive
-parse toggle shorthand escape depends on parseNeedSlash escape requires slash
-# 11. The helpDoc individual cmd depends on the index of PRESET_CMDS
+parse toggle shorthand escape depends on parse_need_slash escape requires slash
+# 11. The help_doc individual cmd depends on the index of PRESET_CMDS
'''
-storedMacros: dict[str:list[str]] = {}
+stored_macros: dict[str:list[str]] = {}
-@cmdRegister(('macro-def', 'm-def'))
-def macroDef(name: str, numCmds: int) -> None:
+@cmd_register(('macro-def', 'm-def'))
+def macro_def(name: str, num_cmds: int) -> None:
'''Format: macro-def < macro name > < Number of cmds >
According to the number of subsequent input cmds,
input a specified line of cmds, you can define an "cmd series" i.e. macro'''
# input
- cmdList: list[str]
- if numCmds: # limited cmd count
- cmdList = [
+ cmd_list: list[str]
+ if num_cmds: # limited cmd count
+ cmd_list = [
input(f'Please input cmd #{i+1}: ')
- for i in range(numCmds)]
+ for i in range(num_cmds)]
else: # unlimited cmd count
- cmdList = []
- while (cmd := input(f'Please input cmd #{len(cmdList)+1}: ')):
- cmdList.append(cmd)
- storedMacros[name] = cmdList
+ cmd_list = []
+ while (cmd := input(f'Please input cmd #{len(cmd_list)+1}: ')):
+ cmd_list.append(cmd)
+ stored_macros[name] = cmd_list
# notify
- print(f'Macro {name} with {len(cmdList)}cmds input completed!')
- print("The following is cmds in it:\n"+'\n'.join(cmdList))
+ print(f'Macro {name} with {len(cmd_list)}cmds input completed!')
+ print("The following is cmds in it:\n"+'\n'.join(cmd_list))
-def showMacro(name: str): return f'Macro {name}: \n' + \
- '\n'.join(storedMacros[name])
+def macro_show(name: str): return f'Macro {name}: \n' + \
+ '\n'.join(stored_macros[name])
-@cmdRegister(('macro-query', 'm-query'))
-def macroQuery(*args: list[str]) -> None:
+@cmd_register(('macro-query', 'm-query'))
+def macro_query(*args: list[str]) -> None:
'''Format: macro-query [... macro name]
With parameters: Find macros by name and display their internal commands (the number can be stacked indefinitely)
No arguments: Lists all defined macros and displays their internal commands'''
if args: # find by names
for name in args:
- if name in storedMacros:
- showMacro(name=name)
+ if name in stored_macros:
+ macro_show(name=name)
else:
print(f'Unknown macro name "{name}"')
else: # lists all defined macros
- for name in storedMacros:
- showMacro(name=name)
+ for name in stored_macros:
+ macro_show(name=name)
-def macroExec1(name: str) -> None:
+def macro_exec1(name: str) -> None:
'''Execute 1 macro'''
- cmds: list[str] = storedMacros[name]
+ cmds: list[str] = stored_macros[name]
for cmd in cmds:
- execInput(cmd)
+ execute_input(cmd)
-@cmdRegister(('macro-exec', 'm-exec'))
-def macroExec(*args: list[str]) -> None:
+@cmd_register(('macro-exec', 'm-exec'))
+def macro_exec(*args: list[str]) -> None:
'''Format: macro-exec [... macro name]
Execute macros by name (unlimited number can be stacked)
If empty, execute macro "" (empty string)'''
args = args if args else ['']
for name in args:
- macroExec1(name=name)
+ macro_exec1(name=name)
-@cmdRegister(('macro-repeat', 'm-repeat'))
-def macroRepeat(name: str, numExecutes: int) -> None:
+@cmd_register(('macro-repeat', 'm-repeat'))
+def macro_repeat(name: str, num_executes: int) -> None:
'''Format: macro-repeat < macro name > < execution times >
Execute macros as "name + number" (number can be stacked indefinitely)'''
- for _ in range(numExecutes):
- macroExec1(name=name)
+ for _ in range(num_executes):
+ macro_exec1(name=name)
# Reasoner management #
-currentNARSInterface: NARSInterface = NARSInterface.constructInterface(
+current_NARS_interface: NARSInterface = NARSInterface.construct_interface(
137,
500, 500,
silent=False)
-reasoners: dict[str:Reasoner] = {'initial': currentNARSInterface}
+reasoners: dict[str:Reasoner] = {'initial': current_NARS_interface}
-def getCurrentReasonerName() -> str:
- global currentNARSInterface
+def current_nar_name() -> str:
+ global current_NARS_interface
for name in reasoners:
- if reasoners[name] is currentNARSInterface:
+ if reasoners[name] is current_NARS_interface:
return name
return None
-@cmdRegister(('reasoner-current', 'r-current'))
-def reasonerCurrent() -> None:
+@cmd_register(('reasoner-current', 'r-current'))
+def reasoner_current() -> None:
'''Gets the name of the current reasoner'''
- name = getCurrentReasonerName()
+ name = current_nar_name()
if name != None:
print(f'The name of the current reasoner is "{name}".')
-@cmdRegister(('reasoner-list', 'r-list'))
-def reasonerList(*keywords: list[str]) -> None:
+@cmd_register(('reasoner-list', 'r-list'))
+def reasoner_list(*keywords: list[str]) -> None:
'''Format: reasoner-list [... specific cmd]
Enumerate existing reasoners; It can be retrieved with parameters'''
keywords = keywords if keywords else ['']
# Search for a matching interface name
- reasonerNames: list[str] = prefixBrowse(reasoners, *keywords)
+ reasoner_names: list[str] = prefix_browse(reasoners, *keywords)
# Displays information about "matched interface"
- if reasonerNames:
- for name in reasonerNames: # match the list of all cmds, as long as they match the search results - not necessarily in order
+ if reasoner_names:
+ for name in reasoner_names: # match the list of all cmds, as long as they match the search results - not necessarily in order
interface: NARSInterface = reasoners[name]
information: str = '\n\t'+"\n\t".join(f"{name}: {repr(inf)}" for name, inf in [
('Memory', interface.reasoner.memory),
@@ -454,49 +457,49 @@ def reasonerList(*keywords: list[str]) -> None:
print(f'No reasoner is browsed by "{", ".join(keywords)}"')
-@cmdRegister(('reasoner-new', 'r-new'),
- (str, 'unnamed'),
- (int, 100),
- (int, 100),
- (bool, False),)
-def reasonerNew(name: str, n_memory: int = 100, capacity: int = 100, silent: bool = False) -> NARSInterface:
+@cmd_register(('reasoner-new', 'r-new'),
+ (str, 'unnamed'),
+ (int, 100),
+ (int, 100),
+ (bool, False),)
+def reasoner_new(name: str, n_memory: int = 100, capacity: int = 100, silent: bool = False) -> NARSInterface:
'''Format: reasoner-new < Name > [Memory capacity] [buffer size] [Silent output]
Create a new reasoner and go to the existing reasoner if it exists
If an empty name is encountered, the default name is "unnamed"'''
- global currentNARSInterface
+ global current_NARS_interface
if name in reasoners:
print(
f'The reasoner exists! Now automatically go to the reasoner "{name}"!')
- return (currentNARSInterface := reasoners[name])
+ return (current_NARS_interface := reasoners[name])
- reasoners[name] = (currentNARSInterface := NARSInterface.constructInterface(
+ reasoners[name] = (current_NARS_interface := NARSInterface.construct_interface(
memory=n_memory,
capacity=capacity,
silent=silent
))
print(
f'A reasoner named "{name}" with memory capacity {n_memory}, buffer capacity {capacity}, silent output {" on " if silent else" off "} has been created!')
- return currentNARSInterface
+ return current_NARS_interface
-@cmdRegister(('reasoner-goto', 'r-goto'), (str, 'initial'))
-def reasonerGoto(name: str) -> NARSInterface:
+@cmd_register(('reasoner-goto', 'r-goto'), (str, 'initial'))
+def reasoner_goto(name: str) -> NARSInterface:
'''Format: reasoner-goto < name >
Transfers the current reasoner of the program to the specified reasoner'''
- global currentNARSInterface
+ global current_NARS_interface
if name in reasoners:
print(f"Gone to reasoner named '{name}'!")
- return (currentNARSInterface := reasoners[name])
+ return (current_NARS_interface := reasoners[name])
print(f"There is no reasoner named '{name}'!")
-@cmdRegister(('reasoner-delete', 'r-delete'))
-def reasonerDelete(name: str) -> None:
+@cmd_register(('reasoner-delete', 'r-delete'))
+def reasoner_delete(name: str) -> None:
'''Format: reasoner-select < name >
Deletes the reasoner with the specified name, but cannot delete the current reasoner'''
- global currentNARSInterface
+ global current_NARS_interface
if name in reasoners:
- if reasoners[name] is currentNARSInterface:
+ if reasoners[name] is current_NARS_interface:
print(
f'Unable to delete reasoner "{name}", it is the current reasoner!')
return
@@ -506,18 +509,18 @@ def reasonerDelete(name: str) -> None:
print(f'There is no reasoner named "{name}"!')
-@cmdRegister(('seed-set', 'seed'), (int, 137))
-def randomSeed(seed: int) -> None:
+@cmd_register(('seed-set', 'seed'), (int, 137))
+def random_seed(seed: int) -> None:
'''Format: seed [seed: integer]
Set the random seed of the random number generator random and numpy.random'''
- NARSInterface.changeRandomSeed(seed=seed)
+ NARSInterface.change_random_seed(seed=seed)
# Total index and other variables #
-_parseNeedSlash: bool = False
+_parse_need_slash: bool = False
-_inputHistory: list[str] = []
+_input_history: list[str] = []
# Special grammar parser #
@@ -525,7 +528,7 @@ def randomSeed(seed: int) -> None:
PUNCT_INDEX: re.Pattern = re.compile(r'([^0-9%]\.)|[\?\!\@]')
-def specialGrammarParse(inp: str) -> str:
+def special_narsese_parse(inp: str) -> str:
'''
Additional syntax parsing for non-cmd input
Main functions:
@@ -559,7 +562,7 @@ def specialGrammarParse(inp: str) -> str:
# First "normal parsing NAL", then do special syntax parsing, special language → Standard Naz
# If can't "normal parsing", enter the following "special syntax"
- if NAL_GrammarParse(inp):
+ if narsese_parse_safe(inp):
return inp
# complete the outermost parenthesis of the statement
@@ -573,7 +576,7 @@ def specialGrammarParse(inp: str) -> str:
return inp
-def execInput(inp: str, *otherInput: list[str]) -> None:
+def execute_input(inp: str, *other_input: list[str]) -> None:
'''
Main functions:
This code is mainly used to process the user input cmds and NAS statements, and perform the corresponding operations according to the input content.
@@ -581,13 +584,13 @@ def execInput(inp: str, *otherInput: list[str]) -> None:
The types, meanings and relationships of each variable:
- in "input" (str): A string entered by the user, which may be an cmd or a Nax statement.
- cmdHistory "Cmd history" (list[str]): Stores the cmd history entered by the user.
- - parseNeedSlash "Escape requires slash" (bool): Indicates whether slashes are required for short escape.
+ - parse_need_slash "Escape requires slash" (bool): Indicates whether slashes are required for short escape.
- PRESET_CMDS (dict): Index list of preset cmds, used to execute functions based on cmd names.
Main operation process:
1. Wait for user input.
2. Check whether the input is an cmd. If yes, execute the corresponding preset cmd function.
- 3. If the input is not a command, determine whether special parsing is required according to the slash required for parseNeedSlash escape.
+ 3. If the input is not a command, determine whether special parsing is required according to the slash required for parse_need_slash escape.
4. Inject parsed NAS statements into the NARS interface.
Possible exceptions:
@@ -596,64 +599,64 @@ def execInput(inp: str, *otherInput: list[str]) -> None:
# multiline cmd disassembly
- if len(otherInput) > 0:
- execInput(inp=inp)
- for i in otherInput:
- execInput(i)
+ if len(other_input) > 0:
+ execute_input(inp=inp)
+ for i in other_input:
+ execute_input(i)
return
# add to history
- _inputHistory.append(inp)
+ _input_history.append(inp)
# pre-jump cmd
if inp.startswith('/'):
# the first word is the cmd name, and the following are parameters
words: list[str] = inp[1:].split()
if words: # if not empty
- cmdName: str = words[0].lower() # case insensitive
- autoExecuteCmdByName(cmdName, words[1:])
+ cmd_name: str = words[0].lower() # case insensitive
+ auto_execute_cmd_by_name(cmd_name, words[1:])
return # If it's executed as a command, it won't execute as Narsese input
# Narsese parsing
- hasSlash = False # usage of backslashes: Enforce/disable "parse simplification"
- if not _parseNeedSlash or (hasSlash := inp.startswith('\\')):
- if hasSlash: # Remove the slash if there is a backslash
+ has_slash = False # usage of backslashes: Enforce/disable "parse simplification"
+ if not _parse_need_slash or (has_slash := inp.startswith('\\')):
+ if has_slash: # Remove the slash if there is a backslash
inp = inp[1:]
- inp = specialGrammarParse(inp=inp)
+ inp = special_narsese_parse(inp=inp)
# input NAL
- currentNARSInterface.inputNAL(inp)
+ current_NARS_interface.input_narsese(inp)
-def autoExecuteCmdByName(cmdName: str, words: list[str], cmdDict: dict[tuple:tuple] = PRESET_CMDS) -> bool:
+def auto_execute_cmd_by_name(cmd_name: str, params: list[str], cmd_dict: dict[tuple:tuple] = PRESET_CMDS) -> bool:
'''Execute cmd by name with autocompletion
returns: whether a cmd is chosen and executed successfully'''
# auto browse & complete
- nameAliasHints: list[tuple[str]] = prefixCmdBrowse(cmdDict, cmdName)
+ name_alias_hints: list[tuple[str]] = prefix_cmd_browse(cmd_dict, cmd_name)
# if it have a precise match, directly use it
- for i in range(len(nameAliasHints)):
- nameAliases = nameAliasHints[i]
- if any(nameAlias == cmdName for nameAlias in nameAliases):
- nameAliasHints = [nameAliases]
+ for i in range(len(name_alias_hints)):
+ name_aliases = name_alias_hints[i]
+ if any(name_alias == cmd_name for name_alias in name_aliases):
+ name_alias_hints = [name_aliases]
break
# Only option: Full match or auto complete
- if len(nameAliasHints) == 1:
+ if len(name_alias_hints) == 1:
# auto complete
- if not cmdName in nameAliasHints[0]:
+ if not cmd_name in name_alias_hints[0]:
print(
- f'Autocompleted cmd to "{"/".join(nameAliasHints[0])}".')
- nameAliasIndex = nameAliasHints[0]
+ f'Autocompleted cmd to "{"/".join(name_alias_hints[0])}".')
+ name_alias_index = name_alias_hints[0]
# Cmd execution: Automatically adjust the "parameter requirements" of specific cmds and intercept parameters
- cmdData = cmdDict[nameAliasIndex]
- cmdHandler = cmdData[0]
+ cmd_data = cmd_dict[name_alias_index]
+ cmd_handler = cmd_data[0]
type_N_default: list[tuple[type, any]] = (
- cmdData[1]
- if len(cmdData) > 1 else None)
- params: list = quickConvertCmdTypes(words[1:], type_N_default)
+ cmd_data[1]
+ if len(cmd_data) > 1 else None)
+ params: list = quick_convert_cmd_types(params, type_N_default)
try:
# in the form of positional arguments, to the appropriate handler. Structure: {Name: (handler, ordinal and default list)}
- cmdHandler(*params)
+ cmd_handler(*params)
return True
except BaseException as e:
print('Cmd execute failed: ',
@@ -661,9 +664,9 @@ def autoExecuteCmdByName(cmdName: str, words: list[str], cmdDict: dict[tuple:tup
return False
else:
hint = 'Are you looking for "' + \
- "\"|\"".join('/'.join(alias) for alias in nameAliasHints) + \
- '"?' if nameAliasHints else ''
- print(f'Unknown cmd {cmdName}. {hint}')
+ "\"|\"".join('/'.join(alias) for alias in name_alias_hints) + \
+ '"?' if name_alias_hints else ''
+ print(f'Unknown cmd {cmd_name}. {hint}')
return False
# @checkExcept error alarm (message formatted message =' Input execution failed: %s')
@@ -672,11 +675,11 @@ def autoExecuteCmdByName(cmdName: str, words: list[str], cmdDict: dict[tuple:tup
def __main__():
# enter preset format prompt "IN", not regards `silent`
- printOutput(PrintType.COMMENT, '', comment_title='Input', end='')
+ print_output(PrintType.COMMENT, '', comment_title='Input', end='')
# get & execute
inp: str = input()
- execInput(inp=inp)
+ execute_input(inp=inp)
## main program ##
diff --git a/pynars/Interface.py b/pynars/Interface.py
index e5c82cd..a471c12 100644
--- a/pynars/Interface.py
+++ b/pynars/Interface.py
@@ -8,7 +8,7 @@
import argparse # for cmdline
# pynars
-from pynars.utils.Print import print_out as printOut
+from pynars.utils.Print import print_out as print_out_origin
from pynars.NARS import Reasoner
from pynars.Narsese import Task
from pynars.utils.Print import PrintType
@@ -19,15 +19,7 @@
# utils #
-def NAL_Parse(narsese: str) -> None | Task:
- '''
- Responsible for calling the NAL parser to parse statements
- ! It might raise errors
- '''
- return NarseseParser.parse(narsese)
-
-
-def NAL_GrammarParse(narsese: str) -> None | Task:
+def narsese_parse_safe(narsese: str) -> None | Task:
'''
Responsible for calling the NAL parser to parse statements
@@ -40,7 +32,7 @@ def NAL_GrammarParse(narsese: str) -> None | Task:
2. Can not parse (error), return a null value (can be used to judge)
'''
try:
- return NAL_Parse(narsese=narsese)
+ return NarseseParser.parse(narsese=narsese)
except: # if errors, return `None` that can be identify
return None
@@ -52,7 +44,7 @@ class NARSOutput:
content: any
p: float
q: float
- commentTitle: str
+ comment_title: str
end: str
def __init__(self, type: PrintType, content, p: float = None, d: float = None, q: float = None, comment_title: str = None, end: str = None):
@@ -129,36 +121,37 @@ class NARSInterface:
# Print out interface static methods & class variables #
- _showColor: bool = True
+ _show_color: bool = True
# Try importing, prompt if no package is available and go to a more compatible path (less program dependency)
try:
- from sty import bg as _strBackGround, fg as _strForeGround # Import background class
+ # Import background class
+ from sty import bg as _str_back_ground, fg as _str_fore_ground
except:
# No color mode
- _showColor = None
+ _show_color = None
print('Unable to import color pack! Automatically switched to `No color mode` and locked!')
@property
- def showColor(self):
- return NARSInterface.showColor
+ def show_color(self):
+ return NARSInterface.show_color
- @showColor.setter
- def showColor(self, value: bool) -> bool | None:
+ @show_color.setter
+ def show_color(self, value: bool) -> bool | None:
# strictly identify None rather than implicit bool(None) == False
- if NARSInterface._showColor == None:
+ if NARSInterface._show_color == None:
return None # the color display cannot be enabled
- NARSInterface._showColor = value
- return NARSInterface._showColor
+ NARSInterface._show_color = value
+ return NARSInterface._show_color
- def floatRestrictStr(x):
+ def float_restrict_str(x):
'''0 to 1 floating point constraint'''
return (f'{round(x, 2):.2f}'
if isinstance(x, float) and 0 <= x <= 1
else ' ')
- def outMessageNoColor(type: PrintType, content,
- p: float = None, d: float = None, q: float = None,
- comment_title: str = None):
+ def out_message_no_color(type: PrintType, content,
+ p: float = None, d: float = None, q: float = None,
+ comment_title: str = None):
''''from pynars.utils.Print import out_print'''
# show_budget = True
# if isinstance(p, float) and isinstance(d, float) and isinstance(q, float):
@@ -166,24 +159,24 @@ def outMessageNoColor(type: PrintType, content,
# show_budget = False
# else:
# show_budget = False
- pStr: str = NARSInterface.floatRestrictStr(p)
- qStr: str = NARSInterface.floatRestrictStr(q)
- dStr: str = NARSInterface.floatRestrictStr(d)
+ p_str: str = NARSInterface.float_restrict_str(p)
+ q_str: str = NARSInterface.float_restrict_str(q)
+ d_str: str = NARSInterface.float_restrict_str(d)
if type:
# ! ↓ The value of this enumeration class comes with a foreground color
value: str = type.value[5:-1]
if type is PrintType.COMMENT and comment_title is not None:
return f'{comment_title}: {str(content)}'
elif type is PrintType.INFO:
- return f'|{pStr}|{dStr}|{qStr}| {value}「{str(content)}」'
+ return f'|{p_str}|{d_str}|{q_str}| {value}「{str(content)}」'
else:
- return f'|{pStr}|{dStr}|{qStr}| {value} | {str(content)}'
+ return f'|{p_str}|{d_str}|{q_str}| {value} | {str(content)}'
# modified colored output of Print.py
@staticmethod
- def outPrintNoColor(type: PrintType, content, p: float = None, d: float = None, q: float = None, comment_title: str = None, end: str = None):
+ def out_print_no_color(type: PrintType, content, p: float = None, d: float = None, q: float = None, comment_title: str = None, end: str = None):
print(
- NARSInterface.outMessageNoColor(
+ NARSInterface.out_message_no_color(
type=type, content=content,
p=p, d=d, q=q,
comment_title=comment_title),
@@ -191,14 +184,14 @@ def outPrintNoColor(type: PrintType, content, p: float = None, d: float = None,
def _is0to1Float(x): return isinstance(x, float) and 0 <= x <= 1
- def _bgEmbrace(
- str, bg): return f'{bg}{str}{NARSInterface._strBackGround.rs}'
+ def _bg_embrace(
+ str, bg): return f'{bg}{str}{NARSInterface._str_back_ground.rs}'
- def _fgEmbrace(
- str, fg): return f'{fg}{str}{NARSInterface._strForeGround.rs}'
+ def _fg_embrace(
+ str, fg): return f'{fg}{str}{NARSInterface._str_fore_ground.rs}'
@staticmethod
- def outMessageWithColor(type: PrintType, content, p: float = None, d: float = None, q: float = None, comment_title: str = None):
+ def out_message_with_color(type: PrintType, content, p: float = None, d: float = None, q: float = None, comment_title: str = None):
# show_budget = True
# if isinstance(p, float) and isinstance(d, float) and isinstance(q, float):
# if p<0 or p>1 or q<0 or q>1 or d<0 or d>1:
@@ -210,8 +203,8 @@ def outMessageWithColor(type: PrintType, content, p: float = None, d: float = No
Although the code has become simpler, the actual call has gone through more functions and calculations, but it has become less concise
'''
- bg, fg = NARSInterface._strBackGround, NARSInterface._strForeGround
- bge, fge = NARSInterface._bgEmbrace, NARSInterface._fgEmbrace
+ bg, fg = NARSInterface._str_back_ground, NARSInterface._str_fore_ground
+ bge, fge = NARSInterface._bg_embrace, NARSInterface._fg_embrace
if NARSInterface._is0to1Float(p):
bg1 = bg(min(255, int(255*p/2+10)), 10, 10)
@@ -244,12 +237,12 @@ def outMessageWithColor(type: PrintType, content, p: float = None, d: float = No
)
@staticmethod
- def printOutWithColor(type: PrintType, content, p: float = None, d: float = None, q: float = None, comment_title: str = None, end: str = None):
- print(NARSInterface.outMessageWithColor(
+ def print_out_with_color(type: PrintType, content, p: float = None, d: float = None, q: float = None, comment_title: str = None, end: str = None):
+ print(NARSInterface.out_message_with_color(
type=type, content=content, p=p, d=d, q=q, comment_title=comment_title), end=end)
@staticmethod
- def changeRandomSeed(seed: int) -> None:
+ def change_random_seed(seed: int) -> None:
'''[Taken from Console.py and improved] Set random and numpy.random random seeds (global)'''
# Set random seeds from random and numpy
'''from importlib import import_module # ! Temporary not use
@@ -261,14 +254,14 @@ def changeRandomSeed(seed: int) -> None:
if not 'numpy' in globals():
import numpy as np
np.random.seed(seed=seed)
- printOut(PrintType.COMMENT,
- f'Changing random seed={seed}...', comment_title='Setup')
+ print_out_origin(PrintType.COMMENT,
+ f'Changing random seed={seed}...', comment_title='Setup')
- @staticmethod
- def loadConfig(content: str) -> None:
- Config.loadFromStr(content=content)
+ # @staticmethod
+ # def load_config(content: str) -> None:
+ # Config.loadFromStr(content=content)
- silentOutput: bool = False
+ silent_output: bool = False
# reasoner
_NARS: Reasoner = None # ! internal
@@ -280,7 +273,7 @@ def reasoner(self) -> Reasoner:
# NARS constructor & initialization #
@staticmethod
- def constructInterface(seed=-1, memory=100, capacity=100, silent: bool = False):
+ def construct_interface(seed=-1, memory=100, capacity=100, silent: bool = False):
'''Construct the reasoner using specific construction parameters instead of having to construct the reasoner itself in each constructor'''
return NARSInterface(seed=seed,
NARS=Reasoner(
@@ -292,16 +285,16 @@ def __init__(self, seed=-1, NARS: reasoner = None, silent: bool = False) -> None
'''init the interface'''
# random seed
if seed > 0:
- NARSInterface.changeRandomSeed(seed)
+ NARSInterface.change_random_seed(seed)
# config
- self.silentOutput: bool = silent
+ self.silent_output: bool = silent
# reasoner
- self.printOutput(
+ self.print_output(
PrintType.COMMENT, f'{"Importing" if NARS else "Creating"} Reasoner...', comment_title='NARS')
self._NARS = NARS if NARS else Reasoner(100, 100)
- self.printOutput(
+ self.print_output(
PrintType.COMMENT, 'Run...', comment_title='NARS')
''' TODO?
Use a Python dictionary instead of "external file address" to input configuration to the reasoner
@@ -311,28 +304,28 @@ def __init__(self, seed=-1, NARS: reasoner = None, silent: bool = False) -> None
# Interface to the outer interface of the PyNARS part #
@staticmethod
- def directPrint(type: PrintType, content: any, p: float = None, d: float = None, q: float = None, comment_title: str = None, end: str = None) -> None:
+ def direct_print(type: PrintType, content: any, p: float = None, d: float = None, q: float = None, comment_title: str = None, end: str = None) -> None:
'''Direct print information by parameters'''
(
- NARSInterface.printOutWithColor
- if NARSInterface.showColor
- else NARSInterface.outPrintNoColor
+ NARSInterface.print_out_with_color
+ if NARSInterface.show_color
+ else NARSInterface.out_print_no_color
)(type=type, content=content, p=p, d=d, q=q, comment_title=comment_title, end=end)
- def printOutput(self, type: PrintType, content: any, p: float = None, d: float = None, q: float = None, comment_title: str = None, end: str = None) -> None:
+ def print_output(self, type: PrintType, content: any, p: float = None, d: float = None, q: float = None, comment_title: str = None, end: str = None) -> None:
# able to be silent
- if not self.silentOutput:
- NARSInterface.directPrint(
+ if not self.silent_output:
+ NARSInterface.direct_print(
type=type, content=content,
p=p, d=d, q=q,
comment_title=comment_title,
end=end)
- # _eventHandlers: list[function] = [] # ! error: name 'function' is not defined
- _eventHandlers: list = []
+ # _event_handlers: list[function] = [] # ! error: name 'function' is not defined
+ _event_handlers: list = []
@property # read only
- def eventHandlers(self):
+ def event_handlers(self):
'''Registry of event handlers
Standard format:
```
@@ -340,43 +333,43 @@ def handler(out: NARSOutput):
# your code
```
'''
- return self._eventHandlers
+ return self._event_handlers
- def _handleNARSOutput(self, out: NARSOutput):
+ def _handle_NARS_output(self, out: NARSOutput):
'''Internally traverses the event handler registry table, running its internal functions one by one'''
- for handler in self._eventHandlers:
+ for handler in self._event_handlers:
try:
handler(out)
except BaseException as e:
print(
f'Handler "{handler.__name__}" errors when deal NARS output "{out}": {e}')
- def inputNAL(self, lines: str) -> list[NARSOutput]:
+ def input_narsese(self, lines: str) -> list[NARSOutput]:
'''Interfacing with NARS: Injects input provided by an external program into NARS'''
- return self._handleLines(lines=lines)
+ return self._handle_lines(lines=lines)
- def executeFile(self, path: str | Path) -> None:
+ def execute_file(self, path: str | Path) -> None:
'''Handle files'''
# it's copied directly from Console.py
if path is not None:
path: Path = Path(path)
file_name = path.name
- self.printOutput(
+ self.print_output(
PrintType.COMMENT, f'Run file <{file_name}>.', comment_title='NARS')
with open(path, 'r') as f:
lines = f.read()
- self._handleLines(lines)
- self.printOutput(
+ self._handle_lines(lines)
+ self.print_output(
PrintType.COMMENT, 'Console.', comment_title='NARS')
# History & Memories #
- _inputHistory: list[str] = []
+ _input_history: list[str] = []
@property # readonly
- def inputHistory(self):
+ def input_history(self):
'''Records texts (statements) entered into the interface'''
- return self._inputHistory
+ return self._input_history
'''
# TODO: The `silent` cannot prevent printing the following lines
@@ -386,7 +379,7 @@ def inputHistory(self):
INFO : Done. Time-cost: 0.0009992122650146484s.
'''
- def _handleLines(self, lines: str) -> list[NARSOutput]:
+ def _handle_lines(self, lines: str) -> list[NARSOutput]:
'''
Process the input stream of statements, decompose it into multiple statements, and pass each statement to NARS for processing, and finally return the result list of NARS output.
@@ -403,7 +396,7 @@ def _handleLines(self, lines: str) -> list[NARSOutput]:
1. Decompose the input statement flow into multiple statements.
2. Go through each statement, call "processing statement" to pass the statement to NARS for processing, and add the processing result to the task list.
3. Traverse the task list, convert the task-related information into NARS output objects, and add them to the out output list.
- 4. Traverse the out output list, call `self.printOutput` to print the output, and call `self._handleNARSOutput` to broadcast the output.
+ 4. Traverse the out output list, call `self.print_output` to print the output, and call `self._handle_NARS_output` to broadcast the output.
5. Return to the out output list.
Possible exceptions:
@@ -418,32 +411,32 @@ def _handleLines(self, lines: str) -> list[NARSOutput]:
# start to handle
- taskList = []
+ task_list = []
for line in lines.split('\n'):
if len(line) == 0:
continue
- taskLine = self.run_line(reasoner=self._NARS, line=line)
- self._inputHistory.append(line)
- if taskLine is not None:
- taskList.extend(taskLine)
+ task_line = self.run_line(reasoner=self._NARS, line=line)
+ self._input_history.append(line)
+ if task_line is not None:
+ task_list.extend(task_line)
outs: list[NARSOutput] = []
- taskList: List[
+ task_list: List[
Tuple[
List[Task], Task, Task,
List[Task], Task,
Tuple[Task, Task]
]
]
- for taskLine in taskList:
+ for task_line in task_list:
tasks_derived, judgement_revised, goal_revised, answers_question, answers_quest,\
- (task_operation_return, task_executed) = taskLine
- for derivedTask in tasks_derived:
+ (task_operation_return, task_executed) = task_line
+ for derived_task in tasks_derived:
outs.append(
NARSOutput(
- PrintType.OUT, derivedTask.sentence.repr(), *derivedTask.budget)
+ PrintType.OUT, derived_task.sentence.repr(), *derived_task.budget)
)
if judgement_revised is not None:
@@ -467,10 +460,10 @@ def _handleLines(self, lines: str) -> list[NARSOutput]:
# * print & event patch
for out in outs:
if out:
- self.printOutput(type=out.type, content=out.content, p=out.p,
- d=out.d, q=out.q, comment_title=out.comment_title, end=out.end)
+ self.print_output(type=out.type, content=out.content, p=out.p,
+ d=out.d, q=out.q, comment_title=out.comment_title, end=out.end)
# broadcast outputs before return
- self._handleNARSOutput(out=out)
+ self._handle_NARS_output(out=out)
# return outputs
return outs
@@ -485,11 +478,11 @@ def run_line(self, reasoner: reasoner, line: str):
line = line[len("''outputMustContain('"):].rstrip("')\n") #
if len(line) == 0: # no any content
return
- if (check := NAL_GrammarParse(line)): # verify the input
- self.printOutput(
+ if (check := narsese_parse_safe(line)): # verify the input
+ self.print_output(
PrintType.INFO, f'OutputContains({check.sentence.repr()})')
else:
- self.printOutput(
+ self.print_output(
PrintType.ERROR, f'parse "{line}" failed!'
)
return
@@ -498,27 +491,27 @@ def run_line(self, reasoner: reasoner, line: str):
return None
# digit -> run cycle
elif line.isdigit():
- nCycles = int(line)
- self.printOutput(PrintType.INFO, f'Run {nCycles} cycles.')
- tasksInCycles: list[Task] = []
+ n_cycles = int(line)
+ self.print_output(PrintType.INFO, f'Run {n_cycles} cycles.')
+ tasks_in_cycles: list[Task] = []
# Get all export statements run during this period, deep copy for backup
- for _ in range(nCycles):
- tasksCaught = reasoner.cycle()
- tasksInCycles.append(deepcopy(tasksCaught))
- return tasksInCycles
+ for _ in range(n_cycles):
+ tasks_caught = reasoner.cycle()
+ tasks_in_cycles.append(deepcopy(tasks_caught))
+ return tasks_in_cycles
# narsese
else:
line = line.rstrip(' \n') # ignore spaces and newline
if 1:
success, task, _ = reasoner.input_narsese(line, go_cycle=False)
if success: # input success
- self.printOutput(
+ self.print_output(
PrintType.IN, task.sentence.repr(), *task.budget)
else: # input failed
- self.printOutput(
+ self.print_output(
PrintType.ERROR, f'Input "{line}" failed.')
- tasksCaught = reasoner.cycle() # run cycles
- return [deepcopy(tasksCaught)] # Returns a inferred statement
+ tasks_caught = reasoner.cycle() # run cycles
+ return [deepcopy(tasks_caught)] # Returns a inferred statement
def __main__():
@@ -531,19 +524,19 @@ def __main__():
filepath: Union[list, None] = args.filepath
filepath = filepath[0] if filepath else None
# setup NARS interface
- interface: NARSInterface = NARSInterface.constructInterface()
+ interface: NARSInterface = NARSInterface.construct_interface()
# enter console loop
while True:
- interface.printOutput(
+ interface.print_output(
PrintType.COMMENT, '', comment_title='Input', end='')
lines = input()
try:
- interface._handleLines(lines)
+ interface._handle_lines(lines)
except Exception as e:
- interface.printOutput(
+ interface.print_output(
PrintType.ERROR, f'Errors when input {lines}\n{e}')
if __name__ == '__main__':
- Config.loadFromDict(DEFAULT_CONFIG)
+ # Config.loadFromDict(DEFAULT_CONFIG) # ! deprecated
__main__()