"""
Point loaded 2-D cantilever steel beam.
"""

from sfepy.mechanics.matcoefs import youngpoisson_to_lame, stiffness_tensor_youngpoisson
from sfepy.fem.geometry_element import geometry_data
from sfepy import data_dir

# Fix the mesh file name if you run this file outside the SfePy directory.
filename_mesh = data_dir + '/abaqus_beam.inp'

output_dir = '.'    # set this to a valid directory you have write access to

young = 200000.0    # Young's modulus [MPa]
poisson = 0.3       # Poisson's ratio

gdata = geometry_data['2_4']
nc = len(gdata.coors)

def stress_strain(out, pb, state, extend=False):
    """
    Calculate and output strain and stress for given displacements.
    """
    from sfepy.base.base import Struct
    from sfepy.fem import Field, FieldVariable
    import numpy as nm

    ev = pb.evaluate
    strain = ev('de_cauchy_strain.2.Omega(u)', mode='el_avg')
    stress = ev('de_cauchy_stress.2.Omega(Steel.D, u)', mode='el_avg')

    # calc stress/strain at qp's
    qstrain = ev('dq_cauchy_strain.ivn.Omega(u)', mode='qp')
    qstress = ev('dq_cauchy_stress.ivn.Omega(Steel.D, u)', mode='qp')

    # stress/strain at nodes
    efield = Field('qstrain', nm.float64, (3,),
                    pb.domain.regions['Omega'])
    evar = FieldVariable('epsilon', 'parameter', efield, 3,
                         primary_var_name='(set-to-None)')
    evar.data_from_qp(qstrain, pb.integrals['ivn'])

    sfield = Field('qstress', nm.float64, (3,),
                    pb.domain.regions['Omega'])
    svar = FieldVariable('sigma', 'parameter', sfield, 3,
                         primary_var_name='(set-to-None)')
    svar.data_from_qp(qstress, pb.integrals['ivn'])

    out['cauchy_strain'] = Struct(name='output_data', mode='cell',
                                  data=strain, dofs=None)
    out['cauchy_stress'] = Struct(name='output_data', mode='cell',
                                  data=stress, dofs=None)
    out['qstrain'] = Struct(name='output_data', mode='vertex', 
                        data=evar.data[0], var_name='S', dofs=None)

    out['qstress'] = Struct(name='output_data', mode='vertex', 
                        data=svar.data[0], var_name='S', dofs=None)

    return out


options = {
    'output_dir' : output_dir,
    'post_process_hook' : 'stress_strain',
}

regions = {
    'Omega' : ('all', {}),
    'Left' : ('nodes in (x < 0.001)', {}),
    'Top' : ('node 600', {}),
}

materials = {
    'Steel' : ({
        'lam' : youngpoisson_to_lame(young, poisson, plane='stress')[0],
        'mu' : youngpoisson_to_lame(young, poisson, plane='stress')[1],
        'D' : stiffness_tensor_youngpoisson(2, young, poisson, plane='stress')
    },),
    'Load' : ({'.val' : [0.0, -0.1]},),
}

fields = {
    'displacement': ('real', 'vector', 'Omega', 1),
}

equations = {
   'balance_of_forces' :
   """dw_lin_elastic_iso.2.Omega(Steel.lam, Steel.mu, v, u )
      = dw_point_load.0.Top(Load.val, v)""",
}

variables = {
    'u' : ('unknown field', 'displacement', 0),
    'v' : ('test field', 'displacement', 'u'),
}

integrals = {
    'ivn' : ('v', 'custom', gdata.coors, [gdata.volume / nc] * nc),
}

ebcs = {
    'Wall' : ('Left', {'u.all' : 0.0}),
}

solvers = {
    'ls' : ('ls.scipy_direct', {}),
    'newton' : ('nls.newton', {
        'i_max' : 1,
        'eps_a' : 1e-6,
        'problem' : 'nonlinear'
    }),
}
