|
1 | 1 | # to run: mpirun -np 4 python mpi_example.py |
2 | 2 | import sys |
| 3 | +from typing import Literal |
3 | 4 | from mpi4py import MPI |
4 | 5 | import numpy as np |
5 | 6 | from netCDF4 import Dataset |
| 7 | + |
| 8 | +format: Literal[ |
| 9 | + 'NETCDF4', |
| 10 | + 'NETCDF4_CLASSIC', |
| 11 | + 'NETCDF3_CLASSIC', |
| 12 | + 'NETCDF3_64BIT_OFFSET', |
| 13 | + 'NETCDF3_64BIT_DATA' |
| 14 | +] |
6 | 15 | if len(sys.argv) == 2: |
7 | | - format = sys.argv[1] |
| 16 | + format = sys.argv[1] # type: ignore |
8 | 17 | else: |
9 | 18 | format = 'NETCDF4_CLASSIC' |
| 19 | + |
10 | 20 | rank = MPI.COMM_WORLD.rank # The process ID (integer 0-3 for 4-process run) |
11 | 21 | if rank == 0: |
12 | | - print('Creating file with format {}'.format(format)) |
| 22 | + print('Creating file with format {}'.format(format)) |
13 | 23 | nc = Dataset('parallel_test.nc', 'w', parallel=True, comm=MPI.COMM_WORLD, |
14 | | - info=MPI.Info(),format=format) |
| 24 | + info=MPI.Info(), format=format) |
15 | 25 | # below should work also - MPI_COMM_WORLD and MPI_INFO_NULL will be used. |
16 | 26 | #nc = Dataset('parallel_test.nc', 'w', parallel=True) |
17 | 27 | d = nc.createDimension('dim',4) |
18 | 28 | v = nc.createVariable('var', np.int32, 'dim') |
19 | 29 | v[rank] = rank |
| 30 | + |
20 | 31 | # switch to collective mode, rewrite the data. |
21 | 32 | v.set_collective(True) |
22 | 33 | v[rank] = rank |
23 | 34 | nc.close() |
| 35 | + |
24 | 36 | # reopen the file read-only, check the data |
25 | 37 | nc = Dataset('parallel_test.nc', parallel=True, comm=MPI.COMM_WORLD, |
26 | | - info=MPI.Info()) |
| 38 | + info=MPI.Info()) |
27 | 39 | assert rank==nc['var'][rank] |
28 | 40 | nc.close() |
| 41 | + |
29 | 42 | # reopen the file in append mode, modify the data on the last rank. |
30 | 43 | nc = Dataset('parallel_test.nc', 'a',parallel=True, comm=MPI.COMM_WORLD, |
31 | | - info=MPI.Info()) |
| 44 | + info=MPI.Info()) |
32 | 45 | if rank == 3: v[rank] = 2*rank |
33 | 46 | nc.close() |
| 47 | + |
34 | 48 | # reopen the file read-only again, check the data. |
35 | 49 | # leave out the comm and info kwargs to check that the defaults |
36 | 50 | # (MPI_COMM_WORLD and MPI_INFO_NULL) work. |
|
0 commit comments