def stop(self,
             turn_off_machine=None,
             clear_routing_tables=None,
             clear_tags=None):
        """
        :param turn_off_machine: decides if the machine should be powered down\
            after running the execution. Note that this powers down all boards\
            connected to the BMP connections given to the transceiver
        :type turn_off_machine: bool
        :param clear_routing_tables: informs the tool chain if it\
            should turn off the clearing of the routing tables
        :type clear_routing_tables: bool
        :param clear_tags: informs the tool chain if it should clear the tags\
            off the machine at stop
        :type clear_tags: boolean
        :rtype: None
        """
        # pylint: disable=protected-access
        for population in self._populations:
            population._end()

        super(AbstractSpiNNakerCommon,
              self).stop(turn_off_machine, clear_routing_tables, clear_tags)
        self.reset_number_of_neurons_per_core()
        globals_variables.unset_simulator()
def EvaluateModel(t_stim, testing_examples):
    current = multiprocessing.current_process()
    print('Started {}'.format(current))
    f_name = "errorlog/" + current.name + "_stdout.txt"
    g_name = "errorlog/" + current.name + "_stderror.txt"
    f = open(f_name, 'w')
    g = open(g_name, 'w')
    old_stdout = sys.stdout
    old_stderr = sys.stderr
    sys.stdout = f
    sys.stderr = g

    from spinn_front_end_common.utilities import globals_variables
    globals_variables.unset_simulator()

    extra_args = ['lenet_dense_dt_01_not_normalised_serialised', '--t_stim', str(t_stim), '--testing_examples',\
                  str(testing_examples), '--result_filename', 'output_data_'+str(t_stim), '--result_dir', 'results',\
                  '--chunk_size', '200']
    import pynn_object_serialisation.experiments.mnist_testing.mnist_testing as mnist_testing
    from pynn_object_serialisation.experiments.mnist_testing.mnist_argparser import parser

    new_args = parser.parse_args(extra_args)
    mnist_testing.run(new_args)
    sys.stdout = old_stdout
    sys.stderr = old_stderr
    print("Run for {} completed".format(t_stim))

    return
Esempio n. 3
0
 def check_directory(self, path, skips=[], broken=[]):
     directory = os.path.join(self._introlab_dir, path)
     for a_script in os.listdir(directory):
         if a_script.endswith(".py"):
             if a_script in skips:
                 continue
             script = os.path.join(directory, a_script)
             try:
                 globals_variables.unset_simulator()
                 plotting = "import matplotlib.pyplot" in open(
                     script).read()
                 if plotting:
                     self.check_plotting_script(script)
                 else:
                     self.check_script(script)
             except Exception as ex:
                 if "virtual machine" in str(ex):
                     self.report(script, "scripts_fails_because_on_vm")
                 elif "'ConnectionHolder'" in str(ex):
                     self.report(script, "scripts_fails_because_on_vm")
                 elif a_script in broken:
                     self.report(script,
                                 "scripts_skipped_with_unkown_issues")
                 else:
                     print("Error on {}".format(script))
                     raise ex
Esempio n. 4
0
 def runsafe(self, method):
     retries = 0
     last_error = None
     while retries < 3:
         try:
             method()
             return
         except JobDestroyedError as ex:
             class_file = sys.modules[self.__module__].__file__
             with open(self.destory_path(), "a") as destroyed_file:
                 destroyed_file.write(class_file)
                 destroyed_file.write("\n")
                 destroyed_file.write(str(ex))
                 destroyed_file.write("\n")
             last_error = ex
             retries += 1
             globals_variables.unset_simulator()
         except SpinnmanException as ex:
             class_file = sys.modules[self.__module__].__file__
             with open(self.spinnman_exception_path(), "a") as exc_file:
                 exc_file.write(class_file)
                 exc_file.write("\n")
                 exc_file.write(str(ex))
                 exc_file.write("\n")
             last_error = ex
             retries += 1
             globals_variables.unset_simulator()
     raise last_error
def test_rte_at_start():
    globals_variables.unset_simulator()
    s.setup(model_binary_folder=os.path.dirname(__file__))
    s.add_machine_vertex_instance(
        RunVertex("test_rte_start.aplx",
                  ExecutableType.USES_SIMULATION_INTERFACE))
    with pytest.raises(SpinnmanException):
        s.run(1000)
Esempio n. 6
0
 def check_directory(self, path):
     directory = os.path.join(self._introlab_dir, path)
     for a_script in os.listdir(directory):
         if a_script.endswith(".py"):
             globals_variables.unset_simulator()
             script = os.path.join(directory, a_script)
             try:
                 self.check_script(script)
             except Exception as ex:
                 print("Error on {}".format(script))
                 raise ex
Esempio n. 7
0
def test_rte_during_run_forever():
    globals_variables.unset_simulator()
    s.setup(model_binary_folder=os.path.dirname(__file__))
    s.add_machine_vertex_instance(
        RunVertex("test_rte_during_run.aplx",
                  ExecutableType.USES_SIMULATION_INTERFACE))
    s.add_socket_address(None, "localhost", conn.local_port)
    s.run(None)
    conn.close()
    with pytest.raises(ExecutableFailedToStopException):
        s.stop()
Esempio n. 8
0
 def setUp(self):
     factor = random.random()
     if factor > p7_integration_factor:
         msg = "Test skipped by random number {} above " \
               "P7_INTEGRATION_FACTOR {}" \
               "".format(factor, p7_integration_factor)
         raise SkipTest(msg)
     globals_variables.unset_simulator()
     class_file = sys.modules[self.__module__].__file__
     path = os.path.dirname(os.path.abspath(class_file))
     os.chdir(path)
Esempio n. 9
0
    def setUp(self):
        # Remove random effect for testing
        # Set test_seed to None to allow random
        self._test_seed = 1

        factor = random.random()
        if factor > p8_integration_factor:
            raise SkipTest("Test skipped by random number {} above "
                           "P8_INTEGRATION_FACTOR {}".format(
                               factor, p8_integration_factor))

        globals_variables.unset_simulator()
        class_file = sys.modules[self.__module__].__file__
        path = os.path.dirname(os.path.abspath(class_file))
        os.chdir(path)
Esempio n. 10
0
    def check_extra_monitor(self):
        mbs = _TRANSFER_SIZE_MEGABYTES

        # setup system
        globals_variables.unset_simulator()
        sim.setup(model_binary_folder=os.path.dirname(__file__),
                  n_chips_required=2)

        # build verts
        writer_vertex = SDRAMWriter(mbs)

        # add verts to graph
        sim.add_machine_vertex_instance(writer_vertex)
        sim.run(12)

        writer_placement = sim.placements().get_placement_of_vertex(
            writer_vertex)

        # pylint: disable=protected-access
        outputs = sim.globals_variables.get_simulator()._last_run_outputs
        monitor_vertices = outputs[_MONITOR_VERTICES]

        receiver_plt = _get_monitor_placement(monitor_vertices,
                                              writer_placement)
        gatherers, gatherer = _get_gatherer_for_monitor(writer_vertex)

        start = float(time.time())

        data = _do_transfer(gatherer, gatherers, monitor_vertices,
                            receiver_plt, writer_placement, writer_vertex)

        end = float(time.time())

        print(
            "time taken to extract {} MB is {}. Transfer rate: {} Mb/s".format(
                mbs, end - start, (mbs * 8) / (end - start)))

        check_data(data)

        sim.stop()
    def stop(self, turn_off_machine=None, clear_routing_tables=None,
             clear_tags=None):
        """
        :param turn_off_machine: decides if the machine should be powered down\
            after running the execution. Note that this powers down all boards\
            connected to the BMP connections given to the transceiver
        :type turn_off_machine: bool
        :param clear_routing_tables: informs the tool chain if it\
            should turn off the clearing of the routing tables
        :type clear_routing_tables: bool
        :param clear_tags: informs the tool chain if it should clear the tags\
            off the machine at stop
        :type clear_tags: boolean
        :rtype: None
        """
        # pylint: disable=protected-access
        for population in self._populations:
            population._end()

        super(AbstractSpiNNakerCommon, self).stop(
            turn_off_machine, clear_routing_tables, clear_tags)
        self.reset_number_of_neurons_per_core()
        globals_variables.unset_simulator()
Esempio n. 12
0
 def runsafe(self, method, retry_delay=3.0):
     retries = 0
     while True:
         try:
             method()
             break
         except JobDestroyedError as ex:
             class_file = sys.modules[self.__module__].__file__
             with open(self.destory_path(), "a") as destroyed_file:
                 destroyed_file.write(class_file)
                 destroyed_file.write("\n")
                 destroyed_file.write(str(ex))
                 destroyed_file.write("\n")
             retries += 1
             globals_variables.unset_simulator()
             if retries >= 3:
                 raise ex
         except SpinnmanException as ex:
             class_file = sys.modules[self.__module__].__file__
             with open(self.spinnman_exception_path(), "a") as exc_file:
                 exc_file.write(class_file)
                 exc_file.write("\n")
                 exc_file.write(str(ex))
                 exc_file.write("\n")
             retries += 1
             globals_variables.unset_simulator()
             if retries >= 3:
                 raise ex
         print("")
         print("==========================================================")
         print(" Will run {} again in {} seconds".format(
             method, retry_delay))
         print("retry: {}".format(retries))
         print("==========================================================")
         print("")
         time.sleep(retry_delay)
Esempio n. 13
0
 def setUp(self):
     globals_variables.unset_simulator()
     class_file = sys.modules[self.__module__].__file__
     path = os.path.dirname(os.path.abspath(class_file))
     os.chdir(path)
Esempio n. 14
0
def run(args, start_index):
    # Record SCRIPT start time (wall clock)
    start_time = plt.datetime.datetime.now()

    # Note that this won't be global between processes
    global try_number
    try_number += 1
    globals_variables.unset_simulator()
    signal.signal(signal.SIGINT, signal_handler)
    current = multiprocessing.current_process()
    print('Started {}'.format(current) + '\n')

    f_name = "errorlog/" + current.name + "_stdout.txt"
    g_name = "errorlog/" + current.name + "_stderror.txt"
    f = open(f_name, 'w')
    g = open(g_name, 'w')
    old_stdout = sys.stdout
    old_stderr = sys.stderr
    # sys.stdout = f
    # sys.stderr = g

    N_layer = 28**2  # number of neurons in input population
    t_stim = args.t_stim
    (x_train, y_train), (x_test, y_test) = mnist.load_data()
    # reshape input to flatten data

    x_test = x_test.reshape(x_test.shape[0], np.prod(x_test.shape[1:]))

    testing_examples = args.chunk_size
    simtime = testing_examples * t_stim
    range_of_slots = np.arange(testing_examples)
    starts = np.ones((N_layer, testing_examples)) * (range_of_slots * t_stim)
    durations = np.ones((N_layer, testing_examples)) * t_stim
    rates = x_test[start_index:start_index + args.chunk_size, :].T
    y_test = y_test[start_index:start_index + args.chunk_size]

    # scaling rates
    _0_to_1_rates = rates / float(np.max(rates))
    rates = _0_to_1_rates * args.rate_scaling

    input_params = {"rates": rates, "durations": durations, "starts": starts}

    print("Number of testing examples to use:", testing_examples)
    print("Min rate", np.min(rates))
    print("Max rate", np.max(rates))
    print("Mean rate", np.mean(rates))

    replace = None

    timestep = args.timestep
    timescale = args.time_scale_factor

    output_v = []
    sim.setup(timestep, timestep, timestep, time_scale_factor=timescale)

    print("Setting number of neurons per core...")

    sim.set_number_of_neurons_per_core(SpikeSourcePoissonVariable, 16)
    sim.set_number_of_neurons_per_core(sim.SpikeSourcePoisson, 16)
    sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 64)
    sim.set_number_of_neurons_per_core(sim.IF_cond_exp, 64)

    print("Restoring populations and projections...")
    populations, projections, extra_params = restore_simulator_from_file(
        sim,
        args.model,
        input_type='vrpss',
        vrpss_cellparams=input_params,
        replace_params=replace)

    def add_correlation_population(sim, populations, projections):
        print("Adding a input/output correlation population...")
        #Define neuron model for population (long intergration time) propably the same as the others
        corr_neuron_model_params = populations[1].celltype.default_parameters
        input_size = populations[0].size
        # Make a population that correlates input and output
        corr_pop = sim.Population(input_size,
                                  cellclass=sim.IF_cond_exp(),
                                  label='corr_pop')
        # Add it to populations
        populations.append(corr_pop)

        #Weight for just one spike

        low_weight = 0.01
        weight = 0.1

        #Proj from input (remember delay)
        #Add to projections
        projections.append(
            sim.Projection(populations[0],
                           corr_pop,
                           sim.OneToOneConnector(),
                           sim.StaticSynapse(weight=low_weight,
                                             delay=len(populations) - 1),
                           receptor_type='excitatory'))
        #Proj from output classes
        #Add to projections
        from_list = [(7, x, weight, 0) for x in range(input_size)]
        projections.append(
            sim.Projection(populations[-2],
                           corr_pop,
                           sim.FromListConnector(from_list),
                           receptor_type='excitatory'))
        return populations, projections

    populations, projections = add_correlation_population(
        sim, populations, projections)

    old_runtime = extra_params['simtime'] if 'simtime' in extra_params else None
    print("Setting i_offsets...")
    set_i_offsets(populations, simtime, old_runtime=old_runtime)

    spikes_dict = {}
    neo_spikes_dict = {}
    current_error = None
    final_connectivity = {}

    def reset_membrane_voltage():
        #This doesn't work see SpyNNaker8 GitHub issue #331 use set_initial_value branches
        for population in populations[1:]:
            population.set_initial_value(variable="v", value=0)
        return

    for pop in populations[:]:
        pop.record("spikes")
    if args.record_v:
        populations[-1].record("v")

    sim_start_time = plt.datetime.datetime.now()
    if not args.reset_v:
        print('Presenting examples {}:{}'.format(
            start_index, start_index + testing_examples))
        sim.run(simtime)

    for i in range(args.chunk_size):
        print('Presenting example {}/{}'.format(start_index + i,
                                                testing_examples))
        sim.run(t_stim)
        reset_membrane_voltage()

    # Compute time taken to reach this point
    end_time = plt.datetime.datetime.now()
    total_time = end_time - start_time
    sim_total_time = end_time - sim_start_time

    for pop in populations[:]:
        spikes_dict[pop.label] = pop.spinnaker_get_data('spikes')
    if args.record_v:
        output_v = populations[-1].spinnaker_get_data('v')

    #The following can take a long time and so is added through a flag
    if args.retrieve_connectivity:
        try:
            for proj in projections:
                try:
                    final_connectivity[proj.label] = \
                        np.array(proj.get(('weight', 'delay'), format="list")._get_data_items())
                except AttributeError as ae:
                    print(
                        "Careful! Something happened when retrieving the "
                        "connectivity:", ae,
                        "\nRetrying using standard PyNN syntax...")
                    final_connectivity[proj.label] = \
                        np.array(proj.get(('weight', 'delay'), format="list"))
                except TypeError as te:
                    print("Connectivity is None (", te, ") for connection",
                          proj.label)
                    print("Connectivity as empty array.")
                    final_connectivity[proj.label] = np.array([])
        except:
            traceback.print_exc()
            print("Couldn't retrieve connectivity.")

    if args.result_filename:
        results_filename = args.result_filename
    else:
        results_filename = "mnist_results"
        if args.suffix:
            results_filename += args.suffix
        else:
            pass

    # Retrieve simulation parameters for provenance tracking and debugging purposes
    sim_params = {
        "argparser": vars(args),
        "git_hash": retrieve_git_commit(),
        "run_end_time": end_time.strftime("%H:%M:%S_%d/%m/%Y"),
        "wall_clock_script_run_time": str(total_time),
        "wall_clock_sim_run_time": str(sim_total_time),
    }
    results_file = os.path.join(
        os.path.join(args.result_dir,
                     results_filename + "_" + str(start_index)))

    np.savez_compressed(results_file,
                        output_v=output_v,
                        neo_spikes_dict=neo_spikes_dict,
                        all_spikes=spikes_dict,
                        all_neurons=extra_params['all_neurons'],
                        testing_examples=testing_examples,
                        N_layer=N_layer,
                        no_testing_examples=testing_examples,
                        num_classes=10,
                        y_test=y_test,
                        input_params=input_params,
                        input_size=N_layer,
                        simtime=simtime,
                        t_stim=t_stim,
                        sim_params=sim_params,
                        final_connectivity=final_connectivity,
                        init_connectivity=extra_params['all_connections'],
                        extra_params=extra_params,
                        current_error=current_error)
    sim.end()

    # Analysis time!
    post_run_analysis(filename=results_file,
                      fig_folder=args.result_dir + args.figures_dir)

    # Report time taken
    print("Results stored in  -- " + results_filename)

    # Report time taken
    print("Total time elapsed -- " + str(total_time))
    return current_error
Esempio n. 15
0
def breakout_test(connections, arms, split=4, runtime=2000, exposure_time=200, noise_rate=100, noise_weight=0.01,
                reward=0, spike_f=False, seed=0):
    np.random.seed(seed)
    sleep = 10 * np.random.random()
    time.sleep(sleep)
    max_attempts = 2
    try_except = 0
    while try_except < max_attempts:
        bandit = []
        bandit_count = -1
        excite = []
        excite_count = -1
        excite_marker = []
        inhib = []
        inhib_count = -1
        inhib_marker = []
        failures = []
        try:
            p.setup(timestep=1.0, min_delay=1, max_delay=127)
            p.set_number_of_neurons_per_core(p.IF_cond_exp, 100)
        except:
            print "set up failed, trying again"
            try:
                p.setup(timestep=1.0, min_delay=1, max_delay=127)
                p.set_number_of_neurons_per_core(p.IF_cond_exp, 100)
            except:
                print "set up failed, trying again for the last time"
                p.setup(timestep=1.0, min_delay=1, max_delay=127)
                p.set_number_of_neurons_per_core(p.IF_cond_exp, 100)
        # starting_pistol = p.Population(len(arms), p.SpikeSourceArray(spike_times=[0]))
        for i in range(len(connections)):
            [in2e, in2i, e_size, e2e, e2i, i_size, i2e, i2i, e2out, i2out] = connections[i]
            if (len(in2e) == 0 and len(in2i) == 0) or (len(e2out) == 0 and len(i2out) == 0):
                failures.append(i)
                print "agent {} was not properly connected to the game".format(i)
            else:
                bandit_count += 1
                bandit.append(
                    p.Population(len(arms), spinn_breakout.Breakout(x_factor=x_factor, y_factor=y_factor, label="breakout {}".format(i))))
                if e_size > 0:
                    excite_count += 1
                    excite.append(
                        p.Population(e_size, p.IF_cond_exp(), label='excite_pop_{}-{}'.format(excite_count, i)))
                    excite_noise = p.Population(e_size, p.SpikeSourcePoisson(rate=noise_rate))
                    p.Projection(excite_noise, excite[excite_count], p.OneToOneConnector(),
                                 p.StaticSynapse(weight=noise_weight), receptor_type='excitatory')
                    if spike_f:
                        excite[excite_count].record('spikes')
                    excite_marker.append(i)
                if i_size > 0:
                    inhib_count += 1
                    inhib.append(p.Population(i_size, p.IF_cond_exp(), label='inhib_pop_{}-{}'.format(inhib_count, i)))
                    inhib_noise = p.Population(i_size, p.SpikeSourcePoisson(rate=noise_rate))
                    p.Projection(inhib_noise, inhib[inhib_count], p.OneToOneConnector(),
                                 p.StaticSynapse(weight=noise_weight), receptor_type='excitatory')
                    if spike_f:
                        inhib[inhib_count].record('spikes')
                    inhib_marker.append(i)
                if len(in2e) != 0:
                    p.Projection(bandit[bandit_count], excite[excite_count], p.FromListConnector(in2e),
                                 receptor_type='excitatory')
                    # p.Projection(starting_pistol, excite[excite_count], p.FromListConnector(in2e),
                    #              receptor_type='excitatory')
                if len(in2i) != 0:
                    p.Projection(bandit[bandit_count], inhib[inhib_count], p.FromListConnector(in2i),
                                 receptor_type='excitatory')
                    # p.Projection(starting_pistol, inhib[inhib_count], p.FromListConnector(in2i),
                    #              receptor_type='excitatory')
                if len(e2e) != 0:
                    p.Projection(excite[excite_count], excite[excite_count], p.FromListConnector(e2e),
                                 receptor_type='excitatory')
                if len(e2i) != 0:
                    p.Projection(excite[excite_count], inhib[inhib_count], p.FromListConnector(e2i),
                                 receptor_type='excitatory')
                if len(i2e) != 0:
                    p.Projection(inhib[inhib_count], excite[excite_count], p.FromListConnector(i2e),
                                 receptor_type='inhibitory')
                if len(i2i) != 0:
                    p.Projection(inhib[inhib_count], inhib[inhib_count], p.FromListConnector(i2i),
                                 receptor_type='inhibitory')
                if len(e2out) != 0:
                    p.Projection(excite[excite_count], bandit[bandit_count], p.FromListConnector(e2out),
                                 receptor_type='excitatory')
                if len(i2out) != 0:
                    p.Projection(inhib[inhib_count], bandit[bandit_count], p.FromListConnector(i2out),
                                 receptor_type='inhibitory')

        simulator = get_simulator()
        try:
            p.run(runtime)
            try_except = max_attempts
            break
        except:
            traceback.print_exc()
            try:
                globals_variables.unset_simulator()
                print "end was necessary"
            except:
                traceback.print_exc()
                print "end wasn't necessary"
            try_except += 1
            print "failed to run on attempt ", try_except, "\n"  # . total fails: ", all_fails, "\n"
            if try_except >= max_attempts:
                print "calling it a failed population, splitting and rerunning"
                return 'fail'

    scores = []
    agent_fitness = []
    fails = 0
    excite_spike_count = [0 for i in range(len(connections))]
    excite_fail = 0
    inhib_spike_count = [0 for i in range(len(connections))]
    inhib_fail = 0
    print "reading the spikes of ", config
    for i in range(len(connections)):
        print "started processing fitness of: ", i
        if i in failures:
            print "worst score for the failure"
            fails += 1
            scores.append([[max_fail_score], [max_fail_score], [max_fail_score], [max_fail_score]])
            # agent_fitness.append(scores[i])
            excite_spike_count[i] -= max_fail_score
            inhib_spike_count[i] -= max_fail_score
        else:
            if spike_f:
                if i in excite_marker:
                    print "counting excite spikes"
                    spikes = excite[i - excite_fail - fails].get_data('spikes').segments[0].spiketrains
                    for neuron in spikes:
                        for spike in neuron:
                            excite_spike_count[i] += 1
                else:
                    excite_fail += 1
                    print "had an excite failure"
                if i in inhib_marker:
                    print "counting inhib spikes"
                    spikes = inhib[i - inhib_fail - fails].get_data('spikes').segments[0].spiketrains
                    for neuron in spikes:
                        for spike in neuron:
                            inhib_spike_count[i] += 1
                else:
                    inhib_fail += 1
                    print "had an inhib failure"
            scores.append(get_scores(game_pop=bandit[i - fails], simulator=simulator))
            # pop[i].stats = {'fitness': scores[i][len(scores[i]) - 1][0]}  # , 'steps': 0}
        print "finished spikes"
        if spike_f:
            agent_fitness.append([scores[i][len(scores[i]) - 1][0], excite_spike_count[i] + inhib_spike_count[i]])
        else:
            agent_fitness.append(scores[i][len(scores[i]) - 1][0])
        # print i, "| e:", excite_spike_count[i], "-i:", inhib_spike_count[i], "|\t", scores[i]
    print "The scores for this run of {} agents are:".format(len(connections))
    for i in range(len(connections)):
        print "c:{}, s:{}, si:{}, si0:{}".format(len(connections), len(scores), len(scores[i]), len(scores[i][0]))
        e_string = "e: {}".format(excite_spike_count[i])
        i_string = "i: {}".format(inhib_spike_count[i])
        score_string = ""
        for j in range(len(scores[i])):
            score_string += "{:4},".format(scores[i][j][0])
        print "{:3} | {:8} {:8} - ".format(i, e_string, i_string), score_string
    p.end()

    return agent_fitness
 def setUp(self):
     globals_variables.unset_simulator()
Esempio n. 17
0
def run(args, start_index):
    # Record SCRIPT start time (wall clock)
    start_time = plt.datetime.datetime.now()

    # Note that this won't be global between processes
    global try_number
    try_number += 1
    globals_variables.unset_simulator()
    signal.signal(signal.SIGINT, signal_handler)
    current = multiprocessing.current_process()
    print('Started {}'.format(current) + '\n')

    f_name = "errorlog/" + current.name + "_stdout.txt"
    g_name = "errorlog/" + current.name + "_stderror.txt"
    f = open(f_name, 'w')
    g = open(g_name, 'w')
    old_stdout = sys.stdout
    old_stderr = sys.stderr
    sys.stdout = f
    sys.stderr = g

    # Checking directory structure exists
    if not os.path.isdir(args.result_dir) and not os.path.exists(
            args.result_dir):
        os.mkdir(args.result_dir)

    # Load data from file

    x_test = np.load(args.data_dir + "x_test.npz")['arr_0']
    y_test = np.load(args.data_dir + "y_test.npz")['arr_0']

    if args.shuffle_data:
        assert len(x_test) == len(y_test)
        p = np.random.permutation(len(y_test))
        x_test = x_test[p]
        y_test = y_test[p]

    if args.testing_examples == 1:
        index = np.argwhere(y_test == args.label_to_test)[0]
        x_test = x_test[index]
        y_test = y_test[index]

    max_rate = args.rate_scaling

    if args.prescaled_data:
        max_rate = 1

    input_params = convert_rate_array_to_VRPSS(x_test[start_index:start_index +
                                                      args.testing_examples],
                                               max_rate=max_rate,
                                               duration=args.t_stim)

    timestep = args.timestep
    timescale = args.time_scale_factor

    output_v = []
    sim.setup(timestep, timestep, timestep, time_scale_factor=timescale)

    print("Setting number of neurons per core...")

    sim.set_number_of_neurons_per_core(SpikeSourcePoissonVariable, 16)
    sim.set_number_of_neurons_per_core(sim.SpikeSourcePoisson, 16)
    sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 16)
    sim.set_number_of_neurons_per_core(sim.IF_cond_exp, 16)
    sim.set_number_of_neurons_per_core(sim.IF_curr_delta, 16)

    v_reset = 0

    replace = {
        'v_thresh': args.v_thresh,
        'tau_refrac': 0,
        'v_reset': v_reset,
        'v_rest': 0,
        'v': 0,
        'cm': 1,
        'tau_m': 1000,
        'tau_syn_E': 0.02,
        'tau_syn_I': 0.02,
        'delay': 0
    }

    populations, projections, extra_params = restore_simulator_from_file(
        sim,
        os.path.join(args.root_dir, args.model),
        input_type='vrpss',
        is_input_vrpss=True,
        vrpss_cellparams=input_params,
        replace_params=replace,
        delta_input=args.delta)

    dt = sim.get_time_step()
    simtime = args.testing_examples * args.t_stim
    N_layer = len(populations)
    min_delay = sim.get_min_delay()
    max_delay = sim.get_max_delay()
    sim.set_number_of_neurons_per_core(SpikeSourcePoissonVariable, 16)
    sim.set_number_of_neurons_per_core(sim.SpikeSourcePoisson, 16)
    sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 16)
    sim.set_number_of_neurons_per_core(sim.IF_cond_exp, 16)
    sim.set_number_of_neurons_per_core(sim.IF_curr_delta, 16)
    old_runtime = extra_params['simtime'] if 'simtime' in extra_params else None
    #set_i_offsets(populations, runtime, old_runtime=old_runtime)
    set_zero_i_offsets(populations)
    spikes_dict = {}
    output_v = []
    neo_spikes_dict = {}

    def record_output(populations, offset, output):
        spikes = populations[-1].spinnaker_get_data('spikes')
        spikes = spikes + [0, offset]
        name = populations[-1].label
        if np.shape(spikes)[0] > 0:
            if name in list(output.keys()):
                output[name] = np.concatenate((output, spikes))
            else:
                output[name] = spikes
        return output

    for pop in populations[:]:
        pop.record("spikes")
    if args.record_v:
        populations[-1].record("v")

    def reset_membrane_voltage(v_reset):
        for population in populations[1:]:
            population.set_initial_value(variable="v", value=v_reset)
        return

    sim_start_time = plt.datetime.datetime.now()
    for presentation in range(args.chunk_size):
        print("Presenting test example {}".format(presentation))
        sim.run(args.t_stim)
        reset_membrane_voltage(v_reset)

    # Compute time taken to reach this point
    end_time = plt.datetime.datetime.now()
    total_time = end_time - start_time
    sim_total_time = end_time - sim_start_time

    for pop in populations[:]:
        spikes_dict[pop.label] = pop.spinnaker_get_data('spikes')
    if args.record_v:
        output_v = populations[-1].spinnaker_get_data('v')

    sim_params = {"argparser": vars(args)}

    # save results
    result_filename = get_result_filename(args, start_index)
    np.savez_compressed(result_filename,
                        output_v=output_v,
                        neo_spikes_dict=neo_spikes_dict,
                        all_spikes=spikes_dict,
                        all_neurons=extra_params['all_neurons'],
                        testing_examples=args.testing_examples,
                        N_layer=N_layer,
                        no_testing_examples=args.testing_examples,
                        num_classes=10,
                        y_test=y_test,
                        start_index=start_index,
                        chunk_size=args.chunk_size,
                        input_params=input_params,
                        input_size=N_layer,
                        simtime=simtime,
                        t_stim=args.t_stim,
                        timestep=timestep,
                        time_scale_factor=timescale,
                        sim_params=sim_params,
                        init_connectivity=extra_params['all_connections'],
                        extra_params=extra_params)
    sim.end()