Invoked with: <dolfinx.io.utils.XDMFFile object at 0x7f23ea04c3b0>, Product(FloatValue(5.0), Coefficient(FunctionSpace(Mesh(blocked element (Basix element (P, quadrilateral, 1, gll_warped, unset, False), (2,)), 0), Basix element (P, quadrilateral, 1, gll_warped, unset, False)), 1)), 0, "/Xdmf/Domain/Grid[@GridType='Uniform'][1]"
from mpi4py import MPI
from petsc4py import PETSc
from petsc4py.PETSc import ScalarType
import ufl
import dolfinx
import numpy as np
import pyvista
comm = MPI.COMM_WORLD
pyvista.OFF_SCREEN = False
plot_sol = True
Define a Python function that returns the constant value
class ConstantFun:
def init(self):
self.myval = 0
def __eval__(self, x):
self.values = np.full(x.shape[1], self.myval) # Assuming x is a 2D array where x.shape[1] gives the number of points
return self.values
The error you're seeing is related to attempting to write the result of the operation uh * 5.0 directly with the xdmf.write_function() method. This operation doesn't return a dolfinx.cpp.fem.Function instance which write_function() expects, but instead, it returns a ufl.algebra.Product object, and hence the method doesn't know how to handle it.
What you should do is to create a new dolfinx.fem.Function by multiplying the vector of uh by 5.0 and then write that function.
This is how you could potentially modify the end of your script to correctly scale your solution and write it to a file:
# ... [previous code remains unchanged] ...
# This part of the code will be modified
scale_factor = 5.0
uh_scaled = dolfinx.fem.Function(V)
uh_scaled.vector[:] = uh.vector * scale_factor
xdmf = dolfinx.io.XDMFFile(MPI.COMM_WORLD, 'uh.xdmf', "w")
xdmf.write_mesh(domain)
xdmf.write_function(uh_scaled, 0)
# ... [rest of the code] ...
Replace the someline with this fixed code. By doing this, you're creating a new with the data of after it has been scaled by the factor of 5. This should resolve the TypeError you were seeing, as is now a instance, which is compatible with the method.
User
Assistant
The issue with the code you have provided is that the dolfinx.fem.Function constructor is not being called correctly. In the following line:
uh_scaled = dolfinx.fem.Function(domain)
The Function constructor expects to receive a FunctionSpace object, but you are passing the domain (which is a dolfinx.mesh.Mesh object). This is why you are seeing a TypeError about incompatible constructor arguments. You need to change this line so that the function space is passed to the constructor rather than the mesh . Here's the corrected line:
User
from mpi4py import MPI
from petsc4py import PETSc
from petsc4py.PETSc import ScalarType
import ufl
import dolfinx
import numpy as np
import pyvista
comm = MPI.COMM_WORLD
pyvista.OFF_SCREEN = False
plot_sol = True
Define a Python function that returns the constant value
Assistant
It seems there's a mistake in the code where it tries to use loc_scaled.set(loc). This should be loc_scaled.copy(loc) instead, because set is used to set all values in the vector to a scalar value, while copy is used to copy the contents of one vector to another.
Here is the correct version of the scaling operation:
with uh.vector.localForm() as loc, uh_scaled.vector.localForm() as loc_scaled:
loc_scaled.copy(loc) # Correct method to copy vector data
loc_scaled.scale(scale_factor)
This correction should fix the TypeError you're experiencing.
To recap, the modified part of your script should look like this:
# ... [previous code remains unchanged] ...
# Scale the solution and write to a file
uh_scaled = dolfinx.fem.Function(V)
scale_factor = 100.0
with uh.vector.localForm() as loc, uh_scaled.vector.localForm() as loc_scaled:
loc_scaled.copy(loc) # Use copy instead of set
loc_scaled.scale(scale_factor)
xdmf = dolfinx.io.XDMFFile(MPI.COMM_WORLD, 'uh_scaled.xdmf', "w")
xdmf.write_mesh(domain)
xdmf.write_function(uh_scaled, 0)
# ... [rest of the code] ...
User
from mpi4py import MPI
from petsc4py import PETSc
from petsc4py.PETSc import ScalarType
import ufl
import dolfinx
import numpy as np
import pyvista
Assistant
To display two different plots for uh and uh_scaled on the same figure using PyVista, you can create two separate UnstructuredGrid objects, one for each function, and then add them to the same object. Since you want to show them in the same figure, you can use separate viewports or you can overlay them in the same viewport depending on your preferences.
Source term
f = dolfinx.fem.Constant(domain, dolfinx.default_scalar_type(-6))
Bilinear and Linear forms
a = ufl.dot(ufl.grad(u), ufl.grad(v)) * ufl.dx
L = f * v * ufl.dx
from dolfinx.fem.petsc import LinearProblem
problem = LinearProblem(
a, L, bcs=[bc],
petsc_options={"ksp_type": "preonly", "pc_type": "lu"}
)
uh = problem.solve()
if plot_sol is True:
u_topology, u_cell_types, u_geometry = dolfinx.plot.vtk_mesh(V)
u_grid = pyvista.UnstructuredGrid(u_topology, u_cell_types, u_geometry)
u_grid.point_data["u"] = uh.x.array.real
u_grid.set_active_scalars("u")
u_plotter = pyvista.Plotter()
u_plotter.add_mesh(u_grid, show_edges=True)
u_plotter.view_xy()
if not pyvista.OFF_SCREEN:
u_plotter.show()
Function
uh
uh_scaled
dolfinx.cpp.fem.Function
write_function
from mpi4py import MPI
from petsc4py import PETSc
from petsc4py.PETSc import ScalarType
import ufl
import dolfinx
import numpy as np
import pyvista
comm = MPI.COMM_WORLD
pyvista.OFF_SCREEN = False
plot_sol = True
Define a Python function that returns the constant value
class ConstantFun:
def init(self):
self.myval = 0
def __eval__(self, x):
self.values = np.full(x.shape[1], self.myval) # Assuming x is a 2D array where x.shape[1] gives the number of points
return self.values
if plot_sol is True:
u_topology, u_cell_types, u_geometry = dolfinx.plot.vtk_mesh(V)
u_grid = pyvista.UnstructuredGrid(u_topology, u_cell_types, u_geometry)
u_grid.point_data["u"] = uh.x.array.real
u_grid.set_active_scalars("u")
u_plotter = pyvista.Plotter()
u_plotter.add_mesh(u_grid, show_edges=True)
u_plotter.view_xy()
if not pyvista.OFF_SCREEN:
u_plotter.show()
Traceback (most recent call last):
File "/home/michelangelo/Ongoing.Projects/NGVU2/mytests/xdmf/fun_in_xdmf.py", line 63, in
uh_scaled = dolfinx.fem.Function(domain)
File "/usr/lib/petsc/lib/python3/dist-packages/dolfinx/fem/function.py", line 302, in init
self._cpp_object = functiontype(dtype)(V._cpp_object)
TypeError: init(): incompatible constructor arguments. The following argument types are supported:
1. dolfinx.cpp.fem.Function_float64(arg0: dolfinx::fem::FunctionSpace)
2. dolfinx.cpp.fem.Function_float64(arg0: dolfinx::fem::FunctionSpace, arg1: dolfinx::la::Vector<double, std::vector<double, std::allocator > >)
Invoked with: <dolfinx.cpp.mesh.Mesh_float64 object at 0x7fdc1c3769d0>
Did you forget to #include <pybind11/stl.h>? Or <pybind11/complex.h>,
<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic
conversions are optional and require extra headers to be included
when compiling your pybind11 module.
V
Function
domain
uh_scaled = dolfinx.fem.Function(V)
Additionally, when you want to scale the function uh by the scale_factor, you should assign the scaled values to the .vector attribute of the uh_scaled function. Here's how you should modify the code for scaling and assigning:
scale_factor = 100.0
with uh.vector.localForm() as loc, uh_scaled.vector.localForm() as loc_scaled:
loc_scaled.scale(scale_factor)
Finally, update the part of your script where the XDMF file is written with the scaled function and the rest of the code that remains unchanged; your full implementation will look like this:
# ... [previous code up to the solution] ...
uh = problem.solve()
# Creating a scaled version of the solution
uh_scaled = dolfinx.fem.Function(V)
scale_factor = 100.0
with uh.vector.localForm() as loc, uh_scaled.vector.localForm() as loc_scaled:
loc_scaled.set(loc)
loc_scaled.scale(scale_factor)
xdmf = dolfinx.io.XDMFFile(MPI.COMM_WORLD, 'uh_scaled.xdmf', "w")
xdmf.write_mesh(domain)
xdmf.write_function(uh_scaled, 0)
# ... [rest of the code for visualization] ...
Make sure to replace your original scaling and XDMF writing code block with the corrected version as shown above. This should fix your issues and allow your script to run correctly.
class ConstantFun:
def init(self):
self.myval = 0
def __eval__(self, x):
self.values = np.full(x.shape[1], self.myval) # Assuming x is a 2D array where x.shape[1] gives the number of points
return self.values
f = dolfinx.fem.Constant(domain, dolfinx.default_scalar_type(-6))
Bilinear and Linear forms
a = ufl.dot(ufl.grad(u), ufl.grad(v)) * ufl.dx
L = f * v * ufl.dx
from dolfinx.fem.petsc import LinearProblem
problem = LinearProblem(
a, L, bcs=[bc],
petsc_options={"ksp_type": "preonly", "pc_type": "lu"}
)
uh = problem.solve()
uh_scaled = dolfinx.fem.Function(V)
scale_factor = 100.0
with uh.vector.localForm() as loc, uh_scaled.vector.localForm() as loc_scaled:
loc_scaled.set(loc)
loc_scaled.scale(scale_factor)
michelangelo@hp:~/Ongoing.Projects/NGVU2/mytests/xdmf$ python3 fun_in_xdmf.py
Traceback (most recent call last):
File "/home/michelangelo/Ongoing.Projects/NGVU2/mytests/xdmf/fun_in_xdmf.py", line 66, in
loc_scaled.set(loc)
File "PETSc/Vec.pyx", line 931, in petsc4py.PETSc.Vec.set
File "PETSc/PETSc.pyx", line 96, in petsc4py.PETSc.asScalar
TypeError: must be real number, not petsc4py.PETSc.Vec
Simply replace the scaling and writing block in your code with the above corrected snippet, and your script should run without that particular error.
comm = MPI.COMM_WORLD
pyvista.OFF_SCREEN = False
plot_sol = True
Define a Python function that returns the constant value
class ConstantFun:
def init(self):
self.myval = 0
def __eval__(self, x):
self.values = np.full(x.shape[1], self.myval) # Assuming x is a 2D array where x.shape[1] gives the number of points
return self.values
f = dolfinx.fem.Constant(domain, dolfinx.default_scalar_type(-6))
Bilinear and Linear forms
a = ufl.dot(ufl.grad(u), ufl.grad(v)) * ufl.dx
L = f * v * ufl.dx
from dolfinx.fem.petsc import LinearProblem
problem = LinearProblem(
a, L, bcs=[bc],
petsc_options={"ksp_type": "preonly", "pc_type": "lu"}
)
uh = problem.solve()
uh_scaled = dolfinx.fem.Function(V)
scale_factor = 1.e3
with uh.vector.localForm() as loc, uh_scaled.vector.localForm() as loc_scaled:
loc.copy(loc_scaled)
loc_scaled.scale(scale_factor)
if plot_sol is True:
u_topology, u_cell_types, u_geometry = dolfinx.plot.vtk_mesh(V)
u_grid = pyvista.UnstructuredGrid(u_topology, u_cell_types, u_geometry)
u_grid.point_data["u"] = uh.x.array.real
u_grid.set_active_scalars("u")
u_plotter = pyvista.Plotter()
u_plotter.add_mesh(u_grid, show_edges=True)
u_plotter.view_xy()
if not pyvista.OFF_SCREEN:
u_plotter.show()
Now it works but i need to have two different plot on the same figure, one for uh and the other for uh_scaled
Plotter
Here is an example of how to modify your existing code to plot both uh and uh_scaled in separate viewports within the same figure:
# ... [previous code remains unchanged] ...
if plot_sol is True:
# Create the first plot for 'uh'
u_topology, u_cell_types, u_geometry = dolfinx.plot.vtk_mesh(V)
u_grid = pyvista.UnstructuredGrid(u_topology, u_cell_types, u_geometry)
u_grid.point_data["u"] = uh.x.array.real
u_grid.set_active_scalars("u")
# Create the second plot for 'uh_scaled'
uh_scaled_topology, uh_scaled_cell_types, uh_scaled_geometry = dolfinx.plot.vtk_mesh(V)
uh_scaled_grid = pyvista.UnstructuredGrid(uh_scaled_topology, uh_scaled_cell_types, uh_scaled_geometry)
uh_scaled_grid.point_data["u_scaled"] = uh_scaled.x.array.real
uh_scaled_grid.set_active_scalars("u_scaled")
# Create a single plotter with two viewports
multi_plotter = pyvista.Plotter(shape=(1, 2))
# Add the original 'uh' plot to the first viewport
multi_plotter.subplot(0, 0)
multi_plotter.add_text("uh", font_size=10)
multi_plotter.add_mesh(u_grid, show_edges=True)
# Add the scaled 'uh_scaled' plot to the second viewport
multi_plotter.subplot(0, 1)
multi_plotter.add_text("uh_scaled", font_size=10)
multi_plotter.add_mesh(uh_scaled_grid, show_edges=True)
# Display the multi-plot
multi_plotter.view_xy()
if not pyvista.OFF_SCREEN:
multi_plotter.show()
This code assumes you want to plot uh on the left and uh_scaled on the right within a single figure with two viewports. Adjust the subplot calls accordingly if you want a different layout.
If you prefer to overlay the plots within the same viewport, you can adjust the code to add both meshes to a single Plotter and control the coloring separately using different scalars. You'll also need to manage the camera positioning and other aspects to ensure both plots are visible and distinguishable.