-
Notifications
You must be signed in to change notification settings - Fork 4
/
bridge.py
247 lines (237 loc) · 9.81 KB
/
bridge.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
"""
* The MIT License
*
* Copyright (c) 2024 Patrick Hammer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* """
#BRIDGE HANDLES NACE-NARS connection with MeTTa (for the world=9 demo)
import sys
import os
useONA = True #whether to use ONA for MeTTa-NARS acceleration instead of MeTTa-NARS with MeTTa-Morph for world=9
useNarsese=False
if "ona" in sys.argv:
useONA = True
if "narsese" in sys.argv:
useONA = True
useNarsese = True
if useONA:
mettanars = os.path.abspath('../AniNAL/OpenNARS-for-Applications/misc/Python')
sys.path.append(mettanars)
cwd = os.getcwd()
os.chdir(mettanars)
from MeTTa import *
os.chdir(cwd)
else:
mettanars = os.path.abspath('../metta-morph/metta-nars/')
sys.path.append(mettanars)
cwd = os.getcwd()
os.chdir(mettanars)
from NAR import *
os.chdir(cwd)
useSpaces = False
if "spaces" in sys.argv and not useNarsese:
from spaces import space_input, space_init, space_tick
useSpaces = True
space_init()
def BRIDGE_INIT(widthval, heightval, BOARDval, SetNACEPlanningObjectiveVal):
global width, height, BOARD, SetNACEPlanningObjective
width = widthval
height = heightval
BOARD = BOARDval
SetNACEPlanningObjective = SetNACEPlanningObjectiveVal
with open("knowledge.metta") as f:
backgroundknowledge = f.read()
for belief in backgroundknowledge.split("\n"):
if belief != "" and not belief.startswith(";"):
NAR_AddInput(belief)
if useSpaces:
space_input(belief)
NAR_Cycle(30)
def ParseGroundedRelation(METTA):
R = METTA.split("--> ")[1].split(")")[0]
S = METTA.split(": (((")[1].split(" x")[0]
P = METTA.split(" x ")[1].split(")")[0]
F_C = METTA.split(") (")[1].split(")")[0].split(" ")
#print("DEBUG", S, P, R, F_C, METTA, float(F_C[1]) < 0.1, R not in ["left", "right", "up", "down"], len(S), len(P)); input()
if float(F_C[1]) < 0.1 or R not in ["left", "right", "up", "down"] or len(S) > 1 or len(P) > 1:
exceptionThrown = 1/0 #TODO return flag
return S, P, R, F_C
def groundedGoal(METTA):
#s,p,yoff,xoff = groundedFunction(METTA)
#((S x P) --> left)
S, P, R, F_C = ParseGroundedRelation(METTA)
yoffset = "y+1"
xoffset = "x"
if R == "up":
yoffset = "y-1"
xoffset = "x"
if R == "down":
yoffset = "y+1"
xoffset = "x"
if R == "left":
yoffset = "y"
xoffset = "x-1"
if R == "right":
yoffset = "y"
xoffset = "x+1"
#print("GROUNDING DEBUG:", S, P, R, yoffset, xoffset)
STR = f"lambda world: any( world[0][{yoffset}][{xoffset}] == '{S}' and world[0][y][x] == '{P}' for x in range(1, width-1) for y in range(1, height-1))"
#print("FUNC:", STR); input()
FUNC = eval(STR)
return FUNC
def groundedBelief(METTA, observed_world):
S, P, R, F_C = ParseGroundedRelation(METTA)
yoffset = 1
xoffset = 0
if P == "up":
yoffset = +1
xoffset = 0
if P == "down":
yoffset = -1
xoffset = 0
if P == "left":
yoffset = 0
xoffset = -1
if P == "right":
yoffset = 0
xoffset = +1
for x in range(1,width-1):
for y in range(1,height-1):
if observed_world[BOARD][y][x] == S:
observed_world[BOARD][y+yoffset][x+xoffset] = P
if observed_world[BOARD][y][x] == P:
observed_world[BOARD][y-yoffset][x-xoffset] = S
goal = None
goalTask = ""
def BRIDGE_Tick(observed_world):
if goal is not None:
if goal(observed_world): #goal achieved
beliefEventFromAchievedGoal = "!(AddBeliefEvent " + goalTask.split("(!: ")[1].split(") (")[0] + ")" + " (1.0 0.9)))"
BRIDGE_Input(beliefEventFromAchievedGoal, observed_world, NACEToNARS=False, ForceMeTTa=True, FromSpace=False)
if useONA:
NAR_Cycle(20)
if useSpaces:
space_tick()
last_observed_world = None
def BRIDGE_Input(METTA, observed_world, NACEToNARS=False, ForceMeTTa=False, FromSpace=False): #can now also be Narsese
global goal, goalTask, last_observed_world
if observed_world is not None:
last_observed_world = observed_world
else:
observed_world = last_observed_world
if useSpaces and not FromSpace:
space_input(METTA)
if METTA.startswith("!") or METTA.endswith("! :|:") or METTA.endswith(". :|:") or METTA.endswith(".") or METTA.endswith("?") or METTA.endswith("? :|:"):
GOAL = "AddGoalEvent" in METTA or METTA.endswith("! :|:")
#METTA = METTA.replace("AddGoalEvent", "AddBeliefEvent").replace("! :|:", ". :|:")
useNarseseNow = useNarsese and not ForceMeTTa
if useNarseseNow:
METTA2 = NAR_NarseseToMeTTa(METTA)
else:
METTA2 = METTA
atomic_terms = [x for x in METTA2.replace("AddBeliefEvent", "").replace(" x ", " ").replace("(", " ").replace(")", " ").replace("!", "").replace("-->","").split(" ") if x != ""]
connectors = ["-->", "IntSet", "<->", "<=>"]
if useNarseseNow:
NAR_SetUseNarsese(True) #bypass metta translation in this case
ret = NAR_AddInput(METTA)
NAR_SetUseNarsese(False)
else:
ret = NAR_AddInput(METTA)
if NACEToNARS:
return
tasks = ret["input"] + ret["derivations"]
ret = NAR_Cycle(20)
tasks += (ret["input"] + ret["derivations"])
processGoals = True
for taskdict in tasks:
if 'metta' not in taskdict:
#print("NOT INCLUDED", taskdict); input() TODO FIX
continue
task = taskdict['metta'].replace(" * ", " x ") #transformation only needed for Narsese version
if useSpaces:
space_input(taskdict['metta'])
if "$1" in task or "#1" in task or "<=>" in task or "==>" in task or "=/>" in task or "&&" in task or "||" in task or "/1" in task or "/2" in task: #check only needed for Narsese version
continue
if GOAL:
#print("!!!!!TASK", task)
try:
if processGoals:
goalTask = task
goal = groundedGoal(task)
SetNACEPlanningObjective(goal)
processGoals = False
print("TASK ACCEPTED", task); #input()
except:
print("TASK REJECTED")
None
elif "(.:" in task:
#print("!!!!!TASK", task)
try:
groundedBelief(task, observed_world)
print("TASK ACCEPTED", task); #input()
except Exception as ex:
print("TASK REJECTED")#,ex)
None
def observeSpatialRelation(y,x, observed_world, horizontal=True, vertical=True):
board = observed_world[BOARD]
if horizontal:
valueMid = board[y][x]
valueLeft = board[y][x-1]
valueRight = board[y][x+1]
MeTTaL = f"!(AddBeliefEvent ((({valueRight} x {valueMid}) --> right) (1.0 0.90)))"
MeTTaR = f"!(AddBeliefEvent ((({valueLeft} x {valueMid}) --> left) (1.0 0.90)))"
if valueRight != " " and valueMid != " ":
BRIDGE_Input(MeTTaL, observed_world, NACEToNARS = True, ForceMeTTa = True)
if valueRight != " " and valueMid != " " and valueLeft != " ":
if useONA:
NAR_Cycle(20)
#NAR_SetUseNarsese(True)
#NAR_AddInput("*concurrent")
#NAR_SetUseNarsese(False)
if valueMid != " " and valueLeft != " ":
BRIDGE_Input(MeTTaR, observed_world, NACEToNARS = True, ForceMeTTa = True)
if vertical:
valueMid = board[y][x]
valueUp = board[y-1][x]
valueDown = board[y+1][x]
MeTTaD = f"!(AddBeliefEvent ((({valueDown} x {valueMid}) --> down) (1.0 0.90)))"
MeTTaU = f"!(AddBeliefEvent ((({valueUp} x {valueMid}) --> up) (1.0 0.90)))"
if valueUp != " " and valueMid != " ":
BRIDGE_Input(MeTTaU, observed_world, NACEToNARS = True, ForceMeTTa = True)
if valueUp != " " and valueMid != " " and valueDown != " ":
if useONA:
NAR_Cycle(20)
#NAR_SetUseNarsese(True)
#NAR_AddInput("*concurrent")
#NAR_SetUseNarsese(False)
if valueMid != " " and valueDown != " ":
BRIDGE_Input(MeTTaD, observed_world, NACEToNARS = True, ForceMeTTa = True)
def BRIDGE_observationToNARS(observed_world):
agent = False
for x in range(1,width-1):
for y in range(1,height-1):
if observed_world[BOARD][y][x] == 'x': #AGENT
agent_x, agent_y = (x,y)
agent = True
observeSpatialRelation(y, x, observed_world)
NAR_Cycle(20)
break
if agent:
break