Ejemplo n.º 1
0
    def test_reset_brain(self, mock_get_brain_info):
        simulations[0].cle = mock.MagicMock()

        class Foo(object):
            pass
        result = Foo()
        result.error_message = ""
        simulations[0].cle.set_simulation_brain.return_value = result
        mock_get_brain_info.return_value = os.path.join(PATH,
                                                        'models/braitenberg.py'), None, {u'record': slice(0L, 2L, 1L), u'neurons': slice(0L, 2L, 1L)}

        SimulationResetStorage.resetBrain(simulations[0], 'expId', 'contextId')
        SimulationResetStorage._get_brain_info_from_storage.assert_called_with('expId', 'contextId')
Ejemplo n.º 2
0
 def test_reset_transfer_functions(self):
     simulations[0].cle = mock.MagicMock()
     tf_sources_list = ['# Imported Python Transfer Function\[email protected]("recorder", filename="all_spikes.csv", headers=["id", "time"])\[email protected]("record_neurons", nrp.brain.record, nrp.spike_recorder)\[email protected](Topic(\'/monitor/spike_recorder\', cle_ros_msgs.msg.SpikeEvent))\ndef csv_spike_monitor(t, recorder, record_neurons):\n    for i in range(0, len(record_neurons.times)):\n        recorder.record_entry(\n            record_neurons.times[i][0],\n            record_neurons.times[i][1]\n        )\n', '# Imported Python Transfer Function\n#\nimport hbp_nrp_cle.tf_framework as nrp\n# This specifies that the neurons 0 to 2 of the circuit population\n# should be monitored. You can see them in the spike train widget\[email protected](nrp.brain.record, nrp.spike_recorder)\ndef all_neurons_spike_monitor(t):\n    # Uncomment to log into the \'log-console\' visible in the simulation\n    # clientLogger.info("Time: ", t)\n    return True\n#\n',
                       '# Imported Python Transfer Function\n#\nimport hbp_nrp_cle.tf_framework as nrp\nfrom hbp_nrp_cle.robotsim.RobotInterface import Topic\nimport std_msgs.msg\[email protected]("output_neuron", nrp.brain.neurons[1], nrp.leaky_integrator_alpha)\[email protected](Topic(\'/robot/eye_version/pos\', std_msgs.msg.Float64))\n# Example TF: get output neuron voltage and output some value on robot actuator to change eyes position whever an output spike is detected. You could do something else with the voltage here and command the robot accordingly.\ndef turn_eyes(t, output_neuron):\n    data = 0.3\n    if output_neuron.voltage < 0.0001:\n        data = -0.3\n    return std_msgs.msg.Float64(data)\n#\n', '# Imported Python Transfer Function\n#\nfrom sensor_msgs.msg import JointState\[email protected]("joints", Topic("/robot/joints", JointState))\[email protected](Topic(\'/joint_states\', JointState))\ndef joint_states_passthrough(t, joints):\n    return joints.value\n#\n', '# Imported Python Transfer Function\n#\nimport hbp_nrp_cle.tf_framework as nrp\nfrom hbp_nrp_cle.robotsim.RobotInterface import Topic\nimport sensor_msgs.msg\[email protected]("camera", Topic(\'/icub_model/left_eye_camera/image_raw\', sensor_msgs.msg.Image))\[email protected]("input_neuron", nrp.brain.neurons[0], nrp.poisson)\[email protected]()\n# Example TF: get image and fire at constant rate. You could do something with the image here and fire accordingly.\ndef grab_image(t, camera, input_neuron):\n    image = camera.value\n    input_neuron.rate = 10\n#\n']
     tf_activation_list = [True, True]
     simulations[0].cle.get_simulation_transfer_functions.return_value = (tf_sources_list, tf_activation_list)
     simulations[0].cle.add_simulation_transfer_function.return_value = None
     bibi_file_abs = os.path.join(os.path.split(
         __file__)[0], "experiments", "experiment_data", "bibi_1.bibi")
     with open(bibi_file_abs) as b_file:
         bibi = bibi_api_gen.CreateFromDocument(b_file.read())
     SimulationResetStorage.resetTransferFunctions(simulations[0], bibi, PATH)
     simulations[0].cle.get_simulation_transfer_functions.assert_called()
     simulations[0].cle.delete_simulation_transfer_function.assert_called_with('grab_image')
Ejemplo n.º 3
0
    def test_get_brain_info_from_storage_user_model(self, mock_get_brain_info,
                                                    mock_get_all_neurons_as_dict, mock_tempfile):

        dummy_dir = "/my/temp/dir"
        mock_tempfile.mkdtemp.return_value = dummy_dir

        self.mock_storageClient_instance.clone_file.return_value = os.path.join(
            dummy_dir, "brain.py")

        bibi_original_path = os.path.join(os.path.split(
            __file__)[0], "experiments", "experiment_data", "bibi_4.bibi")
        bibi_temp_path = os.path.join(tempfile.mkdtemp(), "bibi_test.xml")
        shutil.copyfile(bibi_original_path, bibi_temp_path)

        exp_temp_path = os.path.join(os.path.split(
            __file__)[0], "experiments", "experiment_data", "test_5.exc")

        def fake_get(*args, **kwargs):
            if args[2] == 'experiment_configuration.exc':
                with open(exp_temp_path) as exp_xml:
                    return exp_xml.read()
            with open(bibi_temp_path) as bibi_xml:
                return bibi_xml.read()
        self.mock_storageClient_instance.get_file = fake_get

        dummy_populations = {'pop1': slice(0, 1, 1), 'pop2': slice(1, 2, 1)}
        mock_get_all_neurons_as_dict.return_value = dummy_populations
        with patch('hbp_nrp_backend.rest_server.__SimulationResetStorage.open', mock_open(read_data='Fake_data'), create=True) as m:
            data_from_storage, populations, _ = SimulationResetStorage._get_brain_info_from_storage(
                self.experiment_id, None)

        self.assertEqual(
            '[name: pop2\ntype: 1\nids: []\nstart: 1\nstop: 2\nstep: 1, name: pop1\ntype: 1\nids: []\nstart: 0\nstop: 1\nstep: 1]',
            str(populations).replace('\"', ''))
Ejemplo n.º 4
0
    def test_compute_payload_reset_brain(self, mock_get_brain_info, mock_create_from_document,
                                         mock_get_all_neurons_as_dict, mock_tempfile):

        bibi_original_path = os.path.join(os.path.split(
            __file__)[0], "experiments", "experiment_data", "bibi_1.bibi")
        bibi_temp_path = os.path.join(tempfile.mkdtemp(), "bibi_test.xml")
        shutil.copyfile(bibi_original_path, bibi_temp_path)

        exp_temp_path = os.path.join(os.path.split(
            __file__)[0], "experiments", "experiment_data", "test_1.exc")

        def fake_get(*args, **kwargs):
            if args[2] == 'experiment_configuration.exc':
                with open(exp_temp_path) as exp_xml:
                    return exp_xml.read()
            with open(bibi_temp_path) as bibi_xml:
                return bibi_xml.read()
        self.mock_storageClient_instance.get_file = fake_get

        dummy_dir = "/my/temp/dir"
        mock_tempfile.mkdtemp.return_value = dummy_dir
        self.mock_storageClient_instance.clone_file.return_value = os.path.join(
            dummy_dir, "brain.py")

        dummy_populations = {}
        mock_get_all_neurons_as_dict.return_value = dummy_populations

        payload = SimulationResetStorage._compute_payload(
            ResetSimulationRequest.RESET_BRAIN, self.experiment_id, None)
        self.assertEqual(mock_get_brain_info.call_count, 3)
        self.assertEqual(payload, (None,  '/my/temp/dir/brain.py', []))
Ejemplo n.º 5
0
    def test_get_sdf_world_from_storage_user_model(self, mock_get_header_token):

        bibi_original_path = os.path.join(os.path.split(
            __file__)[0], "experiments", "experiment_data", "bibi_4.bibi")
        bibi_temp_path = os.path.join(tempfile.mkdtemp(), "bibi_test.xml")
        shutil.copyfile(bibi_original_path, bibi_temp_path)

        exp_temp_path = os.path.join(os.path.split(
            __file__)[0], "experiments", "experiment_data", "test_5.exc")

        def fake_get(*args, **kwargs):
            if args[2] == 'experiment_configuration.exc':
                with open(exp_temp_path) as exp_xml:
                    return exp_xml.read()
            with open(bibi_temp_path) as bibi_xml:
                return bibi_xml.read()
        self.mock_storageClient_instance.get_file = fake_get

        fake_filepath = '/abc/cde'
        self.mock_storageClient_instance.clone_file = fake_filepath
        fake_world_sdf_string = '<sdf></sdf>'
        with patch('hbp_nrp_backend.rest_server.__SimulationResetStorage.open', mock_open(read_data=fake_world_sdf_string), create=True) as m:
            # call target function
            world_sdf_string = SimulationResetStorage._get_sdf_world_from_storage(
                self.experiment_id, None)

        # assertions
        mock_get_header_token.assert_called()
        self.assertEqual(self.mock_storageClient_instance.clone_file, fake_filepath)

        self.assertNotEqual(world_sdf_string, fake_world_sdf_string)
Ejemplo n.º 6
0
    def test_reset_brain_throw(self, mock_get_brain_info):
        simulations[0].cle = mock.MagicMock()
        simulations[0].cle.set_simulation_brain.return_value = mock.Mock(
            error_message="error", error_line=10, error_column=50)

        mock_get_brain_info.return_value = (os.path.join(
            PATH, 'models/braitenberg.py'), None, {
                u'record': slice(0L, 2L, 1L),
                u'neurons': slice(0L, 2L, 1L)
            })

        with self.assertRaises(ROSCLEClientException) as context:
            SimulationResetStorage.reset_brain(simulations[0], 'expId',
                                               'contextId')

        self.assertEqual('error, column: 50', context.exception.message)
Ejemplo n.º 7
0
    def test_reset_brain(self, mock_get_brain_info):
        simulations[0].cle = mock.MagicMock()

        simulations[0].cle.set_simulation_brain.return_value = mock.Mock(
            error_message="", error_line=10, error_column=50)
        simulations[0].cle.set_simulation_populations.return_value = mock.Mock(
            message='')
        mock_get_brain_info.return_value = os.path.join(
            PATH, 'models/braitenberg.py'), None, {
                u'record': slice(0L, 2L, 1L),
                u'neurons': slice(0L, 2L, 1L)
            }

        SimulationResetStorage.reset_brain(simulations[0], 'expId',
                                           'contextId')
        SimulationResetStorage._get_brain_info_from_storage.assert_called_with(
            'expId', 'contextId')
Ejemplo n.º 8
0
    def test_reset_brain_throw(self, mock_get_brain_info):
        simulations[0].cle = mock.MagicMock()

        class Foo(object):
            pass
        result = Foo()
        result.error_message = "error"
        result.error_line = 10
        result.error_column = 50
        result.handle_population_change = None
        simulations[0].cle.set_simulation_brain.return_value = result
        mock_get_brain_info.return_value = os.path.join(PATH,
                                                        'models/braitenberg.py'), None, {u'record': slice(0L, 2L, 1L), u'neurons': slice(0L, 2L, 1L)}
        with self.assertRaises(ROSCLEClientException) as context:
            SimulationResetStorage.resetBrain(simulations[0], 'expId', 'contextId')

        self.assertEqual(
            'error, line:10, column:50, population_change:None', context.exception.message)
Ejemplo n.º 9
0
    def test_compute_payload_reset_world(self, mock_get_sdf):

        fake_world_sdf_string = '<sdf></sdf>'
        mock_get_sdf.return_value = fake_world_sdf_string

        reset_world_type = ResetSimulationRequest.RESET_WORLD

        self.assertEqual(SimulationResetStorage._compute_payload(reset_world_type, self.experiment_id, None),
                         (fake_world_sdf_string, None, None))
Ejemplo n.º 10
0
    def test_reset_from_storage_all(self, mock_get_header_token,
                                    mock_reset_brain, mock_resetTFs,
                                    mock_resetSMs, mock_dirname):
        self.mock_storage_client.clone_all_experiment_files.return_value = \
            {'experiment_conf': 'fakeFolder/fakeExp'}

        mock_reset_brain.return_value = None
        mock_resetTFs.return_value = None
        mock_resetSMs.return_value = None
        mock_dirname.return_value = os.path.join(
            PATH, 'experiments/experiment_data')
        simulations[0].cle = mock.MagicMock()
        simulations[0].cle.set_simulation_transfer_function.return_value = None
        simulations[0].lifecycle.experiment_path = os.path.join(
            PATH, 'experiments/experiment_data/test_5.exc')

        SimulationResetStorage.reset_from_storage_all(simulations[0],
                                                      'ExperimentId',
                                                      'fakeContextID')
Ejemplo n.º 11
0
    def test_compute_payload_reset_all(self, mock_get_sdf, mock_get_brain_info):

        fake_world_sdf_string = '<sdf></sdf>'
        mock_get_sdf.return_value = fake_world_sdf_string
        mock_get_brain_info.return_value = os.path.join(PATH,
                                                        'models/braitenberg.py'), None, None
        reset_world_type = ResetSimulationRequest.RESET_FULL

        self.assertEqual(SimulationResetStorage._compute_payload(reset_world_type, self.experiment_id, None),
                         (fake_world_sdf_string, os.path.join(PATH,
                                                              'models/braitenberg.py'), None))
Ejemplo n.º 12
0
    def test_compute_payload_no_payload(self, mock_get_sdf):

        fake_world_sdf_string = '<sdf></sdf>'
        mock_get_sdf.return_value = fake_world_sdf_string

        reset_robot_pose_type = ResetSimulationRequest.RESET_ROBOT_POSE

        empty_payload = (None, None, None)

        self.assertEqual(SimulationResetStorage._compute_payload(reset_robot_pose_type, self.experiment_id, None),
                         empty_payload)
Ejemplo n.º 13
0
    def test_get_brain_info_from_storage(self, mock_get_brain_info,
                                         mock_get_all_neurons_as_dict):

        dummy_dir = "/my/temp/dir"

        self.mock_storage_client.clone_file.return_value = os.path.join(
            dummy_dir, "brain.py")

        bibi_original_path = os.path.join(
            os.path.split(__file__)[0], "experiments", "experiment_data",
            "bibi_1.bibi")
        bibi_temp_path = os.path.join(tempfile.mkdtemp(), "bibi_test.xml")
        shutil.copyfile(bibi_original_path, bibi_temp_path)

        exp_temp_path = os.path.join(
            os.path.split(__file__)[0], "experiments", "experiment_data",
            "test_1.exc")

        def fake_get(*args, **kwargs):
            if args[2] == 'experiment_configuration.exc':
                with open(exp_temp_path) as exp_xml:
                    return exp_xml.read()
            with open(bibi_temp_path) as bibi_xml:
                return bibi_xml.read()

        self.mock_storage_client.get_file = fake_get

        dummy_populations = {'pop1': slice(0, 1, 1), 'pop2': slice(1, 2, 1)}
        mock_get_all_neurons_as_dict.return_value = dummy_populations

        data_from_storage, populations, _ = SimulationResetStorage._get_brain_info_from_storage(
            self.experiment_id, None)

        self.assertEqual(data_from_storage,
                         os.path.join(dummy_dir, 'brain.py'))
        self.assertEqual(
            '[name: pop2\ntype: 1\nids: []\nstart: 1\nstop: 2\nstep: 1, name: pop1\ntype: 1\nids: []\nstart: 0\nstop: 1\nstep: 1]',
            str(populations).replace('\"', ''))
Ejemplo n.º 14
0
                    exd_file.read())
            except ValidationError, ve:
                raise Exception("Could not parse experiment configuration {0:s} due to validation "
                                "error: {1:s}".format(experiment_file_path, str(ve)))

            bibi_file = experiment.bibiConf.src
            bibi_file_abs = os.path.join(EXPERIMENT_DATA_PATH, bibi_file)
            with open(bibi_file_abs) as b_file:
                try:
                    bibi = bibi_api_gen.CreateFromDocument(b_file.read())
                except ValidationError, ve:
                    raise Exception("Could not parse brain configuration {0:s} due to validation "
                                    "error: {1:s}".format(bibi_file_abs, str(ve)))

        mock_get_experiment_data.return_value = experiment, bibi
        SimulationResetStorage.resetFromStorageAll(simulations[0], 'ExperimentId', 'fakeContextID')

    @patch("hbp_nrp_backend.rest_server.__SimulationResetStorage.SimulationResetStorage._get_brain_info_from_storage")
    @patch('hbp_nrp_backend.rest_server.__SimulationResetStorage.SimulationResetStorage._get_sdf_world_from_storage')
    def test_compute_payload_reset_all(self, mock_get_sdf, mock_get_brain_info):

        fake_world_sdf_string = '<sdf></sdf>'
        mock_get_sdf.return_value = fake_world_sdf_string
        mock_get_brain_info.return_value = os.path.join(PATH,
                                                        'models/braitenberg.py'), None, None
        reset_world_type = ResetSimulationRequest.RESET_FULL

        self.assertEqual(SimulationResetStorage._compute_payload(reset_world_type, self.experiment_id, None),
                         (fake_world_sdf_string, os.path.join(PATH,
                                                              'models/braitenberg.py'), None))