Advertisement
toweber

generate_simulate_meas_cost_optimize_ngspice

Sep 12th, 2022
713
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. import os
  2. import ipdb # ipdb.set_trace()
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. import re
  6. from my_optimization import *
  7.  
  8.  
  9. def generate_netlist(R2):
  10.     print("Generating netlist")
  11.     cirfile="generated_netlist.net"
  12.     f = open(cirfile,"w")  
  13.     f.write("* Generated Netlist \n")
  14.     f.write("V1 N001 0 10 \n")
  15.     f.write("R1 N001 out 10k \n")
  16.     f.write("R2 out 0 %f \n" %R2)
  17.     f.write(".tran 0.1ns 1ns \n")
  18.     f.write(".meas TRAN vsaida FIND V(out) at=1n \n")
  19.     f.write(".end \n")
  20.     f.close()
  21.  
  22.  
  23. def meas_result():
  24.     print("Reading log file")
  25.     logfile="generated_netlist.log"
  26.     with open(logfile) as f:
  27.         lines = f.readlines()        
  28.     f.close()
  29.  
  30.     for l in lines:
  31.         #print(l)
  32.         if 'vsaida' in l:
  33.             # match =re.search(r"=(.*) at",l)  # LTSPICE
  34.             match =re.search(r"=  (.*)",l)  # ngspice
  35.             vout = float(match.group(1))
  36.             return vout
  37.  
  38. def simulate():
  39.     print("Simulating")
  40.     os.system('ngspice -b generated_netlist.net > generated_netlist.log')
  41.  
  42. def cost_function(x):
  43.     print("Evaluating cost function")
  44.     #generate, simulate and read log
  45.     generate_netlist(x)
  46.     simulate()
  47.     voltage = meas_result()
  48.  
  49.     #calculate cost
  50.     cost = abs(5-voltage)
  51.     return cost
  52.  
  53.  
  54.  
  55. # OPTIMIZATION
  56.  
  57. size_x = 1
  58. bound_i = (100,20000)
  59. bounds = []
  60. for i in range (0, size_x):
  61.       bounds.append(bound_i)
  62.  
  63. x0 = np.array([3000])
  64.  
  65. maxiter = 100
  66. step = 1000
  67. args = []
  68.  
  69.  
  70. res = my_hillclimbing(cost_function, x0, bounds, maxiter, step, args)
  71. print("Final x: [",)
  72. print("%f" % res.x[0],)
  73. for i in range(1,len(res.x)):
  74.     print(", %f" % res.x[i],)
  75.     print("]\n",)
  76.     #print res.x
  77. print("Final cost: %f \n" % res.cost)    
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement