The following works for me
import basix.ufl
import dolfinx
import dolfinx.fem
import dolfinx.io
import dolfinx.mesh
import mpi4py.MPI
import numpy as np
# Create mesh
mesh = dolfinx.mesh.create_rectangle(
mpi4py.MPI.COMM_WORLD, [np.array([0.0, 0.0]), np.array([1.0, 1.0])], [10, 10], dolfinx.mesh.CellType.triangle)
# Mark a boundary
left_boundary_entities = dolfinx.mesh.locate_entities_boundary(
mesh, mesh.topology.dim - 1, lambda x: np.isclose(x[0], 0.0))
# Create the Taylor-Hood function space
P2 = basix.ufl.element("Lagrange", mesh.basix_cell(), 2, shape=(mesh.geometry.dim,))
P1 = basix.ufl.element("Lagrange", mesh.basix_cell(), 1)
TH = basix.ufl.mixed_element([P2, P1])
W = dolfinx.fem.functionspace(mesh, TH)
# Assign BC on the second component of the velocity space
V, _ = W.sub(0).collapse()
V1, _ = V.sub(1).collapse()
bc_value = dolfinx.fem.Function(V1)
bc_value.interpolate(lambda x: 1 + x[1])
left_boundary_dofs = dolfinx.fem.locate_dofs_topological(
(W.sub(0).sub(1), V1), mesh.topology.dim - 1, left_boundary_entities)
bc = dolfinx.fem.dirichletbc(bc_value, left_boundary_dofs, W.sub(0).sub(1))
# Apply BC
solution = dolfinx.fem.Function(W)
dolfinx.fem.set_bc(solution.x.array, [bc])
# Export for visualization
with dolfinx.io.VTXWriter(mesh.comm, "velocity.bp", solution.sub(0).collapse()) as vtx_file:
vtx_file.write(0.0)
with dolfinx.io.VTXWriter(mesh.comm, "pressure.bp", solution.sub(1).collapse()) as vtx_file:
vtx_file.write(0.0)