-
Notifications
You must be signed in to change notification settings - Fork 13
/
replicate_layout.py
1570 lines (1388 loc) · 73 KB
/
replicate_layout.py
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
# -*- coding: utf-8 -*-
# replicate_layout.py
#
# Copyright (C) 2019-2023 Mitja Nemec
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
import pcbnew
from collections import namedtuple
from collections import defaultdict
import os
import logging
import itertools
import math
from difflib import SequenceMatcher
try:
from .remove_duplicates import remove_duplicates
except:
from remove_duplicates import remove_duplicates
Footprint = namedtuple('Footprint', ['ref', 'fp', 'fp_id', 'sheet_id', 'filename'])
logger = logging.getLogger(__name__)
Settings = namedtuple('Settings', ['rep_tracks', 'rep_zones', 'rep_text', 'rep_drawings',
'group_layouts', 'group_footprints', 'group_tracks', 'group_zones', 'group_text', 'group_drawings',
'rep_locked_tracks', 'rep_locked_zones', 'rep_locked_text', 'rep_locked_drawings',
'intersecting', 'group_items', 'group_only', 'locked_fps', 'remove'],
defaults=[True, True, True, True,
False, False, False, False, False, False,
True, True, True, True,
False, False, False, False, False])
def rotate_around_center(coordinates, angle):
""" rotate coordinates for a defined angle in degrees around coordinate center"""
new_x = coordinates[0] * math.cos(2 * math.pi * angle / 360) \
- coordinates[1] * math.sin(2 * math.pi * angle / 360)
new_y = coordinates[0] * math.sin(2 * math.pi * angle / 360) \
+ coordinates[1] * math.cos(2 * math.pi * angle / 360)
return int(new_x), int(new_y)
def rotate_around_point(old_position, point, angle):
""" rotate coordinates for a defined angle in degrees around a point """
# get relative position to point
rel_x = old_position[0] - point[0]
rel_y = old_position[1] - point[1]
# rotate around
new_rel_x, new_rel_y = rotate_around_center((rel_x, rel_y), angle)
# get absolute position
new_position = (new_rel_x + point[0], new_rel_y + point[1])
return new_position
def get_index_of_tuple(list_of_tuples, index, value):
for pos, t in enumerate(list_of_tuples):
if t[index] == value:
return pos
def update_progress(stage, percentage, message=None):
if message is not None:
print(message)
print(percentage)
def flipped_angle(angle):
if angle > 0:
return 180 - angle
else:
return -180 - angle
class Replicator:
def __init__(self, board, src_anchor_fp_ref, update_func=update_progress):
self.board = board
self.stage = 1
self.max_stages = 0
self.update_progress = update_func
self.level = None
self.settings = Settings
self.src_anchor_fp = None
self.src_anchor_fp_group = None
self.replicate_locked_footprints = None
self.src_sheet = None
self.dst_sheets = []
self.dst_groups = []
self.src_footprints = []
self.other_footprints = []
self.src_bounding_box = None
self.src_tracks = []
self.src_zones = []
self.src_text = []
self.src_drawings = []
self.connectivity_issues = set()
self.pcb_filename = os.path.abspath(board.GetFileName())
self.sch_filename = self.pcb_filename.replace(".kicad_pcb", ".kicad_sch")
self.project_folder = os.path.dirname(self.pcb_filename)
# construct a list of footprints with all pertinent data
logger.info('getting a list of all footprints on board')
footprints = board.GetFootprints()
self.footprints = []
# get dict_of_sheets from layout data only (through footprint Sheetfile and Sheetname properties)
self.dict_of_sheets = {}
unique_sheet_ids = set()
for fp in footprints:
# construct a set of unique sheets from footprint properties
path = fp.GetPath().AsString().upper().replace('00000000-0000-0000-0000-0000', '').split("/")
sheet_path = path[0:-1]
for x in sheet_path:
unique_sheet_ids.add(x)
sheet_id = self.get_sheet_id(fp)
try:
sheet_file = fp.GetSheetfile()
sheet_name = fp.GetSheetname()
except KeyError:
logger.info("Footprint " + fp.GetReference() +
" does not have Sheetfile property, it will not be replicated."
" Most likely it is only in layout")
continue
# footprint is in the schematics and has Sheetfile property
if sheet_file and sheet_id:
self.dict_of_sheets[sheet_id] = [sheet_name, sheet_file]
# footprint is in the schematics but has empty Sheetfile properties
elif sheet_id:
logger.info("Footprint " + fp.GetReference() + " has empty Sheetfile property")
raise LookupError("Footprint " + str(
fp.GetReference()) + " has empty Sheetfile and Sheetname properties. "
"You need to update the layout from schematics")
# footprint is on root level
else:
logger.debug("Footprint " + fp.GetReference() + " on root level")
continue
# catch corner cases with nested hierarchy, where some hierarchical pages don't have any footprints
unique_sheet_ids.remove("")
if len(unique_sheet_ids) > len(self.dict_of_sheets):
# open root schematics file and parse for other schematics files
# This might be prone to errors regarding path discovery
# thus it is used only in corner cases
schematic_found = {}
self.parse_schematic_files(self.sch_filename, schematic_found)
self.dict_of_sheets = schematic_found
# construct a list of all the footprints
for fp in footprints:
try:
sheet_file = fp.GetSheetfile()
sheet_name = fp.GetSheetname()
fp_tuple = Footprint(fp=fp,
fp_id=self.get_footprint_id(fp),
sheet_id=self.get_sheet_path(fp)[0],
filename=self.get_sheet_path(fp)[1],
ref=fp.GetReference())
self.footprints.append(fp_tuple)
except KeyError:
pass
# find anchor footprint and it's group
self.src_anchor_fp = self.get_fp_by_ref(src_anchor_fp_ref)
if self.src_anchor_fp.fp.GetParentGroup():
self.src_anchor_fp_group = self.src_anchor_fp.fp.GetParentGroup().GetName()
else:
self.src_anchor_fp_group = None
# TODO check if there is any other footprint with same ID as anchor footprint
# get net-dict
# you get the netcode by self.netdict.GetNetItem("netname")
self.netdict = self.board.GetNetInfo()
def parse_schematic_files(self, filename, dict_of_sheets):
filename_dir = os.path.dirname(filename)
with open(filename, encoding='utf-8') as f:
contents = f.read()
brace_indexes = []
quote_indexes = []
brace_level = []
sheet_definitions = []
new_lines = []
brace_lvl = 0
in_quote = 0
# get the nesting levels at index
# TODO this will fail if there is a single bracket in a sheetname
for idx in range(len(contents) - 20):
if contents[idx] == "\"":
quote_indexes.append(idx)
if in_quote:
in_quote = False
else:
in_quote = True
# TODO might want to ignore braces within quotes (in_quote is True)
if contents[idx] == "(":
brace_lvl = brace_lvl + 1
brace_level.append(brace_lvl)
brace_indexes.append(idx)
if contents[idx] == ")":
brace_lvl = brace_lvl - 1
brace_level.append(brace_lvl)
brace_indexes.append(idx)
if contents[idx] == "\n":
new_lines.append(idx)
a = contents[idx:idx + 20]
if a.startswith("(sheet\n") or a.startswith("(sheet "):
sheet_definitions.append(idx)
start_idx = sheet_definitions
end_idx = sheet_definitions[1:]
end_idx.append(len(contents))
braces = list(zip(brace_indexes, brace_level))
# parse individual sheet definitions (if any)
for start, end in zip(start_idx, end_idx):
def next_bigger(l, v):
for m in l:
if m > v:
return m
uuid_loc = contents[start:end].find('(uuid') + start
uuid_loc_end = next_bigger(new_lines, uuid_loc)
uuid_complete_string = contents[uuid_loc:uuid_loc_end]
uuid = uuid_complete_string.strip("(uuid").strip(")").replace("\"", '').upper().lstrip()
v8encoding = contents[start:end].find('(property "Sheetname\"')
v7encoding = contents[start:end].find('(property "Sheet name\"')
if v8encoding != -1:
offset = v8encoding
elif v7encoding != -1:
offset = v7encoding
else:
logger.info(f'Did not found sheetname properties in the schematic file '
f'in {filename} line:{str(i)}')
raise LookupError(f'Did not found sheetname properties in the schematic file '
f'in {filename} line:{str(i)}. Unsupported schematics file format')
sheetname_loc = offset + start
sheetname_loc_end = next_bigger(new_lines, sheetname_loc)
sheetname_complete_string = contents[sheetname_loc:sheetname_loc_end]
sheetname = sheetname_complete_string.strip("(property").split('"')[1::2][1]
v8encoding = contents[start:end].find('(property "Sheetfile\"')
v7encoding = contents[start:end].find('(property "Sheet file\"')
if v8encoding != -1:
offset = v8encoding
elif v7encoding != -1:
offset = v7encoding
else:
logger.info(f'Did not found sheetfile properties in the schematic file '
f'in {filename}.')
raise LookupError(f'Did not found sheetfile properties in the schematic file '
f'in {filename}. Unsupported schematics file format')
sheetfile_loc = offset + start
sheetfile_loc_end = next_bigger(new_lines, sheetfile_loc)
sheetfile_complete_string = contents[sheetfile_loc:sheetfile_loc_end]
sheetfile = sheetfile_complete_string.strip("(property").split('"')[1::2][1]
sheetfilepath = os.path.join(filename_dir, sheetfile)
dict_of_sheets[uuid] = [sheetname, sheetfile]
# test if newfound file can be opened
if not os.path.exists(sheetfilepath):
raise LookupError(f'File {sheetfilepath} does not exists. This is either due to error in parsing'
f' schematics files, missing schematics file or an error within the schematics')
# open a newfound file and look for nested sheets
self.parse_schematic_files(sheetfilepath, dict_of_sheets)
pass
return
def replicate_layout(self, src_anchor_fp, level, dst_sheets,
settings, rm_duplicates):
logger.info("Starting replication of sheets: " + repr(dst_sheets)
+ "\non level: " + repr(level)
+ "\nwith tracks=" + repr(settings.rep_tracks) + ", zone=" + repr(settings.rep_zones)
+ ", text=" + repr(settings.rep_text) + ", text=" + repr(settings.rep_drawings)
+ ", intersecting=" + repr(settings.intersecting) + ", remove=" + repr(settings.remove)
+ ", locked footprints=" + repr(settings.locked_fps) + ", group_only=" + repr(settings.group_only))
self.level = level
self.src_anchor_fp = src_anchor_fp
self.dst_sheets = dst_sheets
self.replicate_locked_footprints = settings.locked_fps
self.src_sheet = level
if settings.remove:
self.max_stages = 2
else:
self.max_stages = 0
if settings.rep_tracks:
self.max_stages = self.max_stages + 1
if settings.rep_zones:
self.max_stages = self.max_stages + 1
if settings.rep_text:
self.max_stages = self.max_stages + 1
if settings.rep_drawings:
self.max_stages = self.max_stages + 1
if rm_duplicates:
self.max_stages = self.max_stages + 1
self.update_progress(self.stage, 0.0, "Preparing for replication")
self.prepare_for_replication(level, settings)
if settings.remove:
logger.info("Removing tracks and zones, before footprint placement")
self.stage = 2
self.update_progress(self.stage, 0.0, "Removing zones and tracks")
self.remove_zones_tracks(settings.intersecting)
self.stage = 3
self.update_progress(self.stage, 0.0, "Replicating footprints")
self.replicate_footprints(settings)
if settings.remove:
logger.info("Removing tracks and zones, after footprint placement")
self.stage = 4
self.update_progress(self.stage, 0.0, "Removing zones and tracks")
self.remove_zones_tracks(settings.intersecting)
if settings.rep_tracks:
self.stage = 5
self.update_progress(self.stage, 0.0, "Replicating tracks")
self.replicate_tracks(settings)
if settings.rep_zones:
self.stage = 6
self.update_progress(self.stage, 0.0, "Replicating zones")
self.replicate_zones(settings)
if settings.rep_text:
self.stage = 7
self.update_progress(self.stage, 0.0, "Replicating text")
self.replicate_text(settings)
if settings.rep_drawings:
self.stage = 8
self.update_progress(self.stage, 0.0, "Replicating drawings")
self.replicate_drawings(settings)
if rm_duplicates:
self.stage = 9
self.update_progress(self.stage, 0.0, "Removing duplicates")
self.removing_duplicates()
# finally at the end refill the zones
filler = pcbnew.ZONE_FILLER(self.board)
filler.Fill(self.board.Zones())
def prepare_for_replication(self, level, settings):
# get a list of source footprints for replication
logger.info("Getting the list of source footprints")
self.update_progress(self.stage, 0 / 8, None)
# if needed filter them by group
anchor_sheet_footprints = self.get_footprints_on_sheet(level)
self.src_bounding_box = self.get_footprints_bounding_box(anchor_sheet_footprints)
self.src_footprints = self.get_footprints_for_replication(level, self.src_bounding_box, settings)
excluded_footprints = [fp for fp in anchor_sheet_footprints if fp not in self.src_footprints]
# get the rest of the footprints
logger.info("Getting the list of all the remaining footprints")
self.update_progress(self.stage, 1 / 6, None)
self.other_footprints = self.get_footprints_not_on_sheet(level)
self.other_footprints.extend(excluded_footprints)
# TODO we might need to recalculate bounding box - if so, this has to be ported to highlighting code
# get source tracks
logger.info("Getting source tracks")
self.update_progress(self.stage, 2 / 6, None)
self.src_tracks = self.get_tracks_for_replication(level, self.src_bounding_box, settings)
# get source zones
logger.info("Getting source zones")
self.update_progress(self.stage, 3 / 6, None)
self.src_zones = self.get_zones_for_replication(level, self.src_bounding_box, settings)
# get source text items
logger.info("Getting source text items")
self.update_progress(self.stage, 4 / 6, None)
self.src_text = self.get_text_for_replication(self.src_bounding_box, settings)
# get source drawings
logger.info("Getting source drawing items")
self.update_progress(self.stage, 5 / 6, None)
self.src_drawings = self.get_drawings_for_replication(level, self.src_bounding_box, settings)
# get all the existing groups
groups = self.board.Groups()
g_names = []
for g in groups:
g_names.append(g.GetName())
# create groups for each destination layout if selected
if settings.group_layouts:
for sheet in self.dst_sheets:
dst_group_name = "Replicated Group {}".format(sheet)
# check if this group already exists
# TODO this should no be an issue as existing group can/should be used for deletion of items
if dst_group_name in g_names:
raise LookupError(f"Destination group {dst_group_name} already exists")
dst_group = pcbnew.PCB_GROUP(None)
dst_group.SetName(dst_group_name)
self.board.Add(dst_group)
# store destination lauouts' groups
self.dst_groups.append(dst_group)
# check if any destination footprints are already members of some groups
for sheet in self.dst_sheets:
dst_sheet_fps = self.get_footprints_on_sheet(sheet)
for fp in dst_sheet_fps:
fp_group = fp.fp.GetParentGroup()
dst_group = "Replicated Group {}".format(sheet)
if (fp_group is not None) and (fp_group != dst_group):
raise LookupError(f"Destination footprint {fp} is a member of a different group ({fp_group}). "
f"All destination plugin have either have to be members of destination group ({dst_group})"
f" or no group at all.")
@staticmethod
def get_footprint_id(footprint):
path = footprint.GetPath().AsString().upper().replace('00000000-0000-0000-0000-0000', '').split("/")
if len(path) != 1:
fp_id = path[-1]
# if path is empty, then footprint is not part of schematics
else:
fp_id = None
return fp_id
@staticmethod
def get_sheet_id(footprint):
path = footprint.GetPath().AsString().upper().replace('00000000-0000-0000-0000-0000', '').split("/")
if len(path) != 1:
sheet_id = path[-2]
# if path is empty, then footprint is not part of schematics
else:
sheet_id = None
return sheet_id
def get_sheet_path(self, footprint):
""" get sheet id """
path = footprint.GetPath().AsString().upper().replace('00000000-0000-0000-0000-0000', '').split("/")
if len(path) != 1:
sheet_path = path[0:-1]
sheet_names = [self.dict_of_sheets[x][0] for x in sheet_path if x in self.dict_of_sheets]
sheet_files = [self.dict_of_sheets[x][1] for x in sheet_path if x in self.dict_of_sheets]
sheet_path = [sheet_names, sheet_files]
else:
sheet_path = ["", ""]
return sheet_path
def get_fp_by_ref(self, ref):
for fp in self.footprints:
if fp.ref == ref:
return fp
return None
def get_list_of_footprints_with_same_id(self, fp_id):
footprints_with_same_id = []
for fp in self.footprints:
if fp.fp_id == fp_id:
footprints_with_same_id.append(fp)
return footprints_with_same_id
def get_sheets_to_replicate(self, reference_footprint, level):
sheet_id = reference_footprint.sheet_id
sheet_file = reference_footprint.filename
# find level_id
level_file = sheet_file[sheet_id.index(level)]
logger.info('constructing a list of sheets suitable for replication on level:'
+ repr(level) + ", file:" + repr(level_file))
# construct complete hierarchy path up to the level of reference footprint
sheet_id_up_to_level = []
for i in range(len(sheet_id)):
sheet_id_up_to_level.append(sheet_id[i])
if sheet_id[i] == level:
break
# get all footprints with same ID
footprints_with_same_id = self.get_list_of_footprints_with_same_id(reference_footprint.fp_id)
# if hierarchy is deeper, match only the sheets with same hierarchy from root to -1
sheets_on_same_level = []
# go through all the footprints
for fp in footprints_with_same_id:
# if the footprint is on selected level, it's sheet is added to the list of sheets on this level
if level_file in fp.filename:
sheet_id_list = []
# create a hierarchy path only up to the level
for i in range(len(fp.filename)):
sheet_id_list.append(fp.sheet_id[i])
if fp.filename[i] == level_file:
break
sheets_on_same_level.append(sheet_id_list)
# remove duplicates
sheets_on_same_level.sort()
sheets_on_same_level = list(k for k, _ in itertools.groupby(sheets_on_same_level))
# remove the sheet path for reference footprint
for sheet in sheets_on_same_level:
if sheet == sheet_id_up_to_level:
index = sheets_on_same_level.index(sheet)
del sheets_on_same_level[index]
break
logger.info("suitable sheets are:" + repr(sheets_on_same_level))
return sheets_on_same_level
def get_footprints_on_sheet(self, level):
footprints_on_sheet = []
level_depth = len(level)
for fp in self.footprints:
if level == fp.sheet_id[0:level_depth]:
footprints_on_sheet.append(fp)
return footprints_on_sheet
@staticmethod
def filter_items_by_group(items, group):
items_in_group = []
for item in items:
item_group = item.GetParentGroup()
if item_group and group == item_group.GetName():
items_in_group.append(item)
return items_in_group
@staticmethod
def filter_footprints_by_group(footprints, group):
items_in_group = []
for fp in footprints:
fp_group = fp.fp.GetParentGroup()
if hasattr(fp_group, 'GetName'):
if group and fp_group.GetName():
items_in_group.append(fp)
return items_in_group
def get_footprints_not_on_sheet(self, level):
footprints_not_on_sheet = []
level_depth = len(level)
for fp in self.footprints:
if level != fp.sheet_id[0:level_depth]:
footprints_not_on_sheet.append(fp)
return footprints_not_on_sheet
@staticmethod
def get_nets_from_footprints(footprints):
# go through all footprints and their pads and get the nets they are connected to
nets = []
for fp in footprints:
# get their pads
pads = fp.fp.Pads()
# get net
for pad in pads:
nets.append(pad.GetNetname())
# remove duplicates
nets_clean = []
for i in nets:
if i not in nets_clean:
nets_clean.append(i)
return nets_clean
def get_local_nets(self, src_footprints, other_footprints):
# get nets other footprints are connected to
other_nets = self.get_nets_from_footprints(other_footprints)
# get nets only source footprints are connected to
src_nets = self.get_nets_from_footprints(src_footprints)
src_local_nets = []
for net in src_nets:
if net not in other_nets:
src_local_nets.append(net)
return src_local_nets
@staticmethod
def get_footprints_bounding_box(footprints):
# get first footprint bounding box
bounding_box = footprints[0].fp.GetBoundingBox(False, False)
top = bounding_box.GetTop()
bottom = bounding_box.GetBottom()
left = bounding_box.GetLeft()
right = bounding_box.GetRight()
# iterate through the rest of the footprints and resize bounding box accordingly
for fp in footprints:
fp_box = fp.fp.GetBoundingBox(False, False)
top = min(top, fp_box.GetTop())
bottom = max(bottom, fp_box.GetBottom())
left = min(left, fp_box.GetLeft())
right = max(right, fp_box.GetRight())
position = pcbnew.VECTOR2I(left, top)
size = pcbnew.VECTOR2I(right - left, bottom - top)
bounding_box = pcbnew.BOX2I(position, size)
return bounding_box
def get_tracks(self, bounding_box, containing, exclusive_nets=None):
# get_all tracks
if exclusive_nets is None:
exclusive_nets = []
all_tracks = self.board.GetTracks()
tracks = []
# keep only tracks that are within our bounding box
for track in all_tracks:
track_bb = track.GetBoundingBox()
# if track is contained or intersecting the bounding box
if (containing and bounding_box.Contains(track_bb)) or \
(not containing and bounding_box.Intersects(track_bb)):
tracks.append(track)
# even if track is not within the bounding box, but is on the completely local net
else:
# check if it on a local net
if track.GetNetname() in exclusive_nets:
# and add it to the
tracks.append(track)
return tracks
def get_zones(self, bounding_box, containing, exclusive_nets=None):
if exclusive_nets is None:
exclusive_nets = []
# get all zones
all_zones = []
for zone_id in range(self.board.GetAreaCount()):
all_zones.append(self.board.GetArea(zone_id))
# find all zones which are within the bounding box
zones = []
for zone in all_zones:
zone_bb = zone.GetBoundingBox()
if (containing and bounding_box.Contains(zone_bb)) or \
(not containing and bounding_box.Intersects(zone_bb)):
zones.append(zone)
# even if track is not within the bounding box, but is on the completely local net
else:
if zone.GetNetname() in exclusive_nets:
# and add it to the
zones.append(zone)
return zones
def get_text_items(self, bounding_box, containing, outside=False):
# get all text objects in bounding box
all_text = []
for drawing in self.board.GetDrawings():
if not isinstance(drawing, pcbnew.PCB_TEXT):
continue
if not outside:
text_bb = drawing.GetBoundingBox()
if containing:
if bounding_box.Contains(text_bb):
all_text.append(drawing)
else:
if bounding_box.Intersects(text_bb):
all_text.append(drawing)
else:
text_bb = drawing.GetBoundingBox()
if not bounding_box.Contains(text_bb):
all_text.append(drawing)
return all_text
def get_drawings(self, bounding_box, containing, outside=False):
# get all drawings in source bounding box
all_drawings = []
for drawing in self.board.GetDrawings():
if isinstance(drawing, pcbnew.PCB_TEXT):
# text items are handled separately
continue
if not outside:
dwg_bb = drawing.GetBoundingBox()
if containing:
if bounding_box.Contains(dwg_bb):
all_drawings.append(drawing)
else:
if bounding_box.Intersects(dwg_bb):
all_drawings.append(drawing)
else:
dwg_bb = drawing.GetBoundingBox()
if not bounding_box.Contains(dwg_bb):
all_drawings.append(drawing)
return all_drawings
@staticmethod
def get_footprint_text_items(footprint):
""" get all text item belonging to a footprint """
list_of_items = [footprint.fp.Reference(), footprint.fp.Value()]
footprint_items = footprint.fp.GraphicalItems()
for item in footprint_items:
if type(item) is pcbnew.PCB_TEXT:
list_of_items.append(item)
return list_of_items
def get_sheet_anchor_footprint(self, sheet):
# get all footprints on this sheet
sheet_footprints = self.get_footprints_on_sheet(sheet)
sheet_anchor_fp = self.match_fp_in_list(self.src_anchor_fp, sheet_footprints)
return sheet_anchor_fp
def get_net_pairs(self, sheet):
""" find all net pairs between source sheet and current sheet"""
# find all footprints, pads and nets on this sheet
sheet_footprints = self.get_footprints_on_sheet(sheet)
# find all net pairs via same footprint pads,
# first find footprint matches
fp_matches = defaultdict(list)
for d_fp in sheet_footprints:
for s_fp in self.src_footprints:
if d_fp.fp_id == s_fp.fp_id:
fp_matches[s_fp.ref].append((s_fp, d_fp))
# from matching footprints find closest match if needed
fp_pairs = defaultdict(list)
for key, value in fp_matches.items():
matches = len(value)
if matches == 0:
raise LookupError("Could not find at least one matching footprint for: " + key +
".\nPlease make sure that schematics and layout are in sync.")
if matches == 1:
fp_pairs[key] = value[0]
# if more than one match, get the most likely one
# this is when replicating a sheet which consist of two or more identical subsheets (multiple hierachy)
# the closest match is the one where most of the sheet_id matches
if matches > 1:
match_len = []
for match in value:
match_len.append(len(set(match[0].sheet_id) & set(match[1].sheet_id)))
index = match_len.index(max(match_len))
fp_pairs[key] = value[index]
# For each pad pair get the net pair, and check if it makes sense
connectivity_issues = []
net_pairs = []
for fp_ref, fp_pair in fp_pairs.items():
src_fp_pads = fp_pair[0].fp.Pads()
dst_fp_pads = fp_pair[1].fp.Pads()
# create a list of pads names and pads
s_pads = []
d_pads = []
for pad in src_fp_pads:
s_pads.append((pad.GetName(), pad))
for pad in dst_fp_pads:
d_pads.append((pad.GetName(), pad))
# sort by pad names
s_pads.sort(key=lambda tup: tup[0])
d_pads.sort(key=lambda tup: tup[0])
# add to dict
fp_net_pairs = dict(zip([x[0] for x in d_pads] ,list(zip([x[1].GetNetname() for x in s_pads], [x[1].GetNetname() for x in d_pads]))))
# go through all net pairs
for pad_nr, net_pair in fp_net_pairs.items():
# if net names match
if net_pair[0] == net_pair[1]:
net_pairs.append(net_pair)
continue
# get netname depth
src_net_path = net_pair[0].split("/")
dst_net_path = net_pair[1].split("/")
src_net_depth = len(src_net_path)
dst_net_depth = len(dst_net_path)
net_delta_depth = src_net_depth-dst_net_depth
src_fp_depth = len(fp_pair[0].sheet_id)
dst_fp_depth = len(fp_pair[1].sheet_id)
fp_delta_depth = src_fp_depth - dst_fp_depth
# if both nets are local, they should match
if (src_net_depth == 1) and (dst_net_depth == 1):
net_pairs.append(net_pair)
continue
# otherwise just look at the net name similarity. And if they are pretty similar be content
match_level = self.find_match_level(src_net_path, dst_net_path)
if match_level > 0.8:
net_pairs.append(net_pair)
continue
# if I didn't find proper pair, append it anyway but addit to the list for reporting a warnning
net_pairs.append(net_pair)
logger.warning(f"Significant difference between src net: {src_net_path} and dst net: {dst_net_path}, "
f"with src_net_depth={src_net_depth}, dst_net_depth={dst_net_depth}, "
f"src_fp_depth={src_fp_depth}, dst_fp_depth={dst_fp_depth}, match level {match_level:.2f}")
connectivity_issues.append((fp_pair[1].ref, pad_nr))
if connectivity_issues:
"""
report_string = ""
for item in connectivity_issues:
report_string = report_string + f"Footprint {item[0]}, pad {item[1]}\n"
logger.info(f"Looks like the design has an exotic connectivity that is not supported by the plugin\n"
f"Make sure that you check the connectivity around:\n" + report_string)
"""
self.connectivity_issues.update(connectivity_issues)
# remove duplicates
net_pairs_clean = list(set(net_pairs))
logger.info("Net pairs for sheet " + repr(sheet) + " :" + repr(net_pairs_clean))
return net_pairs_clean
@staticmethod
def find_match_level(netname_a, netname_b):
len_nets_1 = len(netname_a)
len_nets_2 = len(netname_b)
# if both lengths are the same
if len_nets_1 == len_nets_2:
good_match_count = 0
for i in range(len_nets_1):
for j in range(len_nets_2):
a = netname_a[i]
b = netname_b[j]
match_ratio = SequenceMatcher(a=netname_a[i], b=netname_b[j]).ratio()
good_match_count = good_match_count + match_ratio
# normalize for the lenght
return good_match_count / len_nets_1
# otherwise match all of the shortest ones with all of the longest ones
else:
good_match_count = 0
if len_nets_1 < len_nets_2:
for i in range(len_nets_1):
for j in range(len_nets_2):
a = netname_a[i]
b = netname_b[j]
match_ratio = SequenceMatcher(a=netname_a[i], b=netname_b[j]).ratio()
good_match_count = good_match_count + match_ratio
return good_match_count / len_nets_1
else:
for i in range(len_nets_2):
for j in range(len_nets_1):
a = netname_b[i]
b = netname_a[j]
match_ratio = SequenceMatcher(a=netname_b[i], b=netname_a[j]).ratio()
good_match_count = good_match_count + match_ratio
return good_match_count / len_nets_2
@staticmethod
def match_fp_in_list(footprint, fp_list):
# find proper match in source footprints
list_of_possible_dst_footprints = []
for d_fp in fp_list:
if d_fp.fp_id == footprint.fp_id:
list_of_possible_dst_footprints.append(d_fp)
# if there is more than one possible anchor, select the correct one
if len(list_of_possible_dst_footprints) == 1:
dst_fp = list_of_possible_dst_footprints[0]
else:
list_of_matches = []
for fp in list_of_possible_dst_footprints:
index = list_of_possible_dst_footprints.index(fp)
matches = 0
for item in footprint.sheet_id:
if item in fp.sheet_id:
matches = matches + 1
list_of_matches.append((index, matches))
# check if list is empty, if it is, then it is highly likely that schematics and pcb are not in sync
if not list_of_matches:
raise LookupError("Can not find destination footprint for source footprint: " + repr(src_fp.ref)
+ "\n" + "Most likely, schematics and PCB are not in sync")
# select the one with most matches
index, _ = max(list_of_matches, key=lambda item: item[1])
dst_fp = list_of_possible_dst_footprints[index]
return dst_fp
def replicate_footprints(self, settings):
logger.info("Replicating footprints")
nr_sheets = len(self.dst_sheets)
for st_index in range(nr_sheets):
sheet = self.dst_sheets[st_index]
progress = st_index / nr_sheets
self.update_progress(self.stage, progress, None)
logger.info("Replicating footprints on sheet " + repr(sheet))
# get anchor footprint
dst_anchor_fp = self.get_sheet_anchor_footprint(sheet)
dst_anchor_fp_angle = dst_anchor_fp.fp.GetOrientationDegrees()
dst_anchor_fp_position = dst_anchor_fp.fp.GetPosition()
src_anchor_fp_angle = self.src_anchor_fp.fp.GetOrientationDegrees()
anchor_delta_angle = src_anchor_fp_angle - dst_anchor_fp_angle
# go through all footprints
src_footprints = self.src_footprints
dst_footprints = self.get_footprints_on_sheet(sheet)
nr_footprints = len(src_footprints)
for fp_index in range(nr_footprints):
src_fp = src_footprints[fp_index]
progress = progress + (1 / nr_sheets) * (1 / nr_footprints)
self.update_progress(self.stage, progress, None)
# find proper match in source footprints
dst_fp = self.match_fp_in_list(src_fp, dst_footprints)
# skip locked footprints
if dst_fp.fp.IsLocked() is True and self.replicate_locked_footprints is False:
continue
# get footprint to clone position
src_fp_orientation = src_fp.fp.GetOrientationDegrees()
src_fp_pos = src_fp.fp.GetPosition()
# get relative position with respect to source anchor
src_anchor_pos = self.src_anchor_fp.fp.GetPosition()
src_fp_flipped = src_fp.fp.IsFlipped()
src_fp_delta_pos = src_fp_pos - src_anchor_pos
# new orientation is simple
new_orientation = src_fp_orientation - anchor_delta_angle
old_pos = src_fp_delta_pos + dst_anchor_fp_position
new_pos = rotate_around_point(old_pos, dst_anchor_fp_position, anchor_delta_angle)
# convert to tuple of integers
new_pos = [int(x) for x in new_pos]
dst_fp_pos = pcbnew.VECTOR2I(*new_pos)
# place current footprint - only if current footprint is not also the anchor
if dst_fp.ref != dst_anchor_fp.ref:
dst_fp.fp.SetPosition(dst_fp_pos)
if dst_fp.fp.IsFlipped() != src_fp_flipped:
dst_fp.fp.Flip(dst_fp.fp.GetPosition(), False)
dst_fp.fp.SetOrientationDegrees(new_orientation)
# Copy local settings.
dst_fp.fp.SetLocalClearance(src_fp.fp.GetLocalClearance())
dst_fp.fp.SetLocalSolderMaskMargin(src_fp.fp.GetLocalSolderMaskMargin())
dst_fp.fp.SetLocalSolderPasteMargin(src_fp.fp.GetLocalSolderPasteMargin())
dst_fp.fp.SetLocalSolderPasteMarginRatio(src_fp.fp.GetLocalSolderPasteMarginRatio())
dst_fp.fp.SetZoneConnection(src_fp.fp.GetZoneConnection())
# add footprints to corresponding layout groups if selected
# and if footprint is not already member of this group
if settings.group_footprints and dst_fp.fp.GetParentGroup() != self.dst_groups[st_index].GetName():
self.dst_groups[st_index].AddItem(dst_fp.fp)
# flip if dst anchor is flipped in regard to src anchor
if self.src_anchor_fp.fp.IsFlipped() != dst_anchor_fp.fp.IsFlipped():
# ignore anchor fp
if dst_anchor_fp != dst_fp:
dst_fp.fp.Flip(dst_anchor_fp_position, False)
#
src_fp_rel_pos = src_anchor_pos - src_fp_pos
delta_angle = dst_anchor_fp_angle + src_anchor_fp_angle
dst_fp_rel_pos_rot = rotate_around_center([-src_fp_rel_pos[0], src_fp_rel_pos[1]],
-delta_angle)
dst_fp_pos = dst_anchor_fp_position + pcbnew.VECTOR2I(dst_fp_rel_pos_rot[0],
dst_fp_rel_pos_rot[1])
# also need to change the angle
dst_fp.fp.SetPosition(dst_fp_pos)
src_fp_flipped_orientation = flipped_angle(src_fp_orientation)
flipped_delta = flipped_angle(src_anchor_fp_angle) - dst_anchor_fp_angle
new_orientation = src_fp_flipped_orientation - flipped_delta
dst_fp.fp.SetOrientationDegrees(new_orientation)
dst_fp_orientation = dst_fp.fp.GetOrientationDegrees()
dst_fp_flipped = dst_fp.fp.IsFlipped()
# replicate also text layout - also for anchor footprint. I am counting that the user is lazy and will
# just position the destination anchors and will not edit them
# get footprint text
src_text_items = self.get_footprint_text_items(src_fp)
dst_text_items = self.get_footprint_text_items(dst_fp)
# sort text items, as by default the order is random
src_fp_text_items = sorted(src_text_items,
key=lambda element: (element.GetLayer(), element.GetText()))
dst_fp_text_items = sorted(dst_text_items,
key=lambda element: (element.GetLayer(), element.GetText()))
# check if both footprints (source and the one for replication) have the same number of text items
if len(src_fp_text_items) != len(dst_fp_text_items):
raise LookupError(
"Source footprint: " + src_fp.ref + " has different number of text items (" + repr(
len(src_fp_text_items))
+ ")\nthan footprint for replication: " + dst_fp.ref + " (" + repr(
len(dst_fp_text_items)) + ")")
# replicate each text item
src_text: pcbnew.PCB_TEXT
dst_text: pcbnew.PCB_TEXT
for src_text in src_fp_text_items:
txt_index = src_fp_text_items.index(src_text)
src_txt_pos = src_text.GetPosition()
src_txt_rel_pos = src_txt_pos - src_fp_pos
src_txt_orientation = src_text.GetTextAngleDegrees()
delta_angle = dst_fp_orientation - src_fp_orientation
dst_text = dst_fp_text_items[txt_index]
logger.info("Src text UUid:" + src_text.m_Uuid.AsString())
logger.info("Dst text UUid:" + dst_text.m_Uuid.AsString())
dst_text.SetLayer(src_text.GetLayer())
# set text parameters
dst_text.SetAttributes(src_text.GetAttributes())
# properly set position
if src_fp_flipped != dst_fp_flipped:
dst_text.Flip(dst_anchor_fp_position, False)
dst_txt_rel_pos = [-src_txt_rel_pos[0], src_txt_rel_pos[1]]
delta_angle = flipped_angle(src_anchor_fp_angle) - dst_anchor_fp_angle
dst_txt_rel_pos_rot = rotate_around_center(dst_txt_rel_pos, delta_angle)
dst_txt_pos = dst_fp_pos + pcbnew.VECTOR2I(dst_txt_rel_pos_rot[0], dst_txt_rel_pos_rot[1])
dst_text.SetPosition(dst_txt_pos)
dst_text.SetTextAngleDegrees(-src_txt_orientation - anchor_delta_angle)
dst_text.SetMirrored(not src_text.IsMirrored())