# Test Vacask simulator interface

from pyopus.simulator import simulatorClass
import matplotlib.pyplot as plt

if __name__=='__main__':
	# Job list for simulator
	jobList=[
		{	# First job - op analysis
			'name': 'dcop',
			'definitions': [
				{ 'file': 'cmos180n.lib', 'section': 'tm' },
				{ 'file': 'opamp.sim' }
			],
			'params': {
				'vdd': 1.8,
				'temperature': 25
			},
			'options': {
				'tran_method': 'trap'
			},
			'saves': [
			],
			'command': 'op()'
		},
		{	# Second job - op analysis with different temperature
			'name': 'dcop100',
			'definitions': [
				{ 'file': 'cmos180n.lib', 'section': 'tm' },
				{ 'file': 'opamp.sim' }
			],
			'params': {
				'vdd': 1.6,
				'temperature': 100
			},
			'options': {
				'tran_method': 'trap'
			},
			'saves': [
			],
			'command': 'op()'
		},
		{	# Third job - op analysis with different supply voltage
			'name': 'dcopv33',
			'definitions': [
				{ 'file': 'cmos180n.lib', 'section': 'tm' },
				{ 'file': 'opamp.sim' }
			],
			'params': {
				'vdd': 2.0,
				'temperature': 25
			},
			'options': {
				'tran_method': 'trap'
			},
			'saves': [
			],
			'command': 'op()'
		},
		{	# Fourth job - op analysis with different library
			'name': 'dcopff',
			'definitions': [
				{ 'file': 'cmos180n.lib', 'section': 'ws' },
				{ 'file': 'opamp.sim' }
			],
			'params': {
				'vdd': 2.0,
				'temperature': 25
			},
			'options': {
				'tran_method': 'trap'
			},
			'saves': [
			],
			'command': 'op()'
		},
		{	# Fifth job - op analysis with different library
			'name': 'dcopff100',
			'definitions': [
				{ 'file': 'cmos180n.lib', 'section': 'ws' },
				{ 'file': 'opamp.sim' }
			],
			'params': {
				'vdd': 2.0,
				'temperature': 100
			},
			'options': {
				'tran_method': 'trap'
			},
			'saves': [
			],
			'command': 'op()'
		},
		{	# Sixth job - NMOS output characteristics
			# Inner sweep of vds (0..1.8V), outer sweep of vgs (0.3..0.8V, 0.1V step)
			# Outer sweep (sweepDepth=1) is split into sweep points
			'name': 'idvd',
			'definitions': [
				{ 'file': 'cmos180n.lib', 'section': 'tm' },
				{ 'file': 'mosvi.sim' }
			],
			'params': {
				'w': 1e-6,
				'l': 0.18e-6,
				'temperature': 25
			},
			'options': {
			},
			'saves': [
			],
			'command': (
				"an('op', {}, ["
				"sweep('vgsw', {'instance': 'vgs', 'parameter': 'dc', 'from': 0.3, 'to': 0.8, 'step': 0.1}), "
				"sweep('vdsw', {'instance': 'vds', 'parameter': 'dc', 'from': 0, 'to': 1.8, 'mode': 'lin', 'points': 180})"
				"], 1)"
			)
		},
		{	# Seventh job - step response of an RC circuit
			# Capacitance of c1 is swept (1, 2, 4, 8uF), each value is a sweep point
			'name': 'rcstep',
			'definitions': [
				{ 'file': 'rc.sim' }
			],
			'params': {
			},
			'options': {
			},
			'saves': [
			],
			'command': (
				"an('tran', {'step': 1e-6, 'stop': 40e-3, 'maxstep': 0.1e-3}, ["
				"sweep('csw', {'instance': 'c1', 'parameter': 'c', 'values': [1e-6, 2e-6, 4e-6, 8e-6]})"
				"], 1)"
			)
		}
	]

	# Input parameters
	inParams={
		'mirr_w': 7.46e-005,
		'mirr_l': 5.63e-007
	}

	# Create simulator
	sim=simulatorClass("Vacask")(debug=10)

	# Set job list and optimize it
	sim.setJobList(jobList)

	# Print optimized job groups
	ngroups=sim.jobGroupCount()
	print("\nJob Groups:")
	for i in range(ngroups):
		group=sim.jobGroup(i)
		gstr=''
		for j in group:
			gstr += f" {j} ({jobList[j]['name']}), "
		print(f"  {i}: {gstr}")

	print("")
	# Set input parameters
	sim.setInputParameters(inParams)

	# Curves of the NMOS output characteristic (vds, id, label)
	curves=[]

	# Transient responses of the RC circuit (time, vout, label)
	tranCurves=[]

	# Go through all job groups, write file, run it and collect results
	for i in range(ngroups):
		# Run jobs in job group.
		(jobIndices, status)=sim.runJobGroup(i)

		print("")
		for j in jobIndices:
			# Job name
			jobName=jobList[j]['name']
			# Load results
			res=sim.readResults(j, status)
			# Print results
			if res is not None and jobName=='idvd':
				# Go through sweep points (vgs values)
				print(f"Job {j} ({jobName}):")
				for k in range(res.sweepPointCount()):
					pt=res.sweepPoint(k)
					vgs=pt.sweepVars()['vgsw']
					vds=pt.scale()
					# Drain current flows into the drain, i.e. out of vds source
					idrain=-pt.i('vds')
					print(f"  vgs={vgs:.1f}V: id(vds={vds[-1]:.1f}V)={idrain[-1]:e}")
					# Store curve, label is extracted from the vgs value
					curves.append((vds, idrain, f"vgs={vgs:.1f}V"))
			elif res is not None and jobName=='rcstep':
				# Go through sweep points (capacitance values)
				print(f"Job {j} ({jobName}):")
				for k in range(res.sweepPointCount()):
					pt=res.sweepPoint(k)
					c=pt.sweepVars()['csw']
					t=pt.scale()
					vout=pt.v('out')
					print(f"  c={c*1e6:.0f}uF: {len(t)} points, vout(t={t[-1]*1e3:.0f}ms)={vout[-1]:e}")
					# Store curve, label is extracted from the capacitance value
					tranCurves.append((t, vout, f"c={c*1e6:.0f}uF"))
			elif res is not None:
				print(f"Job {j} ({jobName}): Vout={(res.v('out').item()):e}")
			else:
				print(f"Job {j} ({jobName}): no results")
		print("")

	sim.cleanup()

	# Plot NMOS output characteristic
	if len(curves)>0:
		plt.figure()
		for vds, idrain, label in curves:
			plt.plot(vds, idrain*1e6, label=label)
		plt.xlabel("vds [V]")
		plt.ylabel("id [uA]")
		plt.title("NMOS output characteristic")
		plt.legend()
		plt.grid(True)

	# Plot RC circuit step responses
	if len(tranCurves)>0:
		plt.figure()
		for t, vout, label in tranCurves:
			plt.plot(t*1e3, vout, label=label)
		plt.xlabel("t [ms]")
		plt.ylabel("vout [V]")
		plt.title("RC circuit step response")
		plt.legend()
		plt.grid(True)

	plt.show()
