Advertisement
toweber

generate_simulate_meas_cost_optimize

Sep 12th, 2022
681
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 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 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)
  34.             vout = float(match.group(1))
  35.             return vout
  36.  
  37. def simulate():
  38.     print("Simulating")
  39.     os.system('ltspice -b generated_netlist.net')
  40.  
  41. def cost_function(x):
  42.     print("Evaluating cost function")
  43.     #generate, simulate and read log
  44.     generate_netlist(x)
  45.     simulate()
  46.     voltage = meas_result()
  47.  
  48.     #calculate cost
  49.     cost = abs(5-voltage)
  50.     return cost
  51.  
  52.  
  53.  
  54. # OPTIMIZATION
  55.  
  56. size_x = 1
  57. bound_i = (100,20000)
  58. bounds = []
  59. for i in range (0, size_x):
  60.       bounds.append(bound_i)
  61.  
  62. x0 = np.array([3000])
  63.  
  64. maxiter = 100
  65. step = 1000
  66. args = []
  67.  
  68. res = my_hillclimbing(cost_function, x0, bounds, maxiter, step, args)
  69. print("Final x: [",)
  70. print("%f" % res.x[0],)
  71. for i in range(1,len(res.x)):
  72.     print(", %f" % res.x[i],)
  73. print("]\n",)
  74.  
  75. print("Final cost: %f \n" % res.cost)
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement