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.

426 lines
16 KiB

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