Attempt to find max value on mesh in parallel

Hi everyone,

I currently have some code where I am trying to find the maximum and minimum value of a function on the mesh after a certain amount of time and output these values to a txt file, the greatly simplified code is shown below:
from dolfin import *

mesh = UnitSquareMesh(10,10)
space = FunctionSpace(mesh, ‘P’, 1)
T = project(Expression(“10x[0]+100x[1]”, degree=2), Space)
max_T = max(T.vector())
print(“T_max is:”, max_T)

with open(“test.txt”, ‘a’) as f:
f.write(str(max_T))

In my full code, because the system I am modelling is complex, I run this system in parallel via mpirun -n 10 python3 code.py. However, when this finishes, I obtain something like this in my terminal:

T_max is: 1508.040424
T_max is: 1501.694996
T_max is: 1553.542122

And all of these max values are output to my txt file where I only wanted the maximum to be sent to the txt file. Is there a way for a loop to be constructed over all different parallel runs in order for the ‘true’ max value to be selected and output to the txt file?

Thanks in advance

Dear @CoE2845,
Next time, please encapsulate your code with 3x` to ensure proper formatting.
You simply need to use MPI communicators for the problem at hand:

from dolfin import *
from mpi4py import MPI
mesh = UnitSquareMesh(10,10)
Space = FunctionSpace(mesh, "CG", 1)
T = project(Expression("10*x[0]+100*x[1]", degree=2), Space)
max_T = max(T.vector())

print("T_max is : {0:.2e} on Proc {1:d}".format(max_T, MPI.COMM_WORLD.rank))
MPI.COMM_WORLD.barrier()
max_T = mesh.mpi_comm().allreduce(max_T, op=MPI.MAX)
if MPI.COMM_WORLD.rank ==0:
    with open("test.txt", "w") as f:
        f.write(str(max_T))
    print("Global max is {0:.2e} on Proc {1:d}".format(max_T, MPI.COMM_WORLD.rank))