-
Notifications
You must be signed in to change notification settings - Fork 0
/
Entanglement.pm
executable file
·1329 lines (1098 loc) · 40.3 KB
/
Entanglement.pm
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
package Quantum::Entanglement;
use strict;
use warnings;
use Carp;
BEGIN {
use Exporter ();
use Math::Complex;
my @M_Complex = qw(i Re Im rho theta arg cplx cplxe);
our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
$VERSION = 0.32;
@ISA = qw(Exporter);
@EXPORT = qw(&entangle &p_op &p_func &q_logic
&save_state &restore_state);
%EXPORT_TAGS = (DEFAULT => [@EXPORT],
complex => [@M_Complex],
QFT => [qw(&QFT)],);
@EXPORT_OK = (@M_Complex, '&QFT');
}
our (@EXPORT_OK, @EXPORT);
$Quantum::Entanglement::destroy = 1; # true=> p(0) states stomped on
$Quantum::Entanglement::conform = 0; # true=> strives for truth when observing
## Contents:
# Constructors
# Utility Routines
# Overload table
# Overload routines
# parallel operators and functions
# methods for saving and restoring state
# pod
# =begin pretty pictures
#
# Things look a bit like this...
#
# $variable = [ref to var which itself refs to an annon array (the universe),
# offset of values of variable within universe,
# ref to var which itself refs to an annon array (the offsets)];
#
# $offsets = [refs to all the offsets in a given universe, ...]
# $universe= [ [prob1,val1,prob2,val2],
# [prob1,val1,prob2,val2], etc. ]
#
# =cut
# creates a new set of universes
sub _new {
my $universe = [];
my $offsets = [];
my $var = [\$universe,1,\$offsets];
$offsets->[0] = \ $var->[1];
while (@_) {
push @$universe, [shift,shift];
}
bless $var, 'Quantum::Entanglement';
return $var;
}
# add a variable without adding values (ie. a derived value)
# returns the new variable
sub _add {
my $current = $_[0];
my $universe = ${ $current->[0]};
my $offset = scalar(@{$universe->[0]}) + 1;
my $var= [\$universe,$offset,\ ${$current->[2]}];
push @{${$current->[2]}} , \$var->[1];
bless $var, 'Quantum::Entanglement';
return $var;
}
# joins together two previously unconnected universes
# takes two variables as args, gets the universes from those.
# should be used to modify objects in place.
sub _join {
my ($uni1,$uni2) = (${$_[0]->[0]},${$_[1]->[0]});
return () if $uni1 == $uni2;
my $universe = [];
foreach my $s2 (@$uni2) {
foreach my $s1 (@$uni1) {
push @$universe, [@$s1,@$s2];
}
}
my $offsets1 = ${$_[0]->[2]};
my $offsets2 = ${$_[1]->[2]};
my $extra = scalar(@{$uni1->[0]});
push @$offsets1, map {$$_+=$extra; $_} @$offsets2;
${$_[1]->[2]} = $offsets1;
${$_[0]->[0]} = $universe;
${$_[1]->[0]} = $universe;
return (1);
}
# exported constructor
sub entangle {
return _new(@_);
}
## Utility routines
# a view of global state space, might still show historical states which
# are no longer accessable, does not count as observation
sub show_states {
my $rt;
my $var = shift;
my $universe = ${$var->[0]};
if ($_[0]) {
foreach (@$universe) { my $t;
$rt .= (++$t % 2) ? "$_|" : overload::StrVal($_).">\t" foreach @$_;
$rt .= "\n";
}
}
else {
my $os = $var->[1];
$rt .= $_->[$os-1]."|".overload::StrVal($_->[$os]).">\t"
foreach @$universe;
substr($rt,-1,1,"\n");
}
return $rt;
}
# egads! (and don't tell anyone about the grep, it's a secret)
sub DESTROY {
my ($universe, $offsets) = (${$_[0]->[0]}, ${$_[0]->[2]});
my $os = $_[0]->[1];
splice(@$_,$os-1,2) foreach @$universe;
@$offsets = grep {if ($$_ != $os) {$$_ -= 2 if $$_ > $os;1;} else {0;}}
@$offsets;
_rationalise_states([\$universe])
if $Quantum::Entanglement::destroy;
}
# takes two non normalised probabilities and returns true with prob(1/1+2)
sub _sel_output {
my ($c, $d) = @_;
$c = abs($c)**2;
$d = abs($d)**2;
return rand(1) < ($c/($c+$d)) ? 1 : 0;
}
# Gets a ref to a hash of complex probs, produces ref to hash of sequential
# probs and ref to array of ordering.
sub _normalise {
my $hr = $_[0];
my $h2 = {};
my $muts = [keys %{$hr}];
my $sum = 0;
foreach (values %{$hr}) {
$sum += abs($_)**2;
}
if ($sum <= 0) {
croak "$0: Cannot behave probabilistically with -ve probs";
}
else {
my $cum;
@{$h2}{ @{$muts} } = map {$cum +=abs($_)**2;
$cum / $sum } @{$hr}{ @{$muts} };
return ($h2, $muts);
}
}
# this builds up a multi-layered hash so as to find the unique sets of
# states, it then uses _unravel to get them back out of the hash
sub _rationalise_states {
my $universe = ${$_[0]->[0]};
my $len = scalar(@{$universe->[0]})/2;
my @p_os = map {$_*2 } (0..$len-1);
my @v_os = map {$_*2+1} (0..$len-1);
my $foo = {};
foreach my $state (@$universe) { # build an icky data structure
my $tref = $foo;
foreach (@v_os) {
my $val = ref($state->[$_]) ? overload::StrVal($state->[$_])
: $state->[$_];
if ($_==2*$len-1) { # last level of the structure
if (exists $tref->{$val}) {
my @temp = @{$state}[@p_os];
$_+=shift @temp foreach @{$tref->{$val}}[@p_os];
}
else {
$tref->{$val} = [@{$state}];
}
}
else { # an intermediate level
if (exists $tref->{$val}) {
$tref = $tref->{$val};
}
else {
$tref = $tref->{$val} = {};
}
}
}
}
# do something with it...
@$universe =();
while (1) {
my $aref = _unravel($foo);
last unless $aref;
push @$universe, $aref;
}
return $universe;
}
sub _unravel {
my $tref = $_[0];
return undef unless (scalar keys %$tref);
my @hrs;
my($last_ref, $val);
do {
$last_ref = $tref;
($val,$tref) = %$tref;
unshift @hrs, $val, $last_ref;
} until (ref($tref) eq 'ARRAY');
delete ${$last_ref}{$val};
splice @hrs, 0,2;
while (@hrs) {
my $val = shift @hrs;
my $h = shift @hrs;
delete ${$h}{$val} if scalar(keys %{${$h}{$val}}) < 1;
}
return $tref;
}
##
# Overloading. Everything except for assignment operators
# are overloaded specifically. Need to specifically overload a lot
# of stuff so that pruning of states can happen as soon as poss
use overload
'+' => sub { binop(@_, sub{$_[0] + $_[1]} ) },
'*' => sub { binop(@_, sub{$_[0] * $_[1]} ) },
'-' => sub { binop(@_, sub{$_[0] - $_[1]} ) },
'/' => sub { binop(@_, sub{$_[0] / $_[1]} ) },
'**' => sub { binop(@_, sub{$_[0] **$_[1]} ) },
'%' => sub { binop(@_, sub{$_[0] % $_[1]} ) },
'x' => sub { binop(@_, sub{$_[0] x $_[1]} ) },
'.' => sub { binop(@_, sub{$_[0] . $_[1]} ) },
'<<' => sub { binop(@_, sub{$_[0] <<$_[1]} ) },
'>>' => sub { binop(@_, sub{$_[0] >>$_[1]} ) },
'&' => sub { binop(@_, sub{$_[0] & $_[1]} ) },
'|' => sub { binop(@_, sub{$_[0] | $_[1]} ) },
'^' => sub { binop(@_, sub{$_[0] ^ $_[1]} ) },
'~' => sub { unnop($_[0], sub { ~$_[0]} ) },
'neg'=> sub { unnop($_[0], sub { -$_[0]} ) },
'!' => sub { unnop($_[0], sub { !$_[0]} ) },
'++' => sub { mutop($_[0], sub {++$_[0]} ) },
'--' => sub { mutop($_[0], sub {--$_[0]} ) },
'<' => sub { bioop(@_, sub{$_[0] < $_[1]} ) },
'>' => sub { bioop(@_, sub{$_[0] > $_[1]} ) },
'<=' => sub { bioop(@_, sub{$_[0] <= $_[1]} ) },
'>=' => sub { bioop(@_, sub{$_[0] >= $_[1]} ) },
'==' => sub { bioop(@_, sub{$_[0] == $_[1]} ) },
'!=' => sub { bioop(@_, sub{$_[0] != $_[1]} ) },
'lt' => sub { bioop(@_, sub{$_[0] lt $_[1]} ) },
'le' => sub { bioop(@_, sub{$_[0] le $_[1]} ) },
'ge' => sub { bioop(@_, sub{$_[0] ge $_[1]} ) },
'gt' => sub { bioop(@_, sub{$_[0] gt $_[1]} ) },
'eq' => sub { bioop(@_, sub{$_[0] eq $_[1]} ) },
'ne' => sub { bioop(@_, sub{$_[0] ne $_[1]} ) },
'<=>'=> sub { binop(@_, sub{$_[0] <=>$_[1]} ) },
'cmp'=> sub { binop(@_, sub{$_[0] cmp$_[1]} ) },
'cos'=> sub { unnop($_[0], sub{ cos $_[0]} ) },
'sin'=> sub { unnop($_[0], sub{ sin $_[0]} ) },
'exp'=> sub { unnop($_[0], sub{ exp $_[0]} ) },
'abs'=> sub { unnop($_[0], sub{ abs $_[0]} ) },
'log'=> sub { unnop($_[0], sub{ log $_[0]} ) },
'sqrt'=>sub { unnop($_[0], sub{ sqrt $_[0]}) },
'atan2'=>sub{ binop(@_, sub{atan2($_[0], $_[1])} ) },
'&{}'=> \&sub_ent,
'bool'=> \&bool_ent, q{""} => \&str_ent, '0+' => \&num_ent,
'=' => \©_ent,
'fallback' => 1;
# copying (not observation, clones states, does not increase state space)
sub copy_ent {
my $os = $_[0]->[1];
my $val = $_[0]->_add;
my $universe = ${$_[0]->[0]};
push(@$_, $_->[$os-1], $_->[$os]) foreach @$universe;
return $val;
}
# running entangled subroutines
sub sub_ent {
my $obj = $_[0];
my $os = $obj->[1];
my $universe = ${$obj->[0]};
return sub {
my $var = $obj->_add;
foreach my $state (@$universe) {
push(@$state, $state->[$os-1],
scalar( $state->[$os]->(@_) ));
}
return $var;
}
}
# stringification (observation)
sub str_ent {
my $c = $_[0];
my $os = $c->[1];
my $universe = ${$c->[0]};
my %str_vals;
# work out which state we want to retain
foreach my $state (@$universe) {
$str_vals{$state->[$os]} = $state->[$os-1] + ($str_vals{$state->[$os]}||0);
}
my ($hr, $ar) = _normalise(\%str_vals);
my $rand = rand(1);
my $rt;
LOOP: foreach (@$ar) {
if ( $rand < ${$hr}{$_}) {
$rt = $_;
last LOOP;
}
}
# retain only that state
my @retains;
for (0..(@$universe-1)) {
my $state = $universe->[$_];
my $foo = $state->[$os];
push(@retains, $_) if ("$foo" eq $rt);
}
if ($Quantum::Entanglement::destroy) {
@$universe = @$universe[@retains];
return $rt;
}
# set all non retained states to zero probability, leave others alone
my $next_retain = shift @retains;
PURGE: foreach my $snum ( 0..(@$universe-1) ) {
if ($snum == $next_retain) {
$next_retain = shift(@retains) || -1;
next PURGE;
}
my $state = ${$universe}[$snum];
$$state[$_] = 0 foreach grep {!($_ % 2)} (0..(@$state-1))
}
return $rt;
}
# numification (have to coerce things into numbers then strings for
# probability hash purposes, ick) (observation)
sub num_ent {
my $c = $_[0];
my $os = $c->[1];
my $universe = ${$c->[0]};
my %str_vals;
# work out which state we want to retain
foreach my $state (@$universe) {
$str_vals{+$state->[$os]} =
$state->[$os-1] + ($str_vals{+$state->[$os]}||0);
}
my ($hr, $ar) = _normalise(\%str_vals);
my $rand = rand(1);
my $rt;
LOOP: foreach (@$ar) {
if ( $rand < ${$hr}{$_}) {
$rt = +$_;
last LOOP;
}
}
# retain only that state
my @retains;
for (0..(@$universe-1)) {
my $state = $universe->[$_];
my $foo = +$state->[$os];
push(@retains, $_) if ($foo == $rt);
}
if ($Quantum::Entanglement::destroy) {
@$universe = @$universe[@retains];
return $rt;
}
# set probabilty to zero for each state we know can't be so
my $next_retain = shift @retains;
PURGE: foreach my $snum ( 0..(@$universe-1) ) {
if ($snum == $next_retain) {
$next_retain = shift(@retains) || -1;
next PURGE;
}
my $state = ${$universe}[$snum];
$$state[$_] = 0 foreach grep {!($_ % 2)} ( 0..(@$state-1) )
}
return $rt;
}
# boolean context (observation)
sub bool_ent {
my $c = $_[0];
my $os = $c->[1];
my $universe = ${$c->[0]};
my ($rt,$ft,$p_true, $p_false) = (0,0,0,0);
my (@true, @false);
foreach (0..(@$universe-1)) {
my $state = $universe->[$_];
my $c2 = $state->[$os];
if ($c2) {
$rt++;
push @true, $_;
$p_true += $state->[$os-1];
}
else {
$ft++;
push @false, $_;
$p_false += $state->[$os-1];
}
}
return 0 unless $rt; # no states are true, so must be false
return $rt unless $ft; # no states are false, so must be true
# if it can be true, decide if it will end up being true or not
my @retains;
if ( _sel_output( $p_true,$p_false)
or $Quantum::Entanglement::conform) {
@retains = @true;
$rt = $rt;
}
else {
@retains = @false;
$rt = 0;
}
if ($Quantum::Entanglement::destroy) {
@$universe = @$universe[@retains];
return $rt;
}
my $next_retain = shift @retains;
PURGE: foreach my $snum ( 0..(@$universe-1) ) {
if ($snum == $next_retain) {
$next_retain = shift(@retains) || -1;
next PURGE;
}
my $state = ${$universe}[$snum];
$$state[$_] = 0 foreach grep {!($_ % 2)} (0..(@$state-1))
}
return $rt;
}
### any BInary, Non-observational OPeration
sub binop {
my ($c,$d,$r,$code) = @_;
my $var;
my $universe;
if ( ref($d)
&& UNIVERSAL::isa($d, 'Quantum::Entanglement')) {
_join($c,$d);
my $od = $d->[1]; my $oc = $c->[1];
$var = _add($c);
$universe = ${$c->[0]};
foreach my $state (@$universe) {
push @$state, ($state->[$oc-1] * $state->[$od-1],
&$code($state->[$oc],$state->[$od]) );
}
}
else { # adding something to one state
my $oc = $c->[1];
$var = _add($c);
$universe = ${$c->[0]};
if ($r) {
push(@$_, ($_->[$oc-1], &$code($d,$_->[$oc]))) foreach @$universe;
}
else {
push(@$_, ($_->[$oc-1], &$code($_->[$oc],$d))) foreach @$universe;
}
}
return $var;
}
# any BInary Observational OPeration
sub bioop {
my ($c, $d, $reverse, $code) = @_;
my $rt = 0;
my $ft = 0;
my (@true, @false);
my ($p_true, $p_false) = (0,0);
my $universe;
if (ref($d) && UNIVERSAL::isa($d, 'Quantum::Entanglement')) {
$c->_join($d);
$universe = ${$c->[0]};
foreach (0..(@$universe-1)) {
my $state = $universe->[$_];
my $oc = $c->[1]; my $od = $d->[1];
my $d2 = $state->[$od];
my $c2 = $state->[$oc];
if (&$code($c2, $d2)) {
$rt++;
push @true, $_;
$p_true += $state->[$oc-1]* $state->[$od-1];
}
else {
$ft++;
push @false, $_;
$p_false += $state->[$oc-1]* $state->[$od-1];
}
}
}
else {
$universe = ${$c->[0]};
foreach (0..(@$universe-1)) {
my $state = $universe->[$_];
my $d2 = $d;
my $os = $c->[1];
my $c2 = $state->[$os];
($c2, $d2) = ($d2, $c2) if $reverse;
if (&$code($c2,$d2)) {
$rt++;
push @true, $_;
$p_true += $state->[$os-1];
}
else {
$ft++;
push @false, $_;
$p_false += $state->[$os-1];
}
}
}
return 0 unless $rt; # no states are true, so must be false
return $rt unless $ft; # no states are false, so must be true
my @retains;
# if it can be true, decide if it will end up being true or not
if ( _sel_output( $p_true,$p_false)
or $Quantum::Entanglement::conform) {
@retains = @true;
$rt = $rt;
}
else {
@retains = @false;
$rt = 0;
}
if ($Quantum::Entanglement::destroy) {
@$universe = @$universe[@retains];
return $rt;
}
my $next_retain = shift @retains;
PURGE: foreach my $snum ( 0..(@$universe-1) ) {
if ($snum == $next_retain) {
$next_retain = shift(@retains) || -1;
next PURGE;
}
my $state = ${$universe}[$snum];
$$state[$_] = 0 foreach grep {!($_ % 2)} (0..(@$state-1))
}
return $rt;
}
# any MUTating OPerator
sub mutop {
my $c = $_[0];
my $code = $_[1];
my $os = $c->[1];
my $universe = ${$c->[0]};
foreach my $state (@$universe) {
$state->[$os] = &$code($state->[$os]);
}
return $c;
}
sub unnop {
my $c = $_[0];
my $code = $_[1];
my $os = $c->[1];
my $val = $c->_add; my $universe = ${$c->[0]};
foreach my $state (@$universe) {
push(@$state, $state->[$os-1], &$code($state->[$os]) );
}
return $val;
}
##
# performing a conditional in paralell on the states (ie. without looking)
# returns a new variable
sub p_op {
my ($arg1, $op, $arg2, $true_cf, $false_cf) = @_;
$true_cf = ref($true_cf) ? $true_cf : sub {1};
$false_cf = ref($false_cf) ? $false_cf : sub {0};
my $r = 0;
unless (ref($arg1) && UNIVERSAL::isa($arg1, 'Quantum::Entanglement')) {
$r = 1;
($arg1, $arg2) = ($arg2, $arg1);
}
my $tcref;
eval "
\$tcref = sub {
local \*QE::arg1 = \\\$_[0];
local \*QE::arg2 = \\\$_[1];
if (\$_[0] $op \$_[1]) {
return \&\$true_cf;
}
else {
return \&\$false_cf;
}
}
"; croak "$0: something wrong in p_op $@" if $@;
return binop($arg1, $arg2, $r, $tcref);
}
# allows for other functions to be performed accross states, can take
# as many entangled variables as you like...
# can take code ref, or "symbolic" function name (eg. p_func('substr', ..))
sub p_func {
my $func = shift;
my $package = (caller)[0];
# build up the function call by shifting off
# entangled variables until something isn't entangled
my $foo = ref($func) ? "&\$func(" : "$func(";
my @temp = @_;
my $first = $temp[0];
do {
my $c = shift @temp;
_join($first,$c);
} while (ref($temp[0]) && UNIVERSAL::isa($temp[0],'Quantum::Entanglement'));
my @p_codes = ();
do {
my $c = shift;
$foo .= '$state->[' . $c->[1] . '],';
push @p_codes, $c->[1]-1;
} while ( ref($_[0]) && UNIVERSAL::isa($_[0], 'Quantum::Entanglement'));
$foo .= scalar(@_)? '@args);' : ');';
my @args = @_;
# loop over states, evaluating function in caller's package
my $var = $first->_add;
my $p_code = join('*', map {"\$state->[$_]"} @p_codes);
my $universe = ${$first->[0]};
foreach my $state (@$universe) {
my $new_prob = eval $p_code;
push(@$state, $new_prob, eval "package $package; $foo");
croak "Internal error: $@" if $@;
}
return $var;
}
# This allows the introduction of new states into the system, based
# on the current values and probability amplitudes of current states
# must be given a code ref, followed by a list of entangled vars whose
# states will be passed to the function.
sub q_logic {
my $func = shift;
my (@offsets);
my $first = $_[0];
_join($first,$_) foreach @_;
@offsets = map {$_->[1]-1, $_->[1]} @_;
my $var = $first->_add;
my $universe = ${$first->[0]};
my @resultant_space;
foreach my $state (@$universe) {
my @new_states = &$func(@{$state}[@offsets]);
do {
push @resultant_space, [@$state, splice(@new_states,0,2)];
} while (@new_states);
}
@{$universe} = @resultant_space;
return $var;
}
# takes ft of amplitudes of a var, creates new state with the
# transformed amplitudes and the values from the first state.
sub QFT {
my $c = $_[0];
my $var = $c->_add;
my $os = $c->[1];
my $universe = ${$c->[0]};
my @inputs = map {$_->[$os-1]} @$universe; # get current probs
my $num = scalar @inputs;
foreach my $r (0..($num-1)) {
my $prob = 0;
foreach my $x (0..($num-1)) {
$prob += cplxe(1,(-2*pi*$r*$x / $num)) * $inputs[$x];
}
push @{$universe->[$r]}, $prob, $universe->[$r]->[$os];
}
return $var;
}
sub save_state{
my @os;
my $stash = [];
foreach (@_) {
carp "Can only save state of Quantum::Entanglement variables"
unless (ref($_) && UNIVERSAL::isa($_, 'Quantum::Entanglement'));
}
my $first = $_[0];
_join($first, $_) foreach @_;
push(@os, $_->[1]) foreach @_;
my $universe = ${$_[0]->[0]};
foreach my $state (@$universe) {
push @$stash, [ @{$state}[map {$_-1,$_} @os] ];
}
return bless $stash, 'Quantum::Entanglement::State';
}
# completely clobbers current state with whatever was saved previously
sub restore_state {
my $stash = shift;
my $num_saved = scalar(@{$stash->[0]}) /2;
carp "You don't have any states saved!" unless $num_saved;
my @newvars;
$newvars[0] = _new();
${$newvars[0]->[0]}->[0] = ['fake','fake']; # no hackery here, no.
if ($num_saved > 1) {
for (2..$num_saved) {
push(@newvars, $newvars[0]->_add());
push @{${$newvars[0]->[0]}->[0]}, qw(fake fake); # or here, never
}
}
my $universe = ${$newvars[0]->[0]};
shift @$universe;
foreach (@$stash) {
push @$universe, [@$_];
}
return wantarray ? @newvars : $newvars[0];
}
# this is needed for simplicity of exporting save_states
package Quantum::Entanglement::State;
@Quantum::Entanglement::State::ISA = qw(Quantum::Entanglement);
sub DESTROY {}
1;
__END__;
=head1 NAME
Quantum::Entanglement - QM entanglement of variables in perl
=head1 SYNOPSIS
use Quantum::Entanglement qw(:DEFAULT :complex :QFT);
my $c = entangle(1,0,i,1); # $c = |0> + i|1>
my $d = entangle(1,0,1,1); # $d = |0> + |1>
$e = $c * $d; # $e now |0*0> + i|0*1> + |1*0> + i|1*1>, connected to $c, $d
if ($e == 1) { # observe, probabilistically chose an outcome
# if we are here, ($c,$d) = i|(1,1)>
print "* \$e == 1\n";
}
else { # one of the not 1 versions of $e chosen
# if we are here, ($c,$d) = |(0,0)> + i|(1,0)> + |(0,1)>
print "* \$e != 1\n";
}
=head1 BACKGROUND
"Quantum Mechanics - the dreams that stuff is made of."
Quantum mechanics is one of the stranger things to have emerged from science
over the last hundred years. It has led the way to new understanding
of a diverse range of fundamental physical phenomena and, should recent
developments prove fruitful, could also lead to an entirely new mode
of computation where previously intractable problems find themselves open
to easy solution.
While the detailed results of quantum theory are hard to prove, and
even harder to understand, there are a handful of concepts from the
theory which are more easily understood. Hopefully this module will
shed some light on a few of these and their consequences.
One of the more popular interpretations of quantum mechanics holds that
instead of particles always being in a single, well defined, state
they instead exist as an almost ghostly overlay of many different
states (or values) at the same time. Of course, it is our experience
that when we look at something, we only ever find it in one single state.
This is explained by the many states of the particle collapsing to a
single state and highlights the importance of observation.
In quantum mechanics, the
state of a system can be described by a set of numbers which have
a probability amplitude associated with them.
This probability amplitude is similar to the normal idea of probability
except for two differences. It can be a complex number, which leads
to interference between states, and the probability with which we might
observe a system in a particular state is given by the modulus squared
of this amplitude.
Consider the simple system, often called a I<qubit>, which can take
the value of 0 or 1. If we prepare it in the following superposition
of states (a fancy way of saying that we want it to have many possible
values at once):
particle = 1 * (being equal to 1) + (1-i) * (being equal to 0)
we can then measure (observe) the value of the particle. If we do
this, we find that it will be equal to 1 with a probability of
1**2 / (1**2 + (1-i)(1+i) )
and equal to zero with a probability of
(1+i)(1-i) / (1**2 + (1-i)(1+i) )
the factors on the bottom of each equation being necessary so that the chance
of the particle ending up in any state at all is equal to one.
Observing a particle in this way is said to collapse the wave-function,
or superposition of values, into a single value, which it will retain
from then onwards. A simpler way of writing the equation above is
to say that
particle = 1 |1> + (1-i) |0>
where the probability amplitude for a state is given as a 'multiplier'
of the value of the state, which appears inside the C<< | > >> pattern (this
is called a I<ket>, as sometimes the I<bra> or C<< < | >>, pattern appears
to the left of the probability amplitudes in these equations).
Much of the power of quantum computation comes from collapsing states
and modifying the probability with which a state might collapse to a
particular value as this can be done to each possible state at the same
time, allowing for fantastic degrees of parallelism.
Things also get interesting when you have multiple particles together
in the same system. It turns out that if two particles which exist
in many states at once interact, then after doing so, they will be
linked to one another so that when you measure the value of one
you also affect the possible values that the other can take. This
is called entanglement and is important in many quantum algorithms.
=head1 DESCRIPTION
Essentially, this allows you to put variables into a superposition
of states, have them interact with each other (so that all states
interact) and then observe them (testing to see if they satisfy
some comparison operator, printing them) which will collapse
the entire system so that it is consistent with your knowledge.
As in quantum physics, the outcome of an observation will be the result
of selecting one of the states of the system at random. This might
affect variables other than the ones observed, as they are able to
remember their history.
For instance, you can say:
$foo = entangle(1,0,1,1); # foo = |0> + |1>
$bar = entangle(1,0,1,1); # bar = |0> + |1>
if at this point we look at the values of $foo or $bar, we will
see them collapse to zero half of the time and one the other half of
the time. We will also find that us looking at $foo will have no
effect on the possible values, or chance of getting any one of those
values, of $bar.
If we restrain ourselves a little and leave $foo and $bar unobserved
we can instead play some games with them. We can use our entangled
variables just as we would any other variable in perl, for instance,
$c = $foo * $bar;
will cause $c to exist in a superposition of all the possible outcomes
of multiplying each state of $foo with each state in $bar. If we
now measure the value of $c, we will find that one quarter of the time
it will be equal to one, and three quarters of the time it will be equal
to zero.
Lets say we do this, and $c turns out to be equal to zero this time, what
does that leave $foo and $bar as? Clearly we cannot have both $foo and
$bar both equal to one, as then $c would have been equal to one, but all
the other possible values of $foo and $bar can still occur. We say
that the state of $foo is now entangled with the state of $bar so that
($foo, $bar ) = |0,0> + |0,1> + |1,0>.
If we now measure $foo, one third of the time it will be equal to one and
two thirds of the time, it will come out as zero. If we do this and get
one, this means that should we observe $bar it will be equal to zero so
that our earlier measurement of $c still makes sense.
=head1 Use of this module
To use this module in your programs, simply add a
use Quantum::Entanglement;
line to the top of your code, if you want to use complex probability
amplitudes, you should instead say:
use Quantum::Entanglement qw(:complex :DEFAULT);
which will import the C<Math::Complex i Re Im rho theta arg cplx cplxe>
functions / constants into your package.
You can also import a Quantum Fourier transform, which acts on the
probability amplitudes of a state (see below) by adding a C<:QFT>
tag.
This module adds an C<entangle> function to perl, this puts a
variable into multiple states simultaneously. You can then
cause this variable to interact with other entangled, or normal,
values the result of which will also be in many states at once.
The different states which a variable can take each have an associated
complex probability amplitude, this can lead to interesting behaviour,
for instance, a root-not logic gate (see q_logic, below).
=head2 entangle
This sets up a new entangled variable:
$foo = entangle(prob1, val1, prob2, val2, ...);
The probability values are strictly speaking probability amplitudes,
and can be complex numbers (corresponding to a phase or wave-ish
nature (this is stretching things slightly...)). To use straight
numbers, just use them, to use complex values, supply a Math::Complex
number.
Thus
$foo = entangle(1, 0, 1+4*i, 1);
corresponds to:
foo = 1|0> + (1 + 4i)|1>
The probabilities do not need to be normalized, this is done
by the module whenever required (ie. when observing variables).
=head2 Non-observational operations
We can now use our entangled variable just as we would any normal
variable in perl. Much of the time we will be making it do things
where we do not find anything out about the value of our variable,
if this is the case, then the variable does not collapse, although
any result of its interactions will be entangled with itself.
=head2 Observational Operators
Whenever you perform an operation on an entangled variable which
should increase your level of knowledge about the value of the variable
you will cause it to collapse into a single state or set of states.
All logical comparison (C<==>, C<gt> ....) operators, as well as
string and num -ifying and boolean observation will cause collapse.
When an entangled variable is observed in this way, sets of states which
would satisfy the operator are produced (ie. for $a < 2, all states <2 and
all >= 2). One of these sets of states is then selected randomly, using
the probability amplitudes associated with the states. The result of
operating on this state is then returned. Any other states are then
destroyed.
For instance, if
$foo = entangle(1,2,1,3,1,5,1,7);
# |2> +|3> + |5> +|7>
then saying
print '$foo is greater than four' if ($foo > 4);
will cause $foo to be either C<< |2> + |3> >> B<or> C<< |5> +7> >>.
Of course, if you had said instead:
$foo = entangle(-1,2,1,3,1,5,1,7);
# -1|2> + |3> + |5> +|7>
then if C<$foo> was measured here, it would come out as any one of 2,3,5,7
with equal likelyhood (remember, amplitude squared). But saying
print '$foo is greater than four' if ($foo > 4);
will cause foo to be C<< |2> or 3> >> with a probability of C<(-1 + 1) == 0> or
C<< |5 or 7> >> with probability of C<(1 + 1)/2 == 1>. Thus C<< $foo > 4 >>
will B<always> be true.
It is possible to perform operations like these on an entangled
variable without causing collapse by using C<p_op> (below).
When performing an observation, the module can do two things to
the states which can no longer be valid (those to which it did not collapse,
|2 or 3> in the example above). It can either internally
set the probability of them collapsing to be zero or it can delete
them entirely. This could have consequences if you are writing parallel
functions that rely on there being a certain number of states in
a variable, even after collapse.
The default is for collapsed states to be destroyed, to alter this
behaviour, set the C<$Quantum::Entanglement::destroy> variable to
a false value. In general though, you can leave this alone.
=head2 Dammit Jim, I can't change the laws of physics
Although not the default, it is possible to cause observation (for
boolean context or with comparison operators only) to act in a more