# -*- coding: UTF-8 -*-
import os, sys, traceback, json
from pyopus.misc.debug import DbgSetup, DbgMsgOut
DbgSetup(True, 1)

useMPI=False

projData={'analyses': {'AC': {'command': 'ac(10, 1e6, "dec", 100)',
                     'head': 'opus',
                     'modules': ['filter_netlist'],
                     'options': {},
                     'params': {},
                     'saves': []}},
 'analysisNames': ['AC'],
 'designPar': {'c1': {'hi': 6e-06, 'init': 2.5e-06, 'lo': 1e-09},
               'c2': {'hi': 6e-06, 'init': 2.5e-06, 'lo': 1e-09},
               'c3': {'hi': 6e-06, 'init': 2.8e-06, 'lo': 1e-09},
               'l1': {'hi': 0.002, 'init': 0.0014, 'lo': 1e-06},
               'r0': {'hi': 100000.0, 'init': 56000.0, 'lo': 1000.0},
               'r1': {'hi': 10000.0, 'init': 400, 'lo': 100}},
 'designParNames': ['r0', 'c1', 'l1', 'c2', 'r1', 'c3'],
 'headNames': ['opus'],
 'heads': {'opus': {'moddefs': {'filter_netlist': {'file': 'filter_netlist.cir'}},
                    'options': {},
                    'params': {},
                    'settings': {},
                    'simulator': 'SpiceOpus'}},
 'measureLower': {'BW': 1000},
 'measureNames': ['BW'],
 'measureNorm': {},
 'measureUpper': {'BW': 1100},
 'measures': {'BW': {'analysis': 'AC',
                     'depends': [],
                     'expression': 'm.ACbandwidth(v("out")/v("in"), scale(), '
                                   "filter='lp', levelType='db', level=-3.0)",
                     'vector': False}},
 'mirrormap': {'filter_netlist.cir': '.'},
 'opPar': {},
 'opParNames': [],
 'statPar': {},
 'statParNames': [],
 'variableNames': [],
 'variables': {}}

taskData={'cornerNames': ['nominal'],
 'corners': {('nominal', ('opus',)): {'modules': [], 'params': {}}},
 'fixedParameterNames': [],
 'name': 'analysis',
 'optParameterNames': ['r0', 'c1', 'l1', 'c2', 'r1', 'c3'],
 'output': {'aggregatordebug': 0,
            'evaluatordebug': 10,
            'keepfiles': False,
            'optimizerdebug': 0,
            'saveallresults': False,
            'savewaveforms': 'verification',
            'simulatordebug': 10,
            'taskdebug': 1},
 'parameterNames': ['r0', 'c1', 'l1', 'c2', 'r1', 'c3'],
 'parameters': {'c1': {'hi': 6e-06, 'init': 2.5e-06, 'lo': 1e-09},
                'c2': {'hi': 6e-06, 'init': 2.5e-06, 'lo': 1e-09},
                'c3': {'hi': 6e-06, 'init': 2.8e-06, 'lo': 1e-09},
                'l1': {'hi': 0.002, 'init': 0.0014, 'lo': 1e-06},
                'r0': {'hi': 100000.0, 'init': 56000.0, 'lo': 1000.0},
                'r1': {'hi': 10000.0, 'init': 400, 'lo': 100}},
 'requirementNames': [],
 'requirements': {'exclude': [],
                  'lower': {},
                  'norm': {},
                  'tradeoff': {},
                  'upper': {}},
 'settings': {'aggregatorsettings': {},
              'evaluatorsettings': {},
              'failurepenalty': 1000000.0,
              'forwardsolution': True,
              'incrementalcorners': True,
              'initialstep': 0.25,
              'maxiter': None,
              'method': 'noneFull',
              'optimizersettings': {},
              'stopsatisfied': True,
              'stoptol': 1e-05,
              'tradeoffmultiplier': 0},
 'type': 'cbd'}

if __name__=='__main__':
  import numpy as np
  np.random.seed(0)

  if useMPI:
    from pyopus.parallel.mpi import MPI
    from pyopus.parallel.cooperative import cOS

    cOS.setDebug(mpiData['cosdebug'])
    if mpiData['mirror']:
      vm=MPI(mirrorMap=projData['mirrormap'], persistentStorage=mpiData['persistent'], debug=mpiData['vmdebug'])
    else:
      vm=MPI(debug=mpiData['vmdebug'])
    cOS.setVM(vm)

    hosts=MPI.vmStatus['hosts']
    slots=MPI.vmStatus['slots']
    DbgMsgOut('VM', 'Process list (total %d):' % (len(slots)))
    for host in hosts.keys():
      DbgMsgOut('VM', '  Host %s with %d process(es)' % (host, len(hosts[host]['slots'])))
      for slot in hosts[host]['slots']:
        DbgMsgOut('VM', '    slot %d: pid=0x%x (%d)' % (slot, slots[slot]['pid'], slots[slot]['pid']))

  from pyopus.design.sqlite import SQLiteDatabase
  sqld=SQLiteDatabase(os.path.join('..', taskData['name']+'.sqlite'))

  from pyopus.gui.tasks import taskRunner

  try:
    runner=taskRunner[taskData['type']]
    runner(projData, taskData, sqld)
  except Exception as e:
    DbgMsgOut('TASK', 'Task terminated due to exception.')
    DbgMsgOut('TASK', traceback.format_exc())
    sys.exit(1)

  if useMPI:
    cOS.finalize()
