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 (C) Kicad Developers, see change_log.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, you may find one here:
18 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
19 * or you may search the http://www.gnu.org website for the version 2 license,
20 * or you may write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
24#include <cstdio>
25#include <cstdlib>
26#include <cmath>
27#include <string>
28#include <vector>
29#include <algorithm>
30#include <cassert>
31#include <map>
32#include <set>
33#include <cctype>
34
35#include <pad.h>
36#include <footprint.h>
37#include <refdes_utils.h>
38#include <wx/string.h>
39#include <wx/log.h>
40
41#include "topo_match.h"
42
43
44static const wxString traceTopoMatch = wxT( "TOPO_MATCH" );
45
46namespace TMATCH
47{
48
49bool PIN::IsIsomorphic( const PIN& b ) const
50{
51 if( m_conns.size() != b.m_conns.size() )
52 {
53 wxLogTrace( traceTopoMatch, wxT("[conns mismatch n1 %d n2 %d c-ref %d c-other %d thispin %s-%s otherpin %s-%s"),
54 m_netcode,
55 b.m_netcode,
56 (int) m_conns.size(),
57 (int) b.m_conns.size(),
59 m_ref,
61 b.m_ref );
62
63 for( auto c : m_conns )
64 {
65 wxLogTrace( traceTopoMatch, wxT("%s-%s "), c->m_parent->m_reference, c->m_ref );
66 }
67
68 wxLogTrace( traceTopoMatch, wxT("||") );
69
70 for( auto c : b.m_conns )
71 {
72 wxLogTrace( traceTopoMatch, wxT("%s-%s "), c->m_parent->m_reference, c->m_ref );
73 }
74
75
76 wxLogTrace( traceTopoMatch, wxT("] ") );
77 return false;
78 }
79
80 if( m_conns.empty() )
81 {
82 wxLogTrace( traceTopoMatch, wxT("[conns empty]") );
83 return true;
84 }
85
86 std::vector<bool> matches( m_conns.size() );
87
88 for( int i = 0; i < m_conns.size(); i++ )
89 matches[i] = false;
90
91 int nref = 0;
92
93 for( auto& cref : m_conns )
94 {
95 //printf("[CREF: %s]", cref->Format().c_str().AsChar() );
96 for( int i = 0; i < m_conns.size(); i++ )
97 {
98 if( b.m_conns[i]->IsTopologicallySimilar( *cref ) )
99 {
100 //printf("[CMATCH: %s]", b.m_conns[i]->Format().c_str().AsChar() );
101 matches[nref] = true;
102 break;
103 }
104 }
105
106 nref++;
107 }
108
109 for( int i = 0; i < m_conns.size(); i++ )
110 {
111 if( !matches[i] )
112 {
113 return false;
114 }
115 }
116
117 return true;
118}
119
120// fixme: terrible performance, but computers are fast these days, ain't they? :D
121bool checkIfPadNetsMatch( BACKTRACK_STAGE& aMatches, CONNECTION_GRAPH* aRefGraph, COMPONENT* aRef, COMPONENT* aTgt )
122{
123 std::map<PIN*, PIN*> pairs;
124 std::vector<PIN*> pref, ptgt;
125
126 // GetMatchingComponentPairs() returns target->reference map
127 for( auto& m : aMatches.GetMatchingComponentPairs() )
128 {
129 for( PIN* p : m.second->Pins() )
130 {
131 pref.push_back( p );
132 }
133
134 for( PIN* p : m.first->Pins() )
135 {
136 ptgt.push_back( p );
137 }
138 }
139
140 for( PIN* p : aRef->Pins() )
141 {
142 pref.push_back( p );
143 }
144
145 for( PIN* p : aTgt->Pins() )
146 {
147 ptgt.push_back( p );
148 }
149
150 if( pref.size() != ptgt.size() )
151 {
152 return false;
153 }
154
155 for( unsigned int i = 0; i < pref.size(); i++ )
156 {
157 pairs[pref[i]] = ptgt[i];
158 }
159
160 for( PIN* refPin : aRef->Pins() )
161 {
162 wxLogTrace( traceTopoMatch, wxT("pad %s-%s: ") , aRef->GetParent()->GetReferenceAsString() , refPin->GetReference() );
163
164 std::optional<int> prevNet;
165
166 for( COMPONENT* refCmp : aRefGraph->Components() )
167 {
168 for( PIN* ppin : refCmp->Pins() )
169 {
170 if ( ppin->GetNetCode() != refPin->GetNetCode() )
171 continue;
172
173 wxLogTrace( traceTopoMatch, wxT("{ref %s-%s:%d} "), ppin->GetParent()->GetParent()->GetReferenceAsString(), ppin->GetReference(), ppin->GetNetCode() );
174
175 auto tpin = pairs.find( ppin );
176
177 if( tpin != pairs.end() )
178 {
179 int nc = tpin->second->GetNetCode();
180
181// printf("%s-%s:%d ", tpin->second->GetParent()->GetParent()->GetReferenceAsString(), tpin->second->GetReference().c_str().AsChar(), tpin->second->GetNetCode() );
182
183 if( prevNet && ( *prevNet != nc ) )
184 {
185 wxLogTrace( traceTopoMatch, wxT("nets inconsistent\n") );
186 return false;
187 }
188
189 prevNet = nc;
190 }
191 }
192 }
193 }
194
195 return true;
196}
197
198
199std::vector<COMPONENT*>
201{
202 std::vector<COMPONENT*> matches;
203 for( auto cmpTarget : m_components )
204 {
205 // already matched to sth? move on.
206 if( partialMatches.m_locked.find( cmpTarget ) != partialMatches.m_locked.end() )
207 {
208 continue;
209 }
210
211 wxLogTrace( traceTopoMatch, wxT("Check '%s'/'%s' "), aRef->m_reference, cmpTarget->m_reference );
212
213 // first, a basic heuristic (reference prefix, pin count & footprint) followed by a pin connection topology check
214 if( aRef->MatchesWith( cmpTarget ) )
215 {
216 // then a net integrity check (expensive because of poor optimization)
217 if( checkIfPadNetsMatch( partialMatches, aRefGraph, aRef, cmpTarget ) )
218 {
219 wxLogTrace( traceTopoMatch, wxT("match!\n") );
220 matches.push_back( cmpTarget );
221 }
222 else
223 {
224 wxLogTrace( traceTopoMatch, wxT("Reject [net topo mismatch]\n") );
225 }
226 }
227 else
228 {
229 wxLogTrace( traceTopoMatch, wxT("reject\n") );
230 }
231
232
233
234 }
235
236 return matches;
237}
238
240{
241std::sort( m_pins.begin(), m_pins.end(),
242 []( PIN* a, PIN* b )
243 {
244 return a->GetReference() < b->GetReference();
245 } );
246}
247
249{
250 std::map<int, std::vector<PIN*>> nets;
251
253
254 for( auto c : m_components )
255 {
256 c->sortPinsByName();
257
258 for( auto p : c->Pins() )
259 {
260 if( p->GetNetCode() > 0 )
261 nets[p->GetNetCode()].push_back( p );
262 }
263 }
264
265 for( auto iter : nets )
266 {
267 wxLogTrace( traceTopoMatch, wxT("net %d: %d connections\n"), iter.first, (int) iter.second.size() );
268 for( auto p : iter.second )
269 {
270 for( auto p2 : iter.second )
271 if( p != p2 && !alg::contains( p->m_conns, p2 ) )
272 {
273 p->m_conns.push_back( p2 );
274 }
275 }
276 }
277
278/* for( auto c : m_components )
279 for( auto p : c->Pins() )
280 {
281 printf("pin %s: \n", p->m_ref.c_str().AsChar() );
282
283 for( auto c : p->m_conns )
284 printf( "%s ", c->m_ref.c_str().AsChar() );
285 printf("\n");
286 }
287 */
288}
289
290
292 COMPONENT_MATCHES& aResult )
293{
294 std::vector<BACKTRACK_STAGE> stack;
295 BACKTRACK_STAGE top;
296
297 if( m_components.empty()|| aTarget->m_components.empty() )
298 return ST_EMPTY;
299
300 if( m_components.size() != aTarget->m_components.size() )
302
303 top.m_ref = m_components.front();
304 top.m_refIndex = 0;
305
306 stack.push_back( top );
307
308 bool matchFound = false;
309 int nloops = 0;
310 while( !stack.empty() )
311 {
312 nloops++;
313 auto& current = stack.back();
314
315 for( auto it = current.m_locked.begin(); it != current.m_locked.end(); it++ )
316 {
317 if (it->second == current.m_ref)
318 {
319 wxLogTrace( traceTopoMatch, wxT("stk: Remove %s from locked\n"), current.m_ref->m_reference );
320 current.m_locked.erase( it );
321 break;
322 }
323 }
324
325 if( nloops >= c_ITER_LIMIT )
326 {
327 wxLogTrace( traceTopoMatch, wxT("stk: Iter cnt exceeded\n") );
329 }
330
331 if( current.m_currentMatch < 0 )
332 {
333 current.m_matches = aTarget->findMatchingComponents( this, current.m_ref, current );
334 current.m_currentMatch = 0;
335 }
336
337 wxLogTrace( traceTopoMatch, wxT("stk: Current '%s' stack %d cm %d/%d locked %d/%d\n" ),
338 current.m_ref->m_reference, (int) stack.size(),
339 current.m_currentMatch, (int) current.m_matches.size(),
340 (int) current.m_locked.size(), (int) m_components.size() );
341
342 if ( current.m_matches.empty() )
343 {
344 wxLogTrace( traceTopoMatch, wxT("stk: No matches at all, going up [level=%d]\n"), (int) stack.size() );
345 stack.pop_back();
346 continue;
347 }
348
349 if( current.m_currentMatch >= 0 && current.m_currentMatch >= current.m_matches.size() )
350 {
351 wxLogTrace( traceTopoMatch, wxT("stk: No more matches, going up [level=%d]\n"), (int) stack.size() );
352 stack.pop_back();
353 continue;
354 }
355
356 auto& match = current.m_matches[current.m_currentMatch];
357
358 wxLogTrace( traceTopoMatch, wxT("stk: candidate '%s', match list : ( "),
359 current.m_matches[current.m_currentMatch]->m_reference,
360 current.m_refIndex );
361
362 for( auto m : current.m_matches )
363 wxLogTrace( traceTopoMatch, wxT("%s "), m->GetParent()->GetReferenceAsString() );
364
365 wxLogTrace( traceTopoMatch, wxT("\n") );
366
367
368
369 current.m_currentMatch++;
370 current.m_locked[match] = current.m_ref;
371
372
373 if( current.m_locked.size() == m_components.size() )
374 {
375 current.m_nloops = nloops;
376
377 aResult.clear();
378
379 for( auto iter : current.m_locked )
380 aResult[ iter.second->GetParent() ] = iter.first->GetParent();
381
382 return ST_OK;
383 }
384
385
386 BACKTRACK_STAGE next( current );
387 next.m_currentMatch = -1;
388 next.m_ref = m_components[current.m_refIndex + 1];
389 next.m_refIndex = current.m_refIndex + 1;
390
391 stack.push_back( next );
392 };
393
394
396}
397
398#if 0
399int main()
400{
401 FILE * f = fopen("connectivity.dump","rb" );
402 auto cgRef = loadCGraph(f);
403 auto cgTarget = loadCGraph(f);
404
405 cgRef->buildConnectivity();
406 cgTarget->buildConnectivity();
407
408 int attempts = 0;
409 int max_loops = 0;
410
411 for( ;; )
412 {
413 cgRef->shuffle();
414 cgTarget->shuffle();
415
416 const BacktrackStage latest = cgRef->matchCGraphs( cgTarget );
417
418 if( !latest.locked.size() )
419 {
420 printf("MATCH FAIL\n");
421 break;
422 }
423
424 //printf("loops: %d\n", latest.nloops );
425 //printf("Locked: %d\n", latest.locked.size() );
426
427 //if (matchFound)
428 //{
429 // for( auto& iter : latest.locked )
430 //{
431 // printf("%-10s : %-10s\n", iter.first->reference.c_str(), iter.second->reference.c_str() );
432 //}
433
434 //}
435
436 if( latest.nloops > max_loops )
437 {
438 max_loops = latest.nloops;
439 }
440
441 if (attempts % 10000 == 0)
442 {
443 printf("attempts: %d maxloops: %d\n", attempts, max_loops );
444 }
445
446 attempts++;
447
448 }
449
450 fclose(f);
451
452 return 0;
453}
454
455#endif
456
457COMPONENT::COMPONENT( const wxString& aRef, FOOTPRINT* aParentFp, std::optional<VECTOR2I> aRaOffset ) :
458 m_reference( aRef ), m_parentFootprint( aParentFp ), m_raOffset( aRaOffset )
459{
461}
462
463bool COMPONENT::IsSameKind( const COMPONENT& b ) const
464{
466}
467
469{
470 m_pins.push_back( aPin );
471 aPin->SetParent( this );
472}
473
475{
476 if( GetPinCount() != b->GetPinCount() )
477 {
478 return false;
479 }
480
482 {
483 return false;
484 }
485
486 if( m_prefix != b->m_prefix )
487 {
488 return false;
489 }
490
491 for( int pin = 0; pin < b->GetPinCount(); pin++ )
492 {
493 if( !b->m_pins[pin]->IsIsomorphic( *m_pins[pin] ) )
494 {
495 return false;
496 }
497
498 }
499
500 return true;
501}
502
504{
505 auto cmp = new COMPONENT( aFp->GetReference(), aFp );;
506
507 for( auto pad : aFp->Pads() )
508 {
509 auto pin = new PIN( );
510 pin->m_netcode = pad->GetNetCode();
511 pin->m_ref = pad->GetNumber();
512 cmp->AddPin( pin );
513 }
514
515 m_components.push_back( cmp );
516}
517
518std::unique_ptr<CONNECTION_GRAPH> CONNECTION_GRAPH::BuildFromFootprintSet( const std::set<FOOTPRINT*>& aFps )
519{
520 auto cgraph = std::make_unique<CONNECTION_GRAPH>();
521 VECTOR2I ref(0, 0);
522
523 if( aFps.size() > 0 )
524 ref = (*aFps.begin())->GetPosition();
525
526 for( auto fp : aFps )
527 {
528 cgraph->AddFootprint( fp, fp->GetPosition() - ref );
529 }
530
531 cgraph->BuildConnectivity();
532
533 return std::move(cgraph);
534}
535
536
538{
539
540}
541
542
544{
545 for( COMPONENT* fp : m_components )
546 {
547 delete fp;
548 }
549}
550
551
553{
554 for( PIN* p : m_pins )
555 {
556 delete p;
557 }
558}
559
560
561}; // namespace TMATCH
std::deque< PAD * > & Pads()
Definition: footprint.h:206
const LIB_ID & GetFPID() const
Definition: footprint.h:248
wxString GetReferenceAsString() const
Definition: footprint.h:611
const wxString & GetReference() const
Definition: footprint.h:602
const std::map< COMPONENT *, COMPONENT * > & GetMatchingComponentPairs() const
Definition: topo_match.h:138
std::map< COMPONENT *, COMPONENT * > m_locked
Definition: topo_match.h:145
bool MatchesWith(COMPONENT *b)
Definition: topo_match.cpp:474
bool IsSameKind(const COMPONENT &b) const
Definition: topo_match.cpp:463
int GetPinCount() const
Definition: topo_match.h:56
COMPONENT(const wxString &aRef, FOOTPRINT *aParentFp, std::optional< VECTOR2I > aRaOffset=std::optional< VECTOR2I >())
Definition: topo_match.cpp:457
FOOTPRINT * m_parentFootprint
Definition: topo_match.h:71
wxString m_prefix
Definition: topo_match.h:70
void AddPin(PIN *p)
Definition: topo_match.cpp:468
std::vector< PIN * > & Pins()
Definition: topo_match.h:58
wxString m_reference
Definition: topo_match.h:69
std::vector< PIN * > m_pins
Definition: topo_match.h:72
FOOTPRINT * GetParent() const
Definition: topo_match.h:59
STATUS FindIsomorphism(CONNECTION_GRAPH *target, COMPONENT_MATCHES &result)
Definition: topo_match.cpp:291
std::vector< COMPONENT * > & Components()
Definition: topo_match.h:172
std::vector< COMPONENT * > m_components
Definition: topo_match.h:189
std::vector< COMPONENT * > findMatchingComponents(CONNECTION_GRAPH *aRefGraph, COMPONENT *ref, BACKTRACK_STAGE &partialMatches)
Definition: topo_match.cpp:200
void AddFootprint(FOOTPRINT *aFp, const VECTOR2I &aOffset)
Definition: topo_match.cpp:503
static std::unique_ptr< CONNECTION_GRAPH > BuildFromFootprintSet(const std::set< FOOTPRINT * > &aFps)
Definition: topo_match.cpp:518
std::vector< PIN * > m_conns
Definition: topo_match.h:112
void SetParent(COMPONENT *parent)
Definition: topo_match.h:83
COMPONENT * m_parent
Definition: topo_match.h:111
bool IsIsomorphic(const PIN &b) const
Definition: topo_match.cpp:49
wxString m_ref
Definition: topo_match.h:109
main()
std::map< FOOTPRINT *, FOOTPRINT * > COMPONENT_MATCHES
Definition: topo_match.h:149
bool checkIfPadNetsMatch(BACKTRACK_STAGE &aMatches, CONNECTION_GRAPH *aRefGraph, COMPONENT *aRef, COMPONENT *aTgt)
Definition: topo_match.cpp:121
wxString GetRefDesPrefix(const wxString &aRefDes)
Get the (non-numeric) prefix from a refdes - e.g.
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition: kicad_algo.h:100
CITER next(CITER it)
Definition: ptree.cpp:126
Collection of utility functions for component reference designators (refdes)
static const wxString traceTopoMatch
Definition: topo_match.cpp:44