I have an ODE system. I'm looking for a solution of the system using PyDSTool. I try to put the integration step, but I get an error.
import PyDSTool as ds
from PyDSTool import Par, Var
import time
from PyDSTool import *
# Declare names and initial values for (symbolic) parameters
varepsilon = pow(10, -2)
j = 2.5*pow(10, -5)
e = 3.0
y8 = lambda y1,y5,y7: 1 / (1 - 2 / y1) * math.sqrt(y5 ** 2 + (1 - 2 / y1) * (1 + y1 ** 2 * y7 ** 2))
E0 = lambda y1,y8: (1 - 2 / y1) * y8
Phi0 = lambda y1,y7: y1 ** 2 * y7
# Compute nontrivial boundary equilibrium initial condition from parameters (see reference for derivation)
u0 = -math.sqrt(-1 + math.sqrt(varepsilon ** 2 + 12) / varepsilon) * math.sqrt(2) / 6
v0 = 1 / (1 - 2 / e) * math.sqrt(j ** 2 + (1 - 2 / e) * (e ** 2 * u0 ** 2 + 1))
y08 = y8(y1=e, y5=j, y7=u0);
E = E0(y1=e, y8=y08); Phi = Phi0(y1=e, y7=u0)
z01, z03, z04, z05, z07, z08 = e, 0.0, 0.0, j, u0, v0
# Declare symbolic variables
z1, z3, z4, z5, z7, z8 = Var('z1'), Var('z3'), Var('z4'), Var('z5'), Var('z7'), Var('z8')
# Create Symbolic Quantity objects for definitions
p1 = -z1*z5/(z1 - 2);
p3 = -z1**2 *z7;
p4 = z8*(1 - 2/z1);
Q1 = -z5**2/(z1*(z1 - 2)) + (z8**2/z1**3 - z7**2)*(z1 - 2);
Q3 = 2*z5*z7/z1;
Q4 = 2*z5*z8/(z1*(z1 - 2));
c1 = z1*z7*varepsilon;
c3 = -z1*z5*varepsilon;
C = z7*varepsilon/z1 - z8*(1 - 2/z1);
d1 = -z1*z8*varepsilon;
d3 = z1*z5*varepsilon;
B = z1**2*z7 - z8*varepsilon*(1 - 2/z1);
Omega = 1/(c1*d3*p3+c3*d1*p4-c3*d3*p1);
# differential equations
z1dot = z5;
z3dot = z7;
z4dot = z8;
z5dot = Omega*(-Q1*c1*d3*p3 - Q1*c3*d1*p4 + Q1*c3*d3*p1 + B*c3*p4 + C*d3*p3 + E*d3*p3 - Phi*c3*p4);
z7dot = -Omega*(Q3*c1*d3*p3 + Q3*c3*d1*p4 - Q3*c3*d3*p1 + B*c1*p4 - C*d1*p4 + C*d3*p1 - E*d1*p4 + E*d3*p1 - Phi*c1*p4);
z8dot = Omega*(-Q4*c1*d3*p3 - Q4*c3*d1*p4 + Q4*c3*d3*p1 + B*c1*p3 - B*c3*p1 - C*d1*p3 - E*d1*p3 - Phi*c1*p3 + Phi*c3*p1);
# Build Generator
DSargs = args(name='Sining particle')
#print(dir(DSargs))
#DSargs.pars = [varepsilon, j, e]
DSargs.MaxNumPoints = 450
DSargs.MaxStepSize = 2e-2
DSargs.MinStepSize = 1e-5
DSargs.StepSize = e-2
DSargs.tdata = [0.0, 0.1]
DSargs.varspecs = args(z1=z1dot, z3=z3dot, z4=z4dot, z5=z5dot, z7=z7dot, z8=z8dot)
# Use eval method to get a float value from the symbolic definitions given in
# terms of parameter values
DSargs.ics = args(z1=z01, z3=z03, z4=z04, z5=z05, z7=z07, z8=z08)
ode = Generator.Vode_ODEsystem(DSargs)
t = time.time()
result = ode.compute('test')
print("time for integration: %f" %(time.time() - t))
pts = result.sample()
plt.plot(pts['t'], pts['z7'], label='x')
plt.legend()
plt.xlabel('t')
plt.show()
Through the next lines I get an the error:
DSargs.MaxNumPoints = 450
DSargs.MaxStepSize = 2e-2
DSargs.MinStepSize = 1e-5
DSargs.StepSize = e-2
Traceback (most recent call last):
File "C:\Users\mykola\Downloads\pydstool.py", line 65, in <module>
ode = Generator.Vode_ODEsystem(DSargs)
File "C:\Users\mykola\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PyDSTool\Generator\Vode_ODEsystem.py", line 47, in __init__
ODEsystem.__init__(self, kw)
File "C:\Users\mykola\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PyDSTool\Generator\ODEsystem.py", line 61, in __init__
self.checkArgs(kw)
File "C:\Users\mykola\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PyDSTool\Generator\baseclasses.py", line 1069, in checkArgs
raise PyDSTool_KeyError('Invalid keyword arguments for this class')
PyDSTool.errors.PyDSTool_KeyError: 'Invalid keyword arguments for this class'
The library PyDSTool has very little training information in internet.
What I do wrong?. And how to correctly determine the step of integration?
Related
I had read documentation and trying to understand how to work with scipy.optimize.minimize(), but my code just doesn't work, it keeps showing that"ValueError: The user-provided objective function must return a scalar value."
Here is my code:
PH = np.linspace(0, 14, 71)
ni_total = 0.1
citrate_total = 0.9
ammonia_total = 0.3
def concs(citrate_total,ni_total, ammonia_total, PH):
h = 10 ** (-PH)
def equations(p):
cit3, nio2, nh4 = p
Hcit = h*cit3*k4
H2cit = h*Hcit*k3
H3cit = h*H2cit*k2
ni2pfree = (nio2*k1*(h**2))/(1+((nio2*k1*(h**2))/ni_total))
NiH2cit = k7*ni2pfree*H2cit
NiHcit = k6*ni2pfree*Hcit
Nicit = k5*ni2pfree*cit3
nh3 = k8*nh4/h
nin4p2 = k9*(nh4**4)/(h**2)
nin6p2 = k10*(nh4**6) /(h**4)
return (citrate_total - Hcit - H2cit - H3cit - Nicit - NiHcit - NiH2cit - cit3,
ni_total - Nicit - NiHcit - NiH2cit - ni2pfree - nin4p2- nin6p2- nio2,
ammonia_total-nh3-4*nin4p2-6*nin6p2-nh4)
initial_guess=[0.1,0.1,0.1]
res = minimize(equations,initial_guess)
cit3 = res.x[0]
nio2 = res.x[1]
nh4 = res.x[2]
ni2pfree = (nio2 * k1 * (h ** 2)) / (1 + ((nio2 * k1 * (h ** 2)) / ni_total))
Hcit = h * cit3 *k4
H2cit = h * Hcit * k3
H3cit = h * H2cit * k2
NiH2cit = k7 * ni2pfree * H2cit
NiHcit = k6 * ni2pfree * Hcit
Nicit = k5 * ni2pfree * cit3
nh3 = k8 * nh4 / h
nin4p2 = k9 * (nh4 ** 4) / (h ** 2)
nin6p2 = k10 * (nh4 ** 6) / (h ** 4)
return [cit3, nio2, nh4, ni2pfree, Hcit, H2cit, H3cit, NiH2cit, NiHcit, Nicit,nh3,nin4p2,nin6p2]
The function scipy.optimize.minimize() takes in (among others) as arguments the objective fun and initial value x0. fun must return a single real number (also referred to as a scalar); not a list or a tuple.
In contrast, your function returns
def equations(p):
# code
return (..., ..., ...)
Change it to
def equations(p):
# code
return x
with the function value x of equations() that you actually want to minimize.
I am trying to create a specific output pattern for a textfile I wanted to later load into C++.
I wrote a file in Python that creates random coordinates and movement values in a circle.
The output is supposed to have the output:
Place_1 Place_2 Place_3 Movement_1 Movement_2 Movement_3\n
Place_1 Place_2 Place_3 Movement_1 Movement_2 Movement_3\n
Place_1 Place_2 Place_3 Movement_1 Movement_2 Movement_3
The Code is use is
import numpy as np
file = open('log.txt', 'a')
def f(n, center, radius, ecc):
pos = np.zeros((n,6))
r = ecc * radius
for i in range(n):
while 1:
x_1 = -1 + 2 * np.random.rand(1)
x_2 = -1 + 2 * np.random.rand(1)
if (x_1*x_1 + x_2*x_2)<1 :
pos[i,0] = center[0] + r * 2 * x_1 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[i,1] = center[1] + r * 2 * x_2 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[i,2] = center[2] + r * (1 - 2 * (x_1*x_1 + x_2*x_2))
pos[i,3] = (-1 + 2 * np.random.rand(1))
pos[i,4] = (-1 + 2 * np.random.rand(1))
pos[i,5] = (-1 + 2 * np.random.rand(1))
break
string = str(pos[i,:]).strip('[]').rstrip('\n')
file.write(string)
return
f(10000, np.array((127,127,127)), 92, 0.9)
file.close()
The log I create is however very badly formated. How can I get the required format?
You're going to a lot of trouble here that you don't need. This seems to solve the problem, simply.
import numpy as np
file = open('log.txt', 'a')
def f(n, center, radius, ecc):
r = ecc * radius
for i in range(n):
while 1:
pos = [0]*6
x_1 = -1 + 2 * np.random.rand(1)[0]
x_2 = -1 + 2 * np.random.rand(1)[0]
if (x_1*x_1 + x_2*x_2) < 1:
pos[0] = center[0] + r * 2 * x_1 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[1] = center[1] + r * 2 * x_2 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[2] = center[2] + r * (1 - 2 * (x_1*x_1 + x_2*x_2))
pos[3] = (-1 + 2 * np.random.rand(1)[0])
pos[4] = (-1 + 2 * np.random.rand(1)[0])
pos[5] = (-1 + 2 * np.random.rand(1)[0])
break
print(*pos, file=file)
f(10000, np.array((127,127,127)), 92, 0.9)
file.close()
A solution without numpy:
import math
import random
file = open('log.txt', 'a')
def f(n, center, radius, ecc):
r = ecc * radius
for _ in range(n):
pos = [0]*6
while 1:
x_1 = 2 * random.random() - 1
x_2 = 2 * random.random() - 1
vector = x_1*x_1 + x_2*x_2
if vector < 1:
break
pos[0] = center[0] + r * 2 * x_1 * math.sqrt(1 - vector)
pos[1] = center[1] + r * 2 * x_2 * math.sqrt(1 - vector)
pos[2] = center[2] + r * (1 - 2 * vector)
pos[3] = 2 * random.random() -1
pos[4] = 2 * random.random() -1
pos[5] = 2 * random.random() -1
print(*pos, file=file)
f(10000, (127,127,127), 92, 0.9)
file.close()
Use np.savetxt:
import numpy as np
def f(n, center, radius, ecc):
pos = np.zeros((n,6))
r = ecc * radius
for i in range(n):
while 1:
x_1 = -1 + 2 * np.random.rand(1)
x_2 = -1 + 2 * np.random.rand(1)
if (x_1*x_1 + x_2*x_2)<1 :
pos[i,0] = center[0] + r * 2 * x_1 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[i,1] = center[1] + r * 2 * x_2 * np.sqrt(1 - x_1*x_1 - x_2*x_2)
pos[i,2] = center[2] + r * (1 - 2 * (x_1*x_1 + x_2*x_2))
pos[i,3] = (-1 + 2 * np.random.rand(1))
pos[i,4] = (-1 + 2 * np.random.rand(1))
pos[i,5] = (-1 + 2 * np.random.rand(1))
break
np.savetxt('file.txt',pos,delimiter=';')
return
f(100, np.array((127,127,127)), 92, 0.9)
For the formatting issue you can make the coordinates into characters (What I mean is that turn coordinates into a character that would be printed like _ or / something like that) Also you can put empty space in a print like print(" Hello.") also to go to a different line in the console do print("\n Hello."). This probably was not what you were looking for but I hope this somewhat helps.
I'm currently trying to run this block of code.
# %% Imports
import numpy as np
import sympy as sy
import scipy as sc
alpha = sy.Symbol('alpha', real=True)
beta = sy.Symbol('beta', real=True)
s_0 = sy.Symbol('s_0', real=True)
s_1 = sy.Symbol('s_1', real=True)
s_2 = sy.Symbol('s_2', real=True)
t = sy.Symbol('t', real=True)
#run checks on S(t) whether S(t) > S0 for current iteration
def main():
# A. Defining equations to constant variables to be called later
#S(t) > S0, (S(t) + β/α)*S(t) > 0
MODEL_1_1 = ((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(beta*t)) / (1 - (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(beta*t)))
#S(t) > S0, (S(t) + β/α)*S(t) < 0
MODEL_1_2 = -((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(beta*t)) / (1 + (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(beta*t)))
#S(t) < S0, (S(t) + β/α)*S(t) > 0
MODEL_1_3 = ((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(-sy.Abs(beta)*t)) / (1 - (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(-sy.Abs(beta)*t)))
#S(t) < S0, (S(t) + β/α)*S(t) > 0
MODEL_1_4 = -((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(-sy.Abs(beta)*t)) / (1 + (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(-sy.Abs(beta)*t)))
#---------------------------------------------------------------
# B. Initializing values
stock_price = [25725, 25600, 24600]
#---------------------------------------------------------------
# C. Get 2 functions for every t = 1 and t = 2
## C.1. processing t1
if (stock_price[1] > stock_price[0]):
eq1 = MODEL_1_1.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq2 = MODEL_1_2.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
else:
eq1 = MODEL_1_3.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq2 = MODEL_1_4.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
#print(eq1)
#print(eq2)
## C.2. processing t2
if (stock_price[2] > stock_price[0]):
eq3 = MODEL_1_1.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq4 = MODEL_1_2.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
else:
eq3 = MODEL_1_3.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq4 = MODEL_1_4.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
#print(eq3)
#print(eq4)
#------------------------------------------------
# D. Run 4 different solution, get 4 sets of possible (α,β) pair
## D.1. eq1 vs. eq3 -- (S(1) + β/α)*S(1) > 0, (S(2) + β/α)*S(2) > 0
print(eq1)
print(eq3)
sol1 = sy.solvers.nsolve([sy.Eq(eq1,stock_price[1]), sy.Eq(eq3,stock_price[2])],[alpha,beta],[-1,1])
print(sol1)
## D.2. eq2 vs. eq3 -- (S(1) + β/α)*S(1) < 0, (S(2) + β/α)*S(2) > 0
## D.3. eq1 vs. eq4 -- (S(1) + β/α)*S(1) > 0, (S(2) + β/α)*S(2) < 0
## D.4. eq2 vs. eq4 -- (S(1) + β/α)*S(1) < 0, (S(2) + β/α)*S(2) < 0
#check for contradictions against initial condition
#return values that satisfies all condition
#run t = 3 based on the iteration
#repeat
main()
However it keeps throwing
Could not find root within given tolerance. (655317900.776688019361 >
2.16840434497100886801e-19) Try another starting point or tweak arguments.
or
matrix is numerically singular
whenever I try to tweak around the initial starting point.
Could anyone help / suggest alternatives to nsolve for this particular function?
Edit 1:
adding tracebacks
Traceback (most recent call last):
File "D:\SKRIPSI ANDREE\Code\model1.py", line 76, in <module>
main()
File "D:\SKRIPSI ANDREE\Code\model1.py", line 64, in main
sol1 = sy.solvers.nsolve([sy.Eq(eq1,stock_price[1]), sy.Eq(eq3,stock_price[2])],[alpha,beta],[-1,1])
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\utilities\decorator.py", line 88, in func_wrapper
return func(*args, **kwargs)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\solvers\solvers.py", line 2954, in nsolve
x = findroot(f, x0, J=J, **kwargs)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\calculus\optimization.py", line 969, in findroot
for x, error in iterations:
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\calculus\optimization.py", line 660, in __iter__
s = self.ctx.lu_solve(Jx, fxn)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\matrices\linalg.py", line 226, in lu_solve
A, p = ctx.LU_decomp(A)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\matrices\linalg.py", line 136, in LU_decomp
raise ZeroDivisionError('matrix is numerically singular')
ZeroDivisionError: matrix is numerically singular
My global variables are not working in my code. I'm fairly new to this and I can't seem to figure this out: I have set variables (only showing gna for this), which can be manipulated by an entry field, triggered by a corresponding button. For some reason, it's not taking the changes within the loop. I'm trying to make it to where the changed variable can be graphed as well, but it gives me the following error:
Exception in Tkinter callback Traceback (most recent call last):
File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args) File "G:/PYTHON/Eulers.py", line 64, in graph
v[i + 1] = 1 / c * (gna * f[i] - gk * u[i]) * del_t + v[i]
TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('< U32') dtype('< U32') dtype('< U32')
Here is the code:
gna = 0.9
gnalabel = Label(topFrame, text="gna = %s" % gna)
gnalabel.pack()
gnaEntry = Entry(topFrame, justify=CENTER)
gnaEntry.pack()
def gnacallback():
global gna
gna = gnaEntry.get()
gnalabel.config(text="C = %s" % gna)
gnaButton = Button(topFrame, text="Change", width=10, command=gnacallback)
gnaButton.pack()
def graph():
global c, gna, gk, beta, gamma
for i in range(0, len(t)-1):
stinum = np.floor(i / 3000)
stimt = 3000 + 3000 * (stinum - 1)
f[i] = v[i] * (1 - (((v[i]) ** 2) / 3))
v[i + 1] = 1 / c * (gna * f[i] - gk * u[i]) * del_t + v[i]
if(i == stimt):
v[i + 1] = v[i + 1] + v_stim
u[i + 1] = (v[i] + beta - gamma * u[i]) * del_t + u[i]
plt.plot(v)
plt.show()
gna = gnaEntry.get()
Entry.get returns a string, which is probably an unsuitable type for the arithmetic you're doing in graph. Try converting to a number first.
gna = float(gnaEntry.get()) #or perhaps `int` if it's always an integer
I am new to python, transiting from Matlab. I wrote the following code to solve a nonlinear equation system but somehow failed in python. It worked in matlab fsolve for many initial values unless I put an extremely large number. But it only works for python fsolve if the initial value is close enough to the solution. I don't always have good initial guess to the problem so I want it to work most of the time. Thank you very much! Solution is [0.003,0.0053] according to Matlab.
Python code
param = {'r': 0.04,
'mu': 0.112,
'delta': 0.02,
'alpha': 0.35,
'g': 0.0187 + 0.5*0.16*0.16,
'sigma': 0.20,
'xi0': 0.02,
'xi1':1.05,
'lambda0':0.02,
'lambda1':1.05};
param['sgsq'] = 0.5*param['sigma']**2;
param['g0'] = param['g'] - (param['mu'] - param['r']) - param['sgsq'];
#%% Polynomial
import numpy as np
import numpy.polynomial.polynomial as poly
import scipy.optimize as spyopt
param['coef'] = (- (param['r']+param['delta']), (param['g0']+param['delta']
-param['sgsq']), param['sgsq'])
charfun = poly.Polynomial(param['coef'])
param['psi'] = np.max(poly.polyroots(param['coef']))
param['halpha'] = poly.polyval(param['alpha'],param['coef'])
def lumpyfun(x0, param0):
xstar,B = x0
AIPx = - np.power(xstar,param0['alpha']) / param0['halpha']
BigA = ((1.0-param0['alpha'])*(B**param0['alpha'])/(1.0-param0['psi'])/param0['halpha']
+ (param0['lambda1']-param0['lambda0'])/(1.0-param0['psi']))
vprimex = param0['alpha']*AIPx/xstar + param0['psi']*np.power((xstar/B),(param0['psi']-1.0)) * BigA/B
vprimeB = (param0['psi']-param0['alpha'])*np.power(B,param0['alpha']-1.0)/(1.0-param0['psi'])/param0['halpha'] + param0['psi']*(param0['lambda1']-param0['lambda0'])/(1.0-param0['psi'])/B
diffy = (AIPx + np.power(xstar/B,param0['psi']) * BigA - xstar*vprimex - param0['lambda1'], vprimex - vprimeB)
return diffy`def lumpyfun(x0, param0):
#%% Solve the problem
#worked
x0 = np.multiply(np.sqrt(-param['halpha']),(1.0,2.0))/100.0
#lumpyfun(x0,param)
spyopt.fsolve(lumpyfun, x0, args=param)
# not worked
x0 = np.multiply(np.sqrt(-param['halpha']),(1.0,2.0))/10.0
spyopt.fsolve(lumpyfun, x0, args=param, maxfev = 5000000)
Matlab code:
r = 0.04;
mu = 0.112;
delta = 0.02;
alpha = 0.35;
g = 0.0187 + 0.5*0.16*0.16 ; % 0.0187 + 0.5*sigma*sigma;
sigma = 0.20; % 0.16 default;
a2 = 0.5*sigma*sigma;
g0 = g - (mu-r) - a2; % risk-neutral growth;
lambda0 = 0.02;
lambda1 = 1.05;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%h = #(x) sgsq05*x^2 + (mu+delta-sgsq05)*x - (r+delta);
coef = [a2, (g0+delta-a2), - (r+delta)];
halpha = polyval(coef,alpha);
phi = max(roots(coef))
x0 = realsqrt(-halpha)*[1;2]/10;
options = optimoptions('fsolve','Display','off','MaxFunEvals',2000);
sol = fsolve(#(x) diffinvestmentoption(x,phi,alpha,lambda1,lambda0,halpha), x0, options);
function [diffy,X] = diffinvestmentoption(xin,phi,alpha,lambda1,lambda0,halpha)
xstar = xin(1);
B = xin(2);
AIPx = -xstar.^alpha / halpha;
%AIPB = -B.^alpha / halpha;
BigA = (1-alpha)*(B^alpha)/(1-phi)/halpha + (lambda1-lambda0)/(1-phi);
vprimex = alpha*AIPx/xstar + phi*(xstar/B)^(phi-1) * BigA/B;
vprimeB = (phi-alpha)*(B^(alpha-1))/(1-phi)/halpha + phi*(lambda1-lambda0)/(1-phi)/B;
diffy = [AIPx + (xstar/B)^phi * BigA - xstar*vprimex - lambda1;
vprimex - vprimeB];