#!/usr/bin/env python
"""
For this script to work properly, you may need set the following environment vars:
LD_LIBRARY_PATH ...so that libascend can be found
ASCENDLIBRARY ...so that your models can be found
ASCENDSOLVERS ... so that the QRSlv solver can be found
PYTHONPATH ...so that 'import ascpy' works correctly.
"""

# some tricky stuff to set up the environment variables so that ASCEND can find
# all the files it needs
import os, os.path, sys
if not os.environ.get('ASCENDLIBRARY'):
	if os.path.exists('/usr/bin/ascend'):
		ASCROOT="/usr/lib/ascend"
		os.environ['ASCENDLIBRARY'] = os.path.split(sys.path[0])[0] + ":" + os.path.join(ASCROOT,"models")
		os.environ['PYTHONPATH'] = "/usr/lib/python2.6/dist-packages/ascend/"
		print "Using installed version of ASCEND"
	else:
		ASCROOT= os.path.expanduser("~/ascend")
		os.environ['ASCENDLIBRARY'] = os.path.split(sys.path[0])[0] + ":" + os.path.join(ASCROOT,"models")
		os.environ['ASCENDSOLVERS'] = os.path.join(ASCROOT,"solvers","qrslv") + ":" + os.path.join(ASCROOT,"solvers","lsode") + ":" + os.path.join(ASCROOT,"solvers","ida")
		os.environ['PYTHONPATH'] = os.path.join(ASCROOT,"ascxx") + ":" + os.path.join(ASCROOT,"pygtk")
		os.environ['LD_LIBRARY_PATH'] = ASCROOT
	script=os.path.join(sys.argv[0])
	print "Restarting with corrected environment"
	os.execvp('/usr/bin/python',[script,script]+sys.argv[1:])

import ascpy, pylab
import TReport
# import NullReport


import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt


lib = ascpy.Library()
lib.load('dfe_dyn_FO.a4c')

M = lib.findType('dfe_dyn_FO').getSimulation('sim', False)
M.setSolver(ascpy.Solver('QRSlv'))

P = M.getParameters()

I = ascpy.Integrator(M)


I.setEngine('LSODE')
I.setLinearTimesteps(ascpy.Units("1"), 0.0, 10, 100);
I.setMinSubStep(0.1);
I.setMaxSubStep(1);
I.setInitialSubStep(0.001);
I.setMaxSubSteps(400);

I.setParameter('autodiff', False);
I.analyse();
reporter = TReport.TestReporter(I);
I.setReporter(reporter)
I.solve();

fig = plt.figure()
data = reporter.data;
plt.plot(reporter.t, data)
plt.show()


def airrec_tester():
	# prepare ASCEND's library object. you gotta do that.
	L = ascpy.Library()

	# load our model file
	L.load('dfe_dyn_FO.a4c')

	# hunt for the model name that we need from the file that we loaded
	T = L.findType('dfe_dyn_FO')

	# create the simulation. this is the same as the 'simulation' tab in the GUI
	M = T.getSimulation('sim', False)

	# run the 'on_load' method for this model... FIX all the vars, values etc.
	M.run(T.getMethod('on_load')) # you have to explicitly do this in Python

	# assign the 'QRSlv' solver to the problem
	M.setSolver(ascpy.Solver("QRSlv"))

	# solve the model
	M.solve(ascpy.Solver("QRSlv"),ascpy.SolverReporter())

# run all the stuff above!
airrec_tester()

