Skip to main content

PsimASimulate

Usage

psim.PsimASimulate();

Python Help

py.help(psim.PsimASimulate)

Python def

def PsimASimulate(self, maxThread, simList) -> []:
res = None
try:
res = PSIM.__private_A_Simulate2(self, 0, maxThread, simList)
except Exception as e:
print(f"Error: {e}")
return res

def __private_A_Simulate2(self, simType, maxThread, simList) -> []:
#simType: 0:PSIM 11:HYPERSPICE 12:LT_SPICE
result = PSIM_result(self)
AllResult = []
schHandles = []
AllThreadHandle = []
AllSimState = []
AllSimStateIndices = []

if not self.IsValid():
result.ErrorMessage = "PSIM object was not loaded."
result.Result = 0;
result.IsError = 1;
AllResult.append(result)
return AllResult;

simCount = len(simList)


SimOpenSchematicFileW = getattr(self.psimHandle, "SimOpenSchematicFileW")
if not SimOpenSchematicFileW:
raise AttributeError(self.VersionErrorMessage)
SimOpenSchematicFileW.restype = ctypes.c_int

Simulation_Init = getattr(self.psimHandle, "SimulationInit2")
if not Simulation_Init:
raise AttributeError(self.VersionErrorMessage)
Simulation_Init.argtypes = [
ctypes.c_int, # nID : schematic file identifier
ctypes.c_uint32, # dwOptions (DWORD)
ctypes.c_wchar_p, # szSimviewPath
ctypes.POINTER(ctypes.c_wchar_p), # pszError
ctypes.POINTER(ctypes.c_wchar_p), # parameter_list
ctypes.c_int # size of parameter_list
]
Simulation_Init.restype = ctypes.c_int

for i in range(0, simCount):
#simview_flag = 0 # RUN_SIMVIEW and WRITE_GRAPH
error_message = ""
nThreadIndex = 0
result = PSIM_result(self)
schHandle = 0

sd = simList[i]

schFilePath = sd.SchFilePath
graphFilePath = sd.GraphFilePath
simview_flag = sd.SimviewFlag
# int SimOpenSchematicFileW(const wchar_t * szFileName, UINT nFlag)
schHandle = SimOpenSchematicFileW(ctypes.c_wchar_p(schFilePath), ctypes.c_int (1)); #returns 0 on error

if schHandle == 0 :
result.ErrorMessage = "Unable to open schematic file " + schFilePath
result.Result = 0
result.IsError = 1

schHandles.append(schHandle)
AllResult.append(result)
AllThreadHandle.append(nThreadIndex)
AllSimState.append(-1) # -1:Error 0:nothing yet 1:running 2:returned
# AllSimStateIndices
else:
result.IsError = 0;

array_type = ctypes.c_wchar_p * len(simList[i].NameValueList)
w_array = array_type()
i2 = 0
for item in simList[i].NameValueList:
w_array[i2] = ctypes.c_wchar_p(str(item))
i2 += 1
NameValList_size = len(simList[i].NameValueList)
#[ctypes.c_wchar_p(s) for s in my_list]
simview_flag = 1
if(simType == 0):
# # This is only for PsimASimulate
# int SimulationInit2(int nID, DWORD dwOptions, const wchar_t* szSimviewPath, wchar_t* pszError, wchar_t**arrArg, int size)
# Define the function prototype
# call Simulation_Init
dwOptions = simview_flag
pszError = ctypes.c_wchar_p()
nThreadIndex = Simulation_Init(schHandle, ctypes.c_uint32(dwOptions), ctypes.c_wchar_p(graphFilePath), ctypes.byref(pszError), w_array, NameValList_size)
error_message = pszError.value
if (nThreadIndex == 0):
if error_message:
result.ErrorMessage = "Simulation failed for file: " + schFilePath + "\n" + error_message
else:
result.ErrorMessage = "Simulation failed for file: " + schFilePath
result.Result = 0;
result.IsError = 1;

schHandles.append(schHandle)
AllResult.append(result)
AllThreadHandle.append(nThreadIndex)
AllSimState.append(-1) # -1:Error


schHandles.append(schHandle)
AllResult.append(result)
AllThreadHandle.append(nThreadIndex)
AllSimState.append(0) # -1:Error 0:nothing yet 1:running 2:returned
AllSimStateIndices.append(i) #add the index of this thread. It has not ran yet.



Thread_Simulation_Do2 = getattr(self.psimHandle, "Thread_Simulation_Do2")
if not Thread_Simulation_Do2:
raise AttributeError(self.VersionErrorMessage)

GetSimulationResult_wait = getattr(self.psimHandle, "GetSimulationResult_wait")
if not GetSimulationResult_wait:
raise AttributeError(self.VersionErrorMessage)
GetSimulationResult_wait.restype = ctypes.c_int

#int Get_SimErrorMessages(int nThreadIndex, int& nErrorCount, int& nErrorSize, wchar_t* ptrErrors)
Get_SimErrorMessages = getattr(self.psimHandle, "Get_SimErrorMessages")
if not Get_SimErrorMessages:
raise AttributeError(self.VersionErrorMessage)

Get_SimErrorMessages.argtypes = [
ctypes.c_int, # nThreadIndex
ctypes.POINTER(ctypes.c_int), # Reference to nErrorCount
ctypes.POINTER(ctypes.c_int), # Reference to nErrorSize
ctypes.POINTER(ctypes.c_wchar) # ptrErrors
]
Get_SimErrorMessages.restype = ctypes.c_int

GetSimulationGraphRef = getattr(self.psimHandle, "GetSimulationGraphRef")
if not GetSimulationGraphRef:
raise AttributeError(self.VersionErrorMessage)
GetSimulationGraphRef.restype = ctypes.c_int


Graph_GetColCount = getattr(self.psimHandle, "Graph_GetColCount")
if not Graph_GetColCount:
raise AttributeError(self.VersionErrorMessage)

Graph_GetRowCount = getattr(self.psimHandle, "Graph_GetRowCount")
if not Graph_GetRowCount:
raise AttributeError(self.VersionErrorMessage)

Graph_GetColInfo = getattr(self.psimHandle, "Graph_GetColInfo")
if not Graph_GetColInfo:
raise AttributeError(self.VersionErrorMessage)


Graph_GetColCount.restype = ctypes.c_int
Graph_GetRowCount.restype = ctypes.c_int

Graph_GetColInfo.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.POINTER(ctypes.c_wchar)), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.POINTER(ctypes.c_double)), ctypes.POINTER(ctypes.POINTER(ctypes.c_byte))]
Graph_GetColInfo.restype = ctypes.c_int

if((maxThread <= 0) or (maxThread > simCount)):
maxThread = simCount

runningCount = 0
EverythingRunning = False
while True:
i3 = 0
i3_count = len(AllSimStateIndices)
if(i3_count == 0):
break

while( (EverythingRunning == False) and (runningCount < maxThread) and (i3 < i3_count)):
i3_index = AllSimStateIndices[i3];
nState = AllSimState[i3_index]
if(nState == 0): #not yet ran
nThreadIndex = AllThreadHandle[i3_index]
if( nThreadIndex > 0):
Thread_Simulation_Do2(nThreadIndex, 1)
AllSimState[i3_index] = 1 #running
runningCount += 1;
i3 += 1;
if(i3 == i3_count):
EverythingRunning = True

i3 = 0
while(i3 < i3_count):
i3_index = AllSimStateIndices[i3];
nState = AllSimState[i3_index]
if(nState == 1): #running
nThreadIndex = AllThreadHandle[i3_index]
if( nThreadIndex > 0):
# Sleep 100 milli seconds each time we call this function
i3_res = GetSimulationResult_wait(nThreadIndex, 100)
# i3_res: -2:doesn't exist -1:Ended with Cancel 0:Ended with failure 1:Ended with Success 4:Still running
if (i3_res != 4): # if simulation finished
AllSimState[i3_index] = 2 # returned
result = AllResult[i3_index]
if(i3_res == 0): #simulation failed
result.Result = i3_res;
result.IsError = 1

#int Get_SimErrorMessages(int nThreadIndex, int& nErrorCount, int& nErrorSize, wchar_t* ptrErrors)
nErrorCount = ctypes.c_int(0)
nErrorSize = ctypes.c_int(0)
ret = Get_SimErrorMessages(ctypes.c_int(nThreadIndex), ctypes.byref(nErrorCount), ctypes.byref(nErrorSize), None)
if((nErrorCount.value > 0) and (nErrorSize.value > 0)):
ptrErrors = ctypes.create_unicode_buffer(nErrorSize.value+100) # Allocate memory for ptrErrors, wchar_t
ret = Get_SimErrorMessages(ctypes.c_int(nThreadIndex), ctypes.byref(nErrorCount), ctypes.byref(nErrorSize), ptrErrors)
result.ErrorMessage += ptrErrors.value

elif (i3_res == 1):#simulation succeeded
result.Result = i3_res;
result.IsError = 0

# get a pointer to C++ graph object
nFlag = 0;
pnRows = ctypes.c_int(0)
pnIncDec = ctypes.c_int(0)

if((simType == 0) or (simType == 11)):
grf = GetSimulationGraphRef(ctypes.c_int(nThreadIndex))
elif(simType == 12):
# LTSpice
grf = PSIM.__private_OpenGraphFile(self, graphFilePath)

if(grf > 0):
result.graphHandle = grf

# int Graph_GetColCount(int nGraphRef)
numberOfCol = Graph_GetColCount(ctypes.c_int(grf))
#print("Number of curves in this file: ", numberOfCol)

# int Graph_GetRowCount(int nGraphRef)
numberOfRows = Graph_GetRowCount(ctypes.c_int(grf))
#print("Number of rows for each curve: ", numberOfRows)

# BOOL Graph_GetColInfo(int nGraphRef, int nFlag, int nColIndex, LPTSTR * ptrName, int * pnRows, int * pnIncDec, double ** ppValues, BYTE ** ppValidState)
# ptrName : name of the curve
# ppValues: values
# ppValidState: flag for each value 0:missing 1:valid 2:invalid
# pnRows : number of rows


for col in range(0 , numberOfCol):
# read one curve at a time
#print("Reading curve number ", col+1)

ppValues1_B = (ctypes.c_double * numberOfRows)()
ppValidState1_B = (ctypes.c_byte * numberOfRows)()

ppValues = ctypes.cast(ppValues1_B, ctypes.POINTER(ctypes.c_double))
ppValidState = ctypes.cast(ppValidState1_B, ctypes.POINTER(ctypes.c_byte))

ptrName1 = (ctypes.c_wchar * 100)()
ptrName = ctypes.cast(ptrName1, ctypes.POINTER(ctypes.c_wchar))

b = Graph_GetColInfo(ctypes.c_int(grf), ctypes.c_int (0), ctypes.c_int(col), ctypes.byref(ptrName), ctypes.byref(pnRows), ctypes.byref(pnIncDec), ctypes.byref(ppValues), ctypes.byref(ppValidState))

ptrName3 = ctypes.cast(ptrName, ctypes.POINTER(ctypes.c_wchar * 100))
#print(ptrName3.contents.value)
#print(ppValues[10])

crv = PSIM_curve(pnRows.value, ptrName3.contents.value, ppValues, ppValidState)
result.Graph.add_curve(crv)

#result.ErrorMessage = error_message
AllResult[i3_index] = result
AllSimStateIndices.pop(i3)
i3_count -= 1
runningCount -= 1
break


CloseSchematicFile = getattr(self.psimHandle, "SimCloseSchematicFile")
if not CloseSchematicFile:
raise AttributeError(self.VersionErrorMessage)

CloseSchematicFile.restype = ctypes.c_int

nCount = len(schHandles)
for i in range(0, nCount):
schHandle = schHandles[i]
if(schHandle > 0):
# int SimCloseSchematicFile(int nSchematicID)
n1 = CloseSchematicFile(schHandle) #returns 0 on error


return AllResult;