2022年8月7日 星期日

重新排列S參數檔案ports順序並輸出檔案

以下範例讀取32port S參數檔案,重新輸出16組s2p檔案。

import re, itertools


class SNP:
def __init__(self, touchstone_path):
with open(touchstone_path) as f:
text = f.readlines()

self.data = []
self.ports = {}
for line in text:
try:
[float(i) for i in line.strip().split()]
self.data += line.strip().split()
except:
if line.startswith('#'):
self.header = line
else:
m = re.search('!\sPort\[(\d+)\]\s=\s(.*)$', line)
if m:
num = int(m.group(1))
name = m.group(2)
self.ports[num] = name

def reorder(self, order, touchstone_path):
num = len(self.ports)
frequencies = self.data[::2 * num ** 2 + 1]

matrix = list(itertools.product(order, repeat=2))
new_touchstone = [self.header]

touchstone_path += '.s{}p'.format(len(order))
print('\n' + touchstone_path)
for n, i in enumerate(order, 1):
port = '! Port[{}] = {}'.format(n, self.ports[i])
print(port)
new_touchstone.append(port)

for n, f in enumerate(frequencies):
line = [self.data[n * (num ** 2 * 2 + 1)]]
for i, j in matrix:
i -= 1
j -= 1
line.append(self.data[n * (num ** 2 * 2 + 1) + 1 + (2 * num * i) + (2 * j)])
line.append(self.data[n * (num ** 2 * 2 + 1) + 1 + (2 * num * i) + (2 * j + 1)])

new_touchstone.append(' '.join(line))

with open(touchstone_path, 'w') as f:
f.write('\n'.join(new_touchstone))


snp = SNP(r"D:\demo\dq.s32p")
snp.ports
snp.reorder((23, 9), 'd:/demo/dq0')
snp.reorder((21, 11), 'd:/demo/dq1')
snp.reorder((24, 10), 'd:/demo/dq2')
snp.reorder((19, 12), 'd:/demo/dq3')
snp.reorder((17, 14), 'd:/demo/dq4')
snp.reorder((20, 16), 'd:/demo/dq5')
snp.reorder((18, 13), 'd:/demo/dq6')
snp.reorder((22, 15), 'd:/demo/dq7')
snp.reorder((31, 1), 'd:/demo/dq8')
snp.reorder((27, 3), 'd:/demo/dq9')
snp.reorder((29, 2), 'd:/demo/dq10')
snp.reorder((26, 4), 'd:/demo/dq11')
snp.reorder((32, 6), 'd:/demo/dq12')
snp.reorder((25, 8), 'd:/demo/dq13')
snp.reorder((30, 5), 'd:/demo/dq14')
snp.reorder((28, 7), 'd:/demo/dq15')

2022年7月29日 星期五

輸出Report所有維度的獨立變數

 

from win32com import client

oApp = client.Dispatch("Ansoft.ElectronicsDesktop.2022.2")
oDesktop = oApp.GetAppDesktop()
oDesktop.RestoreWindow()
oProject = oDesktop.GetActiveProject()
oDesign = oProject.GetActiveDesign()

oReportSetup = oDesign.GetModule("ReportSetup")
oSolutions = oDesign.GetModule("Solutions")

report_solution = {}
solutions = []
display = {}
context = {}
category = {}
quantities = {}
variations = {}
solve_range = {}

for report_type in oReportSetup.GetAvailableReportTypes():
display[report_type] = oReportSetup.GetAvailableDisplayTypes(report_type)
report_solution[report_type] = oReportSetup.GetAvailableSolutions(report_type)
for s in report_solution[report_type]:
if s not in solutions:
solutions.append(s)

for _report_type, _display in display.items():
for d in _display:
for _solution in report_solution[_report_type]:
ctxt = oReportSetup.GetSolutionContexts(_report_type, d, _solution)
context[(_report_type, d, _solution)] = ctxt
for _ctxt in ctxt:
cate = oReportSetup.GetAllCategories(_report_type, d, _solution, _ctxt)
category[(_report_type, d, _solution, _ctxt)] = cate
for _cate in cate:
q = oReportSetup.GetAllQuantities(_report_type, d, _solution, _ctxt, _cate)
quantities[(_report_type, d, _solution, _ctxt, _cate)] = q

for sol in solutions:
solve_range[sol] = oSolutions.GetSolveRangeInfo(sol)
variations[sol] = oSolutions.GetAvailableVariations(sol)



2022年7月26日 星期二

Q3D輸出Transion Region頻率範圍

 選擇金屬厚度邊,執行腳本即可輸出到訊息視窗。

import math
import ScriptEnv

oDesktop.ClearMessages("", "", 2)
oProject = oDesktop.GetActiveProject()
oDesign = oProject.GetActiveDesign()
oEditor = oDesign.SetActiveEditor("3D Modeler")

try:
selected = oEditor.GetSelections()
edge_id = selected[0].replace('Edge', '')

obj = oEditor.GetObjectNameByEdgeID(edge_id)
material = oEditor.GetPropertyValue('Geometry3DAttributeTab', obj, 'Material').replace('"', '')
AddWarningMessage('Material: {}'.format(material))

unit_map = {'meter': 1, 'mm': 1e-3, 'um': 1e-6, 'nm': 1e-9, 'mil': 2.54e-5, 'in': 2.54e-2}
freq_map = [(1, 'Hz'), (1e3, 'KHz'), (1e6, 'MHz'), (1e9, 'GHz'), (1e12, 'THz')]

unit = oEditor.GetModelUnits()
thickness = float(oEditor.GetEdgeLength(edge_id)) * unit_map[unit]
AddWarningMessage('Thicknetss: {}(m)'.format(thickness))

oDefinitionManager = oProject.GetDefinitionManager()
conductivity = float(
oDefinitionManager.GetPropertyValue('MaterialPropTab', 'Materials:' + material, 'Bulk Conductivity'))
permeability = float(
oDefinitionManager.GetPropertyValue('MaterialPropTab', 'Materials:' + material, 'Relative Permeability'))
AddWarningMessage('Conductivity: {}'.format(conductivity))
AddWarningMessage('Relative Permeability: {}'.format(permeability))

u0 = 4 * math.pi * 1e-7

ac_high = 9 / (math.pi * conductivity * permeability * u0 * thickness ** 2)

for n, (scale, unit) in enumerate(freq_map):
if ac_high / scale < 1:
scale, unit = freq_map[n - 1]
_ac_low = str(round(ac_high / 9 / scale, 3)) + unit
_ac_high = str(round(ac_high / scale, 3)) + unit
break

AddWarningMessage("Transition Region: {} - {}".format(_ac_low, _ac_high))

except:
AddErrorMessage("Please Select Metal Edge!")







2022年7月4日 星期一

SIwave API設定Pin Group Port

 

from win32com import client

oApp = client.Dispatch("SIwave.Application.2022.1")
oApp.RestoreWindow()
oDoc = oApp.GetActiveProject()

# ScrPlaceCircuitElement(string givenElementName,
# string givenPartName,
# int circuitElementType,
# int posTermConnectionType,
# string posTermParam1,
# string posTermParam2,
# string posTermParam3,
# int refTermConnectionType,
# string refTermParam1,
# string refTermParam2,
# string refTermParam3,
# double capVal,
# double indVal,
# double resVal,
# double refZRe,
# double mag,
# double phase) -> short

oDoc.ScrPlaceCircuitElement('ABC',
'DEF',
3,
1,
'FCHIP',
'FCHIP',
'FCHIP_VDD_15_Group',
1,
'FCHIP',
'FCHIP',
'FCHIP_VSS_Group',
0,
0,
0,
50,
0,
0)



2022年6月13日 星期一

類別屬性檢查


class test:
def __init__(self):
self._score = 60

@property
def score(self):
return self._score

@score.setter
def score(self, value):
if value < 0:
self._score = 0
if value > 100:
self._score = 100


x = test()
print(x.score)
x.score = 110
print(x.score)
x.score = -10
print(x.score)

 








2022年5月16日 星期一

傅立葉轉換

時域訊號經過傅立葉轉換到頻域,再轉回時域做比較

import numpy as np

tstop = 10
tstep = 0.01

fstart = -1 / tstep / 2
fstop = 1 / tstep / 2
fstep = 1 / tstop

t = np.arange(0, tstop, tstep)
y0 = np.sin(20 * t)

import matplotlib.pyplot as plt

scale = np.sqrt(2 * np.pi * len(t))
plt.plot(t, y0)
plt.show()
y1 = []
f = np.arange(fstart, fstop, fstep)
for w in f:
y1.append(np.sum(np.exp(-1j * w * t) * y0) / scale)

plt.plot(f, np.abs(y1))
plt.show()

y2 = []
for t0 in t:
y2.append(np.sum(np.exp(1j * t0 * f) * y1) / scale)

plt.plot(t, np.real(y2))
plt.show()

plt.plot(t, y0)
plt.plot(t, y2, c='r', linewidth=1)
plt.show()




2022年4月21日 星期四

在Spyder當中修改padstack definition某一層的屬性

在Spyder當中修改padstack definition某一層的屬性

import clr, os, sys, System
from distutils.dir_util import copy_tree

AnsysEM_Path = 'C:/Program Files/AnsysEM/v221/Win64/'
sys.path.append(AnsysEM_Path)
os.environ['PATH'] += ';' + AnsysEM_Path

clr.AddReference('Ansys.Ansoft.Edb')
clr.AddReference('Ansys.Ansoft.SimSetupData')
import Ansys.Ansoft.Edb as edb

edb.Database.SetRunAsStandAlone(True)

aedb_path = "D:\demo2\Galileo_G87173_20431_12.aedb"
cell_name = 'Galileo_G87173_204'
layer_name = 'UNNAMED_004'
up_height = '10mil'
low_height = '12mil'

# %%----------------------------------------------------------------------------
n = 1
while True:
new_aedb_path = aedb_path.replace('.aedb', '_{}.aedb'.format(n))
if not os.path.isdir(new_aedb_path):
break
n += 1
copy_tree(aedb_path, new_aedb_path)

middle_layer_name = layer_name + '_1'
low_layer_name = layer_name + '_2'

DB = edb.Database.Open(new_aedb_path, False)

try:
cells = [i for i in DB.CircuitCells]
for cell in cells:
if cell.GetName() == cell_name:
break

layout = cell.GetLayout()
padstack_instances = [i for i in layout.PadstackInstances]
padstack_def = {}
for i in padstack_instances:
if i.GetPadstackDef().GetName() not in padstack_def:
padstack_def[i.GetPadstackDef().GetName()] = i.GetPadstackDef()

dimension = System.Collections.Generic.List[edb.Utility.Value]()
dimension.Add(edb.Utility.Value(0))

for i, d in padstack_def.items():
new_data = edb.Definition.PadstackDefData(d.GetData())

new_data.SetPadParameters('Default',
edb.Definition.PadType.RegularPad,
edb.Definition.PadGeometryType.NoGeometry,
dimension,
edb.Utility.Value(0),
edb.Utility.Value(0),
edb.Utility.Value(0))
new_data.SetPadParameters('Default',
edb.Definition.PadType.AntiPad,
edb.Definition.PadGeometryType.NoGeometry,
dimension,
edb.Utility.Value(0),
edb.Utility.Value(0),
edb.Utility.Value(0))
d.SetData(new_data)
DB.Save()
except:
raise
finally:
DB.Close()