# Plot the results recorded by lateralSpreadPile.tcl or lateralSpreadPile.py
# (run in the same directory as the analysis).
#
#   python plotResults.py

import numpy as np
import matplotlib.pyplot as plt

# geometry used in the analysis
L = 40.0              # pile length (m)
dz = 0.5              # node spacing (m)
liqTop, liqBot = 8.0, 10.0   # depth range of the liquefied layer (m)

# recorded data (first column is time)
force = np.loadtxt('globalForces.out')     # 12 global forces per pile element
disp = np.loadtxt('Displacements.out')     # x, y, z displacement of pile nodes 501..581
pyF = np.loadtxt('pyForces.out')           # x reaction at the soil end of springs 2..81
time = force[:, 0]

nEle = (force.shape[1] - 1) // 12
F = force[:, 1:].reshape(len(time), nEle, 12)
V = -F[:, :, 0]                            # shear at end i of each element
M = F[:, :, 4]                             # moment about y at end i of each element
ux = disp[:, 1::3]                         # lateral displacement of pile nodes
p = pyF[:, 1:] / dz                        # load applied to the pile per unit length

depthNode = dz * np.arange(ux.shape[1])
depthEle = depthNode[:-1]
depthSpring = depthNode[1:]

# steps to draw in the profile plots
steps = np.linspace(1, len(time) - 1, 6).astype(int)
colors = plt.cm.viridis(np.linspace(0, 1, len(steps)))

fig, ax = plt.subplots(2, 3, figsize=(13, 9))
profiles = [(ax[0, 0], V, depthEle, 'Shear force (kN)'),
            (ax[0, 1], M, depthEle, 'Bending moment (kN-m)'),
            (ax[0, 2], p, depthSpring, 'Applied load (kN/m)'),
            (ax[1, 0], ux, depthNode, 'Pile displacement (m)')]
for a, data, depth, label in profiles:
    for c, k in zip(colors, steps):
        a.plot(data[k], depth, color=c, label=f't = {time[k]:g}')
    a.axhspan(liqTop, liqBot, color='0.85', zorder=0)
    a.set_xlabel(label)
    a.set_ylabel('Depth (m)')
    a.invert_yaxis()
ax[0, 0].legend(fontsize=8)

# maximum moments in the upper (above liquefied) and lower (below liquefied) layers
upper = depthEle < liqTop
lower = depthEle > liqBot
iU = np.argmax(np.abs(M[:, upper]), axis=1)
iL = np.argmax(np.abs(M[:, lower]), axis=1)
mU = np.abs(M[:, upper])[np.arange(len(time)), iU]
mL = np.abs(M[:, lower])[np.arange(len(time)), iL]
zU = depthEle[upper][iU]
zL = depthEle[lower][iL]

a = ax[1, 1]
a.plot(time, mU, label='upper layer')
a.plot(time, mL, label='lower layer')
a.set_xlabel('Time (s)')
a.set_ylabel('Maximum |moment| (kN-m)')
a.legend(fontsize=8)

a = ax[1, 2]
a.plot(time, zU, label='upper maximum')
a.plot(time, zL, label='lower maximum')
a.plot(time, zL - zU, '--', label='L_effective')
a.axhspan(liqTop, liqBot, color='0.85', zorder=0)
a.set_xlabel('Time (s)')
a.set_ylabel('Depth / length (m)')
a.invert_yaxis()
a.legend(fontsize=8)

for a in ax.flat:
    a.grid(True, alpha=0.3)
fig.tight_layout()
fig.savefig('lateralSpreadResults.png', dpi=150)
plt.show()
