Пример #1
0
    def test_example_10(self):
        # There is only one origin mechanism in the system
        # COMPLETE SPECIFICATION

        import psyneulink as pnl

        a = pnl.TransferMechanism(name='a',
                                  default_variable=[[1.0, 2.0, 3.0]])
        b = pnl.TransferMechanism(name='b')

        p1 = pnl.Process(pathway=[a, b])

        s = pnl.System(processes=[p1])

        check_inputs = []

        def store_inputs():
            check_inputs.append(a.input_values)

        input_dictionary = {a: [[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]}

        s.run(inputs=input_dictionary,
              call_after_trial=store_inputs)

        assert np.allclose(check_inputs, [[[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]])
Пример #2
0
    def test_example_1(self):
        # "If num_trials is not in use, the number of inputs provided determines the number of trials in the run. For
        # example, if five inputs are provided for each origin mechanism, and num_trials is not specified, the system
        # will execute five times."

        import psyneulink as pnl

        a = pnl.TransferMechanism(name='a', default_variable=[[0.0, 0.0]])
        b = pnl.TransferMechanism(name='b', default_variable=[[0.0], [0.0]])
        c = pnl.TransferMechanism(name='c')

        p1 = pnl.Process(pathway=[a, c], name='p1')
        p2 = pnl.Process(pathway=[b, c], name='p2')

        s = pnl.System(processes=[p1, p2])

        input_dictionary = {
            a: [[[1.0, 1.0]], [[1.0, 1.0]]],
            b: [[[2.0], [3.0]], [[2.0], [3.0]]]
        }

        check_inputs_dictionary = {a: [], b: []}

        def store_inputs():
            check_inputs_dictionary[a].append(a.get_input_values(s))
            check_inputs_dictionary[b].append(b.get_input_values(s))

        s.run(inputs=input_dictionary, call_after_trial=store_inputs)

        for mech in input_dictionary:
            assert np.allclose(check_inputs_dictionary[mech],
                               input_dictionary[mech])
Пример #3
0
    def test_duplicate_assigned_mechanism_names_2(self):
        pnl.TransferMechanism(name='A')
        pnl.TransferMechanism(name='A')  # A-1
        pnl.TransferMechanism(name='A')  # A-2
        t = pnl.TransferMechanism(name='A-1')

        assert t.name == 'A-3'
Пример #4
0
def figure_5a():
    """
    This creates the plot for figure 5A in the Montague paper. Figure 5A is
    a 'plot of ∂(t) over time for three trials during training (1, 30, and 50).'
    """

    # Create Processing Components
    sample_mechanism = pnl.TransferMechanism(default_variable=np.zeros(60),
                                             name=pnl.SAMPLE)

    action_selection = pnl.TransferMechanism(default_variable=np.zeros(60),
                                             function=pnl.Linear(slope=1.0,
                                                                 intercept=0.01),
                                             name='Action Selection')

    sample_to_action_selection = pnl.MappingProjection(sender=sample_mechanism,
                                                       receiver=action_selection,
                                                       matrix=np.zeros((60, 60)))
    # Create Composition
    composition_name = 'TD_Learning_Figure_5A'
    comp = pnl.Composition(name=composition_name)

    # Add Processing Components to the Composition
    pathway = [sample_mechanism, sample_to_action_selection, action_selection]

    # Add Learning Components to the Composition
    learning_related_components = comp.add_td_learning_pathway(pathway, learning_rate=0.3).learning_components

    # Unpack Relevant Learning Components
    prediction_error_mechanism = learning_related_components[pnl.OBJECTIVE_MECHANISM]
    target_mechanism = learning_related_components[pnl.TARGET_MECHANISM]

    # Create Log
    prediction_error_mechanism.log.set_log_conditions(pnl.VALUE)

    # Create Stimulus Dictionary
    no_reward_trials = {14, 29, 44, 59, 74, 89}
    inputs = build_stimulus_dictionary(sample_mechanism, target_mechanism, no_reward_trials)

    # Run Composition
    comp.learn(inputs=inputs)

    if args.enable_plot:
        # Get Delta Values from Log
        delta_vals = prediction_error_mechanism.log.nparray_dictionary()[composition_name][pnl.VALUE]

        # Plot Delta Values form trials 1, 30, and 50
        with plt.style.context('seaborn'):
            plt.plot(delta_vals[0][0], "-o", label="Trial 1")
            plt.plot(delta_vals[29][0], "-s", label="Trial 30")
            plt.plot(delta_vals[49][0], "-o", label="Trial 50")
            plt.title("Montague et. al. (1996) -- Figure 5A")
            plt.xlabel("Timestep")
            plt.ylabel("∂")
            plt.legend()
            plt.xlim(xmin=35)
            plt.xticks()
            plt.show(block=not pnl._called_from_pytest)

    return comp
Пример #5
0
    def test_example_8(self):
        # Only one input is provided for the mechanism [repeat]
        # COMPLETE SPECIFICATION

        import psyneulink as pnl

        a = pnl.TransferMechanism(name='a', default_variable=[[0.0], [0.0]])
        b = pnl.TransferMechanism(name='b')

        p1 = pnl.Process(pathway=[a, b])

        s = pnl.System(processes=[p1])

        check_inputs = []

        def store_inputs():
            check_inputs.append(a.get_input_values(s))

        input_dictionary = {
            a: [[[1.0], [2.0]], [[1.0], [2.0]], [[1.0], [2.0]], [[1.0], [2.0]],
                [[1.0], [2.0]]]
        }

        s.run(inputs=input_dictionary, call_after_trial=store_inputs)

        assert np.allclose(check_inputs, input_dictionary[a])
Пример #6
0
    def test_log_csv_multiple_contexts(self):
        pipeline = Queue()
        con_X = pnl.Context(execution_id='comp X', rpc_pipeline=pipeline)
        con_Y = pnl.Context(execution_id='comp Y', rpc_pipeline=pipeline)

        A = pnl.TransferMechanism(name='A')
        B = pnl.TransferMechanism(name='B')
        C = pnl.TransferMechanism(name='C')

        C.set_delivery_conditions(pnl.VALUE)

        X = pnl.Composition(name='comp X')
        Y = pnl.Composition(name='comp Y')

        X.add_linear_processing_pathway([A, C])
        Y.add_linear_processing_pathway([B, C])

        # running with manual contexts for consistent output
        # because output is sorted by context
        X.run(inputs={A: 1}, context=con_X)
        Y.run(inputs={B: 2}, context=con_Y)

        actual = []
        while not pipeline.empty():
            actual.append(pipeline.get())

        assert actual[0].context == 'comp X'
        assert actual[0].time == '0:0:0:1'
        assert actual[0].value.data == [1]
        assert actual[1].context == 'comp Y'
        assert actual[1].time == '0:0:0:1'
        assert actual[1].value.data == [2]
Пример #7
0
    def test_run_resets(self):
        con_with_rpc_pipeline = pnl.Context(rpc_pipeline=Queue())
        pipeline = con_with_rpc_pipeline.rpc_pipeline
        T1 = pnl.TransferMechanism(name='log_test_T1',
                                   size=2)
        T2 = pnl.TransferMechanism(name='log_test_T2',
                                   size=2)
        COMP = pnl.Composition(name='COMP', pathways=[T1, T2])
        T1.set_delivery_conditions('mod_slope')
        T2.set_delivery_conditions('value')
        COMP.run(inputs={T1: [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]},
                 context=con_with_rpc_pipeline)
        pipeline = con_with_rpc_pipeline.rpc_pipeline
        actual = []
        while not pipeline.empty():
            actual.append(pipeline.get())
        assert all([i.context == 'COMP' for i in actual])
        assert np.allclose([
            np.ndarray(shape=np.array(actual[1].value.shape), buffer=np.array(actual[1].value.data)),
            np.ndarray(shape=np.array(actual[3].value.shape), buffer=np.array(actual[3].value.data)),
            np.ndarray(shape=np.array(actual[5].value.shape), buffer=np.array(actual[5].value.data)),
        ], [[[1.0, 2.0]], [[3.0, 4.0]], [[5.0, 6.0]]])

        COMP.run(inputs={T1: [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]},
                 context=con_with_rpc_pipeline)
        actual = []
        while not pipeline.empty():
            actual.append(pipeline.get())
        assert np.allclose([
            np.ndarray(shape=np.array(actual[1].value.shape), buffer=np.array(actual[1].value.data)),
            np.ndarray(shape=np.array(actual[3].value.shape), buffer=np.array(actual[3].value.data)),
            np.ndarray(shape=np.array(actual[5].value.shape), buffer=np.array(actual[5].value.data)),
        ], [[[1.0, 2.0]], [[3.0, 4.0]], [[5.0, 6.0]]])
Пример #8
0
    def test_example_2(self):
        # "If num_trials is in use, run will iterate over the inputs until num_trials is reached. For example, if five
        # inputs are provided for each ORIGIN mechanism, and num_trials = 7, the system will execute seven times. The
        # first two items in the list of inputs will be used on the 6th and 7th trials, respectively."

        import psyneulink as pnl

        a = pnl.TransferMechanism(name='a')
        b = pnl.TransferMechanism(name='b')

        p1 = pnl.Process(pathway=[a, b])

        s = pnl.System(processes=[p1])

        input_dictionary = {a: [[[1.0]], [[2.0]], [[3.0]], [[4.0]], [[5.0]]]}

        expected_inputs = [[[1.0]], [[2.0]], [[3.0]], [[4.0]], [[5.0]],
                           [[1.0]], [[2.0]]]

        check_inputs = []

        def store_inputs():
            check_inputs.append(a.get_input_values(s))

        s.run(inputs=input_dictionary,
              num_trials=7,
              call_after_trial=store_inputs)

        assert np.allclose(check_inputs, expected_inputs)
Пример #9
0
    def test_example_9(self):
        # Only one input is provided for the mechanism [REPEAT]
        # SHORTCUT: Remove outer list because we want to use the same input on every trial

        import psyneulink as pnl

        a = pnl.TransferMechanism(name='a', default_variable=[[0.0], [0.0]])
        b = pnl.TransferMechanism(name='b')

        p1 = pnl.Process(pathway=[a, b])

        s = pnl.System(processes=[p1])

        check_inputs = []

        def store_inputs():
            check_inputs.append(a.get_input_values(s))

        input_dictionary = {a: [[1.0], [2.0]]}

        s.run(inputs=input_dictionary,
              num_trials=5,
              call_after_trial=store_inputs)

        assert np.allclose(check_inputs,
                           [[[1.0], [2.0]], [[1.0], [2.0]], [[1.0], [2.0]],
                            [[1.0], [2.0]], [[1.0], [2.0]]])
Пример #10
0
    def test_example_11(self):
        # There is only one origin mechanism in the system
        # SHORT CUT - specify inputs as a list instead of a dictionary

        import psyneulink as pnl

        a = pnl.TransferMechanism(name='a',
                                  default_variable=[[1.0, 2.0, 3.0]])
        b = pnl.TransferMechanism(name='b')

        p1 = pnl.Process(pathway=[a, b])

        s = pnl.System(processes=[p1])

        check_inputs = []

        def store_inputs():
            check_inputs.append(a.input_values)

        input_list = [[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]

        s.run(inputs=input_list,
              call_after_trial=store_inputs)

        assert np.allclose(check_inputs, [[[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]])
Пример #11
0
    def test_lvoc_features_function(self):
        m1 = pnl.TransferMechanism(
            input_states=["InputState A", "InputState B"])
        m2 = pnl.TransferMechanism()
        c = pnl.Composition()
        c.add_node(m1, required_roles=pnl.NodeRole.INPUT)
        c.add_node(m2, required_roles=pnl.NodeRole.INPUT)
        c._analyze_graph()
        lvoc = pnl.OptimizationControlMechanism(
            agent_rep=pnl.RegressionCFA,
            features=[
                m1.input_states[0], m1.input_states[1], m2.input_state, m2
            ],
            feature_function=pnl.LinearCombination(offset=10.0),
            objective_mechanism=pnl.ObjectiveMechanism(monitor=[m1, m2]),
            function=pnl.GradientOptimization(max_iterations=1),
            control_signals=[(pnl.SLOPE, m1), (pnl.SLOPE, m2)])
        c.add_node(lvoc)
        input_dict = {m1: [[1], [1]], m2: [1]}

        c.run(inputs=input_dict)

        assert len(lvoc.input_states) == 5

        for i in range(1, 5):
            assert lvoc.input_states[i].function.offset == 10.0
def test_prediction_mechanism_assignment():
    '''Tests prediction mechanism assignment and more tests for ObjectiveMechanism and ControlSignal assignments'''

    T1 = pnl.TransferMechanism(name='T1')
    T2 = pnl.TransferMechanism(name='T2')
    T3 = pnl.TransferMechanism(name='T3')

    S = pnl.sys([T1, T2, T3],
                controller=pnl.EVCControlMechanism(name='EVC',
                                                   prediction_mechanisms=(pnl.PredictionMechanism,
                                                                          {pnl.FUNCTION: pnl.INPUT_SEQUENCE,
                                                                           pnl.RATE: 1,
                                                                           pnl.WINDOW_SIZE: 3,
                                                                           }),
                                                   monitor_for_control=[T1],
                                                   objective_mechanism=[T2]
                                                   ),
                control_signals=pnl.ControlSignal(allocation_samples=[1, 5, 10],
                                                  projections=(pnl.SLOPE, T1)),
                monitor_for_control=T3,
                enable_controller=True
                )
    assert len(S.controller.objective_mechanism.input_states)==3

    S.recordSimulationPref = True

    input_dict = {T1:[1,2,3,4]}
    results = S.run(inputs=input_dict)
    assert results == [[[1.]], [[2.]], [[15.]], [[20.]]]
    assert S.simulation_results ==  [[[1.]], [[5.]], [[10.]],
                                    [[1.]], [[2.]], [[5.]], [[10.]], [[10.]], [[20.]],
                                    [[1.]], [[2.]], [[3.]], [[5.]], [[10.]], [[15.]], [[10.]], [[20.]], [[30.]],
                                    [[2.]], [[3.]], [[4.]], [[10.]], [[15.]], [[20.]], [[20.]], [[30.]], [[40.]]]
Пример #13
0
    def test_gating_signal_and_gating_projection_names(self):
        T3 = pnl.TransferMechanism(name='T3')
        T4 = pnl.TransferMechanism(name='T4', input_states=['First State','Second State'])

        # GatingSignal with one GatingProjection
        G1 = pnl.GatingMechanism(gating_signals=[T3])
        assert G1.gating_signals[0].name == 'T3[InputState-0] GatingSignal'
        assert G1.gating_signals[0].efferents[0].name == 'GatingProjection for T3[InputState-0]'

        # GatingSignal with two GatingProjections to two States of same Mechanism
        G2 = pnl.GatingMechanism(gating_signals=[{pnl.PROJECTIONS:[T4.input_states[0], T4.input_states[1]]}])
        assert G2.gating_signals[0].name == 'T4[First State, Second State] GatingSignal'
        assert G2.gating_signals[0].efferents[0].name == 'GatingProjection for T4[First State]'
        assert G2.gating_signals[0].efferents[1].name == 'GatingProjection for T4[Second State]'

        # GatingSignal with two GatingProjections to two States of different Mechanisms
        G3 = pnl.GatingMechanism(gating_signals=[{pnl.PROJECTIONS:[T3, T4]}])
        assert G3.gating_signals[0].name == 'GatingSignal-0 divergent GatingSignal'
        assert G3.gating_signals[0].efferents[0].name == 'GatingProjection for T3[InputState-0]'
        assert G3.gating_signals[0].efferents[1].name == 'GatingProjection for T4[First State]'

        # GatingProjections to ProcessingMechanism from GatingSignals of existing GatingMechanism
        T5 = pnl.TransferMechanism(name='T5',
                                   input_states=[T3.output_states[pnl.RESULTS],
                                                 G3.gating_signals['GatingSignal-0 divergent GatingSignal']],
                                   output_states=[G3.gating_signals['GatingSignal-0 divergent GatingSignal']])
Пример #14
0
    def test_component_execution_counts_for_mechanisms_in_composition(self):

        T1 = pnl.TransferMechanism()
        T2 = pnl.TransferMechanism()
        c = pnl.Composition()
        c.add_node(T1)
        c.add_node(T2)
        c.add_projection(sender=T1, receiver=T2)

        input_dict = {T1: [[0]]}

        c.run(input_dict)
        assert T2.execution_count == 1
        assert T2.input_port.execution_count == 1
        assert T2.parameter_ports[pnl.SLOPE].execution_count == 0
        assert T2.output_port.execution_count == 0

        c.run(input_dict)
        assert T2.execution_count == 2
        assert T2.input_port.execution_count == 2
        assert T2.parameter_ports[pnl.SLOPE].execution_count == 0
        assert T2.output_port.execution_count == 0

        c.run(input_dict)
        assert T2.execution_count == 3
        assert T2.input_port.execution_count == 3
        assert T2.parameter_ports[pnl.SLOPE].execution_count == 0
        assert T2.output_port.execution_count == 0
Пример #15
0
    def test_input_port_and_assigned_projection_names(self):
        T1 = pnl.TransferMechanism(name='T1')
        T2 = pnl.TransferMechanism(name='T2', input_ports=[T1])
        I1 = pnl.InputPort(owner=T2)
        I2 = pnl.InputPort(projections=[T1])
        assert I2.name == 'Deferred Init InputPort'
        T2.add_ports([I2])
        assert I1.name == 'InputPort-1'
        assert I2.name == 'InputPort-2'
        assert T2.input_ports[0].path_afferents[0].name == \
               'MappingProjection from T1[RESULT] to T2[InputPort-0]'
        assert T2.input_ports[2].path_afferents[0].name == \
               'MappingProjection from T1[RESULT] to T2[InputPort-2]'

        # ------------------------------------------------------------------------------------------------
        # TEST 10
        # Test that OutputPorts are properly named

        T1 = pnl.TransferMechanism(output_ports=['MY OUTPUT_PORT', [0]])
        assert T1.output_ports[0].name == 'MY OUTPUT_PORT'
        assert T1.output_ports[1].name == 'OutputPort-0'
        O = pnl.OutputPort(owner=T1)
        assert T1.output_ports[2].name == 'OutputPort-1'
        O2 = pnl.OutputPort()
        T1.add_ports([O2])
        assert T1.output_ports[3].name == 'OutputPort-2'
Пример #16
0
    def test_single_projection_variable(self):
        a = pnl.TransferMechanism()
        b = pnl.TransferMechanism()

        pnl.MappingProjection(sender=a, receiver=b)

        assert b.input_port.defaults.variable.shape == np.array([0]).shape
        assert b.input_port.function.defaults.variable.shape == np.array([0]).shape
Пример #17
0
def test_value_shapes_with_matrix(projection_type, sender_variable,
                                  receiver_variable, projection_value,
                                  function_value):
    A = pnl.TransferMechanism(default_variable=sender_variable)
    B = pnl.TransferMechanism(default_variable=receiver_variable)
    P = projection_type(sender=A, receiver=B)

    assert P.defaults.value.shape == projection_value.shape
    assert P.function.defaults.value.shape == function_value.shape
Пример #18
0
def three_node_linear_composition():
    A = pnl.TransferMechanism(name='A')
    B = pnl.TransferMechanism(name='B')
    C = pnl.TransferMechanism(name='C')

    comp = pnl.Composition()
    comp.add_linear_processing_pathway([A, B, C])

    return comp.nodes, comp
Пример #19
0
 def test_combine_param_alone(self):
     t1 = pnl.TransferMechanism(size=2)
     t2 = pnl.TransferMechanism(size=2)
     t3 = pnl.TransferMechanism(
         size=2, input_ports=pnl.InputPort(combine=pnl.PRODUCT))
     c = pnl.Composition(pathways=[[t1, t3], [t2, t3]])
     input_dict = {t1: [1, 2], t2: [3, 4]}
     val = c.run(inputs=input_dict)
     assert np.allclose(val, [[3, 8]])
    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]
Пример #21
0
    def test_mapping_projection_using_2_item_tuple_with_list_of_state_names(self):

        T1 = pnl.TransferMechanism(name='T1', input_states=[[0,0],[0,0,0]])
        T2 = pnl.TransferMechanism(name='T2',
                                   output_states=[(['InputState-0','InputState-1'], T1)])
        assert len(T2.output_states)==1
        assert T2.output_states[0].efferents[0].receiver.name == 'InputState-0'
        assert T2.output_states[0].efferents[0].matrix.shape == (1,2)
        assert T2.output_states[0].efferents[1].receiver.name == 'InputState-1'
        assert T2.output_states[0].efferents[1].matrix.shape == (1,3)
Пример #22
0
    def test_log_dictionary_with_scheduler(self):
        T1 = pnl.TransferMechanism(name='log_test_T1',
                                   integrator_mode=True,
                                   integration_rate=0.5)
        T2 = pnl.TransferMechanism(name='log_test_T2',
                                   function=pnl.Linear(slope=6.0))
        PS = pnl.Process(name='log_test_PS', pathway=[T1, T2])
        SYS = pnl.System(name='log_test_SYS', processes=[PS])

        def pass_threshold(mech, thresh):
            results = mech.output_states[0].value
            for val in results:
                if abs(val) >= thresh:
                    return True
            return False

        terminate_trial = {
            pnl.TimeScale.TRIAL: pnl.While(pass_threshold, T2, 5.0)
        }

        T1.set_log_conditions(pnl.VALUE)
        T1.set_log_conditions(pnl.SLOPE)
        T1.set_log_conditions(pnl.RESULTS)
        T2.set_log_conditions(pnl.VALUE)
        T2.set_log_conditions(pnl.SLOPE)

        SYS.run(inputs={T1: [[1.0]]}, termination_processing=terminate_trial)

        log_dict_T1 = T1.log.nparray_dictionary(
            entries=['RESULTS', 'slope', 'value'])
        log_dict_T2 = T2.log.nparray_dictionary(entries=['value', 'slope'])

        # Check order of keys (must match order of specification)
        assert list(log_dict_T1.keys()) == [
            'Run', 'Trial', 'Pass', 'Time_step', 'RESULTS', 'slope', 'value'
        ]
        assert list(log_dict_T2.keys()) == [
            'Run', 'Trial', 'Pass', 'Time_step', 'value', 'slope'
        ]

        # Check values T1
        assert np.allclose(log_dict_T1["Run"], [[0], [0], [0]])
        assert np.allclose(log_dict_T1["Trial"], [[0], [0], [0]])
        assert np.allclose(log_dict_T1["Time_step"], [[0], [0], [0]])
        assert np.allclose(log_dict_T1["RESULTS"], [[0.5], [0.75], [0.875]])
        assert np.allclose(log_dict_T1["value"],
                           [[[0.5]], [[0.75]], [[0.875]]])
        assert np.allclose(log_dict_T1["slope"], [[1], [1], [1]])

        # Check values T2
        assert np.allclose(log_dict_T2["Run"], [[0], [0], [0]])
        assert np.allclose(log_dict_T2["Trial"], [[0], [0], [0]])
        assert np.allclose(log_dict_T2["Time_step"], [[1], [1], [1]])
        assert np.allclose(log_dict_T2["value"], [[[3]], [[4.5]], [[5.25]]])
        assert np.allclose(log_dict_T2["slope"], [[6], [6], [6]])
Пример #23
0
 def test_combine_param_alone(self):
     t1 = pnl.TransferMechanism(size=2)
     t2 = pnl.TransferMechanism(size=2)
     t3 = pnl.TransferMechanism(
         size=2, input_states=pnl.InputState(combine=pnl.PRODUCT))
     p1 = pnl.Process(pathway=[t1, t3])
     p2 = pnl.Process(pathway=[t2, t3])
     s = pnl.System(processes=[p1, p2])
     input_dict = {t1: [1, 2], t2: [3, 4]}
     val = s.run(inputs=input_dict)
     assert np.allclose(val, [[3, 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' for MaskedMappingProjection-3 ((2, 3)) must be the same as its 'matrix' ((2, 2))" \
               in str(error_text.value)
Пример #25
0
    def test_noise_variations(self, noise):
        t1 = pnl.TransferMechanism(name='t1', size=2, noise=noise())
        t2 = pnl.TransferMechanism(name='t2', size=2)
        t2.integrator_function.parameters.noise.set(noise())

        t1.integrator_function.noise.base.random_state = np.random.RandomState(
            [0])
        t2.integrator_function.noise.base.random_state = np.random.RandomState(
            [0])

        for _ in range(5):
            np.testing.assert_equal(t1.execute([1, 1]), t2.execute([1, 1]))
def test_control_mechanism_assignment_additional():
    '''Tests "free-standing" specifications of monitor_for_control and ControlSignal (i.e., outside of a list)'''
    T_1 = pnl.TransferMechanism(name='T_1')
    T_2 = pnl.TransferMechanism(name='T_2')
    S = pnl.sys([T_1,T_2],
                controller=pnl.EVCControlMechanism(control_signals=(pnl.SLOPE, T_1)),
                monitor_for_control=T_1,
                control_signals=(pnl.SLOPE, T_2),
                enable_controller=True)
    assert S.controller.objective_mechanism.input_state.path_afferents[0].sender.owner == T_1
    assert T_1.parameter_states[pnl.SLOPE].mod_afferents[0].sender.owner == S.controller
    assert T_2.parameter_states[pnl.SLOPE].mod_afferents[0].sender.owner == S.controller
Пример #27
0
    def test_composition_level_stateful_function_resets(self):
        A = pnl.TransferMechanism(name='A',
                                  integrator_mode=True,
                                  integration_rate=0.5)
        B = pnl.TransferMechanism(name='B',
                                  integrator_mode=True,
                                  integration_rate=0.5)
        C = pnl.TransferMechanism(name='C')

        comp = pnl.Composition(pathways=[[A, C], [B, C]])

        A.log.set_log_conditions('value')
        B.log.set_log_conditions('value')

        comp.run(inputs={
            A: [1.0],
            B: [1.0]
        },
                 reset_stateful_functions_when={
                     A: pnl.AtTrial(3),
                     B: pnl.AtTrial(4)
                 },
                 reset_stateful_functions_to={
                     A: 0.5,
                     B: 0.5
                 },
                 num_trials=5)
        # Mechanism A - resets to 0.5 at the beginning of Trial 3. Its value at the end of Trial 3 will
        # be exactly one step of integration forward from 0.5.
        # Trial 0: 0.5, Trial 1: 0.75, Trial 2: 0.875, Trial 3: 0.75, Trial 4:  0.875
        assert np.allclose(
            A.log.nparray_dictionary('value')[
                comp.default_execution_id]['value'],
            [[np.array([0.5])], [np.array([0.75])], [np.array([0.875])],
             [np.array([0.75])], [np.array([0.875])]])

        # Mechanism B - resets to 0.5 at the beginning of Trial 4. Its value at the end of Trial 4 will
        # be exactly one step of integration forward from 0.5.
        # Trial 0: 0.5, Trial 1: 0.75, Trial 2: 0.875, Trial 3: 0.9375. Trial 4: 0.75
        assert np.allclose(
            B.log.nparray_dictionary('value')[
                comp.default_execution_id]['value'],
            [[np.array([0.5])], [np.array([0.75])], [np.array([0.875])],
             [np.array([0.9375])], [np.array([0.75])]])

        comp.reset()
        comp.run(inputs={A: [1.0], B: [1.0]})

        # Mechanisms A and B should have been reset, so verify that their new values are equal to their values at the
        # end of trial 0

        assert A.parameters.value.get(comp) == B.parameters.value.get(
            comp) == [[0.5]]
Пример #28
0
def test_control_mechanism_assignment():
    """ControlMechanism assignment/replacement,  monitor_for_control, and control_signal specifications"""

    T1 = pnl.TransferMechanism(size=3, name='T-1')
    T2 = pnl.TransferMechanism(function=psyneulink.core.components.functions.
                               transferfunctions.Logistic,
                               output_ports=[{
                                   pnl.NAME: 'O-1'
                               }],
                               name='T-2')
    T3 = pnl.TransferMechanism(function=psyneulink.core.components.functions.
                               transferfunctions.Logistic,
                               name='T-3')
    T4 = pnl.TransferMechanism(function=psyneulink.core.components.functions.
                               transferfunctions.Logistic,
                               name='T-4')
    P = pnl.Process(pathway=[T1, T2, T3, T4])
    S = pnl.System(
        processes=P,
        # controller=pnl.EVCControlMechanism,
        controller=pnl.EVCControlMechanism(control_signals=[(pnl.GAIN, T2)],
                                           monitor_for_control=T4),
        enable_controller=True,
        # Test for use of 4-item tuple with matrix in monitor_for_control specification
        monitor_for_control=[(T1, None, None, np.ones((3, 1))),
                             ('O-1', 1, -1)],
        control_signals=[(pnl.GAIN, T3)])
    assert len(S.controller.objective_mechanism.monitor) == 3
    assert len(S.control_signals) == 2

    # Test for avoiding duplicate assignment of monitor and control_signals
    C1 = pnl.EVCControlMechanism(name='C-1',
                                 objective_mechanism=[(T1, None, None,
                                                       np.ones((3, 1)))],
                                 control_signals=[(pnl.GAIN, T3)])

    # Test direct assignment
    S.controller = C1
    assert len(C1.monitored_output_ports) == 2
    assert len(S.control_signals) == 3
    assert S.controller.name == 'C-1'

    # Test for adding a monitored_output_port and control_signal
    C2 = pnl.EVCControlMechanism(
        name='C-2',
        objective_mechanism=[T3.output_ports[pnl.RESULT]],
        control_signals=[(pnl.GAIN, T4)])
    # Test use of assign_as_controller method
    C2.assign_as_controller(S)
    assert len(C2.monitored_output_ports) == 3
    assert len(S.control_signals) == 4
    assert S.controller.name == 'C-2'
Пример #29
0
 def test_combine_param_redundant_fct_class_spec(self):
     t1 = pnl.TransferMechanism(size=2)
     t2 = pnl.TransferMechanism(size=2)
     t3 = pnl.TransferMechanism(size=2,
                                input_states=pnl.InputState(
                                    function=pnl.LinearCombination,
                                    combine=pnl.PRODUCT))
     p1 = pnl.Process(pathway=[t1, t3])
     p2 = pnl.Process(pathway=[t2, t3])
     s = pnl.System(processes=[p1, p2])
     input_dict = {t1: [1, 2], t2: [3, 4]}
     val = s.run(inputs=input_dict)
     assert np.allclose(val, [[3, 8]])
    def test_lc_control_modulated_mechanisms_all(self):

        T_1 = pnl.TransferMechanism(name='T_1')
        T_2 = pnl.TransferMechanism(name='T_2')

        LC = pnl.LCControlMechanism(monitor_for_control=[T_1, T_2],
                                    modulated_mechanisms=pnl.ALL
                                    )
        S = pnl.System(processes=[pnl.proc(T_1, T_2, LC)])
        assert len(LC.control_signals)==1
        assert len(LC.control_signals[0].efferents)==2
        assert T_1.parameter_states[pnl.SLOPE].mod_afferents[0] in LC.control_signals[0].efferents
        assert T_2.parameter_states[pnl.SLOPE].mod_afferents[0] in LC.control_signals[0].efferents