-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathplc_client_os.pyx
2145 lines (1827 loc) · 79.7 KB
/
plc_client_os.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# distutils: language = c++
"""Open-Sourced PlacementCost client class."""
from ast import Assert
import os, io
import re
import math
from typing import Text, Tuple, overload
from absl import logging
from collections import namedtuple
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import traceback, sys
import random
import textwrap
import numpy as np
from circuit_training.grouping import meta_netlist_data_structure as mnds
from circuit_training.grouping import meta_netlist_convertor
from circuit_training.grouping import meta_netlist_util
# Compile: cd Plc_client_v2 && python3 setup.py build_ext --inplace && cd ..
# Cython
from cython cimport view
from libcpp cimport bool
from libcpp.vector cimport vector
from libc.string cimport memset
cimport numpy as cnp
cnp.import_array() # needed to initialize numpy-API
"""plc_client_os docstrings.
Open-sourced effort for plc_client and Google's API, plc_wrapper_main. This module
is used to initialize a PlacementCost object that computes the meta-information and
proxy cost function for RL agent's reward signal at the end of each placement.
Example:
For testing, please refer to plc_client_os_test.py for more information.
python3 setup.py build_ext --inplace
"""
# Block = namedtuple('Block', 'x_max y_max x_min y_min')
cdef class PlacementCost:
# str as general purpose PyObject *
cdef:
public str netlist_file
public float macro_macro_x_spacing
public float macro_macro_y_spacing
# meta information
cdef:
public meta_netlist
str init_plc
str project_name
str block_name
float width
float height
int grid_col
int grid_row
float hroutes_per_micron
float vroutes_per_micron
float smooth_range
float overlap_thres
float hrouting_alloc
float vrouting_alloc
float macro_horizontal_routing_allocation
float macro_vertical_routing_allocation
bool canvas_boundary_check
float grid_width
float grid_height
dict node_fix
dict node_placed
# store module/component count
cdef:
int port_cnt
int hard_macro_cnt
int hard_macro_pin_cnt
int soft_macro_cnt
int soft_macro_pin_cnt
int module_cnt
# indices storage
cdef:
vector[int] port_indices
vector[int] hard_macro_indices
vector[int] hard_macro_pin_indices
vector[int] soft_macro_indices
vector[int] soft_macro_pin_indices
vector[int] macro_indices
# modules look-up table
cdef:
dict mod_name_to_indices
dict macro_id_to_indices
dict port_id_to_indices
object modules_w_pins
dict hard_macros_to_inpins
dict soft_macros_to_inpins
# store nets information
cdef:
int net_cnt
dict nets
# update flags
cdef:
bool FLAG_UPDATE_WIRELENGTH
bool FLAG_UPDATE_DENSITY
bool FLAG_UPDATE_CONGESTION
bool FLAG_UPDATE_MACRO_ADJ
bool FLAG_UPDATE_MACRO_AND_CLUSTERED_PORT_ADJ
bool FLAG_UPDATE_NODE_MASK
# density
cdef:
object grid_cells
object grid_occupied
# congestion
cdef:
object V_routing_cong
object H_routing_cong
object V_macro_routing_cong
object H_macro_routing_cong
float grid_v_routes
float grid_h_routes
# fd placer
cdef:
dict soft_macro_disp
# miscellaneous
cdef:
list blockages
list placed_macro
bool use_incremental_cost
object node_mask
def __init__(self,
str netlist_file,
float macro_macro_x_spacing = 0.0,
float macro_macro_y_spacing = 0.0):
"""
Creates a PlacementCost object.
"""
print("Creates a PlacementCost object")
# str as general purpose PyObject *
# Check netlist existance
self.netlist_file = netlist_file
self.macro_macro_x_spacing = macro_macro_x_spacing
self.macro_macro_y_spacing = macro_macro_y_spacing
# use google open-sourced parser
self.meta_netlist = meta_netlist_convertor.read_netlist(self.netlist_file)
meta_netlist_util.set_canvas_width_height(self.meta_netlist, 10, 10)
# store nets information
self.net_cnt = 0
# [Experimental] Net Data Structure
# nets[driver] => [list of sinks]
self.nets = {}
# modules to index look-up table
self.mod_name_to_indices = {}
# Set meta information
self.init_plc = None
self.project_name = "circuit_training"
self.block_name = netlist_file.rsplit('/', -1)[-2]
self.hroutes_per_micron = 0.0
self.vroutes_per_micron = 0.0
self.smooth_range = 0.0
self.overlap_thres = 0.0
self.hrouting_alloc = 0.0
self.vrouting_alloc = 0.0
self.macro_horizontal_routing_allocation = 0.0
self.macro_vertical_routing_allocation = 0.0
self.canvas_boundary_check = True
# macro to pins look-up table: [MACRO_NAME] => [PIN_NAME]
self.hard_macros_to_inpins = {}
self.soft_macros_to_inpins = {}
# Placed macro
self.placed_macro = []
# not used
self.use_incremental_cost = False
# blockage
self.blockages = []
# default canvas width/height based on cell area
self.width = math.sqrt(self.get_area()/0.6)
self.height = math.sqrt(self.get_area()/0.6)
# default gridding
self.grid_col = 10
self.grid_row = 10
self.grid_width = float(self.width/self.grid_col)
self.grid_height = float(self.height/self.grid_row)
# initialize congestion map
self.V_routing_cong = np.zeros(shape=(self.grid_col * self.grid_row))
self.H_routing_cong = np.zeros(shape=(self.grid_col * self.grid_row))
self.V_macro_routing_cong = np.zeros(shape=(self.grid_col * self.grid_row))
self.H_macro_routing_cong = np.zeros(shape=(self.grid_col * self.grid_row))
# initial grid mask, flatten before output, not used
self.node_mask = np.ones(shape=(self.grid_row, self.grid_col))
# store module/component count
self.port_cnt = len(self.port_indices)
self.hard_macro_cnt = len(self.hard_macro_indices)
self.hard_macro_pin_cnt = len(self.hard_macro_pin_indices)
self.soft_macro_cnt = len(self.soft_macro_indices)
self.soft_macro_pin_cnt = len(self.soft_macro_pin_indices)
self.module_cnt = self.hard_macro_cnt + self.soft_macro_cnt + self.port_cnt
# Update flags
self.FLAG_UPDATE_WIRELENGTH = True
self.FLAG_UPDATE_DENSITY = True
self.FLAG_UPDATE_CONGESTION = True
self.FLAG_UPDATE_MACRO_ADJ = True
self.FLAG_UPDATE_MACRO_AND_CLUSTERED_PORT_ADJ = True
# FD: store x/y displacement for all soft macro disp
soft_macro_disp = {}
self.node_fix = {}
self.node_placed = {}
self.macro_id_to_indices = {}
macro_idx = 0
port_idx = 0
# read netlist list into data structures
for mod in self.meta_netlist.node:
# [MOD.NAME] => [MOD.ID]
self.mod_name_to_indices[mod.name] = mod.id
if mod.type == mnds.Type.STDCELL:
# standard cell, not used
self.std_cell_cnt += 1
elif mod.type == mnds.Type.MACRO:
# unfix macro
self.node_fix[mod.id] = False
# macro placed
self.node_placed[mod.id] = True
# [mod.id] ==> index
self.macro_id_to_indices[mod.id] = macro_idx
macro_idx += 1
if mod.soft_macro:
# soft macro
self.soft_macro_cnt += 1
self.soft_macro_indices.push_back(mod.id)
else:
# hard macro
self.hard_macro_cnt += 1
self.hard_macro_indices.push_back(mod.id)
self.macro_indices.push_back(mod.id)
elif mod.type == mnds.Type.PORT:
# fix ports
self.node_fix[mod.id] = True
# port placed
self.node_placed[mod.id] = True
# port
self.port_cnt += 1
self.port_indices.push_back(mod.id)
# self.port_id_to_indices[mod.id] = port_idx
port_idx += 1
elif mod.type == mnds.Type.MACRO_PIN:
ref_id = mod.ref_node_id
if self.meta_netlist.node[ref_id].soft_macro:
# soft macro pin
self.soft_macro_pin_cnt += 1
self.soft_macro_pin_indices.push_back(mod.id)
else:
# hard macro pin
self.hard_macro_pin_cnt += 1
self.hard_macro_pin_indices.push_back(mod.id)
# read net information
if (mod.type == mnds.Type.MACRO_PIN or mod.type == mnds.Type.PORT) and len(mod.output_indices) > 0:
self.nets[mod.id] = mod.output_indices.copy()
self.net_cnt += mod.weight
def get_netlist_obj(self):
return self.meta_netlist
def __read_plc(self, plc_pth: str):
"""
Plc file Parser
"""
# meta information
_columns = 0
_rows = 0
_width = 0.0
_height = 0.0
_area = 0.0
_block = None
_routes_per_micron_hor = 0.0
_routes_per_micron_ver = 0.0
_routes_used_by_macros_hor = 0.0
_routes_used_by_macros_ver = 0.0
_smoothing_factor = 0
_overlap_threshold = 0.0
# node information
_hard_macro_cnt = 0
_hard_macro_pin_cnt = 0
_macro_cnt = 0
_macro_pin_cnt = 0
_port_cnt = 0
_soft_macro_cnt = 0
_soft_macro_pin_cnt = 0
_stdcell_cnt = 0
# node placement
_node_plc = {}
for cnt, line in enumerate(open(plc_pth, 'r')):
line_item = re.findall(r'[0-9A-Za-z\.\-]+', line)
# skip empty lines
if len(line_item) == 0:
continue
if 'Columns' in line_item and 'Rows' in line_item:
# Columns and Rows should be defined on the same one-line
_columns = int(line_item[1])
_rows = int(line_item[3])
elif "Width" in line_item and "Height" in line_item:
# Width and Height should be defined on the same one-line
_width = float(line_item[1])
_height = float(line_item[3])
elif all(it in line_item for it in ['Area', 'stdcell', 'macros']):
# Total core area of modules
_area = float(line_item[3])
elif "Area" in line_item:
# Total core area of modules
_area = float(line_item[1])
elif "Block" in line_item:
# The block name of the testcase
_block = str(line_item[1])
elif all(it in line_item for it in\
['Routes', 'per', 'micron', 'hor', 'ver']):
# For routing congestion computation
_routes_per_micron_hor = float(line_item[4])
_routes_per_micron_ver = float(line_item[6])
elif all(it in line_item for it in\
['Routes', 'used', 'by', 'macros', 'hor', 'ver']):
# For MACRO congestion computation
_routes_used_by_macros_hor = float(line_item[5])
_routes_used_by_macros_ver = float(line_item[7])
elif all(it in line_item for it in ['Smoothing', 'factor']):
# smoothing factor for routing congestion
_smoothing_factor = float(line_item[2])
elif all(it in line_item for it in ['Overlap', 'threshold']):
# overlap
_overlap_threshold = float(line_item[2])
elif all(it in line_item for it in ['HARD', 'MACROs'])\
and len(line_item) == 3:
_hard_macro_cnt = int(line_item[2])
elif all(it in line_item for it in ['HARD', 'MACRO', 'PINs'])\
and len(line_item) == 4:
_hard_macro_pin_cnt = int(line_item[3])
elif all(it in line_item for it in ['PORTs'])\
and len(line_item) == 2:
_port_cnt = int(line_item[1])
elif all(it in line_item for it in ['SOFT', 'MACROs'])\
and len(line_item) == 3:
_soft_macro_cnt = int(line_item[2])
elif all(it in line_item for it in ['SOFT', 'MACRO', 'PINs'])\
and len(line_item) == 4:
_soft_macro_pin_cnt = int(line_item[3])
elif all(it in line_item for it in ['STDCELLs'])\
and len(line_item) == 2:
_stdcell_cnt = int(line_item[1])
elif all(it in line_item for it in ['MACROs'])\
and len(line_item) == 2:
_macro_cnt = int(line_item[1])
elif all(re.match(r'[0-9FNEWS\.\-]+', it) for it in line_item)\
and len(line_item) == 5:
# [node_index] [x] [y] [orientation] [fixed]
_node_plc[int(line_item[0])] = line_item[1:]
# return as dictionary
info_dict = { "columns":_columns,
"rows":_rows,
"width":_width,
"height":_height,
"area":_area,
"block":_block,
"routes_per_micron_hor":_routes_per_micron_hor,
"routes_per_micron_ver":_routes_per_micron_ver,
"routes_used_by_macros_hor":_routes_used_by_macros_hor,
"routes_used_by_macros_ver":_routes_used_by_macros_ver,
"smoothing_factor":_smoothing_factor,
"overlap_threshold":_overlap_threshold,
"hard_macro_cnt":_hard_macro_cnt,
"hard_macro_pin_cnt":_hard_macro_pin_cnt,
"macro_cnt":_macro_cnt,
"macro_pin_cnt":_macro_pin_cnt,
"port_cnt":_port_cnt,
"soft_macro_cnt":_soft_macro_cnt,
"soft_macro_pin_cnt":_soft_macro_pin_cnt,
"stdcell_cnt":_stdcell_cnt,
"node_plc":_node_plc
}
return info_dict
def restore_placement(self, plc_pth: str, ifInital=True, ifValidate=False, ifReadComment = False, retrieveFD = False):
"""
Read and retrieve .plc file information
NOTE: DO NOT always set self.init_plc because this function is also
used to read final placement file.
ifReadComment: By default, Google's plc_client does not extract
information from .plc comment. This is purely done in
placement_util.py. For purpose of testing, we included this option.
"""
# if plc is an initial placement
if ifInital:
self.init_plc = plc_pth
# recompute cost from new location
self.FLAG_UPDATE_CONGESTION = True
self.FLAG_UPDATE_DENSITY = True
self.FLAG_UPDATE_WIRELENGTH = True
# extracted information from .plc file
info_dict = self.__read_plc(plc_pth)
# validate netlist.pb.txt is on par with .plc
if ifValidate:
try:
assert(self.hard_macro_cnt == info_dict['hard_macro_cnt'])
assert(self.hard_macro_pin_cnt == info_dict['hard_macro_pin_cnt'])
assert(self.soft_macro_cnt == info_dict['soft_macro_cnt'])
assert(self.soft_macro_pin_cnt == info_dict['soft_macro_pin_cnt'])
assert(self.port_cnt == info_dict['port_cnt'])
except AssertionError:
_, _, tb = sys.exc_info()
traceback.print_tb(tb)
tb_info = traceback.extract_tb(tb)
_, line, _, text = tb_info[-1]
print('[ERROR NETLIST/PLC MISMATCH] at line {} in statement {}'\
.format(line, text))
exit(1)
for mod_idx in info_dict['node_plc'].keys():
mod_x = mod_y = mod_orient = mod_ifFixed = None
try:
mod_x = float(info_dict['node_plc'][mod_idx][0])
mod_y = float(info_dict['node_plc'][mod_idx][1])
mod_orient = info_dict['node_plc'][mod_idx][2]
mod_ifFixed = int(info_dict['node_plc'][mod_idx][3])
except Exception as e:
print('[ERROR PLC PARSER] %s' % str(e))
# extract mod object
mod = self.meta_netlist.node[mod_idx]
# if retrieving FD placement result, then only update soft macros
if retrieveFD:
if mod.soft_macro:
mod.coord.x = mod_x
mod.coord.y = mod_y
else:
mod.coord.x = mod_x
mod.coord.y = mod_y
if mod_orient and mod_orient != '-':
if mod_orient == "N":
mod.orientation = mnds.Orientation.N
elif mod_orient == "FN":
mod.orientation = mnds.Orientation.FN
elif mod_orient == "S":
mod.orientation = mnds.Orientation.S
elif mod_orient == "FS":
mod.orientation = mnds.Orientation.FS
elif mod_orient == "E":
mod.orientation = mnds.Orientation.E
elif mod_orient == "FE":
mod.orientation = mnds.Orientation.FE
elif mod_orient == "W":
mod.orientation = mnds.Orientation.W
elif mod_orient == "FW":
mod.orientation = mnds.Orientation.FW
if mod_ifFixed == 0:
self.node_fix[mod_idx] = False
elif mod_ifFixed == 1:
self.node_fix[mod_idx] = True
# set meta information
if ifReadComment:
print("[INFO] Retrieving Meta information from .plc comments")
self.set_canvas_size(info_dict['width'], info_dict['height'])
self.set_placement_grid(info_dict['columns'], info_dict['rows'])
self.set_block_name(info_dict['block'])
self.set_routes_per_micron(
info_dict['routes_per_micron_hor'],
info_dict['routes_per_micron_ver']
)
self.set_macro_routing_allocation(
info_dict['routes_used_by_macros_hor'],
info_dict['routes_used_by_macros_ver']
)
self.set_congestion_smooth_range(info_dict['smoothing_factor'])
self.set_overlap_threshold(info_dict['overlap_threshold'])
cpdef float get_area(self):
"""
Compute Total Module Area
"""
return self.meta_netlist.total_area
cpdef int get_hard_macros_count(self):
return self.hard_macro_cnt
cpdef int get_ports_count(self):
return self.port_cnt
cpdef int get_soft_macros_count(self):
return self.soft_macro_cnt
cpdef int get_hard_macro_pins_count(self):
return self.hard_macro_pin_cnt
cpdef int get_soft_macro_pins_count(self):
return self.soft_macro_pin_cnt
cpdef __get_pin_position(self, int pin_idx):
"""
private function for getting pin location
* PORT = its own position
* HARD MACRO PIN = ref position + offset position
* SOFT MACRO PIN = ref position
"""
try:
assert (self.meta_netlist.node[pin_idx].type in [mnds.Type.MACRO_PIN, mnds.Type.PORT])
except Exception:
print("[ERROR PIN POSITION] Not a MACRO PIN", self.meta_netlist.node[pin_idx].name)
exit(1)
cdef:
float pin_node_x_offset
float pin_node_y_offset
float temp_pin_node_x_offset
float ref_node_x
float ref_node_y
# PORT pin pos is itself
node = self.meta_netlist.node[pin_idx]
if node.type == mnds.Type.PORT:
return node.coord.x, node.coord.y
# Retrieve node that this pin instantiated on
ref_node_idx = node.ref_node_id
# if ref_node_idx == -1:
# print("[ERROR PIN POSITION] Parent Node Not Found.")
# exit(1)
# Parent node
ref_node = self.meta_netlist.node[ref_node_idx]
ref_node_x = ref_node.coord.x
ref_node_y = ref_node.coord.y
# Retrieve current pin node position
pin_node_x_offset = node.offset.x
pin_node_y_offset = node.offset.y
#macro orientation affects offset
if ref_node.orientation in [mnds.Orientation.N, mnds.Orientation.R0, mnds.Orientation.NORMAL]:
pass
elif ref_node.orientation in [mnds.Orientation.FN, mnds.Orientation.MY, mnds.Orientation.FLIP_X]:
pin_node_x_offset = -1.0 * pin_node_x_offset
elif ref_node.orientation in [mnds.Orientation.S, mnds.Orientation.R180, mnds.Orientation.FLIP_XY]:
pin_node_x_offset = -1.0 * pin_node_x_offset
pin_node_y_offset = -1.0 * pin_node_y_offset
elif ref_node.orientation in [mnds.Orientation.FS, mnds.Orientation.MX, mnds.Orientation.FLIP_Y]:
pin_node_y_offset = -1.0 * pin_node_y_offset
elif ref_node.orientation in [mnds.Orientation.E, mnds.Orientation.R270]:
temp_pin_node_x_offset = pin_node_x_offset
pin_node_x_offset = pin_node_y_offset
pin_node_y_offset = -1.0 * temp_pin_node_x_offset
elif ref_node.orientation in [mnds.Orientation.FE, mnds.Orientation.MX90, mnds.Orientation.MYR90]:
temp_pin_node_x_offset = pin_node_x_offset
pin_node_x_offset = -1.0 * pin_node_y_offset
pin_node_y_offset = -1.0 * temp_pin_node_x_offset
elif ref_node.orientation in [mnds.Orientation.W, mnds.Orientation.R90]:
temp_pin_node_x_offset = pin_node_x_offset
pin_node_x_offset = -1.0 * pin_node_y_offset
pin_node_y_offset = temp_pin_node_x_offset
elif ref_node.orientation in [mnds.Orientation.FW, mnds.Orientation.MY90, mnds.Orientation.MXR90]:
temp_pin_node_x_offset = pin_node_x_offset
pin_node_x_offset = pin_node_y_offset
pin_node_y_offset = temp_pin_node_x_offset
# Google's Plc client DOES NOT compute (node_position + pin_offset) when reading input
return (ref_node_x + pin_node_x_offset, ref_node_y + pin_node_y_offset)
cpdef float get_wirelength(self):
"""
Proxy HPWL computation w/ [Experimental] net
"""
total_hpwl = 0.0
for driver_pin_idx in self.nets.keys():
x_coord = []
y_coord = []
# extract net weight
weight_fact = self.meta_netlist.node[driver_pin_idx].weight
x_coord.append(self.__get_pin_position(driver_pin_idx)[0])
y_coord.append(self.__get_pin_position(driver_pin_idx)[1])
# iterate through each sink
for sink_pin_idx in self.nets[driver_pin_idx]:
x_coord.append(self.__get_pin_position(sink_pin_idx)[0])
y_coord.append(self.__get_pin_position(sink_pin_idx)[1])
if x_coord:
total_hpwl += weight_fact * \
(abs(max(x_coord) - min(x_coord)) + \
abs(max(y_coord) - min(y_coord)))
return total_hpwl
cpdef float get_cost(self):
"""
Compute wirelength cost from wirelength
"""
if self.FLAG_UPDATE_WIRELENGTH:
self.FLAG_UPDATE_WIRELENGTH = False
# avoid zero division
if self.net_cnt == 0:
return self.get_wirelength() / ((self.get_canvas_width_height()[0]\
+ self.get_canvas_width_height()[1]))
else:
return self.get_wirelength() / ((self.get_canvas_width_height()[0]\
+ self.get_canvas_width_height()[1]) * self.net_cnt)
def abu(self, xx, n = 0.1):
xxs = sorted(xx, reverse = True)
cnt = math.floor(len(xxs)*n)
if cnt == 0:
return max(xxs)
return sum(xxs[0:cnt])/cnt
cpdef float get_V_congestion_cost(self):
"""
compute average of top 10% of grid cell cong and take half of it
"""
occupied_cells = sorted([gc for gc in self.V_routing_cong if gc != 0.0], reverse=True)
cong_cost = 0.0
# take top 10%
cong_cnt = math.floor(len(self.V_routing_cong) * 0.1)
# if grid cell smaller than 10, take the average over occupied cells
if len(self.V_routing_cong) < 10:
cong_cost = float(sum(occupied_cells) / len(occupied_cells))
return cong_cost
idx = 0
sum_cong = 0
# take top 10%
while idx < cong_cnt and idx < len(occupied_cells):
sum_cong += occupied_cells[idx]
idx += 1
return float(sum_cong / cong_cnt)
cpdef float get_H_congestion_cost(self):
"""
compute average of top 10% of grid cell cong and take half of it
"""
occupied_cells = sorted([gc for gc in self.H_routing_cong if gc != 0.0], reverse=True)
cong_cost = 0.0
# take top 10%
cong_cnt = math.floor(len(self.H_routing_cong) * 0.1)
# if grid cell smaller than 10, take the average over occupied cells
if len(self.H_routing_cong) < 10:
cong_cost = float(sum(occupied_cells) / len(occupied_cells))
return cong_cost
idx = 0
sum_cong = 0
# take top 10%
while idx < cong_cnt and idx < len(occupied_cells):
sum_cong += occupied_cells[idx]
idx += 1
return float(sum_cong / cong_cnt)
cpdef float get_congestion_cost(self):
"""
Return congestion cost based on routing and macro placement
"""
if self.FLAG_UPDATE_CONGESTION:
self.get_routing()
# print(np.concatenate([self.V_routing_cong, self.H_routing_cong]))
return self.abu(np.concatenate([self.V_routing_cong, self.H_routing_cong]), 0.05)
cpdef (int, int) __get_grid_cell_location(self, float x_pos, float y_pos):
"""
private function: for getting grid cell row/col ranging from 0...N
"""
cdef:
int row
int col
self.grid_width = float(self.width/self.grid_col)
self.grid_height = float(self.height/self.grid_row)
row = math.floor(y_pos / self.grid_height)
col = math.floor(x_pos / self.grid_width)
return row, col
cpdef int get_grid_cell_of_node(self, float x_pos, float y_pos):
"""
Returns the node's current location in terms of grid cell index
"""
cdef:
int row
int col
row, col = self.__get_grid_cell_location(x_pos=x_pos, y_pos=y_pos)
return row * self.grid_col + col
cpdef float __overlap_area(self, object bbox_i, object bbox_j, bool return_pos=False):
"""
private function: for computing block overlapping
"""
x_min_max = min(bbox_i.maxx, bbox_j.maxx)
x_max_min = max(bbox_i.minx, bbox_j.minx)
y_min_max = min(bbox_i.maxy, bbox_j.maxy)
y_max_min = max(bbox_i.miny, bbox_j.miny)
x_diff = x_min_max - x_max_min
y_diff = y_min_max - y_max_min
if x_diff >= 0 and y_diff >= 0:
if return_pos:
return x_diff * y_diff, (x_min_max, y_min_max), (x_max_min, y_max_min)
else:
return x_diff * y_diff
return 0
cpdef __overlap_dist(self, bbox_i, bbox_j):
"""
private function: for computing block overlapping
"""
x_diff = min(bbox_i.maxx, bbox_j.maxx) - max(bbox_i.minx, bbox_j.minx)
y_diff = min(bbox_i.maxy, bbox_j.maxy) - max(bbox_i.miny, bbox_j.miny)
if x_diff > 0 and y_diff > 0:
return x_diff, y_diff
return 0, 0
cpdef void __add_module_to_grid_cells(self, float mod_x, float mod_y, float mod_w, float mod_h):
"""
private function: for add module to density grid cells
"""
# Two corners
ur_x = mod_x + (mod_w/2)
ur_y = mod_y + (mod_h/2)
bl_x = mod_x - (mod_w/2)
bl_y = mod_y - (mod_h/2)
# construct block based on current module
module_block = mnds.BoundingBox( minx=mod_x - (mod_w/2),
maxx=mod_x + (mod_w/2),
miny=mod_y - (mod_h/2),
maxy=mod_y + (mod_h/2))
# Only need two corners of a grid cell
ur_row, ur_col = self.__get_grid_cell_location(ur_x, ur_y)
bl_row, bl_col = self.__get_grid_cell_location(bl_x, bl_y)
# check if out of bound
if ur_row >= 0 and ur_col >= 0:
if bl_row < 0:
bl_row = 0
if bl_col < 0:
bl_col = 0
else:
# OOB, skip module
return
if bl_row >= 0 and bl_col >= 0:
if ur_row > self.grid_row - 1:
ur_row = self.grid_row - 1
if ur_col > self.grid_col - 1:
ur_col = self.grid_col - 1
else:
# OOB, skip module
return
for r_i in range(bl_row, ur_row + 1):
for c_i in range(bl_col, ur_col + 1):
# construct block based on current cell row/col
grid_cell_block = mnds.BoundingBox( minx=c_i * self.grid_width,
maxx=(c_i + 1) * self.grid_width,
miny=r_i * self.grid_height,
maxy=(r_i + 1) * self.grid_height)
self.grid_occupied[self.grid_col * r_i + c_i] += \
self.__overlap_area(grid_cell_block, module_block)
cpdef get_grid_cells_density(self):
"""
compute density for all grid cells
"""
# by default grid row/col is 10/10
self.grid_width = float(self.width/self.grid_col)
self.grid_height = float(self.height/self.grid_row)
grid_area = self.grid_width * self.grid_height
self.grid_occupied = [0] * (self.grid_col * self.grid_row)
self.grid_cells = [0] * (self.grid_col * self.grid_row)
for node_idx in self.macro_indices:
# extract module information
node = self.meta_netlist.node[node_idx]
# skipping unplaced module
# if not module.get_placed_flag():
# continue
node_h = node.dimension.height
node_w = node.dimension.width
node_x = node.coord.x
node_y = node.coord.y
self.__add_module_to_grid_cells(
mod_x=node_x,
mod_y=node_y,
mod_h=node_h,
mod_w=node_w
)
for i, gcell in enumerate(self.grid_occupied):
self.grid_cells[i] = gcell / grid_area
return self.grid_cells
cpdef float get_density_cost(self):
"""
compute average of top 10% of grid cell density and take half of it
"""
if self.FLAG_UPDATE_DENSITY:
self.get_grid_cells_density()
self.FLAG_UPDATE_DENSITY=False
occupied_cells = sorted([gc for gc in self.grid_cells if gc != 0.0], reverse=True)
density_cost = 0.0
# take top 10%
density_cnt = math.floor(len(self.grid_cells) * 0.1)
# if grid cell smaller than 10, take the average over occupied cells
if len(self.grid_cells) < 10:
density_cost = float(sum(occupied_cells) / len(occupied_cells))
return 0.5 * density_cost
idx = 0
sum_density = 0
# take top 10%
while idx < density_cnt and idx < len(occupied_cells):
sum_density += occupied_cells[idx]
idx += 1
return 0.5 * float(sum_density / density_cnt)
cpdef bool set_canvas_size(self, float width, float height):
"""
Set canvas size
"""
self.width = width
self.height = height
# Flag updates
self.FLAG_UPDATE_CONGESTION = True
self.FLAG_UPDATE_DENSITY = True
self.FLAG_UPDATE_MACRO_AND_CLUSTERED_PORT_ADJ = True
self.grid_width = float(self.width/self.grid_col)
self.grid_height = float(self.height/self.grid_row)
return True
cpdef get_canvas_width_height(self):
"""
Return canvas size
"""
return self.width, self.height
cpdef bool set_placement_grid(self, grid_col:int, grid_row:int):
"""
Set grid col/row
"""
print("#[PLACEMENT GRID] Col: %d, Row: %d" % (grid_col, grid_row))
self.grid_col = grid_col
self.grid_row = grid_row
# Flag updates
self.FLAG_UPDATE_CONGESTION = True
self.FLAG_UPDATE_DENSITY = True
self.FLAG_UPDATE_MACRO_AND_CLUSTERED_PORT_ADJ = True
self.V_routing_cong = np.zeros(shape=(self.grid_col * self.grid_row))
self.H_routing_cong = np.zeros(shape=(self.grid_col * self.grid_row))
self.V_macro_routing_cong = np.zeros(shape=(self.grid_col * self.grid_row))
self.H_macro_routing_cong = np.zeros(shape=(self.grid_col * self.grid_row))
self.grid_width = float(self.width/self.grid_col)
self.grid_height = float(self.height/self.grid_row)
return True
cpdef get_grid_num_columns_rows(self):
"""
Return grid col/row
"""
return self.grid_col, self.grid_row
cpdef list get_macro_indices(self):
"""
Return all macro indices
"""
return self.macro_indices
cpdef void set_project_name(self, str project_name):
"""
Set Project name
"""
self.project_name = project_name
cpdef str get_project_name(self):
"""
Return Project name
"""
return self.project_name
cpdef void set_block_name(self, str block_name):
"""
Return Block name
"""
self.block_name = block_name
cpdef str get_block_name(self):
"""
Return Block name
"""
return self.block_name
cpdef void set_routes_per_micron(self, float hroutes_per_micron,
float vroutes_per_micron):
"""
Set Routes per Micron
"""
print("#[ROUTES PER MICRON] Hor: %.2f, Ver: %.2f" % (hroutes_per_micron,
vroutes_per_micron))
# Flag updates
self.FLAG_UPDATE_CONGESTION = True
self.hroutes_per_micron = hroutes_per_micron
self.vroutes_per_micron = vroutes_per_micron
cpdef get_routes_per_micron(self):
"""
Return Routes per Micron
"""
return self.hroutes_per_micron, self.vroutes_per_micron
cpdef void set_congestion_smooth_range(self, float smooth_range):
"""
Set congestion smooth range
"""
print("#[CONGESTION SMOOTH RANGE] Smooth Range: %d" % (smooth_range))
# Flag updates
self.FLAG_UPDATE_CONGESTION = True
self.smooth_range = math.floor(smooth_range)
cpdef float get_congestion_smooth_range(self):
"""
Return congestion smooth range
"""
return self.smooth_range
cpdef void set_overlap_threshold(self, float overlap_thres):
"""
Set Overlap Threshold