From 17779556b35947f391a86e917d1eed2184e6925f Mon Sep 17 00:00:00 2001 From: Ali Elarif Date: Thu, 25 Aug 2022 18:34:14 +0200 Subject: [PATCH] add init implementation of nirb method with feelpp #25 --- .../src/Mordicus/Core/Containers/Solution.py | 2 +- .../Containers/SolutionStructure/FeelppSol.py | 338 ++++++++++++++++ .../Cemosis/DataCompressors/NIRBOffline.py | 375 ++++++------------ .../Cemosis/DataCompressors/NIRBOnline.py | 333 +++++----------- .../Cemosis/DataCompressors/NIRBinitCase.py | 141 +++---- .../DataCompressors/SnapshotReducedBasis.py | 101 +++++ .../models/heat/square/square.cfg | 44 ++ .../models/heat/square/square.geo | 43 ++ .../models/heat/square/square.json | 108 +++++ .../Mordicus/Modules/Cemosis/IO/StateIO.py | 22 + .../IO/InterpolationOperatorWriter.py | 6 +- .../Modules/sorbonne/IO/numpyToVTKWriter.py | 24 +- .../Mordicus/Modules/sorbonne/MOR/Greedy.py | 2 +- .../DataCompressors/test_NIRBinitCase.py | 39 +- .../tests/Modules/Sorbonne/NIRBOffline.py | 7 +- .../tests/Modules/Sorbonne/NIRBOnline.py | 3 +- .../External/script_donnees_init.edp | 2 +- 17 files changed, 998 insertions(+), 592 deletions(-) create mode 100644 src/poc-1/src/Mordicus/Modules/Cemosis/Containers/SolutionStructure/FeelppSol.py create mode 100644 src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/SnapshotReducedBasis.py create mode 100644 src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/models/heat/square/square.cfg create mode 100644 src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/models/heat/square/square.geo create mode 100644 src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/models/heat/square/square.json create mode 100644 src/poc-1/src/Mordicus/Modules/Cemosis/IO/StateIO.py diff --git a/src/poc-1/src/Mordicus/Core/Containers/Solution.py b/src/poc-1/src/Mordicus/Core/Containers/Solution.py index b0b6f5fc..1d6b10ae 100644 --- a/src/poc-1/src/Mordicus/Core/Containers/Solution.py +++ b/src/poc-1/src/Mordicus/Core/Containers/Solution.py @@ -69,7 +69,7 @@ def AddSnapshot(self, snapshot, time): """ time = float(time) if not len(snapshot.shape) == 1 or not snapshot.shape[0] == self.numberOfDOFs:#pragma: no cover - raise ValueError("Provided numpy array should be a vector of length {}".format(self.numberOfDOFs)) + raise ValueError("Provided numpy array should be a vector of length {}".format(self.numberOfDOFs), snapshot.shape) if time in self.snapshots: print( diff --git a/src/poc-1/src/Mordicus/Modules/Cemosis/Containers/SolutionStructure/FeelppSol.py b/src/poc-1/src/Mordicus/Modules/Cemosis/Containers/SolutionStructure/FeelppSol.py new file mode 100644 index 00000000..f75b328f --- /dev/null +++ b/src/poc-1/src/Mordicus/Modules/Cemosis/Containers/SolutionStructure/FeelppSol.py @@ -0,0 +1,338 @@ +# -*- coding: utf-8 -*- +# +# This file is subject to the terms and conditions defined in +# file 'LICENSE.txt', which is part of this source code package. +# +# + +import os +from mpi4py import MPI +if MPI.COMM_WORLD.Get_size() > 1: # pragma: no cover + os.environ["OMP_NUM_THREADS"] = "1" + os.environ["OPENBLAS_NUM_THREADS"] = "1" + os.environ["MKL_NUM_THREADS"] = "1" + os.environ["VECLIB_MAXIMUM_THREADS"] = "1" + os.environ["NUMEXPR_NUM_THREADS"] = "1" +import numpy as np + +import feelpp +from mpi4py import MPI + + +class FeelppSolution(object): + """ + Class containing a wrapping of element in Feelpp function space + + Attributes + ---------- + solutionName : str + name of the solution field (e.g. "U", "T") + nbeOfComponents : int + number of components of the solution (e.g. 3 for "U" in 3D, or 1 for "T") + numberOfNodes : int + number of nodes for the geometrical support of the solution + numberOfDOFs : int + number of degrees of freedom + solution : feelpp sol + solution in feelpp format + reducedCoeff : dict + dictionary with time indices as keys and a np.ndarray of size (numberOfModes,) containing the coefficients of the reduced solution + """ + + def __init__(self, solutionName, nbeOfComponents, numberOfNodes): + + for attr, typ in zip(["solutionName", "nbeOfComponents", "numberOfNodes"], [str, int, int]): + if not isinstance(locals()[attr], typ):#pragma: no cover + raise TypeError("Attribute {0} should be of type {1}".format(attr, str(typ))) + + self.solutionName = solutionName + self.nbeOfComponents = nbeOfComponents + self.numberOfNodes = numberOfNodes + self.numberOfDOFs = nbeOfComponents * numberOfNodes + self.solution = {} + self.compressedSol = {} + + + def AddSolution(self, solution, time): + """ + Adds a solution at time time + + Parameters + ---------- + snapshot : np.ndarray + of size (numberOfDOFs,) + time : float + time of the snapshot + """ + time = float(time) + # if not len(snapshot.shape) == 1 or not snapshot.shape[0] == self.numberOfDOFs:#pragma: no cover + # raise ValueError("Provided numpy array should be a vector of length {}".format(self.numberOfDOFs), snapshot.shape) + + if time in self.solution.keys(): + print( + "Solution at time " + + str(time) + + " already in solution. Replacing it anyways." + ) # pragma: no cover + + self.solution[time] = solution + + keys = list(self.solution.keys()) + + if len(keys) > 1 and keys[-1] < keys[-2]: + self.solution = dict(sorted(self.solution.items(), key=lambda x: x[0])) + + + + def CompressSolution(self, CorrelationOperator, reducedOrderBasis): + """ + Compress solution using the correlation operator between the snapshots defined by the matrix snapshotCorrelationOperator and reducedOrderBasis + + Parameters + ---------- + CorrelationOperator : feelpp._alg.MatrixSparsedouble + correlation operator between the snapshots + reducedOrderBasis : np.ndarray + of size (numberOfModes, numberOfDOFs) + """ + + numberOfModes = reducedOrderBasis.shape[0] + + for time, solution in self.solution.items(): + + matVecProduct =solution.to_petsc().vec().copy() + CorrelationOperator.mat().mult(solution.to_petsc().vec(), matVecProduct) + + matVecProduct = np.array(matVecProduct) + localScalarProduct = np.dot(reducedOrderBasis, matVecProduct) + globalScalarProduct = np.zeros(numberOfModes) + MPI.COMM_WORLD.Allreduce([localScalarProduct, MPI.DOUBLE], [globalScalarProduct, MPI.DOUBLE]) + + self.compressedSol[time] = globalScalarProduct + + self.compressedSol = dict(sorted(self.compressedSol.items(), key=lambda x: x[0])) + + + def FeelppVecToNumpy(self, vec): + """ + Convert Feelpp function space to numpy format + + Parameters : + vec : feelpp + + Returns + ------- + feelpp function space format + """ + # numberOfNodes + return np.array(vec.to_petsc().vec()) + + def GetSnapshot(self, time): + """ + Returns the snapshot at time time + + Parameters + ---------- + time : float + time at which the snapshot is retrieved + + Returns + ------- + np.ndarray + snapshot + """ + return self.snapshots[time] + + + def GetreducedCoeff(self): + """ + Returns the compressed snapshot at time time + + Parameters + ---------- + time : float + time at which the compressed snapshot is retrieved + + Returns + ------- + np.ndarray + compressed snapshot + """ + return self.compressedSol + + + def GetSolutionName(self): + """ + Returns the name of the solution + + Returns + ------- + str + the name of the solution field + """ + return self.solutionName + + + def GetNbeOfComponents(self): + """ + Returns the number of components of the solution + + Returns + ------- + int + the number of components of the solution + """ + return self.nbeOfComponents + + + def GetNumberOfDofs(self): + """ + Returns the number of degrees of freedom of the solution + + Returns + ------- + int + the number of degrees of freedom of the solution + """ + return self.numberOfDOFs + + + def GetNumberOfNodes(self): + """ + Returns the number of nodes of the solution + + Returns + ------- + int + the number of degrees of nodes of the solution + """ + return self.numberOfNodes + + + def GetSnapshots(self): + """ + Returns the complete snapshots dictionary + + Returns + ------- + dict + the snapshots dictionary of the solution + """ + return self.solution + + + def GetCompressedSnapshots(self): + """ + Returns the complete compressedSnapshots dictionary + + Returns + ------- + dict + the compressed representation of the solution + """ + return self.compressedSnapshots + + + def GetCompressedSnapshotsList(self): + """ + Returns the compressed snapshots in the form of a list + + Returns + ------- + list + list containing the snapshots of the solution + """ + return list(self.compressedSnapshots.values()) + + + def GetNumberOfSnapshots(self): + """ + Returns the number of snapshots + + Returns + ------- + int + the number of snapshots (= time indices) of the solution + """ + return len(list(self.snapshots.keys())) + + + def NumpyVecToFeelpp(self, vec): + """ + Convert numpy vector to Feelpp function space format + + Parameters : + vec : numpy array + + Returns + ------- + feelpp function space format + """ + # numberOfNodes + return + + def RemoveSnapshot(self, time): + """ + Removes the snapshot at time time + + Parameters + ---------- + time : float + time of the snapshot + """ + time = float(time) + + if time in self.snapshots: + del self.snapshots[time] + else: + print("no snapshot at time "+str(time)+" to remove") + + + def RemoveSnapshots(self, timeSequence): + """ + Removes the snapshot at times timeSequence + + Parameters + ---------- + time : list or 1d-np.ndarray of floats + times of the snapshot + """ + for time in timeSequence: + self.RemoveSnapshot(time) + + + + # def UncompressSnapshots(self, reducedOrderBasis): + # """ + # Uncompress snapshots using reducedOrderBasis + + # Parameters + # ---------- + # reducedOrderBasis : np.ndarray + # of size (numberOfModes, numberOfDOFs) + # """ + + # if bool(self.snapshots): + # print("Solution already uncompressed. Replacing it anyway") # pragma: no cover + + # snapshots = {} + + # for time, compressedSnapshot in self.GetCompressedSnapshots().items(): + # snapshots[time] = np.dot(compressedSnapshot, reducedOrderBasis) + + # self.SetSnapshots(snapshots) + + + + def __str__(self): + res = "Solution \n" + res += "Name : " + self.solutionName + "\n" + res += "Dimensionality : " + str(self.nbeOfComponents) + "\n" + if len(self.compressedSol) <= 0: + res += "Not compressed" # pragma: no cover + else: + res += "Compressed" # pragma: no cover + return res + + +# if __name__ == "__main__":# pragma: no cover \ No newline at end of file diff --git a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBOffline.py b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBOffline.py index c50571e3..2e1afa1a 100644 --- a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBOffline.py +++ b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBOffline.py @@ -3,6 +3,9 @@ ## Elise Grosjean ## 01/2021 +from ast import MatMult +from email import parser +from fileinput import filename import os import os.path as osp import glob @@ -13,118 +16,70 @@ import warnings import feelpp +import feelpp.mor as mor +import feelpp.mor.reducedbasis.reducedbasis as FppRb +import feelpp.operators as FppOp +import SnapshotReducedBasis as SRB +from NIRBinitCase import * -from Mordicus.Core.Containers import ProblemData as PD from Mordicus.Core.Containers import CollectionProblemData as CPD -from Mordicus.Core.Containers import Solution as S -from Mordicus.Core.DataCompressors import SnapshotPOD as SP from Mordicus.Core.IO import StateIO as SIO -from Mordicus.Modules.sorbonne.IO import MeshReader as MR -from Mordicus.Modules.Safran.FE import FETools as FT -#from BasicTools.FE import FETools as FT2 -from Mordicus.Modules.sorbonne.IO import VTKSolutionReader as VTKSR -from Mordicus.Modules.sorbonne.IO import FFSolutionReader as FFSR -from Mordicus.Modules.sorbonne.IO import numpyToVTKWriter as NpVTK -from Mordicus.Modules.sorbonne.IO import InterpolationOperatorWriter as IOW -from Mordicus.Modules.sorbonne.MOR import Greedy as GD - - - ## Directories currentFolder=os.getcwd() dataFolder = osp.expanduser("~/feelppdb/nirb/") modelFolder = "StationaryNS/" # or "heat" -""" -# 3D Case -OfflineResuFolder=osp.join(currentFolder,'3Dcase/3DData/FineSnapshots/') #folder for offline resu -FineDataFolder=osp.join(currentFolder,'3Dcase/3DData/FineSnapshots/') #folder for fine snapshots -CoarseDataFolder=osp.join(currentFolder,'3Dcase/3DData/CoarseSnapshots/') #folder for coarse snapshots -FineMeshFolder=osp.join(currentFolder,'3Dcase/3DData/FineMesh/') #folder for fine mesh (needed with Freefem snapshots) -CoarseMeshFolder=osp.join(currentFolder,'3Dcase/3DData/CoarseMesh/') #folder for coarse mesh (needed with Freefem) - -""" -# 2D case - -# externalFolder=osp.join(currentFolder,'models/StationaryNS/External') #FreeFem scripts -# OfflineResuFolder=osp.join(dataFolder,modelFolder,'FineSnapshots/') #folder for offline resu -# FineDataFolder=osp.join(dataFolder,modelFolder,'FineSnapshots/') #folder for fine snapshots -# CoarseDataFolder=osp.join(dataFolder,modelFolder,'CoarseSnapshots/') #folder for coarse snapshots -# FineMeshFolder=osp.join(dataFolder,modelFolder,'FineMesh/') #folder for fine mesh (needed with Freefem snapshots) -# CoarseMeshFolder=osp.join(dataFolder,modelFolder,'CoarseMesh/') #folder for coarse mesh (needed with Freefem) - ## Parameters dimension=2 #dimension spatial domain nbeOfComponentsPrimal = 2 # number of components FieldName="Velocity" #Snapshots fieldname -Format= "FreeFem" # FreeFem or VTK -Method="Greedy" #POD or Greedy +Method="POD" #POD or Greedy Rectification=1 #1 with Rectification post-process (Coarse Snapshots required) or 0 without ## Script Files - Initiate data # Create data (mesh1,mesh2,snapshots,uH) for Sorbonne usecase """ -------------------------------------- - generate snapshots + initialize toolbox -------------------------------------- """ -nbeOfInitSnapshots = 1 +## Current Directories +currentFolder=os.getcwd() -from NIRBinitCase import initproblem -print("-----------------------------------") -print(" STEP I. 0: start init ") -print("-----------------------------------") -modelsFolder = osp.expanduser("~/devel/mordicus/src/poc-1/tests/Modules/Cemosis/DataCompressors/models/") -fineSnapList, coarseSnapList, CoarseMesh, FineMesh = initproblem(nbeOfInitSnapshots, modelsFolder=modelsFolder) -print("-----------------------------------") -print("STEP I.0 (bis): snapshots generated") -print("-----------------------------------") +# model directories +toolboxesOptions='heat' -""" ----------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------- - Definition and initialisation of the problem ----------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------- -""" +modelsFolder = f"{currentFolder}/models/" +modelsFolder = f"{modelsFolder}{toolboxesOptions}" +cfg_path = f"{modelsFolder}/square/square.cfg" +geo_path = f"{modelsFolder}/square/square.geo" +model_path = f"{modelsFolder}/square/square.json" -#print("number of modes: ",nev) +# fineness of two grids +H = 0.1 # CoarseMeshSize +h = H**2 # fine mesh size -time=0.0 -# ---------------------------------------------------------- -# Get number of Snapshots and modes -Nsfine = len(fineSnapList) -Nscoarse = len(coarseSnapList) +# set the feelpp environment +config = feelpp.globalRepository(f"nirb/{toolboxesOptions}") +e=feelpp.Environment(sys.argv, opts = toolboxes_options(toolboxesOptions).add(mor.makeToolboxMorOptions()), config=config) +e.setConfigFile(cfg_path) +order =1 -nev=1 #default value number of modes -if len(sys.argv)>1: - nev=int(sys.argv[1]) +# load model +model = loadModel(model_path) +tbCoarse = setToolbox(H, geo_path, model, order) +tbFine = setToolbox(h, geo_path, model,order) +Dmu = loadParameterSpace(model_path) # ---------------------------------------------------------- -# Get coarse snapshots and coarse mesh if rectification processes -# if Rectification == 1: - # coarseSnapListNp = [] - - # for s in range(Nscoarse): - # fineSnapListNp.append(FeelppToNp(fineSnapList[s])) - # coarseSnapListNp.append(FeelppToNp(coarseSnapList[s])) -# CoarseSnapshotsFile=glob.glob(os.path.join(CoarseDataFolder,"*.txt"))[0] -# FFCoarsetoVTKconvert=FFSR.FFSolutionReader(FieldName,CoarseMeshFileName); -# FFCoarsetoVTKconvert.FFReadToNp(externalFolder,CoarseSnapshotsFile) #create the snapshots with vtu format # ---------------------------------------------------------- +## MESH infos +FineMesh = tbFine.mesh() +CoarseMesh = tbCoarse.mesh() -assert Nsfine>0, " !! no snapshots provided !! " -if len(sys.argv)>1: - assert nev<=Nsfine, " !! To many number of modes, nev must be less than ns !!" -if Rectification == 1 and Nscoarse!=Nsfine: - warnings.warn( "Not the same number of coarse and fine snapshots -> not using the rectification post-process! ") - Rectification = 0 -# ---------------------------------------------------------- -# ---------------------------------------------------------- -## MESH READER ## Fine Mesh reader numberOfNodes = FineMesh.numGlobalPoints() print("Fine Mesh --> Number of nodes : ", numberOfNodes) @@ -134,192 +89,96 @@ numberOfNodes2 = CoarseMesh.numGlobalPoints() print("Coarse Mesh --> Number of nodes : ", numberOfNodes2) +""" +-------------------------------------- + generate snapshots +-------------------------------------- +""" +nbeOfInitSnapshots = 30 +nev =nbeOfInitSnapshots +print("-----------------------------------") +print(" STEP I. 0: start init ") +print("-----------------------------------") -# ---------------------------------------------------------- -# # Interpolation on the fine mesh if rectification post-process -# if Rectification==1: -# option="basictools" #ff, basictools -# if Format == "FreeFem": -# Folder=str(Path(FineMeshFileName).parents[0]) -# stem=str(Path(FineMeshFileName).stem) -# #print(stem[-4:]) -# suffix=str(Path(FineMeshFileName).suffix) -# if stem[-4:]!="GMSH": -# FineMeshFileName = Folder+"/"+stem+"GMSH"+suffix -# Folder=str(Path(CoarseMeshFileName).parents[0]) -# stem=str(Path(CoarseMeshFileName).stem) -# suffix=str(Path(CoarseMeshFileName).suffix) -# if stem[-4:]!="GMSH": -# CoarseMeshFileName = Folder+"/"+stem+"GMSH"+suffix -# operator=IOW.InterpolationOperator(FineDataFolder,FineMeshFileName,CoarseMeshFileName,dimension,option=option) -# #operator=SIO.LoadState(FineDataFolder+"/Matrices/operator") -# ---------------------------------------------------------- -## READ SNAPSHOTS +fineSnapList, coarseSnapList = initproblem(nbeOfInitSnapshots, tbFine, tbCoarse, Dmu) +""" +---------------------------------------------------------------------------------------- +---------------------------------------------------------------------------------------- + Greedy/POD Offline part +---------------------------------------------------------------------------------------- +---------------------------------------------------------------------------------------- +""" -# print("-----------------------------------") -# print(" STEP I. 1: reading snapshots ") -# print("-----------------------------------") +print("-----------------------------------") +print(" STEP I. 2: Generate operator ") +print("-----------------------------------") -# collectionProblemData = CPD.CollectionProblemData() -# collectionProblemData.AddVariabilityAxis('unused',int,description="unused parameter") -# collectionProblemData.DefineQuantity("U", full_name=FieldName, unit="unused") #fine -# if Rectification == 1: -# collectionProblemData.DefineQuantity("UH", full_name=FieldName, unit="unused") #coarse - -# parameters = range(Nsfine)#for problemdata - -# cpt=0 #num snapshot - -# ndof = numberOfNodes*nbeOfComponentsPrimal -# Fine_snapshot_array = np.zeros(ndof,) -# ## Reading fine snapshots -# for snap in fineSnapList : -# print(f"Getting fine snapshot ", cpt) -# for i in range(ndof): -# Fine_snapshot_array[i] = snap.to_petsc().vec().__getitem__(i) -# # Fine_snapshot_array= snap.to_petsc().vec().array # get solution field -# solutionU=S.Solution("U",nbeOfComponentsPrimal,numberOfNodes,True) #Add each snapshot in collectionProblemData -# solutionU.AddSnapshot(Fine_snapshot_array,0) #time=0 -# problemData = PD.ProblemData(FineDataFolder+str(cpt)) #name of problemData -# problemData.AddSolution(solutionU) -# collectionProblemData.AddProblemData(problemData,unused=parameters[cpt]) -# cpt+=1 - -# cpt=0 - -# if Rectification == 1: -# ndof = numberOfNodes2*nbeOfComponentsPrimal -# Coarse_snapshot_array = np.zeros(ndof,) -# ## Reading coarse snapshots -# for snap in coarseSnapList : -# print(f"Getting coarse snapshot ", cpt) -# for i in range(ndof): -# Coarse_snapshot_array[i] = snap.to_petsc().vec().__getitem__(i) -# # Coarse_snapshot_array= snap.to_petsc().vec().array # get solution field -# solutionUH=S.Solution("U",nbeOfComponentsPrimal,numberOfNodes2,True) #Add each snapshot in collectionProblemData -# solutionUH.AddSnapshot(Coarse_snapshot_array,0) #time=0 -# problemData = collectionProblemData.GetProblemData(unused=parameters[cpt]) #label of problemData=parameter[cpt] -# problemData.AddSolution(solutionUH) -# collectionProblemData.AddProblemData(problemData,unused=parameters[cpt]) -# cpt+=1 - -# print("ComputeL2ScalarProducMatrix and ComputeH1ScalarProducMatrix ...") -# #l2ScalarProducMatrix = SIO.LoadState(FineDataFolder+"/Matrices/snapshotCorrelationOperator") #if already created -# #h1ScalarProducMatrix = SIO.LoadState(FineDataFolder+"/Matrices/h1ScalarProducMatrix") - -# #from scipy import sparse -# #l2ScalarProducMatrix=sparse.eye(numberOfNodes*nbeOfComponentsPrimal) #works with identity matrix - -# l2ScalarProducMatrix = FT.ComputeL2ScalarProducMatrix(FineMesh, nbeOfComponentsPrimal) -# h1ScalarProducMatrix = FT.ComputeH10ScalarProductMatrix(FineMesh, nbeOfComponentsPrimal) - -# # Snapshots norm -# snapshotUIterator = collectionProblemData.SnapshotsIterator("U") -# snapshots = [] -# #SnapshotsUNorm=[] -# for s in snapshotUIterator: -# snapshots.append(s) -# #norm=np.sqrt(s@l2ScalarProducMatrix@s) -# #SnapshotsUNorm.append(norm) -# #print("norm",norm) - -# if Rectification==1: -# snapshotUHIterator = collectionProblemData.SnapshotsIterator("UH") - -# snapshotsH = [] -# for s in snapshotUHIterator: -# snapshotsH.append(s) - - - -# """ -# ---------------------------------------------------------------------------------------- -# ---------------------------------------------------------------------------------------- -# Greedy/POD Offline part -# ---------------------------------------------------------------------------------------- -# ---------------------------------------------------------------------------------------- -# """ +Vh = feelpp.functionSpace(mesh=FineMesh) +MassMatrix=FppOp.mass(test=Vh,trial=Vh,range=feelpp.elements(FineMesh)) +StiffnessMatrix=FppOp.stiffness(test=Vh,trial=Vh,range=feelpp.elements(FineMesh)) -# print("-----------------------------------") -# print(" STEP I. 2: Creating Reduced Basis ") -# print("-----------------------------------") -# if Method=="Greedy": -# reducedOrderBasisU=GD.Greedy(collectionProblemData,"U",l2ScalarProducMatrix,h1ScalarProducMatrix,nev) # greedy algorithm -# else: #POD -# reducedOrderBasisU = SP.ComputeReducedOrderBasisFromCollectionProblemData(collectionProblemData, "U", 1.e-6, l2ScalarProducMatrix) - -# print("number of modes: ", nev) -# ### Add basis to collectionProblemData - -# collectionProblemData.AddReducedOrderBasis("U", reducedOrderBasisU) -# collectionProblemData.CompressSolutions("U", l2ScalarProducMatrix) #Mass matrix -# nev=collectionProblemData.GetReducedOrderBasisNumberOfModes("U") - -# collectionProblemData.AddOperatorCompressionData("U", l2ScalarProducMatrix) -# collectionProblemData.AddDataCompressionData("U", h1ScalarProducMatrix) - -# ## Ortho basis verification -# """ -# for i in range(nev): -# for j in range(nev): -# t=l2ScalarProducMatrix.dot(reducedOrderBasisU[i,:]) -# norm=t.dot(reducedOrderBasisU[j,:]) -# normh1=reducedOrderBasisU[i,:]@(h1ScalarProducMatrix@reducedOrderBasisU[j,:]) -# print(i,j," ",norm) -# print(" normh1 ", normh1) -# """ - -# ### PT: Rectification -# print("----------------------------------------") -# print(" STEP I. 3. : Rectification PostProcess ") -# print("----------------------------------------") -# # determinist process: Matrix R, allows to go from coeff (uH,phi_i) to (uh,Phi_i) -# if Rectification == 1: -# GD.addRectificationTocollectionProblemData(collectionProblemData,"U","UH",l2ScalarProducMatrix,nev) # greedy algorithm +l2ScalarProducMatrix = MassMatrix +h1ScalarProducMatrix = StiffnessMatrix + +print("-----------------------------------") +print(" STEP I. 2: Creating Reduced Basis ") +print("-----------------------------------") +collectionProblemData = CPD.CollectionProblemData() +collectionProblemData.AddVariabilityAxis('unused',int,description="unused parameter") +collectionProblemData.DefineQuantity("U", full_name=FieldName, unit="unused") #fine +if Rectification == 1: + collectionProblemData.DefineQuantity("UH", full_name=FieldName, unit="unused") #coarse + +cpt=0 #num snapshot + +if Method=="Greedy": + #reducedOrderBasisU=GD.Greedy(collectionProblemData,"U",l2ScalarProducMatrix,h1ScalarProducMatrix,nev) # greedy algorith + reducedOrderBasisU = SRB.ComputeReducedOrderBasisWithPOD(fineSnapList,l2ScalarProducMatrix) +else : #POD + reducedOrderBasisU = SRB.ComputeReducedOrderBasisWithPOD(fineSnapList, l2ScalarProducMatrix) + # reducedOrderBasisU = SPOD.ComputeReducedOrderBasisWithPOD(fineSnapList) + +### Add basis to collectionProblemData +collectionProblemData.AddReducedOrderBasis("U", reducedOrderBasisU) +# collectionProblemData.CompressSolutions("U", l2ScalarProducMatrix) #Mass matrix +nev=collectionProblemData.GetReducedOrderBasisNumberOfModes("U") +collectionProblemData.AddOperatorCompressionData("U", l2ScalarProducMatrix) # Mass matrix +collectionProblemData.AddDataCompressionData("U", h1ScalarProducMatrix) # Energy matrix + +print("number of modes: ", nev) + -# ### Offline Errors +print("----------------------------------------") +print(" STEP I. 3: Save datas for Online phase ") +print("----------------------------------------") + + +from Mordicus.Modules.Cemosis.IO.StateIO import * +file = "massMatrix.dat" +SavePetscArrayBin(file, l2ScalarProducMatrix.mat()) +file = "stiffnessMatrix.dat" +SavePetscArrayBin(file, h1ScalarProducMatrix.mat()) +file="reducedBasisU" +SIO.SaveState(file, reducedOrderBasisU) + +## Ortho basis verification +""" +for i in range(nev): + for j in range(nev): + t=l2ScalarProducMatrix.dot(reducedOrderBasisU[i,:]) + norm=t.dot(reducedOrderBasisU[j,:]) + normh1=reducedOrderBasisU[i,:]@(h1ScalarProducMatrix@reducedOrderBasisU[j,:]) + print(i,j," ",norm) + print(" normh1 ", normh1) +""" + +### Offline Errors # print("-----------------------------------") -# print(" STEP I. 4: Offline errors ") +# print(" STEP I. 4: Offline errors soon !!") # print("-----------------------------------") -# L2compressionErrors=[] -# H1compressionErrors=[] - -# for _, problemData in collectionProblemData.GetProblemDatas().items(): #for each snapshot -# solutionU=problemData.GetSolution("U") -# CompressedSolutionU=solutionU.GetCompressedSnapshots() -# exactSolution = problemData.solutions["U"].GetSnapshot(0) -# reconstructedCompressedSolution = np.dot(CompressedSolutionU[0], reducedOrderBasisU) #pas de tps 0 - -# norml2ExactSolution=np.sqrt(exactSolution@(l2ScalarProducMatrix@exactSolution)) -# normh1ExactSolution=np.sqrt(exactSolution@(h1ScalarProducMatrix@exactSolution)) - -# if norml2ExactSolution !=0 and normh1ExactSolution != 0: -# err=reconstructedCompressedSolution-exactSolution -# relL2Error=np.sqrt(err@l2ScalarProducMatrix@err)/norml2ExactSolution -# relH1Error=np.sqrt(err@h1ScalarProducMatrix@err)/normh1ExactSolution - -# else: #erreur absolue -# relL2Error=np.sqrt(err@l2ScalarProducMatrix@err) -# relH1Error=np.sqrt(err@h1ScalarProducMatrix@err) - -# L2compressionErrors.append(relL2Error) -# H1compressionErrors.append(relH1Error) - -# print("compression relative errors L2 =", L2compressionErrors) -# print("compression relative errors H1 =", H1compressionErrors) - -# print("Offline DONE ... ") -# print("to be continued, with the online part ... ") - -# ## save results -# print("Save state in ",OfflineResuFolder) -# # collectionProblemData.SetDataCompressionData("h1ScalarProducMatrix",h1ScalarProducMatrix) -# # collectionProblemData.SetOperatorCompressionData(l2ScalarProducMatrix) -# FileName=OfflineResuFolder+"collectionProblemData" -# SIO.SaveState(FileName, collectionProblemData) -# # SIO.SaveState("h1ScalarProducMatrix", h1ScalarProducMatrix) -# # SIO.SaveState("snapshotCorrelationOperator", l2ScalarProducMatrix) +print("Offline DONE ... ") +print("to be continued, with the online part ... ") diff --git a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBOnline.py b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBOnline.py index 540ffa99..b2e8277d 100644 --- a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBOnline.py +++ b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBOnline.py @@ -4,32 +4,28 @@ ## 01/2021 from dataclasses import Field +from hashlib import new import os import os.path as osp import glob +from sqlite3 import DatabaseError import sys +from turtle import shape import numpy as np from pathlib import Path import array import warnings -from Mordicus.Core.Containers import ProblemData as PD -from Mordicus.Core.Containers import CollectionProblemData as CPD -from Mordicus.Core.Containers import Solution as S -from Mordicus.Core.DataCompressors import SnapshotPOD as SP -from Mordicus.Core.IO import StateIO as SIO -from Mordicus.Modules.sorbonne.IO import MeshReader as MR -from Mordicus.Modules.sorbonne.IO import VTKMeshReader as VTKMR -from Mordicus.Modules.sorbonne.IO import GmshMeshReader as GmshMR -from Mordicus.Modules.sorbonne.IO import VTKSolutionReader as VTKSR -from Mordicus.Modules.sorbonne.IO import FFSolutionReader as FFSR -from Mordicus.Modules.sorbonne.IO import numpyToVTKWriter as NpVTK -from Mordicus.Modules.sorbonne.IO import InterpolationOperatorWriter as IOW +import feelpp +import feelpp.mor as mor +import feelpp.mor.reducedbasis.reducedbasis as FppRb +import feelpp.operators as FppOp +import SnapshotReducedBasis as SRB +from Mordicus.Modules.Cemosis.Containers.SolutionStructure.FeelppSol import FeelppSolution as FppSol +from NIRBinitCase import * +from Mordicus.Core.IO import StateIO as SIO -from Mordicus.Modules.Safran.FE import FETools as FT -from BasicTools.FE import FETools as FT2 -from BasicTools.FE.Fields.FEField import FEField print("-----------------------------------") print(" STEP II. 0: start Online nirb ") @@ -40,36 +36,9 @@ ## Directories currentFolder=os.getcwd() dataFolder = osp.expanduser("~/feelppdb/nirb/") -modelFolder = "StationaryNS/" # or "heat" - - -# 3D Case -""" -OfflineResuFolder=osp.join(currentFolder,'3Dcase/3DData/FineSnapshots/') #folder for offline resu -FineDataFolder=osp.join(currentFolder,'3Dcase/3DData/FineSolution/') #folder for fine snapshots -CoarseDataFolder=osp.join(currentFolder,'3Dcase/3DData/CoarseSolution/') #folder for coarse snapshots -FineMeshFolder=osp.join(currentFolder,'3Dcase/3DData/FineMesh/') #folder for fine mesh (needed with Freefem snapshots) -CoarseMeshFolder=osp.join(currentFolder,'3Dcase/3DData/CoarseMesh/') #folder for coarse mesh (needed with Freefem) -OnlineResuFolder=osp.join(currentFolder,'3Dcase/3DData/FineSnapshots/') #folder for fine snapshots -""" - -# 2D case - -# externalFolder=osp.join(currentFolder,'StationaryNS/External') #FreeFem scripts -# OfflineResuFolder=osp.join(currentFolder,'StationaryNS/StationaryNSData/FineSnapshots/') #folder for offline resu -# FineDataFolder=osp.join(currentFolder,'StationaryNS/StationaryNSData/FineSolution/') #folder for fine Solution (optional) -# CoarseDataFolder=osp.join(currentFolder,'StationaryNS/StationaryNSData/CoarseSolution/') #folder for coarse solution -# FineMeshFolder=osp.join(currentFolder,'StationaryNS/StationaryNSData/FineMesh/') #folder for fine mesh (needed with Freefem snapshots) -# CoarseMeshFolder=osp.join(currentFolder,'StationaryNS/StationaryNSData/CoarseMesh/') #folder for coarse mesh (needed with Freefem) -# OnlineResuFolder=osp.join(currentFolder,'StationaryNS/StationaryNSData/FineSnapshots/') #folder for offline resu +dataFolder = osp.expanduser("~/feelppdb/nirb/heat/np_1/") +modelFolder = "heat" # or "heat" -externalFolder=osp.join(currentFolder,'models/StationaryNS/External') #FreeFem scripts -OfflineResuFolder=osp.join(dataFolder,modelFolder,'FineSnapshots/') #folder for offline resu -FineDataFolder=osp.join(dataFolder,modelFolder,'FineSolution/') #folder for fine snapshots -CoarseDataFolder=osp.join(dataFolder,modelFolder,'CoarseSolution/') #folder for coarse snapshots -FineMeshFolder=osp.join(dataFolder,modelFolder,'FineMesh/') #folder for fine mesh (needed with Freefem snapshots) -CoarseMeshFolder=osp.join(dataFolder,modelFolder,'CoarseMesh/') #folder for coarse mesh (needed with Freefem) -OnlineResuFolder=osp.join(dataFolder,modelFolder,'OnlineResults/') #folder for offline resu ## Parameters @@ -78,7 +47,7 @@ FieldName="Velocity" #Snapshots fieldname FieldNameExactSolution="u"#"Velocity" #Snapshots fieldname Format= "FreeFem" # FreeFem or VTK -Method="Greedy" #POD or Greedy +Method="POD" #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 @@ -87,167 +56,89 @@ #coarseName="snapshotH0.vtu" #fineName="snapshot0.vtu" -######################################################### -# LOAD DATA FOR ONLINE -######################################################### +""" +-------------------------------------- + initialize toolbox +-------------------------------------- +""" +## Current Directories +currentFolder=os.getcwd() -collectionProblemData = SIO.LoadState(OfflineResuFolder+"collectionProblemData") -nev=collectionProblemData.GetReducedOrderBasisNumberOfModes("U") -l2ScalarProducMatrix = collectionProblemData.GetOperatorCompressionData("U") -h1ScalarProducMatrix=collectionProblemData.GetDataCompressionData("U") -reducedOrderBasisU = collectionProblemData.GetReducedOrderBasis("U") +# model directories +toolboxesOptions='heat' -if Rectification == 1: - R=collectionProblemData.GetDataCompressionData("Rectification") - #print("Rectification matrix: ", R) +modelsFolder = f"{currentFolder}/models/" +modelsFolder = f"{modelsFolder}{toolboxesOptions}" +cfg_path = f"{modelsFolder}/square/square.cfg" +geo_path = f"{modelsFolder}/square/square.geo" +model_path = f"{modelsFolder}/square/square.json" - -# ---------------------------------------------------------- -# Converting the solutions to VTU if FreeFem format -if Format == "FreeFem": - FineMeshFileName=glob.glob(os.path.join(FineMeshFolder,"*.msh")) - #assert len(FineMeshFileName)==1, "!! The user must provide only one fine mesh in the fine mesh folder !!" - FineMeshFileName=FineMeshFileName[0] - CoarseMeshFileName=glob.glob(os.path.join(CoarseMeshFolder,"*.msh")) - #print(CoarseMeshFileName) - - #assert len(CoarseMeshFileName)==1, "!! The user must provide only one coarse mesh in the coarse mesh folder !!" - CoarseMeshFileName=CoarseMeshFileName[0] - - if ComputingError==1: - #print(FineDataFolder) - FineSolutionFile=glob.glob(os.path.join(FineDataFolder,"*"))[0] - print("read the fine solution in ", FineSolutionFile) - suffix=str(Path(FineSolutionFile).suffix) - if suffix == ".txt": - FFFinetoVTKconvert=FFSR.FFSolutionReader(FieldName,FineMeshFileName) - FFFinetoVTKconvert.FFReadToNp(externalFolder,FineSolutionFile) #create the solution with vtu format - - CoarseSnapshotsFile=glob.glob(os.path.join(CoarseDataFolder,"*.txt"))[0] - FFCoarsetoVTKconvert=FFSR.FFSolutionReader(FieldName,CoarseMeshFileName); - FFCoarsetoVTKconvert.FFReadToNp(externalFolder,CoarseSnapshotsFile) #create the coarse solution with vtu format -# ---------------------------------------------------------- -# ---------------------------------------------------------- -## MESH READER - -## FINE MESH reader -if Format == "FreeFem": - print(FineMeshFileName) -else: - FineSnapshotFiles=sorted(glob.glob(os.path.join(FineDataFolder,"*.vtu"))) - FineMeshFileName=FineSnapshotFiles[0] #mesh from the snapshots - #print(FineMeshFileName) - -FineMeshReader=MR.MeshReader(FineMeshFileName,dimension) -FineMesh= FineMeshReader.ReadMesh() -print("Fine mesh defined in " + FineMeshFileName + " has been read") -numberOfNodes = FineMesh.GetNumberOfNodes() -print("number of nodes: ",numberOfNodes) - -## COARSE MESH reader for rectification post-process - -if Format == "FreeFem": - print(CoarseMeshFileName) -else: - CoarseSnapshotFiles=sorted(glob.glob(os.path.join(CoarseDataFolder,"*.vtu"))) - CoarseMeshFileName=CoarseSnapshotFiles[0] #mesh from the snapshots - -CoarseMeshReader = MR.MeshReader(CoarseMeshFileName,dimension) -CoarseMesh = CoarseMeshReader.ReadMesh() -print("Coarse mesh defined in " + CoarseMeshFileName + " has been read") -numberOfNodes2 = CoarseMesh.GetNumberOfNodes() -print("number of nodes: ",numberOfNodes2) +# fineness of two grids +H = 0.1 # CoarseMeshSize +h = H**2 # fine mesh size +# set the feelpp environment +config = feelpp.globalRepository(f"nirb/{toolboxesOptions}") +e=feelpp.Environment(sys.argv, opts = toolboxes_options(toolboxesOptions).add(mor.makeToolboxMorOptions()), config=config) +e.setConfigFile(cfg_path) +order =1 +# load model +model = loadModel(model_path) + +tbCoarse = setToolbox(H, geo_path, model, order) +tbFine = setToolbox(h, geo_path, model,order) +Dmu = loadParameterSpace(model_path) # ---------------------------------------------------------- # ---------------------------------------------------------- -# Interpolation on the fine mesh - -option="basictools" #ff, basictools -if Format == "FreeFem": - Folder=str(Path(FineMeshFileName).parents[0]) - stem=str(Path(FineMeshFileName).stem) - suffix=str(Path(FineMeshFileName).suffix) - if stem[-4:]!="GMSH": - FineMeshFileName = Folder+"/"+stem+"GMSH"+suffix - Folder=str(Path(CoarseMeshFileName).parents[0]) - stem=str(Path(CoarseMeshFileName).stem) - suffix=str(Path(CoarseMeshFileName).suffix) - if stem[-4:]!="GMSH": - CoarseMeshFileName = Folder+"/"+stem+"GMSH"+suffix -operator=IOW.InterpolationOperator(FineDataFolder,FineMeshFileName,CoarseMeshFileName,dimension,option=option) -#operator=SIO.LoadState(FineDataFolder+"/Matrices/operator") -# ---------------------------------------------------------- -# ---------------------------------------------------------- -# READING COARSE SOLUTION - -print("-----------------------------------") -print(" STEP I. 1: read coarse solution ") -print("-----------------------------------") - -CoarseSolutionFile=glob.glob(os.path.join(CoarseDataFolder,"*.vtu")) -print(CoarseSolutionFile) -assert len(CoarseSolutionFile)==1, "!! only one coarse solution needed in the coarse solution folder !!" -CoarseSolutionFile=CoarseSolutionFile[0] - -VTKSnapshotReader=VTKSR.VTKSolutionReader(FieldName); -CoarseSolution =VTKSnapshotReader.VTKReadToNp(CoarseSolutionFile)#.flatten() -CoarseSolutionInterp=operator.dot(CoarseSolution).flatten() -solutionUHh=S.Solution("U",nbeOfComponentsPrimal,numberOfNodes,True) -solutionUHh.AddSnapshot(CoarseSolutionInterp,0) - -onlineproblemData = PD.ProblemData("Online") #create online problem data -onlineproblemData.AddSolution(solutionUHh) - -UnusedParam=-1 #Problem Data label -collectionProblemData.AddProblemData(onlineproblemData,unused=UnusedParam) - -################################################## -# ONLINE COMPRESSION -################################################## - -print("--------------------------------") -print(" STEP II. 2: Online compression") -print("--------------------------------") - -solutionUHh.CompressSnapshots(l2ScalarProducMatrix,reducedOrderBasisU) -CompressedSolutionU = solutionUHh.GetCompressedSnapshots() +## MESH infos +FineMesh = tbFine.mesh() +CoarseMesh = tbCoarse.mesh() +numberOfNodes = CoarseMesh.numGlobalPoints() + +""" +------------------------------------------------------- + Load offline datas for online part +------------------------------------------------------- +""" -if Rectification == 1: - # Rectification +reducedOrderBasisU = SIO.LoadState(dataFolder+"reducedBasisU") +nev = reducedOrderBasisU.shape[0] - coef=np.zeros(nev) - for i in range(nev): - coef[i]=0 - for j in range(nev): - coef[i]+=R[i,j]*CompressedSolutionU[0][j] - - #print("coef without rectification: ", CompressedSolutionU[0]) - #print("coef with rectification ", coef) +# to be done later (read the matrix from file) +Vh = feelpp.functionSpace(mesh=FineMesh) +MassMatrix=FppOp.mass(test=Vh,trial=Vh,range=feelpp.elements(FineMesh)) +StiffnessMatrix=FppOp.stiffness(test=Vh,trial=Vh,range=feelpp.elements(FineMesh)) +MassMatrix.mat().assemble() +StiffnessMatrix.mat().assemble() - reconstructedCompressedSolution = np.dot(coef, reducedOrderBasisU) #with rectification +l2ScalarProducMatrix = MassMatrix +h1ScalarProducMatrix = StiffnessMatrix -else: - reconstructedCompressedSolution = np.dot(CompressedSolutionU[0], reducedOrderBasisU) #pas de tps 0 -################################################## -# SAVE APPROXIMATION -################################################## -if SavingApproximation == 1: - savedata=reconstructedCompressedSolution.reshape((numberOfNodes, nbeOfComponentsPrimal)) - - if Format == "FreeFem": - MeshBase = GmshMR.ReadGMSHBase(FineMeshFileName) - SnapWrite=NpVTK.VTKWriter(MeshBase) - print(SnapWrite.VTKBase) - - SnapWrite.numpyToVTKSanpWriteFromGMSH(savedata,FieldName,osp.join(OnlineResuFolder,"NIRB_Approximation_"+str(nev)+".vtu")) - - else: - MeshBase = VTKMR.ReadVTKBase(FineMeshFileName) - SnapWrite=NpVTK.VTKWriter(MeshBase) - SnapWrite.numpyToVTKSanpWrite(savedata,FieldName,osp.join(OnlineResuFolder,"NIRB_Approximation_"+str(nev)+".vtu")) +""" +----------------------------------------------------------------- + Get coarse solution and project it on fine mesh +----------------------------------------------------------------- +""" +## Solve equation with new parameter on Coarse Mesh +mu = Dmu.element() +coarseSol = SolveFpp(tbCoarse, mu) +interpOper = createInterpolator(tbCoarse, tbFine) +interpSol = interpOper.interpolate(coarseSol) + +""" +------------------------------------------------------- + Get new solution on fine mesh +------------------------------------------------------- +""" +## Compute coeff on reduced basis +newSol = FppSol("UH",dimension, numberOfNodes) +newSol.AddSolution(interpSol, 0) +newSol.CompressSolution(l2ScalarProducMatrix, reducedOrderBasisU) +newCompressedSol = newSol.GetreducedCoeff() +reconstructedSolution = np.dot(newCompressedSol[0], reducedOrderBasisU) ################################################## @@ -256,57 +147,15 @@ if ComputingError==1: print("-----------------------------------") - print(" STEP II. 3: L2 and H1 errors ") + print(" STEP II. 3: Compute online errors ") print("-----------------------------------") - print("reading exact solution...") - FineSolutionFile=glob.glob(os.path.join(FineDataFolder,"*.vtu")) - assert len(FineSolutionFile)==1, "!! only one fine solution needed in the coarse solution folder !!" - FineSolutionFile=FineSolutionFile[0] - print(FineSolutionFile) - VTKSnapshotReader=VTKSR.VTKSolutionReader(FieldNameExactSolution); - exactSolution =VTKSnapshotReader.VTKReadToNp(FineSolutionFile).flatten() - - solutionU=S.Solution("U",nbeOfComponentsPrimal,numberOfNodes,True) - solutionU.AddSnapshot(exactSolution,0) #only one snapshot->time=0 - - problemData = PD.ProblemData("Online") - problemData.AddSolution(solutionU) - collectionProblemData.AddProblemData(problemData,unused=UnusedParam) - - exactSolution =solutionU.GetSnapshot(0) - #solutionU.CompressSnapshots(l2ScalarProducMatrix,reducedOrderBasisU) - - #relative errors list - L2compressionErrors=[] - H1compressionErrors=[] - - norml2ExactSolution=np.sqrt(exactSolution@(l2ScalarProducMatrix@exactSolution)) - normh1ExactSolution=np.sqrt(exactSolution@(h1ScalarProducMatrix@exactSolution)) - - err=reconstructedCompressedSolution-exactSolution - if norml2ExactSolution != 0 and normh1ExactSolution != 0: - - L2relError=np.sqrt(err@(l2ScalarProducMatrix@err))/norml2ExactSolution - H1relError=np.sqrt(err@h1ScalarProducMatrix@err)/normh1ExactSolution - """ - f = open("NIRB_Greedy_errorH1.txt", "a") - f.write("nev ") - f.write(str(nev)) - f.write(" : ") - f.write(str(H1relError)) - f.write("\n") - f.close() - """ - else: - print("norm exact solution = 0") - L2relError=np.sqrt(err@(l2ScalarProducMatrix@err)) - H1relError=np.sqrt(err@h1ScalarProducMatrix@err) - - L2compressionErrors.append(L2relError) - H1compressionErrors.append(H1relError) - print("compression relative errors L2 with nev ", str(nev), " = ", L2compressionErrors) - print("compression relative errors H1 with nev ", str(nev), " = ", H1compressionErrors) + fineSol = np.array(interpSol.to_petsc().vec()) + reducedSol = reconstructedSolution + diff = np.abs(fineSol - reducedSol) + + print('Inf norm = ', np.max(diff)/np.max(fineSol)) + print('l2 discret norm = ',np.sqrt(diff.dot(diff))/np.sqrt(fineSol.dot(fineSol)) ) print("NIRB ONLINE DONE! ") diff --git a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBinitCase.py b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBinitCase.py index f25569dc..ec39304d 100644 --- a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBinitCase.py +++ b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBinitCase.py @@ -12,44 +12,6 @@ -def loadModel(model_path): - """Load the model from given modele path - - Args: - model_path (str): path to the model file (JSON) - - Returns: - json: model loaded - """ - f = open(model_path, "r") - model = json.load(f) - f.close() - return model - - -def setToolbox(h, geo_path, model, order=2): - - # load meshes - mesh_ = feelpp.mesh(dim=2, realdim=2) - mesh = feelpp.load(mesh_, geo_path, h) - - # set mesh and model properties - tb = heat(dim=2, order=order) - tb.setMesh(mesh) - tb.setModelProperties(model) - - tb.init() - - return tb - -def loadParameterSpace(model_path): - - crb_model_properties = mor.CRBModelProperties("", feelpp.Environment.worldCommPtr(), "") - crb_model_properties.setup(model_path) - Dmu = feelpp.mor._mor.ParameterSpace.New(crb_model_properties.parameters(), feelpp.Environment.worldCommPtr()) - return Dmu - - def assembleToolbox(tb, mu): for i in range(0,mu.size()): @@ -72,62 +34,29 @@ def createInterpolator(tbCoarse, tbFine): -def initproblem(numberOfSnapshot, order=2, CoarseMeshSize=0.1, toolboxesOptions="heat", modelsFolder=None): +def initproblem(numberOfInitSnapshot, tbFine, tbCoarse, Dmu): """ ---------------------------------------------------- generate snapshots in case POD method ---------------------------------------------------- - dataFolder : the folder to save datas + tbFine : toolbox for fine mesh (initialized) + tbCoarse : toolbox for coarse mesh (initialized) + Dmu : Space parameters numberOfSnapshot : the number of snapshot for initialization """ - - print("-----------------------------------") - print(" Initialize toolboxes ") - print("-----------------------------------") - ## Current Directories - currentFolder=os.getcwd() - - # set the feelpp environment - config = feelpp.globalRepository(f"nirb/{toolboxesOptions}") - e=feelpp.Environment(sys.argv, opts = toolboxes_options(toolboxesOptions), config=config) - - # fineness of two grids - H = CoarseMeshSize - h = H**2 - - # load the model - if modelsFolder == None : - modelsFolder = f"{currentFolder}/models/" - - modelsFolder = f"{modelsFolder}{toolboxesOptions}" - cfg_path = f"{modelsFolder}/square/square.cfg" - geo_path = f"{modelsFolder}/square/square.geo" - model_path = f"{modelsFolder}/square/square.json" - - e.setConfigFile(cfg_path) - model = loadModel(model_path) - - tbCoarse = setToolbox(H, geo_path, model, order) - tbFine = setToolbox(h, geo_path, model,order) - - # coarseMesh = tbCoarse.mesh() - # fineMesh = tbFine.mesh() - - Dmu = loadParameterSpace(model_path) - mu = Dmu.element() print("-----------------------------------") - print(" Initialize Snapshots ") + print(" Get Initialized Snapshots ") print("-----------------------------------") fineSnapList = [] coarseSnapList = [] - for param in range(numberOfSnapshot): + for param in range(numberOfInitSnapshot): dicparam = dict([ (mu.parameterName(i), mu(i)/float(param+1)) for i in range(mu.size())]) @@ -164,6 +93,62 @@ def initproblem(numberOfSnapshot, order=2, CoarseMeshSize=0.1, toolboxesOptions= print("Number of Snapshots computed = ", len(fineSnapList)) print("Initialize Snapshots DONE ") - return fineSnapList, coarseSnapList, tbCoarse.mesh(), tbFine.mesh() + return fineSnapList, coarseSnapList + +def loadModel(model_path): + """Load the model from given modele path + + Args: + model_path (str): path to the model file (JSON) + + Returns: + json: model loaded + """ + f = open(model_path, "r") + model = json.load(f) + f.close() + return model + +def loadParameterSpace(model_path): + + crb_model_properties = mor.CRBModelProperties("", feelpp.Environment.worldCommPtr(), "") + crb_model_properties.setup(model_path) + Dmu = feelpp.mor._mor.ParameterSpace.New(crb_model_properties.parameters(), feelpp.Environment.worldCommPtr()) + return Dmu + + +def setToolbox(h, geo_path, model, order=2): + + # load meshes + mesh_ = feelpp.mesh(dim=2, realdim=2) + mesh = feelpp.load(mesh_, geo_path, h) + + # set mesh and model properties + tb = heat(dim=2, order=order) + tb.setMesh(mesh) + tb.setModelProperties(model) + + tb.init() + + return tb + +def SolveFpp(toolBox, mu): + + """ + ---------------------------------------------------- + generate snapshots in case POD method + ---------------------------------------------------- + tbFine : toolbox for fine mesh (initialized) + tbCoarse : toolbox for coarse mesh (initialized) + Dmu : Space parameters + numberOfSnapshot : the number of snapshot for initialization + + """ + + assembleToolbox(toolBox, mu) + + toolBox.solve() + + return toolBox.fieldTemperature() diff --git a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/SnapshotReducedBasis.py b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/SnapshotReducedBasis.py new file mode 100644 index 00000000..74af1516 --- /dev/null +++ b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/SnapshotReducedBasis.py @@ -0,0 +1,101 @@ +# -*- coding: utf-8 -*- +# +# This file is subject to the terms and conditions defined in +# file 'LICENSE.txt', which is part of this source code package. +# +# + +from ast import MatMult +import os +from mpi4py import MPI +if MPI.COMM_WORLD.Get_size() > 1: # pragma: no cover + os.environ["OMP_NUM_THREADS"] = "1" + os.environ["OPENBLAS_NUM_THREADS"] = "1" + os.environ["MKL_NUM_THREADS"] = "1" + os.environ["VECLIB_MAXIMUM_THREADS"] = "1" + os.environ["NUMEXPR_NUM_THREADS"] = "1" +import numpy as np + +from mpi4py import MPI +from scipy import sparse +from petsc4py import PETSc +import petsc4py +from petsc4py import * + + +def ComputeReducedOrderBasisWithPOD(snapshotList, snapshotCorrelationOperator, tolerance=1.e-6): + """ + Computes a reducedOrderBasis using the SnapshotPOD algorithm, from the + snapshots contained in the iterator snapshotsIterator, which a correlation + operator between the snapshots defined by the matrix + snapshotCorrelationOperator, with tolerance as target accuracy of the data + compression + + Parameters + ---------- + snapshotList : List(of feelpp.functionSpace().element()) + List of the snapshots on which we want to compute a reducedOrderBasis + snapshotCorrelationOperator : feelpp.algMat + correlation operator between the snapshots + tolerance : float + target accuracy of the data compression + + Returns + ------- + np.ndarray + of size (numberOfModes, numberOfDOFs) + """ + + snapshots = [] + + numberOfDofs = snapshotList[0].functionSpace().nDof() + + for s in snapshotList: + snapshots.append(s.to_petsc().vec()[:]) + + # snapshots = np.array(snapshots) + + # numberOfSnapshots = snapshots.shape[0] + numberOfSnapshots = len(snapshotList) + print('number of snapshots = ', numberOfSnapshots) + + correlationMatrix = np.zeros((numberOfSnapshots, numberOfSnapshots)) + for i, snapshot1 in enumerate(snapshotList): + for j, snapshot2 in enumerate(snapshotList): + if i >= j: + correlationMatrix[i, j] = snapshotCorrelationOperator.energy(snapshot1, snapshot2) + + + mpiReducedCorrelationMatrix = np.zeros((numberOfSnapshots, numberOfSnapshots)) + MPI.COMM_WORLD.Allreduce([correlationMatrix, MPI.DOUBLE], [mpiReducedCorrelationMatrix, MPI.DOUBLE]) + + from Mordicus.Core.BasicAlgorithms import SVD as SVD + + + eigenValuesRed, eigenVectorsRed = SVD.TruncatedSVDSymLower(mpiReducedCorrelationMatrix, tolerance) + + nbePODModes = eigenValuesRed.shape[0] + + print("nbePODModes =", nbePODModes) + + + changeOfBasisMatrix = np.zeros((nbePODModes,numberOfSnapshots)) + for j in range(nbePODModes): + changeOfBasisMatrix[j,:] = eigenVectorsRed[:,j]/np.sqrt(eigenValuesRed[j]) + + snapshots = np.array(snapshots) + reducedOrderBasis = np.dot(changeOfBasisMatrix,snapshots) + + + return reducedOrderBasis + + + +if __name__ == "__main__":# pragma: no cover + + from Mordicus import RunTestFile + RunTestFile(__file__) + + + + diff --git a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/models/heat/square/square.cfg b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/models/heat/square/square.cfg new file mode 100644 index 00000000..e46bd621 --- /dev/null +++ b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/models/heat/square/square.cfg @@ -0,0 +1,44 @@ +directory=modeles/heat/square +case.dimension=2 +case.discretization=P1 +journal=false + + +[toolboxmor] +filename=$cfgdir/square.json +trainset-deim-size=40 +trainset-mdeim-size=40 +name=square + +[heat] +filename=$cfgdir/square.json +verbose_solvertimer=true +ksp-monitor=true +pc-type=gamg + + +[crb] +results-repo-name=square +rebuild-database=true +output-index=0 +error-type=2 +use-random-WNmu=50 +error-max=1e-6 +dimension-max=10 +all-procs-have-same-sampling=false +sampling-size=1000 +sampling-mode=equidistribute#equidistribute, log-equidistribute or log-random +orthonormalize-primal=true +orthonormality-tol=1e-12#1e-8 +orthonormalize-dual=true +solve-dual-problem=false +compute-fem-during-online=true +load-elements-database=true +print-iterations-info=true + +[vec.deim] +greedy.rtol=1e-14 +dimension-max=100 + +[mat.deim] +greedy.rtol=1e-12 \ No newline at end of file diff --git a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/models/heat/square/square.geo b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/models/heat/square/square.geo new file mode 100644 index 00000000..06a47d75 --- /dev/null +++ b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/models/heat/square/square.geo @@ -0,0 +1,43 @@ +// -*- mode: c¯ -*- +h=0.1; + +L=1; +H=1; +Point(1)={0, 0, 0, h}; +Point(2)={L, 0, 0, h}; +Point(3)={L, H, 0, h}; +Point(4)={0, H, 0, h}; + +Point(5)={0.5,1,0,h}; +Point(6)={0,0.5,0,h}; +Point(7)={1,0.5,0,h}; +Point(8)={0.5,0,0,h}; +Point(9)={0.5,0.5,0,h}; +Line(1)={1,8}; +Line(2)={8,2}; +Line(3)={2,7}; +Line(4)={7,3}; +Line(5)={3,5}; +Line(6)={5,4}; +Line(7)={4,6}; +Line(8)={6,1}; +Line(9)={8,9}; +Line(10)={9,5}; +Line(11)={6,9}; +Line(12)={9,7}; +Line Loop(14)={7,11,10,6}; +Plane Surface(14)={14}; +Line Loop(16)={8,1,9,-11}; +Plane Surface(16)={16}; +Line Loop(18)={2,3,-12,-9}; +Plane Surface(18)={18}; +Line Loop(20)={12,4,5,-10}; +Plane Surface(20)={20}; + +//physicalentities +Physical Line("Tflux")={1,2}; +Physical Line("Tfourier")={3,4,5,6,7,8}; +Physical Surface("Fin0")={16}; +Physical Surface("Fin1")={18}; +Physical Surface("Fin2")={14}; +Physical Surface("Fin3")={20}; diff --git a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/models/heat/square/square.json b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/models/heat/square/square.json new file mode 100644 index 00000000..c89e6f62 --- /dev/null +++ b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/models/heat/square/square.json @@ -0,0 +1,108 @@ +{ + "Name": "Square thermal-fin splitted", + "ShortName": "SquareNIRB", + + "Meshes": + { + "heat": + { + "Import": + { + "filename":"$cfgdir/square.geo", + "hsize": 0.1 + } + } + }, + + "CRBParameters": + { + "k0": + { + "min": 0.1, + "max": 1 + }, + "k1": + { + "min": 0.1, + "max": 1 + }, + "k2": + { + "min": 0.1, + "max": 1 + }, + "k3": + { + "min": 0.1, + "max": 1 + } + }, + + "Parameters": + { + "k0": 10, + "k1": 0.1, + "k2": 1, + "k3": 0.1, + "Bi": 1 + }, + + "Materials": + { + "Fin0": + { + "k":"k0:k0", // [W / (m * K)] + "rho":"1", // [kg / m^3] + "Cp":"1" // [J / (kg * K)] + }, + "Fin1": + { + "k":"k1:k1", // [W / (m * K)] + "rho":"1", // [kg / m^3] + "Cp":"1" // [J / (kg * K)] + }, + "Fin2": + { + "k":"k2:k2", // [W / (m * K)] + "rho":"1", // [kg / m^3] + "Cp":"1" // [J / (kg * K)] + }, + "Fin3": + { + "k":"k3:k3", // [W / (m * K)] + "rho":"1", // [kg / m^3] + "Cp":"1" // [J / (kg * K)] + } + }, + + "BoundaryConditions": + { + "heat": + { + "flux": + { + "Tflux": { + "expr": "1" + } + }, + "convective_heat_flux": + { + "Tfourier": + { + "h":"Bi:Bi", + "Text":"0" + } + } + } + }, + + "PostProcess": + { + "heat":{ + "Exports": + { + "fields":["temperature","pid"] + } + } + } +} \ No newline at end of file diff --git a/src/poc-1/src/Mordicus/Modules/Cemosis/IO/StateIO.py b/src/poc-1/src/Mordicus/Modules/Cemosis/IO/StateIO.py new file mode 100644 index 00000000..13f9b822 --- /dev/null +++ b/src/poc-1/src/Mordicus/Modules/Cemosis/IO/StateIO.py @@ -0,0 +1,22 @@ +import petsc4py +from petsc4py import PETSc +import os +from mpi4py import MPI + + +def SavePetscArrayBin(filename, PetscAray): + + outputfile = os.path.join(filename) + + viewer = PETSc.Viewer().createBinary(outputfile, 'w') + viewer(PetscAray) + + +def SavePetscArrayASCII(filename, PetscAray): + + outputfile = os.path.join(filename) + + myviewer = PETSc.Viewer().createASCII( + outputfile, format=PETSc.Viewer.Format.ASCII_COMMON, + comm= PETSc.COMM_WORLD) + PetscAray.view(myviewer) diff --git a/src/poc-1/src/Mordicus/Modules/sorbonne/IO/InterpolationOperatorWriter.py b/src/poc-1/src/Mordicus/Modules/sorbonne/IO/InterpolationOperatorWriter.py index df704a23..811bd89a 100755 --- a/src/poc-1/src/Mordicus/Modules/sorbonne/IO/InterpolationOperatorWriter.py +++ b/src/poc-1/src/Mordicus/Modules/sorbonne/IO/InterpolationOperatorWriter.py @@ -26,8 +26,10 @@ def InterpolationOperator(dataFolder,mesh1,mesh2,dimension,option=None): if option=="ff": # call of freefem (output: InterpolI.txt) print("interpolation with FreeFem++") - - scriptFreeFemInterpolation=osp.join(externalFolder,'FF_Interpolation_Mat_3D.edp') + + #scriptFreeFemInterpolation=osp.join(externalFolder,'FF_Interpolation_Mat_3D.edp') + scriptFreeFemInterpolation=osp.join(externalFolder,'FF_Interpolation.edp') + try: FNULL = open(os.devnull, 'w') ret = subprocess.run(["FreeFem++", scriptFreeFemInterpolation, diff --git a/src/poc-1/src/Mordicus/Modules/sorbonne/IO/numpyToVTKWriter.py b/src/poc-1/src/Mordicus/Modules/sorbonne/IO/numpyToVTKWriter.py index c03d30ed..a339356f 100644 --- a/src/poc-1/src/Mordicus/Modules/sorbonne/IO/numpyToVTKWriter.py +++ b/src/poc-1/src/Mordicus/Modules/sorbonne/IO/numpyToVTKWriter.py @@ -165,19 +165,34 @@ def numpyToVTKSanpWriteFromGMSH(self, SnapshotsList,FieldName="U", solutionName= #print("shape vtkfile", np.shape(numpySnap_array)) p=self.VTKBase.nodes + + print(p) + numberOfNodes=np.shape(p)[0] + #print('number of node vtk = ', numberOfNodes) + vtkPts = vtk.vtkPoints() - #for i in range(numberOfNodes): - # vtkPts.InsertNextPoint(p[i]) - vtkPts.SetData(numpy_support.numpy_to_vtk(p, deep=True)) + # for i in range(numberOfNodes): + # vtkPts.InsertNextPoint(i,p[i]) + + # for i in range(numberOfNodes): + # pi = p[i].tolist() + # pi.append(0.0) + # vtkPts.InsertNextPoint(pi) + # point_id = vtkPts.InsertNextPoint(pi) + # vertices.InsertNextCell(1) + # vertices.InsertCellPoint(point_id) + + vtkPts.SetData(numpy_support.numpy_to_vtk(p)) + VTKBase = vtk.vtkUnstructuredGrid() VTKBase.SetPoints(vtkPts)#pts #print(VTKBase) #VTK_data = numpy_support.numpy_to_vtk(num_array=numpySnap_array.ravel(), deep=True, array_type=vtk.VTK_FLOAT) VTK_data = numpy_support.numpy_to_vtk(num_array=numpySnap_array, deep=True, array_type=vtk.VTK_FLOAT) - + size = VTK_data.GetSize() #print("size array", size) VTK_data.SetName(FieldName) @@ -200,5 +215,6 @@ def numpyToVTKSanpWriteFromGMSH(self, SnapshotsList,FieldName="U", solutionName= writer.SetFileName(out_fname) writer.SetInputData(VTKBase) writer.SetDataModeToAscii() + writer.Update() writer.Write() print('\nfile ', out_fname, ' written\n' ) diff --git a/src/poc-1/src/Mordicus/Modules/sorbonne/MOR/Greedy.py b/src/poc-1/src/Mordicus/Modules/sorbonne/MOR/Greedy.py index a5c20fbb..66ad299b 100644 --- a/src/poc-1/src/Mordicus/Modules/sorbonne/MOR/Greedy.py +++ b/src/poc-1/src/Mordicus/Modules/sorbonne/MOR/Greedy.py @@ -245,4 +245,4 @@ def Rectification(collectionProblemData,FineSolutionName,CoarseSolutionName,snap def addRectificationTocollectionProblemData(collectionProblemData,FineSolutionName,CoarseSolutionName,snapshotCorrelationOperator,nev): R=Rectification(collectionProblemData,FineSolutionName,CoarseSolutionName,snapshotCorrelationOperator,nev) - collectionProblemData.SetDataCompressionData("Rectification",R) + collectionProblemData.AddDataCompressionData("Rectification",R) diff --git a/src/poc-1/tests/Modules/Cemosis/DataCompressors/test_NIRBinitCase.py b/src/poc-1/tests/Modules/Cemosis/DataCompressors/test_NIRBinitCase.py index 661dc944..56a57ade 100644 --- a/src/poc-1/tests/Modules/Cemosis/DataCompressors/test_NIRBinitCase.py +++ b/src/poc-1/tests/Modules/Cemosis/DataCompressors/test_NIRBinitCase.py @@ -4,15 +4,50 @@ import pytest import sys -from Mordicus.Modules.Cemosis.DataCompressors import initCaseNIRB as IC +from Mordicus.Modules.Cemosis.DataCompressors.NIRBinitCase import * import feelpp @pytest.mark.skipif('feelpp' not in sys.modules, reason="requires the Feel++ library") def test_NIRB_init_case(): + """ + -------------------------------------- + initialize toolbox + -------------------------------------- + """ + ## Current Directories + currentFolder=os.getcwd() + + # model directories + toolboxesOptions='heat' + modelsFolder = f"{currentFolder}/models/" + modelsFolder = f"{modelsFolder}{toolboxesOptions}" + cfg_path = f"{modelsFolder}/square/square.cfg" + geo_path = f"{modelsFolder}/square/square.geo" + model_path = f"{modelsFolder}/square/square.json" + + # fineness of two grids + H = 0.1 # CoarseMeshSize + h = H**2 # fine mesh size + + + # set the feelpp environment + config = feelpp.globalRepository(f"nirb/{toolboxesOptions}") + e=feelpp.Environment(sys.argv, opts = toolboxes_options(toolboxesOptions), config=config) + e.setConfigFile(cfg_path) + + order =1 + # load model + model = loadModel(model_path) + + tbCoarse = setToolbox(H, geo_path, model, order) + tbFine = setToolbox(h, geo_path, model,order) + + Dmu = loadParameterSpace(model_path) + currentFolder=os.getcwd() modelsFolder= f"{currentFolder}/models/" numberOfSnapshot = 3 - fineSnapList, _, _, _ = IC.initproblem(numberOfSnapshot, modelsFolder=modelsFolder) + fineSnapList, _ = initproblem(numberOfSnapshot, tbFine, tbCoarse, Dmu) assert len(fineSnapList) == numberOfSnapshot diff --git a/src/poc-1/tests/Modules/Sorbonne/NIRBOffline.py b/src/poc-1/tests/Modules/Sorbonne/NIRBOffline.py index 37fd8afa..76e27ec8 100644 --- a/src/poc-1/tests/Modules/Sorbonne/NIRBOffline.py +++ b/src/poc-1/tests/Modules/Sorbonne/NIRBOffline.py @@ -31,6 +31,7 @@ ## Directories currentFolder=os.getcwd() + """ # 3D Case OfflineResuFolder=osp.join(currentFolder,'3Dcase/3DData/FineSnapshots/') #folder for offline resu @@ -41,6 +42,7 @@ """ # 2D case + externalFolder=osp.join(currentFolder,'StationaryNS/External') #FreeFem scripts OfflineResuFolder=osp.join(currentFolder,'StationaryNS/StationaryNSData/FineSnapshots/') #folder for offline resu FineDataFolder=osp.join(currentFolder,'StationaryNS/StationaryNSData/FineSnapshots/') #folder for fine snapshots @@ -48,14 +50,15 @@ FineMeshFolder=osp.join(currentFolder,'StationaryNS/StationaryNSData/FineMesh/') #folder for fine mesh (needed with Freefem snapshots) CoarseMeshFolder=osp.join(currentFolder,'StationaryNS/StationaryNSData/CoarseMesh/') #folder for coarse mesh (needed with Freefem) + ## Parameters dimension=2 #dimension spatial domain nbeOfComponentsPrimal = 2 # number of components FieldName="Velocity" #Snapshots fieldname Format= "FreeFem" # FreeFem or VTK -Method="Greedy" #POD or Greedy -Rectification=0 #1 with Rectification post-process (Coarse Snapshots required) or 0 without +Method="POD" #POD or Greedy +Rectification=1 #1 with Rectification post-process (Coarse Snapshots required) or 0 without ## Script Files - Initiate data # Create data (mesh1,mesh2,snapshots,uH) for Sorbonne usecase diff --git a/src/poc-1/tests/Modules/Sorbonne/NIRBOnline.py b/src/poc-1/tests/Modules/Sorbonne/NIRBOnline.py index 745acb18..e6a55662 100644 --- a/src/poc-1/tests/Modules/Sorbonne/NIRBOnline.py +++ b/src/poc-1/tests/Modules/Sorbonne/NIRBOnline.py @@ -51,6 +51,7 @@ """ # 2D case + externalFolder=osp.join(currentFolder,'StationaryNS/External') #FreeFem scripts OfflineResuFolder=osp.join(currentFolder,'StationaryNS/StationaryNSData/FineSnapshots/') #folder for offline resu FineDataFolder=osp.join(currentFolder,'StationaryNS/StationaryNSData/FineSolution/') #folder for fine Solution (optional) @@ -66,7 +67,7 @@ FieldName="Velocity" #Snapshots fieldname FieldNameExactSolution="u"#"Velocity" #Snapshots fieldname Format= "FreeFem" # FreeFem or VTK -#Method="Greedy" #POD or Greedy +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 diff --git a/src/poc-1/tests/Modules/Sorbonne/StationaryNS/External/script_donnees_init.edp b/src/poc-1/tests/Modules/Sorbonne/StationaryNS/External/script_donnees_init.edp index 688c0f82..f372e14e 100644 --- a/src/poc-1/tests/Modules/Sorbonne/StationaryNS/External/script_donnees_init.edp +++ b/src/poc-1/tests/Modules/Sorbonne/StationaryNS/External/script_donnees_init.edp @@ -29,7 +29,7 @@ string snapCoarseFile=outputDir+"/coarsesnapshots.txt"; //string meshFile1=getARGV("-outputMesh1","err.log"); //string meshFile2=getARGV("-outputMesh2","err.log"); - +cout<<"output dir = " << outputDir <