
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
import os
MODEL_NAME = 'Cantilever_Beam'
PART_NAME = 'Beam'
JOB_NAME = 'Cantilever_Beam_Job'
L = 1000.0
B = 50.0
H = 100.0
E = 210000.0
NU = 0.3
P = 1000.0
MESH_SIZE = 20.0
TOL = 0.0001
if MODEL_NAME in mdb.models.keys():
    del mdb.models[MODEL_NAME]
model = mdb.Model(name=MODEL_NAME)
sketch = model.ConstrainedSketch(name='Beam_Section', sheetSize=2000.0)
sketch.rectangle(point1=(-B / 2.0, -H / 2.0), point2=(B / 2.0, H / 2.0))
part = model.Part(name=PART_NAME, dimensionality=THREE_D, type=DEFORMABLE_BODY)
part.BaseSolidExtrude(sketch=sketch, depth=L)
del model.sketches['Beam_Section']
material = model.Material(name='Steel')
material.Elastic(table=((E, NU),))
model.HomogeneousSolidSection(name='Steel_Section', material='Steel', thickness=None)
region_all = regionToolset.Region(cells=part.cells[:])
part.SectionAssignment(region=region_all, sectionName='Steel_Section')
assembly = model.rootAssembly
assembly.DatumCsysByDefault(CARTESIAN)
instance = assembly.Instance(name='Beam-1', part=part, dependent=ON)
model.StaticStep(name='Load_Step', previous='Initial', description='Linear static bending of cantilever beam', nlgeom=OFF, initialInc=0.1, maxInc=1.0, minInc=1e-06, maxNumInc=100)
fixed_faces = instance.faces.getByBoundingBox(xMin=-B / 2.0 - TOL, xMax=B / 2.0 + TOL, yMin=-H / 2.0 - TOL, yMax=H / 2.0 + TOL, zMin=-TOL, zMax=TOL)
if len(fixed_faces) != 1:
    raise RuntimeError('Fixed end face selection failed')
fixed_region = regionToolset.Region(faces=fixed_faces)
model.EncastreBC(name='Fixed_End', createStepName='Initial', region=fixed_region)
rp_feature = assembly.ReferencePoint(point=(0.0, 0.0, L))
rp = assembly.referencePoints[rp_feature.id]
rp_region = regionToolset.Region(referencePoints=(rp,))
free_faces = instance.faces.getByBoundingBox(xMin=-B / 2.0 - TOL, xMax=B / 2.0 + TOL, yMin=-H / 2.0 - TOL, yMax=H / 2.0 + TOL, zMin=L - TOL, zMax=L + TOL)
if len(free_faces) != 1:
    raise RuntimeError('Free end face selection failed')
free_region = regionToolset.Region(faces=free_faces)
model.Coupling(name='End_Load_Coupling', controlPoint=rp_region, surface=free_region, influenceRadius=WHOLE_SURFACE, couplingType=DISTRIBUTING, weightingMethod=UNIFORM, u1=ON, u2=ON, u3=ON, ur1=ON, ur2=ON, ur3=ON)
model.ConcentratedForce(name='Tip_Load', createStepName='Load_Step', region=rp_region, cf2=-P)
model.fieldOutputRequests['F-Output-1'].setValues(variables=('S', 'E', 'U', 'RF'))
model.HistoryOutputRequest(name='Tip_Displacement', createStepName='Load_Step', variables=('U2',), region=rp_region)
part.seedPart(size=MESH_SIZE, deviationFactor=0.1, minSizeFactor=0.1)
elem_type = mesh.ElemType(elemCode=C3D8R, elemLibrary=STANDARD, secondOrderAccuracy=OFF, hourglassControl=ENHANCED)
part.setElementType(regions=(part.cells[:],), elemTypes=(elem_type,))
part.setMeshControls(regions=part.cells[:], elemShape=HEX, technique=STRUCTURED)
part.generateMesh()
if len(part.elements) == 0:
    raise RuntimeError('Mesh generation failed')
if JOB_NAME in mdb.jobs.keys():
    del mdb.jobs[JOB_NAME]
job = mdb.Job(name=JOB_NAME, model=MODEL_NAME, description='3D cantilever beam static analysis', type=ANALYSIS, memory=90, memoryUnits=PERCENTAGE, numCpus=4, numDomains=4)
if len(session.viewports.keys()) > 0:
    vp = session.viewports[session.currentViewportName]
    vp.setValues(displayedObject=part)
    vp.view.fitView()
mdb.saveAs(pathName=os.path.join(os.getcwd(), MODEL_NAME + '.cae'))
_sw_record_write(job)
print('Model created: ' + MODEL_NAME)
print('Job created: ' + JOB_NAME)
print('Element count: ' + str(len(part.elements)))
print('Input file generated.')
print('No analysis submitted.')
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')

