Prepare simulation hotstart info
356954
def hotstart(self):
        
        if self.write_hotstart:
            hotstart_time_str = self.event_manager.simulation_end.strftime("%Y%m%d_%H%M")
            try:
                os.mkdir('hotstart')
            except OSError:
                pass

            ov_hotstart_path = os.path.join('..', 'hotstart',
                                            '{0}_ov_hotstart_{1}.ovh'.format(self.project_manager.name,
                                                                             hotstart_time_str))
            self._update_card("WRITE_OV_HOTSTART", ov_hotstart_path, True)
            chan_hotstart_path = os.path.join('..', 'hotstart',
                                              '{0}_chan_hotstart_{1}'.format(self.project_manager.name,
                                                                             hotstart_time_str))
            self._update_card("WRITE_CHAN_HOTSTART", chan_hotstart_path, True)
            sm_hotstart_path = os.path.join('..', 'hotstart',
                                           '{0}_sm_hotstart_{1}.smh'.format(self.project_manager.name,
                                                                            hotstart_time_str))
            self._update_card("WRITE_SM_HOTSTART", sm_hotstart_path, True)
        else:
            self._delete_card("WRITE_OV_HOTSTART")
            self._delete_card("WRITE_CHAN_HOTSTART")
            self._delete_card("WRITE_SM_HOTSTART")

        if self.read_hotstart:
            hotstart_time_str = self.event_manager.simulation_start.strftime("%Y%m%d_%H%M")
            # OVERLAND
            expected_ov_hotstart = os.path.join('hotstart',
                                                '{0}_ov_hotstart_{1}.ovh'.format(self.project_manager.name,
                                                                                  hotstart_time_str))
            if os.path.exists(expected_ov_hotstart):
                self._update_card("READ_OV_HOTSTART", os.path.join("..", expected_ov_hotstart), True)
            else:
                self._delete_card("READ_OV_HOTSTART")
                log.warning("READ_OV_HOTSTART not included as "
                         "{0} does not exist ...".format(expected_ov_hotstart))

            # CHANNEL
            expected_chan_hotstart = os.path.join('hotstart',
                                                  '{0}_chan_hotstart_{1}'.format(self.project_manager.name,
                                                                                 hotstart_time_str))
            if os.path.exists("{0}.qht".format(expected_chan_hotstart)) \
                    and os.path.exists("{0}.dht".format(expected_chan_hotstart)):
                self._update_card("READ_CHAN_HOTSTART", os.path.join("..", expected_chan_hotstart), True)
            else:
                self._delete_card("READ_CHAN_HOTSTART")
                log.warning("READ_CHAN_HOTSTART not included as "
                         "{0}.qht and/or {0}.dht does not exist ...".format(expected_chan_hotstart))

            # INFILTRATION
            expected_sm_hotstart = os.path.join('hotstart',
                                                '{0}_sm_hotstart_{1}.smh'.format(self.project_manager.name,
                                                                                 hotstart_time_str))
            if os.path.exists(expected_sm_hotstart):
                self._update_card("READ_SM_HOTSTART", os.path.join("..", expected_sm_hotstart), True)
            else:
                self._delete_card("READ_SM_HOTSTART")
                log.warning("READ_SM_HOTSTART not included as"
                         " {0} does not exist ...".format(expected_sm_hotstart))
171408
def prepare_for_conf(self):
        
        logger.debug("- preparing: %s", self)
        self.cfg = {
            'self_conf': self.give_satellite_cfg(),
            'schedulers': {},
            'arbiters': {}
        }
        logger.debug("- prepared: %s", self.cfg)
1239943
def run_simulations(self, parameter_list, data_folder):
        

        # Open up a session
        s = drmaa.Session()
        s.initialize()

        # Create a job template for each parameter combination
        jobs = {}
        for parameter in parameter_list:
            # Initialize result
            current_result = {
                'params': {},
                'meta': {}
            }
            current_result['params'].update(parameter)

            command = " ".join([self.script_executable] + ['--%s=%s' % (param,
                                                                        value)
                                                           for param, value in
                                                           parameter.items()])

            # Run from dedicated temporary folder
            current_result['meta']['id'] = str(uuid.uuid4())
            temp_dir = os.path.join(data_folder, current_result['meta']['id'])
            if not os.path.exists(temp_dir):
                os.makedirs(temp_dir)

            jt = s.createJobTemplate()
            jt.remoteCommand = os.path.dirname(
                os.path.abspath(__file__)) + '/run_program.sh'
            jt.args = [command]
            jt.jobEnvironment = self.environment
            jt.workingDirectory = temp_dir
            jt.nativeSpecification = SIMULATION_GRID_PARAMS
            output_filename = os.path.join(temp_dir, 'stdout')
            error_filename = os.path.join(temp_dir, 'stderr')
            jt.outputPath = ':' + output_filename
            jt.errorPath = ':' + error_filename

            jobid = s.runJob(jt)

            # Save the template in our dictionary
            jobs[jobid] = {
                'template': jt,
                'result': current_result,
                'output': output_filename,
                'error': error_filename,
                }

        # Check for job completion, yield results when they are ready
        try:

            while len(jobs):
                found_done = False
                for curjob in jobs.keys():
                    try:
                        status = s.jobStatus(curjob)
                    except drmaa.errors.DrmCommunicationException:
                        pass
                    if status is drmaa.JobState.DONE:

                        current_result = jobs[curjob]['result']

                        # TODO Actually compute time elapsed in the running
                        # state
                        current_result['meta']['elapsed_time'] = 0

                        try:
                            s.deleteJobTemplate(jobs[curjob]['template'])
                        except drmaa.errors.DrmCommunicationException:
                            pass

                        del jobs[curjob]

                        found_done = True

                        yield current_result

                        break
                if not found_done:  # Sleep if we can't find a completed task
                    time.sleep(6)

        finally:
            try:
                for v in jobs.values():
                    s.deleteJobTemplate(v['template'])
                s.control(drmaa.JOB_IDS_SESSION_ALL,
                          drmaa.JobControlAction.TERMINATE)
                s.synchronize([drmaa.JOB_IDS_SESSION_ALL], dispose=True)
                s.exit()
            except(drmaa.errors.NoActiveSessionException):
                pass
145605
def prepare_everything(self):
        """"""
        self.prepare_network()
        self.init_models()
        self.load_conditions()
        with hydpy.pub.options.warnmissingobsfile(False):
            self.prepare_nodeseries()
        self.prepare_modelseries()
        self.load_inputseries()
433122
def OnInit(self):
        """"""
        wx.Image.AddHandler(self.handler)
        frame = MainFrame( config_parser = load_config())
        frame.Show(True)
        self.SetTopWindow(frame)
        if sys.argv[1:]:
            wx.CallAfter( frame.load_memory, sys.argv[1] )
        else:
            log.warn( 'No memory file specified' )
        return True
548380
def run(self):
        """"""
        # Define the resource requirements of each component in the simulation.
        vertices_resources = {
            # Every component runs on exactly one core and consumes a certain
            # amount of SDRAM to hold configuration data.
            component: {Cores: 1, SDRAM: component._get_config_size()}
            for component in self._components
        }

        # Work out what SpiNNaker application needs to be loaded for each
        # component
        vertices_applications = {component: component._get_kernel()
                                 for component in self._components}

        # Convert the Wire objects into Rig Net objects and create a lookup
        # from Net to the (key, mask) to use.
        net_keys = {Net(wire.source, wire.sinks): (wire.routing_key,
                                                   0xFFFFFFFF)
                    for wire in self._wires}
        nets = list(net_keys)

        # Boot the SpiNNaker machine and interrogate it to determine what
        # resources (e.g. cores, SDRAM etc.) are available.
        mc = MachineController(self._hostname)
        mc.boot()
        system_info = mc.get_system_info()

        # Automatically chose which chips and cores to use for each component
        # and generate routing tables.
        placements, allocations, application_map, routing_tables = \
            place_and_route_wrapper(vertices_resources,
                                    vertices_applications,
                                    nets, net_keys,
                                    system_info)

        with mc.application():
            # Allocate memory for configuration data, tagged by core number.
            memory_allocations = sdram_alloc_for_vertices(mc, placements,
                                                          allocations)

            # Load the configuration data for all components
            for component, memory in memory_allocations.items():
                component._write_config(memory)

            # Load all routing tables
            mc.load_routing_tables(routing_tables)

            # Load all SpiNNaker application kernels
            mc.load_application(application_map)

            # Wait for all six cores to reach the 'sync0' barrier
            mc.wait_for_cores_to_reach_state("sync0", len(self._components))

            # Send the 'sync0' signal to start execution and wait for the
            # simulation to finish.
            mc.send_signal("sync0")
            time.sleep(self.length * 0.001)
            mc.wait_for_cores_to_reach_state("exit", len(self._components))

            # Retrieve result data
            for component, memory in memory_allocations.items():
                component._read_results(memory)
1275417
def _prepare_initial_state(self, function_start, state):
        

        if state is None:
            state = self.project.factory.blank_state(mode="static",
                                                     remove_options=self._state_options_to_remove
                                                     )

        # make room for arguments passed to the function
        sp = state.regs.sp
        sp_val = state.solver.eval_one(sp)
        state.memory.set_stack_address_mapping(sp_val,
                                               state.memory.stack_id(function_start) + '_pre',
                                               0
                                               )
        state.registers.store('sp', sp - 0x100)

        # Set the stack address mapping for the initial stack
        state.memory.set_stack_size(state.arch.stack_size)
        initial_sp = state.solver.eval(state.regs.sp) # FIXME: This is bad, as it may lose tracking of multiple sp values
        initial_sp -= state.arch.bytes
        state.memory.set_stack_address_mapping(initial_sp,
                                               state.memory.stack_id(function_start),
                                               function_start
                                               )

        return state
1145554
def prepare_simseries(self, ramflag: bool = True) -> None:
        """"""
        for node in printtools.progressbar(self):
            node.prepare_simseries(ramflag)
1179263
def main():
    
    width       =  20   # grid width 
    height      =  10   # grid height
    iterations  =  20   # how many simulations to run
    num_agents  =   6   # number of agents to enter the world
    
    w = build_world(height, width)
    print(w)
    a = create_random_agents(w, num_agents)
    sim = my_world.WorldSimulation(w, a, 1)
    sim.run(iterations, 'Y', log_folder + os.sep + 'agt_run')
    sim.world.grd.save('test_world_traversed.txt')
612281
def prepare(self):
    
    cmd = [
      'android', 'update', 'project',
      '-p', self.path,
      '-t', self.get_target()
    ]
    self.run_cmd(cmd, 'prepare')
820025
def prepare_data(args):
    
    rnn_type = args.config.get("arch", "rnn_type")
    num_rnn_layer = args.config.getint("arch", "num_rnn_layer")
    num_hidden_rnn_list = json.loads(args.config.get("arch", "num_hidden_rnn_list"))

    batch_size = args.config.getint("common", "batch_size")

    if rnn_type == 'lstm':
        init_c = [('l%d_init_c' % l, (batch_size, num_hidden_rnn_list[l]))
                  for l in range(num_rnn_layer)]
        init_h = [('l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
                  for l in range(num_rnn_layer)]
    elif rnn_type == 'bilstm':
        forward_init_c = [('forward_l%d_init_c' % l, (batch_size, num_hidden_rnn_list[l]))
                          for l in range(num_rnn_layer)]
        backward_init_c = [('backward_l%d_init_c' % l, (batch_size, num_hidden_rnn_list[l]))
                           for l in range(num_rnn_layer)]
        init_c = forward_init_c + backward_init_c
        forward_init_h = [('forward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
                          for l in range(num_rnn_layer)]
        backward_init_h = [('backward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
                           for l in range(num_rnn_layer)]
        init_h = forward_init_h + backward_init_h
    elif rnn_type == 'gru':
        init_h = [('l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
                  for l in range(num_rnn_layer)]
    elif rnn_type == 'bigru':
        forward_init_h = [('forward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
                          for l in range(num_rnn_layer)]
        backward_init_h = [('backward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l]))
                           for l in range(num_rnn_layer)]
        init_h = forward_init_h + backward_init_h
    else:
        raise Exception('network type should be one of the lstm,bilstm,gru,bigru')

    if rnn_type == 'lstm' or rnn_type == 'bilstm':
        init_states = init_c + init_h
    elif rnn_type == 'gru' or rnn_type == 'bigru':
        init_states = init_h
    return init_states
171490
def set_event(self,
                  simulation_start=None,
                  simulation_duration=None,
                  simulation_end=None,
                  rain_intensity=2,
                  rain_duration=timedelta(seconds=30*60),
                  event_type='EVENT',
                 ):
        
        # ADD TEMPORTAL EVENT INFORMAITON
        if event_type == 'LONG_TERM':
            self.event = LongTermMode(self.project_manager,
                                      self.db_session,
                                      self.project_directory,
                                      simulation_start=simulation_start,
                                      simulation_end=simulation_end,
                                      simulation_duration=simulation_duration,
                                     )
        else: # 'EVENT'
            self.event = EventMode(self.project_manager,
                                   self.db_session,
                                   self.project_directory,
                                   simulation_start=simulation_start,
                                   simulation_duration=simulation_duration,
                                   )
            self.event.add_uniform_precip_event(intensity=rain_intensity,
                                                duration=rain_duration)
463970
def __prepare(self):
        """"""
        self.log.debug("prepare")

        if self.__phase > 0:
            raise RuntimeError("Internal error: Can only prepare in phase 0")

        server_instance = self.server_instance
        db = Database()

        # get list of server devices if server was already registered
        server_registered = server_instance in db.get_server_list()

        if server_registered:
            dserver_name = "dserver/{0}".format(server_instance)
            if db.import_device(dserver_name).exported:
                import tango
                dserver = tango.DeviceProxy(dserver_name)
                try:
                    dserver.ping()
                    raise Exception("Server already running")
                except:
                    self.log.info("Last time server was not properly "
                                  "shutdown!")
            _, db_device_map = self.get_devices()
        else:
            db_device_map = {}

        db_devices_add = {}

        # all devices that are registered in database that are not registered
        # as tango objects or for which the tango class changed will be removed
        db_devices_remove = set(db_device_map) - set(self.__objects)

        for local_name, local_object in self.__objects.items():
            local_class_name = local_object.tango_class_name
            db_class_name = db_device_map.get(local_name)
            if db_class_name:
                if local_class_name != db_class_name:
                    db_devices_remove.add(local_name)
                    db_devices_add[local_name] = local_object
            else:
                db_devices_add[local_name] = local_object

        for device in db_devices_remove:
            db.delete_device(device)
            try:
                db.delete_device_alias(db.get_alias(device))
            except:
                pass

        # register devices in database

        # add DServer
        db_dev_info = DbDevInfo()
        db_dev_info.server = server_instance
        db_dev_info._class = "DServer"
        db_dev_info.name = "dserver/" + server_instance

        db_dev_infos = [db_dev_info]
        aliases = []
        for obj_name, obj in db_devices_add.items():
            db_dev_info = DbDevInfo()
            db_dev_info.server = server_instance
            db_dev_info._class = obj.tango_class_name
            db_dev_info.name = obj.full_name
            db_dev_infos.append(db_dev_info)
            if obj.alias:
                aliases.append((obj.full_name, obj.alias))

        db.add_server(server_instance, db_dev_infos)

        # add aliases
        for alias_info in aliases:
            db.put_device_alias(*alias_info)
93206
def prepare(self):
        '''
        
        '''
        super(Minion, self).prepare()

        try:
            if self.config['verify_env']:
                confd = self.config.get('default_include')
                if confd:
                    # If 'default_include' is specified in config, then use it
                    if '*' in confd:
                        # Value is of the form "minion.d/*.conf"
                        confd = os.path.dirname(confd)
                    if not os.path.isabs(confd):
                        # If configured 'default_include' is not an absolute
                        # path, consider it relative to folder of 'conf_file'
                        # (/etc/salt by default)
                        confd = os.path.join(
                            os.path.dirname(self.config['conf_file']), confd
                        )
                else:
                    confd = os.path.join(
                        os.path.dirname(self.config['conf_file']), 'minion.d'
                    )

                v_dirs = [
                        self.config['pki_dir'],
                        self.config['cachedir'],
                        self.config['sock_dir'],
                        self.config['extension_modules'],
                        confd,
                    ]

                verify_env(
                    v_dirs,
                    self.config['user'],
                    permissive=self.config['permissive_pki_access'],
                    root_dir=self.config['root_dir'],
                    pki_dir=self.config['pki_dir'],
                )
        except OSError as error:
            self.environment_failure(error)

        self.setup_logfile_logger()
        verify_log(self.config)
        log.info('Setting up the Salt Minion "%s"', self.config['id'])
        migrations.migrate_paths(self.config)

        # Bail out if we find a process running and it matches out pidfile
        if self.check_running():
            self.action_log_info('An instance is already running. Exiting')
            self.shutdown(1)

        transport = self.config.get('transport').lower()

        # TODO: AIO core is separate from transport
        if transport in ('zeromq', 'tcp', 'detect'):
            # Late import so logging works correctly
            import salt.minion
            # If the minion key has not been accepted, then Salt enters a loop
            # waiting for it, if we daemonize later then the minion could halt
            # the boot process waiting for a key to be accepted on the master.
            # This is the latest safe place to daemonize
            self.daemonize_if_required()
            self.set_pidfile()
            if self.config.get('master_type') == 'func':
                salt.minion.eval_master_func(self.config)
            self.minion = salt.minion.MinionManager(self.config)
        else:
            log.error(
                'The transport \'%s\' is not supported. Please use one of '
                'the following: tcp, zeromq, or detect.', transport
            )
            self.shutdown(1)
35106
def prepareToSolve(self):
        '''
        
        '''
        self.setAndUpdateValues(self.solution_next,self.IncomeDstn,self.LivPrb,self.DiscFac)
        self.defBoroCnst(self.BoroCnstArt)
885896
def main():
    """"""
    parser = argparse.ArgumentParser(description='Stress test applications.')
    parser.add_argument('config_path', help='Path to configuration file.')
    args = parser.parse_args()
    try:
        configuration = load_configuration(args.config_path)
    except InvalidConfigurationError:
        print("\nConfiguration is not valid.")
        print('Example:\n{}'.format(help_configuration))
        return 1
    print("Starting up ...")
    futures = []
    with ProcessPoolExecutor(configuration[PROCESSORS]) as executor:
        for _ in range(configuration[PROCESSES]):
            futures.append(executor.submit(execute_test, configuration))
    print("... finished")
    test_stats = combine_test_stats([f.result() for f in futures])
    show_test_stats(test_stats)
    return 0
723391
def _update_simulation_start_cards(self):
        
        if self.simulation_start is not None:
            self._update_card("START_DATE", self.simulation_start.strftime("%Y %m %d"))
            self._update_card("START_TIME", self.simulation_start.strftime("%H %M"))