Exemple #1
0
    def test_control_signal_and_control_projection_names(self):
        D1 = pnl.DDM(name='D1')
        D2 = pnl.DDM(name='D2')

        # ControlSignal with one ControlProjection
        C1 = pnl.ControlMechanism(control_signals=[D1.parameter_states[
                                                       psyneulink.core.components.functions.distributionfunctions.DRIFT_RATE]])
        assert C1.control_signals[0].name == 'D1[drift_rate] ControlSignal'
        assert C1.control_signals[0].efferents[0].name == 'ControlProjection for D1[drift_rate]'

        # ControlSignal with two ControlProjection to two parameters of same Mechanism
        C2 = pnl.ControlMechanism(control_signals=[{pnl.PROJECTIONS:[D1.parameter_states[
                                                                         psyneulink.core.components.functions.distributionfunctions.DRIFT_RATE],
                                                                     D1.parameter_states[
                                                                         psyneulink.core.components.functions.distributionfunctions.THRESHOLD]]}])
        assert C2.control_signals[0].name == 'D1[drift_rate, threshold] ControlSignal'
        assert C2.control_signals[0].efferents[0].name == 'ControlProjection for D1[drift_rate]'
        assert C2.control_signals[0].efferents[1].name == 'ControlProjection for D1[threshold]'

        # ControlSignal with two ControlProjection to two parameters of different Mechanisms
        C3 = pnl.ControlMechanism(control_signals=[{pnl.PROJECTIONS:[D1.parameter_states[
                                                                         psyneulink.core.components.functions.distributionfunctions.DRIFT_RATE],
                                                                     D2.parameter_states[
                                                                         psyneulink.core.components.functions.distributionfunctions.DRIFT_RATE]]}])
        assert C3.control_signals[0].name == 'ControlSignal-0 divergent ControlSignal'
        assert C3.control_signals[0].efferents[0].name == 'ControlProjection for D1[drift_rate]'
        assert C3.control_signals[0].efferents[1].name == 'ControlProjection for D2[drift_rate]'
    def test_formats_for_control_specification_for_mechanism_and_function_params(
            self):

        control_spec_list = [
            pnl.CONTROL, pnl.CONTROL_SIGNAL, pnl.CONTROL_PROJECTION,
            pnl.ControlSignal,
            pnl.ControlSignal(), pnl.ControlProjection, "CP_OBJECT",
            pnl.ControlMechanism,
            pnl.ControlMechanism(), (0.3, pnl.CONTROL),
            (0.3, pnl.CONTROL_SIGNAL), (0.3, pnl.CONTROL_PROJECTION),
            (0.3, pnl.ControlSignal), (0.3, pnl.ControlSignal()),
            (0.3, pnl.ControlProjection), (0.3, "CP_OBJECT"),
            (0.3, pnl.ControlMechanism), (0.3, pnl.ControlMechanism())
        ]
        for i, ctl_tuple in enumerate(
            [j for j in zip(control_spec_list, reversed(control_spec_list))]):
            C1, C2 = ctl_tuple

            # This shenanigans is to avoid assigning the same instantiated ControlProjection more than once
            if C1 is 'CP_OBJECT':
                C1 = pnl.ControlProjection()
            elif isinstance(C1, tuple) and C1[1] is 'CP_OBJECT':
                C1 = (C1[0], pnl.ControlProjection())
            if C2 is 'CP_OBJECT':
                C2 = pnl.ControlProjection()
            elif isinstance(C2, tuple) and C2[1] is 'CP_OBJECT':
                C2 = (C2[0], pnl.ControlProjection())

            R = pnl.RecurrentTransferMechanism(noise=C1,
                                               function=pnl.Logistic(gain=C2))
            assert R.parameter_states[pnl.NOISE].mod_afferents[0].name in \
                   'ControlProjection for RecurrentTransferMechanism-{}[noise]'.format(i)
            assert R.parameter_states[pnl.GAIN].mod_afferents[0].name in \
                   'ControlProjection for RecurrentTransferMechanism-{}[gain]'.format(i)
Exemple #3
0
    def test_2_item_tuple_from_control_signal_to_parameter_state(self):

        D = pnl.DDM(name='D')

        # Single name
        C = pnl.ControlMechanism(control_signals=[(pnl.DRIFT_RATE, D)])
        assert C.control_signals[0].name == 'D[drift_rate] ControlSignal'
        assert C.control_signals[0].efferents[0].receiver.name == 'drift_rate'

        # List of names
        C = pnl.ControlMechanism(control_signals=[([pnl.DRIFT_RATE, pnl.THRESHOLD], D)])
        assert C.control_signals[0].name == 'D[drift_rate, threshold] ControlSignal'
        assert C.control_signals[0].efferents[0].receiver.name == 'drift_rate'
        assert C.control_signals[0].efferents[1].receiver.name == 'threshold'
    def test_multiple_modulatory_projections_with_mech_and_port_Name_specs(
            self):

        M = pnl.DDM(name='MY DDM')
        C = pnl.ControlMechanism(control_signals=[{
            pnl.MECHANISM:
            M,
            pnl.PARAMETER_PORTS: [
                psyneulink.core.components.functions.distributionfunctions.
                DRIFT_RATE, psyneulink.core.globals.keywords.THRESHOLD
            ]
        }])
        G = pnl.GatingMechanism(gating_signals=[{
            pnl.MECHANISM:
            M,
            pnl.OUTPUT_PORTS: [pnl.DECISION_VARIABLE, pnl.RESPONSE_TIME]
        }])
        assert len(C.control_signals) == 1
        assert len(C.control_signals[0].efferents) == 2
        assert M.parameter_ports[
            psyneulink.core.components.functions.distributionfunctions.
            DRIFT_RATE].mod_afferents[0] == C.control_signals[0].efferents[0]
        assert M.parameter_ports[
            psyneulink.core.globals.keywords.
            THRESHOLD].mod_afferents[0] == C.control_signals[0].efferents[1]
        assert len(G.gating_signals) == 1
        assert len(G.gating_signals[0].efferents) == 2
        assert M.output_ports[pnl.DECISION_VARIABLE].mod_afferents[
            0] == G.gating_signals[0].efferents[0]
        assert M.output_ports[pnl.RESPONSE_TIME].mod_afferents[
            0] == G.gating_signals[0].efferents[1]
    def test_multiple_modulatory_projections_with_port_Name(self):

        M = pnl.DDM(name='MY DDM')
        C = pnl.ControlMechanism(control_signals=[{
            'DECISION_CONTROL': [
                M.parameter_ports[psyneulink.core.components.functions.
                                  distributionfunctions.DRIFT_RATE],
                M.parameter_ports[psyneulink.core.globals.keywords.THRESHOLD]
            ]
        }])
        G = pnl.GatingMechanism(gating_signals=[{
            'DDM_OUTPUT_GATE': [
                M.output_ports[pnl.DECISION_VARIABLE], M.output_ports[
                    pnl.RESPONSE_TIME]
            ]
        }])
        assert len(C.control_signals) == 1
        assert C.control_signals[0].name == 'DECISION_CONTROL'
        assert len(C.control_signals[0].efferents) == 2
        assert M.parameter_ports[
            psyneulink.core.components.functions.distributionfunctions.
            DRIFT_RATE].mod_afferents[0] == C.control_signals[0].efferents[0]
        assert M.parameter_ports[
            psyneulink.core.globals.keywords.
            THRESHOLD].mod_afferents[0] == C.control_signals[0].efferents[1]
        assert len(G.gating_signals) == 1
        assert G.gating_signals[0].name == 'DDM_OUTPUT_GATE'
        assert len(G.gating_signals[0].efferents) == 2
        assert M.output_ports[pnl.DECISION_VARIABLE].mod_afferents[
            0] == G.gating_signals[0].efferents[0]
        assert M.output_ports[pnl.RESPONSE_TIME].mod_afferents[
            0] == G.gating_signals[0].efferents[1]
    def test_multiple_modulatory_projections_with_state_name(self):

        M = pnl.DDM(name='MY DDM')
        C = pnl.ControlMechanism(control_signals=[{
            'DECISION_CONTROL': [
                M.parameter_states[pnl.DRIFT_RATE], M.parameter_states[
                    pnl.THRESHOLD]
            ]
        }])
        G = pnl.GatingMechanism(gating_signals=[{
            'DDM_OUTPUT_GATE': [
                M.output_states[pnl.DECISION_VARIABLE], M.output_states[
                    pnl.RESPONSE_TIME]
            ]
        }])
        assert len(C.control_signals) == 1
        assert C.control_signals[0].name == 'DECISION_CONTROL'
        assert len(C.control_signals[0].efferents) == 2
        assert M.parameter_states[pnl.DRIFT_RATE].mod_afferents[
            0] == C.control_signals[0].efferents[0]
        assert M.parameter_states[pnl.THRESHOLD].mod_afferents[
            0] == C.control_signals[0].efferents[1]
        assert len(G.gating_signals) == 1
        assert G.gating_signals[0].name == 'DDM_OUTPUT_GATE'
        assert len(G.gating_signals[0].efferents) == 2
        assert M.output_states[pnl.DECISION_VARIABLE].mod_afferents[
            0] == G.gating_signals[0].efferents[0]
        assert M.output_states[pnl.RESPONSE_TIME].mod_afferents[
            0] == G.gating_signals[0].efferents[1]
Exemple #7
0
def test_DDM_threshold_modulation(mode):
    M = pnl.DDM(
        name='DDM',
        function=pnl.DriftDiffusionAnalytical(
            threshold=20.0,
        ),
    )
    monitor = pnl.TransferMechanism(default_variable=[[0.0]],
                                    size=1,
                                    function=pnl.Linear(slope=1, intercept=0),
                                    output_ports=[pnl.RESULT],
                                    name='monitor')

    control = pnl.ControlMechanism(
            monitor_for_control=monitor,
            control_signals=[(pnl.THRESHOLD, M)])

    C = pnl.Composition()
    C.add_node(M, required_roles=[pnl.NodeRole.ORIGIN, pnl.NodeRole.TERMINAL])
    C.add_node(monitor)
    C.add_node(control)
    inputs = {M:[1], monitor:[3]}
    val = C.run(inputs, num_trials=1, bin_execute=mode)
    # FIXME: Python version returns dtype=object
    val = np.asfarray(val)
    assert np.allclose(val[0], [60.0])
    assert np.allclose(val[1], [60.2])
    def test_multiple_modulatory_projection_specs(self):

        M = pnl.DDM(name='MY DDM')
        C = pnl.ControlMechanism(control_signals=[{
            pnl.PROJECTIONS: [
                M.parameter_ports[
                    psyneulink.core.components.functions.nonstateful.
                    distributionfunctions.DRIFT_RATE], M.parameter_ports[
                        psyneulink.core.globals.keywords.THRESHOLD]
            ]
        }])
        G = pnl.GatingMechanism(gating_signals=[{
            pnl.PROJECTIONS: [
                M.output_ports[pnl.DECISION_VARIABLE], M.output_ports[
                    pnl.RESPONSE_TIME]
            ]
        }])
        assert len(C.control_signals) == 1
        assert len(C.control_signals[0].efferents) == 2
        assert M.parameter_ports[
            psyneulink.core.components.functions.nonstateful.
            distributionfunctions.
            DRIFT_RATE].mod_afferents[0] == C.control_signals[0].efferents[0]
        assert M.parameter_ports[
            psyneulink.core.globals.keywords.
            THRESHOLD].mod_afferents[0] == C.control_signals[0].efferents[1]
        assert len(G.gating_signals) == 1
        assert len(G.gating_signals[0].efferents) == 2
        assert M.output_ports[pnl.DECISION_VARIABLE].mod_afferents[
            0] == G.gating_signals[0].efferents[0]
        assert M.output_ports[pnl.RESPONSE_TIME].mod_afferents[
            0] == G.gating_signals[0].efferents[1]
    def test_multiple_modulatory_projection_specs(self):

        M = pnl.DDM(name='MY DDM')
        C = pnl.ControlMechanism(control_signals=[{
            pnl.PROJECTIONS: [
                M.parameter_states[pnl.DRIFT_RATE], M.parameter_states[
                    pnl.THRESHOLD]
            ]
        }])
        G = pnl.GatingMechanism(gating_signals=[{
            pnl.PROJECTIONS: [
                M.output_states[pnl.DECISION_VARIABLE], M.output_states[
                    pnl.RESPONSE_TIME]
            ]
        }])
        assert len(C.control_signals) == 1
        assert len(C.control_signals[0].efferents) == 2
        assert M.parameter_states[pnl.DRIFT_RATE].mod_afferents[
            0] == C.control_signals[0].efferents[0]
        assert M.parameter_states[pnl.THRESHOLD].mod_afferents[
            0] == C.control_signals[0].efferents[1]
        assert len(G.gating_signals) == 1
        assert len(G.gating_signals[0].efferents) == 2
        assert M.output_states[pnl.DECISION_VARIABLE].mod_afferents[
            0] == G.gating_signals[0].efferents[0]
        assert M.output_states[pnl.RESPONSE_TIME].mod_afferents[
            0] == G.gating_signals[0].efferents[1]
    def test_multiple_modulatory_projections_with_mech_and_state_name_specs(
            self):

        M = pnl.DDM(name='MY DDM')
        C = pnl.ControlMechanism(control_signals=[{
            pnl.MECHANISM:
            M,
            pnl.PARAMETER_STATES: [pnl.DRIFT_RATE, pnl.THRESHOLD]
        }])
        G = pnl.GatingMechanism(gating_signals=[{
            pnl.MECHANISM:
            M,
            pnl.OUTPUT_STATES: [pnl.DECISION_VARIABLE, pnl.RESPONSE_TIME]
        }])
        assert len(C.control_signals) == 1
        assert len(C.control_signals[0].efferents) == 2
        assert M.parameter_states[pnl.DRIFT_RATE].mod_afferents[
            0] == C.control_signals[0].efferents[0]
        assert M.parameter_states[pnl.THRESHOLD].mod_afferents[
            0] == C.control_signals[0].efferents[1]
        assert len(G.gating_signals) == 1
        assert len(G.gating_signals[0].efferents) == 2
        assert M.output_states[pnl.DECISION_VARIABLE].mod_afferents[
            0] == G.gating_signals[0].efferents[0]
        assert M.output_states[pnl.RESPONSE_TIME].mod_afferents[
            0] == G.gating_signals[0].efferents[1]
Exemple #11
0
    def test_2_item_tuple_from_parameter_state_to_control_signals(self):

        C = pnl.ControlMechanism(control_signals=['a','b'])
        D = pnl.DDM(name='D3',
                     function=pnl.BogaczEtAl(drift_rate=(3,C),
                                             threshold=(2,C.control_signals['b']))
                    )
        assert D.parameter_states[pnl.DRIFT_RATE].mod_afferents[0].sender==C.control_signals[0]
        assert D.parameter_states[pnl.THRESHOLD].mod_afferents[0].sender==C.control_signals[1]
    def test_2_item_tuple_from_control_signal_to_parameter_port(self):

        D = pnl.DDM(name='D')

        # Single name
        C = pnl.ControlMechanism(
            control_signals=[(psyneulink.core.components.functions.
                              distributionfunctions.DRIFT_RATE, D)])
        assert C.control_signals[0].name == 'D[drift_rate] ControlSignal'
        assert C.control_signals[0].efferents[0].receiver.name == 'drift_rate'

        # List of names
        C = pnl.ControlMechanism(control_signals=[([
            psyneulink.core.components.functions.distributionfunctions.
            DRIFT_RATE, psyneulink.core.globals.keywords.THRESHOLD
        ], D)])
        assert C.control_signals[
            0].name == 'D[drift_rate, threshold] ControlSignal'
        assert C.control_signals[0].efferents[0].receiver.name == 'drift_rate'
        assert C.control_signals[0].efferents[1].receiver.name == 'threshold'
 def test_control_of_all_input_ports(self):
     mech = pnl.ProcessingMechanism(input_ports=['A', 'B', 'C'])
     control_mech = pnl.ControlMechanism(control=mech.input_ports)
     comp = pnl.Composition()
     comp.add_nodes([(mech, pnl.NodeRole.INPUT),
                     (control_mech, pnl.NodeRole.INPUT)])
     results = comp.run(inputs={
         mech: [[2], [2], [2]],
         control_mech: [2]
     },
                        num_trials=2)
     np.allclose(results, [[4], [4], [4]])
    def test_2_item_tuple_from_parameter_port_to_control_signals(self):

        C = pnl.ControlMechanism(control_signals=['a', 'b'])
        D = pnl.DDM(name='D3',
                    function=psyneulink.core.components.functions.
                    distributionfunctions.DriftDiffusionAnalytical(
                        drift_rate=(3, C),
                        threshold=(2, C.control_signals['b'])))
        assert D.parameter_ports[
            psyneulink.core.components.functions.distributionfunctions.
            DRIFT_RATE].mod_afferents[0].sender == C.control_signals[0]
        assert D.parameter_ports[
            psyneulink.core.globals.keywords.
            THRESHOLD].mod_afferents[0].sender == C.control_signals[1]
    def test_control_modulation(self):
        Tx = pnl.TransferMechanism(name='Tx')
        Ty = pnl.TransferMechanism(name='Ty')
        Tz = pnl.TransferMechanism(name='Tz')
        C = pnl.ControlMechanism(
            # function=pnl.Linear,
            default_variable=[1],
            monitor_for_control=Ty,
            objective_mechanism=True,
            control_signals=pnl.ControlSignal(modulation=pnl.OVERRIDE,
                                              modulates=(pnl.SLOPE, Tz)))
        comp = pnl.Composition(pathways=[[Tx, Tz], [Ty, C]])
        # comp.show_graph()

        assert Tz.parameter_ports[pnl.SLOPE].mod_afferents[0].sender.owner == C
        result = comp.run(inputs={Tx: [1, 1], Ty: [4, 4]})
        assert comp.results == [[[4.], [4.]], [[4.], [4.]]]
    def test_control_modulation(self):
        Tx = pnl.TransferMechanism(name='Tx')
        Ty = pnl.TransferMechanism(name='Ty')
        Tz = pnl.TransferMechanism(name='Tz')
        C =  pnl.ControlMechanism(
                # function=pnl.Linear,
                default_variable=[1],
                monitor_for_control=Ty,
                control_signals=pnl.ControlSignal(modulation=pnl.OVERRIDE,
                                                  projections=(pnl.SLOPE,Tz)))
        P1=pnl.Process(pathway=[Tx,Tz])
        P2=pnl.Process(pathway=[Ty, C])
        S=pnl.System(processes=[P1, P2])

        assert Tz.parameter_states[pnl.SLOPE].mod_afferents[0].sender.owner == C
        result = S.run(inputs={Tx:[1,1], Ty:[4,4]})
        assert result == [[[4.], [4.]], [[4.], [4.]]]
 def test_control_of_all_output_ports(self):
     mech = pnl.ProcessingMechanism(output_ports=[{
         pnl.VARIABLE: (pnl.OWNER_VALUE, 0)
     }, {
         pnl.VARIABLE: (pnl.OWNER_VALUE, 0)
     }, {
         pnl.VARIABLE: (pnl.OWNER_VALUE, 0)
     }], )
     control_mech = pnl.ControlMechanism(control=mech.output_ports)
     comp = pnl.Composition()
     comp.add_nodes([(mech, pnl.NodeRole.INPUT),
                     (control_mech, pnl.NodeRole.INPUT)])
     results = comp.run(inputs={
         mech: [[2]],
         control_mech: [3]
     },
                        num_trials=2)
     np.allclose(results, [[6], [6], [6]])
    }],
)
Conflict_Monitor = pnl.ObjectiveMechanism(
    name="Conflict_Monitor",
    function=pnl.Energy(matrix=[[0, -2.5], [-2.5, 0]],
                        default_variable=[[0.0, 0.0]]),
    monitor=[OUTPUT],
    default_variable=[[0.0, 0.0]],
)

CONTROL = pnl.ControlMechanism(
    name="CONTROL",
    default_allocation=[0.5],
    function=pnl.DefaultAllocationFunction(default_variable=[[1.0]]),
    monitor_for_control=[],
    objective_mechanism=Conflict_Monitor,
    control=[{
        pnl.NAME: pnl.GAIN,
        pnl.MECHANISM: TASK
    }],
)

Stroop_model.add_node(color_input)
Stroop_model.add_node(color_hidden)
Stroop_model.add_node(OUTPUT)
Stroop_model.add_node(word_input)
Stroop_model.add_node(word_hidden)
Stroop_model.add_node(task_input)
Stroop_model.add_node(TASK)
Stroop_model.add_node(DECISION)
Stroop_model.add_node(Conflict_Monitor, pnl.NodeRole.CONTROLLER_OBJECTIVE)
Exemple #19
0
                default_variable=[[0.0, 0.0]], weights=[1, -1]
            ),
            pnl.NAME: pnl.ARRAY,
            pnl.VARIABLE: [[0.0, 0.0]],
        }
    ],
)

CONTROL = pnl.ControlMechanism(
    name="CONTROL",
    default_allocation=[0.5],
    function=pnl.DefaultAllocationFunction(default_variable=[[1.0]]),
    monitor_for_control=[],
    objective_mechanism=pnl.ObjectiveMechanism(
        name="Conflict Monitor",
        function=pnl.Energy(
            matrix=[[0, -2.5], [-2.5, 0]], default_variable=[[0.0, 0.0]]
        ),
        monitor=[OUTPUT],
        default_variable=[[0.0, 0.0]],
    ),
    control=[{pnl.MECHANISM: TASK, pnl.NAME: pnl.GAIN}],
)

Stroop_model.add_node(color_input)
Stroop_model.add_node(color_hidden)
Stroop_model.add_node(OUTPUT)
Stroop_model.add_node(word_input)
Stroop_model.add_node(word_hidden)
Stroop_model.add_node(task_input)
Stroop_model.add_node(TASK)
    def test_identicalness_of_control_and_gating(self):
        """Tests same configuration as gating in tests/mechansims/test_gating_mechanism"""
        Input_Layer = pnl.TransferMechanism(name='Input Layer',
                                            function=pnl.Logistic,
                                            size=2)
        Hidden_Layer_1 = pnl.TransferMechanism(name='Hidden Layer_1',
                                               function=pnl.Logistic,
                                               size=5)
        Hidden_Layer_2 = pnl.TransferMechanism(name='Hidden Layer_2',
                                               function=pnl.Logistic,
                                               size=4)
        Output_Layer = pnl.TransferMechanism(name='Output Layer',
                                             function=pnl.Logistic,
                                             size=3)

        Control_Mechanism = pnl.ControlMechanism(size=[1],
                                                 control=[
                                                     Hidden_Layer_1.input_port,
                                                     Hidden_Layer_2.input_port,
                                                     Output_Layer.input_port
                                                 ])

        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)
        # This projection is specified in add_backpropagation_learning_pathway method below
        Input_Weights = pnl.MappingProjection(name='Input Weights',
                                              matrix=Input_Weights_matrix)
        # This projection is "discovered" by add_backpropagation_learning_pathway method below
        Middle_Weights = pnl.MappingProjection(name='Middle Weights',
                                               sender=Hidden_Layer_1,
                                               receiver=Hidden_Layer_2,
                                               matrix={
                                                   pnl.VALUE:
                                                   Middle_Weights_matrix,
                                                   pnl.FUNCTION:
                                                   pnl.AccumulatorIntegrator,
                                                   pnl.FUNCTION_PARAMS: {
                                                       pnl.DEFAULT_VARIABLE:
                                                       Middle_Weights_matrix,
                                                       pnl.INITIALIZER:
                                                       Middle_Weights_matrix,
                                                       pnl.RATE:
                                                       Middle_Weights_matrix
                                                   },
                                               })
        Output_Weights = pnl.MappingProjection(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 = pnl.Composition()
        backprop_pathway = comp.add_backpropagation_learning_pathway(
            pathway=pathway,
            loss_function=None,
        )
        # c.add_linear_processing_pathway(pathway=z)
        comp.add_node(Control_Mechanism)

        stim_list = {
            Input_Layer: [[-1, 30]],
            Control_Mechanism: [1.0],
            backprop_pathway.target: [[0, 0, 1]]
        }

        comp.learn(num_trials=3, inputs=stim_list)

        expected_results = [[[0.81493513, 0.85129046, 0.88154205]],
                            [[0.81331773, 0.85008207, 0.88157851]],
                            [[0.81168332, 0.84886047, 0.88161468]]]
        assert np.allclose(comp.results, expected_results)

        stim_list[Control_Mechanism] = [0.0]
        results = comp.learn(num_trials=1, inputs=stim_list)
        expected_results = [[[0.5, 0.5, 0.5]]]
        assert np.allclose(results, expected_results)

        stim_list[Control_Mechanism] = [2.0]
        results = comp.learn(num_trials=1, inputs=stim_list)
        expected_results = [[0.96941429, 0.9837254, 0.99217549]]
        assert np.allclose(results, expected_results)
    def test_control_signal_default_allocation_specification(self):

        m1 = pnl.ProcessingMechanism()
        m2 = pnl.ProcessingMechanism()
        m3 = pnl.ProcessingMechanism()

        # default_allocation not specified in constructor of pnl.ControlMechanism,
        #     so should be set to defaultControlAllocation (=[1]) if not specified in pnl.ControlSignal constructor
        c1 = pnl.ControlMechanism(
            name='C1',
            default_variable=[10],
            control_signals=[
                pnl.ControlSignal(modulates=(
                    pnl.SLOPE,
                    m1)),  # test for assignment to defaultControlAllocation
                pnl.ControlSignal(
                    default_allocation=2,  # test for scalar assignment
                    modulates=(pnl.SLOPE, m2)),
                pnl.ControlSignal(
                    default_allocation=[3],  # test for array assignment
                    modulates=(pnl.SLOPE, m3))
            ])
        comp = pnl.Composition()
        comp.add_nodes([m1, m2, m3])
        comp.add_controller(c1)
        assert c1.control_signals[0].value == [
            10
        ]  # defaultControlAllocation should be assigned
        # (as no default_allocation from pnl.ControlMechanism)
        assert m1.parameter_ports[pnl.SLOPE].value == [1]
        assert c1.control_signals[1].value == [
            2
        ]  # default_allocation from pnl.ControlSignal (converted scalar)
        assert m2.parameter_ports[pnl.SLOPE].value == [1]
        assert c1.control_signals[2].value == [
            3
        ]  # default_allocation from pnl.ControlSignal
        assert m3.parameter_ports[pnl.SLOPE].value == [1]
        result = comp.run(inputs={m1: [2], m2: [3], m3: [4]})
        assert np.allclose(result, [[20.], [6.], [12.]])
        assert c1.control_signals[0].value == [10]
        assert m1.parameter_ports[pnl.SLOPE].value == [10]
        assert c1.control_signals[1].value == [10]
        assert m2.parameter_ports[pnl.SLOPE].value == [2]
        assert c1.control_signals[2].value == [10]
        assert m3.parameter_ports[pnl.SLOPE].value == [3]
        result = comp.run(inputs={m1: [2], m2: [3], m3: [4]})
        assert np.allclose(result, [[20.], [30.], [40.]])
        assert c1.control_signals[0].value == [10]
        assert m1.parameter_ports[pnl.SLOPE].value == [10]
        assert c1.control_signals[1].value == [10]
        assert m2.parameter_ports[pnl.SLOPE].value == [10]
        assert c1.control_signals[2].value == [10]
        assert m3.parameter_ports[pnl.SLOPE].value == [10]

        # default_allocation *is* specified in constructor of pnl.ControlMechanism,
        #     so should be used unless specified in pnl.ControlSignal constructor
        c2 = pnl.ControlMechanism(
            name='C3',
            default_variable=[10],
            default_allocation=[4],
            control_signals=[
                pnl.ControlSignal(modulates=(
                    pnl.SLOPE,
                    m1)),  # tests for assignment to default_allocation
                pnl.ControlSignal(
                    default_allocation=
                    5,  # tests for override of default_allocation
                    modulates=(pnl.SLOPE, m2)),
                pnl.ControlSignal(
                    default_allocation=[6],  # as above same but with array
                    modulates=(pnl.SLOPE, m3))
            ])
        comp = pnl.Composition()
        comp.add_nodes([m1, m2, m3])
        comp.add_controller(c2)
        assert c2.control_signals[0].value == [
            4
        ]  # default_allocation from pnl.ControlMechanism assigned
        assert m1.parameter_ports[pnl.SLOPE].value == [
            10
        ]  # has not yet received pnl.ControlSignal value
        assert c2.control_signals[1].value == [
            5
        ]  # default_allocation from pnl.ControlSignal assigned (converted scalar)
        assert m2.parameter_ports[pnl.SLOPE].value == [10]
        assert c2.control_signals[2].value == [
            6
        ]  # default_allocation from pnl.ControlSignal assigned
        assert m3.parameter_ports[pnl.SLOPE].value == [10]
        result = comp.run(inputs={m1: [2], m2: [3], m3: [4]})
        assert np.allclose(result, [[8.], [15.], [24.]])
        assert c2.control_signals[0].value == [10]
        assert m1.parameter_ports[pnl.SLOPE].value == [4]
        assert c2.control_signals[1].value == [10]
        assert m2.parameter_ports[pnl.SLOPE].value == [5]
        assert c2.control_signals[2].value == [10]
        assert m3.parameter_ports[pnl.SLOPE].value == [6]
        result = comp.run(inputs={m1: [2], m2: [3], m3: [4]})
        assert np.allclose(result, [[20.], [30.], [40.]])
        assert c2.control_signals[0].value == [10]
        assert m1.parameter_ports[pnl.SLOPE].value == [10]
        assert c2.control_signals[1].value == [10]
        assert m2.parameter_ports[pnl.SLOPE].value == [10]
        assert c2.control_signals[2].value == [10]
        assert m3.parameter_ports[pnl.SLOPE].value == [10]
class TestProjectionSpecificationFormats:
    def test_projection_specification_formats(self):
        """Test various matrix and Projection specifications
        Also tests assignment of Projections to pathay of Composition using add_linear_processing_pathway:
        - Projection explicitly specified in sequence (M1_M2_proj)
        - Projection pre-constructed and assigned to Mechanisms, but not specified in pathway(M2_M3_proj)
        - Projection specified in pathway that is duplicate one preconstructed and assigned to Mechanisms (M3_M4_proj)
          (currently it should be ignored; in the future, if/when Projections between the same sender and receiver
           in different Compositions are allowed, then it should be used)
        """
        M1 = pnl.ProcessingMechanism(size=2)
        M2 = pnl.ProcessingMechanism(size=5)
        M3 = pnl.ProcessingMechanism(size=4)
        M4 = pnl.ProcessingMechanism(size=3)

        M1_M2_matrix = (np.arange(2 * 5).reshape((2, 5)) + 1) / (2 * 5)
        M2_M3_matrix = (np.arange(5 * 4).reshape((5, 4)) + 1) / (5 * 4)
        M3_M4_matrix_A = (np.arange(4 * 3).reshape((4, 3)) + 1) / (4 * 5)
        M3_M4_matrix_B = (np.arange(4 * 3).reshape((4, 3)) + 1) / (4 * 3)

        M1_M2_proj = pnl.MappingProjection(matrix=M1_M2_matrix)
        M2_M3_proj = pnl.MappingProjection(sender=M2,
                                           receiver=M3,
                                           matrix={
                                               pnl.VALUE: M2_M3_matrix,
                                               pnl.FUNCTION:
                                               pnl.AccumulatorIntegrator,
                                               pnl.FUNCTION_PARAMS: {
                                                   pnl.DEFAULT_VARIABLE:
                                                   M2_M3_matrix,
                                                   pnl.INITIALIZER:
                                                   M2_M3_matrix
                                               }
                                           })
        M3_M4_proj_A = pnl.MappingProjection(sender=M3,
                                             receiver=M4,
                                             matrix=M3_M4_matrix_A)
        c = pnl.Composition()
        c.add_linear_processing_pathway(
            pathway=[M1, M1_M2_proj, M2, M3, M3_M4_matrix_B, M4])

        assert np.allclose(M2_M3_proj.matrix.base, M2_M3_matrix)
        assert M2.efferents[0] is M2_M3_proj
        assert np.allclose(M3.efferents[0].matrix.base, M3_M4_matrix_A)
        # This is if different Projections are allowed between the same sender and receiver in different Compositions:
        # assert np.allclose(M3.efferents[1].matrix, M3_M4_matrix_B)
        c.run(inputs={M1: [2, -30]})
        # assert np.allclose(c.results, [[-130.19166667, -152.53333333, -174.875]])
        assert np.allclose(c.results, [[-78.115, -91.52, -104.925]])

    def test_multiple_modulatory_projection_specs(self):

        M = pnl.DDM(name='MY DDM')
        C = pnl.ControlMechanism(control_signals=[{
            pnl.PROJECTIONS: [
                M.parameter_ports[psyneulink.core.components.functions.
                                  distributionfunctions.DRIFT_RATE],
                M.parameter_ports[psyneulink.core.globals.keywords.THRESHOLD]
            ]
        }])
        G = pnl.GatingMechanism(gating_signals=[{
            pnl.PROJECTIONS: [
                M.output_ports[pnl.DECISION_VARIABLE], M.output_ports[
                    pnl.RESPONSE_TIME]
            ]
        }])
        assert len(C.control_signals) == 1
        assert len(C.control_signals[0].efferents) == 2
        assert M.parameter_ports[
            psyneulink.core.components.functions.distributionfunctions.
            DRIFT_RATE].mod_afferents[0] == C.control_signals[0].efferents[0]
        assert M.parameter_ports[
            psyneulink.core.globals.keywords.
            THRESHOLD].mod_afferents[0] == C.control_signals[0].efferents[1]
        assert len(G.gating_signals) == 1
        assert len(G.gating_signals[0].efferents) == 2
        assert M.output_ports[pnl.DECISION_VARIABLE].mod_afferents[
            0] == G.gating_signals[0].efferents[0]
        assert M.output_ports[pnl.RESPONSE_TIME].mod_afferents[
            0] == G.gating_signals[0].efferents[1]

    def test_multiple_modulatory_projections_with_port_Name(self):

        M = pnl.DDM(name='MY DDM')
        C = pnl.ControlMechanism(control_signals=[{
            'DECISION_CONTROL': [
                M.parameter_ports[psyneulink.core.components.functions.
                                  distributionfunctions.DRIFT_RATE],
                M.parameter_ports[psyneulink.core.globals.keywords.THRESHOLD]
            ]
        }])
        G = pnl.GatingMechanism(gating_signals=[{
            'DDM_OUTPUT_GATE': [
                M.output_ports[pnl.DECISION_VARIABLE], M.output_ports[
                    pnl.RESPONSE_TIME]
            ]
        }])
        assert len(C.control_signals) == 1
        assert C.control_signals[0].name == 'DECISION_CONTROL'
        assert len(C.control_signals[0].efferents) == 2
        assert M.parameter_ports[
            psyneulink.core.components.functions.distributionfunctions.
            DRIFT_RATE].mod_afferents[0] == C.control_signals[0].efferents[0]
        assert M.parameter_ports[
            psyneulink.core.globals.keywords.
            THRESHOLD].mod_afferents[0] == C.control_signals[0].efferents[1]
        assert len(G.gating_signals) == 1
        assert G.gating_signals[0].name == 'DDM_OUTPUT_GATE'
        assert len(G.gating_signals[0].efferents) == 2
        assert M.output_ports[pnl.DECISION_VARIABLE].mod_afferents[
            0] == G.gating_signals[0].efferents[0]
        assert M.output_ports[pnl.RESPONSE_TIME].mod_afferents[
            0] == G.gating_signals[0].efferents[1]

    def test_multiple_modulatory_projections_with_mech_and_port_Name_specs(
            self):

        M = pnl.DDM(name='MY DDM')
        C = pnl.ControlMechanism(control_signals=[{
            pnl.MECHANISM:
            M,
            pnl.PARAMETER_PORTS: [
                psyneulink.core.components.functions.distributionfunctions.
                DRIFT_RATE, psyneulink.core.globals.keywords.THRESHOLD
            ]
        }])
        G = pnl.GatingMechanism(gating_signals=[{
            pnl.MECHANISM:
            M,
            pnl.OUTPUT_PORTS: [pnl.DECISION_VARIABLE, pnl.RESPONSE_TIME]
        }])
        assert len(C.control_signals) == 1
        assert len(C.control_signals[0].efferents) == 2
        assert M.parameter_ports[
            psyneulink.core.components.functions.distributionfunctions.
            DRIFT_RATE].mod_afferents[0] == C.control_signals[0].efferents[0]
        assert M.parameter_ports[
            psyneulink.core.globals.keywords.
            THRESHOLD].mod_afferents[0] == C.control_signals[0].efferents[1]
        assert len(G.gating_signals) == 1
        assert len(G.gating_signals[0].efferents) == 2
        assert M.output_ports[pnl.DECISION_VARIABLE].mod_afferents[
            0] == G.gating_signals[0].efferents[0]
        assert M.output_ports[pnl.RESPONSE_TIME].mod_afferents[
            0] == G.gating_signals[0].efferents[1]

    def test_mapping_projection_with_mech_and_port_Name_specs(self):
        R1 = pnl.TransferMechanism(output_ports=['OUTPUT_1', 'OUTPUT_2'])
        R2 = pnl.TransferMechanism(default_variable=[[0], [0]],
                                   input_ports=['INPUT_1', 'INPUT_2'])
        T = pnl.TransferMechanism(input_ports=[{
            pnl.MECHANISM:
            R1,
            pnl.OUTPUT_PORTS: ['OUTPUT_1', 'OUTPUT_2']
        }],
                                  output_ports=[{
                                      pnl.MECHANISM:
                                      R2,
                                      pnl.INPUT_PORTS: ['INPUT_1', 'INPUT_2']
                                  }])
        assert len(R1.output_ports) == 2
        assert len(R2.input_ports) == 2
        assert len(T.input_ports) == 1
        for input_port in T.input_ports:
            for projection in input_port.path_afferents:
                assert projection.sender.owner is R1
        assert len(T.output_ports) == 1
        for output_port in T.output_ports:
            for projection in output_port.efferents:
                assert projection.receiver.owner is R2

    def test_mapping_projection_using_2_item_tuple_with_list_of_port_Names(
            self):

        T1 = pnl.TransferMechanism(name='T1', input_ports=[[0, 0], [0, 0, 0]])
        T2 = pnl.TransferMechanism(name='T2',
                                   output_ports=[
                                       (['InputPort-0', 'InputPort-1'], T1)
                                   ])
        assert len(T2.output_ports) == 1
        assert T2.output_ports[0].efferents[0].receiver.name == 'InputPort-0'
        assert T2.output_ports[0].efferents[0].matrix.base.shape == (1, 2)
        assert T2.output_ports[0].efferents[1].receiver.name == 'InputPort-1'
        assert T2.output_ports[0].efferents[1].matrix.base.shape == (1, 3)

    def test_mapping_projection_using_2_item_tuple_and_3_item_tuples_with_index_specs(
            self):

        T1 = pnl.TransferMechanism(name='T1', input_ports=[[0, 0], [0, 0, 0]])
        T2 = pnl.TransferMechanism(name='T2',
                                   input_ports=['a', 'b', 'c'],
                                   output_ports=[
                                       (['InputPort-0', 'InputPort-1'], T1),
                                       ('InputPort-0', (pnl.OWNER_VALUE, 2),
                                        T1),
                                       (['InputPort-0', 'InputPort-1'], 1, T1)
                                   ])
        assert len(T2.output_ports) == 3
        assert T2.output_ports[0].efferents[0].receiver.name == 'InputPort-0'
        assert T2.output_ports[0].efferents[0].matrix.base.shape == (1, 2)
        assert T2.output_ports[0].efferents[1].receiver.name == 'InputPort-1'
        assert T2.output_ports[0].efferents[1].matrix.base.shape == (1, 3)
        assert T2.output_ports[1].owner_value_index == 2
        assert T2.output_ports[2].owner_value_index == 1

    def test_2_item_tuple_from_control_signal_to_parameter_port(self):

        D = pnl.DDM(name='D')

        # Single name
        C = pnl.ControlMechanism(
            control_signals=[(psyneulink.core.components.functions.
                              distributionfunctions.DRIFT_RATE, D)])
        assert C.control_signals[0].name == 'D[drift_rate] ControlSignal'
        assert C.control_signals[0].efferents[0].receiver.name == 'drift_rate'

        # List of names
        C = pnl.ControlMechanism(control_signals=[([
            psyneulink.core.components.functions.distributionfunctions.
            DRIFT_RATE, psyneulink.core.globals.keywords.THRESHOLD
        ], D)])
        assert C.control_signals[
            0].name == 'D[drift_rate, threshold] ControlSignal'
        assert C.control_signals[0].efferents[0].receiver.name == 'drift_rate'
        assert C.control_signals[0].efferents[1].receiver.name == 'threshold'

    def test_2_item_tuple_from_parameter_port_to_control_signals(self):

        C = pnl.ControlMechanism(control_signals=['a', 'b'])
        D = pnl.DDM(name='D3',
                    function=psyneulink.core.components.functions.
                    distributionfunctions.DriftDiffusionAnalytical(
                        drift_rate=(3, C),
                        threshold=(2, C.control_signals['b'])))
        assert D.parameter_ports[
            psyneulink.core.components.functions.distributionfunctions.
            DRIFT_RATE].mod_afferents[0].sender == C.control_signals[0]
        assert D.parameter_ports[
            psyneulink.core.globals.keywords.
            THRESHOLD].mod_afferents[0].sender == C.control_signals[1]

    def test_2_item_tuple_from_gating_signal_to_output_ports(self):

        D4 = pnl.DDM(name='D4')

        # Single name
        G = pnl.GatingMechanism(gating_signals=[(pnl.DECISION_VARIABLE, D4)])
        assert G.gating_signals[0].name == 'D4[DECISION_VARIABLE] GatingSignal'
        assert G.gating_signals[0].efferents[
            0].receiver.name == 'DECISION_VARIABLE'

        # List of names
        G = pnl.GatingMechanism(
            gating_signals=[([pnl.DECISION_VARIABLE, pnl.RESPONSE_TIME], D4)])
        assert G.gating_signals[
            0].name == 'D4[DECISION_VARIABLE, RESPONSE_TIME] GatingSignal'
        assert G.gating_signals[0].efferents[
            0].receiver.name == 'DECISION_VARIABLE'
        assert G.gating_signals[0].efferents[
            1].receiver.name == 'RESPONSE_TIME'

    def test_2_item_tuple_from_input_and_output_ports_to_gating_signals(self):

        G = pnl.GatingMechanism(gating_signals=['a', 'b'])
        T = pnl.TransferMechanism(name='T',
                                  input_ports=[(3, G)],
                                  output_ports=[(2, G.gating_signals['b'])])
        assert T.input_ports[0].mod_afferents[0].sender == G.gating_signals[0]
        assert T.output_ports[0].mod_afferents[0].sender == G.gating_signals[1]

    control_spec_list = [
        pnl.CONTROL, pnl.CONTROL_SIGNAL, pnl.CONTROL_PROJECTION,
        pnl.ControlSignal,
        pnl.ControlSignal(), pnl.ControlProjection, "CP_OBJECT",
        pnl.ControlMechanism,
        pnl.ControlMechanism(), pnl.ControlMechanism, (0.3, pnl.CONTROL),
        (0.3, pnl.CONTROL_SIGNAL), (0.3, pnl.CONTROL_PROJECTION),
        (0.3, pnl.ControlSignal), (0.3, pnl.ControlSignal()),
        (0.3, pnl.ControlProjection), (0.3, "CP_OBJECT"),
        (0.3, pnl.ControlMechanism), (0.3, pnl.ControlMechanism()),
        (0.3, pnl.ControlMechanism)
    ]

    @pytest.mark.parametrize(
        'noise, gain',
        [(noise, gain) for noise, gain in
         [j for j in zip(control_spec_list, reversed(control_spec_list))]])
    def test_formats_for_control_specification_for_mechanism_and_function_params(
            self, noise, gain):
        # This shenanigans is to avoid assigning the same instantiated ControlProjection more than once
        if noise == 'CP_OBJECT':
            noise = pnl.ControlProjection()
        elif isinstance(noise, tuple) and noise[1] == 'CP_OBJECT':
            noise = (noise[0], pnl.ControlProjection())
        if gain == 'CP_OBJECT':
            gain = pnl.ControlProjection()
        elif isinstance(gain, tuple) and gain[1] == 'CP_OBJECT':
            gain = (gain[0], pnl.ControlProjection())

        R = pnl.RecurrentTransferMechanism(
            # NOTE: fixed name prevents failures due to registry naming
            # for parallel test runs
            name='R-CONTROL',
            noise=noise,
            function=psyneulink.core.components.functions.transferfunctions.
            Logistic(gain=gain))
        assert R.parameter_ports[pnl.NOISE].mod_afferents[0].name in \
                'ControlProjection for R-CONTROL[noise]'
        assert R.parameter_ports[pnl.GAIN].mod_afferents[0].name in \
                'ControlProjection for R-CONTROL[gain]'

    gating_spec_list = [
        pnl.GATING, pnl.CONTROL, pnl.GATING_SIGNAL, pnl.CONTROL_SIGNAL,
        pnl.GATING_PROJECTION, pnl.CONTROL_PROJECTION, pnl.GatingSignal,
        pnl.ControlSignal,
        pnl.GatingSignal(),
        pnl.ControlSignal(), pnl.GatingProjection, "GP_OBJECT",
        pnl.GatingMechanism, pnl.ControlMechanism,
        pnl.GatingMechanism(),
        pnl.ControlMechanism(), (0.3, pnl.GATING), (0.3, pnl.CONTROL),
        (0.3, pnl.GATING_SIGNAL), (0.3, pnl.CONTROL_SIGNAL),
        (0.3, pnl.GATING_PROJECTION), (0.3, pnl.CONTROL_PROJECTION),
        (0.3, pnl.GatingSignal), (0.3, pnl.ControlSignal),
        (0.3, pnl.GatingSignal()), (0.3, pnl.ControlSignal()),
        (0.3, pnl.GatingProjection), (0.3, pnl.ControlProjection),
        (0.3, "GP_OBJECT"), (0.3, pnl.GatingMechanism),
        (0.3, pnl.ControlMechanism), (0.3, pnl.GatingMechanism()),
        (0.3, pnl.ControlMechanism())
    ]

    @pytest.mark.parametrize(
        'input_port, output_port',
        [(inp, outp) for inp, outp in
         [j for j in zip(gating_spec_list, reversed(gating_spec_list))]])
    def test_formats_for_gating_specification_of_input_and_output_ports(
            self, input_port, output_port):
        G_IN, G_OUT = input_port, output_port

        # This shenanigans is to avoid assigning the same instantiated ControlProjection more than once
        if G_IN == 'GP_OBJECT':
            G_IN = pnl.GatingProjection()
        elif isinstance(G_IN, tuple) and G_IN[1] == 'GP_OBJECT':
            G_IN = (G_IN[0], pnl.GatingProjection())
        if G_OUT == 'GP_OBJECT':
            G_OUT = pnl.GatingProjection()
        elif isinstance(G_OUT, tuple) and G_OUT[1] == 'GP_OBJECT':
            G_OUT = (G_OUT[0], pnl.GatingProjection())

        if isinstance(G_IN, tuple):
            IN_NAME = G_IN[1]
        else:
            IN_NAME = G_IN
        IN_CONTROL = pnl.CONTROL in repr(IN_NAME).split(".")[-1].upper()
        if isinstance(G_OUT, tuple):
            OUT_NAME = G_OUT[1]
        else:
            OUT_NAME = G_OUT
        OUT_CONTROL = pnl.CONTROL in repr(OUT_NAME).split(".")[-1].upper()

        T = pnl.TransferMechanism(name='T-GATING',
                                  input_ports=[G_IN],
                                  output_ports=[G_OUT])

        if IN_CONTROL:
            assert T.input_ports[0].mod_afferents[0].name in \
                    'ControlProjection for T-GATING[InputPort-0]'
        else:
            assert T.input_ports[0].mod_afferents[0].name in \
                    'GatingProjection for T-GATING[InputPort-0]'

        if OUT_CONTROL:
            assert T.output_ports[0].mod_afferents[0].name in \
                    'ControlProjection for T-GATING[OutputPort-0]'
        else:
            assert T.output_ports[0].mod_afferents[0].name in \
                    'GatingProjection for T-GATING[OutputPort-0]'

        # with pytest.raises(pnl.ProjectionError) as error_text:
        #     T1 = pnl.ProcessingMechanism(name='T1', input_ports=[pnl.ControlMechanism()])
        # assert 'Primary OutputPort of ControlMechanism-0 (ControlSignal-0) ' \
        #        'cannot be used as a sender of a Projection to InputPort of T1' in error_text.value.args[0]
        #
        # with pytest.raises(pnl.ProjectionError) as error_text:
        #     T2 = pnl.ProcessingMechanism(name='T2', output_ports=[pnl.ControlMechanism()])
        # assert 'Primary OutputPort of ControlMechanism-1 (ControlSignal-0) ' \
        #        'cannot be used as a sender of a Projection to OutputPort of T2' in error_text.value.args[0]

    def test_no_warning_when_matrix_specified(self):

        with pytest.warns(None) as w:
            c = pnl.Composition()
            m0 = pnl.ProcessingMechanism(default_variable=[0, 0, 0, 0])
            p0 = pnl.MappingProjection(matrix=[[0, 0, 0, 0], [0, 0, 0, 0],
                                               [0, 0, 0, 0], [0, 0, 0, 0]])
            m1 = pnl.TransferMechanism(default_variable=[0, 0, 0, 0])
            c.add_linear_processing_pathway([m0, p0, m1])
            for warn in w:
                if r'elementwise comparison failed; returning scalar instead' in warn.message.args[
                        0]:
                    raise

    # KDM: this is a good candidate for pytest.parametrize
    def test_masked_mapping_projection(self):

        t1 = pnl.TransferMechanism(size=2)
        t2 = pnl.TransferMechanism(size=2)
        proj = pnl.MaskedMappingProjection(sender=t1,
                                           receiver=t2,
                                           matrix=[[1, 2], [3, 4]],
                                           mask=[[1, 0], [0, 1]],
                                           mask_operation=pnl.ADD)
        c = pnl.Composition(pathways=[[t1, proj, t2]])
        val = c.execute(inputs={t1: [1, 2]})
        assert np.allclose(val, [[8, 12]])

        t1 = pnl.TransferMechanism(size=2)
        t2 = pnl.TransferMechanism(size=2)
        proj = pnl.MaskedMappingProjection(sender=t1,
                                           receiver=t2,
                                           matrix=[[1, 2], [3, 4]],
                                           mask=[[1, 0], [0, 1]],
                                           mask_operation=pnl.MULTIPLY)
        c = pnl.Composition(pathways=[[t1, proj, t2]])
        val = c.execute(inputs={t1: [1, 2]})
        assert np.allclose(val, [[1, 8]])

        t1 = pnl.TransferMechanism(size=2)
        t2 = pnl.TransferMechanism(size=2)
        proj = pnl.MaskedMappingProjection(sender=t1,
                                           receiver=t2,
                                           mask=[[1, 2], [3, 4]],
                                           mask_operation=pnl.MULTIPLY)
        c = pnl.Composition(pathways=[[t1, proj, t2]])
        val = c.execute(inputs={t1: [1, 2]})
        assert np.allclose(val, [[1, 8]])

    def test_masked_mapping_projection_mask_conficts_with_matrix(self):

        with pytest.raises(pnl.MaskedMappingProjectionError) as error_text:

            t1 = pnl.TransferMechanism(size=2)
            t2 = pnl.TransferMechanism(size=2)
            pnl.MaskedMappingProjection(sender=t1,
                                        receiver=t2,
                                        mask=[[1, 2, 3], [4, 5, 6]],
                                        mask_operation=pnl.MULTIPLY)
        assert "Shape of the 'mask'" in str(error_text.value)
        assert "((2, 3)) must be the same as its 'matrix' ((2, 2))" in str(
            error_text.value)

    # FIX 7/22/15 [JDC] - REPLACE WITH MORE ELABORATE TESTS OF DUPLICATE PROJECTIONS:
    #                     SAME FROM OutputPort;  SAME TO InputPort
    #                     TEST ERROR MESSAGES GENERATED BY VARIOUS _check_for_duplicates METHODS
    # def test_duplicate_projection_detection_and_warning(self):
    #
    #     with pytest.warns(UserWarning) as record:
    #         T1 = pnl.TransferMechanism(name='T1')
    #         T2 = pnl.TransferMechanism(name='T2')
    #         T3 = pnl.TransferMechanism(name='T3')
    #         T4 = pnl.TransferMechanism(name='T4')
    #
    #         MP1 = pnl.MappingProjection(sender=T1,receiver=T2,name='MP1')
    #         MP2 = pnl.MappingProjection(sender=T1,receiver=T2,name='MP2')
    #         pnl.proc(T1,MP1,T2,T3)
    #         pnl.proc(T1,MP2,T2,T4)
    #
    #     # hack to find a specific warning (other warnings may be generated by the Process construction)
    #     correct_message_found = False
    #     for warning in record:
    #         if "that already has an identical Projection" in str(warning.message):
    #             correct_message_found = True
    #             break
    #
    #     assert len(T2.afferents)==1
    #     assert correct_message_found

    def test_duplicate_projection_creation_error(self):

        from psyneulink.core.components.projections.projection import DuplicateProjectionError
        with pytest.raises(DuplicateProjectionError) as record:
            T1 = pnl.TransferMechanism(name='T1')
            T2 = pnl.TransferMechanism(name='T2')
            pnl.MappingProjection(sender=T1, receiver=T2, name='MP1')
            pnl.MappingProjection(sender=T1, receiver=T2, name='MP2')
        assert 'Attempt to assign Projection to InputPort-0 of T2 that already has an identical Projection.' \
               in record.value.args[0]
task = pnl.LCAMechanism(name="TASK", size=2, initial_value=[0.5, 0.5])
task_color_wts = np.array([[4, 4], [0, 0]])
task_word_wts = np.array([[0, 0], [4, 4]])
task_color_pathway = [task_input, task, task_color_wts, color_hidden]
task_word_pathway = [task_input, task, task_word_wts, word_hidden]

# Construct the decision pathway:
decision = pnl.DDM(name="DECISION", input_format=pnl.ARRAY)
decision_pathway = [output, decision]

# Construct control mechanism
control = pnl.ControlMechanism(
    name="CONTROL",
    objective_mechanism=pnl.ObjectiveMechanism(
        name="Conflict Monitor",
        function=pnl.Energy(size=2, matrix=[[0, -2.5], [-2.5, 0]]),
        monitor=output,
    ),
    default_allocation=[0.5],
    control_signals=[(pnl.GAIN, task)],
)

# Construct the Composition:
Stroop_model = pnl.Composition(name="Stroop_model")
Stroop_model.add_linear_processing_pathway(color_pathway)
Stroop_model.add_linear_processing_pathway(word_pathway)
Stroop_model.add_linear_processing_pathway(task_color_pathway)
Stroop_model.add_linear_processing_pathway(task_word_pathway)
Stroop_model.add_linear_processing_pathway(decision_pathway)
Stroop_model.add_controller(control)

# Assign conditions:
Exemple #24
0
                              size=2,
                              function=pnl.Logistic(gain=1),
                              leak=.5,
                              competition=2,
                              noise=0,
                              time_step_size=.1,
                              termination_measure=pnl.TimeScale.TRIAL,
                              termination_threshold=3,
                              name='Task Activations [Act 1, Act 2]')

# response = pnl.ProcessingMechanism()

# Create controller
csiController = pnl.ControlMechanism(monitor_for_control=cueInterval,
                                     control_signals=[
                                         (pnl.TERMINATION_THRESHOLD,
                                          activation)
                                     ],
                                     modulation=pnl.OVERRIDE)

comp = pnl.Composition(
    # controller_mode=pnl.BEFORE
)
comp.add_linear_processing_pathway(pathway=[taskLayer, activation])
comp.add_node(cueInterval)
comp.add_node(csiController)
# csiController.control_signals[0].set_log_conditions([pnl.VALUE])

# comp.show_graph()

cueInterval.set_log_conditions([pnl.VALUE])
activation.set_log_conditions([pnl.RESULT, 'mod_termination_threshold'])
Exemple #25
0
                               e_v_FitzHughNagumo=-1.0,
                               f_v_FitzHughNagumo=1.0,
                               time_constant_v_FitzHughNagumo=tau_v,
                               a_w_FitzHughNagumo=1.0,
                               b_w_FitzHughNagumo=-1.0,
                               c_w_FitzHughNagumo=0.0,
                               threshold_FitzHughNagumo=a,
                               time_constant_w_FitzHughNagumo=tau_u,
                               mode_FitzHughNagumo=C,
                               uncorrelated_activity_FitzHughNagumo=d,
                               base_level_gain=G,
                               scaling_factor_gain=k,
                               name='LC-NE')

updateC = pnl.ControlMechanism(objective_mechanism=pnl.ObjectiveMechanism(
    monitor_for_control=[action_selection.output_states[1], conflicts.output_state]),
    control_signals=[LC_NE.parameter_states[35]],
    name='C Update')

update_process = pnl.Process(pathway=[LC_NE],
                             name='UPDATE PROCESS')


actions = ['left', 'right']
reward_values = np.array([1, 0])
first_reward = 0

action_selection.output_state.value = [0, 1]


def reward():
    print(reward_values, action_selection.output_state.value)