
from abaqus import mdb
from abaqusConstants import OFF
import os as _sw_os
_sw_before_jobs = {str(n): mdb.jobs[n] for n in mdb.jobs.keys()}
_sw_written_jobs = []
def _sw_record_write(_job, *args, **kwargs):
    _answer = _job.writeInput(*args, **kwargs)
    _name = str(getattr(_job, 'name', ''))
    if not _name or _name not in mdb.jobs.keys():
        _names = [str(n) for n in mdb.jobs.keys() if mdb.jobs[n] is _job]
        if len(_names) != 1:
            raise RuntimeError('Cannot identify the job which wrote the INP')
        _name = _names[0]
    _sw_written_jobs.append((_name, _sw_os.path.abspath(_name + '.inp')))
    return _answer

from abaqus import *
from abaqusConstants import *
import regionToolset
import mesh
modelName = 'CantileverBeamModel'
partName = 'CantileverBeam'
jobName = 'CantileverBeamJob'
L = 1000.0
W = 50.0
H = 100.0
E = 210000.0
nu = 0.3
tipLoad = -1000.0
meshSize = 25.0
if modelName in mdb.models.keys():
    del mdb.models[modelName]
model = mdb.Model(name=modelName)
sketch = model.ConstrainedSketch(name='BeamProfile', sheetSize=2000.0)
sketch.rectangle(point1=(0.0, 0.0), point2=(L, H))
part = model.Part(name=partName, dimensionality=THREE_D, type=DEFORMABLE_BODY)
part.BaseSolidExtrude(sketch=sketch, depth=W)
del model.sketches['BeamProfile']
material = model.Material(name='Steel')
material.Elastic(table=((E, nu),))
model.HomogeneousSolidSection(name='BeamSection', material='Steel', thickness=None)
allCells = part.cells[:]
part.SectionAssignment(region=regionToolset.Region(cells=allCells), sectionName='BeamSection', offset=0.0, offsetType=MIDDLE_SURFACE, offsetField='', thicknessAssignment=FROM_SECTION)
assembly = model.rootAssembly
assembly.DatumCsysByDefault(CARTESIAN)
instance = assembly.Instance(name='CantileverBeam-1', part=part, dependent=ON)
model.StaticStep(name='LoadStep', previous='Initial', description='Static analysis of a cantilever beam', nlgeom=OFF)
model.fieldOutputRequests['F-Output-1'].setValues(variables=('S', 'E', 'U', 'RF'))
fixedFace = instance.faces.findAt(((0.0, H / 2.0, W / 2.0),))
fixedRegion = regionToolset.Region(faces=fixedFace)
model.EncastreBC(name='FixedEnd', createStepName='Initial', region=fixedRegion)
tipFace = instance.faces.findAt(((L, H / 2.0, W / 2.0),))
assembly.Surface(side1Faces=tipFace, name='TipSurface')
referencePoint = assembly.ReferencePoint(point=(L, H / 2.0, W / 2.0))
rpId = referencePoint.id
rpRegion = regionToolset.Region(referencePoints=(assembly.referencePoints[rpId],))
model.Coupling(name='TipCoupling', controlPoint=rpRegion, surface=assembly.surfaces['TipSurface'], influenceRadius=WHOLE_SURFACE, couplingType=KINEMATIC, localCsys=None, u1=ON, u2=ON, u3=ON, ur1=ON, ur2=ON, ur3=ON)
model.ConcentratedForce(name='TipLoad', createStepName='LoadStep', region=rpRegion, cf2=tipLoad, distributionType=UNIFORM, field='', localCsys=None)
part.seedPart(size=meshSize, deviationFactor=0.1, minSizeFactor=0.1)
part.setMeshControls(regions=part.cells[:], technique=STRUCTURED, elemShape=HEX)
elemType1 = mesh.ElemType(elemCode=C3D8R, elemLibrary=STANDARD, kinematicSplit=AVERAGE_STRAIN, secondOrderAccuracy=OFF, hourglassControl=DEFAULT, distortionControl=DEFAULT)
part.setElementType(regions=(part.cells[:],), elemTypes=(elemType1,))
part.generateMesh()
assembly.regenerate()
job = mdb.Job(name=jobName, model=modelName, description='3D static cantilever beam analysis', type=ANALYSIS, atTime=None, waitMinutes=0, waitHours=0, queue=None, memory=90, memoryUnits=PERCENTAGE, getMemoryFromAnalysis=True, explicitPrecision=SINGLE, nodalOutputPrecision=SINGLE, echoPrint=OFF, modelPrint=OFF, contactPrint=OFF, historyPrint=OFF, userSubroutine='', scratch='', resultsFormat=ODB, multiprocessingMode=DEFAULT, numCpus=4, numDomains=4, numGPUs=0)
_sw_record_write(job)
print('SOUTHWEITION_JOB_PREPARED')

if not _sw_written_jobs:
    _sw_candidates = [n for n in mdb.jobs.keys() if n not in _sw_before_jobs or mdb.jobs[n] is not _sw_before_jobs[n]]
    if len(_sw_candidates) != 1:
        raise RuntimeError('Cannot identify this script job: call writeInput() on exactly the intended job')
    _sw_record_write(mdb.jobs[_sw_candidates[0]], consistencyChecking=OFF)
_sw_name, _sw_inp = _sw_written_jobs[-1]
if not _sw_os.path.isfile(_sw_inp):
    raise RuntimeError('This script did not produce its INP: ' + _sw_inp)
print('SOUTHWEITION_CWD ' + _sw_os.path.dirname(_sw_inp))
print('SOUTHWEITION_JOB ' + _sw_name)
print('SOUTHWEITION_MODEL ' + str(getattr(mdb.jobs[_sw_name], 'model', '')))
print('SOUTHWEITION_INP ' + _sw_inp)
print('SOUTHWEITION_JOB_PREPARED')

