def numpy_to_dolfin_old(nodes, elements):
    """ Deprecated version of numpy_to_dolfin. To be removed? """
    tmpfile = "tmp.xml"

    if rank == 0:
        with open(tmpfile, "w") as f:
            f.write("""
<?xml version="1.0" encoding="UTF-8"?>
<dolfin xmlns:dolfin="http://www.fenics.org/dolfin/">
    <mesh celltype="triangle" dim="2">
        <vertices size="%d">""" % len(nodes))

            for i, pt in enumerate(nodes):
                f.write('<vertex index="%d" x="%g" y="%g"/>' % (
                    i, pt[0], pt[1]))

            f.write("""
        </vertices>
        <cells size="%d">""" % len(elements))

            for i, element in enumerate(elements):
                f.write('<triangle index="%d" v0="%d" v1="%d" v2="%d"/>' % (
                    i, element[0], element[1], element[2]))

            f.write("""
            </cells>
          </mesh>
        </dolfin>""")

    comm.Barrier()

    mesh = df.Mesh(tmpfile)

    comm.Barrier()

    if rank == 0 and os.path.exists(tmpfile):
        os.remove(tmpfile)
    return mesh
Beispiel #2
0
def make_1d_mesh_from_points(Xs):
    N = len(Xs)

    mesh = dolfin.Mesh()
    ed = dolfin.MeshEditor()
    ed.open(mesh, 'interval', 1, 1)

    ed.init_vertices(N)
    av = ed.add_vertex
    for i, x in enumerate(Xs):
        av(i, [x])

    ed.init_cells(N-1)
    ac = ed.add_cell
    for i in range(N-1):
        ac(i, [i, i+1])

    ed.close()

    mesh.init()
    mesh.order()

    return mesh
Beispiel #3
0
 def __init__(self, title, logger, subdomaininfo, facetinfo,
              refinement_info):
     self.mesh_dir = "mesh/"
     self.meshname = str(title) + '_mesh'
     self.mesh_file = self.mesh_dir + self.meshname + '.h5'
     self.mesh = d.Mesh()
     self.logger = logger
     self.logger.info("Loading mesh")
     hdf = d.HDF5File(self.mesh.mpi_comm(), self.mesh_file, "r")
     hdf.read(self.mesh, "/mesh", False)
     self.cells = d.MeshFunction('size_t', self.mesh,
                                 self.mesh.geometric_dimension())
     self.facets = d.MeshFunction('size_t', self.mesh,
                                  self.mesh.geometric_dimension() - 1)
     hdf.read(self.cells, "/subdomains")
     hdf.read(self.facets, "/facets")
     self.dimension = self.mesh.topology().dim()
     self.subdomaininfo = subdomaininfo
     self.facetinfo = facetinfo
     self.refinement_info = refinement_info
     self.logger.info("Loaded mesh")
     if self.refinement_info is not None:
         self.refine()
Beispiel #4
0
def build_mesh(vertices, cells, cell_type):
    '''Mesh defined by its vertices, cells'''
    cell_tdim = cell_type.topological_dimension()
    gdim = cell_type.geometric_dimension()
    # Consistency
    assert gdim == vertices.shape[1]
    assert cell_type.num_vertices() == cells.shape[1]

    mesh = df.Mesh()
    editor = df.MeshEditor()
    editor.open(mesh, cell_type.cellname(), cell_tdim, gdim)
    editor.init_cells(len(cells))
    editor.init_vertices(len(vertices))

    for i, v in enumerate(vertices):
        editor.add_vertex(i, v)

    for i, c in enumerate(cells):
        editor.add_cell(i, c)

    editor.close()

    return mesh
Beispiel #5
0
    def __init__(self, h5_file):
        """__init__.

        :param h5_file:
        """
        self.mesh = df.Mesh()
        hdf = df.HDF5File(self.mesh.mpi_comm(), h5_file, "r")
        hdf.read(self.mesh, "/mesh", False)
        dim = self.mesh.topology().dim()

        self.subdomains = df.MeshFunction("size_t", self.mesh, dim)
        hdf.read(self.subdomains, "/subdomains")

        self.boundaries = df.MeshFunction("size_t", self.mesh, dim - 1)
        hdf.read(self.boundaries, "/boundaries")
        #Used in the program
        self.nv = df.FacetNormal(self.mesh)  #normal vector
        self.ds = df.Measure("ds",
                             domain=self.mesh,
                             subdomain_data=self.boundaries)
        self.dS = df.Measure("dS",
                             domain=self.mesh,
                             subdomain_data=self.boundaries)
Beispiel #6
0
def save_serialized_mesh():
    print 'Importing dolfin, takes a bit of time...'
    import dolfin
    print 'Done importing dolfin.'

    resolution = 96
    mesh_full_filename = 'data/mesh_res_%d_full.xml' % resolution
    mesh_3d = dolfin.Mesh(mesh_full_filename)

    # NOTE: This is temporary. These are parameters of the mesh (when it was
    #       created in full_dendrite_mesh.py) and we should package them in a
    #       different way.
    SCALE_FACTOR = 50.0
    STARTING_X = SCALE_FACTOR * 0.0
    STARTING_Y = SCALE_FACTOR * 0.0
    STARTING_Z = SCALE_FACTOR * 1.0
    STARTING_K = SCALE_FACTOR * 0.01

    initial_point = np.array((STARTING_X, STARTING_Y, STARTING_Z))
    mesh_wrapper = Mesh.from_mesh(mesh_3d, initial_point, STARTING_K)

    serialized_mesh_filename = 'data/serialized_mesh_res_%d.npz' % resolution
    mesh_wrapper.serialize_mesh(serialized_mesh_filename)
Beispiel #7
0
def load_with_meshio(meshFile, dimension):
    # input mesh file name and path witout file extension
    # dimension = max spatial dimension of the mesh
    # (typically 2 or 3 for 2D or 3D)

    # read in the mesh
    mesh = dl.Mesh()
    with dl.XDMFFile(meshFile + ".xdmf") as infile:
        infile.read(mesh)

    # read in the facet boundaries
    mvc = dl.MeshValueCollection("size_t", mesh, dimension - 1)
    with dl.XDMFFile(meshFile + "_facet_region.xdmf") as infile:
        infile.read(mvc, "name_to_read")
    facet_regions = dl.cpp.mesh.MeshFunctionSizet(mesh, mvc)

    # read in the defined physical regions
    mvc2 = dl.MeshValueCollection("size_t", mesh, dimension)
    with dl.XDMFFile(meshFile + ".xdmf") as infile:
        infile.read(mvc2, "name_to_read")
    physical_regions = dl.cpp.mesh.MeshFunctionSizet(mesh, mvc2)

    return mesh, facet_regions, physical_regions
Beispiel #8
0
    def generate_mesh(self):
        import meshio

        geo = self.user_define_pygmsh_geo()
        r = self.pygmsh_generate_mesh(geo)

        d = PygmshMakeRegions().process(cells=r['cells'],
                                        cell_data=r['cell_data'],
                                        field_data=r['field_data'],
                                        dim=r['dim'])

        with tempfile.TemporaryDirectory() as tmpdir:
            mesh_file = osp.join(str(tmpdir), 'mesh.xdmf')
            meshio.write_points_cells(mesh_file,
                                      r['points'],
                                      r['cells'],
                                      cell_data=r['cell_data'])

            with dolfin.XDMFFile(mesh_file) as file:
                mesh = dolfin.Mesh()
                file.read(mesh)
                cf = dolfin.MeshFunction('size_t', mesh, r['dim'], 0)
                file.read(cf)

        self.mesh = mesh
        self.cf = cf

        # initialize facets-cells mapping
        D = self.dim
        mesh.init(D - 1, D)

        # TODO: turn physical objects with dim-1 into facetfunction

        self.cell_regions = d['tag_to_cell_values']
        self.cell_regions['domain'] = domain_cvs = set()
        for cvs in d['tag_to_cell_values'].values():
            domain_cvs.update(cvs)
Beispiel #9
0
    def __init__(self, mesh_file, facet_ids_file=None, cell_ids_file=None):

        #: A :class:`dolfin.Mesh` containing the mesh.
        self.mesh = dolfin.Mesh(mesh_file)

        # Read facet markers
        if facet_ids_file is None:
            facet_ids_file = (os.path.splitext(mesh_file)[0] +
                              "_facet_region.xml")

        # Read cell markers
        if cell_ids_file is None:
            cell_ids_file = (os.path.splitext(mesh_file)[0] +
                            "_physical_region.xml")

        #: A :class:`dolfin.FacetFunction` containing the surface markers.
        self.facet_ids = dolfin.MeshFunction("size_t", self.mesh, facet_ids_file)
        #: A :class:`dolfin.Measure` for the facet parts.
        self._ds = dolfin.Measure('ds')(subdomain_data=self.facet_ids)

        #: A :class:`dolfin.CellFunction` containing the area markers.
        self.cell_ids = dolfin.MeshFunction("size_t", self.mesh, cell_ids_file)
        #: A :class:`dolfin.Measure` for the cell subdomains.
        self._dx = dolfin.Measure("dx")(subdomain_data=self.cell_ids)
Beispiel #10
0
def load_embedding(folder):
    '''Load embedding'''
    h5_file = os.path.join(folder, 'mesh.h5')
    embedding_mesh = df.Mesh()
    h5 = df.HDF5File(embedding_mesh.mpi_comm(), h5_file, 'r')
    h5.read(embedding_mesh, 'embedding_mesh', False)

    edge_coloring = df.MeshFunction('size_t', embedding_mesh, 1, 0)
    h5.read(edge_coloring, 'edge_coloring')

    vertex_map = np.loadtxt(os.path.join(folder, 'vertex_map.txt'))

    edge_encoding = EdgeMap(
        pickle.load(open(os.path.join(folder, 'edge_encoding_0.pkl'), 'rb')),
        pickle.load(open(os.path.join(folder, 'edge_encoding_1.pkl'), 'rb')))

    nc_edge_encoding = EdgeMap(
        pickle.load(open(os.path.join(folder, 'nc_edge_encoding_0.pkl'),
                         'rb')),
        pickle.load(open(os.path.join(folder, 'nc_edge_encoding_1.pkl'),
                         'rb')))

    return LineMeshEmbedding(embedding_mesh, vertex_map, edge_coloring,
                             edge_encoding, nc_edge_encoding)
Beispiel #11
0
def __load_mesh_hdf5(mesh_file):
    """
    Load dolfin mesh from an HDF5 file.

    Parameters
    ----------

    mesh_file : str
        Name of the file containing the mesh information


    Returns
    -------

    mesh : dolfin.cpp.mesh.Mesh
        This function returns a dolfin mesh object.


    """

    # Check dolfin for HDF5 support
    if not dlf.has_hdf5():
        msg = 'The current installation of dolfin does not support HDF5 files.'
        raise SoftwareNotAvailable(msg)

    # Check file extension
    if mesh_file[-3:] == '.h5':
        f = dlf.HDF5File(MPI_COMM_WORLD, mesh_file, 'r')
        mesh = dlf.Mesh()
        f.read(mesh, 'mesh', False)
        f.close()
    else:
        msg = 'The file extension provided must be \'.h5\'.'
        raise ValueError(msg)

    return mesh
Beispiel #12
0
def main():
    parser = argparse.ArgumentParser(description="Trace particles")
    parser.add_argument("mesh_file", type=str,
                        help="Path to mesh file")
    parser.add_argument("u_file", type=str,
                        help="Path to velocity field file")
    parser.add_argument("out_file", type=str,
                        help="Path to .xdmf file to save to")
    args = parser.parse_args()

    mesh = df.Mesh()
    with df.HDF5File(mesh.mpi_comm(), args.mesh_file, "r") as h5f_mesh:
        h5f_mesh.read(mesh, "/mesh", False)

    V = df.VectorFunctionSpace(mesh, "CG", 1)
    u = df.Function(V)

    with df.HDF5File(mesh.mpi_comm(), args.u_file, "r") as h5f_u:
        h5f_u.read(u, "/velocity")

    xdmff = df.XDMFFile(mesh.mpi_comm(), args.out_file)
    xdmff.parameters["rewrite_function_mesh"] = False
    xdmff.parameters["flush_output"] = True
    xdmff.write(u, float(0.))
Beispiel #13
0
def write_xdmf_to_h5(xdmfdir, hdf5file):
    import dolfin as df
    # Read .xdmf mesh into a FEniCS Mesh
    mesh = df.Mesh()
    with df.XDMFFile("%s/mesh.xdmf" % xdmfdir) as infile:
        infile.read(mesh)
        
    # Read cell data to a MeshFunction (of dim n)
    n = mesh.topology().dim()
    subdomains = df.MeshFunction("size_t", mesh, n)
    with df.XDMFFile("%s/subdomains.xdmf" % xdmfdir) as infile:
        infile.read(subdomains, "subdomains")
        
    # Read facet data to a MeshFunction (of dim n-1)
    boundaries = df.MeshFunction("size_t", mesh, n-1, 0)
    with df.XDMFFile("%s/boundaries.xdmf" % xdmfdir) as infile:
        infile.read(boundaries, "boundaries")

    # Write all files into a single h5 file.
    hdf = df.HDF5File(mesh.mpi_comm(), hdf5file, "w")
    hdf.write(mesh, "/mesh")
    hdf.write(subdomains, "/subdomains")
    hdf.write(boundaries, "/boundaries") 
    hdf.close()
Beispiel #14
0
def update_geometry(geometry, u=None, regen_fibers=True, *args):

    new_mesh = df.Mesh(geometry.mesh)

    if u is not None:
        U = move(new_mesh, u, -1.0, *args)
    else:
        U = u

    new_geometry = copy_geometry(new_mesh, geometry)

    fields = ["fiber", "sheet", "sheet_normal"]
    local_basis = ["circumferential", "radial", "longitudinal"]

    for attr in fields + local_basis:
        if hasattr(geometry, attr) and getattr(geometry, attr) is not None:

            regen = regen_fibers if attr == "fiber" else False
            f0 = getattr(geometry, attr).copy()

            f = update_vector_field(f0, new_mesh, U, regen_fibers=regen)
            setattr(new_geometry, attr, f)

    return new_geometry
Beispiel #15
0
def create_3d_mesh(mesh, h=1):
    assert mesh.topology().dim() == 2
    for cell in df.cells(mesh):
        print cell
        print cell.entities(0)
        print cell.get_vertex_coordinates()

    nv = mesh.num_vertices()
    nc = mesh.num_cells()

    mesh3 = df.Mesh()
    editor = df.MeshEditor()
    editor.open(mesh3, 3, 3)
    editor.init_vertices(2 * nv)
    editor.init_cells(3 * nc)

    for v in df.vertices(mesh):
        i = v.global_index()
        p = v.point()
        editor.add_vertex(i, p.x(), p.y(), 0)
        editor.add_vertex(i + nv, p.x(), p.y(), h)

    gid = 0
    for c in df.cells(mesh):
        #gid = c.global_index()
        i, j, k = c.entities(0)
        print i, j, k
        editor.add_cell(gid, i, j, k, i + nv)
        gid = gid + 1
        editor.add_cell(gid, j, j + nv, k, i + nv)
        gid = gid + 1
        editor.add_cell(gid, k, k + nv, j + nv, i + nv)
        gid = gid + 1

    editor.close()
    return mesh3
Beispiel #16
0
def load_geometry_from_h5(
        h5name,
        h5group="",
        fendo=None,
        fepi=None,
        include_sheets=True,
        comm=mpi_comm_world(),
):
    """Load geometry and other mesh data from
    a h5file to an object.
    If the file contains muliple fiber fields
    you can spefify the angles, and if the file
    contais sheets and cross-sheets this can also
    be included

    :param str h5name: Name of the h5file
    :param str h5group: The group within the file
    :param int fendo: Helix fiber angle (endocardium) (if available)
    :param int fepi: Helix fiber angle (epicardium) (if available)
    :param bool include_sheets: Include sheets and cross-sheets
    :returns: An object with geometry data
    :rtype: object

    """

    logger.info("\nLoad mesh from h5")
    # Set default groups
    ggroup = "{}/geometry".format(h5group)
    mgroup = "{}/mesh".format(ggroup)
    lgroup = "{}/local basis functions".format(h5group)
    fgroup = "{}/microstructure/".format(h5group)

    if not os.path.isfile(h5name):
        raise IOError("File {} does not exist".format(h5name))

    # Check that the given file contains
    # the geometry in the given h5group
    if not io_utils.check_h5group(h5name, mgroup, delete=False, comm=comm):
        msg = ("Warning!\nGroup: '{}' does not exist in file:"
               "\n{}").format(mgroup, h5name)

        with h5py.File(h5name) as h:
            keys = h.keys()
        msg += "\nPossible values for the h5group are {}".format(keys)
        raise IOError(msg)

    # Create a dummy object for easy parsing
    class Geometry(object):
        pass

    geo = Geometry()

    with dolfin.HDF5File(comm, h5name, "r") as h5file:

        # Load mesh
        mesh = dolfin.Mesh(comm)
        io_utils.read_h5file(h5file, mesh, mgroup, True)
        geo.mesh = mesh

        # Get mesh functions
        for dim, attr in zip(range(4), ["vfun", "efun", "ffun", "cfun"]):

            dgroup = "{}/mesh/meshfunction_{}".format(ggroup, dim)
            mf = dolfin.MeshFunction("size_t", mesh, dim, mesh.domains())

            if h5file.has_dataset(dgroup):
                io_utils.read_h5file(h5file, mf, dgroup)
            setattr(geo, attr, mf)

        load_local_basis(h5file, lgroup, mesh, geo)
        load_microstructure(h5file, fgroup, mesh, geo, include_sheets)

        # Load the boundary markers
        markers = load_markers(h5file, mesh, ggroup, dgroup)
        geo.markers = markers

        origmeshgroup = "{}/original_geometry".format(h5group)
        if h5file.has_dataset(origmeshgroup):
            original_mesh = dolfin.Mesh(comm)
            io_utils.read_h5file(h5file, original_mesh, origmeshgroup, True)
            setattr(geo, "original_geometry", original_mesh)

    for attr in [
            "f0", "s0", "n0", "r0", "c0", "l0", "cfun", "vfun", "efun", "ffun"
    ]:
        if not hasattr(geo, attr):
            setattr(geo, attr, None)

    return geo
import os, shutil
import dolfin as df

# Info
# from finmag.util.helpers import set_logging_level
# set_logging_level("INFO")
# set_logging_level("DEBUG")

# Geometries
from finmag.util.mesh_templates import Nanodisk

# MESH ------------------------------------------------------------------------

mesh_file = 'mesh/nanocylinder.xml.gz'
if os.path.exists(mesh_file):
    mesh = df.Mesh(mesh_file)
else:
    mesh = Nanodisk(d=183,
                    h=21,
                    center=(0, 0, 0),
                    valign='bottom',
                    name='nano_cylinder').create_mesh(
                        maxh=2,
                        save_result=True,
                        filename='nanocylinder',
                        directory='mesh',
                    )

# Simulation and energies -----------------------------------------------------

# Bulk
Beispiel #18
0
def _inputsort(obj):
    import dolfin

    u = None
    mesh = None
    if not utils.isSequence(obj):
        obj = [obj]

    for ob in obj:
        inputtype = str(type(ob))

        # printc('inputtype is', inputtype, c=2)

        if "vedo" in inputtype:  # skip vtk objects, will be added later
            continue

        if "dolfin" in inputtype or "ufl" in inputtype:
            if "MeshFunction" in inputtype:
                mesh = ob.mesh()

                if ob.dim() > 0:
                    printc('MeshFunction of dim>0 not supported.', c=1)
                    printc('Try e.g.:  MeshFunction("size_t", mesh, 0)',
                           c=1,
                           italic=1)
                    printc('instead of MeshFunction("size_t", mesh, 1)',
                           c=1,
                           strike=1)
                else:
                    #printc(ob.dim(), mesh.num_cells(), len(mesh.coordinates()), len(ob.array()))
                    V = dolfin.FunctionSpace(mesh, "CG", 1)
                    u = dolfin.Function(V)
                    v2d = dolfin.vertex_to_dof_map(V)
                    u.vector()[v2d] = ob.array()
            elif "Function" in inputtype or "Expression" in inputtype:
                u = ob
            elif "ufl.mathfunctions" in inputtype:  # not working
                u = ob
            elif "Mesh" in inputtype:
                mesh = ob
            elif "algebra" in inputtype:
                mesh = ob.ufl_domain()
                #print('algebra', ob.ufl_domain())

        if "str" in inputtype:
            mesh = dolfin.Mesh(ob)

    if u and not mesh and hasattr(u, "function_space"):
        V = u.function_space()
        if V:
            mesh = V.mesh()
    if u and not mesh and hasattr(u, "mesh"):
        mesh = u.mesh()

    #printc('------------------------------------')
    #printc('mesh.topology dim=', mesh.topology().dim())
    #printc('mesh.geometry dim=', mesh.geometry().dim())
    #if u: printc('u.value_rank()', u.value_rank())
    #if u and u.value_rank(): printc('u.value_dimension()', u.value_dimension(0)) # axis=0
    ##if u: printc('u.value_shape()', u.value_shape())
    return (mesh, u)
Beispiel #19
0
#-----------------read--mesh-------------
filename = 'test_2d.vtk'
mesh = meshio.read(filename, file_format="vtk")
points = mesh.points
cells = mesh.cells
meshio.write_points_cells(
    "test_2d.xml",
    points,
    cells,
)

import os

os.system('gmsh -2 test_2d.vtk -format msh2')
os.system('dolfin-convert test_2d.msh mesh_2d.xml')
mesh = df.Mesh("mesh_2d.xml")

import matplotlib.pyplot as plt

plt.figure(1)

df.plot(mesh)
# plt.show()
'''
3. Define traction bc subdomains
'''


#-----------define-heating-boundary-------
class HeatBoundaryAll(df.SubDomain):
    def inside(self, x, on_boundary):
def mesh_import_fun(mesh_naming):
    #import mesh
    return do.Mesh(mesh_naming)
Beispiel #21
0
    r_int,
    r_int,
))

# Create the mesh
diag = np.sqrt(L**2 + (3 * lex)**2)
resolut = diag / 3.
mesh = mshr.generate_mesh(ntube, resolut)

# Output Mesh
outp = file('mesh_info.dat', 'w')
outp.write(finmag.util.meshes.mesh_info(mesh))

# Save mesh to file
file = df.File("nanotube.xml")
file << mesh

# #############################################
# ###### SIMULATION

# Import mesh from the 'xml' file produced by the mesh generator script
mesh = df.Mesh('nanotube.xml')

# MATERIAL PARAMETERS
Ms = 7.96e5  # A m**-1 saturation magnetisation

# Inititate the simulation object with the lengths in nm
sim = Sim(mesh, Ms, unit_length=1e-9)

sim.add(Demag())
Beispiel #22
0
endo_apex_marker = geometry.markers['ENDOPT'][0]
endo_apex_idx = geometry.vfun.array().tolist().index(endo_apex_marker)
endo_apex = geometry.mesh.coordinates()[endo_apex_idx, :]
endo_apex_pos = endo_apex + u(endo_apex)

print(('\n\nGet longitudinal position of endocardial apex: {:.4f} mm'
       '').format(endo_apex_pos[0]))

epi_apex_marker = geometry.markers['EPIPT'][0]
epi_apex_idx = geometry.vfun.array().tolist().index(epi_apex_marker)
epi_apex = geometry.mesh.coordinates()[epi_apex_idx, :]
epi_apex_pos = epi_apex + u(epi_apex)

print(('\n\nGet longitudinal position of epicardial apex: {:.4f} mm'
       '').format(epi_apex_pos[0]))

V = dolfin.VectorFunctionSpace(geometry.mesh, "CG", 1)
u_int = dolfin.interpolate(u, V)
mesh = dolfin.Mesh(geometry.mesh)
dolfin.ALE.move(mesh, u_int)

fig = plt.figure()

dolfin.plot(geometry.mesh, color='b', edgecolor='k', title='Original geometry')
dolfin.plot(mesh, color='r', alpha=0.3, title='Inflating ellipsoid')
ax = plt.gca()
ax.view_init(elev=-83, azim=-179)

fig.savefig('problem2.png')
Beispiel #23
0
def xml_to_gmsh(mesh, results=None):
    """
    function iterates through mesh and results (field) data both provided in .xml format and writes a output .msh file with the field data read in as node data. The output file same name as the field file passed or if no filed file passed will have name of input mesh.

    :param mesh:  (.xml) Mesh that is to be written to a file
    :param field: (.xml) results data
    """

    # get output file
    if results == None:
        fname = mesh.rstrip("xml") + "msh"
        output = open(fname, 'w')
    else:
        fname = results.rstrip("xml") + "msh"
        output = open(fname, 'w')

    # read files into dolfin format
    mesh = dolf.Mesh(mesh)
    Q = dolf.FunctionSpace(mesh, 'CG', 1)
    if results != None:
        field = dolf.Function(Q)
        dolf.File(results) >> field

    cell_type = mesh.type().cell_type()

    nodes = mesh.coordinates()
    n_nodes = mesh.num_vertices()

    nodes = p.hstack(
        (nodes, p.zeros((n_nodes, 3 - p.shape(mesh.coordinates())[1]))))

    cells = mesh.cells()
    n_cells = mesh.num_cells()

    output.write("$MeshFormat\n" + "2.2 0 8\n" + "$EndMeshFormat\n" +
                 "$Nodes \n" + "{0:d}\n".format(n_nodes))

    for ii, node in enumerate(nodes):
        output.write("{0:d} {1} {2} {3}\n".format(ii + 1, node[0], node[1],
                                                  node[2]))

    output.write("$EndNodes\n")

    output.write("$Elements\n" + "{0:d}\n".format(n_cells))

    for ii, cell in enumerate(cells):

        if cell_type == 1:
            output.write("{0:d} 1 0 {1:d} {2:d}\n".format(
                ii + 1, int(cell[0] + 1), int(cell[1] + 1)))

        elif cell_type == 2:
            output.write("{0:d} 2 0 {1:d} {2:d} {3:d}\n".format(
                ii + 1, int(cell[0] + 1), int(cell[1] + 1), int(cell[2] + 1)))

        elif cell_type == 3:
            output.write("{0:d} 4 0 {1:d} {2:d} {3:d} {4:d}\n".format(
                ii + 1, int(cell[0] + 1), int(cell[1] + 1), int(cell[2] + 1),
                int(cell[3] + 1)))

        else:
            print "Unknown cell type"

    output.write("$EndElements\n")

    if results != None:
        output.write("$NodeData\n" + "1\n" + "\"NodalValues\"\n" +
                     "0\n" +  # zero real tags 
                     "3\n" +  # three integer tags
                     "0\n" +  # the time step
                     "1\n" +  #1-component (scalar) field
                     "{0:d}\n".format(len(nodes)))
        for ii, node in enumerate(nodes):
            output.write("{0:d} {1:g}\n".format(ii + 1,
                                                field(node[0], node[1])))

        output.write("$EndNodeData\n")

    output.close()

    # There is some numerical precision error that prevents files created by
    # this script from being converted back into xml by dolfin-convert opening the file in gmsh and resaving fixes this
    print 'calling gmsh...'
    s.call(['gmsh', fname, '-2'])
Beispiel #24
0
    def __init__(self,
                 tfml_file,
                 system_name='magma',
                 p_name='Pressure',
                 f_name='Porosity',
                 c_name='c',
                 n_name='n',
                 m_name='m',
                 d_name='d',
                 N_name='N',
                 h_squared_name='h_squared',
                 x0_name='x0'):
        """read the tfml_file and use libspud to populate the internal parameters

        c: wavespeed
        n: permeability exponent
        m: bulk viscosity exponent
        d: wave dimension
        N: number of collocation points
        x0: coordinate wave peak
        h_squared:  the size of the system in compaction lengths
                    squared (h/delta)**2
        """
        # initialize libspud and extract parameters
        libspud.clear_options()
        libspud.load_options(tfml_file)
        # get model dimension
        self.dim = libspud.get_option("/geometry/dimension")
        self.system_name = system_name
        # get solitary wave parameters
        path = "/system::" + system_name + "/coefficient::"
        scalar_value = "/type::Constant/rank::Scalar/value::WholeMesh/constant"
        vector_value = "/type::Constant/rank::Vector/value::WholeMesh/constant::dim"
        c = libspud.get_option(path + c_name + scalar_value)
        n = int(libspud.get_option(path + n_name + scalar_value))
        m = int(libspud.get_option(path + m_name + scalar_value))
        d = float(libspud.get_option(path + d_name + scalar_value))
        N = int(libspud.get_option(path + N_name + scalar_value))
        self.h = np.sqrt(
            libspud.get_option(path + h_squared_name + scalar_value))
        self.x0 = np.array(libspud.get_option(path + x0_name + vector_value))
        self.swave = SolitaryWave(c, n, m, d, N)
        self.rmax = self.swave.r[-1]
        self.tfml_file = tfml_file

        # check that d <= dim
        assert (d <= self.dim)

        # sort out appropriate index for calculating distance r
        if d == 1:
            self.index = [self.dim - 1]
        else:
            self.index = range(0, int(d))

        # check that the origin point is the correct dimension
        assert (len(self.x0) == self.dim)

        #read in information for constructing Function space and dolfin objects
        # get the mesh parameters and reconstruct the mesh
        meshtype = libspud.get_option("/geometry/mesh/source[0]/name")
        if meshtype == 'UnitSquare':
            number_cells = libspud.get_option(
                "/geometry/mesh[0]/source[0]/number_cells")
            diagonal = libspud.get_option(
                "/geometry/mesh[0]/source[0]/diagonal")
            mesh = df.UnitSquareMesh(number_cells[0], number_cells[1],
                                     diagonal)
        elif meshtype == 'Rectangle':
            x0 = libspud.get_option(
                "/geometry/mesh::Mesh/source::Rectangle/lower_left")
            x1 = libspud.get_option(
                "/geometry/mesh::Mesh/source::Rectangle/upper_right")
            number_cells = libspud.get_option(
                "/geometry/mesh::Mesh/source::Rectangle/number_cells")
            diagonal = libspud.get_option(
                "/geometry/mesh[0]/source[0]/diagonal")
            mesh = df.RectangleMesh(x0[0], x0[1], x1[0], x1[1],
                                    number_cells[0], number_cells[1], diagonal)
        elif meshtype == 'UnitCube':
            number_cells = libspud.get_option(
                "/geometry/mesh[0]/source[0]/number_cells")
            mesh = df.UnitCubeMesh(number_cells[0], number_cells[1],
                                   number_cells[2])
        elif meshtype == 'Box':
            x0 = libspud.get_option(
                "/geometry/mesh::Mesh/source::Box/lower_back_left")
            x1 = libspud.get_option(
                "/geometry/mesh::Mesh/source::Box/upper_front_right")
            number_cells = libspud.get_option(
                "/geometry/mesh::Mesh/source::Box/number_cells")
            mesh = df.BoxMesh(x0[0], x0[1], x0[2], x1[0], x1[1], x1[2],
                              number_cells[0], number_cells[1],
                              number_cells[2])
        elif meshtype == 'UnitInterval':
            number_cells = libspud.get_option(
                "/geometry/mesh::Mesh/source::UnitInterval/number_cells")
            mesh = df.UnitIntervalMesh(number_cells)
        elif meshtype == 'Interval':
            number_cells = libspud.get_option(
                "/geometry/mesh::Mesh/source::Interval/number_cells")
            left = libspud.get_option(
                "/geometry/mesh::Mesh/source::Interval/left")
            right = libspud.get_option(
                "/geometry/mesh::Mesh/source::Interval/right")
            mesh = df.IntervalMesh(number_cells, left, right)
        elif meshtype == 'File':
            mesh_filename = libspud.get_option(
                "/geometry/mesh::Mesh/source::File/file")
            print "tfml_file  = ", self.tfml_file, "mesh_filename=", mesh_filename
            mesh = df.Mesh(mesh_filename)
        else:
            df.error("Error: unknown mesh type " + meshtype)

        #set the functionspace for n-d solitary waves
        path = "/system::" + system_name + "/field::"
        p_family = libspud.get_option(path + p_name +
                                      "/type/rank/element/family")
        p_degree = libspud.get_option(path + p_name +
                                      "/type/rank/element/degree")
        f_family = libspud.get_option(path + f_name +
                                      "/type/rank/element/family")
        f_degree = libspud.get_option(path + f_name +
                                      "/type/rank/element/degree")
        pe = df.FiniteElement(p_family, mesh.ufl_cell(), p_degree)
        ve = df.FiniteElement(f_family, mesh.ufl_cell(), f_degree)
        e = pe * ve
        self.functionspace = df.FunctionSpace(mesh, e)

        #work out the order of the fields
        for i in xrange(
                libspud.option_count("/system::" + system_name + "/field")):
            name = libspud.get_option("/system::" + system_name + "/field[" +
                                      ` i ` + "]/name")
            if name == f_name:
                self.f_index = i
            if name == p_name:
                self.p_index = i
2 6 "Copper"
'''

d.set_log_active(False)
meshpath = '../Mesh/'
if len(sys.argv) > 1:
    meshname = sys.argv[1]
else:
    meshname = 'MeshDiskwithHoleAuto'
    # meshname = meshname + '_refined'
mesh_file = meshpath + meshname + '.h5'
if not os.path.isfile(mesh_file):
    print("Specify correct name for meshfile!")
    sys.exit(0)

mesh = d.Mesh()
hdf = d.HDF5File(mesh.mpi_comm(), mesh_file, "r")
hdf.read(mesh, "/mesh", False)
cells = d.MeshFunction("size_t", mesh, dim=2)
hdf.read(cells, "/subdomains")
facets = d.MeshFunction("size_t", mesh, dim=1)
hdf.read(facets, "/facets")

datafileHDF5 = d.HDF5File(mesh.mpi_comm(), "TemperatureDevelopment_test.h5",
                          "w")
datafile = open('TemperatureDevelopment_test.dat', 'w')

d.plot(mesh)
plt.show()
"""Let's start with some functions and parameters needed for the whole model"""
T_0 = d.Constant(300.)
    def __init__(self,
                 mesh=None,
                 mesh_file=None,
                 region=None,
                 size=None,
                 center=np.zeros(3),
                 nseg=None,
                 element_length=None,
                 element_type='Lagrange 1',
                 offset=1.0):
        """Finite-element basis with given support and resolution.

           Args:

               mesh(dolfin.Mesh):
               mesh_file(str):

                   Explicit specification of finite-element mesh as a
                   dolfin.Mesh object or a dolfin-format mesh file.

               region (Subregion) __OR__ size, center (v3):
               nseg (list of int) __OR__ element_length(float)
                   If mesh and mesh_file are both absent, the mesh is taken
                   to be a rectangular or cubic lattice over the box-shaped
                   domain given by region (if present) or (size,center).

                   If nseg is specified, nseg[d] is the number of segments
                   into which the dth linear dimension of the region is discretized.

                   Otherwise, element_length (scalar,float) specifies
                   a target discretization lengthscale. If element_length is None,
                   it is taken from options['element_length']

               element_type(str):
                   The type of finite-element basis function defined on the mesh,
                   expressed as a compound string of the form 'family degree'
                   for functions of finite-element family *family* and
                   nonnegative-integer degree *degree*. For example,
                   'Lagrange 1' and 'Lagrange 2' correspond to the usual
                   linear and quadratic functions supported on triangles/tetrahedra.

                   For more information on finite-element types, consult e.g.

                   1. The FENICS documentation:
                      https://fenicsproject.org/docs/dolfin/1.5.0/python/programmers-reference/mesh/index.html

                   2. The "Periodic Table of Finite Elements:"
                      http://femtable.org/
        """

        if 'dolfin' not in sys.modules:
            msg = 'failed to load dolfin (FENICS) module, needed for FiniteElementBasis'
            raise ImportError(msg)

        if mesh_file is not None:
            mesh = df.Mesh(mesh_file)

        if mesh is not None:  # get bounding box from mesh coordinates
            pmin, pmax = [
                op(mesh.coordinates(), 0) for op in [np.amin, np.amax]
            ]
            (center, size) = (0.5 * (pmax + pmin), (pmax - pmin))
        else:
            (center, size) = (v3(region.center),
                              v3(region.size)) if region else (v3(center),
                                                               v3(size))
            if not element_length:
                element_length = np.amax(size) / 10.0
            nn = nseg if nseg else [
                int(np.ceil(s / element_length)) for s in size
            ]
            nd = 3 if (len(nn) == 3 and nn[2] > 0) else 2
            pmin, pmax = [df.Point(center + pm * size) for pm in [-0.5, 0.5]]
            if nd == 2:
                mesh = df.RectangleMesh(pmin,
                                        pmax,
                                        nn[0],
                                        nn[1],
                                        diagonal='left')
            else:
                mesh = df.BoxMesh(pmin, pmax, nn[0], nn[1], nn[2])

        family, degree = element_type.split()[0:2]
        self.fs = df.FunctionSpace(mesh, family, int(degree))
        super().__init__(self.fs.dim(),
                         size=size,
                         center=center,
                         offset=offset)
Beispiel #27
0
    k = 0
    fx_tmp = fx.value(x0 + (beta**k) * grad_f0, t_s)
    # ipdb.set_trace()
    while (fx_tmp - fx0 > alpha * (beta**k) * qpval and k < k_max):
        # ipdb.set_trace()
        k = k + 1
        fx_tmp = fx.value(x0 + (beta**k) * grad_f0, t_s)
        # print str(k)
    if k >= k_max:
        print "Armijo reaches step limit."
        # ipdb.set_trace()
    return (k, fx_tmp)


mesh_drt = "./test_geo/seperateTT3"
mesh = dl.Mesh(mesh_drt + '.xml')
subdomains = dl.MeshFunction("size_t", mesh,
                             (mesh_drt + "_physical_region.xml"))
boundaries = dl.MeshFunction("size_t", mesh, (mesh_drt + "_facet_region.xml"))

### cost function's (OP) parameter
yeta0 = 1.0
yeta1 = 0.08
bp0 = [13.0, 13.0, 12.0]
bp1 = [3.0, 6.0, 11.0]
alpha = 0.1
beta = 0.7
alpha_i = 0.05  # 1E-5
beta_i = 0.75
epsl = 1E-6  # 1E-5
lp_step = 20
Beispiel #28
0
parser = argparse.ArgumentParser()
parser.add_argument("--experiment", "-e", type=str, default=None, help='folder containing xdmf data')
parser.add_argument("--stride", "-s", type=int, default=10, help='stride of temporal sampling')
parser.add_argument("--xres", "-nx", type=int, default=100, help='spatial resolution (points)')
args, unknown = parser.parse_known_args()
print(args)
if args.experiment is not None:
    rootdir = args.experiment
print(rootdir)
stride = args.stride


params, data, signature = load_data(rootdir)
# import pdb; pdb.set_trace()

mesh = dolfin.Mesh(comm, os.path.join(rootdir, 'mesh.xml'))
V_alpha = dolfin.FunctionSpace(mesh, "CG", 1)

load_min = params['time_stepping']['load_min']
load_max = params['time_stepping']['load_max']
nsteps = params['time_stepping']['nsteps']
Lx = params['geometry']['Lx']

onedim = False
if not onedim:
	Ly = params['geometry']['Ly']

xs = np.linspace(-Lx/2, Lx/2, args.xres)
y0 = 0.

load_steps = np.linspace(load_min, load_max, nsteps)
Beispiel #29
0
             solver_parameters={
                 "newton_solver": {
                     "relative_tolerance": 1e-4,
                     "maximum_iterations": 100
                 }
             })

    return v


if __name__ == "__main__":
    dl.set_log_active(False)
    np.random.seed(1)
    sep = "\n" + "#" * 80 + "\n"
    print sep, "Set up the mesh and finite element spaces.\n", "Compute wind velocity", sep
    mesh = dl.refine(dl.Mesh("ad_20.xml"))
    wind_velocity = computeVelocityField(mesh)
    Vh = dl.FunctionSpace(mesh, "Lagrange", 2)
    print "Number of dofs: {0}".format(Vh.dim())

    print sep, "Set up Prior Information and model", sep

    true_initial_condition = dl.interpolate(
        dl.Expression(
            'min(0.5,exp(-100*(pow(x[0]-0.35,2) +  pow(x[1]-0.7,2))))'),
        Vh).vector()

    orderPrior = 2

    if orderPrior == 1:
        gamma = 1
def traction_test(ell=0.05,
                  ell_e=.1,
                  degree=1,
                  n=3,
                  nu=0.,
                  load_min=0,
                  load_max=2,
                  loads=None,
                  nsteps=20,
                  Lx=1.,
                  Ly=0.1,
                  outdir="outdir",
                  postfix='',
                  savelag=1,
                  sigma_D0=1.,
                  periodic=False,
                  continuation=False,
                  checkstability=True,
                  configString='',
                  test=True):
    # constants
    # ell = ell
    Lx = Lx
    load_min = load_min
    load_max = load_max
    nsteps = nsteps
    outdir = outdir
    loads = loads

    savelag = 1
    nu = dolfin.Constant(nu)
    ell = dolfin.Constant(ell)
    ell_e = ell_e
    E = dolfin.Constant(1.0)
    K = E.values()[0] / ell_e**2.
    sigma_D0 = E
    n = n
    # h = ell.values()[0]/n
    h = max(ell.values()[0] / n, .005)
    cell_size = h
    continuation = continuation
    isPeriodic = periodic
    config = json.loads(configString) if configString != '' else ''

    cmd_parameters = {
        'material': {
            "ell": ell.values()[0],
            "ell_e": ell_e,
            "K": K,
            "E": E.values()[0],
            "nu": nu.values()[0],
            "sigma_D0": sigma_D0.values()[0]
        },
        'geometry': {
            'Lx': Lx,
            'Ly': Ly,
            'n': n,
        },
        'experiment': {
            'test': test,
            'periodic': isPeriodic,
            'signature': ''
        },
        'stability': {
            'checkstability': checkstability,
            'continuation': continuation
        },
        'time_stepping': {
            'load_min': load_min,
            'load_max': load_max,
            'nsteps': nsteps,
            'outdir': outdir,
            'postfix': postfix,
            'savelag': savelag
        },
        'alt_min': {},
        "code": {}
    }

    # --------------------

    for par in parameters:
        parameters[par].update(cmd_parameters[par])

    if config:
        for par in config:
            parameters[par].update(config[par])
    # else:

    # parameters['material']['ell_e'] =

    Lx = parameters['geometry']['Lx']
    Ly = parameters['geometry']['Ly']
    ell = parameters['material']['ell']
    ell_e = parameters['material']['ell_e']

    BASE_DIR = os.path.dirname(os.path.realpath(__file__))
    fname = "film"
    print(BASE_DIR)
    os.path.isfile(fname)

    signature = hashlib.md5(str(parameters).encode('utf-8')).hexdigest()

    if parameters['experiment']['test'] == True:
        outdir += '-{}'.format(cmd_parameters['time_stepping']['postfix'])
    else:
        outdir += '-{}{}'.format(signature,
                                 cmd_parameters['time_stepping']['postfix'])
    outdir = outdir + '-cont'
    parameters['time_stepping']['outdir'] = outdir
    Path(outdir).mkdir(parents=True, exist_ok=True)
    print('Outdir is: ' + outdir)

    with open(os.path.join(outdir, 'rerun.sh'), 'w') as f:
        configuration = deepcopy(parameters)
        configuration['time_stepping'].pop('outdir')
        str(configuration).replace("\'True\'",
                                   "True").replace("\'False\'", "False")
        rerun_cmd = 'python3 {} --config="{}"'.format(
            os.path.basename(__file__), configuration)
        f.write(rerun_cmd)

    with open(os.path.join(outdir, 'parameters.pkl'), 'w') as f:
        json.dump(parameters, f)

    with open(os.path.join(outdir, 'signature.md5'), 'w') as f:
        f.write(signature)
    print(parameters)

    # boundary_meshfunction = dolfin.MeshFunction("size_t", mesh, "meshes/%s-%s_facet_region.xml"%(fname, signature))
    # cells_meshfunction = dolfin.MeshFunction("size_t", mesh, "meshes/%s-%s_physical_region.xml"%(fname, signature))

    # ------------------
    geometry_parameters = parameters['geometry']

    geom_signature = hashlib.md5(
        str(geometry_parameters).encode('utf-8')).hexdigest()
    meshfile = "%s/meshes/%s-%s.xml" % (BASE_DIR, fname, geom_signature)
    # cmd_parameters['experiment']['signature']=signature

    if os.path.isfile(meshfile):
        print("Meshfile %s exists" % meshfile)
        mesh = dolfin.Mesh("meshes/%s-%s.xml" % (fname, geom_signature))
    else:
        print("Creating meshfile: %s" % meshfile)
        print(('DEBUG: (-Lx/2. ={} , -Ly/2.={})'.format(Lx / 2., -Ly / 2.)))
        geom = mshr.Rectangle(dolfin.Point(-Lx / 2., -Ly / 2.),
                              dolfin.Point(Lx / 2., Ly / 2.))
        mesh = mshr.generate_mesh(geom, n * int(float(Lx / ell)))
    print(meshfile)

    mesh_xdmf = dolfin.XDMFFile("meshes/%s-%s.xdmf" % (fname, geom_signature))
    mesh_xdmf.write(mesh)
    if rank == 0:
        meshf = dolfin.File(os.path.join(outdir, "mesh.xml"))
        meshf << mesh

    V_u = dolfin.VectorFunctionSpace(mesh, "CG", 1)
    V_alpha = dolfin.FunctionSpace(mesh, "CG", 1)
    u = dolfin.Function(V_u, name="Total displacement")
    alpha = dolfin.Function(V_alpha, name="Damage")

    bcs_alpha = []
    bcs_u = [
        DirichletBC(V_u, Constant((0., 0)),
                    '(near(x[0], %f) or near(x[0], %f))' % (-Lx / 2., Lx / 2.))
    ]

    left = dolfin.CompiledSubDomain("near(x[0], -Lx/2.)", Lx=Lx)
    right = dolfin.CompiledSubDomain("near(x[0], Lx/2.)", Lx=Lx)
    bottom = dolfin.CompiledSubDomain("near(x[1],-Ly/2.)", Ly=Ly)
    top = dolfin.CompiledSubDomain("near(x[1],Ly/2.)", Ly=Ly)

    mf = dolfin.MeshFunction("size_t", mesh, 1, 0)
    right.mark(mf, 1)
    left.mark(mf, 2)
    bottom.mark(mf, 3)

    state = [u, alpha]

    Z = dolfin.FunctionSpace(
        mesh, dolfin.MixedElement([u.ufl_element(),
                                   alpha.ufl_element()]))
    z = dolfin.Function(Z)

    v, beta = dolfin.split(z)
    dx = dolfin.Measure("dx", metadata=form_compiler_parameters, domain=mesh)
    ds = dolfin.Measure("ds", subdomain_data=mf)

    # Files for output
    file_out = dolfin.XDMFFile(os.path.join(outdir, "output.xdmf"))
    file_eig = dolfin.XDMFFile(os.path.join(outdir, "perturbations.xdmf"))
    file_con = dolfin.XDMFFile(os.path.join(outdir, "continuation.xdmf"))
    file_bif = dolfin.XDMFFile(
        os.path.join(outdir, "bifurcation_postproc.xdmf"))

    for f in [file_out, file_eig, file_con, file_bif]:
        f.parameters["functions_share_mesh"] = True
        f.parameters["flush_output"] = True

    # Problem definition

    foundation_density = 1. / 2. * 1. / ell_e**2. * dot(u, u)
    model = DamagePrestrainedElasticityModel(
        state,
        E,
        nu,
        ell,
        sigma_D0,
        user_functional=foundation_density,
        eps0t=Expression([['t', 0.], [0., 0.]], t=0., degree=0))
    # import pdb; .set_trace()
    model.dx = dx
    model.ds = ds
    energy = model.total_energy_density(u, alpha) * dx
    # Alternate minimization solver
    solver = solvers.AlternateMinimizationSolver(
        energy, [u, alpha], [bcs_u, bcs_alpha],
        parameters=parameters['alt_min'])

    rP = model.rP(u, alpha, v, beta) * dx + 1 / ell_e**2. * dot(v, v) * dx
    rN = model.rN(u, alpha, beta) * dx

    stability = StabilitySolver(mesh,
                                energy, [u, alpha], [bcs_u, bcs_alpha],
                                z,
                                parameters=parameters['stability'])
    # stability = StabilitySolver(mesh, energy, [u, alpha], [bcs_u, bcs_alpha], z, parameters = parameters['stability'], rayleigh=[rP, rN])

    # if isPeriodic:
    #     stability = StabilitySolver(mesh, energy, [u, alpha], [bcs_u, bcs_alpha], z,
    #         parameters = stability_parameters,
    #         constrained_domain = PeriodicBoundary(Lx))
    # else:
    #     stability = StabilitySolver(mesh, energy, [u, alpha], [bcs_u, bcs_alpha], z, parameters = parameters['stability'])

    load_steps = np.linspace(load_min, load_max,
                             parameters['time_stepping']['nsteps'])
    if loads:
        load_steps = loads

    time_data = []

    linesearch = LineSearch(energy, [u, alpha])
    alpha_old = dolfin.Function(alpha.function_space())
    lmbda_min_prev = 0.000001
    bifurcated = False
    bifurcation_loads = []
    save_current_bifurcation = False
    bifurc_count = 0
    alpha_bif = dolfin.Function(V_alpha)
    alpha_bif_old = dolfin.Function(V_alpha)
    bifurcation_loads = []

    tot_energy = model.elastic_energy_density(model.eps(u), alpha)*dx + \
            1./2.*1/ell_e**2. * dot(u, u)*dx             + \
            model.damage_dissipation_density(alpha)*dx
    cont_atol = 1e-3

    for it, load in enumerate(load_steps):
        model.eps0t.t = load
        alpha_old.assign(alpha)
        ColorPrint.print_warn('Solving load t = {:.2f}'.format(load))

        # First order stability conditions
        (time_data_i, am_iter) = solver.solve()

        # Second order stability conditions
        (stable, negev) = stability.solve(solver.problem_alpha.lb)
        ColorPrint.print_pass(
            'Current state is{}stable'.format(' ' if stable else ' un'))
        # import pdb; pdb.set_trace()

        mineig = stability.mineig if hasattr(stability, 'mineig') else 0.0
        # print('DEBUG: lmbda min', lmbda_min_prev)
        # print('DEBUG: mineig', mineig)
        Deltav = (mineig - lmbda_min_prev) if hasattr(stability, 'eigs') else 0

        if (mineig + Deltav) * (lmbda_min_prev +
                                dolfin.DOLFIN_EPS) < 0 and not bifurcated:
            bifurcated = True
            # save 3 bif modes
            print('DEBUG: About to bifurcate load ', load, 'step', it)
            bifurcation_loads.append(load)
            bifurc_count += 1

        lmbda_min_prev = mineig if hasattr(stability, 'mineig') else 0.
        if stable:
            solver.update()
        else:
            # Continuation
            iteration = 1
            energy_pre = dolfin.assemble(tot_energy)
            alpha_bif.assign(alpha)
            alpha_bif_old.assign(alpha_old)

            while stable == False and iteration < 30:
                # linesearch
                perturbation_v = stability.perturbation_v
                perturbation_beta = stability.perturbation_beta

                h_opt, (hmin, hmax), energy_perturbations = linesearch.search(
                    [u, alpha, alpha_old], perturbation_v, perturbation_beta)

                # import pdb; pdb.set_trace()
                # if h_opt != 0:
                if h_opt > cont_atol:

                    save_current_bifurcation = True

                    # admissible
                    uval = u.vector()[:] + h_opt * perturbation_v.vector()[:]
                    aval = alpha.vector(
                    )[:] + h_opt * perturbation_beta.vector()[:]

                    u.vector()[:] = uval
                    alpha.vector()[:] = aval

                    u.vector().vec().ghostUpdate()
                    alpha.vector().vec().ghostUpdate()

                    (time_data_i, am_iter) = solver.solve()
                    (stable, negev) = stability.solve(alpha_old)
                    ColorPrint.print_pass(
                        '    Continuation iteration #{}, current state is{}stable'
                        .format(iteration, ' ' if stable else ' un'))
                    energy_post = dolfin.assemble(tot_energy)
                    ener_diff = energy_post - energy_pre
                    ColorPrint.print_warn(
                        'DEBUG: step {}, iteration {}, En_post - En_pre ={}'.
                        format(it, iteration, energy_post - energy_pre))

                    iteration += 1
                    if ener_diff < 0: bifurcated = False
                else:
                    # warn
                    ColorPrint.print_warn(
                        'DEBUG: Found (almost) zero increment, we are stuck in the matrix'
                    )
                    ColorPrint.print_warn('DEBUG:   h_opt = {}'.format(h_opt))
                    ColorPrint.print_warn('DEBUG: Continuing load program')
                    break

            solver.update()
            # stable == True
            # modes = np.where(stability.eigs < 0)[0]
            # with file_bif as file:
            #     leneigs = len(modes)
            #     maxmodes = min(3, leneigs)
            #     for n in range(maxmodes):
            #         mode = dolfin.project(stability.linsearch[n]['beta_n'], V_alpha)
            #         modename = 'beta-%d'%n
            #         print(modename)
            #         file.write_checkpoint(mode, modename, 0, append=True)

            # bifurc_count += 1
        time_data_i["load"] = load
        time_data_i["stable"] = stable
        time_data_i["dissipated_energy"] = dolfin.assemble(
            model.damage_dissipation_density(alpha) * dx)
        time_data_i["foundation_energy"] = dolfin.assemble(
            1. / 2. * 1 / ell_e**2. * dot(u, u) * dx)
        time_data_i["membrane_energy"] = dolfin.assemble(
            model.elastic_energy_density(model.eps(u), alpha) * dx)
        time_data_i["elastic_energy"] = time_data_i[
            "membrane_energy"] + time_data_i["foundation_energy"]
        time_data_i["eigs"] = stability.eigs if hasattr(stability,
                                                        'eigs') else np.inf
        time_data_i["stable"] = stability.stable
        time_data_i["# neg ev"] = stability.negev
        # import pdb; pdb.set_trace()

        _sigma = model.stress(model.eps(u), alpha)
        e1 = dolfin.Constant([1, 0])
        _snn = dolfin.dot(dolfin.dot(_sigma, e1), e1)
        time_data_i["sigma"] = 1 / Ly * dolfin.assemble(_snn * model.ds(1))

        time_data_i["S(alpha)"] = dolfin.assemble(1. / (model.a(alpha)) *
                                                  model.dx)
        time_data_i["A(alpha)"] = dolfin.assemble((model.a(alpha)) * model.dx)
        time_data_i["avg_alpha"] = dolfin.assemble(alpha * model.dx)

        ColorPrint.print_pass(
            "Time step {:.4g}: it {:3d}, err_alpha={:.4g}".format(
                time_data_i["load"], time_data_i["iterations"],
                time_data_i["alpha_error"]))

        time_data.append(time_data_i)
        time_data_pd = pd.DataFrame(time_data)

        if np.mod(it, savelag) == 0:
            with file_out as f:
                f.write(alpha, load)
                f.write(u, load)
                f.write_checkpoint(alpha,
                                   "alpha-{}".format(it),
                                   0,
                                   append=True)
                # with file_bif as f:
                print('DEBUG: written step ', it)

        if save_current_bifurcation:
            # modes = np.where(stability.eigs < 0)[0]

            time_data_i['h_opt'] = h_opt
            time_data_i['max_h'] = hmax
            time_data_i['min_h'] = hmin

            with file_bif as file:
                beta0v = dolfin.project(stability.perturbation_beta, V_alpha)
                file.write_checkpoint(beta0v,
                                      'beta0',
                                      bifurc_count - 1,
                                      append=True)
                file.write_checkpoint(alpha_bif_old,
                                      'alpha-old',
                                      bifurc_count - 1,
                                      append=True)
                file.write_checkpoint(alpha_bif,
                                      'alpha-bif',
                                      bifurc_count - 1,
                                      append=True)
                file.write_checkpoint(alpha,
                                      'alpha',
                                      bifurc_count - 1,
                                      append=True)

                np.save(os.path.join(outdir, 'energy_perturbations'),
                        energy_perturbations,
                        allow_pickle=True,
                        fix_imports=True)

            with file_eig as file:
                _v = dolfin.project(
                    dolfin.Constant(h_opt) * perturbation_v, V_u)
                _beta = dolfin.project(
                    dolfin.Constant(h_opt) * perturbation_beta, V_alpha)
                _v.rename('perturbation displacement',
                          'perturbation displacement')
                _beta.rename('perturbation damage', 'perturbation damage')
                # import pdb; pdb.set_trace()
                f.write(_v, load)
                f.write(_beta, load)
                file.write_checkpoint(_v,
                                      'perturbation_v',
                                      bifurc_count - 1,
                                      append=True)
                file.write_checkpoint(_beta,
                                      'perturbation_beta',
                                      bifurc_count - 1,
                                      append=True)

            save_current_bifurcation = False

        time_data_pd.to_json(os.path.join(outdir, "time_data.json"))

    plt.figure()
    plt.plot(time_data_pd["load"].values(),
             time_data_pd["iterations"].values(),
             label='its')
    plt.semilogy()
    ax = plt.gca()
    ax2 = ax.twinx()
    ax2.plot(time_data_pd["load"].values(),
             time_data_pd["alpha_error"].values(),
             'o',
             c='C1',
             label='alpha error')
    plt.savefig(os.path.join(outdir, 'am.pdf'))
    plt.legend()
    plt.close()
    # user_postprocess_timestep(alpha, parameters, load, xresol = 100)

    plt.figure()
    dolfin.plot(alpha)
    plt.savefig(os.path.join(outdir, "alpha.png"))
    plt.figure()
    dolfin.plot(u, mode="displacement")
    plt.savefig(os.path.join(outdir, "u.png"))
    _nu = parameters['material']['nu']
    _E = parameters['material']['E']
    _w1 = parameters['material']['sigma_D0']**2. / parameters['material']['E']

    tc = np.sqrt(2 * _w1 / (_E * (1. - 2. * _nu) * (1. + _nu)))
    if parameters['stability']['checkstability'] == 'True':
        pp.plot_spectrum(parameters, outdir, time_data_pd.sort_values('load'),
                         tc)
    # plt.show()
    print(time_data_pd)
    print()
    print('Output in: ' + outdir)

    return time_data_pd