def goal_fun(R): point = {} point['Rval'] = R point ['Cval'] = 10e-9 create_NetList('rc_ac.net', point) runSim() data = pr.parse_file('sim_result.dat') x = data['acfrequency'] y = np.abs(data['out.v']) freq = minus3dB(x, y) return abs(freq - 10000.0)
def testOneRun(): point = {} point['Rval'] = 1e3 + 100 * rnd.randn() point ['Cval'] = 10e-9 print point templ_filename = 'rc_ac.net' create_NetList(templ_filename, point) runSim() data = pr.parse_file('sim_result.dat') x = data['acfrequency'] y = np.abs(data['out.v']) plt.loglog(x, y, '-rx') plt.grid() plt.show()
import numpy as np import matplotlib.pyplot as plt import parse_result as pr # create the dat file to load with: # qucsator < rc_ac_sweep.net > rc_ac_sweep.dat data = pr.parse_file('rc_ac_sweep.dat') x = data['acfrequency'] y = np.abs(data['out.v']) c = data['Cx'] plt.loglog(x, y[0, :], '-rx') plt.loglog(x, y[4, :], '-go') plt.legend(['Cx=' + str(c[0]), 'Cx=' + str(c[4])]) plt.xlabel('acfrequency') plt.ylabel('abs(out.v)') plt.grid() plt.show()
#!/usr/bin/python -W ignore::DeprecationWarning import numpy as np import parse_result as pr import sys as sys import time as time args = sys.argv print('Processing file: %s' % str(args[1])) filename = args[1] qucs_data = pr.parse_file(str(filename)) if len(sys.argv) < 3: print('Variable list in file:') for key, value in qucs_data.items(): if isinstance(data[key], dict) is False: print('%s\t\t%s' % (key, data[key].shape)) sys.exit() key = sys.argv[2] data = qucs_data[key].real outfile = filename + '.' + time.strftime( '%Y-%m-%d-%H.%M.%S') + '.' + key + '.mtx' print('Exporting variable %s, size %s to file %s' % (key, data.shape, outfile)) fp = open(outfile, 'wb') metadata = '%d %d %d 8\n' % (data.shape[0], data.shape[1], data.shape[2]) fp.write(metadata.encode('ascii')) # This should be by default float64 binary to disk?
figure() for r,sim in enumerate(data): t = sim[:,0] vi = sim[:,1] vo = sim[:,2] plot(t*1e6, vi, 'k-', linewidth=1, label='vi') plot(t*1e6, vo, 'b--', linewidth=2, label='vo - HSPICE') hold(True) grid(True) xlabel('time (us)') ylabel('Vi, Vo (V)') # parse and plot QUCS Vds-IDS import parse_result as pr dat = pr.parse_file('inverter_transient.dat') ## why is this array not flat?? vo = np.ndarray.flatten(dat['vo.Vt']) plot(dat['time']*1e6,vo, 'r-.', linewidth=2, label='vo - QUCS') #plot(dat['vi.V'],dat['vi.V'],'k-') legend() savefig('bsim6_inverter_transient_HSPICE-QUCS.png', bbox_inches='tight') savefig('bsim6_inverter_transient_HSPICE-QUCS.pdf', bbox_inches='tight') show()
def run_simulation(proj, sim_report={}, prefix='', init_test=False): ''' Run simulation from reference netlist and compare outputs (dat, log) ''' #name = proj.split('_')[-2] #project dir name = proj.split(os.sep)[-1] #print name # FIXME fail if the project name has underscore sim_types= ['DC_', 'AC_', 'TR_', 'SP_', 'SW_'] for sim in sim_types: if sim in name: name=name[3:] name = name[:-4] #print name tests_dir = os.getcwd() proj_dir = os.path.join(tests_dir, 'testsuite', proj) print '\nProject : ', proj_dir # cd into project os.chdir(proj_dir) input_net = "netlist.txt" if os.path.isfile(input_net): # fetch types of simulation an types of components sim, comps = get_components(input_net) sim_report['sim_types'] = sim sim_report['comp_types'] = comps # get the Qucs Schematic version from the schematic # get the DataSet field from the schematic file schematic = os.path.join(proj_dir,name+'.sch') #print 'schematic', schematic with open(schematic) as fp: for line in fp: if 'Qucs Schematic' in line: qucs_version = line.split(' ')[-1][:-2] #print qucs_version sim_report['version'] = qucs_version if 'DataSet' in line: # DataSet filename, no quotes ref_dataset = line.split('=')[-1][:-2] #print 'ref_dataset', ref_dataset if init_test: output_dataset = ref_dataset else: output_dataset = "test_"+name+".dat" cmd = [prefix + "qucsator", "-i", input_net, "-o", output_dataset] print 'Running : ', ' '.join(cmd) # TODO run a few times, record average, add to report tic = time.time() # call the solver in a subprocess, set the timeout command = Command(cmd) command.run(timeout=5) toc = time.time() runtime = toc - tic # If return code, ignore time if command.retcode: sim_report['runtime'] = 'FAIL CODE %i' %command.retcode elif command.timeout: sim_report['runtime'] = 'TIMEOUT' else: sim_report['runtime'] = '%f' %runtime print pb('Runtime: %f' %runtime) # if adding test-project just save the log if init_test: # save log.txt # FIXME note that Qucs-gui adds a timestamp to the the log # running Qucsator it does not the same header/footer logout = 'log.txt' print pb('Initializing %s saving: \n %s/%s' %(proj, proj_dir, logout)) with open(logout, 'w') as myFile: myFile.write(command.out) if (command.timeout): errout = 'error_timeout.txt' print pr('Failed initializaton of %s saving: \n %s/%s' %(proj, proj_dir, errout)) with open(errout, 'w') as myFile: myFile.write(command.err) if (command.retcode): errout = 'error_code.txt' print pr('Failed initializaton of %s saving: \n %s/%s' %(proj, proj_dir, errout)) with open(errout, 'w') as myFile: myFile.write(command.err) # perform comparison else: if not os.path.isfile(ref_dataset): print (pr('Bad skipping comparison, missing reference output')) sim_report['fail_comp'] = 'No reference output to compare' # step out os.chdir(tests_dir) return sim_report # TODO failed also catches if the solver didn't run, output_dataset will be empty, # it will fail the comparison # let's compare results # list of failed variable comparisons failed=[] if not command.timeout: print pb('load data %s' %(ref_dataset)) ref_data = parse.parse_file(ref_dataset) print pb('load data %s' %(output_dataset)) test_data = parse.parse_file(output_dataset) #print ref_data['variables'] print pb('Comparing dependent variables') for name, kind in ref_data['variables'].items(): if kind == 'dep': #print name ref_trace = ref_data[name] test_trace = test_data[name] if not np.allclose(ref_trace, test_trace, rtol=1.00001e10, atol=1e-8): print pr(' Failed %s' %(name)) failed.append(name) else: print pg(' Passed %s' %(name)) # keep list of variables that failed comparison if failed: sim_report['fail_comp'] = [failed] # mark project as timed out if command.timeout: sim_report['timeout'] = command.timeout # In case of failure or timeout, save the log and error ouputs if (failed or command.timeout): logout = 'fail_log.txt' print pr('failed %s saving: \n %s/%s' %(proj, proj_dir, logout)) with open(logout, 'w') as myFile: myFile.write(command.out) errout = 'fail_error.txt' print pr('failed %s saving: \n %s/%s' %(proj, proj_dir, errout)) with open(errout, 'w') as myFile: myFile.write(command.err) # TODO add timestamp into qucsator. Or time the call. # qucs creates the log.txt with time start and time end. # step out os.chdir(tests_dir) return sim_report
outfilename='temp%s.dat' %(fn) data.append(np.genfromtxt(outfilename)) # plot HSPICE Vds - Ids figure() for r,sim in enumerate(data): vi = sim[:,1] vo = sim[:,2] plot(vi, vo, 'b--', linewidth=2, label='HSPICE') hold(True) grid(True) xlabel('Vi (V)') ylabel('Vo (V)') # parse and plot QUCS Vds-IDS import parse_result as pr dat = pr.parse_file('inv_dc.dat') plot(dat['vi.V'],dat['vo.V'],'r-.', linewidth=2, label='QUCS') plot(dat['vi.V'],dat['vi.V'],'k-') legend() savefig('bsim6_idvd_pmos_HSPICE-QUCS.png', bbox_inches='tight') savefig('bsim6_idvd_pmos_HSPICE-QUCS.pdf', bbox_inches='tight') show()
for r,sim in enumerate(data): vd = sim[:,0] ids = sim[:,1] if r==0: plot(vd, ids, 'b--', linewidth=2, label='HSPICE') else: plot(vd, ids, 'b--', linewidth=2) hold(True) xlim(-1.3,0) grid(True) xlabel('Vds (V)') ylabel('Ids (A)') # parse and plot QUCS Vds-IDS import parse_result as pr dat = pr.parse_file('test_idvd_pmos.dat') for i in range(3): if i==0 : plot(dat['Vds'],dat['Ids.I'][i],'r-.', linewidth=2, label='QUCS') else: plot(dat['Vds'],dat['Ids.I'][i],'r-.', linewidth=2) legend() ylim(0,6e-5) savefig('bsim6_idvd_pmos_HSPICE-QUCS.png', bbox_inches='tight') savefig('bsim6_idvd_pmos_HSPICE-QUCS.pdf', bbox_inches='tight') show()
import numpy as np import matplotlib.pyplot as plt import parse_result as pr # create the dat file to load with: # qucsator < rc_ac_sweep.net > rc_ac_sweep.dat data = pr.parse_file('rc_ac_sweep.dat') x = data['acfrequency'] y = np.abs(data['out.v']) c = data['Cx'] plt.loglog(x,y[0,:],'-rx') plt.loglog(x,y[4,:],'-go') plt.legend(['Cx=' + str(c[0]), 'Cx=' + str(c[4])]) plt.xlabel('acfrequency') plt.ylabel('abs(out.v)') plt.grid() plt.show()
vd = sim[:,0] ids = sim[:,1] if r==0: plot(vd, ids, 'b-', linewidth=1, label='HSPICE') else: plot(vd, ids, 'b-', linewidth=1) hold(True) xlim(-1.3,1.3) ylim(-1e-6,2e-5) grid(True) xlabel('Vgs (V)') ylabel('Ids (A)') # parse and plot QUCS Vds-IDS import parse_result as pr dat = pr.parse_file('test_idvg_nmos.dat') for i in range(4): if i==0 : plot(dat['Vgs'],dat['Ids.I'][i],'r-', linewidth=1, label='QUCS') else: plot(dat['Vgs'],dat['Ids.I'][i],'r-', linewidth=1) legend() savefig('bsim6_idvg_nmos_HSPICE-QUCS.png', bbox_inches='tight') savefig('bsim6_idvg_nmos_HSPICE-QUCS.pdf', bbox_inches='tight') show()
N = 500 templ_filename = 'rc_ac.net' freq_array = [] for i in range(N): point = {} point['Rval'] = 1e3 + 100 * rnd.randn() point ['Cval'] = 10e-9 create_NetList(templ_filename, point) runSim() data = pr.parse_file('sim_result.dat') x = data['acfrequency'] y = np.abs(data['out.v']) freq = minus3dB(x, y) print freq freq_array.append(freq) print freq_array plt.hist(freq_array, 10)