# Creating the model

```python
%config InlineBackend.figure_format = 'retina'
```

    Overwriting /home/gpetrini/Documentos/Pesquisas/SSM_Brochier/teste.py

```python
import pandas as pd
from sympy import Abs
```

```python
from pysolve3.model import Model
from pysolve3.utils import is_close,round_solution
import numpy as np
import random
import matplotlib.pyplot as plt
%matplotlib inline

def create_inet_model():
    model = Model()

    # Accounting
    model.set_var_default(0)
    model.var('Y', desc='GDP')
    model.var('C', desc='Consumption')
    model.var('Id', desc='Investment') # I is reserved to numpy
    model.var('Omega', desc='Wage share')
    model.var('Pi', desc='Profit share')

    # Identities
    model.var('K', desc='Capital Stock')
    model.var('gk', desc='Capital Stock growth rate')
    model.var('Yfc', desc='Full Capacity out-put')
    model.var('u', desc='Capacity utilization ration')

    # Households
    model.var('Yh', desc='Households’ income')
    model.var('Ydh', desc='Households’ disposable income')
    model.var('W', desc='Wages')
    model.var('FD', desc='Profits')
    model.var('Mh', desc='Bank deposits')
    model.var('B', desc='Government Bills')
    model.var('Sh', desc='Savings of Household')
    model.var('Vh', desc='Household net wealth')
    model.var('pe', desc='Equities price')
    model.var('Lambda', desc='proportion of household wealth allocated in equities')
    model.var('Eq', desc='Equities') # E is reserved for sympy

    # Firms
    model.var('Lf', desc='Firms Loans')
    model.var('FU', desc='Retained profits')
    model.var('Ft', desc='Total profits')
    model.var('Fg', desc='Gross Profits')
    model.var('h', desc='Propensity to invest')

    # Government
    model.var('G', desc='Government Expenditure')
    model.var('T', desc='Taxes')

    # Profits
    model.var('rn', desc='Net profit rate')
    model.var('rg', desc='Gross profit rate')

    # Accouting
    model.param('v', desc='Capital-Output ratio')
    model.param('mu', desc='Mark-up')

    #-----------------------------
    # Identities
    model.param('delta', desc='Depreciation')

    # Households
    model.param('Lambda0', desc='Expectation of return')
    model.param('alpha1', desc='Consumption Sensitivity of wages')
    model.param('alpha2', desc='Consumption Sensitivity of wealth')
    model.param('rm', desc= 'Deposits interest rate')
    model.param('rb', desc= 'Bills interest rate')
    model.param('tau', desc='Direct taxes')
    model.param('alpha4', desc='d(pe) effect')

    # Firms
    model.param('sf', desc='Distribution of profits')
    model.param('a', desc='Fixed parameter')
    model.param('gamma', desc='adjstment parameter')
    model.param('un', desc='Natural capacity utilization rate')

    # Government
    model.param('sigma', desc='Government expenditure rate')

    #-----------------------------
    model.add('B = B(-1) + G - T + rb*B(-1)') # Eq (1) # Checked
    model.add('G = sigma*Y(-1)') # Eq (2) # Checked
    model.add('T= tau*Yh') # Eq (3) # Checked
    model.add('Yh = W + FD + rm*(B(-1) + Mh(-1))') # Eq (4) # Checked
    model.add('W = (1-Pi)*Y') # Eq (5) # Checked
    model.add('Ydh = (1-tau)*Yh') # Eq (6) # Checked
    model.add('C = alpha1*(1-tau)*W + alpha2*Vh(-1)') # Eq (7) # Checked
    model.add('Sh = Ydh - C') # Eq (8) # Checked
    model.add('Lambda = Lambda0 - rb') # Eq (9) # Checked
    model.add('pe = (Lambda*Vh)/Eq') # Dynamic # Eq (10) # Checked
    model.add('Vh = Vh(-1) + Sh + d(pe)*Eq(-1)') # Eq (11) # Checked
    model.add('Mh = Mh(-1) + Sh - pe*d(Eq) - d(B)') # Eq (12) # Checked
    model.add('Pi = mu/(1+mu)') # Eq (13) # Checked
    model.add('Omega = 1 - Pi') # Aux (1) # Checked
    model.add('Id = h*Y') # Eq (14) # Checked
    model.add('h = h(-1) + if_true(u - un > 0.001)*h(-1)*gamma*(u-un) + if_true(un - u > 0.001)*h(-1)*gamma*(u-un)') # Eq (15)
    #model.add('h = h(-1) + h(-1)*gamma*(u-un)') # Aux (2)
    model.add('K = K(-1) + Id - delta*K(-1)') # Eq (16) # Corrected (delta*K(-1))
    model.add('Yfc = K(-1)/v') # Eq (17) # Checked
    model.add('u = Y/Yfc') # Eq (18) # Checked
    model.add('gk = (h*u)/v - delta') # Eq (19) # Checked
    model.add('Lf = Lf(-1) + Id - FU - pe*d(Eq)') # Eq (20) # Checked
    model.add('Eq = a*K(-1)') # Eq (21) # Checked
    model.add('FU = sf*(Pi*Y - rm*Lf(-1))') # Eq (22) # Checked
    model.add('FD= (1-sf)*(Pi*Y - rm*Lf(-1))') # Eq (23) # Checked
    model.add('Ft = (Pi*Y - rm*Lf(-1))') # Eq (24) # Checked
    model.add('Fg = Pi*Y') # Eq (25)
    model.add('rn = Pi*u/v - rb*(Lf(-1))/K(-2)') # Eq (26)
    model.add('rg = Pi*u/v') # Eq (26)

    model.add('Y = C + Id + G') # Eq (28)
    #----------------
    model.var('Z', desc='Autonomous')

    model.add('Z = alpha2*Vh(-1)')

    return model
```

# Defining values

```python
parameters = {'h': 0.2,
              'gamma': 0.014,
              'delta': 0.044,
              'alpha1': 0.8,
              'alpha2': 0.03375,
              'sf': 0.4,
              'a':0.1,
              'sigma':0.34
             }

exogenous = {'mu': 0.7, #Pi = 0.411765
             'un': 0.8,
             'v': 2.5,
             'rm': 0.02,
             'rb': 0.02,
             'tau': 0.37,
             'Lambda0': 0.08,
             'pe': 0.9880216216216237
            }
initial = {'Eq': 9.80392156862745, # Warning
          'K' : 100,
           'Y' : 31.372549019607845,
          'B' : 73.65483130189038,
          'Vh' : 161.44144144144184,
          'Lf' : 78.29005476064303,
          'G' : 10.457516339869283,
          'Id' : 6.274509803921569,
          'C' : 14.640522875816991,
          'FD' : 6.829805584130843,
          'FU' : 4.553203722753896,
          'Sh' : 3.1655184596361137}
```

```python
SFC_Base = create_inet_model()
SFC_Base.set_values(parameters)
SFC_Base.set_values(exogenous)
SFC_Base.set_values(initial)
```

# Solving

```python
%time
start = 1700
time = 500

for i in range(start):
    SFC_Base.solve(iterations=100, threshold=1e-5)

for i in range(time):
    SFC_Base.solve(iterations=100, threshold=1e-5)
```

    CPU times: user 4 µs, sys: 0 ns, total: 4 µs
    Wall time: 8.34 µs

# Getting data

```python
Y = [s['Y'] for s in SFC_Base.solutions[start:]]
Ydh = [s['Ydh'] for s in SFC_Base.solutions[start:]]
Id = [s['Id'] for s in SFC_Base.solutions[start:]]
K = [s['K'] for s in SFC_Base.solutions[start:]]
C = [s['C'] for s in SFC_Base.solutions[start:]]
W = [s['W'] for s in SFC_Base.solutions[start:]]
u = [s['u'] for s in SFC_Base.solutions[start:]]
FD = [s['FD'] for s in SFC_Base.solutions[start:]]
FU = [s['FU'] for s in SFC_Base.solutions[start:]]
Ft = [s['Ft'] for s in SFC_Base.solutions[start:]]
Lf = [s['Lf'] for s in SFC_Base.solutions[start:]]
Mh = [s['Mh'] for s in SFC_Base.solutions[start:]]
Vh = [s['Vh'] for s in SFC_Base.solutions[start:]]
Eq = [s['Eq'] for s in SFC_Base.solutions[start:]]
pe = [s['pe'] for s in SFC_Base.solutions[start:]]
h = [s['h'] for s in SFC_Base.solutions[start:]]
G = [s['G'] for s in SFC_Base.solutions[start:]]
B = [s['B'] for s in SFC_Base.solutions[start:]]
Z = [s['Z']/s['Y'] for s in SFC_Base.solutions[start:]]
rn = [s['rn'] for s in SFC_Base.solutions[start:]]
rg = [s['rg'] for s in SFC_Base.solutions[start:]]

Lf_Y = [Lf[s]/Y[s] for s in range(2,time-start)]
Ft_Y = [Ft[s]/Y[s] for s in range(2,time-start)]
FU_Y = [FU[s]/Y[s] for s in range(2,time-start)]
FD_Y = [FD[s]/Y[s] for s in range(2,time-start)]

gY =  [(Y[i]-Y[i-1])/Y[i-1] for i in range(2,time-start)]
gId = [(Id[i]-Id[i-1])/Id[i-1] for i in range(2,time-start)]
gK = [(K[i]-K[i-1])/K[i-1] for i in range(2,time-start)]
gC = [(C[i]-C[i-1])/C[i-1] for i in range(2,time-start)]
gW = [(W[i]-W[i-1])/W[i-1] for i in range(2,time-start)]
gG = [(G[i]-G[i-1])/G[i-1] for i in range(2,time-start)]
gFD = [(FD[i]-FD[i-1])/FD[i-1] for i in range(2,time-start)]
gFU = [(FU[i]-FU[i-1])/FU[i-1] for i in range(2,time-start)]
gFt = [(Ft[i]-Ft[i-1])/Ft[i-1] for i in range(2,time-start)]
gLf = [(Lf[i]-Lf[i-1])/Lf[i-1] for i in range(2,time-start)]
gMh = [(Mh[i]-Mh[i-1])/Mh[i-1] for i in range(2,time-start)]
gVh = [(Vh[i]-Vh[i-1])/Vh[i-1] for i in range(2,time-start)]
gEq = [(Eq[i]-Eq[i-1])/Eq[i-1] for i in range(2,time-start)]
gB = [(B[i]-B[i-1])/B[i-1] for i in range(2,time-start)]
gZ = [(Z[i]-Z[i-1])/Z[i-1] for i in range(2,time-start)]

```

```python
from pysolve3.utils import is_aclose, round_solution

def print_solutions(solns, vars, indexes):
    print("----------------")
    s = "{0:12} :".format('period')
    for i in indexes:
        s += "   {0: >10} ".format(i)
    print(s)
    for x in vars:
        s = "{0:12} :".format(x[0])
        for i in indexes:
            s += "   {0: >10.5f}".format(solns[i][x[1]])
            if i != 0:
                if not is_aclose([solns[i][x[1]],], [solns[i-1][x[1]],], rtol=1e-4):
                    s += '' #not closed yet
                else:
                    s += '*' #closed
            else:
                s += ' '
        print(s)

ax = sorted([(str(k), k) for k,v in SFC_Base.solutions[0].items()], key=lambda x: x[0])
print_solutions(SFC_Base.solutions, ax, [0, 1, 2, 3, -1])

nice_solution = round_solution(SFC_Base.solutions[-1], decimals=1)
#print_solutions([nice_solution,], ax, [0])
```

    ----------------
    period       :            0             1             2             3            -1
    B            :     73.65483      75.70576     77.82754     80.01193   879139495277667680256.00000
    C            :     14.64052      14.93711     15.18043     15.41565   45457336041602539520.00000
    Eq           :      9.80392      10.00000     10.20009     10.40282   30486008305403645952.00000
    FD           :      6.82981       6.96757      7.09028      7.20381   21213018163402825728.00000
    FU           :      4.55320       4.64505      4.72686      4.80254   14142012108935217152.00000
    Fg           :      0.00000      13.17842     13.41421     13.63529   40137494445322698752.00000
    Ft           :      0.00000      11.61262     11.81714     12.00635   35355030272338042880.00000
    G            :     10.45752      10.66667     10.88161     11.07631   32490390976258146304.00000
    Id           :      6.27451       6.40095      6.51533      6.62232   19529107655445782528.00000
    K            :    100.00000     102.00095    104.02824    106.07331   310975347055104622592.00000
    Lambda       :      0.00000       0.06000      0.06000*      0.06000*      0.06000*
    Lambda0      :      0.08000       0.08000*      0.08000*      0.08000*      0.08000*
    Lf           :     78.29005      79.85346     81.44670     83.06982   243919839962890338304.00000
    Mh           :      0.00000      -0.00232     -0.00626     -0.01226   -408708122282351722496.00000
    Omega        :      0.00000       0.58824      0.58824*      0.58824*      0.58824*
    Pi           :      0.00000       0.41176      0.41176*      0.41176*      0.41176*
    Sh           :      3.16552       2.24110      2.31309      2.37505   9841417800980955136.00000
    T            :      0.00000      10.08881     10.27396     10.44849   32476967713509421056.00000
    Vh           :    161.44144     163.62081    165.87384    168.19127   500458900500298792960.00000
    W            :      0.00000      18.82632     19.16315     19.47898   57339277779032440832.00000
    Y            :     31.37255      32.00473     32.57737     33.11427   97476834673306468352.00000
    Ydh          :      0.00000      17.17821     17.49352     17.79070   55298753842583494656.00000
    Yfc          :      0.00000      40.00000     40.80038     41.61129   121944033221614583808.00000
    Yh           :      0.00000      27.26701     27.76749     28.23920   87775799750132531200.00000
    Z            :      0.00000       5.44865      5.52220      5.59824   16558340040970188800.00000
    _B__1        :     73.65483      73.65483*     75.70576     77.82754   861888151592989884416.00000
    _Eq__1       :      9.80392       9.80392*     10.00000     10.20009   29886507441990660096.00000
    _K__1        :    100.00000     100.00000*    102.00095    104.02824   304860083054036451328.00000
    _K__2        :    100.00000     100.00000*    100.00000*    102.00095   298865074419906576384.00000
    _Lf__1       :     78.29005      78.29005*     79.85346     81.44670   239123208649232777216.00000
    _Mh__1       :      0.00000       0.00000*     -0.00232     -0.00626   -400707711462580092928.00000
    _Vh__1       :    161.44144     161.44144*    163.62081    165.87384   490617482695412940800.00000
    _Y__1        :     31.37255      31.37255*     32.00473     32.57737   95559973459582779392.00000
    _h__1        :      0.20000       0.20000*      0.20000*      0.20000*      0.20035*
    _pe__1       :      0.98802       0.98802*      0.98172      0.97572      0.98496*
    a            :      0.10000       0.10000*      0.10000*      0.10000*      0.10000*
    alpha1       :      0.80000       0.80000*      0.80000*      0.80000*      0.80000*
    alpha2       :      0.03375       0.03375*      0.03375*      0.03375*      0.03375*
    delta        :      0.04400       0.04400*      0.04400*      0.04400*      0.04400*
    gamma        :      0.01400       0.01400*      0.01400*      0.01400*      0.01400*
    gk           :      0.00000       0.02001      0.01988      0.01966      0.02006*
    h            :      0.20000       0.20000*      0.20000*      0.19998*      0.20035*
    mu           :      0.70000       0.70000*      0.70000*      0.70000*      0.70000*
    pe           :      0.98802       0.98172      0.97572      0.97007      0.98496*
    rb           :      0.02000       0.02000*      0.02000*      0.02000*      0.02000*
    rg           :      0.00000       0.13178      0.13151      0.13107      0.13166*
    rm           :      0.02000       0.02000*      0.02000*      0.02000*      0.02000*
    rn           :      0.00000       0.11613      0.11554      0.11510      0.11566*
    sf           :      0.40000       0.40000*      0.40000*      0.40000*      0.40000*
    sigma        :      0.34000       0.34000*      0.34000*      0.34000*      0.34000*
    tau          :      0.37000       0.37000*      0.37000*      0.37000*      0.37000*
    u            :      0.00000       0.80012      0.79846      0.79580      0.79936*
    un           :      0.80000       0.80000*      0.80000*      0.80000*      0.80000*
    v            :      2.50000       2.50000*      2.50000*      2.50000*      2.50000*

```python
print('gk* = ', SFC_Base.evaluate('h*u/v - delta'))
print('v* = ', SFC_Base.evaluate('v'))
print('u* = ', SFC_Base.evaluate('u'))
print('h* = ', SFC_Base.evaluate('h'))
print('d(h)* = ', SFC_Base.evaluate('d(h)'))
print('delta* = ', SFC_Base.evaluate('delta'))
```

    gk* =  0.020059247966498286
    v* =  2.5
    u* =  0.7993566363940583
    h* =  0.20034626926809873
    d(h)* =  0.0
    delta* =  0.044

# Experiments

## Increase in real wages (decrease in $\mu$)

```python
Shock1 = create_inet_model()
Shock1.set_values(parameters)
Shock1.set_values(exogenous)
Shock1.set_values(initial)
```

### Solving

```python
%time
start = 1700
for i in range(start):
    Shock1.solve(iterations=100, threshold=1e-5)

Shock1.set_values({'mu': 0.63})

time = 500
for i in range(start + time):
    Shock1.solve(iterations=100, threshold=1e-5)
```

    CPU times: user 5 µs, sys: 0 ns, total: 5 µs
    Wall time: 9.78 µs

```python
dfSK1 = pd.DataFrame({"0":Shock1.solutions[start-1],
                     "Shock": Shock1.solutions[start],
                     "1": Shock1.solutions[start+1],
                     "2": Shock1.solutions[start+2],
                      "3": Shock1.solutions[start+3],
                      "t-1": Shock1.solutions[-2],
                     "t": Shock1.solutions[-1]})
dfSK1['difference'] = [(Shock1.solutions[-1][ax[i][1]] - Shock1.solutions[-2][ax[i][1]]) for i in range(len(Shock1.solutions[1]))]
dfSK1.style.format("{:.5g}")
```

        0
        Shock
        1
        2
        3
        t-1
        t
        difference

        B
        4.2859e+16
        4.3717e+16
        4.4535e+16
        4.5383e+16
        4.6257e+16
        2.8562e+38
        2.9254e+38
        6.9171e+36

        C
        2.1691e+15
        2.2126e+15
        2.3577e+15
        2.4322e+15
        2.5011e+15
        1.5314e+38
        1.5685e+38
        3.7093e+36

        Eq
        1.4547e+15
        1.4839e+15
        1.5137e+15
        1.5466e+15
        1.5819e+15
        1.0525e+38
        1.078e+38
        2.5494e+36

        FD
        1.0122e+15
        1.0325e+15
        1.0092e+15
        1.0492e+15
        1.0843e+15
        6.5041e+37
        6.6616e+37
        1.5754e+36

        FU
        6.7482e+14
        6.8836e+14
        6.7277e+14
        6.9948e+14
        7.2287e+14
        4.3361e+37
        4.4411e+37
        1.0503e+36

        Fg
        1.9153e+15
        1.9537e+15
        1.9194e+15
        1.992e+15
        2.0565e+15
        1.3014e+38
        1.333e+38
        3.1524e+36

        Ft
        1.6871e+15
        1.7209e+15
        1.6819e+15
        1.7487e+15
        1.8072e+15
        1.084e+38
        1.1103e+38
        2.6257e+36

        G
        1.5504e+15
        1.5815e+15
        1.6132e+15
        1.6885e+15
        1.7523e+15
        1.1178e+38
        1.1449e+38
        2.7075e+36

        Id
        9.3188e+14
        9.5057e+14
        9.9521e+14
        1.0333e+15
        1.0674e+15
        7.1805e+37
        7.3544e+37
        1.7393e+36

        K
        1.4839e+16
        1.5137e+16
        1.5466e+16
        1.5819e+16
        1.619e+16
        1.078e+39
        1.1041e+39
        2.6112e+37

        Lambda
        0.06
        0.06
        0.06
        0.06
        0.06
        0.06
        0.06
        0

        Lambda0
        0.08
        0.08
        0.08
        0.08
        0.08
        0.08
        0.08
        0

        Lf
        1.1639e+16
        1.1873e+16
        1.2166e+16
        1.2467e+16
        1.2777e+16
        1.1135e+39
        1.1405e+39
        2.6971e+37

        Mh
        -2.0412e+16
        -2.0819e+16
        -2.118e+16
        -2.1545e+16
        -2.1916e+16
        1.1129e+39
        1.1398e+39
        2.6957e+37

        Omega
        0.58824
        0.58824
        0.6135
        0.6135
        0.6135
        0.6135
        0.6135
        0

        Pi
        0.41176
        0.41176
        0.3865
        0.3865
        0.3865
        0.3865
        0.3865
        0

        Sh
        4.6961e+14
        4.7903e+14
        4.8602e+14
        5.1514e+14
        5.389e+14
        3.5184e+37
        3.6036e+37
        8.5223e+35

        T
        1.5497e+15
        1.5808e+15
        1.6701e+15
        1.7309e+15
        1.7854e+15
        1.106e+38
        1.1328e+38
        2.679e+36

        Vh
        2.3881e+16
        2.436e+16
        2.4846e+16
        2.5359e+16
        2.5896e+16
        1.4878e+39
        1.5238e+39
        3.6036e+37

        W
        2.7361e+15
        2.791e+15
        3.0467e+15
        3.1619e+15
        3.2643e+15
        2.0658e+38
        2.1158e+38
        5.0037e+36

        Y
        4.6514e+15
        4.7447e+15
        4.966e+15
        5.154e+15
        5.3209e+15
        3.3672e+38
        3.4488e+38
        8.1561e+36

        Ydh
        2.6387e+15
        2.6916e+15
        2.8437e+15
        2.9473e+15
        3.04e+15
        1.8832e+38
        1.9289e+38
        4.5616e+36

        Yfc
        5.8189e+15
        5.9356e+15
        6.0547e+15
        6.1863e+15
        6.3275e+15
        4.2101e+38
        4.3121e+38
        1.0198e+37

        Yh
        4.1884e+15
        4.2725e+15
        4.5138e+15
        4.6782e+15
        4.8254e+15
        2.9893e+38
        3.0617e+38
        7.2406e+36

        Z
        7.9012e+14
        8.0597e+14
        8.2214e+14
        8.3854e+14
        8.5587e+14
        4.9025e+37
        5.0212e+37
        1.1875e+36

        _B__1
        4.2018e+16
        4.2859e+16
        4.3717e+16
        4.4535e+16
        4.5383e+16
        2.7887e+38
        2.8562e+38
        6.7535e+36

        _Eq__1
        1.4261e+15
        1.4547e+15
        1.4839e+15
        1.5137e+15
        1.5466e+15
        1.0276e+38
        1.0525e+38
        2.4891e+36

        _K__1
        1.4547e+16
        1.4839e+16
        1.5137e+16
        1.5466e+16
        1.5819e+16
        1.0525e+39
        1.078e+39
        2.5494e+37

        _K__2
        1.4261e+16
        1.4547e+16
        1.4839e+16
        1.5137e+16
        1.5466e+16
        1.0276e+39
        1.0525e+39
        2.4891e+37

        _Lf__1
        1.1411e+16
        1.1639e+16
        1.1873e+16
        1.2166e+16
        1.2467e+16
        1.0872e+39
        1.1135e+39
        2.6334e+37

        _Mh__1
        -2.0012e+16
        -2.0412e+16
        -2.0819e+16
        -2.118e+16
        -2.1545e+16
        1.0866e+39
        1.1129e+39
        2.632e+37

        _Vh__1
        2.3411e+16
        2.3881e+16
        2.436e+16
        2.4846e+16
        2.5359e+16
        1.4526e+39
        1.4878e+39
        3.5184e+37

        _Y__1
        4.5599e+15
        4.6514e+15
        4.7447e+15
        4.966e+15
        5.154e+15
        3.2876e+38
        3.3672e+38
        7.9632e+36

        _h__1
        0.20035
        0.20035
        0.20035
        0.2004
        0.2005
        0.21325
        0.21325
        0

        _pe__1
        0.98496
        0.98496
        0.98496
        0.98485
        0.98381
        0.84811
        0.84811
        -9.0261e-14

        a
        0.1
        0.1
        0.1
        0.1
        0.1
        0.1
        0.1
        0

        alpha1
        0.8
        0.8
        0.8
        0.8
        0.8
        0.8
        0.8
        0

        alpha2
        0.03375
        0.03375
        0.03375
        0.03375
        0.03375
        0.03375
        0.03375
        0

        delta
        0.044
        0.044
        0.044
        0.044
        0.044
        0.044
        0.044
        0

        gamma
        0.014
        0.014
        0.014
        0.014
        0.014
        0.014
        0.014
        0

        gk
        0.020059
        0.020059
        0.021748
        0.022815
        0.023478
        0.024222
        0.024222
        -6.0923e-15

        h
        0.20035
        0.20035
        0.2004
        0.2005
        0.20061
        0.21325
        0.21325
        0

        mu
        0.7
        0.7
        0.63
        0.63
        0.63
        0.63
        0.63
        0

        pe
        0.98496
        0.98496
        0.98485
        0.98381
        0.98221
        0.84811
        0.84811
        -8.9484e-14

        rb
        0.02
        0.02
        0.02
        0.02
        0.02
        0.02
        0.02
        0

        rg
        0.13166
        0.13166
        0.1268
        0.1288
        0.13001
        0.12365
        0.12365
        -1.1033e-14

        rm
        0.02
        0.02
        0.02
        0.02
        0.02
        0.02
        0.02
        0

        rn
        0.11566
        0.11566
        0.1108
        0.11273
        0.11388
        0.10249
        0.10249
        -3.0004e-14

        sf
        0.4
        0.4
        0.4
        0.4
        0.4
        0.4
        0.4
        0

        sigma
        0.34
        0.34
        0.34
        0.34
        0.34
        0.34
        0.34
        0

        tau
        0.37
        0.37
        0.37
        0.37
        0.37
        0.37
        0.37
        0

        u
        0.79936
        0.79936
        0.8202
        0.83312
        0.84091
        0.7998
        0.7998
        -7.1387e-14

        un
        0.8
        0.8
        0.8
        0.8
        0.8
        0.8
        0.8
        0

        v
        2.5
        2.5
        2.5
        2.5
        2.5
        2.5
        2.5
        0

```python
S1Y = [s['Y'] for s in Shock1.solutions[(start-50):]]
S1Id = [s['Id'] for s in Shock1.solutions[(start-50):]]
S1K = [s['K'] for s in Shock1.solutions[(start-50):]]
S1C = [s['C'] for s in Shock1.solutions[(start-50):]]
S1W = [s['W'] for s in Shock1.solutions[(start-50):]]
S1u = [s['u'] for s in Shock1.solutions[(start-50):]]
S1FD = [s['FD'] for s in Shock1.solutions[(start-50):]]
S1FU = [s['FU'] for s in Shock1.solutions[(start-50):]]
S1Ft = [s['Ft'] for s in Shock1.solutions[(start-50):]]
S1Lf = [s['Lf'] for s in Shock1.solutions[(start-50):]]
S1Mh = [s['Mh'] for s in Shock1.solutions[(start-50):]]
S1Vh = [s['Vh'] for s in Shock1.solutions[(start-50):]]
S1Eq = [s['Eq'] for s in Shock1.solutions[(start-50):]]
S1pe = [s['pe'] for s in Shock1.solutions[(start-50):]]
S1h = [s['h'] for s in Shock1.solutions[(start-50):]]
S1G = [s['G'] for s in Shock1.solutions[(start-50):]]
S1B = [s['B'] for s in Shock1.solutions[(start-50):]]
S1Z = [s['Z']/s['Y'] for s in Shock1.solutions[(start-50):]]
S1rn = [s['rn'] for s in Shock1.solutions[start-50:]]
S1rg = [s['rg'] for s in Shock1.solutions[start-50:]]
S1pe = [s['pe'] for s in Shock1.solutions[start-50:]]

S1Lf_Y = [S1Lf[s]/S1Y[s] for s in range(1,time+start)]
S1Ft_Y = [S1Ft[s]/S1Y[s] for s in range(1,time+start)]
S1FU_Y = [S1FU[s]/S1Y[s] for s in range(1,time+start)]
S1FD_Y = [S1FD[s]/S1Y[s] for s in range(1,time+start)]

S1gY =  [(S1Y[i]- S1Y[i-1])/S1Y[i-1] for i in range(1,time+start)]
S1gId = [(S1Id[i]-S1Id[i-1])/S1Id[i-1] for i in range(1,time+start)]
S1gK = [(S1K[i]-S1K[i-1])/S1K[i-1] for i in range(1,time+start)]
S1gC = [(S1C[i]-S1C[i-1])/S1C[i-1] for i in range(1,time+start)]
S1gW = [(S1W[i]-S1W[i-1])/S1W[i-1] for i in range(1,time+start)]
S1gG = [(S1G[i]-S1G[i-1])/S1G[i-1] for i in range(1,time+start)]
S1gFD = [(S1FD[i]-S1FD[i-1])/S1FD[i-1] for i in range(1,time+start)]
S1gFU = [(S1FU[i]-S1FU[i-1])/S1FU[i-1] for i in range(1,time+start)]
S1gFt = [(S1Ft[i]-S1Ft[i-1])/S1Ft[i-1] for i in range(1,time+start)]
S1gLf = [(S1Lf[i]-S1Lf[i-1])/S1Lf[i-1] for i in range(1,time+start)]
S1gMh = [(S1Mh[i]-S1Mh[i-1])/S1Mh[i-1] for i in range(1,time+start)]
S1gVh = [(S1Vh[i]-S1Vh[i-1])/S1Vh[i-1] for i in range(1,time+start)]
S1gEq = [(S1Eq[i]-S1Eq[i-1])/S1Eq[i-1] for i in range(1,time+start)]
S1gB = [(S1B[i]-S1B[i-1])/S1B[i-1] for i in range(1,time+start)]
S1gZ = [(S1Z[i]-S1Z[i-1])/S1Z[i-1] for i in range(1,time+start)]
```

## Figure 1 - Effects of an increase in real wages (reduction in μ ).

```python
plot_limit = 500
bl_h = [0.2 for i in range(0, time + start)]
bl_u = [0.8 for i in range(0, time + start)]
bl_z = [0.17 for i in range(0, time + start)]

caption = 'Effects of an increase in real wages (reduction in μ)'
plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9)

plt.subplot(2, 2, 1)
plt.title('(a) Growth rate of capital and household wealth')
plt.tick_params(top=False, right=False)
plt.plot(S1gK[0:plot_limit], linestyle='-', color='r', label='Capital')
plt.plot(S1gVh[0:plot_limit], linestyle=':', color='b', label='Wealth')

plt.legend()

plt.subplot(2, 2, 2)
plt.title('(b) Capacity utilization rate')
plt.tick_params(top=False, right=False)
plt.plot(S1u[0:plot_limit], linestyle='-', color='r', label='Capacity utilization rate')
plt.plot(bl_u[0:plot_limit], linestyle=':', color='b', label='Base line')

plt.legend()

plt.subplot(2, 2, 3)
plt.title('(c) Firms propensity to invest')
plt.tick_params(top=False, right=False)
plt.plot(S1h[0:plot_limit], linestyle='-', color='r', label='Propensity to invest')
plt.plot(bl_h[0:plot_limit], linestyle=':', color='b', label='Base line')

plt.legend()

plt.subplot(2, 2, 4)
plt.title('(d) Autonomous expenditure component to income')
plt.tick_params(top=False, right=False)
plt.plot(S1Z[0:plot_limit], linestyle='-', color='r', label='Autonomous')
plt.plot(bl_z[0:plot_limit], linestyle=':', color='b', label='Base line')

plt.legend()

plt.subplots_adjust(right=1.5, hspace=0.5, wspace=0.15)
plt.show()
```

## Figure 2 - Effects of an increase in real wages (reduction in μ )

```python
S1LfK = [S1Lf[i]/S1K[i-1] for i in range(1,time+start)]
S1BK = [S1B[i]/S1K[i-1] for i in range(1,time+start)]
S1VhK = [S1Vh[i]/S1K[i-1] for i in range(1,time+start)]
S1T = [s['T'] for s in Shock1.solutions[start-50:]]
S1GT_Y = [(S1G[i] - S1T[i])/S1Y[i] for i in range(1,time+start)]
S1Basern = [S1rn[i]/rn[i] for i in range(time)]
S1Baserg = [S1rg[i]/rg[i] for i in range(time)]

bl_gt = [0 for i in range(0, time + start)]
```

```python
caption = 'Effects of an increase in real wages (reduction in μ)'
plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9)

plt.subplot(2, 2, 1)
plt.title('(a) Financial assets to capital ratios')
plt.tick_params(top=False, right=False)
plt.plot(S1LfK[0:plot_limit], linestyle='-', color='r', label='Loan')
plt.plot(S1VhK[0:plot_limit], linestyle='-', color='b', label='Wealth')
#plt.plot(S1BK[0:plot_limit], linestyle='-', color='g', label='Bills')

plt.legend()

plt.subplot(2, 2, 2)
plt.title('(b) Profit rates')
plt.tick_params(top=False, right=False)
plt.plot(S1Basern[0:plot_limit], linestyle='-', color='r', label='Net profit rate')
plt.plot(S1Baserg[0:plot_limit], linestyle=':', color='b', label='Gross profit rate')

plt.legend()

plt.subplot(2, 2, 3)
plt.title('(c) Primary government défict to outpur')
plt.tick_params(top=False, right=False)
plt.plot(S1GT_Y[0:plot_limit], linestyle='-', color='r', label='Govt deficit scenario')
plt.plot(bl_gt[0:plot_limit], linestyle='-', color='b', label='Base line')

plt.legend()

plt.subplot(2, 2, 4)
plt.title('(d) Equities as a source of finance for firms')
plt.plot(S1pe[0:plot_limit], linestyle='-', color='b', label='Equity value')

plt.legend()

plt.subplots_adjust(right=1.5, hspace=0.5, wspace=0.15)
plt.show()
```

## Increase in the propensity to consume out of after-tax wages ($\alpha_1$)

```python
Shock2 = create_inet_model()
Shock2.set_values(parameters)
Shock2.set_values(exogenous)
Shock2.set_values(initial)
```

### Solving

```python
%time
start = 1700
for i in range(start):
    Shock2.solve(iterations=100, threshold=1e-5)

Shock2.set_values({'alpha1': 0.84})

time = 500
for i in range(start + time):
    Shock2.solve(iterations=100, threshold=1e-5)
```

    CPU times: user 4 µs, sys: 0 ns, total: 4 µs
    Wall time: 8.58 µs

```python
dfSk2 = pd.DataFrame({"0":Shock2.solutions[start-1],
                     "Shock": Shock2.solutions[start],
                     "1": Shock2.solutions[start+1],
                     "2": Shock2.solutions[start+2],
                      "3": Shock2.solutions[start+3],
                      "t-1": Shock2.solutions[-2],
                     "t": Shock2.solutions[-1]})
dfSk2['difference'] = [(Shock2.solutions[-1][ax[i][1]] - Shock2.solutions[-2][ax[i][1]]) for i in range(len(Shock2.solutions[1]))]
dfSk2.style.format("{:.5g}")
```

        0
        Shock
        1
        2
        3
        t-1
        t
        difference

        B
        4.2859e+16
        4.3717e+16
        4.4547e+16
        4.5411e+16
        4.6305e+16
        3.3261e+37
        3.4023e+37
        7.6143e+35

        C
        2.1691e+15
        2.2126e+15
        2.3747e+15
        2.4523e+15
        2.5227e+15
        9.7122e+36
        9.9348e+36
        2.2256e+35

        Eq
        1.4547e+15
        1.4839e+15
        1.5137e+15
        1.547e+15
        1.583e+15
        6.6213e+36
        6.773e+36
        1.5173e+35

        FD
        1.0122e+15
        1.0325e+15
        1.0897e+15
        1.1364e+15
        1.1765e+15
        4.5784e+36
        4.6833e+36
        1.0492e+35

        FU
        6.7482e+14
        6.8836e+14
        7.2647e+14
        7.5763e+14
        7.8435e+14
        3.0523e+36
        3.1222e+36
        6.9946e+34

        Fg
        1.9153e+15
        1.9537e+15
        2.0536e+15
        2.1364e+15
        2.2082e+15
        8.7229e+36
        8.9228e+36
        1.9989e+35

        Ft
        1.6871e+15
        1.7209e+15
        1.8162e+15
        1.8941e+15
        1.9609e+15
        7.6307e+36
        7.8056e+36
        1.7486e+35

        G
        1.5504e+15
        1.5815e+15
        1.6132e+15
        1.6957e+15
        1.7641e+15
        7.0413e+36
        7.2026e+36
        1.6136e+35

        Id
        9.3188e+14
        9.5057e+14
        9.9954e+14
        1.0404e+15
        1.0761e+15
        4.4307e+36
        4.5322e+36
        1.0153e+35

        K
        1.4839e+16
        1.5137e+16
        1.547e+16
        1.583e+16
        1.6209e+16
        6.773e+37
        6.9282e+37
        1.5521e+36

        Lambda
        0.06
        0.06
        0.06
        0.06
        0.06
        0.06
        0.06
        0

        Lambda0
        0.08
        0.08
        0.08
        0.08
        0.08
        0.08
        0.08
        0

        Lf
        1.1639e+16
        1.1873e+16
        1.2117e+16
        1.2367e+16
        1.2623e+16
        5.586e+37
        5.714e+37
        1.2801e+36

        Mh
        -2.0412e+16
        -2.0819e+16
        -2.1229e+16
        -2.1646e+16
        -2.207e+16
        5.5563e+37
        5.6837e+37
        1.274e+36

        Omega
        0.58824
        0.58824
        0.58824
        0.58824
        0.58824
        0.58824
        0.58824
        0

        Pi
        0.41176
        0.41176
        0.41176
        0.41176
        0.41176
        0.41176
        0.41176
        0

        Sh
        4.6961e+14
        4.7903e+14
        4.4861e+14
        4.8021e+14
        5.0536e+14
        2.1169e+36
        2.1654e+36
        4.8511e+34

        T
        1.5497e+15
        1.5808e+15
        1.6581e+15
        1.7223e+15
        1.7784e+15
        6.9472e+36
        7.1064e+36
        1.592e+35

        Vh
        2.3881e+16
        2.436e+16
        2.4806e+16
        2.5282e+16
        2.5782e+16
        9.4493e+37
        9.6659e+37
        2.1654e+36

        W
        2.7361e+15
        2.791e+15
        2.9338e+15
        3.052e+15
        3.1546e+15
        1.2461e+37
        1.2747e+37
        2.8556e+35

        Y
        4.6514e+15
        4.7447e+15
        4.9874e+15
        5.1884e+15
        5.3628e+15
        2.1184e+37
        2.167e+37
        4.8545e+35

        Ydh
        2.6387e+15
        2.6916e+15
        2.8233e+15
        2.9325e+15
        3.028e+15
        1.1829e+37
        1.21e+37
        2.7107e+35

        Yfc
        5.8189e+15
        5.9356e+15
        6.0547e+15
        6.1881e+15
        6.3319e+15
        2.6485e+37
        2.7092e+37
        6.0693e+35

        Yh
        4.1884e+15
        4.2725e+15
        4.4814e+15
        4.6548e+15
        4.8064e+15
        1.8776e+37
        1.9207e+37
        4.3028e+35

        Z
        7.9012e+14
        8.0597e+14
        8.2214e+14
        8.372e+14
        8.5326e+14
        3.1177e+36
        3.1892e+36
        7.1445e+34

        _B__1
        4.2018e+16
        4.2859e+16
        4.3717e+16
        4.4547e+16
        4.5411e+16
        3.2517e+37
        3.3261e+37
        7.4439e+35

        _Eq__1
        1.4261e+15
        1.4547e+15
        1.4839e+15
        1.5137e+15
        1.547e+15
        6.473e+36
        6.6213e+36
        1.4833e+35

        _K__1
        1.4547e+16
        1.4839e+16
        1.5137e+16
        1.547e+16
        1.583e+16
        6.6213e+37
        6.773e+37
        1.5173e+36

        _K__2
        1.4261e+16
        1.4547e+16
        1.4839e+16
        1.5137e+16
        1.547e+16
        6.473e+37
        6.6213e+37
        1.4833e+36

        _Lf__1
        1.1411e+16
        1.1639e+16
        1.1873e+16
        1.2117e+16
        1.2367e+16
        5.4608e+37
        5.586e+37
        1.2514e+36

        _Mh__1
        -2.0012e+16
        -2.0412e+16
        -2.0819e+16
        -2.1229e+16
        -2.1646e+16
        5.4317e+37
        5.5563e+37
        1.2455e+36

        _Vh__1
        2.3411e+16
        2.3881e+16
        2.436e+16
        2.4806e+16
        2.5282e+16
        9.2376e+37
        9.4493e+37
        2.1169e+36

        _Y__1
        4.5599e+15
        4.6514e+15
        4.7447e+15
        4.9874e+15
        5.1884e+15
        2.071e+37
        2.1184e+37
        4.7458e+35

        _h__1
        0.20035
        0.20035
        0.20035
        0.20041
        0.20052
        0.20915
        0.20915
        0

        _pe__1
        0.98496
        0.98496
        0.98496
        0.98327
        0.98054
        0.85627
        0.85627
        -8.9706e-14

        a
        0.1
        0.1
        0.1
        0.1
        0.1
        0.1
        0.1
        0

        alpha1
        0.8
        0.8
        0.84
        0.84
        0.84
        0.84
        0.84
        0

        alpha2
        0.03375
        0.03375
        0.03375
        0.03375
        0.03375
        0.03375
        0.03375
        0

        delta
        0.044
        0.044
        0.044
        0.044
        0.044
        0.044
        0.044
        0

        gamma
        0.014
        0.014
        0.014
        0.014
        0.014
        0.014
        0.014
        0

        gk
        0.020059
        0.020059
        0.022035
        0.023251
        0.023976
        0.022916
        0.022916
        -5.8842e-15

        h
        0.20035
        0.20035
        0.20041
        0.20052
        0.20065
        0.20915
        0.20915
        0

        mu
        0.7
        0.7
        0.7
        0.7
        0.7
        0.7
        0.7
        0

        pe
        0.98496
        0.98496
        0.98327
        0.98054
        0.97722
        0.85627
        0.85627
        -8.8818e-14

        rb
        0.02
        0.02
        0.02
        0.02
        0.02
        0.02
        0.02
        0

        rg
        0.13166
        0.13166
        0.13567
        0.1381
        0.1395
        0.13174
        0.13174
        -1.1602e-14

        rm
        0.02
        0.02
        0.02
        0.02
        0.02
        0.02
        0.02
        0

        rn
        0.11566
        0.11566
        0.11967
        0.12209
        0.12351
        0.11487
        0.11487
        -3.0503e-14

        sf
        0.4
        0.4
        0.4
        0.4
        0.4
        0.4
        0.4
        0

        sigma
        0.34
        0.34
        0.34
        0.34
        0.34
        0.34
        0.34
        0

        tau
        0.37
        0.37
        0.37
        0.37
        0.37
        0.37
        0.37
        0

        u
        0.79936
        0.79936
        0.82373
        0.83846
        0.84694
        0.79985
        0.79985
        -7.0388e-14

        un
        0.8
        0.8
        0.8
        0.8
        0.8
        0.8
        0.8
        0

        v
        2.5
        2.5
        2.5
        2.5
        2.5
        2.5
        2.5
        0

### Getting data

```python
S2Y = [s['Y'] for s in Shock2.solutions[(start-50):]]
S2Id = [s['Id'] for s in Shock2.solutions[(start-50):]]
S2K = [s['K'] for s in Shock2.solutions[(start-50):]]
S2C = [s['C'] for s in Shock2.solutions[(start-50):]]
S2W = [s['W'] for s in Shock2.solutions[(start-50):]]
S2u = [s['u'] for s in Shock2.solutions[(start-50):]]
S2FD = [s['FD'] for s in Shock2.solutions[(start-50):]]
S2FU = [s['FU'] for s in Shock2.solutions[(start-50):]]
S2Ft = [s['Ft'] for s in Shock2.solutions[(start-50):]]
S2Lf = [s['Lf'] for s in Shock2.solutions[(start-50):]]
S2Mh = [s['Mh'] for s in Shock2.solutions[(start-50):]]
S2Vh = [s['Vh'] for s in Shock2.solutions[(start-50):]]
S2Eq = [s['Eq'] for s in Shock2.solutions[(start-50):]]
S2pe = [s['pe'] for s in Shock2.solutions[(start-50):]]
S2h = [s['h'] for s in Shock2.solutions[(start-50):]]
S2G = [s['G'] for s in Shock2.solutions[(start-50):]]
S2B = [s['B'] for s in Shock2.solutions[(start-50):]]
S2Z = [s['Z']/s['Y'] for s in Shock2.solutions[(start-50):]]
S2rn = [s['rn'] for s in Shock2.solutions[start-50:]]
S2rg = [s['rg'] for s in Shock2.solutions[start-50:]]

S2Lf_Y = [S2Lf[s]/S2Y[s] for s in range(1,time+start)]
S2Ft_Y = [S2Ft[s]/S2Y[s] for s in range(1,time+start)]
S2FU_Y = [S2FU[s]/S2Y[s] for s in range(1,time+start)]
S2FD_Y = [S2FD[s]/S2Y[s] for s in range(1,time+start)]

S2gY =  [(S2Y[i]- S2Y[i-1])/S2Y[i-1] for i in range(1,time+start)]
S2gId = [(S2Id[i]-S2Id[i-1])/S2Id[i-1] for i in range(1,time+start)]
S2gK = [(S2K[i]-S2K[i-1])/S2K[i-1] for i in range(1,time+start)]
S2gC = [(S2C[i]-S2C[i-1])/S2C[i-1] for i in range(1,time+start)]
S2gW = [(S2W[i]-S2W[i-1])/S2W[i-1] for i in range(1,time+start)]
S2gG = [(S2G[i]-S2G[i-1])/S2G[i-1] for i in range(1,time+start)]
S2gFD = [(S2FD[i]-S2FD[i-1])/S2FD[i-1] for i in range(1,time+start)]
S2gFU = [(S2FU[i]-S2FU[i-1])/S2FU[i-1] for i in range(1,time+start)]
S2gFt = [(S2Ft[i]-S2Ft[i-1])/S2Ft[i-1] for i in range(1,time+start)]
S2gLf = [(S2Lf[i]-S2Lf[i-1])/S2Lf[i-1] for i in range(1,time+start)]
S2gMh = [(S2Mh[i]-S2Mh[i-1])/S2Mh[i-1] for i in range(1,time+start)]
S2gVh = [(S2Vh[i]-S2Vh[i-1])/S2Vh[i-1] for i in range(1,time+start)]
S2gEq = [(S2Eq[i]-S2Eq[i-1])/S2Eq[i-1] for i in range(1,time+start)]
S2gB = [(S2B[i]-S2B[i-1])/S2B[i-1] for i in range(1,time+start)]
S2gZ = [(S2Z[i]-S2Z[i-1])/S2Z[i-1] for i in range(1,time+start)]

S2LfK = [S2Lf[i]/S2K[i-1] for i in range(1,time+start)]
S2BK = [S2B[i]/S2K[i-1] for i in range(1,time+start)]
S2VhK = [S2Vh[i]/S2K[i-1] for i in range(1,time+start)]
```

## Figure 3 - Effects of an increase in the propensity to consume out of after-tax wages ($\alpha_1$)

```python
plot_limit = 500
S2Basern = [S2rn[i]/rn[i] for i in range(time)] # rn[1] = rn[start-50], so rn[50] is the first in SS
S2Baserg = [S2rg[i]/rg[i] for i in range(time)]
bl_h = [0.2 for i in range(0, time + start)]
bl_u = [0.8 for i in range(0, time + start)]
bl_z = [0.17 for i in range(0, time + start)]

caption = 'Effects of an increase in real wages (reduction in μ)'
plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9)

plt.subplot(2, 2, 1)
plt.title('(a) Growth rate of capital and household wealth')
plt.tick_params(top=False, right=False)
plt.plot(S2gK[0:plot_limit], linestyle='-', color='r', label='Capital')
plt.plot(S2gVh[0:plot_limit], linestyle=':', color='b', label='Wealth')

plt.legend()

plt.subplot(2, 2, 2)
plt.title('(b) Capacity utilization rate')
plt.tick_params(top=False, right=False)
plt.plot(S2u[0:plot_limit], linestyle='-', color='r', label='Capacity utilization rate')
plt.plot(bl_u[0:plot_limit], linestyle=':', color='b', label='Base line')

plt.legend()

plt.subplot(2, 2, 3)
plt.title('(c) Financial assets to capital ratios')
plt.tick_params(top=False, right=False)
plt.plot(S2LfK[0:plot_limit], linestyle='-', color='r', label='Loan')
plt.plot(S2VhK[0:plot_limit], linestyle='-', color='b', label='Wealth')
#plt.plot(S2BK[0:plot_limit], linestyle='-', color='g', label='Bills')

plt.legend()

plt.subplot(2, 2, 4)
plt.title('(d) Profit rates')
plt.tick_params(top=False, right=False)
plt.plot(S2Basern[0:plot_limit], linestyle='-', color='r', label='Net profit rate')
plt.plot(S2Baserg[0:plot_limit], linestyle=':', color='b', label='Gross profit rate')

plt.legend()

plt.subplots_adjust(right=1.5, hspace=0.5, wspace=0.15)
plt.show()
```

## Figure 4 - Effects of an increase in the propensity to consume out of after-tax wages ( 𝛼1 )

```python
BaseLfK = [Lf[i]/K[i-1] for i in range(1,time)]
S2LfK = [S2Lf[i]/S2K[i-1] for i in range(1,time)]
BaseVhK = [Vh[i]/K[i-1] for i in range(1,time)]
S2VhK = [S2Vh[i]/S2K[i-1] for i in range(1,time)]

plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9)

plt.subplot(2, 2, 1)
plt.title('(a) Firms loan ratios')
plt.tick_params(top=False, right=False)
plt.plot(S2LfK[0:plot_limit], linestyle='-', color='r', label='Firms Loans')
plt.plot(BaseLfK[0:plot_limit], linestyle=':', color='b', label='Base line')

plt.legend()

plt.subplot(2, 2, 2)
plt.title('(b) Household wealth to capital ratio')
plt.tick_params(top=False, right=False)
plt.plot(S2VhK[0:plot_limit], linestyle='-', color='r', label='Household Wealth')
plt.plot(BaseVhK[0:plot_limit], linestyle=':', color='b', label='Base line')

plt.legend()

plt.subplot(2, 2, 3)
plt.title('(c) Firms propensity to invest')
plt.tick_params(top=False, right=False)
plt.plot(S2h[0:plot_limit], linestyle='-', color='r', label='Propensity to invest')
plt.plot(bl_h[0:plot_limit], linestyle=':', color='b', label='Base line')

plt.legend()

plt.subplot(2, 2, 4)
plt.title('(d) Autonomous expenditure component to income')
plt.tick_params(top=False, right=False)
plt.plot(S2Z[0:plot_limit], linestyle='-', color='r', label='Autonomous')
plt.plot(bl_z[0:plot_limit], linestyle=':', color='b', label='Base line')

plt.legend()

plt.subplots_adjust(right=1.5, hspace=0.5, wspace=0.15)
plt.show()
```

##  Increase in the autonomous expenditure component ($\alpha_2$)

```python
Shock3 = create_inet_model()
Shock3.set_values(parameters)
Shock3.set_values(exogenous)
Shock3.set_values(initial)
```

### Solving

```python
start = 1700
for i in range(start):
    Shock3.solve(iterations=100, threshold=1e-5)

Shock3.set_values({'alpha2': 0.0374})

time = 500
for i in range(start + time):
    Shock3.solve(iterations=100, threshold=1e-5)
```

```python
dfSk3 = pd.DataFrame({"0":Shock3.solutions[start-1],
                     "Shock": Shock3.solutions[start],
                     "1": Shock3.solutions[start+1],
                     "2": Shock3.solutions[start+2],
                      "3": Shock3.solutions[start+3],
                      "t-1": Shock3.solutions[-2],
                     "t": Shock3.solutions[-1]})
dfSk3['difference'] = [(Shock3.solutions[-1][ax[i][1]] - Shock3.solutions[-2][ax[i][1]]) for i in range(len(Shock3.solutions[1]))]
dfSk3.style.format("{:.5g}")
```

        0
        Shock
        1
        2
        3
        t-1
        t
        difference

        B
        4.2859e+16
        4.3717e+16
        4.4537e+16
        4.5397e+16
        4.6289e+16
        6.4065e+37
        6.5554e+37
        1.4882e+36

        C
        2.1691e+15
        2.2126e+15
        2.3985e+15
        2.4796e+15
        2.5519e+15
        1.9504e+37
        1.9958e+37
        4.5335e+35

        Eq
        1.4547e+15
        1.4839e+15
        1.5137e+15
        1.5476e+15
        1.5845e+15
        1.3322e+37
        1.3631e+37
        3.0964e+35

        FD
        1.0122e+15
        1.0325e+15
        1.0971e+15
        1.1481e+15
        1.1906e+15
        9.2077e+36
        9.4217e+36
        2.1402e+35

        FU
        6.7482e+14
        6.8836e+14
        7.314e+14
        7.6537e+14
        7.9371e+14
        6.1385e+36
        6.2812e+36
        1.4268e+35

        Fg
        1.9153e+15
        1.9537e+15
        2.066e+15
        2.1558e+15
        2.2317e+15
        1.7552e+37
        1.796e+37
        4.0797e+35

        Ft
        1.6871e+15
        1.7209e+15
        1.8285e+15
        1.9134e+15
        1.9843e+15
        1.5346e+37
        1.5703e+37
        3.567e+35

        G
        1.5504e+15
        1.5815e+15
        1.6132e+15
        1.7059e+15
        1.7801e+15
        1.4164e+37
        1.4493e+37
        3.2921e+35

        Id
        9.3188e+14
        9.5057e+14
        1.0056e+15
        1.05e+15
        1.0878e+15
        8.9579e+36
        9.1662e+36
        2.0821e+35

        K
        1.4839e+16
        1.5137e+16
        1.5476e+16
        1.5845e+16
        1.6236e+16
        1.3631e+38
        1.3948e+38
        3.1684e+36

        Lambda
        0.06
        0.06
        0.06
        0.06
        0.06
        0.06
        0.06
        0

        Lambda0
        0.08
        0.08
        0.08
        0.08
        0.08
        0.08
        0.08
        0

        Lf
        1.1639e+16
        1.1873e+16
        1.2118e+16
        1.2369e+16
        1.2627e+16
        1.1285e+38
        1.1547e+38
        2.623e+36

        Mh
        -2.0412e+16
        -2.0819e+16
        -2.1228e+16
        -2.1644e+16
        -2.2066e+16
        1.1254e+38
        1.1516e+38
        2.6167e+36

        Omega
        0.58824
        0.58824
        0.58824
        0.58824
        0.58824
        0.58824
        0.58824
        0

        Pi
        0.41176
        0.41176
        0.41176
        0.41176
        0.41176
        0.41176
        0.41176
        0

        Sh
        4.6961e+14
        4.7903e+14
        4.4051e+14
        4.776e+14
        5.0595e+14
        4.2678e+36
        4.367e+36
        9.9199e+34

        T
        1.5497e+15
        1.5808e+15
        1.6674e+15
        1.7367e+15
        1.7959e+15
        1.3961e+37
        1.4286e+37
        3.2451e+35

        Vh
        2.3881e+16
        2.436e+16
        2.4797e+16
        2.527e+16
        2.577e+16
        1.8788e+38
        1.9225e+38
        4.367e+36

        W
        2.7361e+15
        2.791e+15
        2.9514e+15
        3.0797e+15
        3.1881e+15
        2.5074e+37
        2.5657e+37
        5.8281e+35

        Y
        4.6514e+15
        4.7447e+15
        5.0173e+15
        5.2355e+15
        5.4197e+15
        4.2626e+37
        4.3617e+37
        9.9078e+35

        Ydh
        2.6387e+15
        2.6916e+15
        2.8391e+15
        2.9572e+15
        3.0578e+15
        2.3772e+37
        2.4325e+37
        5.5255e+35

        Yfc
        5.8189e+15
        5.9356e+15
        6.0547e+15
        6.1905e+15
        6.3381e+15
        5.3287e+37
        5.4525e+37
        1.2386e+36

        Yh
        4.1884e+15
        4.2725e+15
        4.5064e+15
        4.6939e+15
        4.8537e+15
        3.7734e+37
        3.8611e+37
        8.7707e+35

        Z
        7.9012e+14
        8.0597e+14
        9.1105e+14
        9.2741e+14
        9.4509e+14
        6.8671e+36
        7.0267e+36
        1.5962e+35

        _B__1
        4.2018e+16
        4.2859e+16
        4.3717e+16
        4.4537e+16
        4.5397e+16
        6.2611e+37
        6.4065e+37
        1.4545e+36

        _Eq__1
        1.4261e+15
        1.4547e+15
        1.4839e+15
        1.5137e+15
        1.5476e+15
        1.3019e+37
        1.3322e+37
        3.0261e+35

        _K__1
        1.4547e+16
        1.4839e+16
        1.5137e+16
        1.5476e+16
        1.5845e+16
        1.3322e+38
        1.3631e+38
        3.0964e+36

        _K__2
        1.4261e+16
        1.4547e+16
        1.4839e+16
        1.5137e+16
        1.5476e+16
        1.3019e+38
        1.3322e+38
        3.0261e+36

        _Lf__1
        1.1411e+16
        1.1639e+16
        1.1873e+16
        1.2118e+16
        1.2369e+16
        1.1028e+38
        1.1285e+38
        2.5634e+36

        _Mh__1
        -2.0012e+16
        -2.0412e+16
        -2.0819e+16
        -2.1228e+16
        -2.1644e+16
        1.0998e+38
        1.1254e+38
        2.5573e+36

        _Vh__1
        2.3411e+16
        2.3881e+16
        2.436e+16
        2.4797e+16
        2.527e+16
        1.8361e+38
        1.8788e+38
        4.2678e+36

        _Y__1
        4.5599e+15
        4.6514e+15
        4.7447e+15
        5.0173e+15
        5.2355e+15
        4.1658e+37
        4.2626e+37
        9.6827e+35

        _h__1
        0.20035
        0.20035
        0.20035
        0.20043
        0.20055
        0.21015
        0.21015
        0

        _pe__1
        0.98496
        0.98496
        0.98496
        0.98293
        0.97969
        0.8462
        0.8462
        -6.0396e-14

        a
        0.1
        0.1
        0.1
        0.1
        0.1
        0.1
        0.1
        0

        alpha1
        0.8
        0.8
        0.8
        0.8
        0.8
        0.8
        0.8
        0

        alpha2
        0.03375
        0.03375
        0.0374
        0.0374
        0.0374
        0.0374
        0.0374
        0

        delta
        0.044
        0.044
        0.044
        0.044
        0.044
        0.044
        0.044
        0

        gamma
        0.014
        0.014
        0.014
        0.014
        0.014
        0.014
        0.014
        0

        gk
        0.020059
        0.020059
        0.022435
        0.023846
        0.024651
        0.023244
        0.023244
        -4.0801e-15

        h
        0.20035
        0.20035
        0.20043
        0.20055
        0.20071
        0.21015
        0.21015
        0

        mu
        0.7
        0.7
        0.7
        0.7
        0.7
        0.7
        0.7
        0

        pe
        0.98496
        0.98496
        0.98293
        0.97969
        0.9758
        0.8462
        0.8462
        -5.9841e-14

        rb
        0.02
        0.02
        0.02
        0.02
        0.02
        0.02
        0.02
        0

        rg
        0.13166
        0.13166
        0.13649
        0.1393
        0.14084
        0.13175
        0.13175
        -7.9936e-15

        rm
        0.02
        0.02
        0.02
        0.02
        0.02
        0.02
        0.02
        0

        rn
        0.11566
        0.11566
        0.12049
        0.12328
        0.12486
        0.11481
        0.11481
        -2.0831e-14

        sf
        0.4
        0.4
        0.4
        0.4
        0.4
        0.4
        0.4
        0

        sigma
        0.34
        0.34
        0.34
        0.34
        0.34
        0.34
        0.34
        0

        tau
        0.37
        0.37
        0.37
        0.37
        0.37
        0.37
        0.37
        0

        u
        0.79936
        0.79936
        0.82867
        0.84573
        0.8551
        0.79994
        0.79994
        -4.8517e-14

        un
        0.8
        0.8
        0.8
        0.8
        0.8
        0.8
        0.8
        0

        v
        2.5
        2.5
        2.5
        2.5
        2.5
        2.5
        2.5
        0

```python
S3Y = [s['Y'] for s in Shock3.solutions[(start-50):]]
S3Id = [s['Id'] for s in Shock3.solutions[(start-50):]]
S3K = [s['K'] for s in Shock3.solutions[(start-50):]]
S3C = [s['C'] for s in Shock3.solutions[(start-50):]]
S3W = [s['W'] for s in Shock3.solutions[(start-50):]]
S3u = [s['u'] for s in Shock3.solutions[(start-50):]]
S3FD = [s['FD'] for s in Shock3.solutions[(start-50):]]
S3FU = [s['FU'] for s in Shock3.solutions[(start-50):]]
S3Ft = [s['Ft'] for s in Shock3.solutions[(start-50):]]
S3Lf = [s['Lf'] for s in Shock3.solutions[(start-50):]]
S3Mh = [s['Mh'] for s in Shock3.solutions[(start-50):]]
S3Vh = [s['Vh'] for s in Shock3.solutions[(start-50):]]
S3Eq = [s['Eq'] for s in Shock3.solutions[(start-50):]]
S3pe = [s['pe'] for s in Shock3.solutions[(start-50):]]
S3h = [s['h'] for s in Shock3.solutions[(start-50):]]
S3G = [s['G'] for s in Shock3.solutions[(start-50):]]
S3B = [s['B'] for s in Shock3.solutions[(start-50):]]
S3Z = [s['Z']/s['Y'] for s in Shock3.solutions[(start-50):]]
S3rn = [s['rn'] for s in Shock3.solutions[start:]]
S3rg = [s['rg'] for s in Shock3.solutions[start:]]

S3Lf_Y = [S3Lf[s]/S3Y[s] for s in range(1,time+start)]
S3Ft_Y = [S3Ft[s]/S3Y[s] for s in range(1,time+start)]
S3FU_Y = [S3FU[s]/S3Y[s] for s in range(1,time+start)]
S3FD_Y = [S3FD[s]/S3Y[s] for s in range(1,time+start)]

S3gY =  [(S3Y[i]- S3Y[i-1])/S3Y[i-1] for i in range(1,time+start)]
S3gId = [(S3Id[i]-S3Id[i-1])/S3Id[i-1] for i in range(1,time+start)]
S3gK = [(S3K[i]-S3K[i-1])/S3K[i-1] for i in range(1,time+start)]
S3gC = [(S3C[i]-S3C[i-1])/S3C[i-1] for i in range(1,time+start)]
S3gW = [(S3W[i]-S3W[i-1])/S3W[i-1] for i in range(1,time+start)]
S3gG = [(S3G[i]-S3G[i-1])/S3G[i-1] for i in range(1,time+start)]
S3gFD = [(S3FD[i]-S3FD[i-1])/S3FD[i-1] for i in range(1,time+start)]
S3gFU = [(S3FU[i]-S3FU[i-1])/S3FU[i-1] for i in range(1,time+start)]
S3gFt = [(S3Ft[i]-S3Ft[i-1])/S3Ft[i-1] for i in range(1,time+start)]
S3gLf = [(S3Lf[i]-S3Lf[i-1])/S3Lf[i-1] for i in range(1,time+start)]
S3gMh = [(S3Mh[i]-S3Mh[i-1])/S3Mh[i-1] for i in range(1,time+start)]
S3gVh = [(S3Vh[i]-S3Vh[i-1])/S3Vh[i-1] for i in range(1,time+start)]
S3gEq = [(S3Eq[i]-S3Eq[i-1])/S3Eq[i-1] for i in range(1,time+start)]
S3gB = [(S3B[i]-S3B[i-1])/S3B[i-1] for i in range(1,time+start)]
S3gZ = [(S3Z[i]-S3Z[i-1])/S3Z[i-1] for i in range(1,time+start)]
```

## Figure 5 - Effects of an increase in the autonomous expenditure component ($\alpha_2$)

```python
plot_limit = 500
bl_h = [0.2 for i in range(0, time + start)]
bl_u = [0.8 for i in range(0, time + start)]
bl_z = [0.17 for i in range(0, time + start)]

caption = 'Effects of an increase in real wages (reduction in μ)'
plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9)

plt.subplot(2, 2, 1)
plt.title('(a) Growth rate of capital and household wealth')
plt.tick_params(top=False, right=False)
plt.plot(S3gK[0:plot_limit], linestyle='-', color='r', label='Capital')
plt.plot(S3gVh[0:plot_limit], linestyle=':', color='b', label='Wealth')

plt.legend()

plt.subplot(2, 2, 2)
plt.title('(b) Capacity utilization rate')
plt.tick_params(top=False, right=False)
plt.plot(S3u[0:plot_limit], linestyle='-', color='r', label='Capacity utilization rate')
plt.plot(bl_u[0:plot_limit], linestyle=':', color='b', label='Base line')

plt.legend()

plt.subplot(2, 2, 3)
plt.title('(c) Firms propensity to invest')
plt.tick_params(top=False, right=False)
plt.plot(S3h[0:plot_limit], linestyle='-', color='r', label='Propensity to invest')
plt.plot(bl_h[0:plot_limit], linestyle=':', color='b', label='Base line')

plt.legend()

plt.subplot(2, 2, 4)
plt.title('(d) Autonomous expenditure component to income')
plt.tick_params(top=False, right=False)
plt.plot(S3Z[0:plot_limit], linestyle='-', color='r', label='Autonomous')
plt.plot(bl_z[0:plot_limit], linestyle=':', color='b', label='Base line')

plt.legend()

plt.subplots_adjust(right=1.5, hspace=0.5, wspace=0.15)
plt.show()
```

# Comparing

```python
dfcomp = pd.DataFrame({"Base Scenario":SFC_Base.solutions[-1],
                     "Scenario 1": Shock1.solutions[-1],
                     "Scenario 3": Shock2.solutions[-1],
                     "Scenario 2": Shock3.solutions[-1],
                     })
dfcomp.loc['a':,].style.format("{:.5g}")
```

        Base Scenario
        Scenario 1
        Scenario 3
        Scenario 2

        a
        0.1
        0.1
        0.1
        0.1

        alpha1
        0.8
        0.8
        0.84
        0.8

        alpha2
        0.03375
        0.03375
        0.03375
        0.0374

        delta
        0.044
        0.044
        0.044
        0.044

        gamma
        0.014
        0.014
        0.014
        0.014

        gk
        0.020059
        0.024222
        0.022916
        0.023244

        h
        0.20035
        0.21325
        0.20915
        0.21015

        mu
        0.7
        0.63
        0.7
        0.7

        pe
        0.98496
        0.84811
        0.85627
        0.8462

        rb
        0.02
        0.02
        0.02
        0.02

        rg
        0.13166
        0.12365
        0.13174
        0.13175

        rm
        0.02
        0.02
        0.02
        0.02

        rn
        0.11566
        0.10249
        0.11487
        0.11481

        sf
        0.4
        0.4
        0.4
        0.4

        sigma
        0.34
        0.34
        0.34
        0.34

        tau
        0.37
        0.37
        0.37
        0.37

        u
        0.79936
        0.7998
        0.79985
        0.79994

        un
        0.8
        0.8
        0.8
        0.8

        v
        2.5
        2.5
        2.5
        2.5

# Analytical solution and Steady-State inital stocks values

```python
from sympy.interactive import printing
from sympy import Symbol, symbols, Function, simplify, solve
import sympy as sp
printing.init_printing(use_latex = True)

t = Symbol('t') # time
```

Defining  function objects

```python
Y = Function('Y')
C = Function('C')
Id = Function('Id')
Omega = Function('Omega')
pi = Function('pi')
K = Function('K')
gK = Function('gK')
Yfc = Function('Yfc')
u = Function('u')
Yh = Function('Yh')
Yd = Function('Yd')
W = Function('W')
FD = Function('FD')
Mh = Function('Mh')
B = Function('B')
Sh = Function('Sh')
Vh = Function('Vh')
pe = Function('pe')
Lambda = Function('lambda') # lambda is reserved to python basic
Eq = Function('Eq') # E is reserved for numpy
Lf = Function('Lf')
FU = Function('FU')
Ft = Function('Ft')
Fg = Function('Fg')
h = Function('h')
G = Function('G')
T = Function('T')
```

```python
delta = Symbol('delta')
Lambda0 = Symbol('lambda0')
mu = Symbol('mu')
alpha1 = Symbol('alpha1')
alpha2 = Symbol('alpha2')
r = Symbol('r') # rm = rb
tau = Symbol('tau')
sf = Symbol('s_f')
a = Symbol('a')
gamma = Symbol('gamma')
un = Symbol('u_n')
sigma = Symbol('sigma')
v = Symbol('v')
```

```python
vh_eq = Symbol('vh^*')
b_eq = Symbol('b^*')
l_eq = Symbol('l^*')
h_eq = Symbol('h^*')
pi_fixed = Symbol('pi')
g_eq = Symbol('g^*')

Lambda = Symbol('lambda')
irb = Symbol('i_r')
```

## Shot-run Equilibrium

```python
Eq1 = B(t-1) + G(t) - T(t) + r*B(t-1) # B(t)
Eq2 = sigma*Y(t-1) # G(t)
Eq3 = tau*Yh(t) # T(t)
Eq4 = W(t) + FD(t) + r*(B(t-1) + Mh(t-1))  # Yh(t)
Eq5 = (1-pi(t))*Y(t) # W(t)
Eq6 = (1-tau)*Yh(t) # Yd
Eq7 = alpha1*(1-tau)*W(t) + alpha2*Vh(t-1) # C(t)
Eq8 = Yd(t) - C(t) # Sh(t)
Eq9 = Lambda0(t) - r # Lambda(t)
Eq10 = (Lambda(t)*Vh(t))/Eq(t) # pe(t)
Eq11 = Vh(t-1) + Sh(t) + (pe(t) - pe(t-1))*Eq(t-1) #Vh(t)
Eq12 = Mh(t-1) + Sh(t) - pe(t)*(Eq(t) - Eq(t-1)) - (B(t) - B(t-1)) # Mh
Eq13 = mu/(1+mu) # Pi
Eq14 = h(t)*Y(t) # Id
Eq15 = h(t-1) + h(t-1)*gamma(t)*(u(t) - un) #h(t)
Eq16 = K(t-1) + Id(t) - delta*K(t-1) # K(t)
Eq17 = K(t-1)/v # Yfc
Eq18 = Y(t)/Yfc(t) #u
Eq19 = (h(t)*u(t))/v - delta # gK
Eq20 = Lf(t-1) + Id(t) - FU(t) - pe(t)*(Eq(t) - Eq(t-1)) # Lf
Eq21 = a*K(t-1) # Eq
Eq22 = sf*(pi(t)*Y(t) - r*Lf(t-1)) #FU
Eq23 = (1-sf)*(pi(t)*Y(t) - r*Lf(t-1)) #FD
Eq24 = (pi(t)*Y(t) - r*Lf(t-1)) #Ft
Eq25 = pi(t)*Y(t) #Fg
Eq28 = C(t) + Id(t) + G(t) # GDP (Y(t))
```

```python
Eq29a = Eq28.subs(C(t), Eq7) - Y(t) #IMPORTANT: To solve the system
Eq29a
```

```python
Eq29b = Eq29a.subs(Id(t), Eq14)
Eq29b
```

```python
Eq29c = Eq29b.subs(G(t), Eq2)
Eq29c
```

```python
Eq29k = (Eq29c/K(t-1)).expand() # Y -> u/v
Eq29k
```

```python
Eq29w = Eq29k.subs(W(t), Eq5).expand()
Eq29w
```

Rearranging:

$$Y_{t-1} = \frac{Y_t}{(1+g_{Y_{t-1}})}$$

And

$$K_{t-1} = \frac{K_t}{(1+g_{K_{t-1}})}$$

Then

$$\frac{Y_{t-1}}{K_{t-1}} = \frac{1}{v}\frac{(1+g_{K_{t-1}})}{(1+g_{Y_{t-1}})}$$

So

$$\frac{ Y_{t-1}}{K_{t-1}} = \frac{Y_t}{K_{t-1}}\frac{1}{(1+g_{Y_{t-1}})} = \frac{u_t}{v}\frac{1}{(1+g_{Y_{t-1}})}$$

```python
gY = Function('gY')
Eq29t = Eq29w.subs(Y(t-1)/K(t-1), (u(t)/v)*(1/(1+gY(t-1))))
Eq29t
```

Rearranging:

$$\frac{Y_t}{K_{t-1}} = \frac{u_t}{v}$$

```python
Eq29u = Eq29t.subs((Y(t)/K(t-1)), u(t)/v)
Eq29u
```

From footnote 22:

$$\frac{Vh_{t-1}}{K_{t-1}} = \frac{vh_{t-1}}{(1+gK_{t-1})}$$

where

$$vh_{t-1} = \frac{Vh_{t-1}}{K_{t-2}}$$

```python
vh = Function('vh')
Eq29vh = Eq29u.subs((Vh(t-1)/K(t-1)), vh(t-1)/(1+gK(t-1)))
Eq29vh
```

Solving for $u_t$

```python
EqSR = (Eq29vh)
EqSR
solve(EqSR, u(t))[0].factor().collect(gY(t-1)).collect(alpha1).collect(sigma)
```

Rearranging:
$$
u_t = -\frac{(1+g_{Y_{t-1}})(\alpha_2v_{h_{t-1}}v)}{(1+ g_{K_{t-1}})(1+g_{Y_{t-1}})(\alpha_1(1-\tau)(1-\pi) + h_t -1) + \sigma}
$$

$$
u_t = -\frac{(\alpha_2v_{h_{t-1}}v)}{(1+ g_{K_{t-1}})(-1 + \alpha_1(1-\tau)(1-\pi) + h_t) + \frac{\sigma}{(1+g_{Y_{t-1}})}}
$$

$$
u_t = \frac{\alpha_2v_{h_{t-1}}v}{(1+ g_{K_{t-1}})(1 - \alpha_1(1-\tau)(1-\pi) - h_t) - \frac{\sigma}{(1+g_{Y_{t-1}})}}
$$

## Long-run Equilibrium

Making $gK_{t-1} = gK_t = gK^*$

```python
Eq29gk = Eq29vh.subs(gK(t-1), gK(t)).subs(gY(t-1), gK(t)).expand()
Eq29gk
```

Making $h_t = h_{t-1}$ which means $\Delta h = 0$ then $u_t = u_n$

```python
Eq29un = Eq29gk.subs(h(t), h(t-1)).subs(h(t-1), Eq15).subs(u(t),un).expand()
Eq29un
```

Solving for $g_K$ ($\equiv gY$ in the long run)

```python
EqLR = Eq29un
EqLR = solve(EqLR, gK(t))[0].simplify().collect(un).collect(alpha1)
EqLR
```

Rearranging:
$$g^* = \frac{\alpha_2v_hv + \sigma u_n}{u_n(1 - \alpha_1(1-\tau)(1-\pi) - h_t)} - 1$$

Plugging values from appendix B

```python
EqLR = EqLR.subs(vh(t-1), 1.646715)
EqLR = EqLR.subs(alpha2, 0.03375)
EqLR = EqLR.subs(un, 0.8)
EqLR = EqLR.subs(alpha1, 0.8)
EqLR = EqLR.subs(v, 2.5)
EqLR = EqLR.subs(tau, 0.37)
EqLR = EqLR.subs(h(t-1), 0.2)
EqLR = EqLR.subs(pi(t), 0.411765)
EqLR = EqLR.subs(sigma, 0.34)
EqLR
print('Rounding for 10 decimal places:\ng* = ', round(EqLR,10))
print('Rounding for 3 decimal places:\ng* = ', round(EqLR,3))
```

    Rounding for 10 decimal places:
    g* =  0.0201525659
    Rounding for 3 decimal places:
    g* =  0.02

## Initial stocks values

```python
Eqb = sp.Eq(b_eq,(((sigma - tau*(1-sf*pi_fixed)*(1+g_eq)))*(un/v) - tau*irb*sf*l_eq)/(g_eq - irb*(1-tau)))
Eqb
Eql = sp.Eq(l_eq,((1+g_eq)*((h_eq - sf*pi_fixed)*un/v) - g_eq*Lambda*vh_eq)/(g_eq - sf*irb))
Eql
Eqvh = sp.Eq(vh_eq, ((1-tau)*(((1-alpha1 + pi_fixed*(alpha1-sf))*un/v*(1+g_eq)) + irb*b_eq + sf*irb*l_eq))/(g_eq + alpha2))
Eqvh
Eqh = sp.Eq(h_eq, ((1+g_eq)*gamma*un*(1-alpha1*(1-tau)*(1-pi_fixed)) - sigma*gamma*un - gamma*alpha2*vh_eq*v)/(gamma*un*(1+g_eq)))
Eqh
```

### Base scenario

```python
growth = 0.02
#growth = EqLR
EqbBase = Eqb.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.411765), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.03375),(alpha1,0.8),(gamma,0.014),
               (g_eq,growth)])
EqbBase
EqlBase = Eql.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.411765), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.03375),(alpha1,0.8),(gamma,0.014),
               (g_eq,growth)])
EqlBase
EqvhBase = Eqvh.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.411765), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.03375),(alpha1,0.8),(gamma,0.014),
               (g_eq,growth)])
EqvhBase
EqhBase = Eqh.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.411765), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.03375),(alpha1,0.8),(gamma,0.014),
               (g_eq,growth)])
EqhBase
sp.solve([EqbBase, EqlBase,EqvhBase,EqhBase],
         [b_eq, l_eq, vh_eq, h_eq])
```

### Experiment 1 ($\pi = 0.411765 \Rightarrow 0.3865031$)

```python
growth = 0.02421

EqbS1 = Eqb.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.3865031), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.03375),(alpha1,0.8),(gamma,0.014),
               (g_eq,growth)])
EqbS1
EqlS1 = Eql.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.3865031), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.03375),(alpha1,0.8),(gamma,0.014),
               (g_eq,growth)])
EqlS1
EqvhS1 = Eqvh.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.3865031), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.03375),(alpha1,0.8),(gamma,0.014),
               (g_eq,growth)])
EqvhS1
EqhS1 = Eqh.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.3865031), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.03375),(alpha1,0.8),(gamma,0.014),
               (g_eq,growth)])
EqhS1
sp.solve([EqbS1, EqlS1,EqvhS1,EqhS1],
         [b_eq, l_eq, vh_eq, h_eq])
```

### Experiment 2 ($\alpha_1 = 0.8 \Rightarrow 0.84$)

```python
growth = 0.02291702

EqbS2 = Eqb.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.411765), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.03375),(alpha1,0.84),(gamma,0.014),
               (g_eq,growth)])
EqbS2
EqlS2 = Eql.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.411765), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.03375),(alpha1,0.84),(gamma,0.014),
               (g_eq,growth)])
EqlS2
EqvhS2 = Eqvh.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.411765), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.03375),(alpha1,0.84),(gamma,0.014),
               (g_eq,growth)])
EqvhS2
EqhS2 = Eqh.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.411765), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.03375),(alpha1,0.84),(gamma,0.014),
               (g_eq,growth)])
EqhS2
sp.solve([EqbS2, EqlS2,EqvhS2,EqhS2],
         [b_eq, l_eq, vh_eq, h_eq])
```

### Experiment 3 ($\alpha_2 = 0.03375 \Rightarrow 0.0374$)

```python
growth = 0.023161
#growth = EqLR
EqbS2 = Eqb.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.411765), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.0374),(alpha1,0.8),(gamma,0.014),
               (g_eq,growth)])
EqbS2
EqlS2 = Eql.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.411765), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.0374),(alpha1,0.8),(gamma,0.014),
               (g_eq,growth)])
EqlS2
EqvhS2 = Eqvh.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.411765), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.0374),(alpha1,0.8),(gamma,0.014),
               (g_eq,growth)])
EqvhS2
EqhS2 = Eqh.subs([(sigma,0.34), (irb, 0.02),(sf, 0.4),(tau, 0.37),(un,0.8),(pi_fixed,0.411765), (v,2.5),(Lambda,(0.08-0.02)),(alpha2,0.0374),(alpha1,0.8),(gamma,0.014),
               (g_eq,growth)])
EqhS2
sp.solve([EqbS2, EqlS2,EqvhS2,EqhS2],
         [b_eq, l_eq, vh_eq, h_eq])
```

```python
ax = sorted([(str(k), k) for k,v in SFC_Base.solutions[0].items()], key=lambda x: x[0])
symb = [a for (a,b) in ax]
variables = [print(a) for (a,b) in ax]
Symbols = [Symbol(symb[i]) for i in range(len(symb))]
```

    B
    C
    Eq
    FD
    FU
    Fg
    Ft
    G
    Id
    K
    Lambda
    Lambda0
    Lf
    Mh
    Omega
    Pi
    Sh
    T
    Vh
    W
    Y
    Ydh
    Yfc
    Yh
    Z
    _B__1
    _Eq__1
    _K__1
    _K__2
    _Lf__1
    _Mh__1
    _Vh__1
    _Y__1
    _h__1
    _pe__1
    a
    alpha1
    alpha2
    delta
    gamma
    gk
    h
    mu
    pe
    rb
    rg
    rm
    rn
    sf
    sigma
    tau
    u
    un
    v

```python
list(filter(lambda symb: "_" not in symb, ax))
```

    [('B', 'B'),
     ('C', 'C'),
     ('Eq', 'Eq'),
     ('FD', 'FD'),
     ('FU', 'FU'),
     ('Fg', 'Fg'),
     ('Ft', 'Ft'),
     ('G', 'G'),
     ('Id', 'Id'),
     ('K', 'K'),
     ('Lambda', 'Lambda'),
     ('Lambda0', 'Lambda0'),
     ('Lf', 'Lf'),
     ('Mh', 'Mh'),
     ('Omega', 'Omega'),
     ('Pi', 'Pi'),
     ('Sh', 'Sh'),
     ('T', 'T'),
     ('Vh', 'Vh'),
     ('W', 'W'),
     ('Y', 'Y'),
     ('Ydh', 'Ydh'),
     ('Yfc', 'Yfc'),
     ('Yh', 'Yh'),
     ('Z', 'Z'),
     ('_B__1', '_B__1'),
     ('_Eq__1', '_Eq__1'),
     ('_K__1', '_K__1'),
     ('_K__2', '_K__2'),
     ('_Lf__1', '_Lf__1'),
     ('_Mh__1', '_Mh__1'),
     ('_Vh__1', '_Vh__1'),
     ('_Y__1', '_Y__1'),
     ('_h__1', '_h__1'),
     ('_pe__1', '_pe__1'),
     ('a', 'a'),
     ('alpha1', 'alpha1'),
     ('alpha2', 'alpha2'),
     ('delta', 'delta'),
     ('gamma', 'gamma'),
     ('gk', 'gk'),
     ('h', 'h'),
     ('mu', 'mu'),
     ('pe', 'pe'),
     ('rb', 'rb'),
     ('rg', 'rg'),
     ('rm', 'rm'),
     ('rn', 'rn'),
     ('sf', 'sf'),
     ('sigma', 'sigma'),
     ('tau', 'tau'),
     ('u', 'u'),
     ('un', 'un'),
     ('v', 'v')]


```python
# Initialisation Cell
# You should always put imported modules here
from math import *
import numpy as np
import numpy.testing as nt
import numpy.linalg as LA
import warnings
import seaborn as sns
warnings.filterwarnings("ignore")
from matplotlib import pyplot as plt
np.set_printoptions(suppress=True, precision=7)
```

# APPM7037A  - November 2019

# Exam Office Info

| Examiner          | Name              |
|-------------------|-------------------|
| Internal Examiner | Prof B. A. Jacobs |
| External Examiner | Prof C. Harley |

# CDEs Masters - Exam

## Instructions

* Read all the instructions carefully.
* The exam consists of **95 Marks**, with **four** hours available.
* The written section is to be answered in the book provided.
* You must only access Moodle **TESTS** and NOT Moodle.
* The programming section is to be answered within this Jupyter notebook and resubmitted to Moodle **TESTS**.
* Do not rename the notebook, simply answer the questions and resubmit the file to Moodle.
* The moodle submission link will expire at exactly **13:00** and **NO** late submission will be accepted. Please make sure you submit timeously!
* The **Numpy** and **Matplotlib** documentation has been downloaded and is open on your current machine.
* **NB!!!** Anyone caught using Moodle (and its file storing), flash drives or external notes will be awarded zero and reported to the legal office.

## Written Section

* Answer the following questions in the answer book provided.

### Question 1 - 10 Marks

Discuss each of the below listed terms and their relation to one another (i.e. the theorem which describes this relationship):

* Consistency,
* Stability,
* Convergence,

Be sure to give potential methods of analysing consistency, stability and convergence of a  linear PDE.

### Question 2 - 10 Marks

Analyse the stability of the given ADI scheme by taking the discrete Fourier Transform of the equation:
$$
u_{j, n}^{m+1 / 2}-u_{j, n}^{m}=\frac{\nu}{\Delta x^{2}} A u_{j, n}^{m+1 / 2}+\frac{\nu}{\Delta y^{2}} B u_{j, n}^{m},
$$
which can be rewritten as:
$$
\left(1-\frac{\beta_{x}}{2} A\right) u^{m+1 / 2}=\left(1+\frac{\beta_{x}}{2} B\right) u^{m+1 / 2},
$$
with $\beta_x = \frac{\Delta t}{\Delta x^2}$ and $\beta_y = \frac{\Delta t}{\Delta y^2}$.

### Question 3 - 10 Marks
Verify that:
$$
\left.\frac{\partial^{3} u}{\partial x^{3}}\right|_{i, j}=\frac{\delta_{+}^{3} u_{i, j}}{(\Delta x)^{3}}+O(\Delta x).
$$
(Hint: Taylor series)

### Question 4 - 10 Marks

Consider the heat equation in cylindrical coordinates:
$$
u_{t}=\frac{\alpha}{r} \frac{\partial}{\partial r}\left(r \frac{\partial u}{\partial r}\right).
$$
(a) [8 Marks] Using a Lax-Wendroff scheme, set up an updating equation.

(b) [2 Marks] Comment on ways in which the scheme could be improved.

## Programming Section

### Question 1 - 15 Marks

(a) [10 Marks] Consider the wave equation given by:
$$
u_{tt} = c^2u_{xx},
$$
$$
u(x, 0) = x(1 - x), \ \ \ u_t(x, 0) = 0, \ \ \ u(0, t) = u(1, t) = 0.
$$
Write a function that implements a centered space, centered time scheme. Specifically, your function should take as inputs, the stepsizes `dx` and `dt`, the wave speed `c` (not squared valued), the number of iterations to perform `N` and the left and right endpoints `a`, `b`.

Your function should return the solution matrix, containing the wave profile at each time iteration, i.e. `N + 1` rows.

```python
def wave_eq(dx, dt, c, N, ic, a, b):
    # YOUR CODE HERE
    raise NotImplementedError()

```

```python
# Run this test cell to check your code
# Do not delete this cell
# 1 mark
# Unit test
dx = 0.1
c  = 0.2
tf = 8
N  = 20
dt = (tf - 0)/N
a  = 0
b  = 1
ic = lambda x: x*(1 - x)
tans = np.array([0.  , 0.09, 0.16, 0.21, 0.24, 0.25, 0.24, 0.21, 0.16, 0.09, 0.  ])
U = wave_eq(dx, dt, c, N, ic, a, b)
nt.assert_array_almost_equal(tans, U[0, :])
print('Test case passed!!!')
```

```python
# Run this test cell to check your code
# Do not delete this cell
# 1 mark
# Unit test
dx = 0.1
c  = 0.2
tf = 8
N  = 20
dt = (tf - 0)/N
a  = 0
b  = 1
ic = lambda x: x*(1 - x)
tans = np.array([0.    , 0.0836, 0.1536, 0.2036, 0.2336, 0.2436, 0.2336, 0.2036,
       0.1536, 0.0836, 0.    ])
U = wave_eq(dx, dt, c, N, ic, a, b)
nt.assert_array_almost_equal(tans, U[1, :])
print('Test case passed!!!')
```

```python
# Hidden test
# No output will be produced
# 8 marks
```

(b) [5 Marks] Continuing with Question 1(a) above, given the input below, produce the 3D surface plot illustrating the evolution of the wave profile over time.

```python
dx    = 0.001
c     = 0.2
tf    = 8
N     = 2000
dt    = (tf - 0)/N
a     = 0
b     = 1
ic    = lambda x: x*(1 - x)
xvals = np.linspace(a, b, int((b - a)/dx) + 1)
U     = wave_eq(dx, dt, c, N, ic, a, b)
```

```python
# YOUR CODE HERE
raise NotImplementedError()
```

### Question 2 - 15 Marks

Given the equation:
$$
\frac{\partial^{2} T}{\partial r^{2}}+\frac{1}{r} \frac{\partial T}{\partial r}=\frac{1}{4 K} \frac{\partial T}{\partial t}, \quad 0 \leq r \leq 1, \quad t \geq 0,
$$
where:
$$
T^\prime\left(0, t\right)=0, \qquad T(1, t)=100+40 t, \quad T(r, 0)=200\cos(r)
$$

(a) [10 Marks] Write a function which uses central difference approximations for the spatial derivatives and a backward difference approximation for temporal derivatives. The function should take as inputs, the time step `dt`, the spatial step `dr`, a final temperature to approximate `tf`, and the diffusivity coefficient `K`. The function should return the matrix of solutions ended with the approximation at `tf`.

```python
def heatEqnCylinderNBC(dt, dr, tf, K):
    # YOUR CODE HERE
    raise NotImplementedError()
```

```python
# Run this test cell to check your code
# Do not delete this cell
# 1 mark
# Unit test
dr = 0.01
dt = 0.005
K  = 0.1
tf = 0.5
u = heatEqnCylinderNBC(dt, dr, tf, K)
tans = np.array([200.       , 199.9900001, 199.9600013, 199.9100067, 199.8400213,
               199.7500521, 199.640108 , 199.5102001, 199.3603413, 199.1905466,
               199.0008331, 198.7912196, 198.5617272, 198.3123787, 198.0431992,
               197.7542156, 197.4454567, 197.1169534, 196.7687386, 196.400847 ,
               196.0133156, 195.6061829, 195.1794899, 194.733279 , 194.267595 ,
               193.7824843, 193.2779956, 192.7541793, 192.2110877, 191.6487751,
               191.0672978, 190.466714 , 189.8470836, 189.2084687, 188.5509331,
               187.8745426, 187.1793647, 186.4654691, 185.7329271, 184.981812 ,
               184.2121988, 183.4241646, 182.6177881, 181.7931499, 180.9503326,
               180.0894205, 179.2104995, 178.3136576, 177.3989846, 176.4665717,
               175.5165124, 174.5489015, 173.5638359, 172.5614141, 171.5417363,
               170.5049044, 169.4510222, 168.380195 , 167.29253  , 166.1881358,
               165.067123 , 163.9296036, 162.7756913, 161.6055017, 160.4191516,
               159.2167597, 157.9984463, 156.7643332, 155.5145438, 154.249203 ,
               152.9684375, 151.6723752, 150.3611458, 149.0348805, 147.6937117,
               146.3377738, 144.9672021, 143.5821339, 142.1827076, 140.7690631,
               139.3413419, 137.8996866, 136.4442415, 134.975152 , 133.4925652,
               131.9966292, 130.4874936, 128.9653094, 127.4302288, 125.8824053,
               124.3219937, 122.7491499, 121.1640313, 119.5667965, 117.957605 ,
               116.3366179, 114.7039972, 113.0599062, 111.4045094, 109.7379721,
               100.       ])
nt.assert_array_almost_equal(u[0, :], tans)
print('Test case passed!!!')
```

```python
# Run this test cell to check your code
# Do not delete this cell
# 1 mark
# Unit test
dr = 0.01
dt = 0.005
K  = 0.1
tf = 0.5
u = heatEqnCylinderNBC(dt, dr, tf, K)
tans = np.array([199.2194951, 199.1999825, 199.1671443, 199.1157272, 199.0449601,
               198.954583 , 198.8444803, 198.7145953, 198.5649001, 198.3953835,
               198.2060452, 197.996892 , 197.7679365, 197.5191955, 197.2506895,
               196.962442 , 196.6544795, 196.326831 , 195.9795278, 195.6126038,
               195.2260948, 194.8200389, 194.3944763, 193.9494491, 193.4850016,
               193.00118  , 192.4980326, 191.9756095, 191.433963 , 190.873147 ,
               190.2932177, 189.6942329, 189.0762525, 188.4393384, 187.783554 ,
               187.108965 , 186.4156388, 185.7036446, 184.9730535, 184.2239387,
               183.4563747, 182.6704383, 181.8662079, 181.0437636, 180.2031874,
               179.3445631, 178.4679761, 177.5735134, 176.6612638, 175.7313178,
               174.7837671, 173.8187054, 172.8362273, 171.8364292, 170.8194084,
               169.7852636, 168.734094 , 167.6660001, 166.5810825, 165.4794421,
               164.3611798, 163.2263957, 162.0751888, 160.9076564, 159.7238927,
               158.5239885, 157.3080293, 156.0760939, 154.8282524, 153.5645634,
               152.2850713, 150.9898021, 149.6787585, 148.3519142, 147.0092062,
               145.6505255, 144.2757058, 142.8845087, 141.4766063, 140.0515588,
               138.6087868, 137.1475373, 135.6668404, 134.1654569, 132.6418117,
               131.0939118, 129.5192441, 127.914648 , 126.2761573, 124.598803 ,
               122.8763685, 121.1010846, 119.2632497, 117.3507579, 115.3485112,
               113.2376878, 110.994832 , 108.5907209, 105.988954 , 103.1441977,
               100.2      ])
nt.assert_array_almost_equal(u[1, :], tans)
print('Test case passed!!!')
```

```python
# Hidden test
# No output will be produced
# 8 marks
```

(b) [5 Marks] Continuing from Question 2(a) above, plot the surface plot over all time, given the input below:

```python
dr = 0.001
dt = 0.005
K  = 0.1
tf = 0.5
u = heatEqnCylinderNBC(dt, dr, tf, K)
```

```python
# YOUR CODE HERE
raise NotImplementedError()
```

### Question 3 - 10 Marks

(a) [7 Marks] Given the heat equation where:
$$
u_t = u_{xx},
$$
$$
0 < x < 1, \ \ \ t \geq 0, \ \ \ u(0, t) = u(1, t) = 0, \ \ \  u(x, 0) = \sin(\pi x),
$$

Implement a Crank-Nicolson scheme on the heat equation given above and find an approximation to $t = 0.5$. The function should take as inputs, the time-step `dt`, the spatial step `dx`, the final time `tf`, and the initial condition as a handle, `f`. The function should return the solution matrix $U$.

Note: the analytical solution is:
$$
u(x, t) = e^{-\pi^2 t}\sin(\pi x)
$$

```python
def crankNicolson(dt, dx, tf, f):
    # YOUR CODE HERE
    raise NotImplementedError()
```

```python
# Run this test cell to check your code
# Do not delete this cell
# 1 mark
# Unit test
dx    = 0.1
dt    = 0.005
tf    = 0.5
f     = lambda x: np.sin(np.pi * x)
D     = 1
tans  = np.array([0.       , 0.309017 , 0.5877853, 0.809017 , 0.9510565, 1.       ,
                  0.9510565, 0.809017 , 0.5877853, 0.309017 , 0.       ])
ans   = crankNicolson(dt, dx, tf, f)
nt.assert_array_almost_equal(tans, ans[0])
print('Test case passed!!!')
```

```python
# Run this test cell to check your code
# Do not delete this cell
# 1 mark
# Unit test
dx    = 0.1
dt    = 0.005
tf    = 0.5
f     = lambda x: np.sin(np.pi * x)

tans  = np.array([0.       , 0.2942539, 0.5597042, 0.7703667, 0.9056204, 0.9522256,
       0.9056204, 0.7703667, 0.5597042, 0.2942539, 0.       ])
ans   = crankNicolson(dt, dx, tf, f)
nt.assert_array_almost_equal(tans, ans[1])
print('Test case passed!!!')
```

```python
# Hidden test
# No output will be produced
# 5 marks
```

(b) [3 Marks] Continuing with Question 3(a) above, consider the following input:

```python
dx    = 0.1
dt    = 0.005
tf    = 0.5
f     = lambda x: np.sin(np.pi * x)
U     = crankNicolson(dt, dx, tf, f)
```

(c) [3 Marks] Write a function `errorFunction` which returns the absolute error, relative error and the norm (in that order) at time `tf`, between the true solution given in Question 3(a) and your obtained Crank-Nicolson approximation.

```python
def errorFunction():
    # YOUR CODE HERE
    raise NotImplementedError()
```

```python
# Hidden test
# No output will be produced
# 1 mark
```

```python
# Hidden test
# No output will be produced
# 1 mark
```

```python
# Hidden test
# No output will be produced
# 1 mark
```

### Question 4 - 15 Marks

(a) [10 Marks] Consider the PDE given by:
$$
v_t = D\left( v_{xx} + v_{yy}\right),
$$
$$
v(-1, y, t) = v(1, y, t) = 0,\ v(x, y, 0) = 0,
$$
\begin{equation}
v(x, -1, 0) = v(x, 1, 0) = 100, \ \ \ x \in (-1, 1)\ \ \text{i.e. endpoints excluded}
\end{equation}

Periodic boundary conditions should be imposed on $y = -1, y = 1$, i.e.$v(x,-1,t)=v(x,1,t)$ for all $t$ and $x$.

Write a function which implements an ADI scheme to solve the PDE given above. Specifically, the function should take as inputs, the step-sizes, `dx` and `dy`, the time-step `dt`, the constant `D`, and the number of iterations to perform `N`.

The function should return the 2D heatmap for each time-step, that is, a 3D array of `N + 1` time-steps.

```python
def heat2D_ADI(dx, dy, dt, D, N):
    # YOUR CODE HERE
    raise NotImplementedError()
```

```python
# Run this test cell to check your code
# Do not delete this cell
# 1 mark
# Unit test
dx   = 0.2
dy   = 0.2
dt   = 0.1
D    = 0.1
N    = 5
tans = np.array([[  0., 100., 100., 100., 100., 100., 100., 100., 100., 100.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.,   0.],
       [  0., 100., 100., 100., 100., 100., 100., 100., 100., 100.,   0.]])
U    = heat2D_ADI(dx, dy, dt, D, N)
nt.assert_array_almost_equal(tans, U[:, :, 0])
print('Test case passed!!!')
```

```python
# Run this test cell to check your code
# Do not delete this cell
# 1 mark
# Unit test
dx   = 0.2
dy   = 0.2
dt   = 0.1
D    = 0.1
N    = 5
tans = np.array([[ 0.       , 65.3025091, 78.3317661, 79.6479746, 79.780803 ,
        79.7928783, 79.780803 , 79.6479746, 78.3317661, 65.3025091,
         0.       ],
       [ 0.       , 14.8641016, 17.82981  , 18.1294042, 18.1596385,
        18.1623871, 18.1596385, 18.1294042, 17.82981  , 14.8641016,
         0.       ],
       [ 0.       ,  1.5015808,  1.8011785,  1.8314437,  1.834498 ,
         1.8347756,  1.834498 ,  1.8314437,  1.8011785,  1.5015808,
         0.       ],
       [ 0.       ,  0.1517061,  0.1819747,  0.1850325,  0.185341 ,
         0.1853691,  0.185341 ,  0.1850325,  0.1819747,  0.1517061,
         0.       ],
       [ 0.       ,  0.0154802,  0.0185689,  0.0188809,  0.0189124,
         0.0189152,  0.0189124,  0.0188809,  0.0185689,  0.0154802,
         0.       ],
       [ 0.       ,  0.003096 ,  0.0037138,  0.0037762,  0.0037825,
         0.003783 ,  0.0037825,  0.0037762,  0.0037138,  0.003096 ,
         0.       ],
       [ 0.       ,  0.0154802,  0.0185689,  0.0188809,  0.0189124,
         0.0189152,  0.0189124,  0.0188809,  0.0185689,  0.0154802,
         0.       ],
       [ 0.       ,  0.1517061,  0.1819747,  0.1850325,  0.185341 ,
         0.1853691,  0.185341 ,  0.1850325,  0.1819747,  0.1517061,
         0.       ],
       [ 0.       ,  1.5015808,  1.8011785,  1.8314437,  1.834498 ,
         1.8347756,  1.834498 ,  1.8314437,  1.8011785,  1.5015808,
         0.       ],
       [ 0.       , 14.8641016, 17.82981  , 18.1294042, 18.1596385,
        18.1623871, 18.1596385, 18.1294042, 17.82981  , 14.8641016,
         0.       ],
       [ 0.       , 65.3025091, 78.3317661, 79.6479746, 79.780803 ,
        79.7928783, 79.780803 , 79.6479746, 78.3317661, 65.3025091,
         0.       ]])

U = heat2D_ADI(dx, dy, dt, D, N)
nt.assert_array_almost_equal(tans, U[:, :, 1])
print('Test case passed!!!')
```

```python
# Hidden test
# No output will be produced
# 8 marks
```

(b) [2 Marks] Plot a heatmap of the final time-step using the ADI function in Question 4(a), given the input below:

```python
dx = 0.1
dy = 0.1
dt = 0.1
D  = 0.2
N  = 5
U  = heat2D_ADI(dx, dy, dt, D, N)
```

```python
# 2 Marks
# YOUR CODE HERE
raise NotImplementedError()
```

(c) [3 Marks] Modify your function from Question 4(a) to plot the two tridiagonal ADI matrices $A$ and $B$.

```python
#3 Marks
# YOUR CODE HERE
raise NotImplementedError()
```


# FSM Only Applicable to Compression of H

We consider the $9$-periodic potential $v = \frac{1}{\sqrt{2}}(1,1,1,0,1,1,0,1,0)$ and compute the matrices $M^{(j)}$ and $\widetilde{M}^{(j)}$ for $j\in \{0,1,\dots,8\}$ defined as
\begin{align}
\label{eq:M^j}
\rule{5mm}{0mm}M^{(j)}&=
\begin{pmatrix} -v(K-1+j)&-1\\1&0\end{pmatrix}\cdots
\begin{pmatrix} -v(1+j)&-1\\1&0\end{pmatrix}
\begin{pmatrix} -v(j)&-1\\1&0\end{pmatrix}\\
\label{eq:N^j}
\widetilde{M}^{(j)}&=
\begin{pmatrix} -v(j)&-1\\1&0\end{pmatrix}
\begin{pmatrix} -v(1+j)&-1\\1&0\end{pmatrix}\cdots
\begin{pmatrix} -v(K-1+j)&-1\\1&0\end{pmatrix} \,.
\end{align}

Running the cell below outputs all of these matrices, and it can be checked which of these matrices are subject to the condition

\begin{equation}
M_{2,1}\ne 0\qquad\text{or}\qquad |M_{1,1}|>1 \,.
\end{equation}

This condition is satisfied for all matrices $\widetilde{M}^{(j)}$ and the matrix $M^{(0)}$ but not for $M^{(1)}$, $M^{(6)}$ and $M^{(8)}$. Consequently, the FSM is **not applicable** to the two-sided infinite discrete Schrödinger operator $H$ associated to the periodic potential $v$; but it the FSM is **applicable** to the one-sided compression $H_+$.

```python
from IPython.display import display, Math, Latex

def mon(v,l):
######
# Calculate the general monodromy matrix with scaling l
#
# Example:
# v = [1,1,0]; mon(v, l).expand()
# > [      l       1]
# > [l^2 - 1       l]
#
##########################
    M = identity_matrix(2)
    for vv in v:
        M = matrix(2,2,[- l*vv, -1, 1, 0])*M
    return M

def lim_pots(v):
#
# determine all unique limit potentials of a given
# periodic potential v by considering all shifts and flips
#
##########################
    v_rev = deepcopy(v)
    lim = shift_pots(v)
    v_rev.reverse()
    lim_rev = shift_pots(v_rev)
    for pot in lim_rev:
        if pot not in lim:
            lim.append(pot)
    return lim

def shift_pots(v):
#
# determine all unique shifts of a given periodic potential v
#
##########################
    shift = []
    for c in range(len(v)):
        if v not in shift:
            shift.append(v)
        v = left_shift(v)
    return shift

def left_shift(a):
    return [*a[1:], a[0]]

##################################
#
# check the periodic potential v of Example 4.6
#
v = [1,1,1,0,1,1,0,1,0] # potential from 0 to K-1
v_list = shift_pots(v)

v_rev_list = []
for v in v_list:
    v_rev = deepcopy(v)
    v_rev.reverse()
    v_rev_list.append(v_rev)

##############
# iterate shifts of potential for M matrices
#
for k,vv in enumerate(v_list):
    M = mon(vv, 1/sqrt(2))
    display(Math( r' M^{(%(idx)d)}= %(mat)s \quad \text{from potential }%(v)s'
                 % {'idx': k, 'mat': latex(M), 'v': latex(vv)}))

##############
# iterate shifts of reversed potential for N matrices
#
for k,vv in enumerate(v_rev_list):
    M = mon(vv, 1/sqrt(2))
    display(Math( r' \widetilde{M}^{(%(idx)d)}= %(mat)s \quad \text{from potential }%(v)s'
                 % {'idx': k, 'mat': latex(M), 'v': latex(vv)}))

```

$\displaystyle  M^{(0)}= \left(\begin{array}{rr}
-\sqrt{2} & 0 \\
-\frac{3}{2} & -\frac{1}{2} \, \sqrt{2}
\end{array}\right) \quad \text{from potential }\left[1, 1, 1, 0, 1, 1, 0, 1, 0\right]$

$\displaystyle  M^{(1)}= \left(\begin{array}{rr}
-\frac{1}{2} \, \sqrt{2} & 2 \\
0 & -\sqrt{2}
\end{array}\right) \quad \text{from potential }\left[1, 1, 0, 1, 1, 0, 1, 0, 1\right]$

$\displaystyle  M^{(2)}= \left(\begin{array}{rr}
0 & \frac{1}{2} \\
-2 & -\frac{3}{2} \, \sqrt{2}
\end{array}\right) \quad \text{from potential }\left[1, 0, 1, 1, 0, 1, 0, 1, 1\right]$

$\displaystyle  M^{(3)}= \left(\begin{array}{rr}
-\frac{5}{4} \, \sqrt{2} & \frac{3}{4} \\
-\frac{1}{2} & -\frac{1}{4} \, \sqrt{2}
\end{array}\right) \quad \text{from potential }\left[0, 1, 1, 0, 1, 0, 1, 1, 1\right]$

$\displaystyle  M^{(4)}= \left(\begin{array}{rr}
-\frac{1}{4} \, \sqrt{2} & \frac{1}{2} \\
-\frac{3}{4} & -\frac{5}{4} \, \sqrt{2}
\end{array}\right) \quad \text{from potential }\left[1, 1, 0, 1, 0, 1, 1, 1, 0\right]$

$\displaystyle  M^{(5)}= \left(\begin{array}{rr}
-\sqrt{2} & 0 \\
-\frac{1}{2} & -\frac{1}{2} \, \sqrt{2}
\end{array}\right) \quad \text{from potential }\left[1, 0, 1, 0, 1, 1, 1, 0, 1\right]$

$\displaystyle  M^{(6)}= \left(\begin{array}{rr}
-\frac{1}{2} \, \sqrt{2} & 1 \\
0 & -\sqrt{2}
\end{array}\right) \quad \text{from potential }\left[0, 1, 0, 1, 1, 1, 0, 1, 1\right]$

$\displaystyle  M^{(7)}= \left(\begin{array}{rr}
-\sqrt{2} & 0 \\
-1 & -\frac{1}{2} \, \sqrt{2}
\end{array}\right) \quad \text{from potential }\left[1, 0, 1, 1, 1, 0, 1, 1, 0\right]$

$\displaystyle  M^{(8)}= \left(\begin{array}{rr}
-\frac{1}{2} \, \sqrt{2} & \frac{3}{2} \\
0 & -\sqrt{2}
\end{array}\right) \quad \text{from potential }\left[0, 1, 1, 1, 0, 1, 1, 0, 1\right]$

$\displaystyle  \widetilde{M}^{(0)}= \left(\begin{array}{rr}
-\sqrt{2} & \frac{3}{2} \\
0 & -\frac{1}{2} \, \sqrt{2}
\end{array}\right) \quad \text{from potential }\left[0, 1, 0, 1, 1, 0, 1, 1, 1\right]$

$\displaystyle  \widetilde{M}^{(1)}= \left(\begin{array}{rr}
-\frac{1}{2} \, \sqrt{2} & 0 \\
-2 & -\sqrt{2}
\end{array}\right) \quad \text{from potential }\left[1, 0, 1, 0, 1, 1, 0, 1, 1\right]$

$\displaystyle  \widetilde{M}^{(2)}= \left(\begin{array}{rr}
0 & 2 \\
-\frac{1}{2} & -\frac{3}{2} \, \sqrt{2}
\end{array}\right) \quad \text{from potential }\left[1, 1, 0, 1, 0, 1, 1, 0, 1\right]$

$\displaystyle  \widetilde{M}^{(3)}= \left(\begin{array}{rr}
-\frac{5}{4} \, \sqrt{2} & \frac{1}{2} \\
-\frac{3}{4} & -\frac{1}{4} \, \sqrt{2}
\end{array}\right) \quad \text{from potential }\left[1, 1, 1, 0, 1, 0, 1, 1, 0\right]$

$\displaystyle  \widetilde{M}^{(4)}= \left(\begin{array}{rr}
-\frac{1}{4} \, \sqrt{2} & \frac{3}{4} \\
-\frac{1}{2} & -\frac{5}{4} \, \sqrt{2}
\end{array}\right) \quad \text{from potential }\left[0, 1, 1, 1, 0, 1, 0, 1, 1\right]$

$\displaystyle  \widetilde{M}^{(5)}= \left(\begin{array}{rr}
-\sqrt{2} & \frac{1}{2} \\
0 & -\frac{1}{2} \, \sqrt{2}
\end{array}\right) \quad \text{from potential }\left[1, 0, 1, 1, 1, 0, 1, 0, 1\right]$

$\displaystyle  \widetilde{M}^{(6)}= \left(\begin{array}{rr}
-\frac{1}{2} \, \sqrt{2} & 0 \\
-1 & -\sqrt{2}
\end{array}\right) \quad \text{from potential }\left[1, 1, 0, 1, 1, 1, 0, 1, 0\right]$

$\displaystyle  \widetilde{M}^{(7)}= \left(\begin{array}{rr}
-\sqrt{2} & 1 \\
0 & -\frac{1}{2} \, \sqrt{2}
\end{array}\right) \quad \text{from potential }\left[0, 1, 1, 0, 1, 1, 1, 0, 1\right]$

$\displaystyle  \widetilde{M}^{(8)}= \left(\begin{array}{rr}
-\frac{1}{2} \, \sqrt{2} & 0 \\
-\frac{3}{2} & -\sqrt{2}
\end{array}\right) \quad \text{from potential }\left[1, 0, 1, 1, 0, 1, 1, 1, 0\right]$