from pyopus.evaluator.distrib import *

# Problem definition, Miller OTA in IHP SG13G2 (low voltage MOS devices)
# Requires environmental variables PDK_ROOT and PDK (set to ihp-sg13g2).
# PDK paths are set in .vacaskrc.toml which VACASK loads from its
# working directory.

__all__ = [ 'heads', 'analyses', 'measures', 'variables', 'statParams', 'opParams', 'designParams' ]


heads = {
	'vacask': {
		'simulator': 'Vacask',
		'settings': {
			'debug': 0
		},
		'moddefs': {
			'def':  { 'file': 'miller.inc' },
			'tb':   { 'file': 'topdc.inc' },
			'tbrr': { 'file': 'toprr.inc' },
			# IHP SG13G2 low voltage MOS corners
			'tt':   { 'file': 'cornerMOSlv.lib', 'section': 'mos_tt' },
			'ss':   { 'file': 'cornerMOSlv.lib', 'section': 'mos_ss' },
			'ff':   { 'file': 'cornerMOSlv.lib', 'section': 'mos_ff' },
			'sf':   { 'file': 'cornerMOSlv.lib', 'section': 'mos_sf' },
			'fs':   { 'file': 'cornerMOSlv.lib', 'section': 'mos_fs' },
		},
		'options': {
			'tran_method': 'trap'
		},
		'params': {
			'ibias': 50e-6,
			'lev1': -0.2,
			'lev2': 0.2,
			'tstart': 10000e-9,
			'tr': 1e-9,
			'tf': 1e-9,
			'pw': 10000e-9,
			'rload': 100e6,
			'cload': 1e-12,
			# Fixed device multipliers
			'mirr_m': 2,
			'mirr_md': 4,
			'mirr_mo': 4,
			'out_m': 8,
			'load_m': 2,
			'diff_m': 2,
			# Input source waveform type, set to 'pulse' in transient analyses
			# (a pulse source has value lev1 in op/dc analyses)
			'vintype': 'dc'
		}
	}
}

# PDK MOS devices are subcircuits. The PSP103 instance inside the
# subcircuit is named nsg13_lv_nmos (NMOS) or nsg13_lv_pmos (PMOS).
variables={
	'mosList':  [ 'xmn1', 'xmn2', 'xmn3', 'xmn4', 'xmn5', 'xmp1', 'xmp2', 'xmp3' ],
	'isNmos':   [ 1,      1,      1,      1,       1,      0,      0,      0 ],
	'mosInner': [ 'nsg13_lv_nmos' ]*5 + [ 'nsg13_lv_pmos' ]*3,
}

analyses = {
	'op': {
		'head': 'vacask',
		'modules': [ 'def', 'tb' ],
		'options': {
		},
		'params': {
			'rin': 1e6,
			'rfb': 1e6
		},
		# Save all standard results (voltages, currents)
		# Save vgs, vth, vds, and vdss for all MOS transistors in mosList
		# PSP103 reports these quantities with polarity already taken into account
		# (i.e. they are positive for a PMOS in saturation).
		'saves': [
			"all()",
			"p([ ipath(inst, 'x1', inner) for inst, inner in zip(mosList, mosInner) ], ['vgs', 'vth', 'vds', 'vdss'])"
		],
		'command': "op()"
	},
	'dc': {
		'head': 'vacask',
		'modules': [ 'def', 'tb' ],
		'options': {
		},
		'params': {
			'rin': 1e6,
			'rfb': 1e6
		},
		'saves': [ ],
		'command': "dc(-1.2, 1.2, 'lin', 100, 'vin1', 'dc')"
	},
	'ac': {
		'head' : 'vacask',
		'modules': [ 'def', 'tb' ],
		'options': {
		},
		'params': {
			'rin': 1e6,
			'rfb': 1e6
		},
		'saves': [ "all()" ],
		'command': "ac(1, 1e12, 'dec', 10)"
	},
	# Rfb and Cin should be large enough. Small values cause a plateau of incorrect
	# rejection ratios at very low frequencies. This plateau ends at a frequency which
	# is too high.
	# The optimizer exploits this by lowering bandwidth and increasing gain.
	# The obtained rejection ratios are then incorrect in some cases, i.e. too high.
	# Therefore we require the bandwidth to be at least 100Hz and measure gain at 10Hz.
	'accom': {
		'head' : 'vacask',
		'modules': [ 'def', 'tbrr' ],
		'options': {
		},
		'params': {
			'rfb': 1e9,
			'cin': 1,
			'accom': 1.0,
			'acvdd': 0.0,
			'acvss': 0.0
		},
		'saves': [ "all()" ],
		'command': "ac(1, 1e9, 'dec', 10)"
	},
	'acvdd': {
		'head' : 'vacask',
		'modules': [ 'def', 'tbrr' ],
		'options': {
		},
		'params': {
			'rfb': 1e9,
			'cin': 1,
			'accom': 0.0,
			'acvdd': 1.0,
			'acvss': 0.0
		},
		'saves': [ "all()" ],
		'command': "ac(1, 1e9, 'dec', 10)"
	},
	'acvss': {
		'head' : 'vacask',
		'modules': [ 'def', 'tbrr' ],
		'options': {
		},
		'params': {
			'rfb': 1e9,
			'cin': 1,
			'accom': 0.0,
			'acvdd': 0.0,
			'acvss': 1.0
		},
		'saves': [ "all()" ],
		'command': "ac(1, 1e9, 'dec', 10)"
	},
	'noise': {
		'head' : 'vacask',
		'modules': [ 'def', 'tb' ],
		'options': {
		},
		'params': {
			'rin': 1e6,
			'rfb': 1e6
		},
		# By default VACASK saves only the total noise contribution of every instance.
		# Save individual noise contributions of xmn2 (VACASK nc() save directive).
		'saves': [ "all()", "[\"nc('\"+ipath('xmn2', 'x1', 'nsg13_lv_nmos')+\"')\"]" ],
		'command': "noise(1, 1e12, 'dec', 10, 'vin1', 'out')"
	},
	'tran': {
		'head' : 'vacask',
		'modules': [ 'def', 'tb' ],
		'options': {
			'reltol': 1e-4
		},
		'params': {
			'rin': 1e6,
			'rfb': 1e6,
			'vintype': 'pulse'
		},
		'saves': [ "all()" ],
		'command': "tran(param['tr']*1, param['tstart']+param['pw']*2)"
	},
	'translew': {
		'head' : 'vacask',
		'modules': [ 'def', 'tb' ],
		'options': {
			'reltol': 1e-4
		},
		'params': {
			'rin': 1e6,
			'rfb': 1e6,
			'lev1': -0.4,
			'lev2': 0.4,
			'vintype': 'pulse'
		},
		'saves': [ "all()" ],
		'command': "tran(param['tr']*1, param['tstart']+param['pw']*2)"
	},
	'blank': {
		'head': 'vacask',
		'params': {
			'rin': 1e6,
			'rfb': 1e6
		},
		'command': None
	}
}

# Define performance measures, dependencies, and design requirements (lower and upper bounds)
measures = {
	'isup': {
		'analysis': 'op',
		'expression': "isup=-i('vdd1')",
		'upper': 1000e-6,
	},
	'out_op': {
		'analysis': 'op',
		'expression': "v('out')",
		'lower': -12.5e-3,
		'upper': 12.5e-3
	},
	'vgs_drv': {
		'analysis': 'op',
		'expression': """
res=[]
# Loop over all MOS instances in mosList
for inst, inner in zip(mosList, mosInner):
	# Generate full name for MOS instance
	fullName=ipath(inst, 'x1', inner)
	# Extract vgs and vth from results
	vgs=p(fullName, 'vgs')
	vth=p(fullName, 'vth')
	# Compute difference and append to results list
	diff=(vgs-vth).item()
	res.append(diff)
	# Uncomment to print a debug message during evaluation
	# m.debug(f"{fullName}: vgs={vgs.item():f} vth={vth.item():f}")
# Return NumPy array
__result=np.array(res)
""",
		'vector': True,
		'lower': 0.0,
	},
	'vds_drv': {
		'analysis': 'op',
		'expression': """
res=[]
# Loop over all MOS instances in mosList
for inst, inner in zip(mosList, mosInner):
	# Generate full name for MOS instance
	fullName=ipath(inst, 'x1', inner)
	# Extract vds and vdss (drain saturation voltage) from results
	vds=p(fullName, 'vds')
	vdss=p(fullName, 'vdss')
	# Compute difference and append to results list
	diff=(vds-vdss).item()
	res.append(diff)
# Return NumPy array
__result=np.array(res)
""",
		'vector': True,
		'lower': 0.0,
	},
	'swing': {
		'analysis': 'dc',
		'expression': "m.DCswingAtGain(v('out'), v('inp', 'inn'), 0.5, 'out')",
		'lower': 0.7,
	},
	'gain': {
		'analysis': 'ac',
		'expression': """
ndx=m.IatXval(np.abs(scale()), 10.0)[0]
__result=m.XatI(m.ACmag(m.ACtf(v('out'), v('inp', 'inn'))), ndx)
""",
		'lower': 60.0,
	},
	#'bw': {
	#	'analysis': 'ac',
	#	'expression': "m.ACbandwidth(m.ACtf(v('out'), v('inp', 'inn')), scale())",
	#	'lower': 4e3,
	#},
	'gain_com': {
		'analysis': 'accom',
		'expression': """
ndx=m.IatXval(np.abs(scale()), 10.0)[0]
__result=m.XatI(m.ACmag(m.ACtf(v('out'), 1.0)), ndx)
""",
	},
	'gain_vdd': {
		'analysis': 'acvdd',
		'expression': """
ndx=m.IatXval(np.abs(scale()), 10.0)[0]
__result=m.XatI(m.ACmag(m.ACtf(v('out'), 1.0)), ndx)
""",
	},
	'gain_vss': {
		'analysis': 'acvss',
		'expression': """
ndx=m.IatXval(np.abs(scale()), 10.0)[0]
__result=m.XatI(m.ACmag(m.ACtf(v('out'), 1.0)), ndx)
""",
	},
	'ugbw': {
		'analysis': 'ac',
		'expression': "m.ACugbw(m.ACtf(v('out'), v('inp', 'inn')), scale())",
		'lower': 10e6,
	},
	'pm': {
		'analysis': 'ac',
		'expression': "m.ACphaseMargin(m.ACtf(v('out'), v('inp', 'inn')))",
		'lower': 50.0,
	},
	'ph_slope': {
		'analysis': 'ac',
		'expression': """
# Transfer function
tf=m.ACtf(v('out'), v('inp', 'inn'))
# Phase slope in deg/dec
slope=m.dYdX(m.ACphase(tf), np.log10(scale()))
# Look only at points where gain>0dB
mask=m.ACmag(tf)>0
# Max slope in region defined by mask
__result=(slope*mask).max()
""",
		'upper': 0,
	},
	'overshdn': {
		'analysis': 'tran',
		'expression': "m.Tundershoot(v('out'), scale(), t1=param['tstart'], t2=(param['pw']+param['tstart']+param['tr']))",
		'upper': 0.15,
	},
	'overshup': {
		'analysis': 'tran',
		'expression': "m.Tovershoot(v('out'), scale(), t1=(param['pw']+param['tstart']+param['tr']))",
		'upper': 0.15,
	},
	'tsetdn': {
		'analysis': 'tran',
		'expression': "m.TsettlingTime(v('out'), scale(), t1=param['tstart'], t2=(param['pw']+param['tstart']+param['tr']))",
		'upper': 1000e-9,
	},
	'tsetup': {
		'analysis': 'tran',
		'expression': "m.TsettlingTime(v('out'), scale(), t1=(param['pw']+param['tstart'])+param['tr'])",
		'upper': 1000e-9,
	},
	'slewdn': {
		'analysis': 'translew',
		'expression': "m.TslewRate('falling', v('out'), scale(), t1=param['tstart'], t2=(param['pw']+param['tstart']+param['tr']))",
		'lower': 2e6,
	},
	'slewup': {
		'analysis': 'translew',
		'expression': "m.TslewRate('rising', v('out'), scale(), t1=(param['pw']+param['tstart']+param['tr']))",
		'lower': 2e6,
	},
	'cmrr': {
		'analysis': 'blank',
		'expression': "result['gain'][cornerName]-result['gain_com'][cornerName]",
		'lower': 60.0,
		'depends': [ 'gain', 'gain_com' ]
	},
	'psrr_vdd': {
		'analysis': 'blank',
		'expression': "result['gain'][cornerName]-result['gain_vdd'][cornerName]",
		'lower': 60.0,
		'depends': [ 'gain', 'gain_vdd' ]
	},
	'psrr_vss': {
		'analysis': 'blank',
		'expression': "result['gain'][cornerName]-result['gain_vss'][cornerName]",
		'lower': 60.0,
		'depends': [ 'gain', 'gain_vss' ]
	},
	'onoise1k': {
		'analysis': 'noise',
		'expression': "m.XatI(ns('output'), m.IatXval(scale(), 1e3)[0])",
	},
	'inoise1k': {
		'analysis': 'noise',
		'expression': "m.XatI(ns('input'), m.IatXval(scale(), 1e3)[0])",
	},
	# PSP103 noise contributions: idid (channel thermal), flicker (channel flicker)
	'in1kmn2id': {
		'analysis': 'noise',
		'expression': "m.XatI(ns('input', ipath('xmn2', 'x1', 'nsg13_lv_nmos'), 'idid'), m.IatXval(scale(), 1e3)[0])",
	},
	'in1kmn2fl': {
		'analysis': 'noise',
		'expression': "m.XatI(ns('input', ipath('xmn2', 'x1', 'nsg13_lv_nmos'), 'flicker'), m.IatXval(scale(), 1e3)[0])",
	},
	'in1kmn2': {
		'analysis': 'noise',
		'expression': "m.XatI(ns('input', ipath('xmn2', 'x1', 'nsg13_lv_nmos')), m.IatXval(scale(), 1e3)[0])",
	},
	'area': {
		'analysis': 'blank',
		'expression': (
			"(param['mirr_w']*param['mirr_m']+param['mirr_wo']*param['mirr_mo'])*param['mirr_l']"
			"+param['mirr_wd']*param['mirr_md']*param['mirr_ld']"
			"+param['out_w']*param['out_m']*param['out_l']"
			"+param['load_w']*param['load_m']*param['load_l']*2"
			"+param['diff_w']*param['diff_m']*param['diff_l']*2"
			"+param['r_out']/1e3*12e-12"
			"+param['c_out']/1e-12*100e-12"
		),
		'upper': 9000e-12
	}
}

# Design parameters, lower bounds, upper bounds, and initial values
# Initial values are taken from VACASK demo mc/miller_ihp.sim.
# Model validity range: L = 0.13u..10u, W = 0.15u..10u (per device, m=1).
designParams={
	'mirr_w': {
		'lo':	0.15e-6,
		'hi':	10e-6,
		'init': 5e-6,
	},
	'mirr_wd': {
		'lo':	0.15e-6,
		'hi':	10e-6,
		'init': 5e-6,
	},
	'mirr_wo': {
		'lo':	0.15e-6,
		'hi':	10e-6,
		'init': 5e-6,
	},
	'mirr_l': {
		'lo':	0.13e-6,
		'hi':	4e-6,
		'init': 1e-6,
	},
	'mirr_ld': {
		'lo':	0.13e-6,
		'hi':	4e-6,
		'init': 1e-6,
	},
	'out_w': {
		'lo':	0.15e-6,
		'hi':	10e-6,
		'init': 1.53e-6,
	},
	'out_l': {
		'lo':	0.13e-6,
		'hi':	4e-6,
		'init': 0.5e-6,
	},
	'load_w': {
		'lo':	0.15e-6,
		'hi':	10e-6,
		'init': 5e-6,
	},
	'load_l': {
		'lo':	0.13e-6,
		'hi':	4e-6,
		'init': 1e-6,
	},
	'diff_w': {
		'lo':	0.15e-6,
		'hi':	10e-6,
		'init': 5e-6,
	},
	'diff_l': {
		'lo':	0.13e-6,
		'hi':	4e-6,
		'init': 0.5e-6,
	},
	'c_out': {
		'lo':	1e-15,
		'hi':	50e-12,
		'init': 2e-12,
	},
	'r_out': {
		'lo':	1,
		'hi':	200e3,
		'init': 5e3,
	}
}

# Statistical parameters
# No explicit statistical parameters. Mismatch is modelled by the PDK
# (agauss() in the *_mismatch sections of cornerMOSlv.lib).
statParams={}

# Operating parameters definitions, lower bounds, upper bounds, and nominal values
opParams={
	'vdd': {
		'lo': 1.08,
		'hi': 1.32,
		'init': 1.2
	},
	'temperature': {
		'lo': 0.0,
		'hi': 100.0,
		'init': 25
	}
}
