I’m solving a linear system A\hat{x}=b with normalized function \hat{x} = ax. Normalization coefficient a is an expression of some dolfinx.Constant objects (not a dolfinx.Form).
What is the idiomatic way of renormalizing solution vector x=\hat{x}/a in dolfinx?
How about
u.x.array[:] /= constant.value[0]
1 Like
Then I would need to write down the normalization equation two times in the source code, which is error prone. I was hoping for some kind of assemble_vector magic…
Assemble vector would be alot more expensive (computationally) compared to applying it directly to a vector.
Why cant you make a convenience function:
def scale(u, alpha):
u.vector.array/alpha.value[0]
And use this function twice ?
I think, it worked.
import dolfinx
from mpi4py import MPI
import ufl
from petsc4py import PETSc
mesh = dolfinx.UnitSquareMesh(MPI.COMM_WORLD, 10, 10)
V = dolfinx.FunctionSpace(mesh, ("CG", 1))
c1 = dolfinx.Constant(V, 1)
c2 = dolfinx.Constant(V, 2)
c3 = dolfinx.Constant(V, 3)
expr = c1*c2+c3**2
def simplify(expr):
if issubclass(type(expr), ufl.core.operator.Operator):
return PETSc.ScalarType(expr.__class__(*[simplify(e) for e in expr.ufl_operands]))
elif issubclass(type(expr), dolfinx.Constant):
return PETSc.ScalarType(expr.value)
elif issubclass(type(expr), ufl.constantvalue.ConstantValue):
return PETSc.ScalarType(expr)
else:
raise TypeError(f"Unsupported type {type(expr)}")
print(expr)
print(simplify(expr))
c3.value = -2
print(simplify(expr))
Now I can use expr in the forms and obtain its value calling simplify(expr).