/
test_composition.py
7323 lines (6267 loc) · 318 KB
/
test_composition.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
import functools
import logging
from timeit import timeit
import numpy as np
import pytest
from itertools import product
import psyneulink.core.llvm as pnlvm
import psyneulink as pnl
from psyneulink.core.components.functions.statefulfunctions.integratorfunctions import \
AdaptiveIntegrator, DriftDiffusionIntegrator, IntegratorFunction, SimpleIntegrator
from psyneulink.core.components.functions.transferfunctions import \
Linear, Logistic, INTENSITY_COST_FCT_MULTIPLICATIVE_PARAM
from psyneulink.core.components.functions.combinationfunctions import LinearCombination
from psyneulink.core.components.functions.userdefinedfunction import UserDefinedFunction
from psyneulink.core.components.functions.learningfunctions import Reinforcement, BackPropagation
from psyneulink.core.components.functions.optimizationfunctions import GridSearch
from psyneulink.core.components.mechanisms.processing.integratormechanism import IntegratorMechanism
from psyneulink.core.components.mechanisms.processing.objectivemechanism import ObjectiveMechanism
from psyneulink.core.components.mechanisms.processing.processingmechanism import ProcessingMechanism
from psyneulink.core.components.mechanisms.processing.transfermechanism import TransferMechanism
from psyneulink.core.components.mechanisms.modulatory.learning.learningmechanism import LearningMechanism
from psyneulink.core.components.mechanisms.modulatory.control.controlmechanism import ControlMechanism
from psyneulink.core.components.mechanisms.modulatory.control.optimizationcontrolmechanism import OptimizationControlMechanism
from psyneulink.core.components.projections.pathway.mappingprojection import MappingProjection
from psyneulink.core.components.ports.inputport import InputPort
from psyneulink.core.components.ports.modulatorysignals.controlsignal import ControlSignal, CostFunctions
from psyneulink.core.compositions.composition import Composition, CompositionError, NodeRole
from psyneulink.core.compositions.pathway import Pathway, PathwayRole
from psyneulink.core.globals.context import Context
from psyneulink.core.globals.keywords import \
ADDITIVE, ALLOCATION_SAMPLES, BEFORE, DEFAULT, DISABLE, INPUT_PORT, INTERCEPT, LEARNING_MECHANISMS, LEARNED_PROJECTIONS, \
NAME, PROJECTIONS, RESULT, OBJECTIVE_MECHANISM, OUTPUT_MECHANISM, OVERRIDE, SLOPE, TARGET_MECHANISM, VARIANCE
from psyneulink.core.scheduling.condition import AfterNCalls, AtTimeStep, AtTrial, Never
from psyneulink.core.scheduling.condition import EveryNCalls
from psyneulink.core.scheduling.scheduler import Scheduler
from psyneulink.core.scheduling.time import TimeScale
from psyneulink.library.components.mechanisms.modulatory.control.agt.lccontrolmechanism import LCControlMechanism
from psyneulink.library.components.mechanisms.processing.transfer.recurrenttransfermechanism import \
RecurrentTransferMechanism
logger = logging.getLogger(__name__)
# All tests are set to run. If you need to skip certain tests,
# see http://doc.pytest.org/en/latest/skipping.html
def record_values(d, time_scale, *mechs, comp=None):
if time_scale not in d:
d[time_scale] = {}
for mech in mechs:
if mech not in d[time_scale]:
d[time_scale][mech] = []
mech_value = mech.parameters.value.get(comp)
if mech_value is None:
d[time_scale][mech].append(np.nan)
else:
d[time_scale][mech].append(mech_value[0][0])
# Unit tests for each function of the Composition class #######################
# Unit tests for Composition.Composition(
class TestConstructor:
def test_no_args(self):
comp = Composition()
assert isinstance(comp, Composition)
def test_two_calls_no_args(self):
comp = Composition()
assert isinstance(comp, Composition)
comp_2 = Composition()
assert isinstance(comp, Composition)
@pytest.mark.stress
@pytest.mark.parametrize(
'count', [
10000,
]
)
def test_timing_no_args(self, count):
t = timeit('comp = Composition()', setup='from psyneulink.core.compositions.composition import Composition', number=count)
print()
logger.info('completed {0} creation{2} of Composition() in {1:.8f}s'.format(count, t, 's' if count != 1 else ''))
def test_call_after_construction_with_no_arg_then_run_then_illegal_args_error(self):
A = ProcessingMechanism()
B = ProcessingMechanism(function=Linear(slope=2))
C = ProcessingMechanism(function=Logistic)
c = Composition(pathways=[[A],[B],[C]])
assert c() is None
result = c(inputs={A:[[1],[100]],B:[[2],[200]],C:[[3],[1]]})
assert np.allclose(result, [[100],[400],[0.73105858]])
assert np.allclose(c(), [[100],[400],[0.73105858]])
with pytest.raises(CompositionError) as err:
c(23, 'bad_arg', bad_kwarg=1)
assert f" called with illegal argument(s): 23, bad_arg, bad_kwarg" in str(err.value)
def test_call_after_construction_with_learning_pathway(self):
A = ProcessingMechanism()
B = ProcessingMechanism(function=Linear(slope=0.5))
C = ProcessingMechanism(function=Logistic)
c = Composition(pathways=[[A],{'LEARNING_PATHWAY':([B,C], BackPropagation)}])
assert c() is None
# Run without learning
result = c(inputs={A:[[1],[100]],B:[[2],[1]]})
print(result)
assert np.allclose(result, [[100.],[0.62245933]])
assert np.allclose(c(), [[100.],[0.62245933]])
# Run with learning
target = c.pathways['LEARNING_PATHWAY'].target
result = c(inputs={A:[[1],[100]],B:[[2],[1]],target:[[3],[300]]})
np.allclose(result, [[[1.], [0.73105858]], [[100.], [0.62507661]]])
class TestAddMechanism:
def test_add_once(self):
comp = Composition()
comp.add_node(TransferMechanism())
def test_add_twice(self):
comp = Composition()
comp.add_node(TransferMechanism())
comp.add_node(TransferMechanism())
def test_add_same_twice(self):
comp = Composition()
mech = TransferMechanism()
comp.add_node(mech)
comp.add_node(mech)
def test_add_multiple_projections_at_once(self):
comp = Composition(name='comp')
a = TransferMechanism(name='a')
b = TransferMechanism(name='b',
function=Linear(slope=2.0))
c = TransferMechanism(name='a',
function=Linear(slope=4.0))
nodes = [a, b, c]
comp.add_nodes(nodes)
ab = MappingProjection(sender=a, receiver=b)
bc = MappingProjection(sender=b, receiver=c, matrix=[[3.0]])
projections = [ab, bc]
comp.add_projections(projections)
comp.run(inputs={a: 1.0})
assert np.allclose(a.value, [[1.0]])
assert np.allclose(b.value, [[2.0]])
assert np.allclose(c.value, [[24.0]])
assert ab in comp.projections
assert bc in comp.projections
def test_add_multiple_projections_no_sender(self):
comp = Composition(name='comp')
a = TransferMechanism(name='a')
b = TransferMechanism(name='b',
function=Linear(slope=2.0))
c = TransferMechanism(name='a',
function=Linear(slope=4.0))
nodes = [a, b, c]
comp.add_nodes(nodes)
ab = MappingProjection(sender=a, receiver=b)
bc = MappingProjection(sender=b)
projections = [ab, bc]
with pytest.raises(CompositionError) as err:
comp.add_projections(projections)
assert "The add_projections method of Composition requires a list of Projections" in str(err.value)
def test_add_multiple_projections_no_receiver(self):
comp = Composition(name='comp')
a = TransferMechanism(name='a')
b = TransferMechanism(name='b',
function=Linear(slope=2.0))
c = TransferMechanism(name='a',
function=Linear(slope=4.0))
nodes = [a, b, c]
comp.add_nodes(nodes)
ab = MappingProjection(sender=a, receiver=b)
bc = MappingProjection(receiver=c)
projections = [ab, bc]
with pytest.raises(CompositionError) as err:
comp.add_projections(projections)
assert "The add_projections method of Composition requires a list of Projections" in str(err.value)
def test_add_multiple_projections_not_a_proj(self):
comp = Composition(name='comp')
a = TransferMechanism(name='a')
b = TransferMechanism(name='b',
function=Linear(slope=2.0))
c = TransferMechanism(name='a',
function=Linear(slope=4.0))
nodes = [a, b, c]
comp.add_nodes(nodes)
ab = MappingProjection(sender=a, receiver=b)
bc = [[3.0]]
projections = [ab, bc]
with pytest.raises(CompositionError) as err:
comp.add_projections(projections)
assert "The add_projections method of Composition requires a list of Projections" in str(err.value)
def test_add_multiple_nodes_at_once(self):
comp = Composition()
a = TransferMechanism()
b = TransferMechanism()
c = TransferMechanism()
nodes = [a, b, c]
comp.add_nodes(nodes)
output = comp.run(inputs={a: [1.0],
b: [2.0],
c: [3.0]})
assert set(comp.get_nodes_by_role(NodeRole.INPUT)) == set(nodes)
assert set(comp.get_nodes_by_role(NodeRole.OUTPUT)) == set(nodes)
assert np.allclose(output, [[1.0], [2.0], [3.0]])
@pytest.mark.stress
@pytest.mark.parametrize(
'count', [
100,
]
)
def test_timing_stress(self, count):
t = timeit(
'comp.add_node(TransferMechanism())',
setup="""
from psyneulink.core.components.mechanisms.processing.transfermechanism import TransferMechanism
from psyneulink.core.compositions.composition import Composition
comp = Composition()
""",
number=count
)
print()
logger.info('completed {0} addition{2} of a Mechanism to a Composition in {1:.8f}s'.
format(count, t, 's' if count != 1 else ''))
class TestAddProjection:
def test_add_once(self):
comp = Composition()
A = TransferMechanism(name='composition-pytests-A')
B = TransferMechanism(name='composition-pytests-B')
comp.add_node(A)
comp.add_node(B)
comp.add_projection(MappingProjection(), A, B)
def test_add_twice(self):
comp = Composition()
A = TransferMechanism(name='composition-pytests-A')
B = TransferMechanism(name='composition-pytests-B')
comp.add_node(A)
comp.add_node(B)
comp.add_projection(MappingProjection(), A, B)
comp.add_projection(MappingProjection(), A, B)
#
# def test_add_same_twice(self):
# comp = Composition()
# A = TransferMechanism(name='composition-pytests-A')
# B = TransferMechanism(name='composition-pytests-B')
# comp.add_node(A)
# comp.add_node(B)
# proj = MappingProjection()
# comp.add_projection(proj, A, B)
# with pytest.raises(CompositionError) as error_text:
# comp.add_projection(proj, A, B)
# assert "This Projection is already in the Composition" in str(error_text.value)
def test_add_fully_specified_projection_object(self):
comp = Composition()
A = TransferMechanism(name='composition-pytests-A')
B = TransferMechanism(name='composition-pytests-B')
comp.add_node(A)
comp.add_node(B)
proj = MappingProjection(sender=A, receiver=B)
comp.add_projection(proj)
def test_add_proj_sender_and_receiver_only(self):
comp = Composition()
A = TransferMechanism(name='composition-pytests-A')
B = TransferMechanism(name='composition-pytests-B',
function=Linear(slope=2.0))
comp.add_node(A)
comp.add_node(B)
comp.add_projection(sender=A, receiver=B)
result = comp.run(inputs={A: [1.0]})
assert np.allclose(result, [[np.array([2.])]])
def test_add_proj_missing_sender(self):
comp = Composition()
A = TransferMechanism(name='composition-pytests-A')
B = TransferMechanism(name='composition-pytests-B',
function=Linear(slope=2.0))
comp.add_node(A)
comp.add_node(B)
with pytest.raises(CompositionError) as error_text:
comp.add_projection(receiver=B)
assert "a sender must be specified" in str(error_text.value)
def test_add_proj_missing_receiver(self):
comp = Composition()
A = TransferMechanism(name='composition-pytests-A')
B = TransferMechanism(name='composition-pytests-B',
function=Linear(slope=2.0))
comp.add_node(A)
comp.add_node(B)
with pytest.raises(CompositionError) as error_text:
comp.add_projection(sender=A)
assert "a receiver must be specified" in str(error_text.value)
def test_add_proj_invalid_projection_spec(self):
comp = Composition()
A = TransferMechanism(name='composition-pytests-A')
B = TransferMechanism(name='composition-pytests-B',
function=Linear(slope=2.0))
comp.add_node(A)
comp.add_node(B)
with pytest.raises(CompositionError) as error_text:
comp.add_projection("projection")
assert "Invalid projection" in str(error_text.value)
# KAM commented out this test 7/24/18 because it does not work. Should it work?
# Or should the add_projection method of Composition only consider composition nodes as senders and receivers
# def test_add_proj_states_as_sender_and_receiver(self):
# comp = Composition()
# A = TransferMechanism(name='composition-pytests-A',
# default_variable=[[0.], [0.]])
# B = TransferMechanism(name='composition-pytests-B',
# function=Linear(slope=2.0),
# default_variable=[[0.], [0.]])
# comp.add_node(A)
# comp.add_node(B)
#
# comp.add_projection(sender=A.output_ports[0], receiver=B.input_ports[0])
# comp.add_projection(sender=A.output_ports[1], receiver=B.input_ports[1])
#
# print(comp.run(inputs={A: [[1.0], [2.0]]}))
def test_add_proj_weights_only(self):
comp = Composition()
A = TransferMechanism(name='composition-pytests-A',
default_variable=[[0., 0., 0.]])
B = TransferMechanism(name='composition-pytests-B',
default_variable=[[0., 0.]],
function=Linear(slope=2.0))
weights = [[1., 2.], [3., 4.], [5., 6.]]
comp.add_node(A)
comp.add_node(B)
proj = comp.add_projection(weights, A, B)
comp.run(inputs={A: [[1.1, 1.2, 1.3]]})
assert np.allclose(A.parameters.value.get(comp), [[1.1, 1.2, 1.3]])
assert np.allclose(B.get_input_values(comp), [[11.2, 14.8]])
assert np.allclose(B.parameters.value.get(comp), [[22.4, 29.6]])
assert np.allclose(proj.matrix.base, weights)
def test_add_linear_processing_pathway_with_noderole_specified_in_tuple(self):
comp = Composition()
A = TransferMechanism(name='composition-pytests-A')
B = TransferMechanism(name='composition-pytests-B')
C = TransferMechanism(name='composition-pytests-C')
comp.add_linear_processing_pathway([
(A,pnl.NodeRole.LEARNING),
(B,pnl.NodeRole.LEARNING),
C
])
comp._analyze_graph()
autoassociative_learning_nodes = comp.get_nodes_by_role(pnl.NodeRole.LEARNING)
assert A in autoassociative_learning_nodes
assert B in autoassociative_learning_nodes
def test_add_linear_processing_pathway_containing_nodes_with_existing_projections(self):
""" Test that add_linear_processing_pathway uses MappingProjections already specified for
Hidden_layer_2 and Output_Layer in the pathway it creates within the Composition"""
Input_Layer = TransferMechanism(name='Input Layer', size=2)
Hidden_Layer_1 = TransferMechanism(name='Hidden Layer_1', size=5)
Hidden_Layer_2 = TransferMechanism(name='Hidden Layer_2', size=4)
Output_Layer = TransferMechanism(name='Output Layer', size=3)
Input_Weights_matrix = (np.arange(2 * 5).reshape((2, 5)) + 1) / (2 * 5)
Middle_Weights_matrix = (np.arange(5 * 4).reshape((5, 4)) + 1) / (5 * 4)
Output_Weights_matrix = (np.arange(4 * 3).reshape((4, 3)) + 1) / (4 * 3)
Input_Weights = MappingProjection(name='Input Weights', matrix=Input_Weights_matrix)
Middle_Weights = MappingProjection(name='Middle Weights',sender=Hidden_Layer_1, receiver=Hidden_Layer_2,
matrix=Middle_Weights_matrix),
Output_Weights = MappingProjection(name='Output Weights',sender=Hidden_Layer_2,receiver=Output_Layer,
matrix=Output_Weights_matrix)
pathway = [Input_Layer, Input_Weights, Hidden_Layer_1, Hidden_Layer_2, Output_Layer]
comp = Composition()
comp.add_linear_processing_pathway(pathway=pathway)
stim_list = {Input_Layer: [[-1, 30]]}
results = comp.run(num_trials=2, inputs=stim_list)
def test_add_backpropagation_learning_pathway_containing_nodes_with_existing_projections(self):
""" Test that add_backpropagation_learning_pathway uses MappingProjections already specified for
Hidden_layer_2 and Output_Layer in the pathway it creates within the Composition"""
Input_Layer = TransferMechanism(name='Input Layer', size=2)
Hidden_Layer_1 = TransferMechanism(name='Hidden Layer_1', size=5)
Hidden_Layer_2 = TransferMechanism(name='Hidden Layer_2', size=4)
Output_Layer = TransferMechanism(name='Output Layer', size=3)
Input_Weights_matrix = (np.arange(2 * 5).reshape((2, 5)) + 1) / (2 * 5)
Middle_Weights_matrix = (np.arange(5 * 4).reshape((5, 4)) + 1) / (5 * 4)
Output_Weights_matrix = (np.arange(4 * 3).reshape((4, 3)) + 1) / (4 * 3)
Input_Weights = MappingProjection(name='Input Weights', matrix=Input_Weights_matrix)
Middle_Weights = MappingProjection(name='Middle Weights',sender=Hidden_Layer_1, receiver=Hidden_Layer_2,
matrix=Middle_Weights_matrix),
Output_Weights = MappingProjection(name='Output Weights',sender=Hidden_Layer_2,receiver=Output_Layer,
matrix=Output_Weights_matrix)
pathway = [Input_Layer, Input_Weights, Hidden_Layer_1, Hidden_Layer_2, Output_Layer]
comp = Composition()
backprop_pathway = comp.add_backpropagation_learning_pathway(pathway=pathway)
stim_list = {
Input_Layer: [[-1, 30]],
backprop_pathway.target: [[0, 0, 1]]}
results = comp.run(num_trials=2, inputs=stim_list)
def test_linear_processing_pathway_weights_only(self):
comp = Composition()
A = TransferMechanism(name='composition-pytests-A',
default_variable=[[0., 0., 0.]])
B = TransferMechanism(name='composition-pytests-B',
default_variable=[[0., 0.]],
function=Linear(slope=2.0))
weights = [[1., 2.], [3., 4.], [5., 6.]]
comp.add_linear_processing_pathway([A, weights, B])
comp.run(inputs={A: [[1.1, 1.2, 1.3]]})
assert np.allclose(A.parameters.value.get(comp), [[1.1, 1.2, 1.3]])
assert np.allclose(B.get_input_values(comp), [[11.2, 14.8]])
assert np.allclose(B.parameters.value.get(comp), [[22.4, 29.6]])
def test_add_conflicting_projection_object(self):
comp = Composition()
A = TransferMechanism(name='composition-pytests-A')
B = TransferMechanism(name='composition-pytests-B')
C = TransferMechanism(name='composition-pytests-C')
comp.add_node(A)
comp.add_node(B)
comp.add_node(C)
proj = MappingProjection(sender=A, receiver=B)
with pytest.raises(CompositionError) as error:
comp.add_projection(projection=proj, receiver=C)
assert "receiver assignment" in str(error.value)
assert "incompatible" in str(error.value)
@pytest.mark.stress
@pytest.mark.parametrize(
'count', [
1000,
]
)
def test_timing_stress(self, count):
t = timeit('comp.add_projection(A, MappingProjection(), B)',
setup="""
from psyneulink.core.components.mechanisms.processingmechanisms.transfermechanism import TransferMechanism
from psyneulink.core.components.projections.pathwayprojections.mappingprojection import MappingProjection
from psyneulink.core.compositions.composition import Composition
comp = Composition()
A = TransferMechanism(name='composition-pytests-A')
B = TransferMechanism(name='composition-pytests-B')
comp.add_node(A)
comp.add_node(B)
""",
number=count
)
print()
logger.info('completed {0} addition{2} of a projection to a composition in {1:.8f}s'.format(count, t, 's' if count != 1 else ''))
@pytest.mark.stress
@pytest.mark.parametrize(
'count', [
1000,
]
)
def test_timing_stress(self, count):
t = timeit('comp.add_projection(A, MappingProjection(), B)',
setup="""
from psyneulink.core.components.mechanisms.processing.transfermechanism import TransferMechanism
from psyneulink.core.components.projections.pathway.mappingprojection import MappingProjection
from psyneulink.core.compositions.composition import Composition
comp = Composition()
A = TransferMechanism(name='composition-pytests-A')
B = TransferMechanism(name='composition-pytests-B')
comp.add_node(A)
comp.add_node(B)
""",
number=count
)
print()
logger.info('completed {0} addition{2} of a projection to a composition in {1:.8f}s'.format(count, t, 's' if count != 1 else ''))
class TestPathway:
def test_pathway_standalone_object(self):
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
C = ProcessingMechanism(name='C')
p = Pathway(pathway=[A,B,C], name='P')
assert p.pathway == [A, B, C]
assert p.composition is None
assert p.name == 'P'
assert p.input is None
assert p.output is None
assert p.target is None
assert p.roles is None
assert p.learning_components is None
def test_pathway_assign_composition_arg_error(self):
c = Composition()
with pytest.raises(pnl.CompositionError) as error_text:
p = Pathway(pathway=[], composition='c')
assert "\'composition\' can not be specified as an arg in the constructor for a Pathway" in str(
error_text.value)
def test_pathway_assign_roles_error(self):
A = ProcessingMechanism()
c = Composition()
p = Pathway(pathway=[A])
with pytest.raises(AssertionError) as error_text:
p._assign_roles(composition=c)
assert (f"_assign_roles() cannot be called " in str(error_text.value) and
f"because it has not been assigned to a Composition" in str(error_text.value))
c.add_linear_processing_pathway(pathway=p)
p_c = c.pathways[0]
assert p_c._assign_roles(composition=c) is None
def test_pathway_illegal_arg_error(self):
with pytest.raises(pnl.CompositionError) as error_text:
Pathway(pathway=[], foo='bar')
assert "Illegal argument(s) used in constructor for Pathway: foo." in str(error_text.value)
class TestCompositionPathwayAdditionMethods:
def test_pathway_attributes(self):
c = Composition()
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
C = ProcessingMechanism(name='C')
D = ProcessingMechanism(name='D')
E = ProcessingMechanism(name='E')
F = ProcessingMechanism(name='F')
G = ProcessingMechanism(name='G')
p1 = c.add_linear_processing_pathway(pathway=[A,B,C], name='P')
p2 = c.add_linear_processing_pathway(pathway=[D,B])
p3 = c.add_linear_processing_pathway(pathway=[B,E])
l = c.add_linear_learning_pathway(pathway=[F,G], learning_function=Reinforcement, name='L')
assert p1.name == 'P'
assert p1.input == A
assert p1.output == C
assert p1.target is None
assert p2.input == D
assert p2.output is None
assert p2.target is None
assert p3.input is None
assert p3.output == E
assert p3.target is None
assert l.name == 'L'
assert l.input == F
assert l.output == G
assert l.target == c.nodes['Target']
assert l.learning_components[pnl.LEARNING_MECHANISMS] == \
c.nodes['Learning Mechanism for MappingProjection from F[OutputPort-0] to G[InputPort-0]']
assert l.learning_objective == c.nodes['Comparator']
assert all(p in {p1, p2, p3, l} for p in c.pathways)
def test_pathway_order_processing_then_learning_RL(self):
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
C = ProcessingMechanism(name='C')
D = ProcessingMechanism(name='D')
c = Composition()
c.add_linear_processing_pathway(pathway=[A,B])
c.add_linear_learning_pathway(pathway=[C,D], learning_function=Reinforcement)
assert all(n in {B, D} for n in c.get_nodes_by_role(NodeRole.OUTPUT))
def test_pathway_order_processing_then_learning_BP(self):
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
C = ProcessingMechanism(name='C')
D = ProcessingMechanism(name='D')
c = Composition()
c.add_linear_processing_pathway(pathway=[A,B])
c.add_linear_learning_pathway(pathway=[C,D], learning_function=BackPropagation)
assert all(n in {B, D} for n in c.get_nodes_by_role(NodeRole.OUTPUT))
def test_pathway_order_learning_RL_then_processing(self):
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
C = ProcessingMechanism(name='C')
D = ProcessingMechanism(name='D')
c = Composition()
c.add_linear_learning_pathway(pathway=[A,B], learning_function=Reinforcement)
c.add_linear_processing_pathway(pathway=[C,D])
assert all(n in {B, D} for n in c.get_nodes_by_role(NodeRole.OUTPUT))
def test_pathway_order_learning_BP_then_processing(self):
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
C = ProcessingMechanism(name='C')
D = ProcessingMechanism(name='D')
c = Composition()
c.add_linear_learning_pathway(pathway=[A,B], learning_function=BackPropagation)
c.add_linear_processing_pathway(pathway=[C,D])
assert all(n in {B, D} for n in c.get_nodes_by_role(NodeRole.OUTPUT))
def test_pathway_order_learning_RL_then_BP(self):
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
C = ProcessingMechanism(name='C')
D = ProcessingMechanism(name='D')
c = Composition()
c.add_linear_learning_pathway(pathway=[A,B], learning_function=Reinforcement)
c.add_linear_learning_pathway(pathway=[C,D], learning_function=BackPropagation)
assert all(n in {B, D} for n in c.get_nodes_by_role(NodeRole.OUTPUT))
def test_pathway_order_learning_BP_then_RL(self):
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
C = ProcessingMechanism(name='C')
D = ProcessingMechanism(name='D')
c = Composition()
c.add_linear_learning_pathway(pathway=[A,B], learning_function=BackPropagation)
c.add_linear_learning_pathway(pathway=[C,D], learning_function=Reinforcement)
assert all(n in {B, D} for n in c.get_nodes_by_role(NodeRole.OUTPUT))
def test_add_processing_pathway_arg_mech(self):
A = ProcessingMechanism(name='A')
c = Composition()
c.add_linear_processing_pathway(pathway=A)
assert set(c.get_roles_by_node(A)) == {NodeRole.INPUT,
NodeRole.ORIGIN,
NodeRole.SINGLETON,
NodeRole.OUTPUT,
NodeRole.TERMINAL}
assert set(c.pathways[0].roles) == {PathwayRole.INPUT,
PathwayRole.ORIGIN,
PathwayRole.SINGLETON,
PathwayRole.OUTPUT,
PathwayRole.TERMINAL}
def test_add_processing_pathway_arg_pathway(self):
pnl.clear_registry(pnl.PathwayRegistry)
A = ProcessingMechanism(name='A')
p = Pathway(pathway=A, name='P')
c = Composition()
c.add_linear_processing_pathway(pathway=p)
assert set(c.get_roles_by_node(A)) == {NodeRole.INPUT,
NodeRole.ORIGIN,
NodeRole.SINGLETON,
NodeRole.OUTPUT,
NodeRole.TERMINAL}
assert set(c.pathways['P'].roles) == {PathwayRole.INPUT,
PathwayRole.ORIGIN,
PathwayRole.SINGLETON,
PathwayRole.OUTPUT,
PathwayRole.TERMINAL}
def test_add_processing_pathway_with_errant_learning_function_warning(self):
pnl.clear_registry(pnl.PathwayRegistry)
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
p = Pathway(pathway=([A,B], Reinforcement), name='P')
c = Composition()
regexp = "LearningFunction found in specification of 'pathway' arg for "\
"add_linear_procesing_pathway method .*"\
r"Reinforcement'>; it will be ignored"
with pytest.warns(UserWarning, match=regexp):
c.add_linear_processing_pathway(pathway=p)
assert set(c.get_roles_by_node(A)) == {NodeRole.INPUT, NodeRole.ORIGIN}
assert set(c.get_roles_by_node(B)) == {NodeRole.OUTPUT, NodeRole.TERMINAL}
assert set(c.pathways['P'].roles) == {PathwayRole.INPUT,
PathwayRole.ORIGIN,
PathwayRole.OUTPUT,
PathwayRole.TERMINAL}
def test_add_learning_pathway_arg_pathway(self):
pnl.clear_registry(pnl.PathwayRegistry)
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
p = Pathway(pathway=[A,B], name='P')
c = Composition()
c.add_linear_learning_pathway(pathway=p, learning_function=BackPropagation)
assert set(c.get_roles_by_node(A)) == {NodeRole.INPUT, NodeRole.ORIGIN}
assert {NodeRole.OUTPUT}.issubset(c.get_roles_by_node(B))
assert set(c.pathways['P'].roles) == {PathwayRole.INPUT,
PathwayRole.ORIGIN,
PathwayRole.LEARNING,
PathwayRole.OUTPUT}
def test_add_learning_pathway_with_errant_learning_function_in_tuple_spec_error(self):
pnl.clear_registry(pnl.PathwayRegistry)
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
p = Pathway(pathway=([A,B], Reinforcement), name='P')
c = Composition()
with pytest.raises(pnl.CompositionError) as error_text:
c.add_linear_learning_pathway(pathway=p, learning_function=BackPropagation)
assert ("Specification in 'pathway' arg for " in str(error_text.value) and
"add_linear_procesing_pathway method" in str(error_text.value) and
"contains a tuple that specifies a different LearningFunction (Reinforcement)" in str(error_text.value)
and "than the one specified in its 'learning_function' arg (BackPropagation)" in str(error_text.value))
def test_add_bp_learning_pathway_arg_pathway(self):
pnl.clear_registry(pnl.PathwayRegistry)
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
p = Pathway(pathway=[A,B], name='P')
c = Composition()
c.add_backpropagation_learning_pathway(pathway=p)
assert {NodeRole.INPUT, NodeRole.ORIGIN}.issubset(c.get_roles_by_node(A))
assert {NodeRole.OUTPUT}.issubset(c.get_roles_by_node(B))
assert set(c.pathways['P'].roles) == {PathwayRole.INPUT,
PathwayRole.ORIGIN,
PathwayRole.LEARNING,
PathwayRole.OUTPUT}
def test_add_bp_learning_pathway_arg_pathway_name_in_method(self):
pnl.clear_registry(pnl.PathwayRegistry)
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
p = Pathway(pathway=[A,B], name='P')
c = Composition()
c.add_backpropagation_learning_pathway(pathway=p, name='BP')
assert {NodeRole.INPUT, NodeRole.ORIGIN}.issubset(set(c.get_roles_by_node(A)))
assert {NodeRole.OUTPUT}.issubset(set(c.get_roles_by_node(B)))
assert set(c.pathways['BP'].roles) == {PathwayRole.INPUT,
PathwayRole.ORIGIN,
PathwayRole.LEARNING,
PathwayRole.OUTPUT}
def test_add_rl_learning_pathway_arg_pathway(self):
pnl.clear_registry(pnl.PathwayRegistry)
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
p = Pathway(pathway=[A,B], name='P')
c = Composition()
c.add_reinforcement_learning_pathway(pathway=p)
assert {NodeRole.INPUT, NodeRole.ORIGIN}.issubset(set(c.get_roles_by_node(A)))
assert {NodeRole.OUTPUT}.issubset(set(c.get_roles_by_node(B)))
assert set(c.pathways['P'].roles) == {PathwayRole.INPUT,
PathwayRole.ORIGIN,
PathwayRole.LEARNING,
PathwayRole.OUTPUT}
def test_add_td_learning_pathway_arg_pathway(self):
pnl.clear_registry(pnl.PathwayRegistry)
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
p = Pathway(pathway=[A,B], name='P')
c = Composition()
c.add_td_learning_pathway(pathway=p)
assert {NodeRole.INPUT, NodeRole.ORIGIN}.issubset(set(c.get_roles_by_node(A)))
assert {NodeRole.OUTPUT}.issubset(set(c.get_roles_by_node(B)))
assert set(c.pathways['P'].roles) == {PathwayRole.INPUT,
PathwayRole.ORIGIN,
PathwayRole.LEARNING,
PathwayRole.OUTPUT}
def test_add_pathways_with_all_types(self):
pnl.clear_registry(pnl.PathwayRegistry)
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
C = ProcessingMechanism(name='C')
D = ProcessingMechanism(name='D')
E = ProcessingMechanism(name='E')
F = ProcessingMechanism(name='F')
G = ProcessingMechanism(name='G')
H = ProcessingMechanism(name='H')
J = ProcessingMechanism(name='J')
K = ProcessingMechanism(name='K')
L = ProcessingMechanism(name='L')
M = ProcessingMechanism(name='M')
p = Pathway(pathway=[L,M], name='P')
c = Composition()
c.add_pathways(pathways=[A,
[B,C],
(D,E),
{'DICT PATHWAY': F},
([G, H], BackPropagation),
{'LEARNING PATHWAY': ([J,K], Reinforcement)},
p])
assert len(c.pathways) == 7
assert c.pathways['P'].input == L
assert c.pathways['DICT PATHWAY'].input == F
assert c.pathways['DICT PATHWAY'].output == F
assert c.pathways['LEARNING PATHWAY'].output == K
[p for p in c.pathways if p.input == G][0].learning_function == BackPropagation
assert c.pathways['LEARNING PATHWAY'].learning_function == Reinforcement
def test_add_pathways_bad_arg_error(self):
I = InputPort(name='I')
c = Composition()
with pytest.raises(pnl.CompositionError) as error_text:
c.add_pathways(pathways=I)
assert ("The \'pathways\' arg for the add_pathways method" in str(error_text.value)
and "must be a Node, list, tuple, dict or Pathway object" in str(error_text.value))
def test_add_pathways_arg_pathways_list_and_item_not_list_or_dict_or_node_error(self):
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
c = Composition()
with pytest.raises(pnl.CompositionError) as error_text:
c.add_pathways(pathways=[[A,B], 'C'])
assert ("Every item in the \'pathways\' arg for the add_pathways method" in str(error_text.value)
and "must be a Node, list, tuple or dict:" in str(error_text.value))
def test_for_add_processing_pathway_recursion_error(self):
A = TransferMechanism()
C = Composition()
with pytest.raises(pnl.CompositionError) as error_text:
C.add_linear_processing_pathway(pathway=[A,C])
assert f"Attempt to add Composition as a Node to itself in 'pathway' arg for " \
f"add_linear_procesing_pathway method of {C.name}." in str(error_text.value)
def test_for_add_learning_pathway_recursion_error(self):
A = TransferMechanism()
C = Composition()
with pytest.raises(pnl.CompositionError) as error_text:
C.add_backpropagation_learning_pathway(pathway=[A,C])
assert f"Attempt to add Composition as a Node to itself in 'pathway' arg for " \
f"add_backpropagation_learning_pathway method of {C.name}." in str(error_text.value)
class TestDuplicatePathwayWarnings:
def test_add_processing_pathway_exact_duplicate_warning(self):
A = TransferMechanism()
B = TransferMechanism()
P = MappingProjection(sender=A, receiver=B)
comp = Composition()
comp.add_linear_processing_pathway(pathway=[A,P,B])
regexp = "Pathway specified in 'pathway' arg for add_linear_procesing_pathway method .*"\
f"already exists in {comp.name}"
with pytest.warns(UserWarning, match=regexp):
comp.add_linear_processing_pathway(pathway=[A,P,B])
def test_add_processing_pathway_inferred_duplicate_warning(self):
A = TransferMechanism()
B = TransferMechanism()
C = TransferMechanism()
comp = Composition()
comp.add_linear_processing_pathway(pathway=[A,B,C])
regexp = "Pathway specified in 'pathway' arg for add_linear_procesing_pathway method .*"\
f"has same Nodes in same order as one already in {comp.name}"
with pytest.warns(UserWarning, match=regexp):
comp.add_linear_processing_pathway(pathway=[A,B,C])
def test_add_processing_pathway_subset_duplicate_warning(self):
A = TransferMechanism()
B = TransferMechanism()
C = TransferMechanism()
comp = Composition()
comp.add_linear_processing_pathway(pathway=[A,B,C])
regexp = "Pathway specified in 'pathway' arg for add_linear_procesing_pathway method .*"\
f"has same Nodes in same order as one already in {comp.name}"
with pytest.warns(UserWarning, match=regexp):
comp.add_linear_processing_pathway(pathway=[A,B])
def test_add_backpropagation_pathway_exact_duplicate_warning(self):
A = TransferMechanism()
B = TransferMechanism()
P = MappingProjection(sender=A, receiver=B)
comp = Composition()
comp.add_backpropagation_learning_pathway(pathway=[A,P,B])
regexp = "Pathway specified in 'pathway' arg for add_backpropagation_learning_pathway method .*"\
f"already exists in {comp.name}"
with pytest.warns(UserWarning, match=regexp):
comp.add_backpropagation_learning_pathway(pathway=[A,P,B])
def test_add_backpropagation_pathway_inferred_duplicate_warning(self):
A = TransferMechanism()
B = TransferMechanism()
C = TransferMechanism()
comp = Composition()
comp.add_backpropagation_learning_pathway(pathway=[A,B,C])
regexp = "Pathway specified in 'pathway' arg for add_backpropagation_learning_pathway method .*"\
f"has same Nodes in same order as one already in {comp.name}"
with pytest.warns(UserWarning, match=regexp):
comp.add_backpropagation_learning_pathway(pathway=[A,B,C])
def test_add_backpropagation_pathway_contiguous_subset_duplicate_warning(self):
A = TransferMechanism()
B = TransferMechanism()
C = TransferMechanism()
comp = Composition()
comp.add_backpropagation_learning_pathway(pathway=[A,B,C])
regexp = "Pathway specified in 'pathway' arg for add_backpropagation_learning_pathway method .*"\
f"has same Nodes in same order as one already in {comp.name}"
with pytest.warns(UserWarning, match=regexp):
comp.add_backpropagation_learning_pathway(pathway=[A,B])
def test_add_processing_pathway_non_contiguous_subset_is_OK(self):
A = TransferMechanism()
B = TransferMechanism()
C = TransferMechanism()
comp = Composition()
comp.add_linear_processing_pathway(pathway=[A,B,C])
comp.add_linear_processing_pathway(pathway=[A,C])
{A,B,C} == set(comp.nodes)
len(comp.pathways)==2
def test_add_processing_pathway_same_nodes_but_reversed_order_is_OK(self):
A = TransferMechanism()
B = TransferMechanism()
comp = Composition()
comp.add_linear_processing_pathway(pathway=[A,B])
comp.add_linear_processing_pathway(pathway=[B,A])
{A,B} == set(comp.nodes)
len(comp.pathways)==2
class TestCompositionPathwaysArg:
def test_composition_pathways_arg_pathway_object(self):
pnl.clear_registry(pnl.PathwayRegistry)
A = ProcessingMechanism(name='A')
p = Pathway(pathway=A, name='P')
c = Composition(pathways=p)
assert set(c.get_roles_by_node(A)) == {NodeRole.INPUT,
NodeRole.ORIGIN,
NodeRole.SINGLETON,
NodeRole.OUTPUT,
NodeRole.TERMINAL}
assert set(c.pathways['P'].roles) == {PathwayRole.INPUT,
PathwayRole.ORIGIN,
PathwayRole.SINGLETON,
PathwayRole.OUTPUT,
PathwayRole.TERMINAL}
def test_composition_pathways_arg_pathway_object_in_dict_with_name(self):
pnl.clear_registry(pnl.PathwayRegistry)
A = ProcessingMechanism(name='A')
p = Pathway(pathway=[A], name='P')
c = Composition(pathways={'DICT NAMED':p})
assert set(c.get_roles_by_node(A)) == {NodeRole.INPUT,
NodeRole.ORIGIN,
NodeRole.SINGLETON,
NodeRole.OUTPUT,
NodeRole.TERMINAL}
assert set(c.pathways['DICT NAMED'].roles) == {PathwayRole.INPUT,
PathwayRole.ORIGIN,
PathwayRole.SINGLETON,
PathwayRole.OUTPUT,
PathwayRole.TERMINAL}
def test_composition_pathways_arg_mech(self):
A = ProcessingMechanism(name='A')
c = Composition(pathways=A)
assert set(c.get_roles_by_node(A)) == {NodeRole.INPUT,
NodeRole.ORIGIN,
NodeRole.SINGLETON,
NodeRole.OUTPUT,
NodeRole.TERMINAL}
assert set(c.pathways[0].roles) == {PathwayRole.INPUT,
PathwayRole.ORIGIN,
PathwayRole.SINGLETON,
PathwayRole.OUTPUT,
PathwayRole.TERMINAL}
def test_composition_pathways_arg_dict_and_list_and_pathway_roles(self):
pnl.clear_registry(pnl.PathwayRegistry)
A = ProcessingMechanism(name='A')
B = ProcessingMechanism(name='B')
C = ProcessingMechanism(name='C')
D = ProcessingMechanism(name='D')
c = Composition(pathways=[{'P1':[A,B]}, [C,D]])
assert all(n in {A, C} for n in c.get_nodes_by_role(NodeRole.INPUT))
assert all(n in {B, D} for n in c.get_nodes_by_role(NodeRole.OUTPUT))
assert c.pathways['P1'].name == 'P1'
assert set(c.pathways['P1'].roles) == {PathwayRole.ORIGIN,
PathwayRole.INPUT,
PathwayRole.OUTPUT,
PathwayRole.TERMINAL}
assert set(c.pathways['P1'].roles).isdisjoint({PathwayRole.SINGLETON,
PathwayRole.CYCLE,
PathwayRole.CONTROL,
PathwayRole.LEARNING})
assert set(c.pathways[1].roles) == {PathwayRole.ORIGIN,
PathwayRole.INPUT,