KiCad PCB EDA Suite
Loading...
Searching...
No Matches
topo_match.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#include <cstdio>
21#include <cstdlib>
22#include <cmath>
23#include <string>
24#include <vector>
25#include <algorithm>
26#include <cassert>
27#include <future>
28#include <map>
29#include <set>
30#include <unordered_map>
31#include <unordered_set>
32
33#include <thread_pool.h>
34#include <cctype>
35
36#include <core/profile.h>
37#include <pad.h>
38#include <footprint.h>
39#include <refdes_utils.h>
40#include <board.h>
41#include <wx/string.h>
42#include <wx/log.h>
43
44#include "topo_match.h"
45
46
47static const wxString traceTopoMatch = wxT( "TOPO_MATCH" );
48static const wxString traceTopoMatchDetail = wxT( "TOPO_MATCH_DETAIL" );
49
50
51namespace TMATCH
52{
53
54bool PIN::IsIsomorphic( const PIN& b, TOPOLOGY_MISMATCH_REASON& aReason ) const
55{
56 if( m_conns.size() != b.m_conns.size() )
57 {
58 wxLogTrace( traceTopoMatch,
59 wxT( "[conns mismatch n1 %d n2 %d c-ref %d c-other %d thispin %s-%s "
60 "otherpin %s-%s" ),
62 b.m_netcode,
63 (int) m_conns.size(),
64 (int) b.m_conns.size(),
65 m_parent->m_reference,
66 m_ref,
68 b.m_ref );
69
70 aReason.m_reference = m_parent->GetParent()->GetReferenceAsString();
72 aReason.m_reason = wxString::Format(
73 _( "Pad %s of %s connects to %lu pads, but candidate pad %s of %s connects to %lu." ), m_ref,
74 aReason.m_reference, static_cast<unsigned long>( m_conns.size() ), b.m_ref, aReason.m_candidate,
75 static_cast<unsigned long>( b.m_conns.size() ) );
76
77 for( auto c : m_conns )
78 {
79 wxLogTrace( traceTopoMatch, wxT( "%s-%s " ), c->m_parent->m_reference, c->m_ref );
80 }
81
82 wxLogTrace( traceTopoMatch, wxT( "||" ) );
83
84 for( auto c : b.m_conns )
85 {
86 wxLogTrace( traceTopoMatch, wxT( "%s-%s " ), c->m_parent->m_reference, c->m_ref );
87 }
88
89
90 wxLogTrace( traceTopoMatch, wxT( "] " ) );
91 return false;
92 }
93
94 if( m_conns.empty() )
95 {
96 wxLogTrace( traceTopoMatch, wxT( "[conns empty]" ) );
97 return true;
98 }
99
100 std::vector<bool> matches( m_conns.size() );
101
102 for( size_t i = 0; i < m_conns.size(); i++ )
103 matches[i] = false;
104
105 size_t nref = 0;
106
107 for( auto& cref : m_conns )
108 {
109 for( size_t i = 0; i < m_conns.size(); i++ )
110 {
111 if( b.m_conns[i]->IsTopologicallySimilar( *cref ) )
112 {
113 matches[nref] = true;
114 break;
115 }
116 }
117
118 nref++;
119 }
120
121 for( size_t i = 0; i < m_conns.size(); i++ )
122 {
123 if( !matches[i] )
124 {
125 aReason.m_reference = m_parent->GetParent()->GetReferenceAsString();
127 aReason.m_reason = wxString::Format(
128 _( "Pad %s of %s cannot match candidate pad %s of %s due to differing connectivity." ), m_ref,
129 aReason.m_reference, b.m_ref, aReason.m_candidate );
130
131 return false;
132 }
133 }
134
135 return true;
136}
137
138
139std::unordered_map<int, int> buildBaseNetMapping( const BACKTRACK_STAGE& aMatches )
140{
141 std::unordered_map<int, int> mapping;
142 mapping.reserve( aMatches.GetMatchingComponentPairs().size() * 4 );
143
144 for( const auto& [tgtCmp, refCmp] : aMatches.GetMatchingComponentPairs() )
145 {
146 auto& refPins = refCmp->Pins();
147 auto& tgtPins = tgtCmp->Pins();
148
149 for( size_t i = 0; i < refPins.size() && i < tgtPins.size(); i++ )
150 mapping[refPins[i]->GetNetCode()] = tgtPins[i]->GetNetCode();
151 }
152
153 return mapping;
154}
155
156
157bool checkCandidateNetConsistency( const std::unordered_map<int, int>& aBaseMapping,
158 COMPONENT* aRef, COMPONENT* aTgt,
160 const std::unordered_set<int>& aExternalNets )
161{
162 if( aRef->Pins().size() != aTgt->Pins().size() )
163 {
164 aReason.m_reference = aRef->GetParent()->GetReferenceAsString();
165 aReason.m_candidate = aTgt->GetParent()->GetReferenceAsString();
166 aReason.m_reason =
167 wxString::Format( _( "Component %s expects %lu matching pads but candidate %s provides %lu." ),
168 aReason.m_reference, static_cast<unsigned long>( aRef->Pins().size() ),
169 aReason.m_candidate, static_cast<unsigned long>( aTgt->Pins().size() ) );
170 return false;
171 }
172
173 // Track net mappings introduced by this candidate's pins that aren't yet in the
174 // base mapping. Two pins sharing the same ref net must map to the same target net.
175 std::unordered_map<int, int> candidateAdditions;
176
177 for( size_t i = 0; i < aRef->Pins().size(); i++ )
178 {
179 int refNet = aRef->Pins()[i]->GetNetCode();
180 int tgtNet = aTgt->Pins()[i]->GetNetCode();
181
182 // Pads on external (global/power) nets are shared with the outside world and may be
183 // tied to different global nets in different channels (e.g. an address-select pin tied
184 // to +3V3 in one channel and GND in another). Skip them in the net-consistency check
185 // so such legitimate differences do not cause false topology-mismatch errors.
186 if( aExternalNets.count( refNet ) || aExternalNets.count( tgtNet ) )
187 continue;
188
189 auto baseIt = aBaseMapping.find( refNet );
190
191 if( baseIt != aBaseMapping.end() )
192 {
193 if( baseIt->second != tgtNet )
194 {
195 wxLogTrace( traceTopoMatch, wxT( "nets inconsistent\n" ) );
196
197 aReason.m_reference = aRef->GetParent()->GetReferenceAsString();
198 aReason.m_candidate = aTgt->GetParent()->GetReferenceAsString();
199
200 wxString refNetName;
201 wxString tgtNetName;
202
203 if( const BOARD* board = aRef->GetParent()->GetBoard() )
204 {
205 if( const NETINFO_ITEM* net = board->FindNet( refNet ) )
206 refNetName = net->GetNetname();
207 }
208
209 if( const BOARD* board = aTgt->GetParent()->GetBoard() )
210 {
211 if( const NETINFO_ITEM* net = board->FindNet( tgtNet ) )
212 tgtNetName = net->GetNetname();
213 }
214
215 if( refNetName.IsEmpty() )
216 refNetName = wxString::Format( _( "net %d" ), refNet );
217
218 if( tgtNetName.IsEmpty() )
219 tgtNetName = wxString::Format( _( "net %d" ), tgtNet );
220
221 aReason.m_reason = wxString::Format(
222 _( "Pad %s of %s is on net %s but its match in candidate %s is on net %s." ),
223 aRef->Pins()[i]->GetReference(), aReason.m_reference, refNetName,
224 aReason.m_candidate, tgtNetName );
225
226 return false;
227 }
228
229 continue;
230 }
231
232 auto localIt = candidateAdditions.find( refNet );
233
234 if( localIt != candidateAdditions.end() )
235 {
236 if( localIt->second != tgtNet )
237 {
238 wxLogTrace( traceTopoMatch, wxT( "nets inconsistent (candidate internal)\n" ) );
239
240 aReason.m_reference = aRef->GetParent()->GetReferenceAsString();
241 aReason.m_candidate = aTgt->GetParent()->GetReferenceAsString();
242 aReason.m_reason = wxString::Format(
243 _( "Pad %s of %s has inconsistent net mapping in candidate %s." ),
244 aRef->Pins()[i]->GetReference(), aReason.m_reference,
245 aReason.m_candidate );
246
247 return false;
248 }
249
250 continue;
251 }
252
253 candidateAdditions[refNet] = tgtNet;
254 }
255
256 return true;
257}
258
259
260std::vector<COMPONENT*>
262 const std::vector<COMPONENT*>& aStructuralMatches,
263 const TOPOLOGY_MISMATCH_REASON& aStructuralReason,
264 const BACKTRACK_STAGE& partialMatches,
265 std::vector<TOPOLOGY_MISMATCH_REASON>& aMismatchReasons,
266 const std::atomic<bool>* aCancelled )
267{
268 if( aCancelled && aCancelled->load( std::memory_order_relaxed ) )
269 return {};
270
271 PROF_TIMER timerFmc;
272
273 aMismatchReasons.clear();
274 std::vector<COMPONENT*> matches;
275 int candidatesChecked = 0;
276
277 // Build the net consistency map from locked pairs once for this entire evaluation
278 // pass, rather than rebuilding it from scratch for every candidate.
279 std::unordered_map<int, int> baseNetMapping = buildBaseNetMapping( partialMatches );
280
281 double netCheckMs = 0.0;
282
283 for( COMPONENT* cmpTarget : aStructuralMatches )
284 {
285 if( partialMatches.m_locked.find( cmpTarget ) != partialMatches.m_locked.end() )
286 continue;
287
288 candidatesChecked++;
289
290 wxLogTrace( traceTopoMatch, wxT( "Check '%s'/'%s' " ), aRef->m_reference,
291 cmpTarget->m_reference );
292
293 TOPOLOGY_MISMATCH_REASON localReason;
294 localReason.m_reference = aRef->GetParent()->GetReferenceAsString();
295 localReason.m_candidate = cmpTarget->GetParent()->GetReferenceAsString();
296
297 PROF_TIMER timerNet;
298 bool netResult = checkCandidateNetConsistency( baseNetMapping, aRef, cmpTarget, localReason,
300 timerNet.Stop();
301 netCheckMs += timerNet.msecs();
302
303 if( netResult )
304 {
305 wxLogTrace( traceTopoMatch, wxT( "match!\n" ) );
306 matches.push_back( cmpTarget );
307 }
308 else
309 {
310 wxLogTrace( traceTopoMatch, wxT( "Reject [net topo mismatch]\n" ) );
311 aMismatchReasons.push_back( localReason );
312 }
313 }
314
315 PROF_TIMER timerScore;
316
317 std::unordered_map<COMPONENT*, double> simScores;
318 simScores.reserve( matches.size() );
319
320 for( COMPONENT* match : matches )
321 {
322 int n = 0;
323
324 for( size_t i = 0; i < aRef->m_pins.size(); i++ )
325 {
326 if( aRef->m_pins[i]->GetNetCode() == match->m_pins[i]->GetNetCode() )
327 n++;
328 }
329
330 simScores[match] = static_cast<double>( n ) / static_cast<double>( aRef->m_pins.size() );
331 }
332
333 std::sort( matches.begin(), matches.end(),
334 [&]( COMPONENT* a, COMPONENT* b ) -> bool
335 {
336 double simA = simScores[a];
337 double simB = simScores[b];
338
339 if( simA != simB )
340 return simA > simB;
341
342 return a->GetParent()->GetReferenceAsString()
343 < b->GetParent()->GetReferenceAsString();
344 } );
345
346 timerScore.Stop();
347
348 if( matches.empty() && aMismatchReasons.empty() )
349 {
350 // No net-consistency reasons were recorded above, which means there were no structural
351 // candidates to test in the first place. Surface the structural reason captured during
352 // precomputation so the user sees the actual connectivity difference (e.g. a pad that
353 // connects to a different number of pads because of an external loop between channels)
354 // rather than a generic "no compatible component" message.
355 if( !aStructuralReason.m_reason.IsEmpty() )
356 {
357 aMismatchReasons.push_back( aStructuralReason );
358 }
359 else
360 {
362 reason.m_reference = aRef->GetParent()->GetReferenceAsString();
363 reason.m_reason = _( "No compatible component found in the target area." );
364 aMismatchReasons.push_back( reason );
365 }
366 }
367
368 timerFmc.Stop();
369
370 wxLogTrace( traceTopoMatchDetail,
371 wxT( " findMatch '%s' (%d pins): %s total, checked %d/%d structural, "
372 "netCheck %0.3f ms, score %0.3f ms, %d matches" ),
373 aRef->m_reference, aRef->GetPinCount(), timerFmc.to_string(),
374 candidatesChecked, (int) aStructuralMatches.size(),
375 netCheckMs, timerScore.msecs(),
376 (int) matches.size() );
377
378 return matches;
379}
380
381
382void CONNECTION_GRAPH::breakTie( COMPONENT* aRef, std::vector<COMPONENT*>& aMatches ) const
383{
384 if( aMatches.size() <= 1 )
385 return;
386
387 wxString candidateRefs;
388
389 for( size_t i = 0; i < aMatches.size(); i++ )
390 {
391 if( i > 0 )
392 candidateRefs += wxT( ", " );
393
394 candidateRefs += aMatches[i]->GetParent()->GetReferenceAsString();
395 }
396
397 wxLogTrace( traceTopoMatch, wxT( "Topology tie for %s: %s" ),
398 aRef->GetParent()->GetReferenceAsString(), candidateRefs );
399
400 if( breakTieBySymbolUuid( aRef, aMatches ) )
401 {
402 wxLogTrace( traceTopoMatchDetail, wxT( "Broke tie with symbol UUID match for %s" ),
403 aRef->GetParent()->GetReferenceAsString() );
404 }
405 else if( breakTieByValue( aRef, aMatches ) )
406 {
407 wxLogTrace( traceTopoMatchDetail, wxT( "Broke tie with footprint value match for %s" ),
408 aRef->GetParent()->GetReferenceAsString() );
409 }
410 // TODO: other tie breakers can be added, e.g. based on position or reference designators,
411 // just waiting for actual user test cases
412 else
413 {
414 wxLogTrace( traceTopoMatchDetail, wxT( "No tie breakers worked for %s, leaving match order alone." ),
415 aRef->GetParent()->GetReferenceAsString() );
416 }
417}
418
419
420bool CONNECTION_GRAPH::breakTieByValue( COMPONENT* aRef, std::vector<COMPONENT*>& aMatches ) const
421{
422 FOOTPRINT* refFp = aRef ? aRef->GetParent() : nullptr;
423
424 if( !refFp )
425 return false;
426
427 const wxString refValue = refFp->GetValue();
428
429 if( refValue.IsEmpty() )
430 return false;
431
432 int valueHitCount = 0;
433 int uniqueMatchIdx = -1;
434
435 for( size_t i = 0; i < aMatches.size(); i++ )
436 {
437 if( aMatches[i]->GetParent()->GetValue() == refValue )
438 {
439 if( uniqueMatchIdx < 0 )
440 uniqueMatchIdx = static_cast<int>( i );
441
442 valueHitCount++;
443 }
444 }
445
446 // Only one candidate may share the value for it to disambiguate the tie. Several same-value
447 // candidates (e.g. a bank of identical decoupling caps) tell us nothing.
448 if( valueHitCount == 1 )
449 {
450 std::rotate( aMatches.begin(), aMatches.begin() + uniqueMatchIdx, aMatches.begin() + uniqueMatchIdx + 1 );
451 return true;
452 }
453
454 return false;
455}
456
457
458bool CONNECTION_GRAPH::breakTieBySymbolUuid( COMPONENT* aRef, std::vector<COMPONENT*>& aMatches ) const
459{
460 auto getSymbolInstanceUuid =
461 []( const FOOTPRINT* aFootprint ) -> KIID
462 {
463 if( !aFootprint )
464 return niluuid;
465
466 const KIID_PATH& path = aFootprint->GetPath();
467
468 if( path.empty() )
469 return niluuid;
470
471 const KIID& symbolUuid = path.back();
472
473 return symbolUuid;
474 };
475
476 FOOTPRINT* refFp = aRef ? aRef->GetParent() : nullptr;
477 const KIID refSymbolUuid = getSymbolInstanceUuid( refFp );
478 wxString candidateSymbolUuids;
479 wxString matchingSymbolCandidates;
480 int symbolUuidHitCount = 0;
481 int uniqueMatchIdx = -1;
482
483 if( refSymbolUuid == niluuid )
484 {
485 wxLogTrace( traceTopoMatchDetail, wxT( "Tie symbol UUID unavailable for %s" ),
486 refFp ? refFp->GetReferenceAsString() : wxString( wxT( "<null>" ) ) );
487 return false;
488 }
489
490 // Inspect every tied candidate and collect:
491 // 1) a detailed ref->symbol UUID mapping string for traces, and
492 // 2) the subset of candidates whose symbol-path tail UUID matches the reference.
493 for( size_t i = 0; i < aMatches.size(); i++ )
494 {
495 FOOTPRINT* candidateFp = aMatches[i]->GetParent();
496 const wxString candidateRef = candidateFp->GetReferenceAsString();
497 const KIID candidateSymbolUuid = getSymbolInstanceUuid( candidateFp );
498
499 if( i > 0 )
500 candidateSymbolUuids += wxT( ", " );
501
502 if( candidateSymbolUuid == niluuid )
503 candidateSymbolUuids += candidateRef + wxT( "=<none>" );
504 else
505 candidateSymbolUuids += candidateRef + wxT( "=" ) + candidateSymbolUuid.AsString();
506
507 if( candidateSymbolUuid == refSymbolUuid )
508 {
509 if( uniqueMatchIdx < 0 )
510 uniqueMatchIdx = static_cast<int>( i );
511
512 symbolUuidHitCount++;
513
514 if( !matchingSymbolCandidates.IsEmpty() )
515 matchingSymbolCandidates += wxT( ", " );
516
517 matchingSymbolCandidates += candidateRef;
518 }
519 }
520
521 wxLogTrace( traceTopoMatchDetail, wxT( "Tie reference symbol UUID for %s: %s (hits=%d)" ),
522 refFp->GetReferenceAsString(), refSymbolUuid.AsString(), symbolUuidHitCount );
523
524 wxLogTrace( traceTopoMatchDetail, wxT( "Tie candidate symbol UUIDs: %s" ), candidateSymbolUuids );
525
526 // One match is what we want, we should have one match between the source symbol instance
527 // and the destination only since in theory we are repeating across two instances of the same sheet
528 if( symbolUuidHitCount == 1 )
529 {
530 wxLogTrace( traceTopoMatchDetail, wxT( "Symbol UUID unique match (usable) for %s: %s" ),
531 refFp->GetReferenceAsString(), matchingSymbolCandidates );
532
533 std::rotate( aMatches.begin(), aMatches.begin() + uniqueMatchIdx, aMatches.begin() + uniqueMatchIdx + 1 );
534
535 wxLogTrace( traceTopoMatchDetail, wxT( "Applied symbol UUID tie-break for %s: selected %s" ),
536 refFp->GetReferenceAsString(), aMatches.front()->GetParent()->GetReferenceAsString() );
537
538 return true;
539 }
540 // Copy and pasting footprints can result in multiple matches
541 else if( symbolUuidHitCount > 1 )
542 {
543 wxLogTrace( traceTopoMatchDetail, wxT( "Symbol UUID multiple matches (not usable) for %s: %s" ),
544 refFp->GetReferenceAsString(), matchingSymbolCandidates );
545 return false;
546 }
547 // Probably not sheet instances, break the tie some other way
548 else
549 {
550 wxLogTrace( traceTopoMatchDetail, wxT( "No symbol UUID candidate match (not usable) for %s" ),
551 refFp->GetReferenceAsString() );
552 return false;
553 }
554}
555
556
558{
559 std::sort( m_pins.begin(), m_pins.end(),
560 []( PIN* a, PIN* b )
561 {
562 return a->GetReference() < b->GetReference();
563 } );
564}
565
566
568{
569 std::sort( m_components.begin(), m_components.end(),
570 []( COMPONENT* a, COMPONENT* b )
571 {
572 if( a->GetPinCount() != b->GetPinCount() )
573 return a->GetPinCount() > b->GetPinCount();
574
575 return a->GetParent()->GetReferenceAsString() < b->GetParent()->GetReferenceAsString();
576 } );
577}
578
579
580void CONNECTION_GRAPH::BuildConnectivity( const std::unordered_set<int>& aExternalNets )
581{
582 m_externalNets = aExternalNets;
583
584 std::map<int, std::vector<PIN*>> nets;
585
587
588 for( auto c : m_components )
589 {
590 c->sortPinsByName();
591
592 for( auto p : c->Pins() )
593 {
594 if( p->GetNetCode() > 0 )
595 nets[p->GetNetCode()].push_back( p );
596 }
597 }
598
599 for( auto& [netcode, pins] : nets )
600 {
601 // Skip nets that extend beyond this channel's footprint set. Global power nets
602 // (GND, VCC, etc.) are shared across channels and can create spurious intra-channel
603 // connections that cause false topology mismatches when hierarchical pins are tied
604 // directly to those nets.
605 if( aExternalNets.count( netcode ) )
606 continue;
607
608 wxLogTrace( traceTopoMatch, wxT( "net %d: %d connections\n" ), netcode,
609 (int) pins.size() );
610
611 for( PIN* p : pins )
612 {
613 p->m_conns.reserve( pins.size() - 1 );
614
615 for( PIN* p2 : pins )
616 {
617 if( p != p2 )
618 p->m_conns.push_back( p2 );
619 }
620 }
621 }
622
623/* for( auto c : m_components )
624 for( auto p : c->Pins() )
625 {
626 printf("pin %s: \n", p->m_ref.c_str().AsChar() );
627
628 for( auto c : p->m_conns )
629 printf( "%s ", c->m_ref.c_str().AsChar() );
630 printf("\n");
631 }
632 */
633}
634
635
637{
638 std::map<wxString, int> counts;
639 std::map<wxString, wxString> footprintOf;
640 std::map<wxString, std::vector<wxString>> partsUsing;
641 std::set<wxString> repeatedRefs;
642};
643
644
645static SIDE_INVENTORY takeInventory( const std::vector<COMPONENT*>& aComponents )
646{
647 SIDE_INVENTORY inventory;
648
649 for( COMPONENT* cmp : aComponents )
650 {
651 const wxString reference = cmp->GetParent()->GetReferenceAsString();
652 wxString footprint = cmp->GetParent()->GetFPIDAsString();
653
654 if( footprint.IsEmpty() )
655 footprint = _( "(no library ID)" );
656
657 inventory.counts[footprint]++;
658 inventory.partsUsing[footprint].push_back( reference );
659
660 if( !inventory.footprintOf.emplace( reference, footprint ).second )
661 inventory.repeatedRefs.insert( reference );
662 }
663
664 for( auto& [footprint, parts] : inventory.partsUsing )
665 std::sort( parts.begin(), parts.end() );
666
667 return inventory;
668}
669
670
671static bool sameFootprintInventory( const std::vector<COMPONENT*>& aRefComponents,
672 const std::vector<COMPONENT*>& aTargetComponents,
673 std::vector<TOPOLOGY_MISMATCH_REASON>& aMismatchReasons )
674{
675 const SIDE_INVENTORY ref = takeInventory( aRefComponents );
676 const SIDE_INVENTORY target = takeInventory( aTargetComponents );
677
678 if( ref.counts == target.counts )
679 return true;
680
681 // Same name on both sides but a different footprint. That is the part someone changed.
682 for( const auto& [reference, footprint] : ref.footprintOf )
683 {
684 auto other = target.footprintOf.find( reference );
685
686 if( other == target.footprintOf.end() || other->second == footprint || ref.repeatedRefs.count( reference )
687 || target.repeatedRefs.count( reference ) )
688 continue;
689
691 reason.m_reference = reference;
692 reason.m_candidate = reference;
693 reason.m_reason = wxString::Format( _( "%s uses footprint '%s' in the reference area but "
694 "'%s' in the target area." ),
695 reference, footprint, other->second );
696 aMismatchReasons.push_back( reason );
697 }
698
699 // Lines that name parts go before bare counts. The caller shows the first line as the headline.
700 std::vector<TOPOLOGY_MISMATCH_REASON> namedParts;
701 std::vector<TOPOLOGY_MISMATCH_REASON> countsOnly;
702 std::vector<wxString> refOnly;
703 std::vector<wxString> targetOnly;
704
705 const size_t maxNamed = 12;
706
707 auto joinParts = []( const std::vector<wxString>& aParts )
708 {
709 wxString joined;
710
711 for( const wxString& part : aParts )
712 {
713 if( !joined.IsEmpty() )
714 joined += wxT( ", " );
715
716 joined += part;
717 }
718
719 return joined;
720 };
721
722 for( const auto& [footprint, count] : ref.counts )
723 {
724 if( !target.counts.count( footprint ) )
725 refOnly.push_back( footprint );
726 }
727
728 for( const auto& [footprint, count] : target.counts )
729 {
730 if( !ref.counts.count( footprint ) )
731 targetOnly.push_back( footprint );
732 }
733
734 // One footprint swapped for one other. Put both names in one line so a small spelling
735 // difference is easy to see.
736 const bool pairedSwap = refOnly.size() == 1 && targetOnly.size() == 1
737 && ref.partsUsing.at( refOnly.front() ).size() <= maxNamed
738 && target.partsUsing.at( targetOnly.front() ).size() <= maxNamed;
739
740 if( pairedSwap )
741 {
743 reason.m_reason =
744 wxString::Format( _( "Footprint '%s' in the reference area (%s) appears as "
745 "'%s' in the target area (%s)." ),
746 refOnly.front(), joinParts( ref.partsUsing.at( refOnly.front() ) ),
747 targetOnly.front(), joinParts( target.partsUsing.at( targetOnly.front() ) ) );
748 namedParts.push_back( reason );
749 }
750
751 auto reportUsage = [&]( const wxString& aFootprint, int aRefUses, int aTargetUses )
752 {
753 if( aRefUses == aTargetUses )
754 return;
755
756 if( pairedSwap && ( aFootprint == refOnly.front() || aFootprint == targetOnly.front() ) )
757 return;
758
759 // Only one side uses this footprint, so name the parts that do. Their numbering does not
760 // have to match the other side. A long list is left as counts.
761 const std::vector<wxString>& parts =
762 aRefUses == 0 ? target.partsUsing.at( aFootprint ) : ref.partsUsing.at( aFootprint );
764
765 if( ( aRefUses == 0 || aTargetUses == 0 ) && parts.size() <= maxNamed )
766 {
767 const wxString named = joinParts( parts );
768
769 if( aRefUses == 0 )
770 {
771 reason.m_reason = wxString::Format( _( "Footprint '%s' is used by %s in the target "
772 "area but by nothing in the reference area." ),
773 aFootprint, named );
774 }
775 else
776 {
777 reason.m_reason = wxString::Format( _( "Footprint '%s' is used by %s in the "
778 "reference area but by nothing in the "
779 "target area." ),
780 aFootprint, named );
781 }
782
783 namedParts.push_back( reason );
784 }
785 else
786 {
787 reason.m_reason = wxString::Format( _( "Footprint '%s': %d in the reference area, %d in "
788 "the target area." ),
789 aFootprint, aRefUses, aTargetUses );
790 countsOnly.push_back( reason );
791 }
792 };
793
794 for( const auto& [footprint, refUses] : ref.counts )
795 {
796 auto used = target.counts.find( footprint );
797
798 reportUsage( footprint, refUses, used == target.counts.end() ? 0 : used->second );
799 }
800
801 for( const auto& [footprint, targetUses] : target.counts )
802 {
803 if( !ref.counts.count( footprint ) )
804 reportUsage( footprint, 0, targetUses );
805 }
806
807 aMismatchReasons.insert( aMismatchReasons.end(), namedParts.begin(), namedParts.end() );
808 aMismatchReasons.insert( aMismatchReasons.end(), countsOnly.begin(), countsOnly.end() );
809
810 return false;
811}
812
813
815 std::vector<TOPOLOGY_MISMATCH_REASON>& aMismatchReasons,
816 const ISOMORPHISM_PARAMS& aParams )
817{
818 std::vector<BACKTRACK_STAGE> stack;
820
821 aMismatchReasons.clear();
822
823 if( aParams.m_totalComponents )
824 aParams.m_totalComponents->store( (int) m_components.size(), std::memory_order_relaxed );
825
826 PROF_TIMER timerTotal;
827 int backtrackCount = 0;
828 double mrvTotalMs = 0.0;
829
830 std::vector<TOPOLOGY_MISMATCH_REASON> localReasons;
831
832 if( m_components.empty()|| aTarget->m_components.empty() )
833 {
835
836 if( m_components.empty() && aTarget->m_components.empty() )
837 reason.m_reason = _( "Neither area has any footprints to match." );
838 else if( m_components.empty() )
839 reason.m_reason = _( "The reference area has no footprints to match." );
840 else
841 reason.m_reason = _( "The target area has no footprints to match." );
842
843 aMismatchReasons.push_back( reason );
844 return false;
845 }
846
847 if( m_components.size() != aTarget->m_components.size() )
848 {
850 reason.m_reason = wxString::Format( _( "The reference area has %d components and the "
851 "target area has %d." ),
852 (int) m_components.size(), (int) aTarget->m_components.size() );
853 aMismatchReasons.push_back( reason );
854 return false;
855 }
856
857 if( !sameFootprintInventory( m_components, aTarget->m_components, aMismatchReasons ) )
858 return false;
859
860 // Structural compatibility (MatchesWith) depends only on pin count, footprint ID, and
861 // pin connection topology -- all immutable graph properties. Precompute it once per
862 // source component so the backtracking loop never repeats these comparisons.
863 size_t numRef = m_components.size();
864 std::vector<std::vector<COMPONENT*>> structuralMatches( numRef );
865
866 // When a source component has no structural match at all, keep a representative reason so we
867 // can explain the actual connectivity difference rather than a generic "no compatible
868 // component" message.
869 std::vector<TOPOLOGY_MISMATCH_REASON> structuralReasons( numRef );
870
871 PROF_TIMER timerPrecompute;
872 {
874 std::vector<std::future<void>> futures;
875 futures.reserve( numRef );
876
877 const std::atomic<bool>* cancelled = aParams.m_cancelled;
878
879 for( size_t i = 0; i < numRef; i++ )
880 {
881 futures.emplace_back( tp.submit_task(
882 [this, i, aTarget, &structuralMatches, &structuralReasons, cancelled]()
883 {
884 if( cancelled && cancelled->load( std::memory_order_relaxed ) )
885 return;
886
887 COMPONENT* ref = m_components[i];
888 TOPOLOGY_MISMATCH_REASON reason;
889 TOPOLOGY_MISMATCH_REASON bestReason;
890 int bestRank = -1;
891
892 for( COMPONENT* tgt : aTarget->m_components )
893 {
894 if( ref->MatchesWith( tgt, reason ) )
895 {
896 structuralMatches[i].push_back( tgt );
897 continue;
898 }
899
900 // Report against the counterpart the user expects to match.
901 int rank = 0;
902
903 if( tgt->m_reference == ref->m_reference )
904 rank = 3;
905 else if( ref->IsSameKind( *tgt ) )
906 rank = 2;
907 else if( COMPONENT::prefixesShareCommonBase( ref->m_prefix, tgt->m_prefix ) )
908 rank = 1;
909
910 if( rank >= bestRank )
911 {
912 bestRank = rank;
913 bestReason = reason;
914 }
915 }
916
917 if( structuralMatches[i].empty() )
918 structuralReasons[i] = bestReason;
919 } ) );
920 }
921
922 for( auto& f : futures )
923 f.wait();
924 }
925 timerPrecompute.Stop();
926
927 wxLogTrace( traceTopoMatchDetail,
928 wxT( "Structural precomputation: %s (%d source x %d target)" ),
929 timerPrecompute.to_string(), (int) numRef,
930 (int) aTarget->m_components.size() );
931
932 if( aParams.m_cancelled && aParams.m_cancelled->load( std::memory_order_relaxed ) )
933 return false;
934
935 top.m_ref = m_components.front();
936 top.m_refIndex = 0;
937
938 stack.push_back( top );
939
940 int nloops = 0;
941
942 while( !stack.empty() )
943 {
944 if( aParams.m_cancelled && aParams.m_cancelled->load( std::memory_order_relaxed ) )
945 return false;
946
947 nloops++;
948 auto& current = stack.back();
949
950 for( auto it = current.m_locked.begin(); it != current.m_locked.end(); it++ )
951 {
952 if (it->second == current.m_ref)
953 {
954 wxLogTrace( traceTopoMatch, wxT( "stk: Remove %s from locked\n" ),
955 current.m_ref->m_reference );
956 current.m_locked.erase( it );
957 break;
958 }
959 }
960
961 if( nloops >= c_ITER_LIMIT )
962 {
963 wxLogTrace( traceTopoMatch, wxT( "stk: Iter cnt exceeded\n" ) );
964
966 reason.m_reason = wxString::Format( _( "Gave up after %d attempts to pair up the two "
967 "areas. Either their connections differ, or too "
968 "many components are interchangeable to tell "
969 "apart." ),
970 c_ITER_LIMIT );
971
972 if( aMismatchReasons.empty() )
973 aMismatchReasons.push_back( reason );
974 else
975 aMismatchReasons.insert( aMismatchReasons.begin(), reason );
976
977 return false;
978 }
979
980 if( current.m_currentMatch < 0 )
981 {
982 PROF_TIMER timerInitMatch;
983
984 localReasons.clear();
985 current.m_matches = aTarget->findMatchingComponents(
986 current.m_ref, structuralMatches[current.m_refIndex],
987 structuralReasons[current.m_refIndex], current, localReasons,
988 aParams.m_cancelled );
989
990 timerInitMatch.Stop();
991
992 wxLogTrace( traceTopoMatchDetail,
993 wxT( "iter %d: initial match for '%s' (%d pins): %s, %d candidates" ),
994 nloops, current.m_ref->m_reference, current.m_ref->GetPinCount(),
995 timerInitMatch.to_string(), (int) current.m_matches.size() );
996
997 if( current.m_matches.empty() && aMismatchReasons.empty() && !localReasons.empty() )
998 aMismatchReasons = localReasons;
999
1000 current.m_currentMatch = 0;
1001 }
1002
1003 wxLogTrace( traceTopoMatch, wxT( "stk: Current '%s' stack %d cm %d/%d locked %d/%d\n" ),
1004 current.m_ref->m_reference, (int) stack.size(), current.m_currentMatch,
1005 (int) current.m_matches.size(), (int) current.m_locked.size(),
1006 (int) m_components.size() );
1007
1008 if( current.m_currentMatch == 0 && current.m_matches.size() > 1 )
1009 breakTie( current.m_ref, current.m_matches );
1010
1011 if ( current.m_matches.empty() )
1012 {
1013 wxLogTrace( traceTopoMatch, wxT( "stk: No matches at all, going up [level=%d]\n" ),
1014 (int) stack.size() );
1015 stack.pop_back();
1016 backtrackCount++;
1017 continue;
1018 }
1019
1020 if( current.m_currentMatch >= 0
1021 && static_cast<size_t>( current.m_currentMatch ) >= current.m_matches.size() )
1022 {
1023 wxLogTrace( traceTopoMatch, wxT( "stk: No more matches, going up [level=%d]\n" ),
1024 (int) stack.size() );
1025 stack.pop_back();
1026 backtrackCount++;
1027 continue;
1028 }
1029
1030 auto& match = current.m_matches[current.m_currentMatch];
1031
1032 wxLogTrace( traceTopoMatch, wxT( "stk: candidate '%s', match list : ( " ),
1033 current.m_matches[current.m_currentMatch]->m_reference, current.m_refIndex );
1034
1035 for( auto m : current.m_matches )
1036 wxLogTrace( traceTopoMatch, wxT( "%s " ), m->GetParent()->GetReferenceAsString() );
1037
1038 wxLogTrace( traceTopoMatch, wxT( "\n" ) );
1039
1040 current.m_currentMatch++;
1041 current.m_locked[match] = current.m_ref;
1042
1043 if( aParams.m_matchedComponents )
1044 {
1045 aParams.m_matchedComponents->store( (int) current.m_locked.size(),
1046 std::memory_order_relaxed );
1047 }
1048
1049 if( current.m_locked.size() == m_components.size() )
1050 {
1051 current.m_nloops = nloops;
1052
1053 aResult.clear();
1054 aMismatchReasons.clear();
1055
1056 for( auto iter : current.m_locked )
1057 aResult[ iter.second->GetParent() ] = iter.first->GetParent();
1058
1059 timerTotal.Stop();
1060 wxLogTrace( traceTopoMatch,
1061 wxT( "Isomorphism: %s, %d iterations, %d backtracks, "
1062 "MRV total %0.1f ms (%d candidates)" ),
1063 timerTotal.to_string(), nloops, backtrackCount, mrvTotalMs,
1064 (int) m_components.size() );
1065
1066 return true;
1067 }
1068
1069
1070 // MRV heuristic: find the unlocked component with the fewest candidate matches.
1071 // Collect unlocked components, then evaluate them in parallel since each
1072 // findMatchingComponents call is independent (read-only on graphs and current stage).
1073 struct MRV_CANDIDATE
1074 {
1075 COMPONENT* m_cmp;
1076 size_t m_index;
1077 std::vector<COMPONENT*> m_matches;
1078 std::vector<TOPOLOGY_MISMATCH_REASON> m_reasons;
1079 };
1080
1081 std::vector<MRV_CANDIDATE> mrvCandidates;
1082
1083 // Build a set of all ref-components already locked so we can skip them in O(1)
1084 // instead of scanning m_locked values for each component.
1085 std::unordered_set<COMPONENT*> lockedRefs;
1086 lockedRefs.reserve( current.m_locked.size() );
1087
1088 for( const auto& [tgt, ref] : current.m_locked )
1089 lockedRefs.insert( ref );
1090
1091 for( size_t i = 0; i < m_components.size(); i++ )
1092 {
1093 COMPONENT* cmp = m_components[i];
1094
1095 if( cmp != current.m_ref && lockedRefs.find( cmp ) == lockedRefs.end() )
1096 mrvCandidates.push_back( { cmp, i, {}, {} } );
1097 }
1098
1099 static const size_t MRV_PARALLEL_THRESHOLD = 4;
1100
1101 PROF_TIMER timerMrv;
1102
1103 if( mrvCandidates.size() >= MRV_PARALLEL_THRESHOLD )
1104 {
1106 std::vector<std::future<void>> futures;
1107 futures.reserve( mrvCandidates.size() );
1108
1109 const std::atomic<bool>* cancelled = aParams.m_cancelled;
1110
1111 for( MRV_CANDIDATE& c : mrvCandidates )
1112 {
1113 futures.emplace_back( tp.submit_task(
1114 [&c, aTarget, &current, &structuralMatches, &structuralReasons, cancelled]()
1115 {
1116 c.m_matches = aTarget->findMatchingComponents(
1117 c.m_cmp, structuralMatches[c.m_index],
1118 structuralReasons[c.m_index], current, c.m_reasons,
1119 cancelled );
1120 } ) );
1121 }
1122
1123 for( auto& f : futures )
1124 f.wait();
1125 }
1126 else
1127 {
1128 for( MRV_CANDIDATE& c : mrvCandidates )
1129 {
1130 c.m_matches = aTarget->findMatchingComponents(
1131 c.m_cmp, structuralMatches[c.m_index],
1132 structuralReasons[c.m_index], current, c.m_reasons,
1133 aParams.m_cancelled );
1134 }
1135 }
1136
1137 timerMrv.Stop();
1138 double mrvMs = timerMrv.msecs();
1139 mrvTotalMs += mrvMs;
1140
1141 wxLogTrace( traceTopoMatchDetail,
1142 wxT( "iter %d: MRV scan %0.3f ms, %d unlocked candidates" ),
1143 nloops, mrvMs, (int) mrvCandidates.size() );
1144
1145 if( aParams.m_cancelled && aParams.m_cancelled->load( std::memory_order_relaxed ) )
1146 return false;
1147
1148 int minMatches = std::numeric_limits<int>::max();
1149 COMPONENT* altNextRef = nullptr;
1150 COMPONENT* bestNextRef = nullptr;
1151 int bestRefIndex = 0;
1152 int altRefIndex = 0;
1153 std::vector<COMPONENT*> bestMatches;
1154
1155 for( MRV_CANDIDATE& c : mrvCandidates )
1156 {
1157 int nMatches = static_cast<int>( c.m_matches.size() );
1158
1159 if( nMatches == 1 )
1160 {
1161 bestNextRef = c.m_cmp;
1162 bestRefIndex = static_cast<int>( c.m_index );
1163 bestMatches = std::move( c.m_matches );
1164 break;
1165 }
1166 else if( nMatches == 0 )
1167 {
1168 altNextRef = c.m_cmp;
1169 altRefIndex = static_cast<int>( c.m_index );
1170
1171 if( aMismatchReasons.empty() && !c.m_reasons.empty() )
1172 aMismatchReasons = c.m_reasons;
1173 }
1174 else if( nMatches < minMatches )
1175 {
1176 minMatches = nMatches;
1177 bestNextRef = c.m_cmp;
1178 bestRefIndex = static_cast<int>( c.m_index );
1179 bestMatches = std::move( c.m_matches );
1180 }
1181 }
1182
1183 BACKTRACK_STAGE next( current );
1184
1185 if( bestNextRef )
1186 {
1187 wxLogTrace( traceTopoMatchDetail,
1188 wxT( "iter %d: MRV picked '%s' (%d matches, best of %d)" ),
1189 nloops, bestNextRef->m_reference,
1190 (int) bestMatches.size(), (int) mrvCandidates.size() );
1191
1192 next.m_ref = bestNextRef;
1193 next.m_refIndex = bestRefIndex;
1194 next.m_matches = std::move( bestMatches );
1195 next.m_currentMatch = 0;
1196 }
1197 else
1198 {
1199 wxLogTrace( traceTopoMatchDetail,
1200 wxT( "iter %d: MRV dead end, alt='%s'" ),
1201 nloops, altNextRef ? altNextRef->m_reference : wxString( "(none)" ) );
1202
1203 next.m_ref = altNextRef;
1204 next.m_refIndex = altRefIndex;
1205 next.m_currentMatch = -1;
1206 }
1207
1208 stack.push_back( next );
1209 };
1210
1211 timerTotal.Stop();
1212 wxLogTrace( traceTopoMatch,
1213 wxT( "Isomorphism: %s, %d iterations, %d backtracks, "
1214 "MRV total %0.1f ms (%d candidates)" ),
1215 timerTotal.to_string(), nloops, backtrackCount, mrvTotalMs,
1216 (int) m_components.size() );
1217
1218 return false;
1219}
1220
1221
1222#if 0
1223int main()
1224{
1225 FILE * f = fopen("connectivity.dump","rb" );
1226 auto cgRef = loadCGraph(f);
1227 auto cgTarget = loadCGraph(f);
1228
1229 cgRef->buildConnectivity();
1230 cgTarget->buildConnectivity();
1231
1232 int attempts = 0;
1233 int max_loops = 0;
1234
1235 for( ;; )
1236 {
1237 cgRef->shuffle();
1238 cgTarget->shuffle();
1239
1240 const BacktrackStage latest = cgRef->matchCGraphs( cgTarget );
1241
1242 if( !latest.locked.size() )
1243 {
1244 printf("MATCH FAIL\n");
1245 break;
1246 }
1247
1248 //printf("loops: %d\n", latest.nloops );
1249 //printf("Locked: %d\n", latest.locked.size() );
1250
1251 //if (matchFound)
1252 //{
1253 // for( auto& iter : latest.locked )
1254 //{
1255 // printf("%-10s : %-10s\n", iter.first->reference.c_str(), iter.second->reference.c_str() );
1256 //}
1257
1258 //}
1259
1260 if( latest.nloops > max_loops )
1261 {
1262 max_loops = latest.nloops;
1263 }
1264
1265 if (attempts % 10000 == 0)
1266 {
1267 printf("attempts: %d maxloops: %d\n", attempts, max_loops );
1268 }
1269
1270 attempts++;
1271
1272 }
1273
1274 fclose(f);
1275
1276 return 0;
1277}
1278
1279#endif
1280
1281
1282COMPONENT::COMPONENT( const wxString& aRef, FOOTPRINT* aParentFp,
1283 std::optional<VECTOR2I> aRaOffset ) :
1284 m_raOffset( aRaOffset ),
1285 m_reference( aRef ),
1286 m_parentFootprint( aParentFp )
1287{
1289}
1290
1291
1292bool COMPONENT::isChannelSuffix( const wxString& aSuffix )
1293{
1294 if( aSuffix.IsEmpty() )
1295 return true;
1296
1297 for( wxUniChar ch : aSuffix )
1298 {
1299 if( std::isalpha( static_cast<int>( ch ) ) )
1300 return false;
1301 }
1302
1303 return true;
1304}
1305
1306
1307bool COMPONENT::prefixesShareCommonBase( const wxString& aPrefixA, const wxString& aPrefixB )
1308{
1309 if( aPrefixA == aPrefixB )
1310 return true;
1311
1312 size_t commonLen = 0;
1313 size_t minLen = std::min( aPrefixA.length(), aPrefixB.length() );
1314
1315 while( commonLen < minLen && aPrefixA[commonLen] == aPrefixB[commonLen] )
1316 commonLen++;
1317
1318 if( commonLen == 0 )
1319 return false;
1320
1321 wxString suffixA = aPrefixA.Mid( commonLen );
1322 wxString suffixB = aPrefixB.Mid( commonLen );
1323
1324 return isChannelSuffix( suffixA ) && isChannelSuffix( suffixB );
1325}
1326
1327
1328bool COMPONENT::isUnannotatedRef( const wxString& aRef )
1329{
1330 // REF** placeholder prefix ends in wildcard glyph so shares no base with annotated dest
1331 // clean-prefix placeholders like SW? already match via prefixesShareCommonBase
1332 wxString prefix = UTIL::GetRefDesPrefix( aRef );
1333
1334 return !prefix.IsEmpty() && ( prefix.Last() == '*' || prefix.Last() == '?' );
1335}
1336
1337
1338bool COMPONENT::IsSameKind( const COMPONENT& b ) const
1339{
1342 {
1343 return false;
1344 }
1345
1346 return ( m_parentFootprint->GetFPID() == b.m_parentFootprint->GetFPID() )
1347 || ( m_parentFootprint->GetFPID().empty() && b.m_parentFootprint->GetFPID().empty() );
1348}
1349
1350
1352{
1353 m_pins.push_back( aPin );
1354 aPin->SetParent( this );
1355}
1356
1357
1359{
1360 if( GetPinCount() != b->GetPinCount() )
1361 {
1363 aReason.m_candidate = b->GetParent()->GetReferenceAsString();
1364 aReason.m_reason =
1365 wxString::Format( _( "Component %s has %d pads but candidate %s has %d." ), aReason.m_reference,
1366 GetPinCount(), aReason.m_candidate, b->GetPinCount() );
1367 return false;
1368 }
1369
1370 if( !IsSameKind( *b ) )
1371 {
1373 aReason.m_candidate = b->GetParent()->GetReferenceAsString();
1374
1377 {
1378 aReason.m_reason = wxString::Format(
1379 _( "Reference prefix mismatch: %s uses prefix '%s' but candidate %s uses '%s'." ),
1380 aReason.m_reference, m_prefix, aReason.m_candidate, b->m_prefix );
1381 }
1382 else
1383 {
1384 wxString refFootprint = GetParent()->GetFPIDAsString();
1385 wxString candFootprint = b->GetParent()->GetFPIDAsString();
1386
1387 if( refFootprint.IsEmpty() )
1388 refFootprint = _( "(no library ID)" );
1389
1390 if( candFootprint.IsEmpty() )
1391 candFootprint = _( "(no library ID)" );
1392
1393 aReason.m_reason =
1394 wxString::Format( _( "Library link mismatch: %s expects '%s' but candidate %s is '%s'." ),
1395 aReason.m_reference, refFootprint, aReason.m_candidate, candFootprint );
1396 }
1397
1398 return false;
1399 }
1400
1401 for( int pin = 0; pin < b->GetPinCount(); pin++ )
1402 {
1403 // Call with the reference pin as the subject so the reason's reference/candidate match
1404 // MatchesWith's own orientation (this == reference, b == candidate).
1405 if( !m_pins[pin]->IsIsomorphic( *b->m_pins[pin], aReason ) )
1406 {
1407 if( aReason.m_reason.IsEmpty() )
1408 {
1410 aReason.m_candidate = b->GetParent()->GetReferenceAsString();
1411 aReason.m_reason = wxString::Format( _( "Component pads differ between %s and %s." ),
1412 aReason.m_reference, aReason.m_candidate );
1413 }
1414
1415 return false;
1416 }
1417
1418 }
1419
1420 return true;
1421}
1422
1423
1425{
1426 auto cmp = new COMPONENT( aFp->GetReference(), aFp );
1427
1428 for( auto pad : aFp->Pads() )
1429 {
1430 auto pin = new PIN( );
1431 pin->m_netcode = pad->GetNetCode();
1432 pin->m_ref = pad->GetNumber();
1433 cmp->AddPin( pin );
1434 }
1435
1436 m_components.push_back( cmp );
1437}
1438
1439
1440std::unique_ptr<CONNECTION_GRAPH>
1441CONNECTION_GRAPH::BuildFromFootprintSet( const std::set<FOOTPRINT*>& aFps,
1442 const std::set<FOOTPRINT*>& aOtherChannelFps,
1443 const std::unordered_set<int>& aGlobalNets )
1444{
1445 auto cgraph = std::make_unique<CONNECTION_GRAPH>();
1446 VECTOR2I ref(0, 0);
1447
1448 if( aFps.size() > 0 )
1449 ref = (*aFps.begin())->GetPosition();
1450
1451 for( auto fp : aFps )
1452 cgraph->AddFootprint( fp, fp->GetPosition() - ref );
1453
1454 std::unordered_map<int, int> localNetPadCounts;
1455
1456 for( const FOOTPRINT* fp : aFps )
1457 {
1458 for( const PAD* pad : fp->Pads() )
1459 {
1460 if( pad->GetNetCode() > 0 )
1461 localNetPadCounts[pad->GetNetCode()]++;
1462 }
1463 }
1464
1465 std::unordered_map<int, int> otherChannelNetPadCounts;
1466
1467 for( const FOOTPRINT* fp : aOtherChannelFps )
1468 {
1469 for( const PAD* pad : fp->Pads() )
1470 {
1471 if( pad->GetNetCode() > 0 )
1472 otherChannelNetPadCounts[pad->GetNetCode()]++;
1473 }
1474 }
1475
1476 // Caller-supplied global rails, plus the pairwise fallback: nets with >=2 pads in both channels.
1477 // Single-pad boundary nets stay in the comparison; excluding them asymmetrically breaks the match.
1478 std::unordered_set<int> externalNets = aGlobalNets;
1479
1480 for( const auto& [netCode, localCount] : localNetPadCounts )
1481 {
1482 auto otherIt = otherChannelNetPadCounts.find( netCode );
1483
1484 if( localCount >= 2 && otherIt != otherChannelNetPadCounts.end() && otherIt->second >= 2 )
1485 externalNets.insert( netCode );
1486 }
1487
1488 cgraph->BuildConnectivity( externalNets );
1489
1490 return cgraph;
1491}
1492
1493
1498
1499
1501{
1502 for( COMPONENT* fp : m_components )
1503 {
1504 delete fp;
1505 }
1506}
1507
1508
1510{
1511 for( PIN* p : m_pins )
1512 {
1513 delete p;
1514 }
1515}
1516
1517
1518}; // namespace TMATCH
virtual const BOARD * GetBoard() const
Return the BOARD in which this BOARD_ITEM resides, or NULL if none.
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:409
COMPONENT(const LIB_ID &aFPID, const wxString &aReference, const wxString &aValue, const KIID_PATH &aPath, const std::vector< KIID > &aKiids)
std::deque< PAD * > & Pads()
Definition footprint.h:404
wxString GetFPIDAsString() const
Definition footprint.h:479
const LIB_ID & GetFPID() const
Definition footprint.h:473
wxString GetReferenceAsString() const
Definition footprint.h:910
const wxString & GetValue() const
Definition footprint.h:925
const wxString & GetReference() const
Definition footprint.h:901
Definition kiid.h:46
wxString AsString() const
Definition kiid.cpp:264
bool empty() const
Definition lib_id.h:189
Handle the data for a net.
Definition netinfo.h:50
Definition pad.h:61
A small class to help profiling.
Definition profile.h:46
void Stop()
Save the time when this function was called, and set the counter stane to stop.
Definition profile.h:86
std::string to_string()
Definition profile.h:153
double msecs(bool aSinceLast=false)
Definition profile.h:147
const std::unordered_map< COMPONENT *, COMPONENT * > & GetMatchingComponentPairs() const
Definition topo_match.h:173
std::unordered_map< COMPONENT *, COMPONENT * > m_locked
Definition topo_match.h:183
static bool prefixesShareCommonBase(const wxString &aPrefixA, const wxString &aPrefixB)
Check if two prefixes share a common starting sequence.
static bool isUnannotatedRef(const wxString &aRef)
True for un-annotated placeholder refs like REF** that match any counterpart on FPID and topology alo...
bool IsSameKind(const COMPONENT &b) const
int GetPinCount() const
Definition topo_match.h:69
COMPONENT(const wxString &aRef, FOOTPRINT *aParentFp, std::optional< VECTOR2I > aRaOffset=std::optional< VECTOR2I >())
FOOTPRINT * m_parentFootprint
Definition topo_match.h:106
std::optional< VECTOR2I > m_raOffset
Definition topo_match.h:103
bool MatchesWith(COMPONENT *b, TOPOLOGY_MISMATCH_REASON &aDetail)
void AddPin(PIN *p)
std::vector< PIN * > & Pins()
Definition topo_match.h:71
friend class PIN
Definition topo_match.h:60
wxString m_reference
Definition topo_match.h:104
static bool isChannelSuffix(const wxString &aSuffix)
Check if a suffix looks like a channel identifier.
std::vector< PIN * > m_pins
Definition topo_match.h:107
FOOTPRINT * GetParent() const
Definition topo_match.h:72
std::vector< COMPONENT * > findMatchingComponents(COMPONENT *ref, const std::vector< COMPONENT * > &aStructuralMatches, const TOPOLOGY_MISMATCH_REASON &aStructuralReason, const BACKTRACK_STAGE &partialMatches, std::vector< TOPOLOGY_MISMATCH_REASON > &aFailureDetails, const std::atomic< bool > *aCancelled=nullptr)
bool FindIsomorphism(CONNECTION_GRAPH *target, COMPONENT_MATCHES &result, std::vector< TOPOLOGY_MISMATCH_REASON > &aFailureDetails, const ISOMORPHISM_PARAMS &aParams={})
void BuildConnectivity(const std::unordered_set< int > &aExternalNets={})
static std::unique_ptr< CONNECTION_GRAPH > BuildFromFootprintSet(const std::set< FOOTPRINT * > &aFps, const std::set< FOOTPRINT * > &aOtherChannelFps={}, const std::unordered_set< int > &aGlobalNets={})
bool breakTieByValue(COMPONENT *aRef, std::vector< COMPONENT * > &aMatches) const
Break a tie by footprint value when the symbol UUID can't, e.g.
std::vector< COMPONENT * > m_components
Definition topo_match.h:243
void AddFootprint(FOOTPRINT *aFp, const VECTOR2I &aOffset)
bool breakTieBySymbolUuid(COMPONENT *aRef, std::vector< COMPONENT * > &aMatches) const
The most useful tie breaker is based on symbol/sheet instances, since multiple channels in a design a...
void breakTie(COMPONENT *aRef, std::vector< COMPONENT * > &aMatches) const
Many times components are electrically/topologically identical, e.g.
std::unordered_set< int > m_externalNets
Definition topo_match.h:244
std::vector< PIN * > m_conns
Definition topo_match.h:147
void SetParent(COMPONENT *parent)
Definition topo_match.h:118
COMPONENT * m_parent
Definition topo_match.h:146
bool IsIsomorphic(const PIN &b, TOPOLOGY_MISMATCH_REASON &aDetail) const
wxString m_ref
Definition topo_match.h:144
static bool empty(const wxTextEntryBase *aCtrl)
#define _(s)
KIID niluuid(0)
std::unordered_map< int, int > buildBaseNetMapping(const BACKTRACK_STAGE &aMatches)
std::map< FOOTPRINT *, FOOTPRINT * > COMPONENT_MATCHES
Definition topo_match.h:187
static SIDE_INVENTORY takeInventory(const std::vector< COMPONENT * > &aComponents)
static bool sameFootprintInventory(const std::vector< COMPONENT * > &aRefComponents, const std::vector< COMPONENT * > &aTargetComponents, std::vector< TOPOLOGY_MISMATCH_REASON > &aMismatchReasons)
bool checkCandidateNetConsistency(const std::unordered_map< int, int > &aBaseMapping, COMPONENT *aRef, COMPONENT *aTgt, TOPOLOGY_MISMATCH_REASON &aReason, const std::unordered_set< int > &aExternalNets)
wxString GetRefDesPrefix(const wxString &aRefDes)
Get the (non-numeric) prefix from a refdes - e.g.
CITER next(CITER it)
Definition ptree.cpp:120
Collection of utility functions for component reference designators (refdes)
std::atomic< bool > * m_cancelled
Definition topo_match.h:46
std::atomic< int > * m_totalComponents
Definition topo_match.h:48
std::map< wxString, std::vector< wxString > > partsUsing
std::map< wxString, int > counts
std::map< wxString, wxString > footprintOf
std::set< wxString > repeatedRefs
std::string path
KIBIS top(path, &reporter)
KIBIS_PIN * pin
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
static thread_pool * tp
BS::priority_thread_pool thread_pool
Definition thread_pool.h:27
static const wxString traceTopoMatchDetail
static const wxString traceTopoMatch
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:683