Git Product home page Git Product logo

fireshape / fireshape Goto Github PK

View Code? Open in Web Editor NEW
26.0 26.0 9.0 1.52 MB

A shape optimisation toolbox built on the Firedrake finite element library.

Home Page: https://fireshape.readthedocs.io

License: GNU Lesser General Public License v3.0

Python 99.56% Shell 0.19% Makefile 0.26%
finite-elements firedrake optimal-control pde-constrained-optimization rol scientific-computing shape-optimization

fireshape's Introduction

Fireshape - Shape Optimization with Firedrake

CircleCI Read the Docs Actions Docker images

Documentation

The documentation is available here.

We have also published an Open Access paper about Fireshape. It is available here.

Requirements

Please install the firedrake finite element library first.

curl -O https://raw.githubusercontent.com/firedrakeproject/firedrake/master/scripts/firedrake-install
python3 firedrake-install

Installation

Activate the Firedrake virtualenv first

source path/to/firedrake/bin/activate

Then install the Rapid Optimization Library along with roltrilinos.

pip3 install --no-cache-dir pyroltrilinos

Now you are ready to install fireshape.

For users:

pip3 install git+https://github.com/fireshape/fireshape.git

For developers:

git clone [email protected]:fireshape/fireshape.git
python -m pip install -e fireshape/

Docker images

Fireshape is also available as a docker image.

fireshape's People

Contributors

ainlina avatar apaganini avatar dependabot[bot] avatar florianwechsung avatar francesco-ballarin avatar gninr avatar medinaeder avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

fireshape's Issues

cannot import fireshape.zoo in docker image

The following example run in the docker image fireshape/fireshape

from firedrake import *
from fireshape import *
import fireshape.zoo as fsz

returns

ModuleNotFoundError: No module named 'fireshape.zoo'

levelset_bsplines breaks if levels is increased

If I increase the levels in the bsplines example, the mesh deformation doesn't seem sensible:

import firedrake as fd
import fireshape.zoo as fsz
import fireshape as fs
import ROL

n = 100
mesh = fd.UnitSquareMesh(n, n)

bbox = [(-3, 4), (-3, 4)]
orders = [2, 2]
levels = [4, 4]
Q = fs.BsplineControlSpace(mesh, bbox, orders, levels)
inner = fs.H1InnerProduct(Q, fixed_bids=[1, 2, 3, 4])
q = fs.ControlVector(Q, inner)

mesh_m = Q.mesh_m
(x, y) = fd.SpatialCoordinate(mesh_m)
f = (pow(x-0.5, 2))+pow(y-0.5, 2) - 2.

out = fd.File("domain.pvd")


J = fsz.LevelsetFunctional(f, Q, cb=lambda: out.write(mesh_m.coordinates))
J = 0.1 * J

params_dict = {
    'General': {
        'Secant': {'Type': 'Limited-Memory BFGS',
                   'Maximum Storage': 2}},
    'Step': {
        'Type': 'Line Search',
        'Line Search': {'Descent Method': {
            'Type': 'Quasi-Newton Step'}}},
    'Status Test': {
        'Gradient Tolerance': 1e-5,
        'Step Tolerance': 1e-6,
        'Iteration Limit': 50}}

params = ROL.ParameterList(params_dict, "Parameters")
problem = ROL.OptimizationProblem(J, q)
solver = ROL.OptimizationSolver(problem, params)
solver.solve()

image

Any ideas, @APaganini ?

Heuristic in ElasticityInnerProduct

ElasticityInnerProduct uses a heuristic to define Lamé parameters.
This is not documented. Also, the user should be allowed to provide a
a value different from 10 to be set on free_bids when
the Lamé parameter is constructed.

Should we include a similar heuristic into LaplaceInnerProduct?

No module named zoo

Similar to #53, maybe

Trying to the run the cantilever example found in https://zenodo.org/record/4036176

$python main.py 
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    from fireshape import *
  File "/home/waalge/clones/firedrake/lib/python3.8/site-packages/fireshape/__init__.py", line 8, in <module>
    import zoo
ModuleNotFoundError: No module named 'zoo'

Context:
I'd run

pip install git+https://github.com/fireshape/fireshape.git

TBH i don't know which version that installs.

Fixed with:

Uninstalling and using the cloned repo for the install fixed the error

pip install -e . 

Installing ROL failed

Just a signpost for the next person....

Following the README instructions,

pip3 install --no-cache-dir roltrilinos rol

Failed with output

ImportError: libteuchosparameterlist.so.12: cannot open shared object file: No such file or directory

Googling it took me to
https://bitbucket.org/dolfin-adjoint/pyadjoint/issues/83/failed-to-import-rol-with-pyadjoint-
And running

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/PATH/TO/FIREDRAKE-ENV/lib/python3.8/site-packages/roltrilinos/lib

Fixed the problem 🥳

Context:

Ubuntu 20.04.1, python3.8, ...

Firedrake status of components:

---------------------------------------------------------------------------
|Package             |Branch                        |Revision  |Modified  |
---------------------------------------------------------------------------
|COFFEE              |master                        |70c1e66   |False     |
|FInAT               |master                        |15444f9   |False     |
|PyOP2               |master                        |12c09bf3  |False     |
|fiat                |master                        |42ceef3   |False     |
|firedrake           |master                        |a7fc01a1  |True      |
|h5py                |firedrake                     |78531f08  |False     |
|libspatialindex     |master                        |4768bf3   |True      |
|libsupermesh        |master                        |5827e88   |False     |
|loopy               |firedrake                     |4f2b3941  |False     |
|petsc               |firedrake                     |e85aaad7c1|False     |
|petsc4py            |firedrake                     |4eb4f85   |False     |
|pyadjoint           |master                        |f635da0   |False     |
|tsfc                |master                        |50e6aab   |False     |
|ufl                 |master                        |057c5f6f  |False     |
---------------------------------------------------------------------------

bsplines with elasticity inner product crash

This is on 9fe93e2af1b2b3eab509ef1d44a1fdbefbf4d90b

test_levelset.py:166: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
/home/wechsung/Documents/Uni/DPhil/shapelib/fireshape/control.py:239: in __init__
    self.inner_product.get_impl(self.V_r, self.FullIFW)
/home/wechsung/Documents/Uni/DPhil/shapelib/fireshape/innerproduct.py:69: in get_impl
    a = self.get_weak_form(V)
/home/wechsung/Documents/Uni/DPhil/shapelib/fireshape/innerproduct.py:190: in get_weak_form
    mu = self.get_mu(V)
/home/wechsung/Documents/Uni/DPhil/shapelib/fireshape/innerproduct.py:180: in get_mu
    fd.solve(a == b, mu, bcs = [bc_fix, bc_free])
/home/wechsung/bin/firedrake/src/firedrake/firedrake/solving.py:121: in solve
    _solve_varproblem(*args, **kwargs)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/solving.py:150: in _solve_varproblem
    appctx=appctx)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/variational_solver.py:307: in __init__
    super(LinearVariationalSolver, self).__init__(*args, **kwargs)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/variational_solver.py:158: in __init__
    options_prefix=self.options_prefix)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/solving_utils.py:306: in __init__
    mat_type=mat_type)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/assemble.py:145: in create_assembly_callable
    collect_loops=True)
<decorator-gen-529>:2: in _assemble
    ???
/home/wechsung/bin/firedrake/src/firedrake/firedrake/utils.py:61: in wrapper
    return f(*args, **kwargs)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/assemble.py:569: in _assemble
    thunk(bcs)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/assemble.py:491: in thunk
    i, j)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/assemble.py:331: in mat
    m = testmap(test.function_space()[i])
/home/wechsung/bin/firedrake/src/firedrake/firedrake/assemble.py:489: in <lambda>
    tensor_arg = mat(lambda s: get_map(s, tsbc, decoration),
/home/wechsung/bin/firedrake/src/firedrake/firedrake/assemble.py:446: in get_map
    return x.cell_node_map(bcs)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/functionspaceimpl.py:451: in cell_node_map
    parent)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/functionspacedata.py:505: in get_map
    nodes = [bc.nodes for bc in explicit_bcs]
/home/wechsung/bin/firedrake/src/firedrake/firedrake/functionspacedata.py:505: in <listcomp>
    nodes = [bc.nodes for bc in explicit_bcs]
/home/wechsung/bin/firedrake/src/PyOP2/pyop2/utils.py:62: in __get__
    obj.__dict__[self.__name__] = result = self.fget(obj)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/bcs.py:179: in nodes
    return self._function_space.boundary_nodes(self.sub_domain, self.method)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/functionspaceimpl.py:514: in boundary_nodes
    return self._shared_data.boundary_nodes(self, sub_domain, method)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/functionspacedata.py:442: in boundary_nodes
    return get_boundary_nodes(V.mesh(), key, V)
<decorator-gen-517>:2: in get_boundary_nodes
    ???
/home/wechsung/bin/firedrake/src/firedrake/firedrake/functionspacedata.py:53: in cached
    result = f(mesh, key, *args, **kwargs)
/home/wechsung/bin/firedrake/src/firedrake/firedrake/functionspacedata.py:306: in get_boundary_nodes
    indices = dmplex.boundary_nodes(V, sub_domain, method)
firedrake/dmplex.pyx:703: in firedrake.dmplex.boundary_nodes
    ???
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <firedrake.mesh._Facets object at 0x7fe1c7cb4da0>, markers = ()

    def subset(self, markers):
        """Return the subset corresponding to a given marker value.
    
            :param markers: integer marker id or an iterable of marker ids
                (or ``None``, for an empty subset).
            """
        valid_markers = set([unmarked]).union(self.unique_markers)
        markers = as_tuple(markers, int)
        if self.markers is None and valid_markers.intersection(markers):
            return self._null_subset
        try:
            return self._subsets[markers]
        except KeyError:
            # check that the given markers are valid
            if len(set(markers).difference(valid_markers)) > 0:
                invalid = set(markers).difference(valid_markers)
                raise LookupError("{0} are not a valid markers (not in {1})".format(invalid, self.unique_markers))
    
            # build a list of indices corresponding to the subsets selected by
            # markers
            indices = np.concatenate([np.nonzero(self.markers == i)[0]
>                                     for i in markers])
E           ValueError: need at least one array to concatenate

/home/wechsung/bin/firedrake/src/firedrake/firedrake/mesh.py:188: ValueError

We can probably wait for the other bspline issues to be fixed until we attack this.

ElasticityInner heuristic is too soft in periodic domains

The elasticity constant is too small in periodic meshes. These meshes do not have constrained boundaries and as a result mu = 1 per the current heuristic. This is too soft and the mesh can become severely distorted.

An improved heuristic should alleviate these problems.

Future bug when pyadjoint is updated

When the new pyadjoint functionality is implemented, the default output of fda.derivative is the L2 representative (instead of the l2 one; see pyadjoint's pull request Fixing errors related to default L2 grad in adjoints #3579). When that happens, we need to use fda.derivative(.., options={"riesz_representation": None}) to get back the l2 representative. Note that now it will be a cofunction, so there's no need for tricks in objective.PDEConstrainedObjective.derivative(), which currently is

 def derivative(self, out):
        """
        Get the derivative from pyadjoint.
        """
        dJ = self.Jred.derivative()
        # Pyadjoint returns a function instead of a cofunction
        # because it assumes it is computing the gradient
        with dJ.dat.vec as vec_dJ:
            with self.deriv_r.dat.vec as vec_r:
                vec_dJ.copy(vec_r)
        out.from_first_derivative(self.deriv_r)

deprecation warning, rol installed used setup.py

Installing collected packages: roltrilinos, rol
    Running setup.py install for rol ... done
  DEPRECATION: rol was installed using the legacy 'setup.py install' method,
because a wheel could not be built for it. pip 21.0 will remove support for this
functionality. A possible replacement is to fix the wheel build issue reported
above. You can find discussion regarding this at
https://github.com/pypa/pip/issues/8368.

question still open in source code

control.py, lines 333-337 contains comments from debugging. Everything is probably fine, but let's check that it's fine.

        # self.V_r =
        # self.inner_product = inner_product
        # self.inner_product.get_impl(self.V_r, self.FullIFW)

        # is this the proper space?
        self.V_control = fd.VectorFunctionSpace(self.mesh_r, "CG", maxdegree)
        self.I_control = self.build_interpolation_matrix(self.V_control)

Cantilever example path handling error

Not yet in master but ...

Adding the cantilever example and running from root:

$python examples/cantilever/main.py 
Traceback (most recent call last):
  File "examples/cantilever/main.py", line 10, in <module>
    mesh = Mesh("cantilever.msh")
  File "<decorator-gen-28>", line 2, in Mesh
  File "/home/waalge/clones/firedrake/src/PyOP2/pyop2/profiling.py", line 60, in wrapper
    return f(*args, **kwargs)
  File "/home/waalge/clones/firedrake/src/firedrake/firedrake/mesh.py", line 1647, in Mesh
    plex = _from_gmsh(meshfile, comm)
  File "/home/waalge/clones/firedrake/src/firedrake/firedrake/mesh.py", line 217, in _from_gmsh
    gmsh_viewer.setFileName(filename)
  File "PETSc/Viewer.pyx", line 325, in petsc4py.PETSc.Viewer.setFileName
petsc4py.PETSc.Error: error code 65
[0] PetscViewerFileSetName() line 660 in /home/waalge/clones/firedrake/src/petsc/src/sys/classes/viewer/impls/ascii/filev.c
[0] PetscViewerFileSetName_ASCII() line 765 in /home/waalge/clones/firedrake/src/petsc/src/sys/classes/viewer/impls/ascii/filev.c
[0] Unable to open file
[0] Cannot open PetscViewer file: cantilever.msh

Its simply that the filename must be the full path.
Thus...

$cd examples/cantilever
$python main.py 

Works fine.

Alternatively in the main.py editing the beginning of the file to handle this

import os

from firedrake import *
from fireshape import *
import fireshape.zoo as fsz
import ROL
from PDEconstraint import LinearElasticitySolver
from objective import Compliance


# setup problem

mesh = Mesh(os.path.join(os.path.dirname(__file__), "cantilever.msh"))

And then

$python examples/cantilever/main.py 

Runs.

./solution directory is then at cwd which is fine 🤷

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.