You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

370 lines
14 KiB

  1. import sys
  2. import operator
  3. from os import listdir, system
  4. import re
  5. from random import randrange
  6. from ale_py import ALEInterface, SDL_SUPPORT, Action
  7. #from colors import *
  8. from PIL import Image
  9. from matplotlib import pyplot as plt
  10. import cv2
  11. import pickle
  12. import queue
  13. from dataclasses import dataclass, field
  14. from sklearn.cluster import KMeans
  15. from enum import Enum
  16. from copy import deepcopy
  17. import numpy as np
  18. import logging
  19. logger = logging.getLogger(__name__)
  20. #import readchar
  21. from sample_factory.algo.utils.tensor_dict import TensorDict
  22. from query_sample_factory_checkpoint import SampleFactoryNNQueryWrapper
  23. import time
  24. tempest_binary = "/home/spranger/projects/tempest-devel/ranking_release/bin/storm"
  25. rom_file = "/home/spranger/research/Skiing/env/lib/python3.10/site-packages/AutoROM/roms/skiing.bin"
  26. def tic():
  27. import time
  28. global startTime_for_tictoc
  29. startTime_for_tictoc = time.time()
  30. def toc():
  31. import time
  32. if 'startTime_for_tictoc' in globals():
  33. return time.time() - startTime_for_tictoc
  34. class Verdict(Enum):
  35. INCONCLUSIVE = 1
  36. GOOD = 2
  37. BAD = 3
  38. verdict_to_color_map = {Verdict.BAD: "200,0,0", Verdict.INCONCLUSIVE: "40,40,200", Verdict.GOOD: "00,200,100"}
  39. def convert(tuples):
  40. return dict(tuples)
  41. @dataclass(frozen=True)
  42. class State:
  43. x: int
  44. y: int
  45. ski_position: int
  46. def default_value():
  47. return {'action' : None, 'choiceValue' : None}
  48. @dataclass(frozen=True)
  49. class StateValue:
  50. ranking: float
  51. choices: dict = field(default_factory=default_value)
  52. def exec(command,verbose=True):
  53. if verbose: print(f"Executing {command}")
  54. system(f"echo {command} >> list_of_exec")
  55. return system(command)
  56. num_tests_per_cluster = 50
  57. factor_tests_per_cluster = 0.2
  58. num_ski_positions = 8
  59. def input_to_action(char):
  60. if char == "0":
  61. return Action.NOOP
  62. if char == "1":
  63. return Action.RIGHT
  64. if char == "2":
  65. return Action.LEFT
  66. if char == "3":
  67. return "reset"
  68. if char == "4":
  69. return "set_x"
  70. if char == "5":
  71. return "set_vel"
  72. if char in ["w", "a", "s", "d"]:
  73. return char
  74. def drawImportantStates(important_states):
  75. draw_commands = {1: list(), 2:list(), 3:list(), 4:list(), 5:list(), 6:list(), 7:list(), 8:list(), 9:list(), 10:list(), 11:list(), 12:list(), 13:list(), 14:list()}
  76. for state in important_states:
  77. x = state[0].x
  78. y = state[0].y
  79. markerSize = 2
  80. ski_position = state[0].ski_position
  81. draw_commands[ski_position].append(f"-fill 'rgba(255,204,0,{state[1].ranking})' -draw 'rectangle {x-markerSize},{y-markerSize} {x+markerSize},{y+markerSize} '")
  82. for i in range(1,15):
  83. command = f"convert images/1_full_scaled_down.png {' '.join(draw_commands[i])} first_try_{i:02}.png"
  84. exec(command)
  85. def saveObservations(observations, verdict, testDir):
  86. testDir = f"images/testing_{experiment_id}/{verdict.name}_{testDir}_{len(observations)}"
  87. if len(observations) < 20:
  88. logger.warn(f"Potentially spurious test case for {testDir}")
  89. testDir = f"{testDir}_pot_spurious"
  90. exec(f"mkdir {testDir}", verbose=False)
  91. for i, obs in enumerate(observations):
  92. img = Image.fromarray(obs)
  93. img.save(f"{testDir}/{i:003}.png")
  94. ski_position_counter = {1: (Action.LEFT, 40), 2: (Action.LEFT, 35), 3: (Action.LEFT, 30), 4: (Action.LEFT, 10), 5: (Action.NOOP, 1), 6: (Action.RIGHT, 10), 7: (Action.RIGHT, 30), 8: (Action.RIGHT, 40) }
  95. def run_single_test(ale, nn_wrapper, x,y,ski_position, duration=200):
  96. #print(f"Running Test from x: {x:04}, y: {y:04}, ski_position: {ski_position}", end="")
  97. testDir = f"{x}_{y}_{ski_position}"
  98. for i, r in enumerate(ramDICT[y]):
  99. ale.setRAM(i,r)
  100. ski_position_setting = ski_position_counter[ski_position]
  101. for i in range(0,ski_position_setting[1]):
  102. ale.act(ski_position_setting[0])
  103. ale.setRAM(14,0)
  104. ale.setRAM(25,x)
  105. ale.setRAM(14,180)
  106. all_obs = list()
  107. speed_list = list()
  108. first_action_set = False
  109. first_action = 0
  110. for i in range(0,duration):
  111. resized_obs = cv2.resize(ale.getScreenGrayscale(), (84,84), interpolation=cv2.INTER_AREA)
  112. for i in range(0,4):
  113. all_obs.append(resized_obs)
  114. if len(all_obs) >= 4:
  115. stack_tensor = TensorDict({"obs": np.array(all_obs[-4:])})
  116. action = nn_wrapper.query(stack_tensor)
  117. if not first_action_set:
  118. first_action_set = True
  119. first_action = input_to_action(str(action))
  120. ale.act(input_to_action(str(action)))
  121. else:
  122. ale.act(Action.NOOP)
  123. speed_list.append(ale.getRAM()[14])
  124. if len(speed_list) > 15 and sum(speed_list[-6:-1]) == 0:
  125. saveObservations(all_obs, Verdict.BAD, testDir)
  126. return Verdict.BAD
  127. saveObservations(all_obs, Verdict.GOOD, testDir)
  128. return Verdict.GOOD
  129. def optimalAction(choices):
  130. return max(choices.items(), key=operator.itemgetter(1))[0]
  131. def computeStateRanking(mdp_file):
  132. logger.info("Computing state ranking")
  133. tic()
  134. command = f"{tempest_binary} --prism {mdp_file} --buildchoicelab --buildstateval --prop 'Rmax=? [C <= 1000]'"
  135. exec(command)
  136. logger.info(f"Computing state ranking - DONE: took {toc()} seconds")
  137. def fillStateRanking(file_name, match=""):
  138. logger.info("Parsing state ranking")
  139. tic()
  140. state_ranking = dict()
  141. try:
  142. with open(file_name, "r") as f:
  143. file_content = f.readlines()
  144. for line in file_content:
  145. if not "move=0" in line: continue
  146. ranking_value = float(re.search(r"Value:([+-]?(\d*\.\d+)|\d+)", line)[0].replace("Value:",""))
  147. if ranking_value <= 0.1:
  148. continue
  149. stateMapping = convert(re.findall(r"([a-zA-Z_]*[a-zA-Z])=(\d+)?", line))
  150. #print("stateMapping", stateMapping)
  151. choices = convert(re.findall(r"[a-zA-Z_]*(left|right|noop)[a-zA-Z_]*:(-?\d+\.?\d*)", line))
  152. choices = {key:float(value) for (key,value) in choices.items()}
  153. #print("choices", choices)
  154. #print("ranking_value", ranking_value)
  155. state = State(int(stateMapping["x"]), int(stateMapping["y"]), int(stateMapping["ski_position"]))
  156. value = StateValue(ranking_value, choices)
  157. state_ranking[state] = value
  158. logger.info(f"Parsing state ranking - DONE: took {toc()} seconds")
  159. return state_ranking
  160. except EnvironmentError:
  161. print("Ranking file not available. Exiting.")
  162. toc()
  163. sys.exit(1)
  164. except:
  165. toc()
  166. fixed_left_states = list()
  167. fixed_right_states = list()
  168. fixed_noop_states = list()
  169. def populate_fixed_actions(state, action):
  170. if action == Action.LEFT:
  171. fixed_left_states.append(state)
  172. if action == Action.RIGHT:
  173. fixed_right_states.append(state)
  174. if action == Action.NOOP:
  175. fixed_noop_states.append(state)
  176. def update_prism_file(old_prism_file, new_prism_file):
  177. fixed_left_formula = "formula Fixed_Left = false "
  178. fixed_right_formula = "formula Fixed_Right = false "
  179. fixed_noop_formula = "formula Fixed_Noop = false "
  180. for state in fixed_left_states:
  181. fixed_left_formula += f" | (x={state.x}&y={state.y}&ski_position={state.ski_position}) "
  182. for state in fixed_right_states:
  183. fixed_right_formula += f" | (x={state.x}&y={state.y}&ski_position={state.ski_position}) "
  184. for state in fixed_noop_states:
  185. fixed_noop_formula += f" | (x={state.x}&y={state.y}&ski_position={state.ski_position}) "
  186. fixed_left_formula += ";\n"
  187. fixed_right_formula += ";\n"
  188. fixed_noop_formula += ";\n"
  189. with open(f'{old_prism_file}', 'r') as file :
  190. filedata = file.read()
  191. if len(fixed_left_states) > 0: filedata = re.sub(r"^formula Fixed_Left =.*$", fixed_left_formula, filedata, flags=re.MULTILINE)
  192. if len(fixed_right_states) > 0: filedata = re.sub(r"^formula Fixed_Right =.*$", fixed_right_formula, filedata, flags=re.MULTILINE)
  193. if len(fixed_noop_states) > 0: filedata = re.sub(r"^formula Fixed_Noop =.*$", fixed_noop_formula, filedata, flags=re.MULTILINE)
  194. with open(f'{new_prism_file}', 'w') as file:
  195. file.write(filedata)
  196. ale = ALEInterface()
  197. #if SDL_SUPPORT:
  198. # ale.setBool("sound", True)
  199. # ale.setBool("display_screen", True)
  200. # Load the ROM file
  201. ale.loadROM(rom_file)
  202. with open('all_positions_v2.pickle', 'rb') as handle:
  203. ramDICT = pickle.load(handle)
  204. y_ram_setting = 60
  205. x = 70
  206. nn_wrapper = SampleFactoryNNQueryWrapper()
  207. iteration = 0
  208. experiment_id = int(time.time())
  209. init_mdp = "velocity_safety"
  210. exec(f"mkdir -p images/testing_{experiment_id}")
  211. exec(f"cp 1_full_scaled_down.png images/testing_{experiment_id}/testing_0000.png")
  212. exec(f"cp {init_mdp}.prism {init_mdp}_000.prism")
  213. markerSize = 1
  214. #markerList = {1: list(), 2:list(), 3:list(), 4:list(), 5:list(), 6:list(), 7:list(), 8:list()}
  215. imagesDir = f"images/testing_{experiment_id}"
  216. def drawOntoSkiPosImage(states, color, target_prefix="cluster_", alpha_factor=1.0):
  217. markerList = {ski_position:list() for ski_position in range(1,num_ski_positions + 1)}
  218. for state in states:
  219. s = state[0]
  220. marker = f"-fill 'rgba({color}, {alpha_factor * state[1].ranking})' -draw 'rectangle {s.x-markerSize},{s.y-markerSize} {s.x+markerSize},{s.y+markerSize} '"
  221. markerList[s.ski_position].append(marker)
  222. for pos, marker in markerList.items():
  223. command = f"convert {imagesDir}/{target_prefix}_{pos:02}.png {' '.join(marker)} {imagesDir}/{target_prefix}_{pos:02}.png"
  224. exec(command, verbose=False)
  225. def concatImages(prefix):
  226. exec(f"montage {imagesDir}/{prefix}_*png -geometry +0+0 -tile x1 {imagesDir}/{prefix}.png", verbose=False)
  227. exec(f"sxiv {imagesDir}/{prefix}.png&")
  228. def drawStatesOntoTiledImage(states, color, target, source="images/1_full_scaled_down.png", alpha_factor=1.0):
  229. """
  230. Useful to draw a set of states, e.g. a single cluster
  231. """
  232. markerList = {1: list(), 2:list(), 3:list(), 4:list(), 5:list(), 6:list(), 7:list(), 8:list()}
  233. logger.info(f"Drawing {len(states)} states onto {target}")
  234. tic()
  235. for state in states:
  236. s = state[0]
  237. marker = f"-fill 'rgba({color}, {alpha_factor * state[1].ranking})' -draw 'rectangle {s.x-markerSize},{s.y-markerSize} {s.x+markerSize},{s.y+markerSize} '"
  238. markerList[s.ski_position].append(marker)
  239. for pos, marker in markerList.items():
  240. command = f"convert {source} {' '.join(marker)} {imagesDir}/{target}_{pos:02}.png"
  241. exec(command, verbose=False)
  242. exec(f"montage {imagesDir}/{target}_*png -geometry +0+0 -tile x1 {imagesDir}/{target}.png", verbose=False)
  243. logger.info(f"Drawing {len(states)} states onto {target} - Done: took {toc()} seconds")
  244. def drawClusters(clusterDict, target, alpha_factor=1.0):
  245. for ski_position in range(1, num_ski_positions + 1):
  246. source = "images/1_full_scaled_down.png"
  247. exec(f"cp {source} {imagesDir}/{target}_{ski_position:02}.png")
  248. for _, clusterStates in clusterDict.items():
  249. color = f"{np.random.choice(range(256))}, {np.random.choice(range(256))}, {np.random.choice(range(256))}"
  250. drawOntoSkiPosImage(clusterStates, color, target, alpha_factor=alpha_factor)
  251. concatImages(target)
  252. def drawResult(clusterDict, target):
  253. for ski_position in range(1, num_ski_positions + 1):
  254. source = "images/1_full_scaled_down.png"
  255. exec(f"cp {source} {imagesDir}/{target}_{ski_position:02}.png")
  256. for _, (clusterStates, result) in clusterDict.items():
  257. color = "100,100,100"
  258. if result == Verdict.GOOD:
  259. color = "0,200,0"
  260. elif result == Verdict.BAD:
  261. color = "200,0,0"
  262. drawOntoSkiPosImage(clusterStates, color, target, alpha_factor=0.7)
  263. concatImages(target)
  264. def _init_logger():
  265. logger = logging.getLogger('main')
  266. logger.setLevel(logging.INFO)
  267. handler = logging.StreamHandler(sys.stdout)
  268. formatter = logging.Formatter( '[%(levelname)s] %(module)s - %(message)s')
  269. handler.setFormatter(formatter)
  270. logger.addHandler(handler)
  271. def clusterImportantStates(ranking, n_clusters=40):
  272. logger.info(f"Starting to cluster {len(ranking)} states into {n_clusters} cluster")
  273. tic()
  274. states = [[s[0].x,s[0].y, s[0].ski_position * 10, s[1].ranking] for s in ranking]
  275. kmeans = KMeans(n_clusters, random_state=0, n_init="auto").fit(states)
  276. logger.info(f"Starting to cluster {len(ranking)} states into {n_clusters} cluster - DONE: took {toc()} seconds")
  277. clusterDict = {i : list() for i in range(0,n_clusters)}
  278. for i, state in enumerate(ranking):
  279. clusterDict[kmeans.labels_[i]].append(state)
  280. drawClusters(clusterDict, f"clusters")
  281. return clusterDict
  282. if __name__ == '__main__':
  283. _init_logger()
  284. logger = logging.getLogger('main')
  285. logger.info("Starting")
  286. n_clusters = 40
  287. testAll = False
  288. while True:
  289. #computeStateRanking(f"{init_mdp}_{iteration:03}.prism")
  290. ranking = fillStateRanking("action_ranking")
  291. sorted_ranking = sorted( (x for x in ranking.items() if x[1].ranking > 0.1), key=lambda x: x[1].ranking)
  292. clusters = clusterImportantStates(sorted_ranking, n_clusters)
  293. if testAll: failingPerCluster = {i: list() for i in range(0, n_clusters)}
  294. clusterResult = dict()
  295. for id, cluster in clusters.items():
  296. num_tests = int(factor_tests_per_cluster * len(cluster))
  297. num_tests = 1
  298. logger.info(f"Testing {num_tests} states (from {len(cluster)} states) from cluster {id}")
  299. randomStates = np.random.choice(len(cluster), num_tests, replace=False)
  300. randomStates = [cluster[i] for i in randomStates]
  301. verdictGood = True
  302. for state in randomStates:
  303. x = state[0].x
  304. y = state[0].y
  305. ski_pos = state[0].ski_position
  306. result = run_single_test(ale,nn_wrapper,x,y,ski_pos, duration=50)
  307. if result == Verdict.BAD:
  308. if testAll:
  309. failingPerCluster[id].append(state)
  310. else:
  311. clusterResult[id] = (cluster, Verdict.BAD)
  312. verdictGood = False
  313. break
  314. if verdictGood:
  315. clusterResult[id] = (cluster, Verdict.GOOD)
  316. if testAll: drawClusters(failingPerCluster, f"failing")
  317. drawResult(clusterResult, "result")
  318. update_prism_file(f"{init_mdp}_{iteration-1:03}.prism", f"{init_mdp}_{iteration:03}.prism")