dafoam_matdiff.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 """
3 Compare values in two different Petsc matrices and identify the max relative/absolute error
4 """
5 
6 import os, sys
7 import argparse
8 import petsc4py
9 
10 petsc4py.init(sys.argv)
11 from petsc4py import PETSc
12 
13 
14 def evalMatDiff(mat1, mat2, mode, diffTol=1e-30):
15  # the relative error is computed as
16  # (mat1-mat2)/mat1
17 
18  # read mat 1
19  jacMat1 = PETSc.Mat().create(PETSc.COMM_WORLD)
20  viewer = PETSc.Viewer().createBinary(mat1, comm=PETSc.COMM_WORLD)
21  jacMat1.load(viewer)
22 
23  # read mat 2
24  jacMat2 = PETSc.Mat().create(PETSc.COMM_WORLD)
25  viewer = PETSc.Viewer().createBinary(mat2, comm=PETSc.COMM_WORLD)
26  jacMat2.load(viewer)
27 
28  Istart, Iend = jacMat1.getOwnershipRange()
29 
30  # absolute error
31  jacMatDiff = PETSc.Mat().create(PETSc.COMM_WORLD)
32  viewer = PETSc.Viewer().createBinary(mat1, comm=PETSc.COMM_WORLD)
33  jacMatDiff.load(viewer)
34  jacMatDiff.axpy(-1.0, jacMat2, structure=jacMatDiff.Structure.DIFFERENT_NONZERO_PATTERN)
35 
36  maxDiff = -1.0e30
37  maxVal1 = -1.0e30
38  maxVal2 = -1.0e30
39  maxRowI = -1.0e30
40  maxColI = -1.0e30
41  l2norm = 0.0
42  foundDiff = 0
43  for i in range(Istart, Iend):
44  rowVals = jacMatDiff.getRow(i)
45  nCols = len(rowVals[0])
46  for j in range(nCols):
47  colI = rowVals[0][j]
48  valDiff = abs(rowVals[1][j])
49  valRef = abs(jacMat1[i, colI])
50  if mode == "rel":
51  valError = valDiff / (valRef + diffTol)
52  elif mode == "abs":
53  valError = valDiff
54  else:
55  print("mode not supported! Options are: abs or rel")
56  l2norm = l2norm + valDiff ** 2
57  if abs(valError) > diffTol:
58  if abs(valError) > maxDiff:
59  foundDiff = 1
60  maxDiff = valError
61  maxRowI = i
62  maxColI = colI
63  maxVal1 = jacMat1.getValue(i, colI)
64  maxVal2 = jacMat2.getValue(i, colI)
65 
66  if foundDiff == 1:
67  print("L2Norm: %20.16e" % l2norm)
68  print("MaxDiff: %20.16e" % maxDiff)
69  print("MaxVal1: %20.16e" % maxVal1)
70  print("MaxVal2: %20.16e" % maxVal2)
71  print("MaxrowI: %d" % maxRowI)
72  print("MaxcolI: %d" % maxColI)
73  return maxDiff
74  else:
75  print("Two matrices are exactly same with tolerance: %e" % diffTol)
76  return 0.0, 0.0
77 
78 
79 if __name__ == "__main__":
80  print("\nUsage: python dafoam_matreldiff.py matName1 matName2 mode")
81  print("Example python dafoam_matreldiff.py dRdWT1.bin dRdWT2.bin abs\n")
82  evalMatDiff(sys.argv[1], sys.argv[2], sys.argv[3])
dafoam_matdiff.evalMatDiff
def evalMatDiff(mat1, mat2, mode, diffTol=1e-30)
Definition: dafoam_matdiff.py:14