Skip to content

Commit

Permalink
add Rectification process #25
Browse files Browse the repository at this point in the history
  • Loading branch information
Ali Elarif committed Sep 9, 2022
1 parent edcd4e0 commit b711a1c
Show file tree
Hide file tree
Showing 7 changed files with 133 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -99,22 +99,17 @@ def CompressSolution(self, CorrelationOperator, reducedOrderBasis):
reducedOrderBasis : np.ndarray
of size (numberOfModes, numberOfDOFs)
"""

numberOfModes = reducedOrderBasis.size[0]

globalScalarProduct = PETSc.Vec().create()
globalScalarProduct.setSizes(numberOfModes)
globalScalarProduct.setFromOptions()

for time, solution in self.solution.items():
ur,uc = reducedOrderBasis.createVecs()

matVecProduct =solution.to_petsc().vec().copy()
CorrelationOperator.mult(solution.to_petsc().vec(), matVecProduct)
for time, solution in self.solution.items():

reducedOrderBasis.mult(matVecProduct, globalScalarProduct)
CorrelationOperator.mult(solution.to_petsc().vec(), ur)

self.compressedSol[time] = globalScalarProduct
reducedOrderBasis.mult(ur, uc)

self.compressedSol[time] = uc

self.compressedSol = dict(sorted(self.compressedSol.items(), key=lambda x: x[0]))


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,22 @@
print(" STEP II. 0: start Online nirb ")
print("-----------------------------------")

## Parameters
## Parameter
dimension=2 #dimension spatial domain
Method="POD" #POD or Greedy
Rectification=True #True with Rectification post-process (Coarse Snapshots required) or 0 without
ComputingError=True # True will take more time for compution direct FE solution in fine mesh
export = True # True will save the NIRB result and interpolation of coarse solution in fine mesh
toolboxesOptions='heat'
modelfile={'heat':'square/square', 'fluid':'lid-driven-cavity/cfd2d'}
order = 1

if len(sys.argv)==3:
nbeOfInitSnapshots = int(sys.argv[1])
Rectification = int(sys.argv[2])
else :
nbeOfInitSnapshots = 10
Rectification = 0 # 1 with Rectification post-process (Coarse Snapshots required) or 0 without

# fineness of two grids
H = 0.1 # CoarseMeshSize
h = H**2 # fine mesh size
Expand Down Expand Up @@ -84,7 +91,7 @@
numberOfNodes = FineMesh.numGlobalPoints()
print("Fine Mesh --> Number of nodes : ", numberOfNodes)

if Rectification :
if Rectification==1 :
# define the coarse toolboxes and mesh
tbCoarse = setToolbox(H, geo_path, model, dim=dimension, order=order,type_tb=toolboxesOptions)
CoarseMesh = tbCoarse.mesh()
Expand All @@ -96,10 +103,6 @@
generate snapshots
--------------------------------------
"""
if len(sys.argv)==2:
nbeOfInitSnapshots = int(sys.argv[1])
else :
nbeOfInitSnapshots = 10
nev =nbeOfInitSnapshots
print("-----------------------------------")
print(" STEP I. 0: start init ")
Expand Down Expand Up @@ -144,6 +147,16 @@
nev = reducedOrderBasisU.size[0]
print("number of modes: ", nev)

if Rectification==1:
## interpolate coarse snapshots in fine mesh
interpOper = createInterpolator(tbCoarse, tbFine, type_tb=toolboxesOptions)
coarseSnapInterpList = []
for snap in coarseSnapList :
coarseSnapInterpList.append(interpOper.interpolate(snap))
RectificationMat = SRB.Rectification(coarseSnapInterpList, fineSnapList, l2ScalarProducMatrix, reducedOrderBasisU)



### Add basis to collectionProblemData
# collectionProblemData.AddReducedOrderBasis("U", reducedOrderBasisU)
# # collectionProblemData.CompressSolutions("U", l2ScalarProducMatrix) #Mass matrix
Expand All @@ -162,6 +175,10 @@
SavePetscArrayBin(file, h1ScalarProducMatrix.mat())
file="reducedBasisU.dat"
SavePetscArrayBin(file, reducedOrderBasisU)
if Rectification==1:
file="rectification.dat"
SavePetscArrayBin(file, RectificationMat)


## Ortho basis verification
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,16 @@
## Parameters
dimension=2 #dimension spatial domain
Method="POD" #POD or Greedy
Rectification=0 #1 with Rectification post-process (Coarse Snapshots required) or 0 without
ComputingError=True # 1 will take more time for compution direct FE solution in fine mesh
ComputingError=1 # 1 will take more time for compution direct FE solution in fine mesh
export = True # True will save the NIRB result and interpolation of coarse solution in fine mesh
toolboxesOptions='heat'
modelfile={'heat':'square/square', 'fluid':'lid-driven-cavity/cfd2d'}
order = 1

if len(sys.argv)==2:
Rectification = int(sys.argv[1])
else :
Rectification = 0 # 1 with Rectification post-process (Coarse Snapshots required) or 0 without
# fineness of two grids
H = 0.1 # CoarseMeshSize
h = H**2 # fine mesh size
Expand Down Expand Up @@ -103,8 +107,14 @@
l2ScalarProducMatrix = LoadPetscArrayBin(filename)
filename= dataFolder + "stiffnessMatrix.dat"
h1ScalarProducMatrix = LoadPetscArrayBin(filename)
if Rectification :
filename= dataFolder + "rectification.dat"
RectificationMat = LoadPetscArrayBin(filename)
RectificationMat.assemble()

l2ScalarProducMatrix.assemble()
h1ScalarProducMatrix.assemble()

"""
-----------------------------------------------------------------
Get coarse solution and project it on fine mesh
Expand Down Expand Up @@ -137,8 +147,14 @@

## Get new reconstructed solution in PETSc format
resPETSc = Xh.element().to_petsc()
reducedOrderBasisU.multTranspose(newCompressedSol[0], resPETSc.vec())

if Rectification==1:
coef = newCompressedSol[0].copy()
RectificationMat.mult(newCompressedSol[0],coef)
reducedOrderBasisU.multTranspose(coef, resPETSc.vec())
print("Solution computed with Rectification process ")
else :
reducedOrderBasisU.multTranspose(newCompressedSol[0], resPETSc.vec())

##################################################
# Save Online data for vizualisation
##################################################
Expand All @@ -158,7 +174,7 @@
# ONLINE ERRORS
##################################################

if ComputingError :
if ComputingError==1 :

print("-----------------------------------")
print(" STEP II. 3: Compute online errors ")
Expand All @@ -183,7 +199,11 @@
error.append(diffSolve.norm(PETSc.NormType.NORM_INFINITY))

# error = np.array(error)
filename = 'nirb_error.txt'
if Rectification==1:
filename = 'nirb_error_rectification.err'
else :
filename = 'nirb_error.err'

WriteVecAppend(filename, error)
# np.savetxt(filename, error)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,7 @@ def initproblem(numberOfInitSnapshot, Dmu, tbFine, tbCoarse=None, type_tb='heat'
fineSnapList.append(tbFine.fieldTemperature())
coarseSnapList.append(tbCoarse.fieldTemperature())
else :
for param in range(numberOfInitSnapshot):

dicparam = dict([ (mu.parameterName(i), mu(i)/float(param+0.001)) for i in range(mu.size())])

mu.setParameters(dicparam)
for mu in vector_mu :

if feelpp.Environment.isMasterRank():
print(f"Running simulation with mu = {mu}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,50 @@ def TruncatedEVDPetscMat(matrix, epsilon = None, nbModes = None):

return eigenValues[0:nbModes], eigenVectors[0:nbModes]

def Rectification(CoarseSnaps, FineSnaps, correlationMatrix, reducedBasis):
""" Compute the rectification matrix R given by :
R[i,j] = B_h*(B_H)^-1
with B_h[i,j] = <U_h(s_i),\phi_j >
and B_H[i,j] = <U_H(s_i),\phi_j >
"""
nbModes = reducedBasis.size[0]

BH = np.zeros((nbModes,nbModes))
Bh = BH.copy()


R = PETSc.Mat().createDense(size=(nbModes,nbModes))
R.setFromOptions()
R.setUp()
R.assemble()

lfine = []
lcoarse = []

Udof,Usnap = reducedBasis.createVecs()
reducedBasis.assemble()

for i in range(nbModes):
lfine.append(FineSnaps[i].to_petsc().vec())
lcoarse.append(CoarseSnaps[i].to_petsc().vec())

CM = correlationMatrix.mat()

for i in range(nbModes):
CM.mult(lfine[i],Udof)
reducedBasis.mult(Udof,Usnap)
Bh[i,:] = Usnap[:]

CM.mult(lcoarse[i],Udof)
reducedBasis.mult(Udof,Usnap)
BH[i,:] = Usnap[:]


lambd=1e-10 #regularization (AT@A +lambda I_d)^-1
for i in range(nbModes):
R[i,:]=(np.linalg.inv(BH.transpose()@BH+lambd*np.eye(nbModes))@BH.transpose()@Bh[:,i])

return R



Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/bin/bash

dataFolder="~/feelppdb/nirb/heat"

removeOldDatas="rm -r ${dataFolder}"


Nsnap="2 4 8"
Rectification=0
biorthonormal=0

for n in $Nsnap;
do

Ns=$n

offline="python3 NIRBOffline.py ${Ns} ${Rectification}"
online="python3 NIRBOnline.py ${Rectification}"

${offline}
${online}

echo " ------------------------------------------ "
echo " Restarting program with Ns = : $Ns "
echo " ------------------------------------------ "


done
exit


2 changes: 1 addition & 1 deletion src/poc-1/tests/Modules/Sorbonne/NIRBOnline.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
Method="Greedy" #POD or Greedy
Rectification=0 #1 with Rectification post-process (Coarse Snapshots required) or 0 without
ComputingError=1 # 1 if the fine solution is provided
SavingApproximation=1 #if NIRB approximation saved
SavingApproximation=0 #if NIRB approximation saved

## Fine and coarse Solution files name
#coarseName="snapshotH0.vtu"
Expand Down

0 comments on commit b711a1c

Please sign in to comment.