forked from GarryMorrison/Feynman-knowledge-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththe_semantic_db_code.py
1824 lines (1512 loc) · 57.2 KB
/
the_semantic_db_code.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
#!/usr/bin/env python
#######################################################################
# the semantic-db class implementation file
#
# Author: Garry Morrison
# email: garry -at- semantic-db.org
# Date: 2014
# Update: 5/8/2015
# Copyright: GPLv3
#
# Usage:
#
#######################################################################
import sys
import random
import copy
import re
from operator import mul
# put this here for now:
# http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort
# 6/8/2014: Doh! There is a bug in sorting things like 0 vs 00 vs 000.
def natural_sorted(list, key=lambda s:s):
"""
Sort the list into natural alphanumeric order.
"""
def get_alphanum_key_func(key):
convert = lambda text: int(text) if text.isdigit() else text
return lambda s: [convert(c) for c in re.split('([0-9]+)', key(s))]
sort_key = get_alphanum_key_func(key)
# list.sort(key=sort_key)
return sorted(list,key=sort_key)
# 4/3/2015: I hate when integers are displayed as floats. Sorry, pet peeve.
# convert float to int if possible:
def float_to_int(x,t=3):
if float(x).is_integer():
return str(int(x))
# return str("%.3f" % x)
return str(round(x,t))
# NB: I have not yet normalized kets vs superpositions in terms of supported functions.
# The basics are covered, but there are still gaps I'm too lazy to fill, ATM.
class ket(object):
def __init__(self,label='?',value=1):
self.label = label
self.value = float(value) # perhaps look into decimal type.
# http://docs.python.org/2/library/decimal.html
# nah. float seems appropriate.
def __str__(self):
return self.display()
def __len__(self):
# return 1 # maybe if self.label == "", return 0?
if self.label == '':
return 0
return 1
# 6/1/2014: finally implement iterator.
def __iter__(self):
yield ket(self.label,self.value)
def type(self):
return "ket"
def old_display(self):
if self.value == 1:
return '|' + self.label + '>'
else:
return str(self.value) + '|' + self.label + '>'
# probably slower. Need to do a speed test, and see if significant.
# tweaked for exact display, so dump to file and load again don't accidentally zero coeffs.
def display(self,exact=False):
if self.value == 1:
return "|{0}>".format(self.label)
elif exact:
return str(self.value) + '|' + self.label + '>'
else:
# return "{0:.3f}|{1}>".format(self.value,self.label)
return float_to_int(self.value,3) + '|' + self.label + '>'
def long_display(self):
# return self.display()
if self.value == 1:
return self.label
else:
return str("%.3f" % self.value) + ' ' + self.label
def readable_display(self):
if self.label == '':
return ""
if self.value == 1:
return self.label
else:
if self.value.is_integer():
return "{0:.0f} {1}".format(self.value,self.label)
return "{0:.2f} {1}".format(self.value,self.label)
def transpose(self):
return bra(self.label,self.value)
def __add__(self,x):
return superposition() + self + x
# 14/1/2015:
# I think this is right ...
def clean_add(self,x):
return (superposition() + self).clean_add(x)
def apply_bra(self,a_bra):
return apply_bra_to_ket(a_bra,self)
# maybe an apply_projection too?
def probably_buggy_apply_fn(self,fn,t1=None,t2=None): # Bug? What happens if the result is |> or contains |>?
if t1 == None: # Bug? What happens if fn() is a superposition?
return fn(self)
elif t2 == None:
return fn(self,t1)
else:
return fn(self,t1,t2)
def apply_fn(self,fn,t1=None,t2=None): # Bug? What happens if the result is |> or contains |>?
#print("boop")
result = fast_superposition()
if t1 == None: # Bug? What happens if fn() is a superposition?
r = fn(self)
elif t2 == None:
r = fn(self,t1)
else:
r = fn(self,t1,t2)
return (result + r).superposition()
def apply_fn_collapse(self,fn,t=None):
if t == None:
return fn(self)
return fn(self,t)
def apply_sp_fn(self,fn,t1=None,t2=None,t3=None,t4=None):
if t1 == None:
return fn(self)
elif t2 == None:
return fn(self,t1)
elif t3 == None:
return fn(self,t1,t2)
elif t4 == None:
return fn(self,t1,t2,t3)
else:
return fn(self,t1,t2,t3,t4)
# need to check this works. # seems to.
def apply_naked_fn(self,fn,t1=None,t2=None,t3=None):
if t1 == None:
return fn()
elif t2 == None:
return fn(t1)
elif t3 == None:
return fn(t1,t2)
else:
return fn(t1,t2,t3)
def apply_op(self,context,op):
return context.recall(op,self,True) # see much later in the code for definition of recall.
# apply the same op more than once.
# especially useful for networks.
def apply_op_multi(self,context,op,n):
result = copy.deepcopy(self)
for k in range(n):
result = result.apply_op(context,op)
return result
def select_elt(self,k):
if k != 1 and k != -1:
return ket("",0)
else:
return ket(self.label,self.value)
# 5/2/2015: eg: without this: select[1,5] "" |bah> bugs out if "" |bah> is not defined.
# seems to work!
def select_range(self,a,b):
if a <= 1 <= b:
return ket(self.label,self.value)
return ket("",0)
def pick_elt(self):
return ket(self.label,self.value)
def weighted_pick_elt(self):
return ket(self.label,self.value)
def find_index(self,one):
label = one.label if type(one) == ket else one
if self.label == label:
return 1
return 0
def find_value(self,one):
label = one.label if type(one) == ket else one
if self.label == label:
return self.value
return 0
def find_max_coeff(self):
return self.value
def find_min_coeff(self):
return self.value
def normalize(self,t=1):
result = copy.deepcopy(self)
if result.value > 0:
result.value = t
return result
def rescale(self,t=1):
result = copy.deepcopy(self)
if result.value > 0:
result.value = t
return result
def multiply(self,t):
return ket(self.label,self.value*t)
# 6/1/2015: hrmm... maybe abs, absolute_noise, and relative_noise should be sigmoids!
# newly added 2/4/2014:
# yeah. moved to sigmoid (4/5/2015) Hope we don't break anything!
# def abs(self):
# return ket(self.label,abs(self.value))
# newly added 7/4/2014:
# add noise to the ket/sp in range [0,t]
def absolute_noise(self,t):
return ket(self.label,self.value + random.uniform(0,t)) # hrmm.. so noise is additive only?
# newly added 7/4/2014:
# add noise to ket/sp in range [0,t*max_coeff]
def relative_noise(self,t):
max_coeff = self.value
return ket(self.label,self.value + random.uniform(0,t*max_coeff))
def coeff_sort(self):
return ket(self.label,self.value)
def ket_sort(self):
return ket(self.label,self.value)
def find_max_coeff(self):
return self.value
def find_min_coeff(self):
return self.value
def number_find_max_coeff(self):
return ket("number: " + str(self.value))
def number_find_min_coeff(self):
return ket("number: " + str(self.value))
def discrimination(self):
return ket(" ",self.value)
# 24/2/2015:
# implements discrim-drop[t] SP
# ie: if discrim is > t return |>, else return value.
# don't know how I want this to work!
def discrimination_drop(self,t):
return ket(self.label,self.value)
# sigmoids apply to the values of kets, and leave ket labels alone.
def apply_sigmoid(self,sigmoid,t1=None,t2=None):
result = copy.deepcopy(self)
if t1 == None:
result.value = sigmoid(result.value)
elif t2 == None:
result.value = sigmoid(result.value,t1)
else:
result.value = sigmoid(result.value,t1,t2)
return result
# do we need a superposition version of this? Probably...
# implements: similar[op] |x>
def old_similar(self,context,op): # should I use .apply_op(context,op,True)?
f = self.apply_op(context,op) # use apply_op or context.recall() directly?
print("f:",f.display()) # in light of active=True thing, apply_op() seems the right answer.
# return context.pattern_recognition(f,op) # yeah, but what about in pat_rec?
return context.pattern_recognition(f,op).delete_ket(self) # we delete self, ie |x>, from the result, since it is always a 100% match anyway.
# 23/2/2015:
# implements: similar[op1,op2] |x>
def similar(self,context,ops):
try:
op1,op2 = ops.split(',')
except:
op1 = ops
op2 = ops
f = self.apply_op(context,op1)
return context.pattern_recognition(f,op2).delete_ket(self) # we delete self, ie |x>, from the result, since it is always a 100% match anyway.
# 23/2/2015:
# implements: self-similar[op1,op2] |x>
# ie don't delete |x>
def self_similar(self,context,ops):
try:
op1,op2 = ops.split(',')
except:
op1 = ops
op2 = ops
f = self.apply_op(context,op1)
return context.pattern_recognition(f,op2)
# implements: find-topic[op] |x>
def find_topic(self,context,op):
return context.map_to_topic(self,op)
# 2/4/2015: intn-find-topic[op] |a b c>
# this goes some way to a search engine.
# currently we don't have a superposition version of this. Not sure it is needed.
#
def intn_find_topic(self,context,op):
words = self.label.lower().split()
print("words:",words)
if len(words) == 0:
return ket("",0)
results = [context.map_to_topic(ket(x),op) for x in words]
print("len results:",len(results))
if len(results) == 0: # this should never be true!
return ket("",0)
r = results[0]
for sp in results:
print("sp:",sp)
r = intersection(r,sp)
return r.normalize(100).coeff_sort()
# implement op3 op2 op1 |x> # this is actaully also "matrix multiplication", of sorts.
def merged_apply_op(self,context,ops):
result = copy.deepcopy(self)
for op in ops.split()[::-1]:
# print("op:",op)
result = result.apply_op(context,op)
return result
def count(self):
# return 1
# 4/1/2015 tweak:
if self.label == "":
return 0
return 1
def count_sum(self):
return self.value
def number_count(self):
# return ket("number: 1")
# 4/1/2015 tweak:
if self.label == "":
return ket("number: 0")
return ket("number: 1")
def number_count_sum(self):
return ket("number: " + float_to_int(self.value))
def drop(self):
if self.value > 0:
return ket(self.label,self.value)
else:
return ket("",0)
def drop_below(self,t):
if self.value >= t:
return ket(self.label,self.value)
else:
return ket("",0)
def drop_above(self,t):
if self.value <= t:
return ket(self.label,self.value)
else:
return ket("",0)
# I'm using this in show_range, arithemetic etc, so can feed in sp or ket.
# deprecated. Now use x.the_label()
# usage: X.ket()
# the other half is in superposition.
def ket(self):
return ket(self.label,self.value)
def the_label(self):
return self.label
def the_value(self):
return self.value
def activate(self,context=None,op=None,self_label=None):
return ket(self.label,self.value) # not sure if we need this:
#return self # or if this will suffice.
# 4/1/2015:
def is_not_empty(self):
print("ket is-not-empty:",self)
if self.label == "":
return ket("no")
return ket("yes")
class bra(object):
def __init__(self,label='?',value=1):
self.label = label
self.value = float(value)
def __str__(self):
return self.display()
def type(self):
return "bra"
def old_display(self):
if self.value == 1:
return '<' + self.label + '|'
else:
return '<' + self.label + '|' + str(self.value)
def display(self): # do we need an "exact" option here?
if self.value == 1:
return "<{0}|".format(self.label)
else:
return "<{0}|{1:.3f}".format(self.label,self.value)
def transpose(self):
return ket(self.label,self.value)
# also at some stage I suppose a transpose of a superposition.
# so I guess we would need to distinguish between a bra-superposition and a ket-superposition.
def transpose(x):
return x.transpose()
# need to think on how we want |> and <| to behave.
# eg, currently <*||> returns 1. May want 0.
def labels_match(label_1,label_2):
print("label_1:",label_1)
print("label_2:",label_2)
truth_var = True
one = label_1.lower() # make label compare case insensitive
two = label_2.lower() # hrrmm... may not want this ....
if one[0] == '!': # for now only consider bra's with <!x| rather than kets |!x>
one = one[1:] # though it is not much work to extend it.
truth_var = False
print("one:",one)
print("two:",two)
if one == two:
return truth_var
a_cat = one.split(': ')
b_cat = two.split(': ')
if a_cat[-1] == '*':
new_a_cat = a_cat[:-1]
new_b_cat = b_cat[:len(new_a_cat)]
if new_a_cat == new_b_cat:
return truth_var
else:
return not truth_var
if b_cat[-1] == '*':
new_b_cat = b_cat[:-1]
new_a_cat = a_cat[:len(new_b_cat)]
if new_b_cat == new_a_cat:
return truth_var
else:
return not truth_var
return not truth_var
# 25/3/2014 added label_descent()
# Pretty sure it is correct.
def label_descent(x):
print("x:",x)
result = [x]
if x == "*":
return result
if x.endswith(": *"):
x = x[:-3]
while True:
try:
x,null = x.rsplit(": ",1)
result.append(x + ": *")
except:
result.append("*")
return result
# 18/1/2015: could probably tidy this!
# and I think, in a lot of use cases we don't even need it!
# also, should it be here, or in the functions file?
def extract_category_value(label):
one = label.split(': ')
value = one[-1]
category = ": ".join(one[:-1])
return category, value
def apply_bra_to_ket(a_bra,a_ket):
if type(a_bra) == str: # this is so we don't need bra("person: Fred") everywhere.
a_bra = bra(a_bra) # we can use "person: Fred" directly.
# maybe the same conversion from string for a_ket??
elif type(a_bra) == ket: # this so we can fudge and pass in a ket that acts like a bra.
a_bra = bra(a_bra.label,a_bra.value)
star = "*"
if a_bra.value == 1 or a_ket.value == 1:
star = ""
print(a_bra.display() + star + a_ket.display())
if labels_match(a_bra.label,a_ket.label):
return a_bra.value * a_ket.value
else:
return 0
class superposition(object):
def __init__(self):
self.data = []
def __str__(self):
return self.display()
def __len__(self):
if len(self.data) == 1: # if sp is |> then return lenght= 0
if self.data[0].label == "": # given how the rest of the project handles |> probably never gets touched, but anyway, good just in case.
return 0
return len(self.data)
def type(self): # seems to be broken in console.
return "(" + " + ".join(x.type() for x in self.data) + ")" # just returns |>
def add_ket(self,a_ket):
if a_ket.label == '': # treat |> as the identity ket
return
match = None
for x in self.data:
if x.label == a_ket.label:
match = True
x.value += a_ket.value
break
if match == None:
new_ket = ket(a_ket.label,a_ket.value)
self.data.append(new_ket)
def __add__(self,elt):
result = copy.deepcopy(self)
if type(elt) == ket:
result.add_ket(elt)
if type(elt) == superposition:
for x in elt.data:
result.add_ket(x)
return result
# 6/1/2015:
def __iter__(self): # finally wrote an iterator for superpositions!
for x in self.data:
yield x
# a version of add that does not add kets with the same label
def clean_add_ket(self,a_ket):
if a_ket.label == '':
return
# if len([x.label for x in self.data if x.label == a_ket.label]) == 0:
if sum(1 for x in self.data if x.label == a_ket.label) == 0:
self.data.append(ket(a_ket.label,a_ket.value))
# same as above, but also works for superpositions:
def clean_add(self,one):
if type(one) == ket:
self.clean_add_ket(one)
if type(one) == superposition:
for x in one.data:
self.clean_add_ket(x)
def display(self,exact=False):
if len(self.data) == 0:
return '|>'
return " + ".join(x.display(exact) for x in self.data)
# LOL. Currently is never invoked, the ket version gets called instead!
# Maybe need to tweak which table to use in the processor.
def long_display(self):
if len(self.data) == 0:
return '|>'
# return "\n".join(str("%.3f" % x.value) + ' |' + x.label + '>' for x in self.data)
# let's do a tidier one, we don't need ket label wrappers here!
# tmp change to number of sig figures:
# return "\n".join(str("%.3f" % x.value) + ' ' + x.label for x in self.data)
return "\n".join(str("%.1f" % x.value) + ' ' + x.label for x in self.data)
# Hrmm.. meant to be more readable, but not so much!
def readable_display(self):
if len(self.data) == 0:
return ""
return ", ".join(x.readable_display() for x in self.data)
def apply_bra(self,a_bra):
return sum(apply_bra_to_ket(a_bra,x) for x in self.data)
# maybe a version where the projection is of more than one element?
def apply_projection(self,a_bra):
if len(self.data) == 0:
return 0 # should this be ket("")? Or ket("",0)
result = copy.deepcopy(self)
for x in result.data:
x.value = apply_bra_to_ket(a_bra,x)
return result
# we don't need the next two.
# use apply_fn(extract_value), and apply_fn(extract_category), and apply_fn(apply_value) instead.
# def apply_extract_value(self):
# result = copy.deepcopy(self)
## result.data = [x.apply_extract_value() for x in result.data ]
# result.data = [extract_value(x) for x in result.data ]
# return result
# def apply_extract_category(self):
# result = copy.deepcopy(self)
## result.data = [x.apply_extract_category() for x in result.data ]
# result.data = [extract_category(x) for x in result.data ]
# return result
# for the family of functions that apply to kets.
# mapping ket -> ket.
# this is buggy if fn(x) actually returns a superposition!
# it sort of works, but creates wierd bugs down the line.
# Now, if we had a mixed type that can handle lists of not just
# kets, but superpositions, sequences, and everything else, then it would be fine.
def buggy_apply_fn(self,fn):
result = superposition()
result.data = [fn(x) for x in self.data ] # this behaviour is more inline of what you would
return result # expect from the sequence type (not yet implemented!)
# let's try and write a non-buggy version, but without needing to collapse the kets.
def also_buggy_apply_fn(self,fn,t1=None,t2=None): # maybe an apply_ket_fn, and apply_sp_fn?
result = superposition()
for x in self.data:
if t1 == None:
r = fn(x)
elif t2 == None:
r = fn(x,t1)
else:
r = fn(x,t1,t2)
if type(r) == ket: # this code is ugly, and I suspect buggy!
result.data.append(r) # with fast_sp, should be able to fix this mess!
if type(r) == superposition:
result.data += r.data # this line looks buggy!!!
return result
def still_buggy_apply_fn(self,fn,t1=None,t2=None):
result = superposition()
for x in self:
if t1 == None:
r = fn(x)
elif t2 == None:
r = fn(x,t1)
else:
r = fn(x,t1,t2)
for elt in r:
# result.data.append(elt) # BUGGY! Because we side-stepped "result += elt" we also
# side-stepped checking for |>. This bug probably elsewhere too!
# option a: # swapping in fast_sp should help, since then we can use "result += elt"
# result += elt
# option b:
if elt.label != '':
result.data.append(elt) # pretty sure this is broken! that's why "push-float pop-float (|number: 3> + 2|number: 5> + 7|number: 6>)" doesn't work as expected.
return result
def apply_fn(self,fn,t1=None,t2=None):
#print("beep")
result = fast_superposition()
for x in self:
if t1 == None:
r = fn(x)
elif t2 == None:
r = fn(x,t1)
else:
r = fn(x,t1,t2)
for elt in r:
result += elt
return result.superposition()
# define a function that maps sp -> sp, instead of ket -> ket/sp.
# now we need to 1) add it to ket class, and 2) wire it into the processor.
# 5/2/2015: starting to wonder if there is a tidier way to do this!!
def apply_sp_fn(self,fn,t1=None,t2=None,t3=None,t4=None):
if t1 == None:
return fn(self)
elif t2 == None:
return fn(self,t1)
elif t3 == None:
return fn(self,t1,t2)
elif t4 == None:
return fn(self,t1,t2,t3)
else:
return fn(self,t1,t2,t3,t4)
# need to check this works!
# 27/6/2014: hrmm... so let me get this right, a sp_fn applies to the applied superposition.
# and naked_fn ignores any passed in superpositions.
def apply_naked_fn(self,fn,t1=None,t2=None,t3=None):
if t1 == None:
return fn()
elif t2 == None:
return fn(t1)
elif t3 == None:
return fn(t1,t2)
else:
return fn(t1,t2,t3)
# keep this variant distinct from apply_fn(fn) for now.
# also, now fn can map ket -> ket, and also ket -> superposition.
def apply_fn_collapse(self,fn,t=None):
result = superposition()
if t == None:
for x in self.data:
result += fn(x)
else:
for x in self.data:
result += fn(x,t)
return result
# if there are repeated elements in the superposition, add them up.
# This is buggy, some of the time! Look into it!
# I think it might just be the apply_fn() with fn() returning a superposition, is the bug.
# Yup. The bug was in apply_fn(). Fixed now.
# eg, ((ket) + (ket + ket + ket + ket) + (ket + ket))
# would cause collapse() to fail.
def collapse(self):
return superposition() + self
def apply_op(self,context,op):
result = superposition()
for x in self.data:
result += context.recall(op,x,True) # should this be apply_op() instead?
return result
# apply the same op more than once.
# especially useful for networks.
def apply_op_multi(self,context,op,n):
result = copy.deepcopy(self)
for k in range(n):
result = result.apply_op(context,op)
return result
def count(self):
# if len(self.data) == 1 and ... # do we need code to implement "count |> == |number: 0>" here? For now nope, see if it bugs eventually!
return len(self.data) # Indeed, |> as identity element may mean (not certain) that it never comes up.
def count_sum(self):
return sum(x.value for x in self.data)
def number_count(self):
result = len(self.data)
return ket("number: " + str(result))
def number_count_sum(self):
result = sum(x.value for x in self.data) # does this bug out if len(self.data) == 0?
return ket("number: " + float_to_int(result))
def product(self): # need to put these in ket now.
r = 1
for x in self.data:
r *= x.value
return r
def number_product(self):
r = 1
for x in self.data:
r *= x.value
return ket("number: " + str(r))
def drop(self):
result = copy.deepcopy(self)
result.data = [x for x in result.data if x.value > 0 ]
return result
def drop_below(self,t):
result = copy.deepcopy(self)
result.data = [x for x in result.data if x.value >= t ]
return result
def drop_above(self,t):
result = copy.deepcopy(self)
result.data = [x for x in result.data if x.value <= t ]
return result
# NB: we use: 1 <= k <= len, not 0 <= k < len to access ket objects.
# NB: though we still use -1 for the last element, -2 for the second last element, etc.
# 3/11/2014: hrmm... is this wired into the processor yet?
def select_elt(self,k):
# result = copy.deepcopy(self)
# if k >= 1 and k <= len(result.data):
# result.data = [result.data[k - 1]]
# else:
# result.data = []
# return result
if k >= 1 and k <= len(self.data):
return copy.deepcopy(self.data[k - 1])
elif k < 0:
return copy.deepcopy(self.data[k])
else:
return ket("",0)
# now with the change to select_elt(k), if you want to select a single elt, but still return a superposition,
# you need to do select_range(k,k).
# what if we want to index from the end of the list? cf, tail -3 or something?
def select_range(self,a,b):
a = max(1,a) - 1
b = min(b,len(self.data))
result = superposition()
result.data = copy.deepcopy(self.data[a:b])
return result
def delete_elt(self,k):
result = copy.deepcopy(self)
result.data = [x for i,x in enumerate(result.data) if i != (k-1) ]
return result
# maybe a version of this that takes into account the coeffs, and makes a weighted random choice.
# Yeah. For a start, see: http://stackoverflow.com/questions/3679694/a-weighted-version-of-random-choice
# Yup. This looks good: (BTW, what happens if coeffs are < 0?)
# def weighted_choice(choices):
# total = sum(w for c, w in choices)
# r = random.uniform(0, total)
# upto = 0
# for c, w in choices:
# if upto + w > r:
# return c
# upto += w
# assert False, "Shouldn't get here"
#
#
# 14/6/2015: broken! If self.data is the empy list it triggers an exception.
# also, we really don't need to copy the entire superposition, and then return only one of them.
# fixed version just below
def broken_pick_elt(self): # has some similarity with wave-fn collapse in QM.
result = copy.deepcopy(self)
return random.choice(result.data)
def pick_elt(self):
if len(self) == 0:
return ket("",0)
return copy.deepcopy(random.choice(self.data))
def weighted_pick_elt(self): # quick test in the console, looks to be roughly right.
if len(self) == 0:
return ket("",0)
total = sum(x.value for x in self)
r = random.uniform(0,total)
upto = 0
for x in self:
w = x.value
if upto + w > r:
return x
upto += w
assert False, "Shouldn't get here"
# NB: this is case sensitive, since |x> != |X>
# NB: in some cases find_index() gives very different answers than set_mbr(), in terms of yes or no of membership.
# It basically boils down to:
# labels_match(x.label,label) vs x.label == label (first is used, indirectly, in set_mbr(), second in find_index() )
#
# Also recall:
## test for set membership of |x> in |X>
#def set_mbr(x,X,t=1):
# return X.apply_bra(x) >= t
#
def find_index(self,one):
label = one.label if type(one) == ket else one
for k,x in enumerate(self.data):
if x.label == label:
return k + 1
return 0 # yeah, 0 for not in the superposition.
def find_value(self,one):
label = one.label if type(one) == ket else one # maybe a version for when one is a superposition?
for x in self.data:
if x.label == label:
return x.value
return 0
def delete_ket(self,one): # do we need a delete_sp() too?
result = copy.deepcopy(self)
result.data = [x for x in result.data if x.label != one.label ]
return result
def normalize(self,t=1):
result = copy.deepcopy(self)
the_sum = sum(x.value for x in result.data)
if the_sum > 0:
for x in result.data:
x.value = t*x.value/the_sum
return result
def rescale(self,t=1):
if len(self.data) == 0:
return ket("")
result = copy.deepcopy(self)
the_max = max(x.value for x in result.data)
if the_max > 0:
for x in result.data:
x.value = t*x.value/the_max
return result
def multiply(self,t):
result = copy.deepcopy(self)
for x in result.data:
x.value = x.value*t
return result
# 6/1/2015: again, abs, absolute_noise and relative_noise should be sigmoids. Pretty sure!
# OK. Abs and absolute_noise we can certainly migrate to sigmoids.
# But relative-noise needs to know max_coeff, which is impossible with sigmoids.
# So just abs in sigmoids I guess.
# newly added 2/4/2014:
def abs(self): # probably rare use given coeffs are meant to be >= 0
result = copy.deepcopy(self)
for x in result.data:
x.value = abs(x.value)
return result
# newly added 7/4/2014:
# add noise to the ket/sp in range [0,t]
def absolute_noise(self,t):
result = copy.deepcopy(self)
for x in result.data:
x.value = x.value + random.uniform(0,t)
return result
# newly added 7/4/2014:
# add noise to ket/sp in range [0,t*max_coeff]
def relative_noise(self,t):
max_coeff = self.find_max_coeff()
result = copy.deepcopy(self)
for x in result.data:
x.value = x.value + random.uniform(0,t*max_coeff)
return result
def reverse(self):
result = copy.deepcopy(self)
result.data.reverse()
return result
def shuffle(self):
result = copy.deepcopy(self)
random.shuffle(result.data)
return result
# with thanks to this page: https://wiki.python.org/moin/HowTo/Sorting
# maybe we want the reverse, biggest first, not last?
def coeff_sort(self):
result = superposition()
# result.data = sorted(self.data, key=lambda x: x.value)
result.data = sorted(self.data, key=lambda x: x.value,reverse=True)
return result
def ket_sort(self):
result = superposition()
# result.data = sorted(self.data, key=lambda x: x.label.lower())
# result.data = sorted(self.data, key=lambda x: x.label.lower(),reverse=False)
# 22/5/2014: let's try for a natural sort: Woot! It works!
result.data = natural_sorted(self.data, key=lambda x: x.label.lower())
return result
def find_max_elt(self):
if len(self.data) == 0:
return ket("",0)
the_max = max(x.value for x in self.data)
for x in self.data:
if x.value == the_max: