# Plot the results recorded by excavation.tcl or excavation.py (run in the same
# directory as the analysis, with excavationMesh.py alongside this script).
#
#   python plotResults.py

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection

from excavationMesh import soilNodes, soilElements, permanentNodes, permanentElements, beamNodes, beamElements

# number of gravity steps and steps per excavation lift in the analysis
nGravity = 8
nPerLift = 4
nLift = 10

disp = np.loadtxt('displacement.out')[:, 1:]       # x, y at the permanent soil nodes
force = np.loadtxt('globalForces.out')[:, 1:]      # 6 global forces per wall element

# rows at the end of the gravity analysis and of each excavation lift
rows = [nGravity - 1 + nPerLift * k for k in range(nLift + 1)]
colors = plt.cm.viridis(np.linspace(0, 1, len(rows)))
labels = ['gravity'] + [f'lift {k} ({0.5 * k:g} m)' for k in range(1, nLift + 1)]

fig = plt.figure(figsize=(13, 9))
gs = fig.add_gridspec(2, 3)

# deformed mesh of the permanent soil elements at the end of the excavation (magnified)
mag = 25.0
xy = {tag: (x, y) for tag, x, y in soilNodes}
col = {tag: i for i, tag in enumerate(permanentNodes)}
uEnd = disp[-1]
conn = {e[0]: e[1:] for e in soilElements}


def polys(deformed):
    out = []
    for e in permanentElements:
        pts = []
        for n in conn[e]:
            x, y = xy[n]
            if deformed:
                i = col[n]
                x, y = x + mag * uEnd[2 * i], y + mag * uEnd[2 * i + 1]
            pts.append((x, y))
        out.append(pts)
    return out


a = fig.add_subplot(gs[0, :])
a.add_collection(PolyCollection(polys(False), facecolor='none', edgecolor='0.8', lw=0.5))
a.add_collection(PolyCollection(polys(True), facecolor='none', edgecolor='tab:green', lw=0.7))
wall = sorted((y, x) for tag, x, y in beamNodes)
wy = np.array([w[0] for w in wall])
a.plot([0, 0], [wy.min(), wy.max()], color='tab:blue', lw=3)
a.set_aspect('equal')
a.autoscale()
a.set_title(f'Deformed mesh at the end of excavation (displacements x {mag:g})')

# wall response: element forces at end i, elements ordered from the base up
yEle = np.array([xy_y for xy_y in (dict((t, y) for t, x, y in beamNodes)[e[1]] for e in beamElements)])
F = force.reshape(force.shape[0], len(beamElements), 6)
V = F[:, :, 0]                                     # shear (global x force at end i)
M = F[:, :, 2]                                     # moment at end i

ax = [fig.add_subplot(gs[1, k]) for k in range(3)]
for c, r, lab in zip(colors, rows, labels):
    ax[0].plot(M[r], yEle, color=c, label=lab)
    ax[1].plot(V[r], yEle, color=c)

# wall displacement taken from the soil nodes adjacent to the wall on the left side
left = sorted((y, n) for n, x, y in soilNodes if abs(x + 0.25) < 1e-6 and n in col)
yl = np.array([y for y, n in left])
for c, r in zip(colors, rows):
    ux = [disp[r, 2 * col[n]] for y, n in left]
    ax[2].plot(ux, yl, color=c)

ax[0].set_xlabel('Wall bending moment (kN-m)')
ax[1].set_xlabel('Wall shear force (kN)')
ax[2].set_xlabel('Soil displacement next to wall (m)')
for a in ax:
    a.set_ylabel('Elevation (m)')
    a.axhline(10.0, color='0.6', lw=0.8, ls='--')
    a.grid(True, alpha=0.3)
ax[0].legend(fontsize=7)

fig.tight_layout()
fig.savefig('excavationResults.png', dpi=150)
plt.show()
