gladiusmaximus

Gradient descent on spice netlist

Nov 19th, 2014
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. from __future__ import print_function
  2. from numpy import *
  3. import subprocess
  4. import re
  5. from scipy.optimize import minimize, show_options
  6. import os
  7.  
  8. with open('nand.net', 'r') as f:
  9.     source = f.read()
  10.  
  11. TMP_NAME = 'tmp.net'
  12.  
  13. def test(p, v=False):
  14.     if v:
  15.         print (' '.join('{0: 13.7f}'.format(p[i]) for i in range(len(p))), end='')
  16.     if any(p < 0):
  17.         a, b, c, d = nan, nan, nan, nan
  18.     else:
  19.         with open(TMP_NAME, 'w+') as f:
  20.             f.write(source.format(**locals()))
  21.             f.flush()
  22.         p = subprocess.Popen(['ngspice', TMP_NAME], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  23.         out = p.communicate(input='exit')[0]
  24.         try:
  25.             a = re.findall(r'tplh_b1af *?=  ([\d\.\-e]*)', out)[0]
  26.             b = re.findall(r'tphl_b1ar *?=  ([\d\.\-e]*)', out)[0]
  27.             c = re.findall(r'tphl_a1br *?=  ([\d\.\-e]*)', out)[0]
  28.             d = re.findall(r'tplh_a1bf *?=  ([\d\.\-e]*)', out)[0]
  29.         except:
  30.             a, b, c, d = nan, nan, nan, nan
  31.     t = array([a, b, c, d], dtype=float128)
  32.     if v:
  33.         print (' ', t)
  34.     return t
  35.  
  36. a1, b1, _, _ = test([1])
  37. def cost(p, v=False):
  38.     return sum((test(p, v)[2:] - 2)**2)
  39.  
  40. if __name__ == '__main__':
  41.     x0 = array([2], dtype=float128)
  42.     res = minimize(cost, x0, args=(True,), method='Nelder-Mead', options=dict(maxiter=160))
  43.     print (res)
  44.     os.remove(TMP_NAME)
  45. #5 2 nand
Advertisement
Add Comment
Please, Sign In to add comment