fork download
  1. import mpi.MPI;
  2. import java.util.Arrays;
  3.  
  4. public class MPIAHCalculation {
  5.  
  6. public static void main(String[] args) {
  7. MPI.Init(args);
  8.  
  9. int rank = MPI.COMM_WORLD.Rank();
  10. int size = MPI.COMM_WORLD.Size();
  11.  
  12. final int H = 100; // Assume H is predefined.
  13. int[][] MX = new int[H][H];
  14. int[][] MR = new int[H][H];
  15. int[] Z = new int[H];
  16. int[] C = new int[H];
  17. int D = 0;
  18.  
  19. if (rank == 0) {
  20. // Initialize data in rank 0
  21. MX = fillMatrix(H, H, 1);
  22. MR = fillMatrix(H, H, 1);
  23. Z = fillVector(H, 1);
  24. C = fillVector(H, 1);
  25. D = 5; // Example constant
  26. }
  27.  
  28. // Broadcast matrices and constants to all processes
  29. for (int i = 0; i < H; i++) {
  30. MPI.COMM_WORLD.Bcast(MX[i], 0, H, MPI.INT, 0);
  31. MPI.COMM_WORLD.Bcast(MR[i], 0, H, MPI.INT, 0);
  32. }
  33. MPI.COMM_WORLD.Bcast(Z, 0, H, MPI.INT, 0);
  34. MPI.COMM_WORLD.Bcast(C, 0, H, MPI.INT, 0);
  35. MPI.COMM_WORLD.Bcast(new int[]{D}, 0, 1, MPI.INT, 0);
  36.  
  37. // Divide work among processes
  38. int rowsPerProcess = H / size;
  39. int startRow = rank * rowsPerProcess;
  40. int endRow = (rank == size - 1) ? H : startRow + rowsPerProcess;
  41.  
  42. // Compute AH locally
  43. int[] localAH = new int[endRow - startRow];
  44. int c = Arrays.stream(C).min().orElse(Integer.MAX_VALUE);
  45.  
  46. for (int i = startRow; i < endRow; i++) {
  47. localAH[i - startRow] = c * Z[i] + D * matrixRowDot(MX, MR, i);
  48. }
  49.  
  50. // Gather results at rank 0
  51. int[] AH = null;
  52. if (rank == 0) {
  53. AH = new int[H];
  54. }
  55. MPI.COMM_WORLD.Gather(localAH, 0, endRow - startRow, MPI.INT, AH, 0, rowsPerProcess, MPI.INT, 0);
  56.  
  57. if (rank == 0) {
  58. System.out.println("AH: " + Arrays.toString(AH));
  59. }
  60.  
  61. MPI.Finalize();
  62. }
  63.  
  64. // Utility method to fill a matrix with a specific value
  65. public static int[][] fillMatrix(int rows, int cols, int value) {
  66. int[][] matrix = new int[rows][cols];
  67. for (int i = 0; i < rows; i++) {
  68. Arrays.fill(matrix[i], value);
  69. }
  70. return matrix;
  71. }
  72.  
  73. // Utility method to fill a vector with a specific value
  74. public static int[] fillVector(int size, int value) {
  75. int[] vector = new int[size];
  76. Arrays.fill(vector, value);
  77. return vector;
  78. }
  79.  
  80. // Compute dot product of matrix row and vector
  81. public static int matrixRowDot(int[][] matrix1, int[][] matrix2, int row) {
  82. int sum = 0;
  83. for (int i = 0; i < matrix1[row].length; i++) {
  84. sum += matrix1[row][i] * matrix2[i][row]; // Adjusted dot product logic
  85. }
  86. return sum;
  87. }
  88. }
  89.  
Success #stdin #stdout #stderr 0.3s 40772KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "import mpi.MPI"
Execution halted