-
Notifications
You must be signed in to change notification settings - Fork 0
/
the_semantic_db_console.py
333 lines (275 loc) · 9.82 KB
/
the_semantic_db_console.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#!/usr/bin/python3
#######################################################################
# the semantic-db console
#
# Author: Garry Morrison
# email: garry -at- semantic-db.org
# Date: 2014
# Update: 19/7/2015
# Copyright: closed for now
#
# Usage: ./the_semantic_db_console.py
#
#######################################################################
# export PYTHONIOENCODING=UTF8
#
import sys
import glob
import os
import datetime
import time
import codecs
from the_semantic_db_code import *
from the_semantic_db_functions import *
from the_semantic_db_processor import *
# starting .sw directory:
sw_file_dir = "sw-examples"
#sys.stdout = codecs.getwriter("utf-8")(sys.__stdout__)
# check it exists, if not create it:
if not os.path.exists(sw_file_dir):
print("Creating " + sw_file_dir + " directory.")
os.makedirs(sw_file_dir)
# print ("Welcome!"
print("Welcome! 欢迎 ! ")
C = context_list("sw console")
old_help_string = """
q, quit, exit : quit the agent.
h, help : print this message
context : print list of context's
context string : set current context to string
dump : print current context
dump multi : print context list
dump self : print what we know about the default ket/sp
dump ket/sp : print what we know about the given ket/sp
load file.sw : load file.sw
save file.sw : save current context to file.sw
save multi file.sw : save context list to file.sw
files : show the available .sw files
create inverse : create inverse for current context
create multi inverse : create inverse for all context in context list
x = foo: bah : set x (the default ket) to |foo: bah>
id : display the default ket/superposition
s, store : set x to the result of the last computation
. : repeat last computation
if none of the above : process_input_line(C,line,x)
"""
help_string = """
q, quit, exit quit the agent.
h, help print this message
context print list of context's
context string set current context to string
icontext interactive context
reset reset back to completely empty console
Warning! you will lose all unsaved work!
dump print current context
dump exact print current context in exact mode
dump multi print context list
dump self print what we know about the default ket/sp
dump ket/sp print what we know about the given ket/sp
display (relatively) readable display of current context
display ket/sp (relatively) readable display about what we know for the ket/sp
freq convert current context to frequency list
mfreq convert context list to frequency list
load file.sw load file.sw
save file.sw save current context to file.sw
save multi file.sw save context list to file.sw
files show the available .sw files
cd change and create if necessary the .sw directory
ls, dir, dirs show the available directories
create inverse create inverse for current context
create multi inverse create inverse for all context in context list
x = foo: bah set x (the default ket) to |foo: bah>
id display the default ket/superposition
s, store set x to the result of the last computation
. repeat last computation
i interactive history
history show last 30 commands
history n show last n commands
save history save console history to file
running-time line find running time for a command
-- comment ignore, this is just a comment line.
if none of the above process_input_line(C,line,x)
"""
x = ket("",0)
stored_line = ""
command_history = []
command_history_file = "sa-console-command-history.txt" # file where we save the command history. Might be interesting.
# save history function:
def save_history(history,history_file):
print("saving history ... ")
try:
f = codecs.open(history_file,'w','utf-8')
today = str(datetime.date.today())
f.write(today + "\n")
for line in history:
f.write(" " + line + "\n")
f.write("\n")
f.close()
print("Done.")
except:
print("failed!")
# the interactive semantic agent:
while True:
line = input("\nsa: ")
if line == "i":
n = 30
if len(command_history) > 0:
count = min(len(command_history),n)
history = command_history[-count:]
for k,line in enumerate(history):
print(" " + str(k) + ") " + line)
selection = input("\nEnter your selection: ")
try:
selection = int(selection)
line = history[selection]
print("Your selection:",line,"\n")
except:
continue
else:
print("history is empty")
continue
command_history.append(line)
# exit the agent:
if line in ['q','quit','exit']:
# save history before we go:
save_history(command_history,command_history_file)
print("\nBye!")
break
if line in ['h','help']:
print(help_string)
elif line == "context":
print(C.show_context_list())
elif line == "icontext":
print(C.show_context_list_index())
selection = input("Enter your selection: ")
try:
selection = int(selection)
if C.set_index(selection):
print(C.dump_universe())
except:
continue
# switch context:
elif line.startswith("context "):
name = line[8:]
C.set(name)
print(C.dump_universe())
elif line == "reset":
check = input("\n Warning! This will erase all unsaved work! Are you sure? (y/n): ")
if len(check) > 0 and check[0] == 'y':
C = context_list("sw console")
print("\n Gone ... ")
elif line == "dump":
print(C.dump_universe())
elif line == "dump exact":
print(C.dump_universe(True))
elif line == "dump multi":
print(C.dump_multiverse())
elif line == "dump self":
print(C.dump_sp_rules(x))
elif line.startswith("dump "):
var = line[5:]
print("var:",var,"\n")
try:
sp = extract_compound_superposition(C,var)[0]
print(C.dump_sp_rules(sp))
except:
continue
elif line == "display":
print(C.display_all())
elif line.startswith("display "):
var = line[8:]
print("var:",var,"\n")
try:
sp = extract_compound_superposition(C,var)[0]
print(C.display_sp(sp))
except:
continue
elif line == "freq":
result = C.to_freq_list()
print(result)
elif line == "mfreq":
print(C.multiverse_to_freq_list())
elif line.startswith("load "):
name = line[5:]
name = sw_file_dir + "/" + name # load and save files to the sw_file_dir.
print("loading sw file:",name)
# time it!
start_time = time.time()
load_sw(C,name)
end_time = time.time()
delta_time = end_time - start_time
print("\n Time taken:",display_time(delta_time))
elif line == "save history":
# save history:
save_history(command_history,command_history_file)
elif line.startswith("save multi "):
name = line[11:]
name = sw_file_dir + "/" + name # load and save files to the sw_file_dir.
print("saving context list to:",name)
save_sw_multi(C,name)
elif line.startswith("save "):
name = line[5:]
name = sw_file_dir + "/" + name # load and save files to the sw_file_dir.
print("saving current context to:",name)
save_sw(C,name)
elif line == "files":
sep = " "
max_len = 0
data = []
for file in glob.glob(sw_file_dir + "/*.sw"):
base = os.path.basename(file)
max_len = max(max_len,len(base))
data.append([base,extract_sw_stats(file)])
print()
for file,stats in data:
print(" " + file.ljust(max_len) + sep + stats)
elif line.startswith("cd "):
sw_file_dir = line[3:]
# check it exists, if not create it:
if not os.path.exists(sw_file_dir):
print("Creating " + sw_file_dir + " directory.")
os.makedirs(sw_file_dir)
elif line in ['ls','dir','dirs']:
print("directory list:")
for dir in [d for d in os.listdir('.') if os.path.isdir(d) and not d.startswith("__")]:
prefix = " "
if dir == sw_file_dir:
prefix = "* "
sw_count = len(glob.glob(dir + "/*.sw"))
print(prefix + dir + " (" + str(sw_count) + ")")
elif line == "create inverse":
C.create_universe_inverse()
elif line == "create multi inverse":
C.create_multiverse_inverse()
elif line.startswith("x = "):
var = line[4:]
try:
x = extract_compound_superposition(C,var)[0]
except:
x = ket(var)
elif line == "id":
print(x)
elif line in ['s','store']: # set x to the result of the last computation.
x = result
print("stored:",x)
elif line.startswith("--"):
continue
elif line.startswith("history"):
try:
n = int(line[8:])
except:
n = 30
if len(command_history) > 0:
count = min(len(command_history),n)
for line in command_history[-count:]:
print(" " + line)
else:
if line == ".":
line = stored_line
stored_line = line
start_time = time.time()
result = process_input_line(C,line,x) # maybe handling of comment lines should be in here?
print(result)
end_time = time.time()
delta_time = end_time - start_time
print("\n Time taken:",display_time(delta_time)) # display_time() is in the sdb_functions.py file