ZLayout EDA Library v1.0.0
Advanced Electronic Design Automation Layout Library with Bilingual Documentation
Loading...
Searching...
No Matches
component_db.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""
3EDA组件数据库系统(简化版)
4使用SQLite存储组件参数,支持灵活的组件定义和用户自定义模块
5"""
6
7import sqlite3
8import json
9import uuid
10from typing import Dict, List, Any, Optional
11from dataclasses import dataclass
12
13@dataclass
15 """组件规格定义"""
16 name: str
17 category: str # 'passive', 'active', 'digital', 'analog', 'mixed', 'custom'
18 parameters: Dict[str, Any]
19 electrical_params: Dict[str, Any]
20 physical_params: Dict[str, Any]
21 technology_node: str = "28nm"
22 manufacturer: str = "Generic"
23 description: str = ""
24 tags: Optional[List[str]] = None
25
26 def __post_init__(self):
27 if self.tags is None:
28 self.tags = []
29
31 """组件数据库管理器"""
32
33 def __init__(self, db_path: str = "components.db"):
34 self.db_path = db_path
35 self.conn = sqlite3.connect(self.db_path)
36 self._init_database()
37
38 def _init_database(self):
39 """初始化数据库"""
40 self.conn.execute('''
41 CREATE TABLE IF NOT EXISTS components (
42 id TEXT PRIMARY KEY,
43 name TEXT NOT NULL,
44 category TEXT NOT NULL,
45 parameters TEXT NOT NULL,
46 electrical_params TEXT NOT NULL,
47 physical_params TEXT NOT NULL,
48 technology_node TEXT DEFAULT '28nm',
49 manufacturer TEXT DEFAULT 'Generic',
50 description TEXT DEFAULT '',
51 tags TEXT DEFAULT '[]'
52 )
53 ''')
54
55 self.conn.execute('''
56 CREATE TABLE IF NOT EXISTS modules (
57 id TEXT PRIMARY KEY,
58 name TEXT NOT NULL,
59 description TEXT DEFAULT '',
60 components TEXT NOT NULL,
61 connections TEXT NOT NULL
62 )
63 ''')
64
65 self.conn.commit()
67
69 """填充基本组件库"""
70 # 检查是否已有数据
71 cursor = self.conn.execute("SELECT COUNT(*) FROM components")
72 if cursor.fetchone()[0] > 0:
73 return
74
75 # 基本无源器件
76 basic_components = [
78 name="resistor_1k",
79 category="passive",
80 parameters={
81 "resistance": 1000,
82 "tolerance": 0.05,
83 "power_rating": 0.25
84 },
85 electrical_params={
86 "max_voltage": 200,
87 "temperature_coefficient": 100
88 },
89 physical_params={
90 "package": "0603",
91 "area": 1.28 # mm²
92 },
93 description="1kΩ电阻",
94 tags=["passive", "resistor"]
95 ),
97 name="capacitor_100nf",
98 category="passive",
99 parameters={
100 "capacitance": 100e-9,
101 "tolerance": 0.1,
102 "voltage_rating": 25
103 },
104 electrical_params={
105 "esr": 0.01,
106 "temperature_range": [-55, 125]
107 },
108 physical_params={
109 "package": "0402",
110 "area": 0.5 # mm²
111 },
112 description="100nF陶瓷电容",
113 tags=["passive", "capacitor"]
114 ),
116 name="inductor_10uh",
117 category="passive",
118 parameters={
119 "inductance": 10e-6,
120 "tolerance": 0.2,
121 "current_rating": 1.0
122 },
123 electrical_params={
124 "dc_resistance": 0.1,
125 "q_factor": 50
126 },
127 physical_params={
128 "package": "0603",
129 "area": 1.28 # mm²
130 },
131 description="10μH电感",
132 tags=["passive", "inductor"]
133 )
134 ]
135
136 for comp in basic_components:
137 self.add_component(comp)
138
139 def add_component(self, spec: ComponentSpec) -> str:
140 """添加组件到数据库"""
141 component_id = str(uuid.uuid4())
142
143 self.conn.execute('''
144 INSERT INTO components (id, name, category, parameters, electrical_params,
145 physical_params, technology_node, manufacturer, description, tags)
146 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
147 ''', (
148 component_id,
149 spec.name,
150 spec.category,
151 json.dumps(spec.parameters),
152 json.dumps(spec.electrical_params),
153 json.dumps(spec.physical_params),
154 spec.technology_node,
155 spec.manufacturer,
156 spec.description,
157 json.dumps(spec.tags)
158 ))
159
160 self.conn.commit()
161 return component_id
162
163 def get_component(self, component_id: str) -> Optional[ComponentSpec]:
164 """获取组件规格"""
165 cursor = self.conn.execute(
166 "SELECT * FROM components WHERE id = ?", (component_id,)
167 )
168 row = cursor.fetchone()
169
170 if not row:
171 return None
172
173 return ComponentSpec(
174 name=row[1],
175 category=row[2],
176 parameters=json.loads(row[3]),
177 electrical_params=json.loads(row[4]),
178 physical_params=json.loads(row[5]),
179 technology_node=row[6],
180 manufacturer=row[7],
181 description=row[8],
182 tags=json.loads(row[9])
183 )
184
186 category: Optional[str] = None,
187 name_pattern: Optional[str] = None) -> List[Dict[str, Any]]:
188 """搜索组件"""
189 query = "SELECT id, name, category, description FROM components WHERE 1=1"
190 params = []
191
192 if category:
193 query += " AND category = ?"
194 params.append(category)
195
196 if name_pattern:
197 query += " AND name LIKE ?"
198 params.append(f"%{name_pattern}%")
199
200 cursor = self.conn.execute(query, params)
201 results = []
202
203 for row in cursor.fetchall():
204 results.append({
205 "id": row[0],
206 "name": row[1],
207 "category": row[2],
208 "description": row[3]
209 })
210
211 return results
212
214 name: str,
215 parameters: Dict[str, Any],
216 electrical_params: Optional[Dict[str, Any]] = None,
217 physical_params: Optional[Dict[str, Any]] = None,
218 description: str = "") -> str:
219 """创建自定义组件"""
220 spec = ComponentSpec(
221 name=name,
222 category="custom",
223 parameters=parameters,
224 electrical_params=electrical_params if electrical_params else {},
225 physical_params=physical_params if physical_params else {},
226 description=description,
227 tags=["custom"]
228 )
229
230 return self.add_component(spec)
231
233 name: str,
234 components: List[str],
235 connections: List[Dict[str, Any]],
236 description: str = "") -> str:
237 """创建模块(包括中间模块)"""
238 module_id = str(uuid.uuid4())
239
240 # 如果没有名称,生成一个
241 if not name:
242 name = f"module_{module_id[:8]}"
243
244 self.conn.execute('''
245 INSERT INTO modules (id, name, description, components, connections)
246 VALUES (?, ?, ?, ?, ?)
247 ''', (
248 module_id,
249 name,
250 description,
251 json.dumps(components),
252 json.dumps(connections)
253 ))
254
255 self.conn.commit()
256 return module_id
257
258 def get_component_library(self) -> Dict[str, Any]:
259 """获取组件库概览"""
260 cursor = self.conn.execute('''
261 SELECT category, COUNT(*) as count
262 FROM components
263 GROUP BY category
264 ''')
265
266 library = {}
267 for row in cursor.fetchall():
268 category, count = row
269 library[category] = count
270
271 return library
272
273 def close(self):
274 """关闭数据库连接"""
275 if self.conn:
276 self.conn.close()
277
278# 使用示例
279if __name__ == "__main__":
280 # 创建数据库
281 db = ComponentDatabase("eda_components.db")
282
283 # 查看基本组件库
284 print("=== 基本组件库 ===")
285 library = db.get_component_library()
286 for category, count in library.items():
287 print(f"{category}: {count} 个组件")
288
289 # 搜索组件
290 print("\n=== 搜索无源器件 ===")
291 passive_components = db.search_components(category="passive")
292 for comp in passive_components:
293 print(f"- {comp['name']}: {comp['description']}")
294
295 # 创建自定义组件
296 print("\n=== 创建自定义组件 ===")
297 custom_id = db.create_custom_component(
298 name="custom_op_amp",
299 parameters={
300 "gain": 100,
301 "bandwidth": 1e6,
302 "slew_rate": 1e6
303 },
304 electrical_params={
305 "supply_voltage": [3.3, 5.0],
306 "input_impedance": 1e12
307 },
308 description="自定义运算放大器"
309 )
310 print(f"创建自定义组件ID: {custom_id}")
311
312 # 创建中间模块
313 print("\n=== 创建中间模块 ===")
314 module_id = db.create_module(
315 name="amplifier_stage",
316 components=[custom_id],
317 connections=[{"from": "input", "to": "op_amp_in"}],
318 description="放大器级"
319 )
320 print(f"创建模块ID: {module_id}")
321
322 # 获取组件详情
323 print("\n=== 组件详情 ===")
324 comp = db.get_component(custom_id)
325 if comp:
326 print(f"组件名: {comp.name}")
327 print(f"类别: {comp.category}")
328 print(f"参数: {comp.parameters}")
329
330 db.close()
List[Dict[str, Any]] search_components(self, Optional[str] category=None, Optional[str] name_pattern=None)
Optional[ComponentSpec] get_component(self, str component_id)
str create_custom_component(self, str name, Dict[str, Any] parameters, Optional[Dict[str, Any]] electrical_params=None, Optional[Dict[str, Any]] physical_params=None, str description="")
str add_component(self, ComponentSpec spec)
Dict[str, Any] get_component_library(self)
str create_module(self, str name, List[str] components, List[Dict[str, Any]] connections, str description="")
__init__(self, str db_path="components.db")