# OpenSees -- Open System for Earthquake Engineering Simulation
# Pacific Earthquake Engineering Research Center
#
# Basic Elastic Frame
# ----------------------
#  2d Elastic Beam Column Elements
#  Dynamic Analysis given elCentro data using UniformExcitation

# Units: kips, in, sec

import math
import openseespy.opensees as ops

#
# set some parameters
#

PI = 2.0 * math.asin(1.0)
g = 386.4
ft = 12.0
Load1 = 1185.0
Load2 = 1185.0
Load3 = 970.0
record = 'IELC180'  # ElCentro Motion
zeta = 0.02         # 2% damping
modeI = 1           # first mode damping pinned to (mode 1)
modeJ = 3           # second mode damping pinned to (mode 3)

# set floor masses
m1 = Load1 / (4 * g)  # 4 nodes per floor
m2 = Load2 / (4 * g)
m3 = Load3 / (4 * g)

# set floor distributed loads
w1 = Load1 / (90 * ft)  # frame 90 ft long
w2 = Load2 / (90 * ft)
w3 = Load3 / (90 * ft)


# ------------------------------
# Start of model generation
# ------------------------------

# Remove existing model
ops.wipe()

# Create ModelBuilder (with two-dimensions and 3 DOF/node)
ops.model('BasicBuilder', '-ndm', 2, '-ndf', 3)

# Create nodes & add to Domain - command: node(nodeId, xCrd, yCrd, '-mass', massX, massY, massRz)
# NOTE: mass is optional
ops.node(1, 0.0, 0.0)
ops.node(2, 360.0, 0.0)
ops.node(3, 720.0, 0.0)
ops.node(4, 1080.0, 0.0)
ops.node(5, 0.0, 162.0, '-mass', m1, m1, 0.0)
ops.node(6, 360.0, 162.0, '-mass', m1, m1, 0.0)
ops.node(7, 720.0, 162.0, '-mass', m1, m1, 0.0)
ops.node(8, 1080.0, 162.0, '-mass', m1, m1, 0.0)
ops.node(9, 0.0, 324.0, '-mass', m2, m2, 0.0)
ops.node(10, 360.0, 324.0, '-mass', m2, m2, 0.0)
ops.node(11, 720.0, 324.0, '-mass', m2, m2, 0.0)
ops.node(12, 1080.0, 324.0, '-mass', m2, m2, 0.0)
ops.node(13, 0.0, 486.0, '-mass', m3, m3, 0.0)
ops.node(14, 360.0, 486.0, '-mass', m3, m3, 0.0)
ops.node(15, 720.0, 486.0, '-mass', m3, m3, 0.0)
ops.node(16, 1080.0, 486.0, '-mass', m3, m3, 0.0)

# Set the boundary conditions - command: fix(nodeID, xRestrnt, yRestrnt, rZRestrnt)
ops.fix(1, 1, 1, 1)
ops.fix(2, 1, 1, 1)
ops.fix(3, 1, 1, 1)
ops.fix(4, 1, 1, 1)

# Define geometric transformations for beam-column elements
ops.geomTransf('Linear', 1)  # beams
ops.geomTransf('PDelta', 2)  # columns

# Define elements
# Create elastic beam-column - command: element('elasticBeamColumn', eleID, node1, node2, A, E, Iz, geomTransfTag)

# Define the Columns
ops.element('elasticBeamColumn', 1, 1, 5, 75.6, 29000.0, 3400.0, 2)    # W14X257
ops.element('elasticBeamColumn', 2, 5, 9, 75.6, 29000.0, 3400.0, 2)    # W14X257
ops.element('elasticBeamColumn', 3, 9, 13, 75.6, 29000.0, 3400.0, 2)   # W14X257
ops.element('elasticBeamColumn', 4, 2, 6, 91.4, 29000.0, 4330.0, 2)    # W14X311
ops.element('elasticBeamColumn', 5, 6, 10, 91.4, 29000.0, 4330.0, 2)   # W14X311
ops.element('elasticBeamColumn', 6, 10, 14, 91.4, 29000.0, 4330.0, 2)  # W14X311
ops.element('elasticBeamColumn', 7, 3, 7, 91.4, 29000.0, 4330.0, 2)    # W14X311
ops.element('elasticBeamColumn', 8, 7, 11, 91.4, 29000.0, 4330.0, 2)   # W14X311
ops.element('elasticBeamColumn', 9, 11, 15, 91.4, 29000.0, 4330.0, 2)  # W14X311
ops.element('elasticBeamColumn', 10, 4, 8, 75.6, 29000.0, 3400.0, 2)   # W14X257
ops.element('elasticBeamColumn', 11, 8, 12, 75.6, 29000.0, 3400.0, 2)  # W14X257
ops.element('elasticBeamColumn', 12, 12, 16, 75.6, 29000.0, 3400.0, 2) # W14X257

# Define the Beams
ops.element('elasticBeamColumn', 13, 5, 6, 34.7, 29000.0, 5900.0, 1)   # W33X118
ops.element('elasticBeamColumn', 14, 6, 7, 34.7, 29000.0, 5900.0, 1)   # W33X118
ops.element('elasticBeamColumn', 15, 7, 8, 34.7, 29000.0, 5900.0, 1)   # W33X118
ops.element('elasticBeamColumn', 16, 9, 10, 34.2, 29000.0, 4930.0, 1)  # W30X116
ops.element('elasticBeamColumn', 17, 10, 11, 34.2, 29000.0, 4930.0, 1) # W30X116
ops.element('elasticBeamColumn', 18, 11, 12, 34.2, 29000.0, 4930.0, 1) # W30X116
ops.element('elasticBeamColumn', 19, 13, 14, 20.1, 29000.0, 1830.0, 1) # W24X68
ops.element('elasticBeamColumn', 20, 14, 15, 20.1, 29000.0, 1830.0, 1) # W24X68
ops.element('elasticBeamColumn', 21, 15, 16, 20.1, 29000.0, 1830.0, 1) # W24X68

# Define loads for Gravity Analysis
# ---------------------------------

# Create a Linear TimeSeries (load factor varies linearly with time): command timeSeries('Linear', tag)
ops.timeSeries('Linear', 1)

# Create a Plain load pattern with a linear TimeSeries: command pattern('Plain', tag, timeSeriesTag)
ops.pattern('Plain', 1, 1)
ops.eleLoad('-ele', 13, 14, 15, '-type', '-beamUniform', -w1)
ops.eleLoad('-ele', 16, 17, 18, '-type', '-beamUniform', -w2)
ops.eleLoad('-ele', 19, 20, 21, '-type', '-beamUniform', -w3)

# ---------------------------------
# Create Analysis for Gravity Loads
# ---------------------------------

# Create the system of equation, a SPD using a band storage scheme
ops.system('BandSPD')

# Create the DOF numberer, the reverse Cuthill-McKee algorithm
ops.numberer('RCM')

# Create the constraint handler, a Plain handler is used as homo constraints
ops.constraints('Plain')

# Create the integration scheme, the LoadControl scheme using steps of 1.0
ops.integrator('LoadControl', 1.0)

# Create the convergence test and the solution algorithm, a Newton algorithm
ops.test('NormDispIncr', 1.0e-10, 6)
ops.algorithm('Newton')

# create the analysis object
ops.analysis('Static')

# ---------------------------------
# Perform Gravity Analysis
# ---------------------------------

ops.analyze(1)

# ----------------------------------------------------
# set gravity loads constant and time in domain to 0.0
# ----------------------------------------------------

ops.loadConst('-time', 0.0)

# ----------------------------------
# Determine Rayleigh Damping Factors
# ----------------------------------

eigenValues = ops.eigen(5)
wI = math.sqrt(eigenValues[modeI - 1])
wJ = math.sqrt(eigenValues[modeJ - 1])
alphaM = zeta * 2.0 * wI * wJ / (wI + wJ)
betaK = zeta * 2.0 / (wI + wJ)
ops.rayleigh(alphaM, 0.0, 0.0, betaK)

print('\nEigenvalues:')
for i, eigenValue in enumerate(eigenValues):
    print(f'T{i+1} = {2*PI/math.sqrt(eigenValue)}')

#
# Define Dynamic Loads - Uniform Excitation
#

def ReadRecord(inFilename, outFilename):
    """Read a PEER strong motion record (old SMD or new NGA format), write the
    acceleration values to outFilename, and return (dt, nPts)."""
    dt = 0.0
    nPts = 0
    with open(inFilename, 'r') as inFile, open(outFilename, 'w') as outFile:
        inHeader = True
        for line in inFile:
            words = line.replace(',', ' ').split()
            if len(words) == 0:
                continue
            if not inHeader:
                outFile.write(line)
            elif words[0] == 'NPTS=':
                # old SMD format: NPTS=  4000, DT= .01000 SEC
                nPts = int(words[1])
                dt = float(words[words.index('DT=') + 1])
                inHeader = False
            elif words[-1] == 'DT' and len(words) >= 4:
                # new NGA format: 3930 0.00500 NPTS, DT
                nPts = int(words[0])
                dt = float(words[1])
                inHeader = False
    return dt, nPts


dT, nPts = ReadRecord(record + '.AT2', record + '.acc')

# the record is in units of g, so it is scaled by g to get in/sec^2
ops.timeSeries('Path', 2, '-filePath', record + '.acc', '-dt', dT, '-factor', g)
ops.pattern('UniformExcitation', 2, 1, '-accel', 2)

#
# create a recorder
#

ops.recorder('Node', '-time', '-file', 'disp.out', '-node', 13, 9, 5, 1, '-dof', 1, 2, 3, 'disp')
ops.recorder('Node', '-time', '-file', 'relAccel.out', '-node', 13, 9, 5, 1, '-dof', 1, 'accel')
ops.recorder('Node', '-time', '-file', 'totalAccel.out', '-timeSeries', 2, '-node', 13, 9, 5, 1, '-dof', 1, 'accel')

#
# Create the transient Analysis
#

# wipeAnalysis first as moving from static to transient
ops.wipeAnalysis()

ops.system('BandGeneral')
ops.constraints('Plain')
ops.test('NormUnbalance', 1.0e-6, 10)
ops.algorithm('Newton')
ops.numberer('RCM')
ops.integrator('Newmark', 0.5, 0.25)  # Newmark average acceleration
ops.analysis('Transient')

#
# Perform the Transient Analysis
#

# analyze one step at a time, keeping track of the peak roof displacement
maxDisp = 0.0
tMax = 0.0
for i in range(nPts):
    if ops.analyze(1, dT) != 0:
        print(f'analysis failed at time {ops.getTime()}')
        break
    u = abs(ops.nodeDisp(13, 1))
    if u > maxDisp:
        maxDisp = u
        tMax = ops.getTime()

print(f'\nPeak roof displacement: {maxDisp} at time {tMax}')

ops.wipe()
