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.

417 lines
16 KiB

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