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.

418 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 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 --build-all-labels --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. def createDisjunction(formulas):
  167. return " | ".join(formulas)
  168. def clusterFormula(cluster):
  169. formula = ""
  170. states = [(s[0].x,s[0].y, s[0].ski_position) for s in cluster]
  171. skiPositionGroup = defaultdict(list)
  172. for item in states:
  173. skiPositionGroup[item[2]].append(item)
  174. first = True
  175. for skiPosition, group in skiPositionGroup.items():
  176. formula += f"ski_position={skiPosition} & ("
  177. yPosGroup = defaultdict(list)
  178. for item in group:
  179. yPosGroup[item[1]].append(item)
  180. for y, y_group in yPosGroup.items():
  181. if first:
  182. first = False
  183. else:
  184. formula += " | "
  185. sorted_y_group = sorted(y_group, key=lambda s: s[0])
  186. formula += f"( y={y} & ("
  187. current_x_min = sorted_y_group[0][0]
  188. current_x = sorted_y_group[0][0]
  189. x_ranges = list()
  190. for state in sorted_y_group[1:-1]:
  191. if state[0] - current_x == 1:
  192. current_x = state[0]
  193. else:
  194. x_ranges.append(f" ({current_x_min}<= x & x<={current_x})")
  195. current_x_min = state[0]
  196. current_x = state[0]
  197. x_ranges.append(f" ({current_x_min}<= x & x<={sorted_y_group[-1][0]})")
  198. formula += " | ".join(x_ranges)
  199. formula += ") )"
  200. formula += ")"
  201. return formula
  202. def createUnsafeFormula(clusters):
  203. formulas = ""
  204. disjunction = "formula Unsafe = false"
  205. for i, cluster in enumerate(clusters):
  206. formulas += f"formula Unsafe_{i} = {clusterFormula(cluster)};\n"
  207. clusterFormula(cluster)
  208. disjunction += f" | Unsafe_{i}"
  209. disjunction += ";\n"
  210. label = "label \"Unsafe\" = Unsafe;\n"
  211. return formulas + "\n" + disjunction + label
  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. label = "label \"Safe\" = Safe;\n"
  220. return formulas + "\n" + disjunction + label
  221. def updatePrismFile(newFile, iteration, safeStates, unsafeStates):
  222. logger.info("Creating next prism file")
  223. tic()
  224. initFile = f"{newFile}_no_formulas.prism"
  225. newFile = f"{newFile}_{iteration:03}.prism"
  226. exec(f"cp {initFile} {newFile}", verbose=False)
  227. with open(newFile, "a") as prism:
  228. prism.write(createSafeFormula(safeStates))
  229. prism.write(createUnsafeFormula(unsafeStates))
  230. logger.info(f"Creating next prism file - DONE: took {toc()} seconds")
  231. ale = ALEInterface()
  232. #if SDL_SUPPORT:
  233. # ale.setBool("sound", True)
  234. # ale.setBool("display_screen", True)
  235. # Load the ROM file
  236. ale.loadROM(rom_file)
  237. with open('all_positions_v2.pickle', 'rb') as handle:
  238. ramDICT = pickle.load(handle)
  239. y_ram_setting = 60
  240. x = 70
  241. nn_wrapper = SampleFactoryNNQueryWrapper()
  242. iteration = 0
  243. experiment_id = int(time.time())
  244. init_mdp = "velocity_safety"
  245. exec(f"mkdir -p images/testing_{experiment_id}", verbose=False)
  246. #exec(f"cp 1_full_scaled_down.png images/testing_{experiment_id}/testing_0000.png")
  247. #exec(f"cp {init_mdp}.prism {init_mdp}_000.prism")
  248. markerSize = 1
  249. #markerList = {1: list(), 2:list(), 3:list(), 4:list(), 5:list(), 6:list(), 7:list(), 8:list()}
  250. imagesDir = f"images/testing_{experiment_id}"
  251. def drawOntoSkiPosImage(states, color, target_prefix="cluster_", alpha_factor=1.0):
  252. markerList = {ski_position:list() for ski_position in range(1,num_ski_positions + 1)}
  253. for state in states:
  254. s = state[0]
  255. #marker = f"-fill 'rgba({color}, {alpha_factor * state[1].ranking})' -draw 'rectangle {s.x-markerSize},{s.y-markerSize} {s.x+markerSize},{s.y+markerSize} '"
  256. marker = f"-fill 'rgba({color}, {alpha_factor * state[1].ranking})' -draw 'point {s.x},{s.y} '"
  257. markerList[s.ski_position].append(marker)
  258. for pos, marker in markerList.items():
  259. command = f"convert {imagesDir}/{target_prefix}_{pos:02}_individual.png {' '.join(marker)} {imagesDir}/{target_prefix}_{pos:02}_individual.png"
  260. exec(command, verbose=False)
  261. def concatImages(prefix, iteration):
  262. exec(f"montage {imagesDir}/{prefix}_*_individual.png -geometry +0+0 -tile x1 {imagesDir}/{prefix}_{iteration}.png", verbose=False)
  263. exec(f"sxiv {imagesDir}/{prefix}_{iteration}.png&", verbose=False)
  264. def drawStatesOntoTiledImage(states, color, target, source="images/1_full_scaled_down.png", alpha_factor=1.0):
  265. """
  266. Useful to draw a set of states, e.g. a single cluster
  267. """
  268. markerList = {1: list(), 2:list(), 3:list(), 4:list(), 5:list(), 6:list(), 7:list(), 8:list()}
  269. logger.info(f"Drawing {len(states)} states onto {target}")
  270. tic()
  271. for state in states:
  272. s = state[0]
  273. marker = f"-fill 'rgba({color}, {alpha_factor * state[1].ranking})' -draw 'rectangle {s.x-markerSize},{s.y-markerSize} {s.x+markerSize},{s.y+markerSize} '"
  274. markerList[s.ski_position].append(marker)
  275. for pos, marker in markerList.items():
  276. command = f"convert {source} {' '.join(marker)} {imagesDir}/{target}_{pos:02}_individual.png"
  277. exec(command, verbose=False)
  278. exec(f"montage {imagesDir}/{target}_*_individual.png -geometry +0+0 -tile x1 {imagesDir}/{target}.png", verbose=False)
  279. logger.info(f"Drawing {len(states)} states onto {target} - Done: took {toc()} seconds")
  280. def drawClusters(clusterDict, target, iteration, alpha_factor=1.0):
  281. for ski_position in range(1, num_ski_positions + 1):
  282. source = "images/1_full_scaled_down.png"
  283. exec(f"cp {source} {imagesDir}/{target}_{ski_position:02}_individual.png", verbose=False)
  284. for _, clusterStates in clusterDict.items():
  285. color = f"{np.random.choice(range(256))}, {np.random.choice(range(256))}, {np.random.choice(range(256))}"
  286. drawOntoSkiPosImage(clusterStates, color, target, alpha_factor=alpha_factor)
  287. concatImages(target, iteration)
  288. def drawResult(clusterDict, target, iteration):
  289. for ski_position in range(1, num_ski_positions + 1):
  290. source = "images/1_full_scaled_down.png"
  291. exec(f"cp {source} {imagesDir}/{target}_{ski_position:02}_individual.png")
  292. for _, (clusterStates, result) in clusterDict.items():
  293. color = "100,100,100"
  294. if result == Verdict.GOOD:
  295. color = "0,200,0"
  296. elif result == Verdict.BAD:
  297. color = "200,0,0"
  298. drawOntoSkiPosImage(clusterStates, color, target, alpha_factor=0.7)
  299. concatImages(target, iteration)
  300. def _init_logger():
  301. logger = logging.getLogger('main')
  302. logger.setLevel(logging.INFO)
  303. handler = logging.StreamHandler(sys.stdout)
  304. formatter = logging.Formatter( '[%(levelname)s] %(module)s - %(message)s')
  305. handler.setFormatter(formatter)
  306. logger.addHandler(handler)
  307. def clusterImportantStates(ranking, iteration, n_clusters=40):
  308. logger.info(f"Starting to cluster {len(ranking)} states into {n_clusters} cluster")
  309. tic()
  310. states = [[s[0].x,s[0].y, s[0].ski_position * 10, s[1].ranking] for s in ranking]
  311. kmeans = KMeans(n_clusters, random_state=0, n_init="auto").fit(states)
  312. logger.info(f"Starting to cluster {len(ranking)} states into {n_clusters} cluster - DONE: took {toc()} seconds")
  313. clusterDict = {i : list() for i in range(0,n_clusters)}
  314. for i, state in enumerate(ranking):
  315. clusterDict[kmeans.labels_[i]].append(state)
  316. drawClusters(clusterDict, f"clusters", iteration)
  317. return clusterDict
  318. if __name__ == '__main__':
  319. _init_logger()
  320. logger = logging.getLogger('main')
  321. logger.info("Starting")
  322. n_clusters = 40
  323. testAll = False
  324. safeStates = list()
  325. unsafeStates = list()
  326. iteration = 0
  327. while True:
  328. updatePrismFile(init_mdp, iteration, safeStates, unsafeStates)
  329. computeStateRanking(f"{init_mdp}_{iteration:03}.prism")
  330. ranking = fillStateRanking("action_ranking")
  331. sorted_ranking = sorted( (x for x in ranking.items() if x[1].ranking > 0.1), key=lambda x: x[1].ranking)
  332. clusters = clusterImportantStates(sorted_ranking, iteration, n_clusters)
  333. if testAll: failingPerCluster = {i: list() for i in range(0, n_clusters)}
  334. clusterResult = dict()
  335. for id, cluster in clusters.items():
  336. num_tests = int(factor_tests_per_cluster * len(cluster))
  337. logger.info(f"Testing {num_tests} states (from {len(cluster)} states) from cluster {id}")
  338. randomStates = np.random.choice(len(cluster), num_tests, replace=False)
  339. randomStates = [cluster[i] for i in randomStates]
  340. verdictGood = True
  341. for state in randomStates:
  342. x = state[0].x
  343. y = state[0].y
  344. ski_pos = state[0].ski_position
  345. result = run_single_test(ale,nn_wrapper,x,y,ski_pos, duration=50)
  346. if result == Verdict.BAD:
  347. if testAll:
  348. failingPerCluster[id].append(state)
  349. else:
  350. clusterResult[id] = (cluster, Verdict.BAD)
  351. verdictGood = False
  352. unsafeStates.append(cluster)
  353. break
  354. if verdictGood:
  355. clusterResult[id] = (cluster, Verdict.GOOD)
  356. safeStates.append(cluster)
  357. if testAll: drawClusters(failingPerCluster, f"failing")
  358. drawResult(clusterResult, "result", iteration)
  359. iteration += 1