Skip to content

Commit

Permalink
refactor: ♻️ Renames some Operation to Operator
Browse files Browse the repository at this point in the history
Renames the class `Operation` to `Operator` with some changes to "Operation" originally intended as "Operator"

#43
  • Loading branch information
ARCJ137442 committed Nov 1, 2023
1 parent 697e452 commit 5298484
Show file tree
Hide file tree
Showing 16 changed files with 94 additions and 94 deletions.
2 changes: 1 addition & 1 deletion Experiments/ExConsole/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ def exeF(arguments: Iterable[Term], task: Task=None, memory: Memory=None) -> Uni
'''
print(f'executed: arguments={arguments}, task={task}, memory={memory}. the "task" will be returned')
return task
Operation.register(Operation.Operation('f'), exeF)
Operation.register(Operation.Operator('f'), exeF)
# build task
# task1: Task = NarseseParser.parse('f(x).') # the same as <(*, x) --> ^f>.
# task1: Task = NarseseParser.parse('f(x).') # the same as <(*, x) --> ^f>.
Expand Down
8 changes: 4 additions & 4 deletions Experiments/FighterPlane/Agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ def __init__(self): # nars_type: 'opennars' or 'ONA'
# self.dont_move()
# elif operation == '^fire':
# self.fire()
self.core.register_operation('left', self.move_left)
self.core.register_operation('right', self.move_right)
self.core.register_operation('deactivate', self.dont_move)
self.core.register_operation('fire', self.fire)
self.core.register_operator('left', self.move_left)
self.core.register_operator('right', self.move_right)
self.core.register_operator('deactivate', self.dont_move)
self.core.register_operator('fire', self.fire)
self.inference_cycle_frequency = 5


Expand Down
2 changes: 1 addition & 1 deletion Experiments/GoalAgent/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
def main():
Config.projection_decay = 1e-4
nars = Reasoner(100, 100)
nars.register_operation("say_hello", say_hello)
nars.register_operator("say_hello", say_hello)

# task1 = Narsese.parse("<{SELF}-->[good]>! :|:")
# task2 = Narsese.parse("<{SELF}-->[good]>! :|:")
Expand Down
4 changes: 2 additions & 2 deletions Experiments/Pong/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ def player_move(arguments: Iterable[Term], task: Task=None, memory: Memory=None)
def player_stop(arguments: Iterable[Term], task: Task=None, memory: Memory=None):
Action.value = 0

nars.register_operation('move', player_move)
nars.register_operation('stop', player_stop)
nars.register_operator('move', player_move)
nars.register_operator('stop', player_stop)

# begin playing
i_step = 0
Expand Down
4 changes: 2 additions & 2 deletions Experiments/Pong/main2.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,8 @@ def player_move(arguments: Iterable[Term], task: Task=None, memory: Memory=None)
def player_stop(arguments: Iterable[Term], task: Task=None, memory: Memory=None):
action = 0

nars.register_operation('move', player_move)
nars.register_operation('stop', player_stop)
nars.register_operator('move', player_move)
nars.register_operator('stop', player_stop)

# begin playing
i_step = 0
Expand Down
2 changes: 1 addition & 1 deletion pynars/Console.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def run_nars(filepath: str, seed: int = 137, n_memory: int = 100, capacity: int
rand_seed(seed)
print_out(PrintType.COMMENT, f'rand_seed={seed}', comment_title='Setup')
nars = Reasoner(n_memory, capacity)
nars.register_operation('left', lambda *args: print('execute left.'))
nars.register_operator('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')
Expand Down
40 changes: 20 additions & 20 deletions pynars/ConsolePlus.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,39 +299,39 @@ def eval_code(*args: List[str]) -> None:
print(f'eval failed: {e}')


@cmd_register(('operation', 'operation-list', 'o-list'))
def operation_list(*keywords: List[str]) -> None:
'''Format: operation-list [*keywords]
Enumerate existing operations; It can be retrieved with parameters'''
@cmd_register(('operator', 'operator-list', 'o-list'))
def operator_list(*keywords: List[str]) -> None:
'''Format: operator-list [*keywords]
Enumerate existing operators; It can be retrieved with parameters'''
keywords = keywords if keywords else ['']
# Search for a matching interface name
from pynars.NARS.Operation.Register import registered_operations, get_registered_operation_by_name, registered_operation_names
operation_names: List[str] = prefix_browse(registered_operation_names(), *keywords)
from pynars.NARS.Operation.Register import registered_operators, get_registered_operator_by_name, registered_operator_names
operator_names: List[str] = prefix_browse(registered_operator_names(), *keywords)
# Displays information about "matched interface"
if operation_names:
for name in operation_names: # match the list of all cmds, as long as they match the search results - not necessarily in order
op = get_registered_operation_by_name(name)
f = registered_operations[op]
print(f'''<Operation {str(op)}>: {
if operator_names:
for name in operator_names: # match the list of all cmds, as long as they match the search results - not necessarily in order
op = get_registered_operator_by_name(name)
f = registered_operators[op]
print(f'''<Operator {str(op)}>: {
'No function' if f == None else
'No description' if f.__doc__.strip() == '' else
f.__doc__}''')
return
print(f'No Operation is browsed by "{", ".join(keywords)}"')
print(f'No Operator is browsed by "{", ".join(keywords)}"')


@cmd_register(('register-operation', 'operation-register', 'o-register', 'register'))
def operation_register(*args: List[str]) -> None:
'''Format: register-operation <Operation(Term) Name> [<'eval'/'exec'> <Python Code>]
Register an operation to NARS interface.
@cmd_register(('register-operator', 'operator-register', 'o-register', 'register'))
def operator_register(*args: List[str]) -> None:
'''Format: register-operator <Operator(Term) Name> [<'eval'/'exec'> <Python Code>]
Register an operator to NARS interface.
function signature:
execution_F(arguments: Iterable[Term], task: Task=None, memory: Memory=None) -> Union[Task,None]
default fallback of execution_F when only 1 argument is provided:
print(f'executed: arguments={arguments}, task={task}, memory={memory}. the "task" will be returned')
! Unsupported: register mental operations
! Unsupported: register mental operators
'''
name = args[0]
"The operator's name without `^` as prefix"
Expand All @@ -354,13 +354,13 @@ def execution_F(arguments: Iterable[Term], task: Task=None, memory: Memory=None)
execution_F.__doc__ = f'''
The execution is auto generated from operator with name={name} in {eType} mode with code={code}
'''.strip()
if (op:=current_NARS_interface.reasoner.register_operation(name, execution_F)) is not None:
print(f'Operation {str(op)} was successfully registered ' + (
if (op:=current_NARS_interface.reasoner.register_operator(name, execution_F)) is not None:
print(f'Operator {str(op)} was successfully registered ' + (
'without code'
if len(args) == 1
else f'in mode "{eType}" with code={code}'))
else:
print(f'The operation with name="{name}" was already registered!')
print(f'The operator with name="{name}" was already registered!')


@cmd_register(('simplify-parse', 'parse'))
Expand Down
2 changes: 1 addition & 1 deletion pynars/NAL/MentalOperation/_aware.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from pynars.Narsese._py.Statement import Statement
from pynars.Narsese._py.Task import Belief, Desire, Task
from pynars.Narsese._py.Truth import Truth
from ._register import registered_operations
from ._register import registered_operators
from pynars.Narsese import Term
from ..Functions.Tools import truth_from_term, truth_to_quality, truth_to_term
from pynars.Narsese import Base
Expand Down
6 changes: 3 additions & 3 deletions pynars/NAL/MentalOperation/_execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from pynars.Narsese._py.Statement import Statement
from pynars.Narsese._py.Task import Belief, Desire, Task
from pynars.Narsese._py.Truth import Truth
from ._register import registered_operations
from ._register import registered_operators
from pynars.Narsese import Term
from ..Functions.Tools import truth_from_term, truth_to_quality
from pynars.Narsese import Base
Expand All @@ -16,9 +16,9 @@ def execute(task: Task):
''''''
stat: Statement = task.term
if stat.is_executable:
operation: Operation = stat.predicate
operator: Operator = stat.predicate
args = stat.terms
return registered_operations[operation](task, *args)
return registered_operators[operator](task, *args)
else:
return None

Expand Down
8 changes: 4 additions & 4 deletions pynars/NAL/MentalOperation/_register.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
from typing import Callable, Dict
from pynars.Narsese._py.Operation import *

registered_operations: Dict[Operation, Callable] = {}
registered_operators: Dict[Operator, Callable] = {}

def register(operation: Operation, callable: Callable):
def register(operator: Operator, callable: Callable):
''''''
global registered_operations
registered_operations[operation] = callable
global registered_operators
registered_operators[operator] = callable
10 changes: 5 additions & 5 deletions pynars/NARS/Control/Reasoner.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,11 +182,11 @@ def mental_operation(self, task: Task, concept: Concept, answers_question: Task,

return task_operation_return, task_executed, belief_awared

def register_operation(self, name_operation: str, callback: Callable):
'''register an operation and return the operation if successful (otherwise, return None)'''
if not Operation.is_registered_by_name(name_operation):
from pynars.Narsese import Operation as Op
op = Op(name_operation)
def register_operator(self, name_operator: str, callback: Callable):
'''register an operator and return the operator if successful (otherwise, return None)'''
if not Operation.is_registered_by_name(name_operator):
from pynars.Narsese import Operator as Op
op = Op(name_operator)
Operation.register(op, callback)
return op
return None
Expand Down
6 changes: 3 additions & 3 deletions pynars/NARS/DataStructures/_py/Memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,13 +240,13 @@ def _accept_goal(self, task: Task, concept: Concept, task_link: TaskLink=None):
truth = task.truth
if truth.e > Config.decision_threshold:
if (task is not None) and task.is_executable and not (desire is not None and desire.evidential_base.contains(task.evidential_base)):
# execute registered operations
# execute with registered operators
stat: Statement = task.term
op = stat.predicate
from pynars.NARS.Operation.Register import registered_operations
from pynars.NARS.Operation.Register import registered_operators
from pynars.NARS.Operation.Execution import execute
# ! if `op` isn't registered, an error "AttributeError: 'NoneType' object has no attribute 'stamp'" from "key: Callable[[Task], Any] = lambda task: (hash(task), hash(task.stamp.evidential_base))" will be raised
if op in registered_operations and not task.is_mental_operation:
if op in registered_operators and not task.is_mental_operation:
# to judge whether the goal has been fulfilled
task_operation_return, task_executed = execute(task, concept, self)
concept_task = self.take_by_key(task.term, remove=False)
Expand Down
6 changes: 3 additions & 3 deletions pynars/NARS/Operation/Execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from pynars.Narsese._py.Statement import Statement
from pynars.Narsese._py.Task import Belief, Desire, Task
from pynars.Narsese._py.Truth import Truth
from .Register import registered_operations
from .Register import registered_operators
from pynars.Narsese import Term
from pynars.NAL.Functions.Tools import truth_from_term, truth_to_quality
from pynars.Narsese import Base
Expand All @@ -34,9 +34,9 @@ def execute(task: Task, concept: Concept, memory: Memory):
if task.term != concept.term:
concept = memory.take_by_key(task.term, remove=False)
stat: Statement = task.term
operation: Operation = stat.predicate
operator: Operator = stat.predicate
args = stat.subject.terms
function_op: Callable = registered_operations.get(operation, None)
function_op: Callable = registered_operators.get(operator, None)

if function_op is not None:
belief = executed_task(task)
Expand Down
30 changes: 15 additions & 15 deletions pynars/NARS/Operation/Register.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
from typing import Callable, Dict
from pynars.Narsese._py.Operation import *

registered_operations: Dict[Operation, Callable] = {}
registered_operators: Dict[Operator, Callable] = {}

def registered_operation_names():
def registered_operator_names():
''''''
global registered_operations
return [registered_operation.word for registered_operation in registered_operations.keys()]
global registered_operators
return [registered_operator.word for registered_operator in registered_operators.keys()]


def register(operation: Operation, callable: Callable):
def register(operator: Operator, callable: Callable):
''''''
global registered_operations
registered_operations[operation] = callable
global registered_operators
registered_operators[operator] = callable


def is_registered_by_name(word):
''''''
global registered_operations
for registered_operation in registered_operations.keys():
if registered_operation.word == word:
global registered_operators
for registered_operator in registered_operators.keys():
if registered_operator.word == word:
return True
return False


def get_registered_operation_by_name(word):
def get_registered_operator_by_name(word):
''''''
global registered_operations
for registered_operation in registered_operations.keys():
if registered_operation.word == word:
return registered_operation
global registered_operators
for registered_operator in registered_operators.keys():
if registered_operator.word == word:
return registered_operator
return None
8 changes: 4 additions & 4 deletions pynars/Narsese/Parser/parser.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pynars.Narsese import Term, Judgement, Tense, Statement, Copula, Truth, Stamp, Interval
from pynars.Narsese import Base, Operation, Budget, Task, Goal, Punctuation, Question, Quest, Sentence, VarPrefix, Variable, Connector, Compound, SELF
from pynars.Narsese import Base, Operator, Budget, Task, Goal, Punctuation, Question, Quest, Sentence, VarPrefix, Variable, Connector, Compound, SELF
from pathlib import Path
from datetime import datetime
from pynars import Config, Global
Expand Down Expand Up @@ -186,7 +186,7 @@ def atom_term(self, word: Token):
@inline_args
def op(self, word: Token):
word = word.value
return Operation(word)
return Operator(word)

@inline_args
def interval(self, word: Token):
Expand All @@ -213,15 +213,15 @@ def statement_term(self, statement):
return statement

@inline_args
def statement_operation1(self, op: Operation, *args: str):
def statement_operation1(self, op: Operator, *args: str):
terms = (term for term in args)
return Statement(Compound(Connector.Product, *terms, is_input=True), Copula.Inheritance, op, is_input=True)

@inline_args
def statement_operation2(self, word: Token, *args: str):
op = word.value
terms = (term for term in args)
return Statement(Compound(Connector.Product, *terms, is_input=True), Copula.Inheritance, Operation(op), is_input=True)
return Statement(Compound(Connector.Product, *terms, is_input=True), Copula.Inheritance, Operator(op), is_input=True)

@inline_args
def inheritance(self):
Expand Down
Loading

0 comments on commit 5298484

Please sign in to comment.