kicad-sch-api 0.3.4__py3-none-any.whl → 0.3.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of kicad-sch-api might be problematic. Click here for more details.

Files changed (34) hide show
  1. kicad_sch_api/collections/__init__.py +21 -0
  2. kicad_sch_api/collections/base.py +296 -0
  3. kicad_sch_api/collections/components.py +422 -0
  4. kicad_sch_api/collections/junctions.py +378 -0
  5. kicad_sch_api/collections/labels.py +412 -0
  6. kicad_sch_api/collections/wires.py +407 -0
  7. kicad_sch_api/core/labels.py +348 -0
  8. kicad_sch_api/core/nets.py +310 -0
  9. kicad_sch_api/core/no_connects.py +274 -0
  10. kicad_sch_api/core/schematic.py +136 -2
  11. kicad_sch_api/core/texts.py +343 -0
  12. kicad_sch_api/core/types.py +12 -0
  13. kicad_sch_api/geometry/symbol_bbox.py +26 -32
  14. kicad_sch_api/interfaces/__init__.py +17 -0
  15. kicad_sch_api/interfaces/parser.py +76 -0
  16. kicad_sch_api/interfaces/repository.py +70 -0
  17. kicad_sch_api/interfaces/resolver.py +117 -0
  18. kicad_sch_api/parsers/__init__.py +14 -0
  19. kicad_sch_api/parsers/base.py +148 -0
  20. kicad_sch_api/parsers/label_parser.py +254 -0
  21. kicad_sch_api/parsers/registry.py +153 -0
  22. kicad_sch_api/parsers/symbol_parser.py +227 -0
  23. kicad_sch_api/parsers/wire_parser.py +99 -0
  24. kicad_sch_api/symbols/__init__.py +18 -0
  25. kicad_sch_api/symbols/cache.py +470 -0
  26. kicad_sch_api/symbols/resolver.py +367 -0
  27. kicad_sch_api/symbols/validators.py +453 -0
  28. {kicad_sch_api-0.3.4.dist-info → kicad_sch_api-0.3.5.dist-info}/METADATA +1 -1
  29. kicad_sch_api-0.3.5.dist-info/RECORD +58 -0
  30. kicad_sch_api-0.3.4.dist-info/RECORD +0 -34
  31. {kicad_sch_api-0.3.4.dist-info → kicad_sch_api-0.3.5.dist-info}/WHEEL +0 -0
  32. {kicad_sch_api-0.3.4.dist-info → kicad_sch_api-0.3.5.dist-info}/entry_points.txt +0 -0
  33. {kicad_sch_api-0.3.4.dist-info → kicad_sch_api-0.3.5.dist-info}/licenses/LICENSE +0 -0
  34. {kicad_sch_api-0.3.4.dist-info → kicad_sch_api-0.3.5.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,348 @@
1
+ """
2
+ Label element management for KiCAD schematics.
3
+
4
+ This module provides collection classes for managing label elements,
5
+ featuring fast lookup, bulk operations, and validation.
6
+ """
7
+
8
+ import logging
9
+ import uuid
10
+ from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union
11
+
12
+ from ..utils.validation import SchematicValidator, ValidationError, ValidationIssue
13
+ from .types import Point, Label
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class LabelElement:
19
+ """
20
+ Enhanced wrapper for schematic label elements with modern API.
21
+
22
+ Provides intuitive access to label properties and operations
23
+ while maintaining exact format preservation.
24
+ """
25
+
26
+ def __init__(self, label_data: Label, parent_collection: "LabelCollection"):
27
+ """
28
+ Initialize label element wrapper.
29
+
30
+ Args:
31
+ label_data: Underlying label data
32
+ parent_collection: Parent collection for updates
33
+ """
34
+ self._data = label_data
35
+ self._collection = parent_collection
36
+ self._validator = SchematicValidator()
37
+
38
+ # Core properties with validation
39
+ @property
40
+ def uuid(self) -> str:
41
+ """Label element UUID."""
42
+ return self._data.uuid
43
+
44
+ @property
45
+ def text(self) -> str:
46
+ """Label text (net name)."""
47
+ return self._data.text
48
+
49
+ @text.setter
50
+ def text(self, value: str):
51
+ """Set label text with validation."""
52
+ if not isinstance(value, str) or not value.strip():
53
+ raise ValidationError("Label text cannot be empty")
54
+ old_text = self._data.text
55
+ self._data.text = value.strip()
56
+ self._collection._update_text_index(old_text, self)
57
+ self._collection._mark_modified()
58
+
59
+ @property
60
+ def position(self) -> Point:
61
+ """Label position."""
62
+ return self._data.position
63
+
64
+ @position.setter
65
+ def position(self, value: Union[Point, Tuple[float, float]]):
66
+ """Set label position."""
67
+ if isinstance(value, tuple):
68
+ value = Point(value[0], value[1])
69
+ elif not isinstance(value, Point):
70
+ raise ValidationError(f"Position must be Point or tuple, got {type(value)}")
71
+ self._data.position = value
72
+ self._collection._mark_modified()
73
+
74
+ @property
75
+ def rotation(self) -> float:
76
+ """Label rotation in degrees."""
77
+ return self._data.rotation
78
+
79
+ @rotation.setter
80
+ def rotation(self, value: float):
81
+ """Set label rotation."""
82
+ self._data.rotation = float(value)
83
+ self._collection._mark_modified()
84
+
85
+ @property
86
+ def size(self) -> float:
87
+ """Label text size."""
88
+ return self._data.size
89
+
90
+ @size.setter
91
+ def size(self, value: float):
92
+ """Set label size with validation."""
93
+ if value <= 0:
94
+ raise ValidationError(f"Label size must be positive, got {value}")
95
+ self._data.size = float(value)
96
+ self._collection._mark_modified()
97
+
98
+ def validate(self) -> List[ValidationIssue]:
99
+ """Validate this label element."""
100
+ return self._validator.validate_label(self._data.__dict__)
101
+
102
+ def to_dict(self) -> Dict[str, Any]:
103
+ """Convert label element to dictionary representation."""
104
+ return {
105
+ "uuid": self.uuid,
106
+ "text": self.text,
107
+ "position": {"x": self.position.x, "y": self.position.y},
108
+ "rotation": self.rotation,
109
+ "size": self.size,
110
+ }
111
+
112
+ def __str__(self) -> str:
113
+ """String representation."""
114
+ return f"<Label '{self.text}' @ {self.position}>"
115
+
116
+
117
+ class LabelCollection:
118
+ """
119
+ Collection class for efficient label element management.
120
+
121
+ Provides fast lookup, filtering, and bulk operations for schematic label elements.
122
+ """
123
+
124
+ def __init__(self, labels: List[Label] = None):
125
+ """
126
+ Initialize label collection.
127
+
128
+ Args:
129
+ labels: Initial list of label data
130
+ """
131
+ self._labels: List[LabelElement] = []
132
+ self._uuid_index: Dict[str, LabelElement] = {}
133
+ self._text_index: Dict[str, List[LabelElement]] = {}
134
+ self._modified = False
135
+
136
+ # Add initial labels
137
+ if labels:
138
+ for label_data in labels:
139
+ self._add_to_indexes(LabelElement(label_data, self))
140
+
141
+ logger.debug(f"LabelCollection initialized with {len(self._labels)} labels")
142
+
143
+ def add(
144
+ self,
145
+ text: str,
146
+ position: Union[Point, Tuple[float, float]],
147
+ rotation: float = 0.0,
148
+ size: float = 1.27,
149
+ label_uuid: Optional[str] = None,
150
+ ) -> LabelElement:
151
+ """
152
+ Add a new label element to the schematic.
153
+
154
+ Args:
155
+ text: Label text (net name)
156
+ position: Label position
157
+ rotation: Label rotation in degrees
158
+ size: Label text size
159
+ label_uuid: Specific UUID for label (auto-generated if None)
160
+
161
+ Returns:
162
+ Newly created LabelElement
163
+
164
+ Raises:
165
+ ValidationError: If label data is invalid
166
+ """
167
+ # Validate inputs
168
+ if not isinstance(text, str) or not text.strip():
169
+ raise ValidationError("Label text cannot be empty")
170
+
171
+ if isinstance(position, tuple):
172
+ position = Point(position[0], position[1])
173
+ elif not isinstance(position, Point):
174
+ raise ValidationError(f"Position must be Point or tuple, got {type(position)}")
175
+
176
+ if size <= 0:
177
+ raise ValidationError(f"Label size must be positive, got {size}")
178
+
179
+ # Generate UUID if not provided
180
+ if not label_uuid:
181
+ label_uuid = str(uuid.uuid4())
182
+
183
+ # Check for duplicate UUID
184
+ if label_uuid in self._uuid_index:
185
+ raise ValidationError(f"Label UUID {label_uuid} already exists")
186
+
187
+ # Create label data
188
+ label_data = Label(
189
+ uuid=label_uuid,
190
+ position=position,
191
+ text=text.strip(),
192
+ rotation=rotation,
193
+ size=size,
194
+ )
195
+
196
+ # Create wrapper and add to collection
197
+ label_element = LabelElement(label_data, self)
198
+ self._add_to_indexes(label_element)
199
+ self._mark_modified()
200
+
201
+ logger.debug(f"Added label: {label_element}")
202
+ return label_element
203
+
204
+ def get(self, label_uuid: str) -> Optional[LabelElement]:
205
+ """Get label by UUID."""
206
+ return self._uuid_index.get(label_uuid)
207
+
208
+ def get_by_text(self, text: str) -> List[LabelElement]:
209
+ """Get all labels with the given text."""
210
+ return self._text_index.get(text, []).copy()
211
+
212
+ def remove(self, label_uuid: str) -> bool:
213
+ """
214
+ Remove label by UUID.
215
+
216
+ Args:
217
+ label_uuid: UUID of label to remove
218
+
219
+ Returns:
220
+ True if label was removed, False if not found
221
+ """
222
+ label_element = self._uuid_index.get(label_uuid)
223
+ if not label_element:
224
+ return False
225
+
226
+ # Remove from indexes
227
+ self._remove_from_indexes(label_element)
228
+ self._mark_modified()
229
+
230
+ logger.debug(f"Removed label: {label_element}")
231
+ return True
232
+
233
+ def find_by_text(self, text: str, exact: bool = True) -> List[LabelElement]:
234
+ """
235
+ Find labels by text.
236
+
237
+ Args:
238
+ text: Text to search for
239
+ exact: If True, exact match; if False, substring match
240
+
241
+ Returns:
242
+ List of matching label elements
243
+ """
244
+ if exact:
245
+ return self._text_index.get(text, []).copy()
246
+ else:
247
+ matches = []
248
+ for label_element in self._labels:
249
+ if text.lower() in label_element.text.lower():
250
+ matches.append(label_element)
251
+ return matches
252
+
253
+ def filter(self, predicate: Callable[[LabelElement], bool]) -> List[LabelElement]:
254
+ """
255
+ Filter labels by predicate function.
256
+
257
+ Args:
258
+ predicate: Function that returns True for labels to include
259
+
260
+ Returns:
261
+ List of labels matching predicate
262
+ """
263
+ return [label for label in self._labels if predicate(label)]
264
+
265
+ def bulk_update(self, criteria: Callable[[LabelElement], bool], updates: Dict[str, Any]):
266
+ """
267
+ Update multiple labels matching criteria.
268
+
269
+ Args:
270
+ criteria: Function to select labels to update
271
+ updates: Dictionary of property updates
272
+ """
273
+ updated_count = 0
274
+ for label_element in self._labels:
275
+ if criteria(label_element):
276
+ for prop, value in updates.items():
277
+ if hasattr(label_element, prop):
278
+ setattr(label_element, prop, value)
279
+ updated_count += 1
280
+
281
+ if updated_count > 0:
282
+ self._mark_modified()
283
+ logger.debug(f"Bulk updated {updated_count} label properties")
284
+
285
+ def clear(self):
286
+ """Remove all labels from collection."""
287
+ self._labels.clear()
288
+ self._uuid_index.clear()
289
+ self._text_index.clear()
290
+ self._mark_modified()
291
+
292
+ def _add_to_indexes(self, label_element: LabelElement):
293
+ """Add label to internal indexes."""
294
+ self._labels.append(label_element)
295
+ self._uuid_index[label_element.uuid] = label_element
296
+
297
+ # Add to text index
298
+ text = label_element.text
299
+ if text not in self._text_index:
300
+ self._text_index[text] = []
301
+ self._text_index[text].append(label_element)
302
+
303
+ def _remove_from_indexes(self, label_element: LabelElement):
304
+ """Remove label from internal indexes."""
305
+ self._labels.remove(label_element)
306
+ del self._uuid_index[label_element.uuid]
307
+
308
+ # Remove from text index
309
+ text = label_element.text
310
+ if text in self._text_index:
311
+ self._text_index[text].remove(label_element)
312
+ if not self._text_index[text]:
313
+ del self._text_index[text]
314
+
315
+ def _update_text_index(self, old_text: str, label_element: LabelElement):
316
+ """Update text index when label text changes."""
317
+ # Remove from old text index
318
+ if old_text in self._text_index:
319
+ self._text_index[old_text].remove(label_element)
320
+ if not self._text_index[old_text]:
321
+ del self._text_index[old_text]
322
+
323
+ # Add to new text index
324
+ new_text = label_element.text
325
+ if new_text not in self._text_index:
326
+ self._text_index[new_text] = []
327
+ self._text_index[new_text].append(label_element)
328
+
329
+ def _mark_modified(self):
330
+ """Mark collection as modified."""
331
+ self._modified = True
332
+
333
+ # Collection interface methods
334
+ def __len__(self) -> int:
335
+ """Return number of labels."""
336
+ return len(self._labels)
337
+
338
+ def __iter__(self) -> Iterator[LabelElement]:
339
+ """Iterate over labels."""
340
+ return iter(self._labels)
341
+
342
+ def __getitem__(self, index: int) -> LabelElement:
343
+ """Get label by index."""
344
+ return self._labels[index]
345
+
346
+ def __bool__(self) -> bool:
347
+ """Return True if collection has labels."""
348
+ return len(self._labels) > 0
@@ -0,0 +1,310 @@
1
+ """
2
+ Net management for KiCAD schematics.
3
+
4
+ This module provides collection classes for managing electrical nets,
5
+ featuring fast lookup, bulk operations, and validation.
6
+ """
7
+
8
+ import logging
9
+ from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Union
10
+
11
+ from ..utils.validation import SchematicValidator, ValidationError, ValidationIssue
12
+ from .types import Net
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class NetElement:
18
+ """
19
+ Enhanced wrapper for schematic net elements with modern API.
20
+
21
+ Provides intuitive access to net properties and operations
22
+ while maintaining exact format preservation.
23
+ """
24
+
25
+ def __init__(self, net_data: Net, parent_collection: "NetCollection"):
26
+ """
27
+ Initialize net element wrapper.
28
+
29
+ Args:
30
+ net_data: Underlying net data
31
+ parent_collection: Parent collection for updates
32
+ """
33
+ self._data = net_data
34
+ self._collection = parent_collection
35
+ self._validator = SchematicValidator()
36
+
37
+ # Core properties with validation
38
+ @property
39
+ def name(self) -> str:
40
+ """Net name."""
41
+ return self._data.name
42
+
43
+ @name.setter
44
+ def name(self, value: str):
45
+ """Set net name with validation."""
46
+ if not isinstance(value, str) or not value.strip():
47
+ raise ValidationError("Net name cannot be empty")
48
+ old_name = self._data.name
49
+ self._data.name = value.strip()
50
+ self._collection._update_name_index(old_name, self)
51
+ self._collection._mark_modified()
52
+
53
+ @property
54
+ def components(self) -> List[Tuple[str, str]]:
55
+ """List of component connections (reference, pin) tuples."""
56
+ return self._data.components.copy()
57
+
58
+ @property
59
+ def wires(self) -> List[str]:
60
+ """List of wire UUIDs in this net."""
61
+ return self._data.wires.copy()
62
+
63
+ @property
64
+ def labels(self) -> List[str]:
65
+ """List of label UUIDs in this net."""
66
+ return self._data.labels.copy()
67
+
68
+ def add_connection(self, reference: str, pin: str):
69
+ """Add component pin to net."""
70
+ self._data.add_connection(reference, pin)
71
+ self._collection._mark_modified()
72
+
73
+ def remove_connection(self, reference: str, pin: str):
74
+ """Remove component pin from net."""
75
+ self._data.remove_connection(reference, pin)
76
+ self._collection._mark_modified()
77
+
78
+ def add_wire(self, wire_uuid: str):
79
+ """Add wire to net."""
80
+ if wire_uuid not in self._data.wires:
81
+ self._data.wires.append(wire_uuid)
82
+ self._collection._mark_modified()
83
+
84
+ def remove_wire(self, wire_uuid: str):
85
+ """Remove wire from net."""
86
+ if wire_uuid in self._data.wires:
87
+ self._data.wires.remove(wire_uuid)
88
+ self._collection._mark_modified()
89
+
90
+ def add_label(self, label_uuid: str):
91
+ """Add label to net."""
92
+ if label_uuid not in self._data.labels:
93
+ self._data.labels.append(label_uuid)
94
+ self._collection._mark_modified()
95
+
96
+ def remove_label(self, label_uuid: str):
97
+ """Remove label from net."""
98
+ if label_uuid in self._data.labels:
99
+ self._data.labels.remove(label_uuid)
100
+ self._collection._mark_modified()
101
+
102
+ def validate(self) -> List[ValidationIssue]:
103
+ """Validate this net element."""
104
+ return self._validator.validate_net(self._data.__dict__)
105
+
106
+ def to_dict(self) -> Dict[str, Any]:
107
+ """Convert net element to dictionary representation."""
108
+ return {
109
+ "name": self.name,
110
+ "components": self.components,
111
+ "wires": self.wires,
112
+ "labels": self.labels,
113
+ }
114
+
115
+ def __str__(self) -> str:
116
+ """String representation."""
117
+ return f"<Net '{self.name}' ({len(self.components)} connections)>"
118
+
119
+
120
+ class NetCollection:
121
+ """
122
+ Collection class for efficient net management.
123
+
124
+ Provides fast lookup, filtering, and bulk operations for schematic nets.
125
+ """
126
+
127
+ def __init__(self, nets: List[Net] = None):
128
+ """
129
+ Initialize net collection.
130
+
131
+ Args:
132
+ nets: Initial list of net data
133
+ """
134
+ self._nets: List[NetElement] = []
135
+ self._name_index: Dict[str, NetElement] = {}
136
+ self._modified = False
137
+
138
+ # Add initial nets
139
+ if nets:
140
+ for net_data in nets:
141
+ self._add_to_indexes(NetElement(net_data, self))
142
+
143
+ logger.debug(f"NetCollection initialized with {len(self._nets)} nets")
144
+
145
+ def add(
146
+ self,
147
+ name: str,
148
+ components: List[Tuple[str, str]] = None,
149
+ wires: List[str] = None,
150
+ labels: List[str] = None,
151
+ ) -> NetElement:
152
+ """
153
+ Add a new net to the schematic.
154
+
155
+ Args:
156
+ name: Net name
157
+ components: Initial component connections
158
+ wires: Initial wire UUIDs
159
+ labels: Initial label UUIDs
160
+
161
+ Returns:
162
+ Newly created NetElement
163
+
164
+ Raises:
165
+ ValidationError: If net data is invalid
166
+ """
167
+ # Validate inputs
168
+ if not isinstance(name, str) or not name.strip():
169
+ raise ValidationError("Net name cannot be empty")
170
+
171
+ name = name.strip()
172
+
173
+ # Check for duplicate name
174
+ if name in self._name_index:
175
+ raise ValidationError(f"Net name {name} already exists")
176
+
177
+ # Create net data
178
+ net_data = Net(
179
+ name=name,
180
+ components=components or [],
181
+ wires=wires or [],
182
+ labels=labels or [],
183
+ )
184
+
185
+ # Create wrapper and add to collection
186
+ net_element = NetElement(net_data, self)
187
+ self._add_to_indexes(net_element)
188
+ self._mark_modified()
189
+
190
+ logger.debug(f"Added net: {net_element}")
191
+ return net_element
192
+
193
+ def get(self, name: str) -> Optional[NetElement]:
194
+ """Get net by name."""
195
+ return self._name_index.get(name)
196
+
197
+ def remove(self, name: str) -> bool:
198
+ """
199
+ Remove net by name.
200
+
201
+ Args:
202
+ name: Name of net to remove
203
+
204
+ Returns:
205
+ True if net was removed, False if not found
206
+ """
207
+ net_element = self._name_index.get(name)
208
+ if not net_element:
209
+ return False
210
+
211
+ # Remove from indexes
212
+ self._remove_from_indexes(net_element)
213
+ self._mark_modified()
214
+
215
+ logger.debug(f"Removed net: {net_element}")
216
+ return True
217
+
218
+ def find_by_component(self, reference: str, pin: Optional[str] = None) -> List[NetElement]:
219
+ """
220
+ Find nets connected to a component.
221
+
222
+ Args:
223
+ reference: Component reference
224
+ pin: Specific pin (if None, returns all nets for component)
225
+
226
+ Returns:
227
+ List of matching net elements
228
+ """
229
+ matches = []
230
+ for net_element in self._nets:
231
+ for comp_ref, comp_pin in net_element.components:
232
+ if comp_ref == reference and (pin is None or comp_pin == pin):
233
+ matches.append(net_element)
234
+ break
235
+ return matches
236
+
237
+ def filter(self, predicate: Callable[[NetElement], bool]) -> List[NetElement]:
238
+ """
239
+ Filter nets by predicate function.
240
+
241
+ Args:
242
+ predicate: Function that returns True for nets to include
243
+
244
+ Returns:
245
+ List of nets matching predicate
246
+ """
247
+ return [net for net in self._nets if predicate(net)]
248
+
249
+ def bulk_update(self, criteria: Callable[[NetElement], bool], updates: Dict[str, Any]):
250
+ """
251
+ Update multiple nets matching criteria.
252
+
253
+ Args:
254
+ criteria: Function to select nets to update
255
+ updates: Dictionary of property updates
256
+ """
257
+ updated_count = 0
258
+ for net_element in self._nets:
259
+ if criteria(net_element):
260
+ for prop, value in updates.items():
261
+ if hasattr(net_element, prop):
262
+ setattr(net_element, prop, value)
263
+ updated_count += 1
264
+
265
+ if updated_count > 0:
266
+ self._mark_modified()
267
+ logger.debug(f"Bulk updated {updated_count} net properties")
268
+
269
+ def clear(self):
270
+ """Remove all nets from collection."""
271
+ self._nets.clear()
272
+ self._name_index.clear()
273
+ self._mark_modified()
274
+
275
+ def _add_to_indexes(self, net_element: NetElement):
276
+ """Add net to internal indexes."""
277
+ self._nets.append(net_element)
278
+ self._name_index[net_element.name] = net_element
279
+
280
+ def _remove_from_indexes(self, net_element: NetElement):
281
+ """Remove net from internal indexes."""
282
+ self._nets.remove(net_element)
283
+ del self._name_index[net_element.name]
284
+
285
+ def _update_name_index(self, old_name: str, net_element: NetElement):
286
+ """Update name index when net name changes."""
287
+ if old_name in self._name_index:
288
+ del self._name_index[old_name]
289
+ self._name_index[net_element.name] = net_element
290
+
291
+ def _mark_modified(self):
292
+ """Mark collection as modified."""
293
+ self._modified = True
294
+
295
+ # Collection interface methods
296
+ def __len__(self) -> int:
297
+ """Return number of nets."""
298
+ return len(self._nets)
299
+
300
+ def __iter__(self) -> Iterator[NetElement]:
301
+ """Iterate over nets."""
302
+ return iter(self._nets)
303
+
304
+ def __getitem__(self, index: int) -> NetElement:
305
+ """Get net by index."""
306
+ return self._nets[index]
307
+
308
+ def __bool__(self) -> bool:
309
+ """Return True if collection has nets."""
310
+ return len(self._nets) > 0