Control parameter tuning with PyQSPICE

Hello everyone,

I am using QSPICE for designing closed-loop control of a three-phase UPS. I am using PyQSPICE to run the simulation from a Python file. The simulation tends to hang if I run it from the GUI. The .qraw file generated after the simulation is 21GB.

I am looking for a way to automate the control parameter tuning process from the Python script where I am currently varying PI controller parameters Kp and Ki and repeating the simulation to check for control performance. If for example, I define two .param Kp and Ki, and these values can be changed from the Python file and the simulation repeated, this would automate the control tuning process to some extent. Is there any way to edit the .qsch file and change a couple of .param fields from a Python script?

Thanks in advance.

Hi @pythonpoweretrx ,

As you use PyQSPICE, I believe you generated your netlist file, by calling qsch2cir() method.
The netlist file is an ASCII file and you can open it, edit it (by using RegEx and so on), and save it from Python. If you assign a little bit longer and unique variable/parameter names on your parameters of concern, it’s very easy to replace those variable values in your Python code.

I’m not very expert on numerical analysis on Python but I believe there are many data sequence manipulation libraries searching peaks/minima from your big 21GB file, and automatically run the next loop step to tune your loop.


In my example here, these 2 lines are running RegEx to modifye the netlist.

run.cir4label('ac')
run.cir4label('tran')

best regards,
Masashi

Thank you very much for your reply.

Suppose, I define two controller parameters in the schematic with:

.param curr_controller_Kp 0.01
.param curr_controller_Ki 1.5

Could you give me the statements to modify them in the next simulation run?

Thanks again.

@pythonpoweretrx

Please try this…(I’m relocating/moving now and I can’t confirm it by myself, small debugging needed :slight_smile: )


I think you have this code block already.

fname = "Your_Python_FileName"
run = pqs(fname)
run.qsch2cir()

Now, you open the netlist and edit.

# read the netlist, store each line in "lines" variable with the change
lines = ""
with open(run.path['cir'], encoding='SJIS') as f:
  for line in f:
    line = line.rstrip('\r\n')
    if ret := re.match(r'^.*curr_controller_Kp', line):
      new_val = 9.99
      lines = lines + ".param curr_controller_Kp " + str(new_val) + "\n"		
    else:
      lines = lines + line + "\n"
# override the netlist with "lines"
with open(run.path['cir'], "w", encoding='SJIS') as f:
  f.write(lines)

Thank you so much! I will work on this and post the final code for others once I get it working.