From 28abcdd3ae8ed268b108e7379536792c00394415 Mon Sep 17 00:00:00 2001 From: Ali Elarif Date: Mon, 5 Sep 2022 18:40:13 +0200 Subject: [PATCH] fix bug of interpolation and conversion of PETSc vect to feelpp element #25 --- .../Cemosis/DataCompressors/NIRBOffline.py | 151 ++++++--------- .../Cemosis/DataCompressors/NIRBOnline.py | 170 +++++++---------- .../Cemosis/DataCompressors/NIRBinitCase.py | 176 +++++------------- .../Modules/sorbonne/IO/numpyToVTKWriter.py | 4 +- 4 files changed, 178 insertions(+), 323 deletions(-) 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 6e45672..a10d2c0 100644 --- a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBOffline.py +++ b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBOffline.py @@ -23,86 +23,74 @@ import SnapshotReducedBasis as SRB from NIRBinitCase import * from feelpp.toolboxes.heat import * -from Mordicus.Core.DataCompressors import SnapshotPOD as SP from petsc4py import PETSc nirb_dir = "/data/home/elarif/devel/feelpp/python/pyfeelpp-toolboxes/feelpp/toolboxes/nirb/" sys.path.append(nirb_dir) from nirb import * -from Mordicus.Core.Containers import CollectionProblemData as CPD -from Mordicus.Core.IO import StateIO as SIO +# from Mordicus.Core.Containers import CollectionProblemData as CPD +# from Mordicus.Core.IO import StateIO as SIO -## Directories -currentFolder=os.getcwd() -dataFolder = osp.expanduser("~/feelppdb/nirb/") -modelFolder = "StationaryNS/" # or "heat" +print("-----------------------------------") +print(" STEP II. 0: start Online nirb ") +print("-----------------------------------") ## Parameters - dimension=2 #dimension spatial domain -nbeOfComponentsPrimal = 2 # number of components -FieldName="Velocity" #Snapshots fieldname Method="POD" #POD or Greedy -Rectification=1 #1 with Rectification post-process (Coarse Snapshots required) or 0 without +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 +# fineness of two grids +H = 0.1 # CoarseMeshSize +h = H**2 # fine mesh size + + +## Directories +PWD=os.getcwd() +dataFolder = osp.expanduser(f"~/feelppdb/nirb/{toolboxesOptions}/np_1/") +# model directories +modelsFolder = f"{PWD}/models/" +modelsFolder = f"{modelsFolder}{toolboxesOptions}/" +cfg_path = f"{modelsFolder}{modelfile[toolboxesOptions]}.cfg" +geo_path = f"{modelsFolder}{modelfile[toolboxesOptions]}.geo" +model_path = f"{modelsFolder}{modelfile[toolboxesOptions]}.json" +msh_path = f"{dataFolder}{modelfile[toolboxesOptions]}.msh" -## Script Files - Initiate data -# Create data (mesh1,mesh2,snapshots,uH) for Sorbonne usecase """ -------------------------------------- initialize toolbox -------------------------------------- """ -## Current Directories -currentFolder=os.getcwd() - -# model directories -toolboxesOptions='heat' # 'fluid' - -if (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" -elif (toolboxesOptions=='fluid'): - modelsFolder = f"{currentFolder}/models/lid-driven-cavity" - # modelsFolder = f"{modelsFolder}{toolboxesOptions}" - cfg_path = f"{modelsFolder}/cfd2d.cfg" - geo_path = f"{modelsFolder}/cfd2d.geo" - model_path = f"{modelsFolder}/cfd2d.json" - - -start = timeit.timeit() - -# fineness of two grids -H = 0.1 # CoarseMeshSize -h = H**2 # fine mesh size - +start = timeit.timeit() # 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, dim=dimension, order=order,type_tb=toolboxesOptions) +# define the toolboxes tbFine = setToolbox(h, geo_path, model, dim=dimension, order=order,type_tb=toolboxesOptions) -Dmu = loadParameterSpace(model_path) +# Get actual mu parameter +Dmu = loadParameterSpace(model_path) + # ---------------------------------------------------------- # ---------------------------------------------------------- -## MESH infos +## Fine mesh infos FineMesh = tbFine.mesh() -CoarseMesh = tbCoarse.mesh() -## Fine Mesh reader numberOfNodes = FineMesh.numGlobalPoints() print("Fine Mesh --> Number of nodes : ", numberOfNodes) -## Coarse Mesh reader if rectification process -if Rectification==1 : +if Rectification : + # define the coarse toolboxes and mesh + tbCoarse = setToolbox(H, geo_path, model, dim=dimension, order=order,type_tb=toolboxesOptions) + CoarseMesh = tbCoarse.mesh() numberOfNodes2 = CoarseMesh.numGlobalPoints() print("Coarse Mesh --> Number of nodes : ", numberOfNodes2) @@ -116,8 +104,10 @@ print("-----------------------------------") print(" STEP I. 0: start init ") print("-----------------------------------") - -fineSnapList, coarseSnapList = initproblem(nbeOfInitSnapshots, tbFine, tbCoarse, Dmu) +if Rectification : + fineSnapList, coarseSnapList = initproblem(nbeOfInitSnapshots, Dmu, tbFine, tbCoarse, type_tb=toolboxesOptions) +else : + fineSnapList, _ = initproblem(nbeOfInitSnapshots,Dmu, tbFine, type_tb=toolboxesOptions) """ ---------------------------------------------------------------------------------------- @@ -126,55 +116,31 @@ ---------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------- """ +print("--------------------------------------------") +print(" STEP I. 2: Generate L2 and H1 operator ") +print("--------------------------------------------") -print("-----------------------------------") -print(" STEP I. 2: Generate operator ") -print("-----------------------------------") - -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)) - -l2ScalarProducMatrix = MassMatrix -h1ScalarProducMatrix = StiffnessMatrix +Vh = feelpp.functionSpace(mesh=FineMesh) # feelpp space function +l2ScalarProducMatrix=FppOp.mass(test=Vh,trial=Vh,range=feelpp.elements(FineMesh)) +h1ScalarProducMatrix=FppOp.stiffness(test=Vh,trial=Vh,range=feelpp.elements(FineMesh)) 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 - -nbPODMode = len(fineSnapList) -nbDofs = fineSnapList[0].functionSpace().nDof() - -oper = l2ScalarProducMatrix.mat() -oper.assemble() -oper = np.array(oper[:,:]) -snaparray = [] -for s in fineSnapList: - snaparray.append(s.to_petsc().vec()[:]) - +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) + reducedOrderBasisU = SRB.PODReducedBasisPETSc(fineSnapList,l2ScalarProducMatrix) else : #POD - # reducedOrderBasisU = SRB.ComputeReducedOrderBasisWithPOD(fineSnapList, l2ScalarProducMatrix) - rbb = SP.ComputeReducedOrderBasis(snaparray, oper, 1.e-6) - -nbPODMode = rbb.shape[0] -reducedOrderBasisU = PETSc.Mat().createDense(size=(nbPODMode,nbDofs)) -reducedOrderBasisU.setFromOptions() -reducedOrderBasisU.setUp() -reducedOrderBasisU.assemble() + # reducedOrderBasisU = SRB.PODReducedBasisPETSc(fineSnapList, l2ScalarProducMatrix) + reducedOrderBasisU = SRB.PODReducedBasisNumpy(fineSnapList, l2ScalarProducMatrix) -print('shape = ', rbb.shape) -reducedOrderBasisU[:,:] = rbb # number of modes nev = reducedOrderBasisU.size[0] print("number of modes: ", nev) @@ -190,8 +156,6 @@ 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()) @@ -199,7 +163,6 @@ SavePetscArrayBin(file, h1ScalarProducMatrix.mat()) file="reducedBasisU.dat" SavePetscArrayBin(file, reducedOrderBasisU) -# SIO.SaveState(file, reducedOrderBasisU) ## Ortho basis verification """ 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 b50ef79..441009f 100644 --- a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBOnline.py +++ b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBOnline.py @@ -28,8 +28,9 @@ from Mordicus.Modules.Cemosis.Containers.SolutionStructure.FeelppSol import energy from NIRBinitCase import * -from feelpp.toolboxes.heat import * +from feelpp.toolboxes.heat import toolboxes_options from Mordicus.Modules.Cemosis.IO.StateIO import * + nirb_dir = "/data/home/elarif/devel/feelpp/python/pyfeelpp-toolboxes/feelpp/toolboxes/nirb/" sys.path.append(nirb_dir) from nirb import * @@ -39,30 +40,29 @@ print(" STEP II. 0: start Online nirb ") print("-----------------------------------") - -#time=0.0 #steady -## Directories -currentFolder=os.getcwd() -dataFolder = osp.expanduser("~/feelppdb/nirb/") -dataFolder = osp.expanduser("~/feelppdb/nirb/heat/np_1/") -modelFolder = "heat" # or "heat" - - ## Parameters - dimension=2 #dimension spatial domain -nbeOfComponentsPrimal = 2 # number of components -FieldName="Velocity" #Snapshots fieldname -FieldNameExactSolution="u"#"Velocity" #Snapshots fieldname -Format= "FreeFem" # FreeFem or VTK 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 +ComputingError=True # 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 +# fineness of two grids +H = 0.1 # CoarseMeshSize +h = H**2 # fine mesh size -## Fine and coarse Solution files name -#coarseName="snapshotH0.vtu" -#fineName="snapshot0.vtu" +## Directories +PWD=os.getcwd() +dataFolder = osp.expanduser(f"~/feelppdb/nirb/{toolboxesOptions}/np_1/") +# model directories +modelsFolder = f"{PWD}/models/" +modelsFolder = f"{modelsFolder}{toolboxesOptions}/" +cfg_path = f"{modelsFolder}{modelfile[toolboxesOptions]}.cfg" +geo_path = f"{modelsFolder}{modelfile[toolboxesOptions]}.geo" +model_path = f"{modelsFolder}{modelfile[toolboxesOptions]}.json" +msh_path = f"{dataFolder}{modelfile[toolboxesOptions]}.msh" """ -------------------------------------- @@ -70,38 +70,18 @@ -------------------------------------- """ start = timeit.timeit() - -## 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" - -msh_path = f"{dataFolder}/square.msh" - -# 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) - +# define the toolboxes tbCoarse = setToolbox(H, geo_path, model, dim=dimension, order=order,type_tb=toolboxesOptions) tbFine = setToolbox(h, geo_path, model, dim=dimension, order=order,type_tb=toolboxesOptions) - -Dmu = loadParameterSpace(model_path) +# Get actual mu parameter +Dmu = loadParameterSpace(model_path) # ---------------------------------------------------------- # ---------------------------------------------------------- @@ -109,6 +89,8 @@ FineMesh = tbFine.mesh() CoarseMesh = tbCoarse.mesh() numberOfNodes = CoarseMesh.numGlobalPoints() +# Define feelpp function space +Xh = feelpp.functionSpace(mesh=FineMesh, order=order) """ ------------------------------------------------------- @@ -119,15 +101,11 @@ reducedOrderBasisU = LoadPetscArrayBin(filename) nev = reducedOrderBasisU.size[0] filename= dataFolder + "massMatrix.dat" -MassMatrix = LoadPetscArrayBin(filename) +l2ScalarProducMatrix = LoadPetscArrayBin(filename) filename= dataFolder + "stiffnessMatrix.dat" -StiffnessMatrix = LoadPetscArrayBin(filename) - -MassMatrix.assemble() -StiffnessMatrix.assemble() - -l2ScalarProducMatrix = MassMatrix -h1ScalarProducMatrix = StiffnessMatrix +h1ScalarProducMatrix = LoadPetscArrayBin(filename) +l2ScalarProducMatrix.assemble() +h1ScalarProducMatrix.assemble() """ ----------------------------------------------------------------- Get coarse solution and project it on fine mesh @@ -136,29 +114,34 @@ ## Solve equation with new parameter on Coarse Mesh mu = Dmu.element() coarseSol = SolveFpp(tbCoarse, mu) -interpOper = createInterpolator(tbCoarse, tbFine, type_tb='heat') +interpOper = createInterpolator(tbCoarse, tbFine, type_tb=toolboxesOptions) interpSol = interpOper.interpolate(coarseSol) -FineSol = SolveFpp(tbFine, mu) - +# Export interpolated sol +if export : + ep = feelpp.exporter(mesh=FineMesh, name="feelpp_interp") + ep.addScalar("un", 1.) + if (order==1): + ep.addP1c("U_interp", interpSol) + elif (order==2): + ep.addP2c("U_interp", interpSol) + ep.save() """ ------------------------------------------------------- Get new solution on fine mesh ------------------------------------------------------- """ -## Compute coeff on reduced basis +## Get projection of interpolate solution on reduced space newSol = FppSol("UH",dimension, numberOfNodes) newSol.AddSolution(interpSol, 0) newSol.CompressSolution(l2ScalarProducMatrix, reducedOrderBasisU) newCompressedSol = newSol.GetCompressedSolution() -## Get new reconstructed solution -reconstructedSolution = interpSol.to_petsc().vec().copy() -reducedOrderBasisU.multTranspose(newCompressedSol[0], reconstructedSolution) - +## Get new reconstructed solution in PETSc format +resPETSc = Xh.element().to_petsc() +reducedOrderBasisU.multTranspose(newCompressedSol[0], resPETSc.vec()) -# reconstructedSolution = interpSol.to_petsc() ################################################## # Save Online data for vizualisation ################################################## @@ -166,61 +149,48 @@ print("-----------------------------------") print(" STEP II. 4: Saving datas on Disk ") print("-----------------------------------") -feelppsol = feelpp.functionSpace(mesh=FineMesh, order=1) - -# sol_ublas = feelpp._alg.VectorUBlas.createFromPETSc(reconstructedSolution) - -# uu = reconstructedSolution - -# sol_ublas = feelppsol.createFromPETSc(uu) +resFpp = Xh.element(resPETSc) # convert to feelpp element function +# Export NIRB approximation sol +if export : + ep = feelpp.exporter(mesh=FineMesh, name="feelpp_nirb_discr") + ep.addScalar("un", 1.) + if (order==1): + ep.addP1c("U_nirb", resFpp) + elif (order==2): + ep.addP2c("U_nirb", resFpp) + ep.save() -# sol_ublas = reconstructedSolution.to_ -# print(type(sol_ublas)) - -# feelppsol._alg.VectorUBlas.createFromPETSc(reconstructedSolution) - -# print(feelppsol) - - -# print('blas ', v_ublas) - -# feelppsol = coarseSol.functionSpace() -# petscsol = reconstructedSolution.copy() -# print('petsol', petscsol) -# print(feelppsol) -# print(coarseSol) -# coarseSol.createFromPETSc(reconstructedSolution) -# print(help(interpSol)) - - -export = feelpp.exporter(mesh=FineMesh, name="feelpp_nirb") -# export.addP1c("u", FineSol) -export.addP1c("u_interp", interpSol) -export.save() ################################################## # ONLINE ERRORS ################################################## -# finish = timeit.timeit() - -if ComputingError==1: +if ComputingError : print("-----------------------------------") print(" STEP II. 3: Compute online errors ") print("-----------------------------------") - # FineSol = SolveFpp(tbFine, mu) + FineSol = SolveFpp(tbFine, mu) - diffSolve = FineSol.to_petsc().vec() - reconstructedSolution + diffSolve = FineSol.to_petsc().vec() - resPETSc.vec() diffInterp = (FineSol - interpSol).to_petsc().vec() + error = [] + error.append(h) + error.append(diffSolve.norm()) + error.append(diffSolve.norm(PETSc.NormType.NORM_INFINITY)) + + error = np.array(error) + filename = 'nirb_error'+str(H)+'.txt' + np.savetxt(filename, error) + print("---------- NIRB Solve absolute Error -----------------") - print ('l2-norm =', diffSolve.norm()) - print ('Infinity-norm =', diffSolve.norm(PETSc.NormType.NORM_INFINITY)) + print ('l2-norm =', error[1]) + print ('Infinity-norm =', error[2]) print("---------- NIRB Solve relative Error -----------------") - print ('l2-norm =', diffSolve.norm()/FineSol.to_petsc().vec().norm()) - print ('Infinity-norm =', diffSolve.norm(PETSc.NormType.NORM_INFINITY)/FineSol.to_petsc().vec().norm(PETSc.NormType.NORM_INFINITY)) + print ('l2-norm =', error[1]/FineSol.to_petsc().vec().norm()) + print ('Infinity-norm =', error[2]/FineSol.to_petsc().vec().norm(PETSc.NormType.NORM_INFINITY)) print("---------- NIRB Interp Error -----------------") print ('l2-norm =', diffInterp.norm()) @@ -231,7 +201,7 @@ finish = timeit.timeit() print("Elapsed time = ", finish - start ) -print("NIRB ONLINE DONE! ") +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 942e559..41ab024 100644 --- a/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBinitCase.py +++ b/src/poc-1/src/Mordicus/Modules/Cemosis/DataCompressors/NIRBinitCase.py @@ -15,45 +15,20 @@ sys.path.append(nirb_dir) from nirb import * - - -# def assembleToolbox(tb, mu): - -# for i in range(0,mu.size()): -# tb.addParameterInModelProperties(mu.parameterName(i), mu(i)) -# tb.updateParameterValues() - - - -# def createInterpolator(tbCoarse, tbFine): -# """Create an interpolator between two toolboxes - -# Args: -# tbCorase (Toolbox): coarse toolbox -# tbFine (Toolbox): fine toolbox -# """ -# Vh_coarse = tbCoarse.spaceTemperature() -# Vh_fine = tbFine.spaceTemperature() -# interpolator = fi.interpolator(domain = Vh_coarse, image = Vh_fine, range = tbCoarse.rangeMeshElements()) -# return interpolator - - - -def initproblem(numberOfInitSnapshot, tbFine, tbCoarse, Dmu): +def initproblem(numberOfInitSnapshot, Dmu, tbFine, tbCoarse=None, type_tb='heat'): """ ---------------------------------------------------- generate snapshots in case POD method ---------------------------------------------------- tbFine : toolbox for fine mesh (initialized) - tbCoarse : toolbox for coarse mesh (initialized) + tbCoarse : toolbox for coarse mesh (initialized) if Rectification ListParam : list of Space parameters (to be done) numberOfSnapshot : the number of snapshot for initialization """ mu = Dmu.element() - print("-----------------------------------") print(" Get Initialized Snapshots ") print("-----------------------------------") @@ -61,32 +36,47 @@ def initproblem(numberOfInitSnapshot, tbFine, tbCoarse, Dmu): fineSnapList = [] coarseSnapList = [] - print('init mu', mu.view()) - for param in range(numberOfInitSnapshot): + if tbCoarse!=None : + for param in range(numberOfInitSnapshot): - dicparam = dict([ (mu.parameterName(i), mu(i)+float(2)) for i in range(mu.size())]) - lmu = [ mu(i)+float(2) for i in range(mu.size())] - + dicparam = dict([ (mu.parameterName(i), mu(i)/float(param+0.001)) for i in range(mu.size())]) + + mu.setParameters(dicparam) - # Dmu.setParameters(dicparam) - # for i in range(mu.size()): - # mu.setParameter(i, lmu[i]) - mu.setParameters(dicparam) + if feelpp.Environment.isMasterRank(): + print(f"Running simulation with mu = {mu}") - # print('init mu', mu.view()) + assembleToolbox(tbCoarse, mu) + assembleToolbox(tbFine, mu) - if feelpp.Environment.isMasterRank(): - print(f"Running simulation with mu = {mu}") + tbFine.solve() + tbCoarse.solve() - assembleToolbox(tbCoarse, mu) - assembleToolbox(tbFine, mu) + if (type_tb=='fluid') : + fineSnapList.append(tbFine.fieldVelocity()) + coarseSnapList.append(tbCoarse.fieldVelocity()) + else : + 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) - tbFine.solve() - tbCoarse.solve() + if feelpp.Environment.isMasterRank(): + print(f"Running simulation with mu = {mu}") + + assembleToolbox(tbFine, mu) + + tbFine.solve() + + if (type_tb=='fluid') : + fineSnapList.append(tbFine.fieldVelocity()) + else : + fineSnapList.append(tbFine.fieldTemperature()) - fineSnapList.append(tbFine.fieldTemperature()) - coarseSnapList.append(tbCoarse.fieldTemperature()) - # exportFine = feelpp.exporter(mesh=fineMesh, name="Snapshot") # exportFine.addScalar(f"mu{param}", mu(1)) # # exportFine.step() @@ -109,96 +99,28 @@ def initproblem(numberOfInitSnapshot, tbFine, tbCoarse, Dmu): 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 setToolbox(h, geo_path, model, dim=2, order=2, type_tb="heat"): -# """Set up the toolbox object for the given model and mesh - -# Args: -# h (float): size of the mesh -# geo_path (str): path to the goemetries file -# model (str): path to the model file -# dim (int): dimension of the mesh -# order (int): order of the finite elements -# type_tb (str): name of the toolbox {"heat"|"fluid"} - -# Returns: -# Toolbox: toolbox object -# """ - -# # load meshes -# mesh_ = feelpp.mesh(dim=2, realdim=2) -# mesh = feelpp.load(mesh_, geo_path, h) - -# # set mesh and model properties -# if type_tb == "heat": -# tb = heat.heat(dim=dim, order=order) -# elif type_tb == "fluid": -# tb = fluid.fluid(dim=dim) -# else: -# raise ValueError("Unknown toolbox") - -# tb.setMesh(mesh) -# tb.setModelProperties(model) - -# tb.init() - -# return tb - - - -def SolveFpp(toolBox, mu): +def SolveFpp(toolBox, mu, type_tb='heat'): """ ---------------------------------------------------- - generate snapshots in case POD method + Given a parameter mu, get Finite element solution + associated to this parameter ---------------------------------------------------- - tbFine : toolbox for fine mesh (initialized) - tbCoarse : toolbox for coarse mesh (initialized) - Dmu : Space parameters - numberOfSnapshot : the number of snapshot for initialization - + toolBox : toolbox (initialized) + mu : crb_parameter + type_tb : type of toolbox ('heat' of 'fluid') """ assembleToolbox(toolBox, mu) toolBox.solve() - return toolBox.fieldTemperature() + if (type_tb=='fluid') : + return toolBox.fieldVelocity() + elif (type_tb=='heat') : + return toolBox.fieldTemperature() + else : + raise ValueError("type_tb must be 'heat' or 'fluid'") + 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 a339356..655dce0 100644 --- a/src/poc-1/src/Mordicus/Modules/sorbonne/IO/numpyToVTKWriter.py +++ b/src/poc-1/src/Mordicus/Modules/sorbonne/IO/numpyToVTKWriter.py @@ -166,7 +166,7 @@ def numpyToVTKSanpWriteFromGMSH(self, SnapshotsList,FieldName="U", solutionName= p=self.VTKBase.nodes - print(p) + # print(p) numberOfNodes=np.shape(p)[0] @@ -192,7 +192,7 @@ def numpyToVTKSanpWriteFromGMSH(self, SnapshotsList,FieldName="U", solutionName= #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) - + print(VTK_data) size = VTK_data.GetSize() #print("size array", size) VTK_data.SetName(FieldName)