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 auto& match = current.m_matches[current.m_currentMatch];
350
351 if( current.m_currentMatch >= 0 && current.m_currentMatch >= current.m_matches.size() )
352 {
353 wxLogTrace( traceTopoMatch, wxT("stk: No more matches, going up [level=%d]\n"), (int) stack.size() );
354 stack.pop_back();
355 continue;
356 }
357
358
359
360 wxLogTrace( traceTopoMatch, wxT("stk: candidate '%s', match list : ( "),
361 current.m_matches[current.m_currentMatch]->m_reference,
362 current.m_refIndex );
363
364 for( auto m : current.m_matches )
365 wxLogTrace( traceTopoMatch, wxT("%s "), m->GetParent()->GetReferenceAsString() );
366
367 wxLogTrace( traceTopoMatch, wxT("\n") );
368
369
370
371 current.m_currentMatch++;
372 current.m_locked[match] = current.m_ref;
373
374
375 if( current.m_locked.size() == m_components.size() )
376 {
377 current.m_nloops = nloops;
378
379 aResult.clear();
380
381 for( auto iter : current.m_locked )
382 aResult[ iter.second->GetParent() ] = iter.first->GetParent();
383
384 return ST_OK;
385 }
386
387
388 BACKTRACK_STAGE next( current );
389 next.m_currentMatch = -1;
390 next.m_ref = m_components[current.m_refIndex + 1];
391 next.m_refIndex = current.m_refIndex + 1;
392
393 stack.push_back( next );
394 };
395
396
398}
399
400#if 0
401int main()
402{
403 FILE * f = fopen("connectivity.dump","rb" );
404 auto cgRef = loadCGraph(f);
405 auto cgTarget = loadCGraph(f);
406
407 cgRef->buildConnectivity();
408 cgTarget->buildConnectivity();
409
410 int attempts = 0;
411 int max_loops = 0;
412
413 for( ;; )
414 {
415 cgRef->shuffle();
416 cgTarget->shuffle();
417
418 const BacktrackStage latest = cgRef->matchCGraphs( cgTarget );
419
420 if( !latest.locked.size() )
421 {
422 printf("MATCH FAIL\n");
423 break;
424 }
425
426 //printf("loops: %d\n", latest.nloops );
427 //printf("Locked: %d\n", latest.locked.size() );
428
429 //if (matchFound)
430 //{
431 // for( auto& iter : latest.locked )
432 //{
433 // printf("%-10s : %-10s\n", iter.first->reference.c_str(), iter.second->reference.c_str() );
434 //}
435
436 //}
437
438 if( latest.nloops > max_loops )
439 {
440 max_loops = latest.nloops;
441 }
442
443 if (attempts % 10000 == 0)
444 {
445 printf("attempts: %d maxloops: %d\n", attempts, max_loops );
446 }
447
448 attempts++;
449
450 }
451
452 fclose(f);
453
454 return 0;
455}
456
457#endif
458
459COMPONENT::COMPONENT( const wxString& aRef, FOOTPRINT* aParentFp, std::optional<VECTOR2I> aRaOffset ) :
460 m_reference( aRef ), m_parentFootprint( aParentFp ), m_raOffset( aRaOffset )
461{
463}
464
465bool COMPONENT::IsSameKind( const COMPONENT& b ) const
466{
468}
469
471{
472 m_pins.push_back( aPin );
473 aPin->SetParent( this );
474}
475
477{
478 if( GetPinCount() != b->GetPinCount() )
479 {
480 return false;
481 }
482
484 {
485 return false;
486 }
487
488 if( m_prefix != b->m_prefix )
489 {
490 return false;
491 }
492
493 for( int pin = 0; pin < b->GetPinCount(); pin++ )
494 {
495 if( !b->m_pins[pin]->IsIsomorphic( *m_pins[pin] ) )
496 {
497 return false;
498 }
499
500 }
501
502 return true;
503}
504
506{
507 auto cmp = new COMPONENT( aFp->GetReference(), aFp );;
508
509 for( auto pad : aFp->Pads() )
510 {
511 auto pin = new PIN( );
512 pin->m_netcode = pad->GetNetCode();
513 pin->m_ref = pad->GetNumber();
514 cmp->AddPin( pin );
515 }
516
517 m_components.push_back( cmp );
518}
519
520std::unique_ptr<CONNECTION_GRAPH> CONNECTION_GRAPH::BuildFromFootprintSet( const std::set<FOOTPRINT*>& aFps )
521{
522 auto cgraph = std::make_unique<CONNECTION_GRAPH>();
523 VECTOR2I ref(0, 0);
524
525 if( aFps.size() > 0 )
526 ref = (*aFps.begin())->GetPosition();
527
528 for( auto fp : aFps )
529 {
530 cgraph->AddFootprint( fp, fp->GetPosition() - ref );
531 }
532
533 cgraph->BuildConnectivity();
534
535 return std::move(cgraph);
536}
537
538
540{
541
542}
543
544
546{
547 for( COMPONENT* fp : m_components )
548 {
549 delete fp;
550 }
551}
552
553
555{
556 for( PIN* p : m_pins )
557 {
558 delete p;
559 }
560}
561
562
563}; // namespace TMATCH
std::deque< PAD * > & Pads()
Definition: footprint.h:205
const LIB_ID & GetFPID() const
Definition: footprint.h:247
wxString GetReferenceAsString() const
Definition: footprint.h:610
const wxString & GetReference() const
Definition: footprint.h:601
const std::map< COMPONENT *, COMPONENT * > & GetMatchingComponentPairs() const
Definition: topo_match.h:137
std::map< COMPONENT *, COMPONENT * > m_locked
Definition: topo_match.h:144
bool MatchesWith(COMPONENT *b)
Definition: topo_match.cpp:476
bool IsSameKind(const COMPONENT &b) const
Definition: topo_match.cpp:465
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:459
FOOTPRINT * m_parentFootprint
Definition: topo_match.h:71
wxString m_prefix
Definition: topo_match.h:70
void AddPin(PIN *p)
Definition: topo_match.cpp:470
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:171
std::vector< COMPONENT * > m_components
Definition: topo_match.h:188
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:505
static std::unique_ptr< CONNECTION_GRAPH > BuildFromFootprintSet(const std::set< FOOTPRINT * > &aFps)
Definition: topo_match.cpp:520
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:148
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