def write_checkpoint(self): """Write checkpoint file (with solution and time) to disk.""" checkpoint_filepath = self.output_dir + "checkpoint_t" + str(self.state.time) + ".h5" self.latest_checkpoint_filepath = checkpoint_filepath phaseflow.helpers.print_once("Writing checkpoint file to " + checkpoint_filepath) with fenics.HDF5File(fenics.mpi_comm_world(), checkpoint_filepath, "w") as h5: h5.write(self.state.solution.function_space().mesh().leaf_node(), "mesh") h5.write(self.state.solution.leaf_node(), "solution") if self.second_order_time_discretization: h5.write(self.old_state.solution.leaf_node(), "old_solution") if fenics.MPI.rank(fenics.mpi_comm_world()) is 0: with h5py.File(checkpoint_filepath, "r+") as h5: h5.create_dataset("time", data = self.state.time) h5.create_dataset("timestep_size", data = self.timestep_size) if self.second_order_time_discretization: h5.create_dataset("old_time", data = self.old_state.time)
def write_data(self, file_name): print file_name ### Create a 1d mesh editor = fc.MeshEditor() mesh = fc.Mesh() editor.open(mesh, 1, 1) editor.init_vertices(len(self.center_xs)) editor.init_cells(len(self.center_xs) - 1) # Add vertices i = 0 for d in self.distances: editor.add_vertex(i, d) i += 1 # Add cells for i in range(len(self.distances) - 1): editor.add_cell(i, np.array([i, i+1], dtype = np.uintp)) editor.close() ### Create output hdf5 file out_file = fc.HDF5File(mesh.mpi_comm(), file_name, "w") ### Create and set data functions V = fc.FunctionSpace(mesh, "CG", 1) smb = fc.Function(V) surface = fc.Function(V) bed = fc.Function(V) width = fc.Function(V) thickness = fc.Function(V) smb.vector().set_local(self.flowline_data['smb']) smb.vector().apply("insert") surface.vector().set_local(self.flowline_data['surface']) surface.vector().apply("insert") bed.vector().set_local(self.flowline_data['bed']) bed.vector().apply("insert") width.vector().set_local(self.flowline_data['width']) width.vector().apply("insert") thickness.vector().set_local(self.flowline_data['surface'] - self.flowline_data['bed']) thickness.vector().apply("insert") out_file.write(mesh, "/mesh") out_file.write(smb.vector(), "/smb") out_file.write(surface.vector(), "/surface") out_file.write(bed.vector(), "/bed") out_file.write(width.vector(), "/width") out_file.write(thickness.vector(), "/thickness") out_file.close()
def read_checkpoint(self, filepath): """Read solutions and times from a checkpoint file.""" self._mesh = fenics.Mesh() print("Reading checkpoint from " + filepath) with fenics.HDF5File(self.mesh.mpi_comm(), filepath, "r") as h5: h5.read(self._mesh, "mesh", True) self._function_space = fenics.FunctionSpace( self.mesh, self._element) for i in range(self.time_order + 1): self._solutions[i] = fenics.Function(self.function_space) h5.read(self._solutions[i], "solution" + str(i)) """ fenics.HDF5File doesn't implement read methods for every write method. Our only option here seems to be to use a fenics.Vector to store values, because a reader is implemented for GenericVector, which Vector inherits from. Furthermore, for the correct read method to be called, we must pass a boolean as a third argument related to distributed memory. """ time = fenics.Vector(fenics.mpi_comm_world(), 1) h5.read(time, "time" + str(i), False) self._times[i] = time.get_local()[0] self.newton_solution = fenics.Function(self.function_space) self.setup_solver()
def read_checkpoint(self, checkpoint_filepath): """Read the checkpoint solution and time, perhaps to restart.""" phaseflow.helpers.print_once("Reading checkpoint file from " + checkpoint_filepath) self.mesh = fenics.Mesh() with fenics.HDF5File(self.mesh.mpi_comm(), checkpoint_filepath, "r") as h5: h5.read(self.mesh, "mesh", True) self.setup_element() self.setup_function_space() self.setup_states() with fenics.HDF5File(self.mesh.mpi_comm(), checkpoint_filepath, "r") as h5: h5.read(self.old_state.solution, "solution") if self.second_order_time_discretization: h5.read(self.old_old_state.solution, "old_solution") with h5py.File(checkpoint_filepath, "r") as h5: self.old_state.time = h5["time"].value self.set_timestep_size(h5["timestep_size"].value) if self.second_order_time_discretization: self.old_old_state.time = h5["old_time"].value self.restarted = True self.output_dir += "restarted_t" + str(self.old_state.time) + "/"
def writeToHDF5(self): print 'self.hdfFileName', self.hdfFileName, type(self.hdfFileName) mesh = Mesh(self.xmlFileName) hfile = fc.HDF5File(mesh.mpi_comm(), self.hdfFileName, "w") V = fc.FunctionSpace(mesh, 'CG', 1) thicknessiD = interpolateDataClass(thickness.interp, degree=2) bediD = interpolateDataClass(bed.interp, degree=2) surfaceiD = interpolateDataClass(surface.interp, degree=2) smbiD = interpolateDataClass(smb.interp, degree=2) velocityiD = interpolateDataClass(velocity.interp, degree=2) t2miD = interpolateDataClass(t2m.interp, degree=2) th = project(thicknessiD, V) be = project(bediD, V) su = project(surfaceiD, V) sm = project(smbiD, V) ve = project(velocityiD, V) t2 = project(t2miD, V) hfile.write(th, 'thickness') hfile.write(be, 'bed') hfile.write(su, 'surface') hfile.write(sm, 'smb') hfile.write(ve, 'velocity') hfile.write(t2, 't2m') hfile.write(mesh, "mesh") hfile.close() parTHF = File(self.paraFileName + 'thickness' + '.pvd') parTHF << th parBEF = File(self.paraFileName + 'bed' + '.pvd') parBEF << be parSUF = File(self.paraFileName + 'surface' + '.pvd') parSUF << su parSMF = File(self.paraFileName + 'smb' + '.pvd') parSMF << sm parVEF = File(self.paraFileName + 'velocity' + '.pvd') parVEF << ve parT2F = File(self.paraFileName, 't2m' + '.pvd') parT2F << t2 print 'Done with mesh'
def write_checkpoint(self, filepath): """Write solutions, times, and timestep sizes to a checkpoint file.""" print("Writing checkpoint to " + filepath) with fenics.HDF5File(self.mesh.mpi_comm(), filepath, "w") as h5: h5.write(self._solutions[0].function_space().mesh().leaf_node(), "mesh") for i in range(len(self._solutions)): h5.write(self._solutions[i].leaf_node(), "solution" + str(i)) """ The fenics.HDF5File interface does not allow us to write floats, but rather only a numpy array. """ h5.write(numpy.array((self._times[i], )), "time" + str(i))
def checkpoint(solution, time, checkpoint_filepath): """ Write a checkpoint file (with solution and time). The Poisson problem implemented in this module is not time dependent; but Phaseflow simulations are time dependent, and require h5py in addition to the built-in `fenics.HDF5File` for checkpointing/restarting between time steps. """ with fenics.HDF5File(fenics.mpi_comm_world(), checkpoint_filepath, "w") as h5: h5.write(solution.function_space().mesh(), "mesh") h5.write(solution, "solution") with h5py.File(checkpoint_filepath, "r+") as h5: h5.create_dataset("time", data=time)
def runModelButt(self): if len(markers) > 0: try: self.runButt.setEnabled(False) self.dr = float(self.sptlResLineEdit.text()) # dr = 150 self.pauseButt.setEnabled(True) interpolateData(True, self.dr,{}) ########################################### ### INTERPOLATE DATA SO EVEN INTERVAL ### ########################################### ''' Interpolating data at an even interval so the data points align with the invterval mesh. ''' self.thickness1dInterp = interp1d(thickness.distanceData, thickness.pathData) self.bed1dInterp = interp1d(bed.distanceData, bed.pathData) self.surface1dInterp = interp1d(surface.distanceData, surface.pathData) self.smb1dInterp = interp1d(smb.distanceData, smb.pathData) self.velocity1dInterp = interp1d(velocity.distanceData, velocity.pathData) self.t2m1dInterp = interp1d(t2m.distanceData, t2m.pathData) # N is the number of total data points including the last # Data points on interval [0, N*dr] inclusive on both ends self.N = int(np.floor(bed.distanceData[-1] / float(self.dr))) # length of path / resolution self.x = np.arange(0, (self.N + 1) * self.dr, self.dr) # start point, end point, number of segments. END POINT NOT INCLUDED! self.mesh = fc.IntervalMesh(self.N, 0, self.dr * self.N) # number of cells, start point, end point self.thicknessModelData = self.thickness1dInterp(self.x) self.bedModelData = self.bed1dInterp(self.x) self.surfaceModelData = self.surface1dInterp(self.x) self.smbModelData = self.smb1dInterp(self.x) self.velocityModelData = self.velocity1dInterp(self.x) self.t2mModelData = self.t2m1dInterp(self.x) self.THICKLIMIT = 10. # Ice is never less than this thick self.H = self.surfaceModelData - self.bedModelData self.surfaceModelData[self.H <= self.THICKLIMIT] = self.bedModelData[self.H <= self.THICKLIMIT] # FIXME the intervalMesh is consistantly 150 between each datapoint this not true for the data being sent self.hdf_name = '.data/latest_profile.h5' self.hfile = fc.HDF5File(self.mesh.mpi_comm(), self.hdf_name, "w") self.V = fc.FunctionSpace(self.mesh, "CG", 1) self.functThickness = fc.Function(self.V, name="Thickness") self.functBed = fc.Function(self.V, name="Bed") self.functSurface = fc.Function(self.V, name="Surface") self.functSMB = fc.Function(self.V, name='SMB') self.functVelocity = fc.Function(self.V, name='Velocity') self.functT2m = fc.Function(self.V, name='T2m') surface.pathPlotItem.setData(self.x, self.surfaceModelData) pg.QtGui.QApplication.processEvents() self.functThickness.vector()[:] = self.thicknessModelData self.functBed.vector()[:] = self.bedModelData self.functSurface.vector()[:] = self.surfaceModelData self.functSMB.vector()[:] = self.smbModelData self.functVelocity.vector()[:] = self.velocityModelData self.functT2m.vector()[:] = self.t2mModelData self.hfile.write(self.functThickness.vector(), "/thickness") self.hfile.write(self.functBed.vector(), "/bed") self.hfile.write(self.functSurface.vector(), "/surface") self.hfile.write(self.functSMB.vector(), "/smb") self.hfile.write(self.functVelocity.vector(), "/velocity") self.hfile.write(self.functT2m.vector(), "/t2m") self.hfile.write(self.mesh, "/mesh") self.hfile.close() self.runModel() except ValueError: print 'ERROR: Must have valid spatial resolution.'
def writeToHDF5(p, t, fname, meshname): mesh = Mesh(meshname) hfile = fc.HDF5File(mesh.mpi_comm(), fname, "w") V = fc.FunctionSpace(mesh, 'CG', 1) # thicknessModelData = thickness.interp(mesh.coordinates()[::, 0], mesh.coordinates()[::, 1], grid=False) # bedModelData = bed.interp(mesh.coordinates()[::, 0], mesh.coordinates()[::, 1], grid=False) # surfaceModelData = surface.interp(mesh.coordinates()[::, 0], mesh.coordinates()[::, 1], grid=False) # smbModelData = smb.interp(mesh.coordinates()[::, 0], mesh.coordinates()[::, 1], grid=False) # velocityModelData = velocity.interp(mesh.coordinates()[::, 0], mesh.coordinates()[::, 1], grid=False) # # functThickness = fc.Function(V, name="Thickness") # functBed = fc.Function(V, name="Bed") # functSurface = fc.Function(V, name="Surface") # functSMB = fc.Function(V, name='SMB') # functVelocity = fc.Function(V, name='Velocity') # # print 'len: ', len(functThickness.vector()[:]) # print 'len: ', len(thicknessModelData) # # functThickness.vector()[:] = thicknessModelData # functBed.vector()[:] = bedModelData # functSurface.vector()[:] = surfaceModelData # functSMB.vector()[:] = smbModelData # functVelocity.vector()[:] = velocityModelData # # hfile.write(functThickness, "thickness") # hfile.write(functBed, "bed") # hfile.write(functSurface, "surface") # hfile.write(functSMB, "smb") # hfile.write(functVelocity, "velocity") thicknessiD = interpolateData(thickness.interp, degree=2) bediD = interpolateData(bed.interp, degree=2) surfaceiD = interpolateData(surface.interp, degree=2) smbiD = interpolateData(smb.interp, degree=2) velocityiD = interpolateData(velocity.interp, degree=2) th = project(thicknessiD, V) be = project(bediD, V) su = project(surfaceiD, V) sm = project(smbiD, V) ve = project(velocityiD, V) hfile.write(th, 'thickness') hfile.write(be, 'bed') hfile.write(su, 'surface') hfile.write(sm, 'smb') hfile.write(ve, 'velocity') hfile.write(mesh, "mesh") hfile.close() print 'mesh ', mesh.coordinates()[::, 0], mesh.coordinates()[::, 1] # print 'velocity', velocityModelData # print 'thick', thicknessModelData # print 'bed', bedModelData # print 'surfae', surfaceModelData # print 'smb', smbModelData paraF = File('paraf.pvd') # paraF << th # paraF << be # paraF << su # paraF << sm paraF << ve print 'Done with mesh'
def __init__(self, fileName, timeEnd, timeStep, average=False): fc.set_log_active(False) self.times = [] self.BB = [] self.HH = [] self.TD = [] self.TB = [] self.TX = [] self.TY = [] self.TZ = [] self.us = [] self.ub = [] ########################################################## ################ MESH ################# ########################################################## # TODO: Probably do not have to save then open mesh self.mesh = df.Mesh() self.inFile = fc.HDF5File(self.mesh.mpi_comm(), fileName, "r") self.inFile.read(self.mesh, "/mesh", False) ######################################################### ################# FUNCTION SPACES ##################### ######################################################### self.E_Q = df.FiniteElement("CG", self.mesh.ufl_cell(), 1) self.Q = df.FunctionSpace(self.mesh, self.E_Q) self.E_V = df.MixedElement(self.E_Q, self.E_Q, self.E_Q) self.V = df.FunctionSpace(self.mesh, self.E_V) self.assigner_inv = fc.FunctionAssigner([self.Q, self.Q, self.Q], self.V) self.assigner = fc.FunctionAssigner(self.V, [self.Q, self.Q, self.Q]) self.U = df.Function(self.V) self.dU = df.TrialFunction(self.V) self.Phi = df.TestFunction(self.V) self.u, self.u2, self.H = df.split(self.U) self.phi, self.phi1, self.xsi = df.split(self.Phi) self.un = df.Function(self.Q) self.u2n = df.Function(self.Q) self.zero_sol = df.Function(self.Q) self.Bhat = df.Function(self.Q) self.H0 = df.Function(self.Q) self.A = df.Function(self.Q) if average: self.inFile.read(self.Bhat.vector(), "/bedAvg", True) self.inFile.read(self.A.vector(), "/smbAvg", True) self.inFile.read(self.H0.vector(), "/thicknessAvg", True) else: self.inFile.read(self.Bhat.vector(), "/bed", True) self.inFile.read(self.A.vector(), "/smb", True) self.inFile.read(self.H0.vector(), "/thickness", True) self.Hmid = theta * self.H + (1 - theta) * self.H0 self.B = softplus(self.Bhat, -rho / rho_w * self.Hmid, alpha=0.2) # Is not the bed, it is the lower surface self.S = self.B + self.Hmid self.width = df.interpolate(Width(degree=2), self.Q) self.strs = Stresses(self.U, self.Hmid, self.H0, self.H, self.width, self.B, self.S, self.Phi) self.R = -(self.strs.tau_xx + self.strs.tau_xz + self.strs.tau_b + self.strs.tau_d + self.strs.tau_xy) * df.dx ############################################################################# ######################## MASS CONSERVATION ################################ ############################################################################# self.h = df.CellSize(self.mesh) self.D = self.h * abs(self.U[0]) / 2. self.area = self.Hmid * self.width self.mesh_min = self.mesh.coordinates().min() self.mesh_max = self.mesh.coordinates().max() # Define boundaries self.ocean = df.FacetFunctionSizet(self.mesh, 0) self.ds = fc.ds(subdomain_data=self.ocean) # THIS DS IS FROM FENICS! border integral for f in df.facets(self.mesh): if df.near(f.midpoint().x(), self.mesh_max): self.ocean[f] = 1 if df.near(f.midpoint().x(), self.mesh_min): self.ocean[f] = 2 self.R += ((self.H - self.H0) / dt * self.xsi \ - self.xsi.dx(0) * self.U[0] * self.Hmid \ + self.D * self.xsi.dx(0) * self.Hmid.dx(0) \ - (self.A - self.U[0] * self.H / self.width * self.width.dx(0)) \ * self.xsi) * df.dx + self.U[0] * self.area * self.xsi * self.ds(1) \ - self.U[0] * self.area * self.xsi * self.ds(0) ##################################################################### ######################### SOLVER SETUP ########################### ##################################################################### # Bounds self.l_thick_bound = df.project(Constant(thklim), self.Q) self.u_thick_bound = df.project(Constant(1e4), self.Q) self.l_v_bound = df.project(-10000.0, self.Q) self.u_v_bound = df.project(10000.0, self.Q) self.l_bound = df.Function(self.V) self.u_bound = df.Function(self.V) self.assigner.assign(self.l_bound, [self.l_v_bound] * 2 + [self.l_thick_bound]) self.assigner.assign(self.u_bound, [self.u_v_bound] * 2 + [self.u_thick_bound]) # This should set the velocity at the divide (left) to zero self.dbc0 = df.DirichletBC(self.V.sub(0), 0, lambda x, o: df.near(x[0], self.mesh_min) and o) # Set the velocity on the right terminus to zero self.dbc1 = df.DirichletBC(self.V.sub(0), 0, lambda x, o: df.near(x[0], self.mesh_max) and o) # overkill? self.dbc2 = df.DirichletBC(self.V.sub(1), 0, lambda x, o: df.near(x[0], self.mesh_max) and o) # set the thickness on the right edge to thklim self.dbc3 = df.DirichletBC(self.V.sub(2), thklim, lambda x, o: df.near(x[0], self.mesh_max) and o) # Define variational solver for the mass-momentum coupled problem self.J = df.derivative(self.R, self.U, self.dU) self.coupled_problem = df.NonlinearVariationalProblem(self.R, self.U, bcs=[self.dbc0, self.dbc1, self.dbc3], \ J=self.J) self.coupled_problem.set_bounds(self.l_bound, self.u_bound) self.coupled_solver = df.NonlinearVariationalSolver(self.coupled_problem) # Acquire the optimizations in fenics_optimizations set_solver_options(self.coupled_solver) self.t = 0 self.timeEnd = float(timeEnd) self.dtFloat = float(timeStep) self.inFile.close()
def dataToHDF5(fileName, distanceData, thicknessPathData, bedPathData, surfacePathData, smbPathData, velocityPathData, t2mPathData, widthData, midFlowline, flowlines, resolution=1000): # Create interps for each of our variables thickness1dInterpAvg = interp1d(distanceData, thicknessPathData[1]) bed1dInterpAvg = interp1d(distanceData, bedPathData[1]) surface1dInterpAvg = interp1d(distanceData, surfacePathData[1]) smb1dInterpAvg = interp1d(distanceData, smbPathData[1]) velocity1dInterpAvg = interp1d(distanceData, velocityPathData[1]) t2m1dInterpAvg = interp1d(distanceData, t2mPathData[1]) thickness1dInterp = interp1d(distanceData, thicknessPathData[0]) bed1dInterp = interp1d(distanceData, bedPathData[0]) surface1dInterp = interp1d(distanceData, surfacePathData[0]) smb1dInterp = interp1d(distanceData, smbPathData[0]) velocity1dInterp = interp1d(distanceData, velocityPathData[0]) t2m1dInterp = interp1d(distanceData, t2mPathData[0]) width1dInterp = interp1d(distanceData, widthData) midFlowlineXData = [] midFlowlineYData = [] shearMargin0XData = [] shearMargin1XData = [] shearMargin0YData = [] shearMargin1YData = [] for i in range(len(midFlowline)): midFlowlineXData.append(midFlowline[i][0]) midFlowlineYData.append(midFlowline[i][1]) shearMargin0XData.append(flowlines[0][i][0]) shearMargin0YData.append(flowlines[0][i][1]) shearMargin1XData.append(flowlines[1][i][0]) shearMargin1YData.append(flowlines[1][i][1]) midFlowlineX1dInterp = interp1d(distanceData, midFlowlineXData) midFlowlineY1dInterp = interp1d(distanceData, midFlowlineYData) shearMargin0X1dInterp = interp1d(distanceData, shearMargin0XData) shearMargin0Y1dInterp = interp1d(distanceData, shearMargin0YData) shearMargin1X1dInterp = interp1d(distanceData, shearMargin1XData) shearMargin1Y1dInterp = interp1d(distanceData, shearMargin1YData) numberOfPoints = int(np.floor(distanceData[-1] / float(resolution))) x = np.arange(0, (numberOfPoints + 1) * resolution, resolution) mesh = fc.IntervalMesh(numberOfPoints, 0, resolution * numberOfPoints) thicknessModelData = thickness1dInterp(x) bedModelData = bed1dInterp(x) surfaceModelData = surface1dInterp(x) smbModelData = smb1dInterp(x) velocityModelData = velocity1dInterp(x) t2mModelData = t2m1dInterp(x) widthModelData = width1dInterp(x) midFlowlineXModelData = midFlowlineX1dInterp(x) midFlowlineYModelData = midFlowlineY1dInterp(x) shearMargin0XModelData = shearMargin0X1dInterp(x) shearMargin0YModelData = shearMargin0Y1dInterp(x) shearMargin1XModelData = shearMargin1X1dInterp(x) shearMargin1YModelData = shearMargin1Y1dInterp(x) thicknessModelDataAvg = thickness1dInterpAvg(x) bedModelDataAvg = bed1dInterpAvg(x) surfaceModelDataAvg = surface1dInterpAvg(x) smbModelDataAvg = smb1dInterpAvg(x) velocityModelDataAvg = velocity1dInterpAvg(x) t2mModelDataAvg = t2m1dInterpAvg(x) H = surfaceModelData - bedModelData HAvg = surfaceModelDataAvg - bedModelDataAvg surfaceModelData[H <= thklim] = bedModelData[H <= thklim] surfaceModelDataAvg[HAvg <= thklim] = bedModelDataAvg[HAvg <= thklim] fileName = '.data/' + fileName hfile = fc.HDF5File(mesh.mpi_comm(), '.data/latestProfile.h5', "w") profileFile = fc.HDF5File(mesh.mpi_comm(), str(fileName), "w") V = fc.FunctionSpace(mesh, "CG", 1) functThickness = fc.Function(V, name="Thickness") functBed = fc.Function(V, name="Bed") functSurface = fc.Function(V, name="Surface") functSMB = fc.Function(V, name="SMB") functVelocity = fc.Function(V, name="Velocity") functT2m = fc.Function(V, name="t2m") functWidth = fc.Function(V, name="width") functMidXValues = fc.Function(V, name='midX') functMidYValues = fc.Function(V, name='midY') functShear0XValues = fc.Function(V, name='Shear_0_X') functShear0YValues = fc.Function(V, name='Shear_0_Y') functShear1XValues = fc.Function(V, name='Shear_1_X') functShear1YValues = fc.Function(V, name='Shear_1_Y') functThicknessAvg = fc.Function(V, name="ThicknessAvg") functBedAvg = fc.Function(V, name="BedAvg") functSurfaceAvg = fc.Function(V, name="SurfaceAvg") functSMBAvg = fc.Function(V, name="SMBAvg") functVelocityAvg = fc.Function(V, name="VelocityAvg") functT2mAvg = fc.Function(V, name="t2mAvg") functThickness.vector()[:] = thicknessModelData functBed.vector()[:] = bedModelData functSurface.vector()[:] = surfaceModelData functSMB.vector()[:] = smbModelData functVelocity.vector()[:] = velocityModelData functT2m.vector()[:] = t2mModelData functWidth.vector()[:] = widthModelData functMidXValues.vector()[:] = midFlowlineXModelData functMidYValues.vector()[:] = midFlowlineYModelData functShear0XValues.vector()[:] = shearMargin0XModelData functShear0YValues.vector()[:] = shearMargin0YModelData functShear1XValues.vector()[:] = shearMargin1XModelData functShear1YValues.vector()[:] = shearMargin1YModelData functThicknessAvg.vector()[:] = thicknessModelDataAvg functBedAvg.vector()[:] = bedModelDataAvg functSurfaceAvg.vector()[:] = surfaceModelDataAvg functSMBAvg.vector()[:] = smbModelDataAvg functVelocityAvg.vector()[:] = velocityModelDataAvg functT2mAvg.vector()[:] = t2mModelDataAvg hfile.write(functThickness.vector(), "/thickness") hfile.write(functBed.vector(), "/bed") hfile.write(functSurface.vector(), "/surface") hfile.write(functSMB.vector(), "/smb") hfile.write(functVelocity.vector(), "/velocity") hfile.write(functT2m.vector(), "/t2m") hfile.write(functThicknessAvg.vector(), "/thicknessAvg") hfile.write(functBedAvg.vector(), "/bedAvg") hfile.write(functSurfaceAvg.vector(), "/surfaceAvg") hfile.write(functSMBAvg.vector(), "/smbAvg") hfile.write(functVelocityAvg.vector(), "/velocityAvg") hfile.write(functT2mAvg.vector(), "/t2mAvg") hfile.write(functWidth.vector(), "/width") hfile.write(functMidYValues.vector(), "/Mid_y") hfile.write(functMidXValues.vector(), "/Mid_x") hfile.write(functShear0XValues.vector(), "/Shear_0_x") hfile.write(functShear0YValues.vector(), "/Shear_0_y") hfile.write(functShear1XValues.vector(), "/Shear_1_x") hfile.write(functShear1YValues.vector(), "/Shear_1_y") hfile.write(mesh, "/mesh") profileFile.write(functThickness.vector(), "/thickness") profileFile.write(functBed.vector(), "/bed") profileFile.write(functSurface.vector(), "/surface") profileFile.write(functSMB.vector(), "/smb") profileFile.write(functVelocity.vector(), "/velocity") profileFile.write(functT2m.vector(), "/t2m") profileFile.write(functWidth.vector(), "/width") profileFile.write(functMidYValues.vector(), "/Mid_y") profileFile.write(functMidXValues.vector(), "/Mid_x") profileFile.write(functShear0XValues.vector(), "/Shear_0_x") profileFile.write(functShear0YValues.vector(), "/Shear_0_y") profileFile.write(functShear1XValues.vector(), "/Shear_1_x") profileFile.write(functShear1YValues.vector(), "/Shear_1_y") profileFile.write(mesh, "/mesh") profileFile.write(functThicknessAvg.vector(), "/thicknessAvg") profileFile.write(functBedAvg.vector(), "/bedAvg") profileFile.write(functSurfaceAvg.vector(), "/surfaceAvg") profileFile.write(functSMBAvg.vector(), "/smbAvg") profileFile.write(functVelocityAvg.vector(), "/velocityAvg") profileFile.write(functT2mAvg.vector(), "/t2mAvg") hfile.close() profileFile.close()
def __init__(self, mesh: fenics.Mesh, mode: str, file_name: str, function: fenics.Function, function_name: str): self.file = fenics.HDF5File(mesh.mpi_comm(), file_name, mode) self.function = function self.function_name = function_name
def onButtonPress(event): global line_points_x, line_points_y if event.inaxes is not None: ax = event.inaxes if ax == axarr[1] and event.button == 1: # print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' \ # %(event.button, event.x, event.y, event.xdata, event.ydata)) line_points_x.append(event.xdata) line_points_y.append(event.ydata) line.set_xdata(line_points_x) line.set_ydata(line_points_y) f.canvas.draw() # This was supposed to get the margins and plot them, but it isn't working. """ xml,yml,xmr,ymr = get_margins(event.xdata,event.ydata) print event.xdata,event.ydata,xml,yml,xmr,ymr l_margin_line_x.append(xml) l_margin_line_y.append(yml) r_margin_line_x.append(xmr) r_margin_line_y.append(ymr) margin_line_l.set_xdata(l_margin_line_x) margin_line_l.set_ydata(l_margin_line_y) margin_line_r.set_xdata(r_margin_line_x) margin_line_r.set_ydata(r_margin_line_y) """ f.canvas.draw() elif ax == axarr[1] and event.button == 3: # Collect data B = [] S = [] xf = [] yf = [] """ What a f*****g abortion, trying to keep the spacing of interpolated points even while moving through the individual points in the profile. This works within a meter or so, meaning that the difference between RESOLUTION and what is actually done is at most a meter. """ for i in range(1, len(line_points_x)): dx = line_points_x[i] - line_points_x[i - 1] dy = line_points_y[i] - line_points_y[i - 1] d = sqrt(dx**2 + dy**2) xhat = dx / d yhat = dy / d total_distance = 0. if i == 1: p = 0 remainder = 0 else: p = 1 while (p * RESOLUTION + (RESOLUTION - remainder)) < d: if p <= 1: xf.append(line_points_x[i - 1] + xhat * p * (RESOLUTION - remainder)) yf.append(line_points_y[i - 1] + yhat * p * (RESOLUTION - remainder)) else: xf.append(xf[-1] + xhat * RESOLUTION) yf.append(yf[-1] + yhat * RESOLUTION) p += 1 remainder = d - ((p - 2) * RESOLUTION + (RESOLUTION - remainder)) for x, y in zip(xf, yf): B.append(Binterp(x, y)) S.append(Sinterp(x, y)) # print x,y,B[-1],S[-1] B = array(B)[:, 0] S = array(S)[:, 0] # Smooth the surface #S = smooth(S,15) #B = smooth(B,15) # Plot data ff, ax = plt.subplots(1) ax.plot(B, lw=4) ax.plot(S, lw=4) plt.show() # Write data N = len(B) mesh = fc.IntervalMesh(N - 1, 0, RESOLUTION * (N - 1)) V = fc.FunctionSpace(mesh, "CG", 1) hfile = fc.HDF5File(mesh.mpi_comm(), "latest_profile.h5", "w") H = S - B S[H <= THICKLIMIT] = B[H <= THICKLIMIT] # Functions with the data as a vector and V is the functionspace Bed = fc.Function(V, name="Bed") Surface = fc.Function(V, name="Surface") Bed.vector()[:] = B Surface.vector()[:] = S hfile.write(Bed.vector(), "/bed") hfile.write(Surface.vector(), "/surface") hfile.write(mesh, "/mesh") hfile.close()
def run(output_dir="output/wang2010_natural_convection_air", rayleigh_number=1.e6, prandtl_number=0.71, stefan_number=0.045, heat_capacity=1., thermal_conductivity=1., liquid_viscosity=1., solid_viscosity=1.e8, gravity=(0., -1.), m_B=None, ddT_m_B=None, penalty_parameter=1.e-7, temperature_of_fusion=-1.e12, regularization_smoothing_factor=0.005, mesh=fenics.UnitSquareMesh(fenics.dolfin.mpi_comm_world(), 20, 20, "crossed"), initial_values_expression=("0.", "0.", "0.", "0.5*near(x[0], 0.) -0.5*near(x[0], 1.)"), boundary_conditions=[{ "subspace": 0, "value_expression": ("0.", "0."), "degree": 3, "location_expression": "near(x[0], 0.) | near(x[0], 1.) | near(x[1], 0.) | near(x[1], 1.)", "method": "topological" }, { "subspace": 2, "value_expression": "0.5", "degree": 2, "location_expression": "near(x[0], 0.)", "method": "topological" }, { "subspace": 2, "value_expression": "-0.5", "degree": 2, "location_expression": "near(x[0], 1.)", "method": "topological" }], start_time=0., end_time=10., time_step_size=1.e-3, stop_when_steady=True, steady_relative_tolerance=1.e-4, adaptive=False, adaptive_metric="all", adaptive_solver_tolerance=1.e-4, nlp_absolute_tolerance=1.e-8, nlp_relative_tolerance=1.e-8, nlp_max_iterations=50, restart=False, restart_filepath=""): """Run Phaseflow. Phaseflow is configured entirely through the arguments in this run() function. See the tests and examples for demonstrations of how to use this. """ # Handle default function definitions. if m_B is None: def m_B(T, Ra, Pr, Re): return T * Ra / (Pr * Re**2) if ddT_m_B is None: def ddT_m_B(T, Ra, Pr, Re): return Ra / (Pr * Re**2) # Report arguments. phaseflow.helpers.print_once( "Running Phaseflow with the following arguments:") phaseflow.helpers.print_once(phaseflow.helpers.arguments()) phaseflow.helpers.mkdir_p(output_dir) if fenics.MPI.rank(fenics.mpi_comm_world()) is 0: arguments_file = open(output_dir + "/arguments.txt", "w") arguments_file.write(str(phaseflow.helpers.arguments())) arguments_file.close() # Check if 1D/2D/3D. dimensionality = mesh.type().dim() phaseflow.helpers.print_once("Running " + str(dimensionality) + "D problem") # Initialize time. if restart: with h5py.File(restart_filepath, "r") as h5: time = h5["t"].value assert (abs(time - start_time) < TIME_EPS) else: time = start_time # Define the mixed finite element and the solution function space. W_ele = make_mixed_fe(mesh.ufl_cell()) W = fenics.FunctionSpace(mesh, W_ele) # Set the initial values. if restart: mesh = fenics.Mesh() with fenics.HDF5File(mesh.mpi_comm(), restart_filepath, "r") as h5: h5.read(mesh, "mesh", True) W_ele = make_mixed_fe(mesh.ufl_cell()) W = fenics.FunctionSpace(mesh, W_ele) w_n = fenics.Function(W) with fenics.HDF5File(mesh.mpi_comm(), restart_filepath, "r") as h5: h5.read(w_n, "w") else: w_n = fenics.interpolate( fenics.Expression(initial_values_expression, element=W_ele), W) # Organize the boundary conditions. bcs = [] for item in boundary_conditions: bcs.append( fenics.DirichletBC(W.sub(item["subspace"]), item["value_expression"], item["location_expression"], method=item["method"])) # Set the variational form. """Set local names for math operators to improve readability.""" inner, dot, grad, div, sym = fenics.inner, fenics.dot, fenics.grad, fenics.div, fenics.sym """The linear, bilinear, and trilinear forms b, a, and c, follow the common notation for applying the finite element method to the incompressible Navier-Stokes equations, e.g. from danaila2014newton and huerta2003fefluids. """ def b(u, q): return -div(u) * q # Divergence def D(u): return sym(grad(u)) # Symmetric part of velocity gradient def a(mu, u, v): return 2. * mu * inner(D(u), D(v)) # Stokes stress-strain def c(w, z, v): return dot(dot(grad(z), w), v) # Convection of the velocity field dt = fenics.Constant(time_step_size) Re = fenics.Constant(reynolds_number) Ra = fenics.Constant(rayleigh_number) Pr = fenics.Constant(prandtl_number) Ste = fenics.Constant(stefan_number) C = fenics.Constant(heat_capacity) K = fenics.Constant(thermal_conductivity) g = fenics.Constant(gravity) def f_B(T): return m_B(T=T, Ra=Ra, Pr=Pr, Re=Re) * g # Buoyancy force, $f = ma$ gamma = fenics.Constant(penalty_parameter) T_f = fenics.Constant(temperature_of_fusion) r = fenics.Constant(regularization_smoothing_factor) def P(T): return 0.5 * (1. - fenics.tanh( (T_f - T) / r)) # Regularized phase field. mu_l = fenics.Constant(liquid_viscosity) mu_s = fenics.Constant(solid_viscosity) def mu(T): return mu_s + (mu_l - mu_s) * P(T) # Variable viscosity. L = C / Ste # Latent heat u_n, p_n, T_n = fenics.split(w_n) w_w = fenics.TrialFunction(W) u_w, p_w, T_w = fenics.split(w_w) v, q, phi = fenics.TestFunctions(W) w_k = fenics.Function(W) u_k, p_k, T_k = fenics.split(w_k) F = (b(u_k, q) - gamma * p_k * q + dot(u_k - u_n, v) / dt + c(u_k, u_k, v) + b(v, p_k) + a(mu(T_k), u_k, v) + dot(f_B(T_k), v) + C / dt * (T_k - T_n) * phi - dot(C * T_k * u_k, grad(phi)) + K / Pr * dot(grad(T_k), grad(phi)) + 1. / dt * L * (P(T_k) - P(T_n)) * phi) * fenics.dx def ddT_f_B(T): return ddT_m_B(T=T, Ra=Ra, Pr=Pr, Re=Re) * g def sech(theta): return 1. / fenics.cosh(theta) def dP(T): return sech((T_f - T) / r)**2 / (2. * r) def dmu(T): return (mu_l - mu_s) * dP(T) # Set the Jacobian (formally the Gateaux derivative) in variational form. JF = (b(u_w, q) - gamma * p_w * q + dot(u_w, v) / dt + c(u_k, u_w, v) + c(u_w, u_k, v) + b(v, p_w) + a(T_w * dmu(T_k), u_k, v) + a(mu(T_k), u_w, v) + dot(T_w * ddT_f_B(T_k), v) + C / dt * T_w * phi - dot(C * T_k * u_w, grad(phi)) - dot(C * T_w * u_k, grad(phi)) + K / Pr * dot(grad(T_w), grad(phi)) + 1. / dt * L * T_w * dP(T_k) * phi) * fenics.dx # Set the functional metric for the error estimator for adaptive mesh refinement. """I haven't found a good way to make this flexible yet. Ideally the user would be able to write the metric, but this would require giving the user access to much data that phaseflow is currently hiding. """ M = P(T_k) * fenics.dx if adaptive_metric == "phase_only": pass elif adaptive_metric == "all": M += T_k * fenics.dx for i in range(dimensionality): M += u_k[i] * fenics.dx else: assert (False) # Make the problem. problem = fenics.NonlinearVariationalProblem(F, w_k, bcs, JF) # Make the solvers. """ For the purposes of this project, it would be better to just always use the adaptive solver; but unfortunately the adaptive solver encounters nan's whenever evaluating the error for problems not involving phase-change. So far my attempts at writing a MWE to reproduce the issue have failed. """ adaptive_solver = fenics.AdaptiveNonlinearVariationalSolver(problem, M) adaptive_solver.parameters["nonlinear_variational_solver"]["newton_solver"]["maximum_iterations"]\ = nlp_max_iterations adaptive_solver.parameters["nonlinear_variational_solver"]["newton_solver"]["absolute_tolerance"]\ = nlp_absolute_tolerance adaptive_solver.parameters["nonlinear_variational_solver"]["newton_solver"]["relative_tolerance"]\ = nlp_relative_tolerance static_solver = fenics.NonlinearVariationalSolver(problem) static_solver.parameters["newton_solver"][ "maximum_iterations"] = nlp_max_iterations static_solver.parameters["newton_solver"][ "absolute_tolerance"] = nlp_absolute_tolerance static_solver.parameters["newton_solver"][ "relative_tolerance"] = nlp_relative_tolerance # Open a context manager for the output file. with fenics.XDMFFile(output_dir + "/solution.xdmf") as solution_file: # Write the initial values. write_solution(solution_file, w_n, time) if start_time >= end_time - TIME_EPS: phaseflow.helpers.print_once( "Start time is already too close to end time. Only writing initial values." ) return w_n, mesh # Solve each time step. progress = fenics.Progress("Time-stepping") fenics.set_log_level(fenics.PROGRESS) for it in range(1, MAX_TIME_STEPS): if (time > end_time - TIME_EPS): break if adaptive: adaptive_solver.solve(adaptive_solver_tolerance) else: static_solver.solve() time = start_time + it * time_step_size phaseflow.helpers.print_once("Reached time t = " + str(time)) write_solution(solution_file, w_k, time) # Write checkpoint/restart files. restart_filepath = output_dir + "/restart_t" + str(time) + ".h5" with fenics.HDF5File(fenics.mpi_comm_world(), restart_filepath, "w") as h5: h5.write(mesh.leaf_node(), "mesh") h5.write(w_k.leaf_node(), "w") if fenics.MPI.rank(fenics.mpi_comm_world()) is 0: with h5py.File(restart_filepath, "r+") as h5: h5.create_dataset("t", data=time) # Check for steady state. if stop_when_steady and steady(W, w_k, w_n, steady_relative_tolerance): phaseflow.helpers.print_once( "Reached steady state at time t = " + str(time)) break # Set initial values for next time step. w_n.leaf_node().vector()[:] = w_k.leaf_node().vector() # Report progress. progress.update(time / end_time) if time >= (end_time - fenics.dolfin.DOLFIN_EPS): phaseflow.helpers.print_once("Reached end time, t = " + str(end_time)) break # Return the interpolant to sample inside of Python. w_k.rename("w", "state") return w_k, mesh