Debian Codegraph @

legacy/bench-empty.py

raw symbols SCIP
1 import re
2 import os
3 import sys
4 import lzma
5 import tempfile
6 import subprocess
7 import importlib.resources
8 from collections import deque, Counter, namedtuple
9 from itertools import chain, count, zip_longest
10 from functools import reduce
11 from random import shuffle, seed
12 from warnings import warn
13 from math import factorial
14 from multiprocessing.dummy import Pool
15 import pickle
16 import json
17 from apycula.wirenames import wirenames, clknames
18 from PIL import Image, ImageDraw
19 from shutil import copytree
20
21 from apycula import bitmatrix
22 from apycula import attrids
23 from apycula import codegen
24 from apycula import bslib
25 from apycula import pindef
26 from apycula import fse_parser
27 from apycula import gowin_pack
28 import tiled_fuzzer
29 from apycula import codegen
30 from apycula import bslib
31 #TODO proper API
32 #from apycula import dat19_h4x
33 from apycula import tm_parser
34 from apycula import chipdb
35
36 gowinhome = os.getenv("GOWINHOME")
37 if not gowinhome:
38 raise Exception("GOWINHOME not set")
39
40 # device = os.getenv("DEVICE")
41 device = sys.argv[1]
42
43 params = {
44 "GW1NS-2": {
45 "package": "LQFP144",
46 "device": "GW1NS-2C",
47 "partnumber": "GW1NS-UX2CLQ144C5/I4",
48 },
49 "GW1NS-4": {
50 "package": "QFN48",
51 "device": "GW1NSR-4C",
52 "partnumber": "GW1NSR-LV4CQN48PC7/I6",
53 },
54 "GW1N-9": {
55 "package": "PBGA256",
56 "device": "GW1N-9",
57 "partnumber": "GW1N-LV9PG256C6/I5",
58 },
59 "GW1N-9C": {
60 "package": "UBGA332",
61 "device": "GW1N-9C",
62 "partnumber": "GW1N-LV9UG332C6/I5",
63 },
64 "GW1N-4": {
65 "package": "PBGA256",
66 "device": "GW1N-4",
67 "partnumber": "GW1N-LV4PG256C6/I5",
68 },
69 "GW1N-1": {
70 "package": "LQFP144",
71 "device": "GW1N-1",
72 "partnumber": "GW1N-LV1LQ144C6/I5",
73 },
74 "GW1NZ-1": {
75 "package": "QFN48",
76 "device": "GW1NZ-1",
77 "partnumber": "GW1NZ-LV1QN48C6/I5",
78 },
79 "GW2A-18": {
80 "package": "PBGA256",
81 "device": "GW2A-18",
82 "partnumber": "GW2A-LV18PG256C8/I7",
83 },
84 "GW2A-18C": {
85 "package": "PBGA256S",
86 "device": "GW2A-18C",
87 "partnumber": "GW2A-LV18PG256SC8/I7", #"GW2AR-LV18PG256SC8/I7", "GW2AR-LV18QN88C8/I7"
88 },
89 "GW5A-25A": {
90 "package": "MBGA121N",
91 "device": "GW5A-25A",
92 "partnumber": "GW5A-LV25MG121NC1/I0",
93 },
94 "GW1N-1P5C": {
95 "package": "QFN48XF",
96 "device": "GW1N-1P5C",
97 "partnumber": "GW1N-UV1P5QN48XFC7/I6",
98 },
99 "GW5AST-138C": {
100 "package": "PBGA484A",
101 "device": "GW5AST-138C",
102 "partnumber": "GW5AST-LV138PG484AC1/I0",
103 },
104 }[device]
105
106 # collect all routing bits of the tile
107 _route_mem = {}
108 def route_bits(db, row, col):
109 mem = _route_mem.get((row, col), None)
110 if mem != None:
111 return mem
112
113 bits = set()
114 for w in db[row, col].pips.values():
115 for v in w.values():
116 bits.update(v)
117 for w in db[row, col].clock_pips.values():
118 for v in w.values():
119 bits.update(v)
120 _route_mem.setdefault((row, col), bits)
121 return bits
122
123 def get_fuse_num(ttyp, y, x):
124 # bits YYXX
125 if device.lower().startswith('gw5'):
126 bits = y * 200 + x
127 else:
128 bits = y * 100 + x
129
130 for i, fs in enumerate(fse['header']['fuse'][1]):
131 if fs[ttyp] == bits:
132 return i
133 return -1
134
135 def print_longval(ttyp, table, contains = None, must_all = False):
136 "ttyp, num, contains = 0"
137 for row in fse[ttyp]['longval'][table]:
138 if contains == None:
139 print(row)
140 else:
141 are_all = must_all
142 for val in contains:
143 if val in row[16:]:
144 are_all = True
145 if not must_all:
146 break
147 else:
148 if must_all:
149 are_all = False
150 break
151 if are_all:
152 print(row)
153
154 def print_longval_key(ttyp, table, key, ignore_key_elem = 0, zeros = True):
155 if zeros:
156 sorted_key = (sorted(key) + [0] * 16)[:16 - ignore_key_elem]
157 end = 16
158 else:
159 sorted_key = sorted(key)
160 end = ignore_key_elem + len(sorted_key)
161 for rec in fse[ttyp]['longval'][table]:
162 k = rec[ignore_key_elem:end]
163 if k == sorted_key:
164 print(rec)
165
166 def print_alonenode(ttyp, contains = 0):
167 "ttyp, contains = 0"
168 for row in fse[ttyp]['alonenode'][69]:
169 if contains == 0 or contains in row:
170 print(row)
171
172 def get_wires_to(fse, ttyp, wiren, table = 2):
173 for wr in [wire for wire in fse[ttyp]['wire'][table] if wire[1] == wiren]:
174 print(wr)
175
176 def get_wires_from(fse, ttyp, wiren, table = 2):
177 for wr in [wire for wire in fse[ttyp]['wire'][table] if wire[0] == wiren]:
178 print(wr)
179
180 def get_grid_rc(fse, row, col):
181 grow = 0
182 h = fse[fse['header']['grid'][61][row][col]]['height']
183 while row:
184 grow += h
185 h = fse[fse['header']['grid'][61][row][col]]['height']
186 row -= 1
187 gcol = 0
188 w = fse[fse['header']['grid'][61][row][col]]['width']
189 while col:
190 gcol += w
191 w = fse[fse['header']['grid'][61][row][col]]['width']
192 col -= 1
193 return (grow, gcol, h, w)
194
195 def pict(bm, name):
196 im = bslib.display(None, bm)
197 im_scaled = im.resize((im.width * 10, im.height * 10), Image.NEAREST)
198 im_scaled.save(f"/home/rabbit/tmp/{name}")
199
200 def get_bits(bm):
201 bits = set()
202 rows, cols =bitmatrix.shape(bm)
203 for row in range(rows):
204 for col in range(cols):
205 if bm[row][col] == 1:
206 bits.update({(row, col)})
207 return bits
208
209 def deep_bank_cmp(bel, ref_bel):
210 keys = set(bel.bank_flags.keys())
211 ref_keys = set(ref_bel.bank_flags.keys())
212 if keys != ref_keys:
213 print(f' keys diff:{keys ^ ref_keys}')
214 return
215 for key, val in bel.bank_flags.items():
216 if val != ref_bel.bank_flags[key]:
217 print(f' val diff: {key}:{val} vs {ref_bel.bank_flags[key]}')
218
219 def deep_io_cmp(bel, ref_bel, irow, icol, ibel):
220 iostd_keys = set(bel.iob_flags.keys())
221 ref_iostd_keys = set(ref_bel.iob_flags.keys())
222 if iostd_keys != ref_iostd_keys:
223 print(f' iostd diff:{iostd_keys ^ ref_iostd_keys}')
224 for iostd_key, typ_rec in bel.iob_flags.items():
225 ref_typ_rec = ref_bel.iob_flags[iostd_key]
226 if set(typ_rec.keys()) != set(ref_typ_rec.keys()):
227 print(f' type diff:{iostd_key} {set(typ_rec.keys()) ^ set(ref_typ_rec.keys())}')
228 continue
229 if typ_rec == ref_typ_rec:
230 continue
231 print(f' {iostd_key}')
232 for typ_key, flag_rec in typ_rec.items():
233 ref_flag_rec = ref_typ_rec[typ_key]
234 if set(flag_rec.flags.keys()) != set(ref_flag_rec.flags.keys()):
235 print(f' flag diff:{iostd_key} {typ_key} {set(flag_rec.flags.keys()) ^ set(ref_flag_rec.flags.keys())}')
236 continue
237 if flag_rec == ref_flag_rec:
238 continue;
239 print(f' {typ_key}')
240 if flag_rec.encode_bits != ref_flag_rec.encode_bits:
241 print(f' encode diff:({irow}, {icol})[{ibel}] {iostd_key} {typ_key} {flag_rec.encode_bits ^ ref_flag_rec.encode_bits}')
242 for flag_key, opt_rec in flag_rec.flags.items():
243 ref_opt_rec = ref_flag_rec.flags[flag_key]
244 if set(opt_rec.options.keys()) != set(ref_opt_rec.options.keys()):
245 print(f' opt diff:{iostd_key} {typ_key} {flag_key} {set(opt_rec.options.keys()) ^ set(ref_opt_rec.options.keys())}')
246 continue
247 if opt_rec == ref_opt_rec:
248 continue
249 print(f' {flag_key}')
250 for opt_key, bits in opt_rec.options.items():
251 ref_bits = ref_opt_rec.options[opt_key]
252 if bits != ref_bits:
253 print(f' bits diff:{iostd_key} {typ_key} {flag_key} {opt_key} {bits} vs {ref_bits}')
254
255
256 def tbrl2rc(fse, side, num):
257 if side == 'T':
258 row = 0
259 col = int(num) - 1
260 elif side == 'B':
261 row = len(fse['header']['grid'][61])-1
262 col = int(num) - 1
263 elif side == 'L':
264 row = int(num) - 1
265 col = 0
266 elif side == 'R':
267 row = int(num) - 1
268 col = len(fse['header']['grid'][61][0])-1
269 return (row, col)
270
271 def attrs2log(attrs, pos):
272 for name, p in attrs[0].items():
273 if p == pos:
274 return f'{pos}:{attrs[1][name]}:{name}'
275
276 def st(tiletyp, fuses):
277 res = []
278 sorted_res = []
279 for tname, tables in fse[tiletyp].items():
280 if tname in {"width", "height"}: continue
281 for ttyp, table in tables.items():
282 for row in table:
283 row_fuses = fuses.intersection(row)
284 if row_fuses:
285 #print(f"fuses {row_fuses} found in {tname}({ttyp}): {row}")
286 sorted_res.append((row_fuses, tname, ttyp, row))
287 res.append(row)
288 for rd in sorted(sorted_res, key = lambda x: ord(x[1][0]) * 100000 + x[2] * 100 + len(x[0])):
289 print(f"fuses {sorted(rd[0])} found in {rd[1]}({rd[2]}): {rd[3]}")
290 return
291
292 def find_node(name):
293 for node_key, node_rec in db.nodes.items():
294 for node in node_rec[1]:
295 if node[2] == name:
296 print('*', node_key, node_rec)
297
298 def find_nodes_row(row):
299 for node_key, node_rec in db.nodes.items():
300 for node in node_rec[1]:
301 if node[0] == row:
302 print('*', node_key, node_rec)
303
304 def find_nodes_row(row, name):
305 for node_key, node_rec in db.nodes.items():
306 for node in node_rec[1]:
307 if node[0] == row and node[2] == name:
308 print(node)
309
310 if __name__ == "__main__":
311 with open(f"{gowinhome}/IDE/share/device/{params['device']}/{params['device']}.fse", 'rb') as f:
312 fse = fse_parser.read_fse(f, device)
313
314 with open(f"{gowinhome}/IDE/share/device/{params['device']}/{params['device']}.tm", 'rb') as f:
315 tm = tm_parser.read_tm(f, device)
316
317 with open(f"/home/rabbit/src/apicula/{device}-dat.pickle", "rb") as f:
318 dat = pickle.load(f)
319
320 db = chipdb.load_chipdb(f"/home/rabbit/src/apicula/apycula/{device}.msgpack.xz")
321
322 if len(sys.argv) > 2:
323 img = bslib.read_bitstream(f'{sys.argv[2]}')[0]
324 bm = chipdb.tile_bitmap(db, img, True)
325 else:
326 import ipdb; ipdb.set_trace()
327
328 #for ri, rr in dat['CiuBdConnection'].items():
329 # print(ri, rr)
330
331 """
332 seen = set()
333 for row in fse['header']['grid'][61]:
334 for ttyp in row:
335 if ttyp not in seen:
336 seen.add(ttyp)
337 src = set()
338 for rrow in fse[ttyp]['wire'][2]:
339 if rrow[0] in {289, 290}:
340 src.add(rrow[0])
341 if src:
342 print(ttyp, src)
343 """
344
345 row3 = db.rows - 1
346 col3 = db.cols - 1
347 row3 = 0
348 col3 = 0
349 import ipdb; ipdb.set_trace()
350 # cmp images
351 if len(sys.argv) > 3:
352 fuses = set()
353 sec_img = bslib.read_bitstream(f'{sys.argv[3]}')[0]
354 sec_bm = chipdb.tile_bitmap(db, sec_img)
355 diff = bitmatrix.xor(img, sec_img)
356 diff_tiles = fse_parser.tile_bitmap(fse, diff)
357 sec_tiles = fse_parser.tile_bitmap(fse, sec_img)
358 print(diff_tiles.keys())
359 ttyp = fse['header']['grid'][61][row3][col3]
360 # first tiles wo same
361 first_tiles = set()
362 for ft in fse_parser.tile_bitmap(fse, img):
363 if ft in diff_tiles:
364 first_tiles.update({ft})
365 print('first tiles:', sorted(first_tiles))
366 #print(fse_parser.parse_tile(fse, 49, fse_parser.tile_bitmap(fse, img)[(19, 37, 49)]))
367 #print(fse_parser.parse_tile(fse, 49, fse_parser.tile_bitmap(fse, sec_img)[(19, 37, 49)]))
368 print('first bits:', sorted(get_bits(fse_parser.tile_bitmap(fse, img, True)[(row3, col3, ttyp)])))
369 fuses = set()
370 for df in get_bits(fse_parser.tile_bitmap(fse, img, True)[(row3, col3, ttyp)]):
371 fuses.update({get_fuse_num(ttyp, df[0], df[1])})
372 print('first fuses:', sorted(fuses))
373 if (row3, col3, ttyp) in fse_parser.tile_bitmap(fse, sec_img).keys():
374 print('second bits:', sorted(get_bits(fse_parser.tile_bitmap(fse, sec_img)[(row3, col3, ttyp)])))
375 rbits = route_bits(db, row3, col3)
376 fuses = set()
377 func_fuses = set()
378 for df in get_bits(diff_tiles[(row3, col3, ttyp)]):
379 fuses.update({get_fuse_num(ttyp, df[0], df[1])})
380 if df not in rbits:
381 func_fuses.update({get_fuse_num(ttyp, df[0], df[1])})
382 print("=====================================")
383 print("all diff:", sorted(fuses))
384 print("func diff:", sorted(func_fuses))
385 print("=====================================")
386
387 row = row3
388 col = col3
389 ttyp = fse['header']['grid'][61][row][col]
390 consts = set()
391 if 'const' in fse[ttyp].keys():
392 consts = {item for sublist in fse[ttyp]['const'][4] for item in sublist}
393 print("consts:", consts)
394
395 rbits = route_bits(db, row, col)
396 r, c = bitmatrix.nonzero(bm[(row, col)])
397 tile = set(zip(r, c))
398 bits = tile# - rbits
399 fuses = set()
400 for df in sorted(bits):
401 fs = get_fuse_num(ttyp, df[0], df[1])
402 if fs not in consts:
403 fuses.update({fs})
404 print("all first bits:")
405 #print(sorted(bits))
406 print(sorted(fuses))
407 all_fuses = fuses.copy()
408 fuses = set()
409 for df in sorted(bits):
410 if df in rbits:
411 fuses.update({get_fuse_num(ttyp, df[0], df[1])})
412 print('route:', sorted(fuses))
413 print('func:', sorted(all_fuses - fuses))
414
415
416 if (row3, col3, ttyp) in fse_parser.tile_bitmap(fse, sec_img).keys():
417 rbits = route_bits(db, row, col)
418 r, c = bitmatrix.nonzero(sec_bm[(row, col)])
419 tile = set(zip(r, c))
420 bits = tile# - rbits
421 fuses = set()
422 for df in sorted(bits):
423 fs = get_fuse_num(ttyp, df[0], df[1])
424 if fs not in consts:
425 fuses.update({fs})
426 print("all second bits:")
427 #print(sorted(bits))
428 print(sorted(fuses))
429 all_fuses = fuses.copy()
430 fuses = set()
431 for df in sorted(bits):
432 if df in rbits:
433 fuses.update({get_fuse_num(ttyp, df[0], df[1])})
434 print('route:', sorted(fuses))
435 print('func:', sorted(all_fuses - fuses))
436 print(row, col, ttyp)
437
438 import ipdb; ipdb.set_trace()