forked from GarryMorrison/Feynman-knowledge-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththe_semantic_db_processor.py
1261 lines (1060 loc) · 41.1 KB
/
the_semantic_db_processor.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#######################################################################
# the semantic-db parser
#
# Author: Garry Morrison
# email: garry -at- semantic-db.org
# Date: 2014
# Update: 5/8/2015
# Copyright: GPLv3
#
# Usage:
#
#######################################################################
from string import ascii_letters
import copy
import os
from the_semantic_db_code import *
from the_semantic_db_functions import *
# Some hash tables mapping ops to the python equivalent.
# Left hand side is BKO language, right is python.
# functions built into ket/superposition classes.
built_in_table = {
"display" : "display",
"transpose" : "transpose",
# "select-elt" : "select_elt",
"pick-elt" : "pick_elt",
"pick-an-element-from" : "pick_elt", # added 13/7/2015, to make it closer to natural language
"weighted-pick-elt" : "weighted_pick_elt", # added 5/8/2015. Been meaning to add this one for a long time!
# "find-index" : "find_index",
# "find-value" : "find_value",
"normalize" : "normalize",
"rescale" : "rescale",
# "rescale" : "rescale",
# "sigmoid" : "apply_sigmoid",
# "function" : "apply_fn",
# "similar" : "similar",
# "collapse-fn" : "apply_fn_collapse",
"collapse" : "collapse",
"count" : "number_count",
"how-many" : "number_count",
"count-sum" : "number_count_sum",
"sum" : "number_count_sum",
"measure-currency" : "number_count_sum",
"product" : "number_product",
"drop" : "drop",
# "drop-below" : "drop_below",
# "drop-above" : "drop_above",
# "select-range" : "select_range",
# "delete-elt" : "delete_elt",
"reverse" : "reverse",
"shuffle" : "shuffle",
"coeff-sort" : "coeff_sort",
"ket-sort" : "ket_sort",
"max-elt" : "find_max_elt",
"min-elt" : "find_min_elt",
"max" : "find_max",
"min" : "find_min",
# new:
"discrimination" : "discrimination",
"discrim" : "discrimination",
# special:
"type" : "type", # implemented for debugging purposes.
# new 7/9/2014:
# "long" : "long_display",
# new, 4/1/2015:
"not-empty" : "is_not_empty",
"do-you-know" : "is_not_empty",
# new 6/1/2015:
"max-coeff" : "number_find_max_coeff",
"min-coeff" : "number_find_min_coeff",
# 17/7/2015: our first compound op in this table. Normally you would put this in the compound op table, but it has no parameters, so it wont work there! (I tried).
# yeah, sloppy code though! I find this somewhat unpleasant!
# hopefully we eventually find a cleaner way to do all this.
# and by "this", I mean all these different tables and so on.
"reverse-rank" : "reverse().apply_sp_fn(rank).reverse",
}
# table of sigmoids:
sigmoid_table = {
"clean" : "clean",
# "threshold-filter" : "threshold_filter", # we can't handle paramters with our ops yet.
"binary-filter" : "binary_filter",
"not-binary-filter" : "not_binary_filter",
"pos" : "pos",
"NOT" : "NOT",
"xor-filter" : "xor_filter",
# "mult" : "mult", # yeah, the sigmoid version works, but moved to compound table
# ".multiply({0})" Decided it was common enough that it needed to be built in.
"invert" : "invert",
# 4/5/2015:
"sigmoid-abs" : "sigmoid_abs", # maybe just call it "abs"? We only need the "sigmoid_" prefix for python, so not to stomp on abs().
"abs" : "sigmoid_abs",
}
# some ket -> ket functions:
fn_table = {
"apply-value" : "apply_value",
"extract-category" : "extract_category",
"extract-value" : "extract_value",
"to-number" : "category_number_to_number",
"shout" : "shout",
# "discrim" : "discrimination", # Broken. discrim (3|a> + 9|b>) returns 12| >. Doh! It should be 9 - 3, not 9 + 3.
"F" : "to_Fahrenheit", # should these be to-F, to-C, to-K?
"C" : "to_Celsius",
"K" : "to_Kelvin",
"to-km" : "to_km",
"to-meter" : "to_meter",
"to-mile" : "to_mile",
"to-miles" : "to_mile",
"to-value" : "to_value",
"to-category" : "to_category",
# 3/6/2014:
"day-of-the-week" : "day_of_the_week",
# 23/6/2014:
"long" : "long_display", # BUG! I have no idea why this insists on using the "37|ket>"" instead of "37 ket" notation!
"split" : "split_ket", # ahh.... it is running long_display with respect to kets, not superposition as I expected!
# maybe shift to another table to fix.
# 29/6/2014:
# "sp-as-list" : "sp_as_list", # Nope! Belongs in the sp_fn_table.
# 10/11/2014:
"expand-hierarchy" : "expand_hierarchy",
"chars" : "chars",
# 4/1/2015:
"pop-float" : "pop_float",
"push-float" : "push_float",
"cat-depth" : "category_depth",
# 4/2/2015:
"to-comma-number" : "number_to_comma_number",
# 5/2/2015:
"current-time" : "current_time",
"current-date" : "current_date",
# 9/2/2015:
"extract-3-tail" : "extract_3_tail",
# 19/7/2015:
"extract-3-tail-chars" : "extract_3_tail_chars",
# 1/3/2015:
"to-coeff" : "to_coeff",
# 3/3/2015:
"extract-movie-year" : "extract_year",
"ket-length" : "ket_length",
# 27/4/2015:
"lower-case" : "lower_case",
"upper-case" : "upper_case",
"one-gram" : "one_gram",
# 14/5/2015:
"two-gram" : "two_gram",
"three-gram" : "three_gram",
# 30/4/2015:
"plus-or-minus" : "plus_or_minus",
# 5/8/2015:
"split-chars" : "split_chars",
}
# 7/4/2014 me wonders. do fn_table and fn_table2 really need to be separate?
# some other functions. Some are ket -> ket, some are ket -> superposition.
fn_table2 = {
"read" : "read_text",
"spell" : "spell_word",
# don't get the point of this one!
# "factor" : "factor_numbers",
"factor" : "factor_number",
"near-number" : "near_numbers",
"strange-int" : "strange_int",
"is-prime" : "is_prime",
"strange-int-prime" : "strange_int_prime",
"strange-int-depth" : "strange_int_depth",
"strange-int-delta" : "strange_int_delta",
"strange-int-list" : "strange_int_list",
}
# 3/2/2015: NB: all functions in this table are almost certainly vulnerable to injection attacks, cf SQL injection attacks!
# Fix!!!
# table of compound operators.
# They need to be handled separately from those in the tables above, because they have parameters.
compound_table = {
"select-elt" : ".select_elt({0})",
# "find-index" # can't support these two until we have more advanced parsing.
# "find-value # eg: find-index[|person: Fred>] |x> currently would split on the space in the ket.
"normalize" : ".normalize({0})",
"rescale" : ".rescale({0})",
"similar" : ".similar(context,\"{0}\")",
# 23/2/2015:
"self-similar" : ".self_similar(context,\"{0}\")",
"find-topic" : ".find_topic(context,\"{0}\")",
# "collapse-function" : ".apply_fn_collapse({0})", # broken for now. eg, how handle collapse-fn[spell] |x> ??
"drop-below" : ".drop_below({0})", # Not needed anyway. Just use: collapse spell |x>
"drop-above" : ".drop_above({0})",
"select-range" : ".select_range({0})", # may comment this one out, but fine for now to have two versions.
"select" : ".select_range({0})",
"delete-elt" : ".delete_elt({0})",
"threshold-filter" : ".apply_sigmoid(threshold_filter,{0})",
"not-threshold-filter" : ".apply_sigmoid(not_threshold_filter,{0})",
# "mult" : ".apply_sigmoid(mult,{0})", # this is now moved to ket/sp since it is common enough.
"mult" : ".multiply({0})",
"sigmoid-in-range" : ".apply_sigmoid(sigmoid_in_range,{0})",
"smooth" : ".apply_fn_collapse(smooth,{0})",
"set-to" : ".apply_sigmoid(set_to,{0})",
# 4/1/2015:
"subtraction-invert" : ".apply_sigmoid(subtraction_invert,{0})",
# newly added: 7/4/2014:
"absolute-noise" : ".absolute_noise({0})",
"relative-noise" : ".relative_noise({0})",
# newly added 8/5/2014:
"common" : ".apply_sp_fn(common,context,\"{0}\")",
# newly added 12/5/2014:
"exp" : ".apply_sp_fn(exp,context,\"{0}\")",
# newly added 17/4/2015:
"full-exp" : ".apply_sp_fn(full_exp,context,\"{0}\")",
# newly added 19/5/2014
# rel-kets tweaked 13/2/2015:
"relevant-kets" : ".apply_sp_fn(relevant_kets,context,\"{0}\")",
"intn-relevant-kets" : ".apply_sp_fn(intersection_relevant_kets,context,\"{0}\")",
"rel-kets" : ".apply_sp_fn(relevant_kets,context,\"{0}\")",
"intn-rel-kets" : ".apply_sp_fn(intersection_relevant_kets,context,\"{0}\")",
# "matrix" : ".apply_naked_fn(matrix,context,\"{0}\")",
# "multi-matrix" : ".apply_naked_fn(multi_matrix,context,\"{0}\")",
# newly added 21/5/2014:
"matrix" : ".apply_naked_fn(multi_matrix,context,\"{0}\")", # this deprecates/replaces the naked_fn(matrix,...) version.
"merged-matrix" : ".apply_naked_fn(merged_multi_matrix,context,\"{0}\")",
"naked-matrix" : ".apply_naked_fn(merged_naked_matrix,context,\"{0}\")",
# newly added 22/5/2014:
"map" : ".apply_sp_fn(map,context,\"{0}\")",
# newly added 28/5/2014:
"categorize" : ".apply_naked_fn(categorize,context,\"{0}\")",
# newly added 5/6/2014:
"vector" : ".apply_sp_fn(vector,context,\"{0}\")",
# added 6/6/2014:
"print-pixels" : ".apply_sp_fn(print_pixels,context,\"{0}\")",
# added 27/6/2014:
"active-buffer" : ".apply_sp_fn(console_active_buffer,context,\"{0}\")",
# added 28/7/2014:
"train-of-thought" : ".apply_sp_fn(console_train_of_thought,context,\"{0}\")",
# added 4/8/2014:
"exp-max" : ".apply_sp_fn(exp_max,context,\"{0}\")",
# added 7/8/2014:
"sp-propagate" : ".apply_sp_fn(sp_propagate,context,\"{0}\")",
"op-propagate" : ".apply_sp_fn(sp_propagate,context,\"{0}\")", # an alias
# 12/1/2015
"load-image" : ".apply_sp_fn(load_image,context,\"{0}\")",
# 20/4/2015
"save-image" : ".apply_sp_fn(save_image,context,\"{0}\")", # why do these need to be apply_sp_fn instead of just apply_fn?
# 29/1/2015:
"table" : ".apply_sp_fn(pretty_print_table,context,\"{0}\")",
# 1/2/2015:
"sort-by" : ".apply_sp_fn(sort_by,context,\"{0}\")",
# 2/2/2015:
"strict-table" : ".apply_sp_fn(pretty_print_table,context,\"{0}\",True)",
# 3/2/2015:
"sleep" : ".apply_sp_fn(bko_sleep,\"{0}\")",
# 5/2/2015:
"rank-table" : ".apply_sp_fn(pretty_print_table,context,\"{0}\",False,True)",
"strict-rank-table" : ".apply_sp_fn(pretty_print_table,context,\"{0}\",True,True)",
# 25/2/2015:
"greater-than" : ".apply_fn(greater_than,{0})",
"greater-equal-than" : ".apply_fn(greater_equal_than,{0})",
"less-than" : ".apply_fn(less_than,{0})",
"less-equal-than" : ".apply_fn(less_equal_than,{0})",
"equal" : ".apply_fn(equal,{0})",
"in-range" : ".apply_fn(in_range,{0})",
"is-greater-than" : ".apply_fn(greater_than,{0}).is_not_empty()",
"is-greater-equal-than" : ".apply_fn(greater_equal_than,{0}).is_not_empty()",
"is-less-than" : ".apply_fn(less_than,{0}).is_not_empty()",
"is-less-equal-than" : ".apply_fn(less_equal_than,{0}).is_not_empty()",
"is-equal" : ".apply_fn(equal,{0}).is_not_empty()",
"is-in-range" : ".apply_fn(in_range,{0}).is_not_empty()",
# 12/4/2015:
# not 100% sure this is the best way to do this, but for now is fine.
"coeff-greater-than" : ".apply_fn(push_float).apply_fn(greater_than,{0}).apply_fn(pop_float)",
"coeff-greater-equal-than" : ".apply_fn(push_float).apply_fn(greater_equal_than,{0}).apply_fn(pop_float)",
"coeff-less-than" : ".apply_fn(push_float).apply_fn(less_than,{0}).apply_fn(pop_float)",
"coeff-less-equal-than" : ".apply_fn(push_float).apply_fn(less_equal_than,{0}).apply_fn(pop_float)",
"coeff-equal" : ".apply_fn(push_float).apply_fn(equal,{0}).apply_fn(pop_float)",
"coeff-in-range" : ".apply_fn(push_float).apply_fn(in_range,{0}).apply_fn(pop_float)",
"is-coeff-greater-than" : ".apply_fn(push_float).apply_fn(greater_than,{0}).is_not_empty()",
"is-coeff-greater-equal-than" : ".apply_fn(push_float).apply_fn(greater_equal_than,{0}).is_not_empty()",
"is-coeff-less-than" : ".apply_fn(push_float).apply_fn(less_than,{0}).is_not_empty()",
"is-coeff-less-equal-than" : ".apply_fn(push_float).apply_fn(less_equal_than,{0}).is_not_empty()",
"is-coeff-equal" : ".apply_fn(push_float).apply_fn(equal,{0}).is_not_empty()",
"is-coeff-in-range" : ".apply_fn(push_float).apply_fn(in_range,{0}).is_not_empty()",
# 21/2/2015:
"round" : ".apply_fn(round_numbers,{0})",
# 22/2/2015:
"such-that" : ".apply_fn(such_that,context,\"{0}\")",
# 24/2/2015:
"discrim-drop" : ".discrimination_drop({0})",
# 4/3/2015: yeah, we are starting to define compound operators now. Though is slightly inelegant in terms of injection attacks!
"times" : ".apply_fn(pop_float).multiply({0}).apply_fn(push_float)",
# 12/3/2015: another compound operator: pick[n]
"pick" : ".shuffle().select_range(1,{0})",
# 24/3/2015:
"find-unique" : ".apply_naked_fn(find_unique,context,\"{0}\")",
# 2/6/2015:
"find-inverse" : ".apply_naked_fn(find_inverse,context,\"{0}\")",
# 2/4/2015:
"intn-find-topic" : ".intn_find_topic(context,\"{0}\")",
# 17/4/2015:
"apply-weights" : ".apply_sp_fn(apply_weights,\"{0}\")",
# 4/5/2015:
"max-filter" : ".apply_sigmoid(max_filter,{0})",
# 10/5/2015:
"image-load" : ".apply_naked_fn(improved_image_load,\"{0}\")",
# 11/5/2015:
"image-save" : ".apply_sp_fn(improved_image_save_show,\"{0}\")",
# 12/5/2015:
"average-categorize" : ".apply_naked_fn(average_categorize,context,\"{0}\")",
# 5/8/2015:
"select-chars" : ".apply_sp_fn(select_chars,\"{0}\")",
}
# 7/4/2014: new addition, functions that map sp -> ket/sp
# Pretty sure this breaks the linearity.
# Ie, the functions here are in general not linear, while most other ops/fns are.
# 30/6/2014: heh. I'd forgotten I had this!
sp_fn_table = {
"list-to-words" : "sp_to_words",
"read-letters" : "read_letters",
"read-words" : "read_words",
"merge-labels" : "merge_labels",
"sp-as-list" : "sp_as_list",
# 6/3/2015:
"display-algebra" : "display_algebra",
# 26-4-2015:
"rank" : "rank",
# 19/5/2015:
"image-show" : "improved_image_save_show",
}
# 2/2/2015: new addition functions that map ket -> ket/sp but needs context info.
ket_context_table = {
"int-coeffs-to-word" : "int_coeffs_to_word",
# 14/4/2015:
# "list-kets" : "list_kets", # deleted. Same funtionality as starts-with, essentially.
"starts-with" : "starts_with",
# 4/5/2015:
"show-image" : "show_image",
}
def sanitize_op(op):
if not op[0].isalpha():
return None
if all(c in ascii_letters + '0123456789-' for c in op):
return op
else:
return None
def valid_op(op):
if not op[0].isalpha() and not op[0] == '!':
return False
return all(c in ascii_letters + '0123456789-+!?.' for c in op)
def process_single_op(op):
print("op:",op)
splitat = "[,]"
pieces = ''.join(s if s not in splitat else ' ' for s in op).split()
if len(pieces) > 1:
print("compound op found")
op = pieces[0]
parameters = ",".join(pieces[1:])
if op not in compound_table:
print(op,"not in compound_table")
python_code = ""
else:
python_code = compound_table[op].format(parameters) # probably risk of injection attack here
elif op in built_in_table: # tables don't have injection bugs, since they must be in tables, hence already vetted.
print("op in built in table") # unless I guess a hash-table collision between safe and unsafe?
python_code = ".{0}()".format(built_in_table[op])
elif op in sigmoid_table:
print("op in sigmoid table")
python_code = ".apply_sigmoid({0})".format(sigmoid_table[op])
elif op in fn_table: # I'm a little uncertain aboud the distinction between
print("op in fn table") # fn_table vs fn_table2
python_code = ".apply_fn({0})".format(fn_table[op])
elif op in fn_table2:
print("op in fn table 2")
python_code = ".apply_fn({0})".format(fn_table2[op])
elif op in sp_fn_table:
print("op in sp fn table")
python_code = ".apply_sp_fn({0})".format(sp_fn_table[op])
elif op in ket_context_table:
print("op in ket context table")
python_code = ".apply_fn({0},context)".format(ket_context_table[op])
else:
if op == "\"\"":
python_code = ".apply_op(context,\"\")"
elif op == "ops": # short-cut so we don't have to type supported-ops all the damn time!
python_code = ".apply_op(context,\"supported-ops\")"
elif not valid_op(op):
# return ""
# add code so that op2 7 op1 |x> is the same as op2 mult[7] op1 |x>
try:
value = float(op)
python_code = ".multiply({0})".format(op)
except:
if op == '-': # treat - |x> as mult[-1] |x>
python_code = ".multiply(-1)"
else:
return ""
else:
print("op is literal") # NB: we have to be very careful here, or it will cause SQL-injection type bugs!!
python_code = ".apply_op(context,\"{0}\")".format(op) # fix is not hard. Process the passed in op to a valid op form.
print("py:",python_code) # lower+upper+dash+number and thats roughly it.
return python_code
# here is an example of an injection bug (with an earlier version of the code):
# op: era") shoot_me() print("
# op: era") shoot_me() print("
# op is literal
# py: x.apply_op(context,"era") shoot_me() print("")
# Note for the future: is there a cleaner way to do this without the somewhat risky eval?
# x must be a ket or a superposition.
#def process(context,x,ops): # I think the order should be changed to (context,ops,x)
def process(context,ops,x):
line = ops.split()[::-1] # put more advanced processing, and splitting a line into ops later.
code = "x"
for op in line:
multi = op.split("^")
if len(multi) == 2:
print("multi-op",multi[1],"found")
tmp = process_single_op(multi[0])
for k in range(int(multi[1])):
code += tmp
else:
code += process_single_op(op)
if code == "x":
return None
print("python:",code)
return eval(code)
# 17/2/2014:
def extract_leading_ket(s):
try:
head, rest = s.split("|",1)
head = head.strip()
if len(head) == 0:
value = 1
else:
value = float(head)
label, rest = rest.split(">",1)
return ket(label,value), rest
except:
return s
def extract_leading_bra(s):
if s[0] != "<":
return s
try:
label, rest = s[1:].split("|",1)
return bra(label), rest
except:
return s
def old_old_extract_literal_superposition(s):
rest = s
result = superposition()
try:
x, rest = extract_leading_ket(rest)
result.data.append(x)
except:
return result, rest
while True:
try:
null, rest = rest.split("+",1)
x, rest = extract_leading_ket(rest)
result.data.append(x)
except:
return result, rest
def old_extract_literal_superposition(s):
rest = s
result = superposition()
while True:
try:
x, rest = extract_leading_ket(rest)
result.data.append(x)
saved = rest
null, rest = rest.split("+",1)
print("els saved:",saved)
print("els null:",null)
print("null len:",len(null.strip()))
print("els result:",result)
if len(null.strip()) != 0:
print("els null not zero")
return result, saved
except:
print("els final result:",result)
return result, rest
def extract_literal_superposition(s,self_object=None):
rest = s
saved = rest
result = superposition()
while True:
try:
x, rest = extract_leading_ket(rest)
if x.label == "_self":
x.label = self_object # assumes of course that self_object is a string.
result.data.append(x)
except:
return result, saved
try:
saved = rest
null, rest = rest.split("+",1)
# print("els saved:",saved)
# print("els null:",null)
# print("null len:",len(null.strip()))
# print("els result:",result)
if len(null.strip()) != 0:
print("els null not zero")
return result, saved
except:
print("els final result:",result)
return result, rest
# 7/1/2015
# This might help speed up Kevin Bacon numbers.
# Anyway, useful.
# Note a clean superposition is one that has all coeff 1 and implicit.
# |a> + |b> + |c> is a clean superposition.
# 3|a> + 1|b> + |c> is not.
# NB: it does not sub in values for |_self>
# NB: it breaks badly if the superposition is not clean!
def extract_clean_superposition(line):
line = line.rstrip() # in case there is white-space at the end of the line.
r = superposition() # assumes there is never any white-space at the start of the line!
for x in line[1:-1].split("> + |"):
r.data.append(ket(x))
return r
def old_parse_rule_line(C,s):
if s.strip().startswith("--"):
return False
try:
op, rest = s.split("|",1)
op = op.strip()
label, rest = rest.split(">",1)
except:
return False
if op.startswith("--") or op == "supported-ops":
return False
# handle stored_rules:
try:
null, rest = rest.split("#=>",1)
rest = rest.strip()
print("FYI: just learnt this stored rest:" + rest + ":")
rule = stored_rule(rest)
# print("FYI: stored rule worked ...")
C.learn(op,label,rule)
# print("FYI: just learnt this stored rule:",rule)
return True
except Exception as e:
# print("FYI: exception for stored rule")
# print("reason:",e)
pass
add_learn = False
try:
null, rest = rest.split("+=>",1)
add_learn = True
except:
try:
null, rest = rest.split("=>",1)
except:
return False
try: # maybe tweak to handle: O|tmp> => op2 op1 |_self>
rule, null = extract_compound_superposition(C,rest,label)
except:
return False
print("op:",op)
print("label:",label)
print("rest:",rest.rstrip())
print("rule:",rule,"\n")
if op == "" and label == "context":
if len(rule.data) > 0:
name = rule.data[0].label
if name.startswith("context: "):
name = name[9:]
C.set(name)
return True
if not add_learn:
C.learn(op,label,rule)
else:
C.add_learn(op,label,rule)
return True
# 28/7/2014: let's improve parse_rule so that we can learn rules indirectly.
# eg:
# |you> => |Fred>
# age "" |you> => |24>
# another eg:
# |list> => |Sam> + |Mary> + |Liz>
# age "" |list> => |19> -- they are all 19 years old.
# and a more interesting one:
# op-self "" |list> => 13 |_self> -- ie, we need to run ECS for everyone in "" |list>
#
# This function is currently broken!
# age friends (|Fred> + |Sam>) => |age: 20>
# age-self friends split |Fred Sam> => 20 |_self>
# age |person: Fred> => |22>
# All work. Good.
# But:
# |person: Harry> => |bah>
# age|person: Harry> => |bah>
# are broken.
# With this debug info:
# head: |person: Harry>
# tail: |bah>
# op 1: |person: -- this is the problem. It splits on space inside the ket!
# indirect_label 1: Harry>
#
# 29/7/2014: I think it is fixed!
# Using this:
# P S action
# -1 -1 False
# 0 -1 P
# -1 0 S
# 0 0 min(P,S)
#
def parse_rule_line(C,s):
if s.strip().startswith("--"): # filter out comment lines.
return False
try:
head,tail = s.split("=>",1) # split the rule line into text before the rule symbol "=>", and after.
rule_type = head[-1]
if rule_type in ['#','+','!']: # cases to handle:
head = head[:-1] # op |x>#=> ... (yeah, normally a space to separate ket from rule symbol, but valid with no space too!)
else: # op |x>+=> ...
rule_type = ' ' # op |x>=> ...
head = head.strip() # op |x> !=> ... (memoizing rules, new as of 15/2/2015)
tail = tail.strip()
except:
return False
print("head:",head)
print("tail:",tail)
pipe_min = head.find("|")
space_min = head.find(" ")
print("pipe_min: ",pipe_min)
print("space_min:",space_min)
if pipe_min < 0 and space_min < 0: # filter out lines that don't have pipe or space char
return False
if (pipe_min >= 0 and space_min < 0) or (pipe_min >= 0 and space_min >=0 and pipe_min < space_min):
op, rest = head.split("|",1)
indirect_label = "|" + rest
else:
op, indirect_label = head.split(" ",1)
print("op 1:",op)
print("indirect_label 1:",indirect_label)
if op == "supported-ops": # we don't bother learning supported-ops rules. They are auto-generated by learn().
return False
indirect_label, null = extract_compound_superposition(C,indirect_label) # I think this is the appropriate way to call ECS().
print("op 2:",op)
print("indirect_label 2:",indirect_label)
if rule_type == "#": # handle stored rules separately, as they are slightly different from the other two.
print("inside parse_rule_line stored_rule")
rule = stored_rule(tail)
for label in indirect_label: # presumably extract_compound_superposition() always returns a sp.
C.learn(op,label,rule) # look into converting sp's into iterable objects. New python to learn!
return True
if rule_type == "!": # handle stored rules separately, as they are slightly different from the other two.
print("inside parse_rule_line memoizing_rule")
rule = memoizing_rule(tail)
for label in indirect_label:
C.learn(op,label,rule)
return True
add_learn = False
if rule_type == '+':
add_learn = True
try:
for label in indirect_label.data: # NB: indirect_label is a superposition
print("parse_rule_line learn label:",label)
rule, null = extract_compound_superposition(C,tail,label.label) # the last parameter needs to be string, not a ket.
print("parse_rule_line learn rule:",rule)
if op == "" and label.label == "context": # handle context in a special way!
if len(rule.data) > 0:
name = rule.data[0].label
if name.startswith("context: "):
name = name[9:]
C.set(name)
else:
C.learn(op,label,rule,add_learn)
return True
except:
return False
# Now, make use of parse_rule_line()
# load sw file:
def load_sw(c,file):
try:
with open(file,'r') as f:
for line in f:
if line.startswith("exit sw"): # use "exit sw" as the code to stop processing a .sw file.
return
parse_rule_line(c,line) # this is broken! bug found when loading fragment-document.sw fragments
except:
print("failed to load:",file)
# and its brother:
# save current context:
def save_sw(c,name,exact_dump=True):
try:
file = open(name,'w')
file.write(c.dump_universe(exact_dump))
file.close()
except:
print("failed to save:",name)
# save multiverse:
def save_sw_multi(c,name):
try:
file = open(name,'w')
file.write(c.dump_multiverse(True))
file.close()
except:
print("failed to save:",name)
# copied from here:
# http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
def human_readable_size(num):
for x in ['B ','KB','MB','GB','TB']:
if num < 1024.0:
if x == 'B ':
return "%3.0f %s" % (num,x)
else:
return "%3.1f %s" % (num,x)
num /= 1024.0
def broken_human_readable_size(num): # Doh. Gets some answers wrong.
for x in ['B ','KB','MB','GB','TB']: # because "%3.0f" rounds up, and this method does not.
if num < 1024:
return "%3.0d %s" % (num,x)
num //= 1024
import time
# find the stats of a .sw file:
# needs some tweaks yet ...
# works fine, though is hinting at getting slow for large sw files.
def extract_sw_stats(file):
try:
stats = []
context = ""
count = 0
with open(file,'r') as f:
for line in f:
if line.startswith("supported-ops |"):
count += 1
elif line.startswith("|context> => |"):
tmp_context = line[14:].split(">")[0]
if tmp_context.startswith("context: "):
tmp_context = tmp_context[9:]
if len(tmp_context) > 0:
if len(context) > 0 or count > 0:
stats.append(context + " (" + str(count) + ")")
context = tmp_context
count = 0
if len(context) > 0 or count > 0:
stats.append(context + " (" + str(count) + ")")
# now find file size:
size = human_readable_size(os.path.getsize(file))
# now find file date:
date = time.strftime('%d/%m/%Y', time.gmtime(os.path.getmtime(file)))
return date + " " + size + " " + ", ".join(stats)
except:
print("failed to load:",file)
return ""
# we need code to handle the input in the semantic-agent console:
# we have three cases to handle:
# op3 op2 op1 # use x as the implicit ket # currently handled by process(c,line,x)
# op-b op-a |x> # specifiy |x> # currently not handled
# op |x> => 3|a> + |b> # learn rule # currenlty handled by parse_rule_line(C,line).
def old_process_input_line(C,line,x):
if not parse_rule_line(C,line):
try:
op, rest = line.split("|",1)
except:
return process(C,line,x)
try:
op = op.strip()
label, rest = rest.split(">",1)
return process(C,op,ket(label))
except:
return
return
def process_input_line(C,line,x):
if not parse_rule_line(C,line):
try:
result, null = extract_compound_superposition(C,line)
return result
except:
return process(C,line,x)
def process_op_ket(C,line,left_label=None):
try:
op, rest = line.split("|",1)
op = op.strip()
label, rest = rest.split(">",1)
if label == "_self" and left_label is not None:
label = left_label
return process(C,op,ket(label)), rest
except:
return None
# eg: intersection(op|X>,op|Y>)
def old_process_function(C,line):
try:
fn, rest = line.split("(",1)
fn = fn.strip()
print("fn:",fn)
sp1, rest = process_op_ket(C,rest) # sp is short for superposition
print("sp1:",sp1)
null, rest = rest.split(",",1)
sp2, rest = process_op_ket(C,rest)
print("sp2:",sp2)
null, rest = rest.split(")",1)
print("rest:",rest)
except:
return None
# return intersection(sp1,sp2)
code = "{0}(sp1,sp2)".format(fn) # this is seriously dangerous for injection attacks, ATM.
print("python:",code)
return eval(code)
# dummy len 1 fn:
def sp_len_1(x):
return ket("sp") + x
# white listed functions that take 1 parameter:
whitelist_table_1 = {
# "dump" : "C.dump_sp_rules", # buggy since, it returns a string! Not a ket/sp.
"sp" : "sp_len_1",
# "to-number" : "category_number_to_number", # I think this is better in the ket->ket section.
# "discrimination" : "discrimination", # probably ditto.
# "discrim" : "discrimination", # nah. That way leads to bugs. Belongs here.
# Heh. Added it to ket/sp classes. It belongs there now.
# "read-letters" : "read_letters", # try this in sp_fn_table above.
# "read-words" : "read_words", # yup. This one too. This table is almost always the wrong place for functions!
}
# whitelisted functions, that take 2 parameters:
whitelist_table_2 = {
"intersection" : "intersection",
"intn" : "intersection",
"common" : "intersection", # this is for those that haven't studied maths.
"union" : "union", # though if they haven't this work won't make much sense anyway!
"mult" : "multiply",
"multiply" : "multiply", # for when you are not lazy :)
"addition" : "addition",
"simm" : "simm",
"silent-simm" : "silent_simm",
"weighted-simm" : "weighted_simm", # hrmm... I thought this took 3 parameters, not 2!
"nfc" : "normed_frequency_class", # pretty unlikely this will be used at command line since needs freq lists.
"ket-nfc" : "ket_normed_frequency_class",
# "apply" : "apply", # 10/11/2014: What is this function?? Commented out!
"range" : "show_range",
"ket-simm" : "ket_simm",
"to-base" : "decimal_to_base",
"general-to-specific" : "general_to_specific",
# 4/1/2015:
"equal" : "test_equal",
# 22/2/2015:
"ED" : "Euclidean_distance",
# 26/2/2015:
"mbr" : "mbr",
"measure" : "mbr",
# 9/4/2015:
"subset" : "subset",
}