#######################################################################
#                                                                     #
#  Excavation of cohesionless soil supported by a cantilevered sheet  #
#  pile wall.  2D Plane Strain analysis.  Beam elements define the    #
#  wall, and beam-contact elements are used to create a frictional    #
#  soil-pile interface. Initial state analysis is used to create      #
#  an initial state of stress and strain due to gravity without the   #
#  corresponding displacements.                                       #
#                                                                     #
#   Created by:  Chris McGann                                         #
#                Pedro Arduino                                        #
#              --University of Washington--                           #
#                                                                     #
#   Python version of excavation.tcl; the mesh data generated with    #
#   GiD is in excavationMesh.py                                       #
#                                                                     #
# ---> Basic units are kN and m                                       #
#                                                                     #
#######################################################################

import os
import time
import openseespy.opensees as ops

from excavationMesh import (soilNodes, soilFix, permanentNodes, soilElements, permanentElements,
                            beamNodes, beamElements, contactElements, permanentContactElements, lifts)

ops.wipe()

#-----------------------------------------------------------------------------------------
#  1. CREATE SOIL NODES AND FIXITIES
#-----------------------------------------------------------------------------------------
ops.model('BasicBuilder', '-ndm', 2, '-ndf', 2)

# define soil nodes
for tag, x, y in soilNodes:
    ops.node(tag, x, y)
print('Finished creating all -ndf 2 soil nodes...')

# define fixities for soil nodes
for tag, fx, fy in soilFix:
    ops.fix(tag, fx, fy)
print('Finished creating all -ndf 2 boundary conditions...')

#-----------------------------------------------------------------------------------------
#  3. CREATE LAGRANGE MULTIPLIER NODES FOR BEAM CONTACT ELEMENTS
#-----------------------------------------------------------------------------------------

for k in range(1, 43):
    ops.node(1000 + k, 0.00, 0.00)
print('Finished creating all -ndf 2 nodes...')

#-----------------------------------------------------------------------------------------
#  4. CREATE SOIL MATERIALS
#-----------------------------------------------------------------------------------------

# define pressure depended material for soil
ops.nDMaterial('PressureDependMultiYield02', 5, 2, 1.8, 9.6e3, 2.7e4, 36, 0.1,
               101.0, 0.0, 26, 0.067, 0.23, 0.06,
               0.27, 20, 5.0, 3.0, 1.0,
               0.0, 0.77, 0.9, 0.02, 0.7, 101.0)
# element thickness
thick1 = 1.0
# body force in x-direction
xWgt1 = 0.00
# body force in y-direction
yWgt1 = -9.81 * 1.8

# create wrapper material for initial state analysis
ops.nDMaterial('InitialStateAnalysisWrapper', 1, 5, 2)

print('Finished creating all soil materials...')

#-----------------------------------------------------------------------------------------
#  5. CREATE SOIL ELEMENTS
#-----------------------------------------------------------------------------------------

for tag, n1, n2, n3, n4 in soilElements:
    ops.element('quad', tag, n1, n2, n3, n4, thick1, 'PlaneStrain', 1, 0.0, 0.0, xWgt1, yWgt1)
print('Finished creating all soil elements...')

#-----------------------------------------------------------------------------------------
#  6. CREATE BEAM NODES AND FIXITIES
#-----------------------------------------------------------------------------------------
ops.model('BasicBuilder', '-ndm', 2, '-ndf', 3)

# define beam nodes
for tag, x, y in beamNodes:
    ops.node(tag, x, y)
print('Finished creating all -ndf 3 beam nodes...')

# fix the base node of the sheetpile in the vertial direction
ops.fix(100, 0, 1, 0)
print('Finished creating all -ndf 3 boundary conditions...')

#-----------------------------------------------------------------------------------------
#  7. CREATE BEAM MATERIALS
#-----------------------------------------------------------------------------------------

# beam properties
thick = 0.5
area = 0.5
I = 9.75e-4
beamE = 200000000
numIntPts = 3
transTag = 1
secTag = 1

# geometric transformation
ops.geomTransf('Linear', transTag)

# beam section
ops.section('Elastic', secTag, beamE, area, I)

print('Finished creating all beam materials...')

#-----------------------------------------------------------------------------------------
#  8. CREATE BEAM ELEMENTS
#-----------------------------------------------------------------------------------------

# Gauss-Legendre integration with numIntPts integration points along each element
ops.beamIntegration('Legendre', 1, secTag, numIntPts)

for tag, nI, nJ in beamElements:
    ops.element('dispBeamColumn', tag, nI, nJ, transTag, 1)
print('Finished creating all beam elements...')

#-----------------------------------------------------------------------------------------
#  9. CREATE CONTACT MATERIAL FOR BEAM CONTACT ELEMENTS
#-----------------------------------------------------------------------------------------

# two-dimensional contact material
ops.nDMaterial('ContactMaterial2D', 2, 0.1, 1000.0, 0.0, 0.0)

print('Finished creating all contact materials...')

#-----------------------------------------------------------------------------------------
#  10. CREATE BEAM CONTACT ELEMENTS
#-----------------------------------------------------------------------------------------

# set gap and force tolerances for beam contact elements
gapTol = 1.0e-10
forceTol = 1.0e-10

# define beam contact elements
for tag, m1, m2, slave, lagr in contactElements:
    ops.element('BeamContact2D', tag, m1, m2, slave, lagr, 2, thick, gapTol, forceTol)
print('Finished creating all beam-contact elements...')

#-----------------------------------------------------------------------------------------
#  13. CREATE RECORDERS
#-----------------------------------------------------------------------------------------

beamElementList = [e[0] for e in beamElements]

# PERMANENT RECORDERS---------------------------------------------------------------------
# record nodal displacments at permanent nodes
ops.recorder('Node', '-file', 'displacement.out', '-time', '-node', *permanentNodes, '-dof', 1, 2, 'disp')
# record elemental stress in the soil at permanent elements
for gp in range(1, 5):
    ops.recorder('Element', '-file', f'stress{gp}.out', '-time', '-ele', *permanentElements,
                 'material', gp, 'stress')
# record permanent contact element information
ops.recorder('Element', '-file', 'slaveForce.out', '-time', '-ele', *permanentContactElements, 'forces')
ops.recorder('Element', '-file', 'frictForce.out', '-time', '-ele', *permanentContactElements, 'frictionforces')
ops.recorder('Element', '-file', 'contForce.out', '-time', '-ele', *permanentContactElements, 'forcescalars')
ops.recorder('Element', '-file', 'mastForce.out', '-time', '-ele', *permanentContactElements, 'masterforces')
# record beam response
ops.recorder('Element', '-file', 'globalForces.out', '-time', '-ele', *beamElementList, 'globalForce')

# RECORDERS FOR EXCAVATED MATERIAL (TO BE REMOVED)---------------------------------------
# the tags of the recorders for each lift are kept so they can be removed with the lift
liftRecorders = []
for lift in lifts:
    d = f"lift{lift['lift']}"
    os.makedirs(d, exist_ok=True)
    eles = range(lift['firstElement'], lift['firstElement'] + 10)
    bce = lift['contactElement']
    tags = [ops.recorder('Node', '-file', f'{d}/disp.out', '-time', '-node', *lift['soilNodes'], '-dof', 1, 2, 'disp')]
    for gp in range(1, 5):
        tags.append(ops.recorder('Element', '-file', f'{d}/stress{gp}.out', '-time', '-eleRange', eles[0], eles[-1],
                                 'material', gp, 'stress'))
    tags.append(ops.recorder('Element', '-file', f'{d}/slaveForce.out', '-time', '-ele', bce, 'forces'))
    tags.append(ops.recorder('Element', '-file', f'{d}/frictForce.out', '-time', '-ele', bce, 'frictionforces'))
    tags.append(ops.recorder('Element', '-file', f'{d}/contForce.out', '-time', '-ele', bce, 'forcescalars'))
    tags.append(ops.recorder('Element', '-file', f'{d}/mastForce.out', '-time', '-ele', bce, 'masterforces'))
    liftRecorders.append(tags)

print('Finished creating recorders...')

#-----------------------------------------------------------------------------------------
#  12. GRAVITY ANALYSIS (w/ INITIAL STATE ANALYSIS TO RESET DISPLACEMENTS)
#-----------------------------------------------------------------------------------------

# define analysis parameters for gravity phase
ops.constraints('Transformation')
ops.test('NormDispIncr', 1e-5, 15, 1)
ops.algorithm('Newton')
ops.numberer('RCM')
ops.system('BandGeneral')
ops.integrator('LoadControl', 1)
ops.analysis('Static')

# turn on initial state analysis feature
ops.InitialStateAnalysis('on')

# ensure soil material intially considers linear elastic behavior
ops.updateMaterialStage('-material', 1, '-stage', 0)

# set contact elements to be frictionless for gravity analysis
ops.setParameter('-val', 0, '-eleRange', 1001, 1042, 'friction')

startT = time.time()
ops.analyze(4)

# update soil material to consider elastoplastic behavior and analyze a few more steps
ops.updateMaterialStage('-material', 1, '-stage', 1)

ops.analyze(4)

# designate end of initial state analysis (zeros displacements, keeps state variables)
ops.InitialStateAnalysis('off')

# turn on frictional behavior for beam contact elements
ops.setParameter('-val', 1, '-eleRange', 1001, 1042, 'friction')

#-----------------------------------------------------------------------------------------
#  14. REMOVE ELEMENTS TO SIMULATE EXCAVATION
#-----------------------------------------------------------------------------------------

# define analysis parameters for excavation phase
ops.constraints('Transformation')
ops.test('NormDispIncr', 1e-4, 60, 1)
ops.algorithm('KrylovNewton')
ops.numberer('RCM')
ops.system('BandGeneral')
ops.integrator('LoadControl', 1)
ops.analysis('Static')

for lift, tags in zip(lifts, liftRecorders):
    # recorders
    for tag in tags:
        ops.remove('recorder', tag)
    # soil elements
    for k in range(10):
        ops.remove('element', lift['firstElement'] + k)
    # contact element
    ops.remove('element', lift['contactElement'])
    # lagrange multiplier node
    ops.remove('node', lift['lagrangeNode'])
    # soil nodes
    for n in lift['soilNodes']:
        ops.remove('node', n)

    # run analysis after object removal
    ops.analyze(4)

# excavation analysis complete
endT = time.time()
print(f'Analysis execution time: {endT - startT:.0f} seconds')

ops.wipe()
