woodsja

Classes are for nerds

Nov 18th, 2018
463
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.34 KB | None | 0 0
  1. from pysc2.agents import base_agent
  2. from pysc2.env import sc2_env
  3. from pysc2.lib import actions, features, units
  4. from absl import app
  5. import time
  6. from datetime import datetime
  7.  
  8.  
  9. import numpy as np
  10.  
  11.  
  12.  
  13. SCREEN_SIZE = 84
  14. MINIMAP_SIZE = 64
  15.  
  16. # A3C example from: https://github.com/greentfrapp/pysc2-RLagents/blob/master/Agents/PySC2_A3C_AtariNet.py
  17.  
  18. """
  19. Use the following command to launch Tensorboard:
  20. tensorboard --logdir=worker_0:'./train_0',worker_1:'./train_1',worker_2:'./train_2',worker_3:'./train_3'
  21. """
  22.  
  23. # helper functions
  24.  
  25. # copies one set of variables to another
  26. # used to set worker network parameters to those of the global network
  27. def update_target_graph(from_scope, to_scope):
  28.   from_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, from_scope)
  29.   to_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, to_scope)
  30.   op_holder = []
  31.   for from_var, to_var, in zip(from_vars, to_vars):
  32.     op_holder.append(to_var.assign(from_var))
  33.   return op_holder
  34.  
  35. def process_observation(observation, action_spec):
  36.   # reward
  37.   reward = observation.reward
  38.   # features
  39.   features = observation.observation
  40.   # these have spatial data that we should process with a conv net
  41.   spatial_features = ['feature_minimap','feature_screen']
  42.   # they're variable features because they change size depending on what you select
  43.   variable_features = ['cargo','multi_select','build_queue']
  44.   available_actions = ['available_actions']
  45.  
  46.   # shapes of some features depend on the state
  47.   # tf requires fixed-input shapes, set max size then pad the input if it falls short
  48.   max_no = {'available_actions':len(action_spec.functions), 'cargo': 500, 'multi_select': 500, 'build_queue': 10}
  49.   non_spatial_stack = []
  50.   for feature_label in observation.observation:
  51.     if feature_label not in spatial_features + variable_features + available_actions:
  52.       non_spatial_stack = np.concatenate((non_spatial_stack, feature_label.reshape(-1)))
  53.  
  54.  
  55. class minigame_agent(base_agent.BaseAgent):
  56.   def __init__(self):
  57.     super(minigame_agent, self).__init__()
  58.  
  59.  
  60.   def step(self, obs):
  61.     super(minigame_agent, self).step(obs)
  62.  
  63.     # single_select will always be a tuple(7,) i.e. invarient dims
  64.     #raveled_single_select = np.ravel(obs.observation.single_select[0]).tolist()
  65.     #single_select = raveled_single_select
  66.  
  67.     # multi_select will be a tuple(n,7) *if* something's selected.
  68.     # If nothing is selected multi_select will return NoneType
  69.     # DefeatRoaches has at most 9 marines you can select...
  70.     # since there's gonna be a maximum of 200 units, why not map onto a bigger vector of zeros?
  71.     #raveled_multi_select = np.ravel(obs.observation.multi_select).tolist()
  72.     #multi_select = [0] * 7 * 9
  73.     #for i, item in enumerate(raveled_multi_select):
  74.     #  multi_select[i] = item
  75.  
  76.     # feature_screen should always be a tuple(17, SCREEN_SIZE, SCREEN_SIZE)
  77.     #feature_screen = obs.observation.feature_screen.tolist()
  78.  
  79.  
  80.     # feature_minimap should always be a tuple(7, SCREEN_SIZE, SCREEN_SIZE)
  81.     #feature_minimap = obs.observation.feature_minimap.tolist()
  82.  
  83.  
  84.     # player should always be a tuple(11,)
  85.     #raveled_player = np.ravel(obs.observation.player).tolist()
  86.     #player = raveled_player
  87.  
  88.     # feature_units will be a tuple(n,26) where n is the number of units present on the map
  89.     # since there's a maximum of 200 units why not map onto a bigger vector of zeros?
  90.     # in DefeatRoaches, there are a maximum of 9+5 units
  91.  
  92.     #raveled_feature_units = np.ravel(obs.observation.feature_units).tolist()
  93.     #feature_units = [0] * 26 * 14
  94.     #for i, item in enumerate(raveled_feature_units):
  95.     #  feature_units[i] = item
  96.  
  97.     # Since actions are sequenced, it would be nice to have them as a one-hot implementation; 523 total actions
  98.     #raveled_available_actions = np.ravel(obs.observation.available_actions).tolist()
  99.     #available_actions = [0] * 523
  100.     #for i, item in enumerate(raveled_available_actions):
  101.     #  available_actions[item] = 1
  102.  
  103.     # what happens if we just work off the nonspatial list first?
  104.     #nonspatial_list = single_select + multi_select + player + feature_units + available_actions
  105.  
  106.     #process_observation(self.obs_spec, self.action_spec)
  107.  
  108.     # put a break point here to see what's going on
  109.     return actions.FUNCTIONS.no_op()
  110.  
  111. def main(unused_argv):
  112.   agent = minigame_agent()
  113.   try:
  114.     while True:
  115.       try:
  116.         with sc2_env.SC2Env(
  117.           map_name="DefeatRoaches",
  118.           agent_interface_format=features.AgentInterfaceFormat(
  119.             feature_dimensions=features.Dimensions(screen=SCREEN_SIZE,
  120.                                                    minimap=MINIMAP_SIZE),
  121.             use_feature_units=True),
  122.           step_mul=1,
  123.           game_steps_per_episode=0,
  124.           visualize=True,
  125.           ) as env:
  126.  
  127.           agent.setup(env.observation_spec(), env.action_spec())
  128.           timesteps = env.reset()
  129.           agent.reset()
  130.  
  131.           while True:
  132.             step_actions = [agent.step(timesteps[0])]
  133.             timesteps = env.step(step_actions)
  134.  
  135.       except KeyboardInterrupt:
  136.         raise
  137.       except Exception as e:
  138.         with open('log.txt', 'a') as myfile:
  139.           myfile.write('At %s recorded exception: %s.\n' %
  140.                        (datetime.now(), repr(e)))
  141.  
  142.   except KeyboardInterrupt:
  143.     pass
  144.  
  145. if __name__ == "__main__":
  146.   app.run(main)
Advertisement
Add Comment
Please, Sign In to add comment