Exemplo n.º 1
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]
Exemplo n.º 2
0
    def test_composition_default_names_2(self):

        T = pnl.TransferMechanism(name='T0')
        C1 = pnl.Composition(name='MY COMPOSITION', pathways=[T])
        C2 = pnl.Composition(name='MY COMPOSITION', pathways=[T])
        assert C1.name == 'MY COMPOSITION'
        assert C2.name == 'MY COMPOSITION-1'
Exemplo n.º 3
0
    def test_composition_names(self):

        T = pnl.TransferMechanism()
        C1 = pnl.Composition(pathways=[T])
        C2 = pnl.Composition(pathway=[T])
        assert C1.name == 'Composition-0'
        assert C2.name == 'Composition-1'
    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]])
Exemplo n.º 5
0
    def test_composition_names(self):
        C1 = pnl.Composition()
        C2 = pnl.Composition()
        C3 = pnl.Composition()

        assert C1.name == 'Composition-0'
        assert C2.name == 'Composition-1'
        assert C3.name == 'Composition-2'
Exemplo n.º 6
0
    def test_add_pathway_methods_return_pathway(self):
        c = pnl.Composition()
        p = c.add_linear_processing_pathway(
            pathway=[pnl.ProcessingMechanism(),
                     pnl.ProcessingMechanism()])
        assert isinstance(p, pnl.Pathway)

        c = pnl.Composition()
        p = c.add_linear_learning_pathway(
            pathway=[pnl.ProcessingMechanism(),
                     pnl.ProcessingMechanism()],
            learning_function=pnl.BackPropagation)
        assert isinstance(p, pnl.Pathway)
Exemplo n.º 7
0
    def test_model_based_ocm_no_simulations(self):
        A = pnl.ProcessingMechanism(name='A')
        B = pnl.ProcessingMechanism(name='B',
                                    function=pnl.SimpleIntegrator(rate=1))

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

        control_signal = pnl.ControlSignal(
            projections=[(pnl.SLOPE, A)],
            function=pnl.Linear,
            variable=1.0,
            allocation_samples=[1, 2, 3],
            intensity_cost_function=pnl.Linear(slope=0.))

        objective_mech = pnl.ObjectiveMechanism(monitor=[B])
        ocm = pnl.OptimizationControlMechanism(
            agent_rep=comp,
            features=[A.input_state],
            objective_mechanism=objective_mech,
            function=pnl.GridSearch(),
            num_estimates=1,
            control_signals=[control_signal],
            search_statefulness=False,
        )

        comp.add_controller(ocm)

        inputs = {A: [[[1.0]]]}

        comp.run(inputs=inputs, num_trials=1)

        # initial 1 + each allocation sample (1, 2, 3) integrated
        assert B.parameters.value.get(comp) == 7
    def test_configure_learning(self):

        o = pnl.TransferMechanism()
        m = pnl.ContrastiveHebbianMechanism(input_size=2,
                                            hidden_size=0,
                                            target_size=2,
                                            mode=pnl.SIMPLE_HEBBIAN,
                                            separated=False,
                                            matrix=[[0, -.5], [-.5, 0]])

        regexp = r"Learning cannot be enabled for .* because it has no LearningMechanism"
        with pytest.warns(UserWarning, match=regexp):
            m.learning_enabled = True

        m.configure_learning()
        m.reset_stateful_function_when = pnl.Never()

        c = pnl.Composition()
        c.add_linear_processing_pathway([m, o])
        c.scheduler.add_condition(o, pnl.WhenFinished(m))
        c.learn(inputs={m: [2, 2]}, num_trials=4)
        results = c.parameters.results.get(c)
        np.testing.assert_allclose(
            results,
            [[[2.671875]], [[2.84093837]], [[3.0510183]], [[3.35234623]]])
Exemplo n.º 9
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
Exemplo n.º 10
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])
Exemplo n.º 11
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
Exemplo n.º 12
0
    def test_simple_hebbian(self):
        Hebb_C = pnl.Composition()
        size = 9

        Hebb2 = pnl.RecurrentTransferMechanism(
            size=size,
            function=pnl.Linear,
            enable_learning=True,
            hetero=0.,
            auto=0.,
            name='Hebb2',
        )

        Hebb_C.add_node(Hebb2)

        src = [1, 0, 0, 1, 0, 0, 1, 0, 0]

        inputs_dict = {Hebb2: np.array(src)}

        Hebb_C.run(num_trials=5, inputs=inputs_dict)
        activity = Hebb2.value

        assert np.allclose(
            activity,
            [[1.86643089, 0., 0., 1.86643089, 0., 0., 1.86643089, 0., 0.]])
Exemplo n.º 13
0
    def test_DDM(self):
        myMechanism = pnl.DDM(
            function=psyneulink.core.components.functions.nonstateful.
            distributionfunctions.DriftDiffusionAnalytical(
                drift_rate=(1.0),
                threshold=(10.0),
                starting_point=0.0,
            ),
            name='My_DDM',
        )

        myMechanism_2 = pnl.DDM(
            function=psyneulink.core.components.functions.nonstateful.
            distributionfunctions.DriftDiffusionAnalytical(drift_rate=2.0,
                                                           threshold=20.0),
            name='My_DDM_2')

        myMechanism_3 = pnl.DDM(
            function=psyneulink.core.components.functions.nonstateful.
            distributionfunctions.DriftDiffusionAnalytical(drift_rate=3.0,
                                                           threshold=30.0),
            name='My_DDM_3',
        )

        z = pnl.Composition()
        z.add_linear_processing_pathway([
            myMechanism,
            pnl.MappingProjection(matrix=pnl.IDENTITY_MATRIX), myMechanism_2,
            pnl.MappingProjection(matrix=pnl.FULL_CONNECTIVITY_MATRIX),
            myMechanism_3
        ])

        result = z.run(inputs={myMechanism: [[40]]})[0][0]

        expected_output = [
            (myMechanism.input_ports[0].parameters.value.get(z),
             np.array([40.])),
            (myMechanism.output_ports[0].parameters.value.get(z),
             np.array([10.])),
            (myMechanism_2.input_ports[0].parameters.value.get(z),
             np.array([10.])),
            (myMechanism_2.output_ports[0].parameters.value.get(z),
             np.array([20.])),
            (myMechanism_3.input_ports[0].parameters.value.get(z),
             np.array([20.])),
            (myMechanism_3.output_ports[0].parameters.value.get(z),
             np.array([30.])),
            (result, np.array([30.])),
        ]

        for i in range(len(expected_output)):
            val, expected = expected_output[i]
            # setting absolute tolerance to be in accordance with reference_output precision
            # if you do not specify, assert_allcose will use a relative tolerance of 1e-07,
            # which WILL FAIL unless you gather higher precision values to use as reference
            np.testing.assert_allclose(
                val,
                expected,
                atol=1e-08,
                err_msg='Failed on expected_output[{0}]'.format(i))
    def test_scheduled_contrastive_hebbian(self):
        o = pnl.TransferMechanism()
        m = pnl.ContrastiveHebbianMechanism(
            input_size=2,
            hidden_size=0,
            target_size=2,
            separated=False,
            mode=pnl.SIMPLE_HEBBIAN,
            integrator_mode=True,
            enable_learning=False,
            matrix=[[0, -1], [-1, 0]],
            # auto=0,
            # hetero=-1,
        )

        # set max passes to ensure failure if no convergence instead of infinite loop
        m.max_passes = 1000

        c = pnl.Composition()
        c.add_linear_processing_pathway([m, o])
        c.scheduler.add_condition(o, pnl.WhenFinished(m))
        c._analyze_graph()
        print('matrix:\n', m.afferents[1].matrix)
        c.run(inputs={m: [2, 2]}, num_trials=4)
        results = c.results
        print(results)
        np.testing.assert_allclose(results,
                                   [[np.array([2.])], [np.array([2.])],
                                    [np.array([2.])], [np.array([2.])]])
Exemplo n.º 15
0
 def test_output_port_variable_spec(self):
     # Test specification of OutputPort's variable
     udf = pnl.UserDefinedFunction(
         custom_function=lambda x: np.array([[1], [2], [3]]))
     mech = pnl.ProcessingMechanism(
         function=udf,
         name='MyMech',
         output_ports=[
             pnl.OutputPort(name='z', variable=(pnl.OWNER_VALUE, 2)),
             pnl.OutputPort(name='y', variable=(pnl.OWNER_VALUE, 1)),
             pnl.OutputPort(name='x', variable=(pnl.OWNER_VALUE, 0)),
             pnl.OutputPort(name='all', variable=(pnl.OWNER_VALUE)),
             pnl.OutputPort(name='execution count',
                            variable=(pnl.OWNER_EXECUTION_COUNT))
         ])
     expected = [[3.], [2.], [1.], [[1.], [2.], [3.]], [0]]
     for i, e in zip(mech.output_values, expected):
         assert np.array_equal(i, e)
     mech.execute([0])
     expected = [[3.], [2.], [1.], [[1.], [2.], [3.]], [1]]
     for i, e in zip(mech.output_values, expected):
         assert np.array_equal(i, e)
     # OutputPort mech.output_ports['all'] has a different dimensionality than the other OutputPorts;
     #    as a consequence, when added as a terminal node, the Composition can't construct an IDENTITY_MATRIX
     #    from the mech's OutputPorts to the Composition's output_CIM.
     # FIX: Remove the following line and correct assertions below once above condition is resolved
     mech.remove_ports(ports=mech.output_ports['all'])
     C = pnl.Composition(name='MyComp')
     C.add_node(node=mech)
     outs = C.run(inputs={mech: np.array([[0]])})
     assert np.array_equal(outs, np.array([[3], [2], [1], [2]]))
     outs = C.run(inputs={mech: np.array([[0]])})
     assert np.array_equal(outs, np.array([[3], [2], [1], [3]]))
Exemplo n.º 16
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]]])
Exemplo n.º 17
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
Exemplo n.º 18
0
    def test_configure_learning(self):

        o = pnl.TransferMechanism()
        m = pnl.ContrastiveHebbianMechanism(input_size=2,
                                            hidden_size=0,
                                            target_size=2,
                                            mode=pnl.SIMPLE_HEBBIAN,
                                            separated=False,
                                            matrix=[[0, -.5], [-.5, 0]])

        with pytest.warns(UserWarning) as record:
            m.learning_enabled = True

        correct_message_found = False
        for warning in record:
            if ("Learning cannot be enabled" in str(warning.message)
                    and "because it has no LearningMechanism" in str(
                        warning.message)):
                correct_message_found = True
                break
        assert correct_message_found

        m.configure_learning()
        m.reinitialize_when = pnl.Never()

        c = pnl.Composition()
        c.add_linear_processing_pathway([m, o])
        c.scheduler.add_condition(o, pnl.WhenFinished(m))
        c.run(inputs={m: [2, 2]}, num_trials=4)
        results = c.parameters.results.get(c)
        np.testing.assert_allclose(
            results,
            [[[2.671875]], [[2.84093837]], [[3.0510183]], [[3.35234623]]])
Exemplo n.º 19
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
Exemplo n.º 20
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]])
Exemplo n.º 21
0
    def test_model_based_ocm_with_buffer(self):

        A = pnl.ProcessingMechanism(name='A')
        B = pnl.ProcessingMechanism(name='B')

        comp = pnl.Composition(name='comp', controller_mode=pnl.BEFORE)
        comp.add_linear_processing_pathway([A, B])

        search_range = pnl.SampleSpec(start=0.25, stop=0.75, step=0.25)
        control_signal = pnl.ControlSignal(
            projections=[(pnl.SLOPE, A)],
            function=pnl.Linear,
            variable=1.0,
            allocation_samples=search_range,
            intensity_cost_function=pnl.Linear(slope=0.))

        objective_mech = pnl.ObjectiveMechanism(monitor=[B])
        ocm = pnl.OptimizationControlMechanism(
            agent_rep=comp,
            features=[A.input_state],
            feature_function=pnl.Buffer(history=2),
            objective_mechanism=objective_mech,
            function=pnl.GridSearch(),
            control_signals=[control_signal])
        objective_mech.log.set_log_conditions(pnl.OUTCOME)

        comp.add_controller(ocm)

        inputs = {A: [[[1.0]], [[2.0]], [[3.0]]]}

        for i in range(1, len(ocm.input_states)):
            ocm.input_states[i].function.reinitialize()
        comp.run(inputs=inputs, retain_old_simulation_data=True)

        log = objective_mech.log.nparray_dictionary()

        # "outer" composition
        assert np.allclose(log["comp"][pnl.OUTCOME], [[0.75], [1.5], [2.25]])

        # preprocess to ignore control allocations
        log_parsed = {}
        for key, value in log.items():
            cleaned_key = re.sub(r'comp-sim-(\d).*', r'\1', key)
            log_parsed[cleaned_key] = value

        # First round of simulations is only one trial.
        # (Even though the feature fn is a Buffer, there is no history yet)
        for i in range(0, 3):
            assert len(log_parsed[str(i)]["Trial"]) == 1

        # Second and third rounds of simulations are two trials.
        # (The buffer has history = 2)
        for i in range(3, 9):
            assert len(log_parsed[str(i)]["Trial"]) == 2
Exemplo n.º 22
0
def test_dot_notation():
    c = pnl.Composition()
    d = pnl.Composition()
    t = pnl.TransferMechanism()
    c.add_node(t)
    d.add_node(t)

    t.execute(1)
    assert t.value == 1
    c.run({t: 5})
    assert t.value == 5
    d.run({t: 10})
    assert t.value == 10
    c.run({t: 20}, context='custom execution id')
    assert t.value == 20

    # context None
    assert t.parameters.value.get() == 1
    assert t.parameters.value.get(c) == 5
    assert t.parameters.value.get(d) == 10
    assert t.parameters.value.get('custom execution id') == 20
Exemplo n.º 23
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]]
 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]])
Exemplo n.º 25
0
 def test_combine_param_redundant_fct_constructor_spec(self):
     t1 = pnl.TransferMechanism(size=2)
     t2 = pnl.TransferMechanism(size=2)
     t3 = pnl.TransferMechanism(
         size=2,
         input_ports=pnl.InputPort(
             function=psyneulink.core.components.functions.nonstateful.
             combinationfunctions.LinearCombination(operation=pnl.PRODUCT),
             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_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
Exemplo n.º 27
0
    def test_transfer_mech(self):

        T_1 = pnl.TransferMechanism(name='log_test_T_1', size=2)
        T_2 = pnl.TransferMechanism(name='log_test_T_2', size=2)
        con_with_rpc_pipeline = pnl.Context(rpc_pipeline=Queue())
        PS = pnl.Composition(name='log_test_PS', pathways=[T_1, T_2])

        T_1.set_log_conditions('mod_noise')
        T_1.set_log_conditions(pnl.RESULT)

        T_1.set_delivery_conditions('mod_noise')
        T_1.set_delivery_conditions(pnl.RESULT)

        PS.run(inputs={T_1: [0, 0]}, context=con_with_rpc_pipeline)
        PS.run(inputs={T_1: [1, 2]}, context=con_with_rpc_pipeline)
        PS.run(inputs={T_1: [3, 4]}, context=con_with_rpc_pipeline)

        # assert T_1.log.print_entries() ==
        # test_log.py::TestLog::test_log
        # Log for log_test_T_1:
        # Logged Item:   Time       Context                    Value
        # 'RESULT'       0:0:0:0   'PROCESSING, COMPOSI...   [0. 0.]
        # 'RESULT'       1:0:0:0   'PROCESSING, COMPOSI...   [1. 2.]
        # 'RESULT'       2:0:0:0   'PROCESSING, COMPOSI...   [3. 4.]
        # 'mod_noise'    0:0:0:0   'PROCESSING, COMPOSI...   [0.]
        # 'mod_noise'    1:0:0:0   'PROCESSING, COMPOSI...   [0.]
        # 'mod_noise'    2:0:0:0   'PROCESSING, COMPOSI...   [0.]

        expected = [
            [[0], [1], [2]],
            [[0.], [0.], [0.]],
            [[0.], [0.], [0.]],
            [[0.], [0.], [0.]],
            [[0.0], [0.0], [0.0]],
            [[0., 0.], [1., 2.], [3., 4.]],
        ]

        actual = []
        pipeline = con_with_rpc_pipeline.rpc_pipeline
        while not pipeline.empty():
            actual.append(pipeline.get())
        t_1_entries = [i for i in actual if i.componentName == 'log_test_T_1']
        noise = [i for i in t_1_entries if i.parameterName == 'noise']
        results = [i for i in t_1_entries if i.parameterName == 'RESULT']
        assert all([
            noise[0].time == '0:0:0:0', noise[0].value.data == [0],results[0].value.data == [0.0, 0.0],
            noise[1].time == '1:0:0:0', noise[1].value.data == [0],results[1].value.data == [1.0, 2.0],
            noise[2].time == '2:0:0:0', noise[2].value.data == [0],results[2].value.data == [3.0, 4.0],
        ])
    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]])
Exemplo n.º 29
0
 def test_delivery_initialization(self):
     con_with_rpc_pipeline = pnl.Context(rpc_pipeline=Queue())
     pipeline = con_with_rpc_pipeline.rpc_pipeline
     T = pnl.TransferMechanism(
             prefs={pnl.DELIVERY_PREF: pnl.PreferenceEntry(pnl.LogCondition.EXECUTION, pnl.PreferenceLevel.INSTANCE)}
     )
     comp = pnl.Composition(name='comp', nodes=[T])
     comp.run([1], context=con_with_rpc_pipeline)
     actual = []
     while not pipeline.empty():
         actual.append(pipeline.get())
     assert all([
         len(actual) == 1,
         actual[0].time == '0:0:0:0',
         actual[0].value.shape == [1, 1],
         actual[0].value.data == [1.0]
     ])
Exemplo n.º 30
0
    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.]]]