Skip to content
Permalink
Browse files

Merge branch 'parse_flags_as_kwargs' into 'master'

Parse flags as kwargs

See merge request !222
  • Loading branch information
JSchoeberl committed Aug 17, 2017
2 parents e064090 + aa866fa commit 4ba90d5ec2d76651fe4220aacc7d4bdbcfd3eb65
@@ -342,6 +342,7 @@ namespace ngcomp
: FESpace (ama, aflags),
flags(aflags)
{
type = "hcurlho";
name="HCurlHighOrderFESpace(hcurlho)";

// define flags
@@ -28,6 +28,7 @@ namespace ngcomp
HDivHighOrderFESpace (shared_ptr<MeshAccess> ama, const Flags & flags, bool parseflags)
: FESpace (ama, flags)
{
type = "hdivho";
name="HDivHighOrderFESpace(hdivho)";
// allowed flags
DefineNumFlag("relorder");

Large diffs are not rendered by default.

@@ -1161,29 +1161,18 @@ void NGS_DLL_HEADER ExportNgfem(py::module &m) {
(m, "DifferentialOperator")
;

m.def("CreateBilinearFormIntegrator", [] (py::object self_class, string name, int dim,
py::object py_coef, py::object definedon, bool imag,
string filename, Flags flags, py::object definedonelem)
m.def("CreateBilinearFormIntegrator", [] (py::object self_class, const string name,
py::object py_coef, int dim, bool imag,
string filename, py::kwargs kwargs)
-> shared_ptr<BilinearFormIntegrator>
{
auto flags = CreateFlagsFromKwArgs(self_class,kwargs);
Array<shared_ptr<CoefficientFunction>> coef = MakeCoefficients(py_coef);
auto bfi = GetIntegrators().CreateBFI (name, dim, coef);

if (!bfi) cerr << "undefined integrator '" << name
<< "' in " << dim << " dimension" << endl;

auto definedon_list = py::extract<py::list>(definedon);
if (definedon_list.check())
{
Array<int> defon = makeCArray<int> (definedon_list());
for (int & d : defon) d--;
bfi -> SetDefinedOn (defon);
}
else if (py::extract<BitArray> (definedon).check())
bfi -> SetDefinedOn (py::extract<BitArray> (definedon)());
else if (!py::extract<DummyArgument>(definedon).check())
throw Exception (string ("cannot handle definedon of type <todo>"));

if (filename.length())
{
cout << "set integrator filename: " << filename << endl;
@@ -1192,20 +1181,60 @@ void NGS_DLL_HEADER ExportNgfem(py::module &m) {
bfi -> SetFlags (flags);
if (imag)
bfi = make_shared<ComplexBilinearFormIntegrator> (bfi, Complex(0,1));
if (! py::extract<DummyArgument> (definedonelem).check())
bfi -> SetDefinedOnElements (py::extract<shared_ptr<BitArray>>(definedonelem)());
self_class.attr("__initialize__")(bfi,**kwargs);
return bfi;
},
py::arg("self_class"),
py::arg("name")="",py::arg("dim")=-1,py::arg("coef"),
py::arg("definedon")=DummyArgument(),py::arg("imag")=false,
py::arg("filename")="", py::arg("flags") = py::dict(),
py::arg("definedonelements")=DummyArgument()
py::arg("self_class"), py::arg("name")="",
py::arg("coef"),py::arg("dim")=-1,
py::arg("imag")=false, py::arg("filename")=""
);

typedef BilinearFormIntegrator BFI;
py::class_<BFI, shared_ptr<BFI>>
(m, "BFI")
.def_static("__flags_doc__", [] ()
{
return py::dict
(
py::arg("dim") = "int = -1\n"
"Dimension of integrator. If -1 then dim is set when integrator is\n"
"added to BilinearForm",
py::arg("definedon") = "ngsolve.Region\n"
"Region the integrator is defined on. Regions can be obtained by i.e.\n"
"mesh.Materials('regexp') or mesh.Boundaries('regexp'). If not set\n"
"integration is done on all volume elements",
py::arg("definedonelem") = "ngsolve.BitArray\n"
"Element wise integrator definition."
);
})
.def_static("__special_treated_flags__", [] ()
{
return py::dict
(
py::arg("definedonelem") = py::cpp_function([](py::object,Flags*,py::list) { ; }),
py::arg("definedon") = py::cpp_function ([] (py::object, Flags*, py::list) { ; })
);
})
.def("__initialize__", [] (shared_ptr<BFI> self, py::kwargs kwargs)
{
if(kwargs.contains("definedon"))
{
auto definedon = kwargs["definedon"];
auto definedon_list = py::extract<py::list>(definedon);
if (definedon_list.check())
{
Array<int> defon = makeCArray<int> (definedon_list());
for (int & d : defon) d--;
self->SetDefinedOn (defon);
}
else if (py::extract<BitArray> (definedon).check())
self->SetDefinedOn (py::extract<BitArray> (definedon)());
else if (!py::extract<DummyArgument>(definedon).check())
throw Exception (string ("cannot handle definedon of type <todo>"));
}
if(kwargs.contains("definedonelem"))
self->SetDefinedOnElements(py::cast<shared_ptr<BitArray>>(kwargs["definedonelem"]));
})
.def("__str__", [](shared_ptr<BFI> self) { return ToString<BilinearFormIntegrator>(*self); } )

.def("Evaluator", [](shared_ptr<BFI> self, string name ) { return self->GetEvaluator(name); } )
@@ -73,6 +73,58 @@ void SetFlag(Flags &flags, string s, py::object value)
}
}

Flags CreateFlagsFromKwArgs(const py::object& pyclass, const py::kwargs& kwargs, py::list info)
{
auto flags_doc = pyclass.attr("__flags_doc__")();
py::dict flags_dict;

if (kwargs.contains("flags"))
{
cout << IM(2) << "WARNING: using flags as kwarg is deprecated in " << py::str(pyclass)
<< ", use the flag arguments as kwargs instead!" << endl;
auto addflags = py::cast<py::dict>(kwargs["flags"]);
for (auto item : addflags)
flags_dict[item.first.cast<string>().c_str()] = item.second;
}
for (auto item : kwargs)
if (!flags_doc.contains(item.first.cast<string>().c_str()) &&
!(item.first.cast<string>() == "flags"))
cout << IM(2) << "WARNING: kwarg '" << item.first.cast<string>()
<< "' is an undocumented flags option for class "
<< std::string(py::str(pyclass)) << ", maybe there is a typo?" << endl;

py::dict special;
try
{
special = pyclass.attr("__special_treated_flags__")();
}
catch(std::exception e)
{ }

for (auto item : kwargs)
{
auto name = item.first.cast<string>();
if (name != "flags")
{
if(!special.contains(name.c_str()))
flags_dict[name.c_str()] = item.second;
}
}

auto flags = py::extract<Flags>(flags_dict)();

for (auto item : kwargs)
{
auto name = item.first.cast<string>();
if (name != "flags")
{
if(special.contains(name.c_str()))
special[name.c_str()](item.second, &flags, info);
}
}
return flags;
}

const char* docu_string(const char* str)
{
if(getenv("NETGEN_DOCUMENTATION_RST_FORMAT"))
@@ -366,6 +366,9 @@ template <> inline void PyExportSymbolTable<shared_ptr<double>, shared_ptr<doubl
;
}

// Parse python kwargs to flags
Flags CreateFlagsFromKwArgs(const py::object& pyclass, const py::kwargs& kwargs, py::list info = py::list());

// replace docu links with plain text for help function
const char* docu_string(const char* str);

@@ -21,7 +21,7 @@


order=4
fes = L2(mesh, order=order, flags = { "dgjumps" : True })
fes = L2(mesh, order=order, dgjumps = True)
u = fes.TrialFunction()
v = fes.TestFunction()

@@ -58,7 +58,7 @@ def MakeGeometry():
f = LinearForm(fes)
f += SymbolicLFI(CoefficientFunction([0, 0, 1])*v)

c = Preconditioner(a, type="multigrid", flags= { "inverse" : "sparsecholesky" })
c = Preconditioner(a, type="multigrid", inverse = "sparsecholesky")

gfu = GridFunction(fes)
Draw (gfu)
@@ -18,13 +18,13 @@

f.Assemble()

a = BilinearForm (v, symmetric=True, flags = { "eliminate_internal" : False })
a = BilinearForm (v, symmetric=True, eliminate_internal = False)
a += Mass (coef=1)
a += Laplace (coef=1)


# c = Preconditioner (a, "multigrid", { "test" : True, "smoother" : "block", "finesmoothingsteps" : 1 })
c = Preconditioner (a, "bddc", { "test" : True })
# c = Preconditioner (a, type = "multigrid", test = True, smoother = "block", finesmoothingsteps = 1)
c = Preconditioner (a, type = "bddc", test = True)

print ("now assemble the matrix ...")
a.Assemble()
@@ -30,7 +30,7 @@ def MakeGeometry():

ngsglobals.msg_level = 5

fes = HCurl(mesh, order=4, dirichlet="outer", flags = { "nograds" : True })
fes = HCurl(mesh, order=4, dirichlet="outer", nograds = True)

# u and v refer to trial and test-functions in the definition of forms below
u = fes.TrialFunction()
@@ -14,8 +14,8 @@
mesh = Mesh( geo.GenerateMesh(maxh=0.5))

order = 3
V = HDivDiv(mesh, order=order-1, dirichlet="bottom|right|top", flags = { "plus" : True } )
Q = HCurl(mesh, order=order, dirichlet="left", flags = { "type1" : True } )
V = HDivDiv(mesh, order=order-1, dirichlet="bottom|right|top", plus = True)
Q = HCurl(mesh, order=order, dirichlet="left", type1 = True)
X = FESpace([V,Q])

print ("ndof-V:", V.ndof, ", ndof-Q:", Q.ndof)
@@ -25,11 +25,11 @@
n = specialcf.normal(mesh.dim)
h = specialcf.mesh_size

a = BilinearForm(fes, symmetric=True, flags = { "eliminate_internal" : True })
a = BilinearForm(fes, symmetric=True, eliminate_internal = True)
a += SymbolicBFI(grad(u) * grad(v))
a += SymbolicBFI(grad(u)*n*(vhat-v)+grad(v)*n*(uhat-u)+10*order*order/h*(u-uhat)*(v-vhat), element_boundary=True)

c = Preconditioner(type="direct", bf=a, flags = { "inverse" : "sparsecholesky" } )
c = Preconditioner(type="direct", bf=a, inverse = "sparsecholesky")
# c = Preconditioner(type="bddc", bf=a)

a.Assemble()
@@ -8,7 +8,7 @@
# mesh.Refine()

order = 2
fes1 = HDiv(mesh, order=order, flags = { "discontinuous" : True } )
fes1 = HDiv(mesh, order=order, discontinuous=True)
fes2 = L2(mesh, order=order-1)
fes3 = FacetFESpace(mesh, order=order, dirichlet=[1,2,3])

@@ -19,12 +19,12 @@

n = specialcf.normal(mesh.dim)

a = BilinearForm(fes, symmetric=False, flags = { "eliminate_internal" : True })
a = BilinearForm(fes, symmetric=False, eliminate_internal = True)
a += SymbolicBFI(sigma*tau + div(sigma)*v + div(tau)*u)
a += SymbolicBFI(sigma*n*vhat+tau*n*uhat, element_boundary=True)

# c = Preconditioner(type="direct", bf=a, flags = { "inverse" : "sparsecholesky" } )
# c = Preconditioner(type="direct", bf=a, flags = { "inverse" : "pardiso" } )
# c = Preconditioner(type="direct", bf=a, inverse = sparsecholesky)
# c = Preconditioner(type="direct", bf=a, inverse = pardiso)
# c = Preconditioner(type="local", bf=a)
c = Preconditioner(type="bddc", bf=a)

@@ -1,15 +1,16 @@
from ngsolve import *
import ngsolve.utils as utils

pde = comp.PDE("d1_square.pde")
pde = PDE("d1_square.pde")
pde.Solve()
mesh = pde.Mesh()

v = pde.spaces["v"]

lap = fem.BFI (name="laplace", coef=utils.x*utils.y)
src = fem.LFI (name="source", coef=4.8)
lap = BFI (name="laplace", coef=utils.x*utils.y)
src = LFI (name="source", coef=4.8)

i = comp.ElementId(comp.VOL,1)
i = ElementId(VOL,1)
el = v.GetFE(i)
trafo = mesh.GetTrafo(i)

@@ -41,7 +41,7 @@ def MakeGeometry():

ngsglobals.msg_level = 5

fes = HCurl(mesh, order=4, dirichlet="outer", flags = { "nograds" : True })
fes = HCurl(mesh, order=4, dirichlet="outer", nograds = True)

u = fes.TrialFunction()
v = fes.TestFunction()
@@ -56,7 +56,7 @@ def MakeGeometry():
a += SymbolicBFI(nu*curl(u)*curl(v) + 1e-6*nu*u*v)

#c = Preconditioner(a, type="bddc", flags={"inverse":"masterinverse"})
c = Preconditioner(a, type="bddc", flags={"inverse":"mumps"})
c = Preconditioner(a, type="bddc", inverse = "mumps")

f = LinearForm(fes)
f += SymbolicLFI(CoefficientFunction((y,0.05-x,0)) * v, definedon=mesh.Materials("coil"))
@@ -77,7 +77,7 @@
inv = mstar.mat.Inverse(X.FreeDofs(), inverse="mumps")

# the non-linear term
conv = BilinearForm(X, flags = { "nonassemble" : True })
conv = BilinearForm(X, nonassemble = True)
conv += SymbolicBFI( CoefficientFunction( (ux,uy) ) * (grad(ux)*vx+grad(uy)*vy) )

t = 0
@@ -57,10 +57,10 @@
a += SymbolicBFI(grad(u)*grad(v))

# Some possible preconditioners:
#c = Preconditioner(a, type="direct", flags={"inverse":"mumps"}) # direct solve with mumps
#c = Preconditioner(a, type="bddc", flags={"inverse":"mumps"}) # BBDC + mumps for coarse inverse
#c = Preconditioner(a, type="direct", inverse = "mumps") # direct solve with mumps
#c = Preconditioner(a, type="bddc", inverse = "mumps") # BBDC + mumps for coarse inverse
#c = Preconditioner(a, type="hypre") # BoomerAMG (use only for order 1)
c = Preconditioner(a, type="bddc", flags={"usehypre":True}) # BDDC + BoomerAMG for coarse matrix
c = Preconditioner(a, type="bddc", usehypre = True) # BDDC + BoomerAMG for coarse matrix

a.Assemble()

@@ -58,7 +58,7 @@
inv = mstar.mat.Inverse(X.FreeDofs(), inverse="sparsecholesky")

# the non-linear term
conv = BilinearForm(X, flags = { "nonassemble" : True })
conv = BilinearForm(X, nonassemble = True)
conv += SymbolicBFI( CoefficientFunction( (ux,uy) ) * (grad(ux)*vx+grad(uy)*vy) )

# for visualization
@@ -60,7 +60,7 @@
Draw (uin, mesh, "uin")
Draw (uscat, mesh, "uscat")
Draw (uin-uscat, mesh, "utot")
cf=mesh.GetPMLTrafo(2).PML_CF(2)
cf=mesh.GetPMLTrafo(2).PML_CF
mesh.UnSetPML(2)
Draw (cf-Conj(cf),mesh,"scaling")

@@ -1,11 +1,8 @@
from ngsolve.fem import *
from ngsolve.comp import *
from ngsolve.utils import *

import netgen
from ngsolve import *
from netgen.csg import unit_cube

ngsglobals.msg_level = 1
mesh = Mesh (netgen.csg.unit_cube.GenerateMesh(maxh=0.2))
mesh = Mesh (unit_cube.GenerateMesh(maxh=0.2))

import timeit

0 comments on commit 4ba90d5

Please sign in to comment.
You can’t perform that action at this time.