示例#1
0
文件: inputoutput.py 项目: pf4d/cslvr
def print_min_max(u, title, color='97', cls=None):
	"""
	Print the minimum and maximum values of ``u``, a Vector, Function, or array.

	:param u: the variable to print the min and max of
	:param title: the name of the function to print
	:param color: the color of printed text
	:type u: :class:`~dolfin.GenericVector`, :class:`~numpy.ndarray`, :class:`~dolfin.Function`, int, float, :class:`~dolfin.Constant`
	:type title: string
	:type color: string
	"""
	if isinstance(u, GenericVector):
		uMin = MPI.min(mpi_comm_world(), u.min())
		uMax = MPI.max(mpi_comm_world(), u.max())
		s    = title + ' <min, max> : <%.3e, %.3e>' % (uMin, uMax)
		print_text(s, color, cls=cls)
	elif isinstance(u, indexed.Indexed):
		dim = u.value_rank() + 1
		for i in range(u.value_rank()):
			uMin = u.vector().array()[i : u.vector().size() : dim].min()
			uMax = u.vector().array()[i : u.vector().size() : dim].max()
			s    = title + '_%i <min, max> : <%.3e, %.3e>' % (i, uMin, uMax)
			print_text(s, color, cls=cls)
	elif isinstance(u, ndarray):
		if u.dtype != float64:
			u = u.astype(float64)
		uMin = MPI.min(mpi_comm_world(), u.min())
		uMax = MPI.max(mpi_comm_world(), u.max())
		s    = title + ' <min, max> : <%.3e, %.3e>' % (uMin, uMax)
		print_text(s, color, cls=cls)
	elif isinstance(u, Function):# \
		#   or isinstance(u, dolfin.functions.function.Function):
		uMin = MPI.min(mpi_comm_world(), u.vector().min())
		uMax = MPI.max(mpi_comm_world(), u.vector().max())
		s    = title + ' <min, max> : <%.3e, %.3e>' % (uMin, uMax)
		print_text(s, color, cls=cls)
	elif isinstance(u, int) or isinstance(u, float):
		s    = title + ' : %.3e' % u
		print_text(s, color, cls=cls)
	elif isinstance(u, Constant):
		s    = title + ' : %.3e' % u(0)
		print_text(s, color, cls=cls)
	else:
		er = title + ": print_min_max function requires a Vector, Function" \
		     + ", array, int or float, not %s." % type(u)
		print_text(er, 'red', 1)
示例#2
0
    def compute(self, get):
        u = get(self.valuename)

        if u is None:
            return None

        if isinstance(u, Function):
            if len(u.vector().array()) > 0:
                minimum = numpy.min(u.vector().array())
            else:
                minimum = 1e16
            return MPI.min(mpi_comm_world(), minimum)
        elif hasattr(u, "__len__"):
            return MPI.min(mpi_comm_world(), min(u))
        elif isinstance(u, (float, int, long)):
            return MPI.min(mpi_comm_world(), u)
        else:
            raise Exception("Unable to take min of %s" % str(u))
示例#3
0
def test_interpolation_rank0(V):
    @function.expression.numba_eval
    def expr_eval(values, x, cell_idx):
        values[:, 0] = 1.0

    f = Expression(expr_eval, shape=())
    w = interpolate(f, V)
    x = w.vector()
    assert MPI.max(MPI.comm_world, abs(x.get_local()).max()) == 1
    assert MPI.min(MPI.comm_world, abs(x.get_local()).min()) == 1
示例#4
0
 def functional(self, t, u, p):
   # Only check final time
   if t < self.T:
     return 0
   else:
     # Compute stream function and report minimum
     psi = stream_function(u)
     psi_min = psi.vector().min()   # local minimum
     true_min = MPI.min(psi_min)    # minimum over all processes
     
     return true_min
示例#5
0
    def functional(self, t, u, p):
        # Only check final time
        if t < self.T:
            return 0
        else:
            # Compute stream function and report minimum
            psi = stream_function(u)
            psi_min = psi.vector().min()  # local minimum
            true_min = MPI.min(psi_min)  # minimum over all processes

            return true_min
示例#6
0
文件: helper.py 项目: pf4d/fenics_mpm
def print_min_max(u, title, color='97'):
    r"""
	Print the minimum and maximum values of ``u``, a Vector, Function, or array.

	:param u: the variable to print the min and max of
	:param title: the name of the function to print
	:param color: the color of printed text
	:type u: :class:`~fenics.GenericVector`, :class:`~numpy.ndarray`, :class:`~fenics.Function`, int, float, :class:`~fenics.Constant`
	:type title: string
	:type color: string
	"""
    if isinstance(u, GenericVector):
        uMin = MPI.min(MPI.comm_world, u.min())
        uMax = MPI.max(MPI.comm_world, u.max())
        s = title + ' <min, max> : <%.3e, %.3e>' % (uMin, uMax)
        print_text(s, color)
    elif isinstance(u, np.ndarray):
        if u.dtype != np.float64:
            u = u.astype(float64)
        uMin = MPI.min(MPI.comm_world, u.min())
        uMax = MPI.max(MPI.comm_world, u.max())
        s = title + ' <min, max> : <%.3e, %.3e>' % (uMin, uMax)
        print_text(s, color)
    elif isinstance(u, Function):  # \
        #   or isinstance(u, dolfin.functions.function.Function):
        uMin = MPI.min(MPI.comm_world, u.vector().min())
        uMax = MPI.max(MPI.comm_world, u.vector().max())
        s = title + ' <min, max> : <%.3e, %.3e>' % (uMin, uMax)
        print_text(s, color)
    elif isinstance(u, int) or isinstance(u, float):
        s = title + ' : %.3e' % u
        print_text(s, color)
    elif isinstance(u, Constant):
        s = title + ' : %.3e' % u(0)
        print_text(s, color)
    else:
        er = title + ": print_min_max function requires a Vector, Function" \
             + ", array, int or float, not %s." % type(u)
        print_text(er, 'red', 1)
示例#7
0
def test_interpolation_jit_rank0(V):
    f = Expression("1.0", degree=0)
    w = interpolate(f, V)
    x = w.vector()
    assert MPI.max(MPI.comm_world, abs(x.get_local()).max()) == 1
    assert MPI.min(MPI.comm_world, abs(x.get_local()).min()) == 1
示例#8
0
alpha = Constant(6*k*k)
Rb = Constant(1.0)
eta_top = Constant(1.0)
eta_bottom = Constant(0.01)
eta = eta_bottom + phi * (eta_top - eta_bottom)
forms_stokes = FormsStokes(mesh, mixedL, mixedG, alpha) \
    .forms_steady(eta, Rb * phi * Constant((0, -1, 0)))

ssc = StokesStaticCondensation(mesh,
                               forms_stokes['A_S'], forms_stokes['G_S'],
                               forms_stokes['B_S'],
                               forms_stokes['Q_S'], forms_stokes['S_S'])

# Particle advector
C_CFL = 0.5
hmin = MPI.min(comm, mesh.hmin())
ap = advect_rk3(ptcls, u_vec.function_space(), u_vec, "closed")


# Write particles and their values to XDMF file
particles_directory = "./particles/"
points_list = list(Point(*pp) for pp in ptcls.positions())
particles_values = ptcls.get_property(property_idx)
XDMFFile(os.path.join(particles_directory, "step%.4d.xdmf" % 0)) \
    .write(points_list, particles_values)

n_particles = MPI.sum(comm, len(points_list))
info("Solving with %d particles" % n_particles)

# Write the intitial compostition field to XDMF file
XDMFFile("composition.xdmf").write_checkpoint(phi, "composition", float(t), append=False)
示例#9
0
    rndnoise = np.random.randn(nbobspt*dimsol).reshape((nbobspt, dimsol))
    DD[ii] = dd + sigmas.reshape((len(sigmas),1))*rndnoise
waveobj.dd = DD
waveobj.solvefwd_cost()
if mpirank == 0:
    print 'noise misfit={}, regul cost={}, ratio={}'.format(waveobj.cost_misfit, \
    waveobj.cost_reg, waveobj.cost_misfit/waveobj.cost_reg)
#myplot.plot_timeseries(waveobj.solfwd[2], 'pd', 0, skip, dl.Function(V))


# Matvec for Hessian
if mpirank == 0:    print 'Compute gradient'
waveobj.update_PDE({'b':b_target_fn})
waveobj.solvefwd_cost()
waveobj.solveadj_constructgrad()
x, y = dl.Function(Vm), dl.Function(Vm)
setfct(x, 1.0)
if mpirank == 0:    print 'Time Hessian matvec'
for ii in range(10):
    MPI.barrier(mpicomm)
    t0 = Wtime()
    waveobj.mult(x.vector(), y.vector())
    t1 = Wtime()
    dt = t1-t0
    mindt = MPI.min(mpicomm, t1-t0)
    maxdt = MPI.max(mpicomm, t1-t0)
    avgdt = MPI.sum(mpicomm, t1-t0) / float(mpisize)
    if mpirank == 0:
        print 'min={}, max={}, avg={}'.format(mindt, maxdt, avgdt)

示例#10
0
def create_slice(basemesh, point, normal, closest_region=False, crinkle_clip=False):
    """Create a slicemesh from a basemesh.

    :param basemesh: Mesh to slice
    :param point: Point in slicing plane
    :param normal: Normal to slicing plane
    :param closest_region: Set to True to extract disjoint region closest to specified point
    :param crinkle_clip: Set to True to return mesh of same topological dimension as basemesh

    .. note::

        Only 3D-meshes currently supported for slicing.

    .. warning::

        Slice-instances are intended for visualization only, and may produce erronous
        results if used for computations.

    """
    assert basemesh.geometry().dim() == 3, "Can only slice 3D-meshes."

    P = np.array([point[0], point[1], point[2]], dtype=np.double)

    # Create unit normal
    n = np.array([normal[0],normal[1], normal[2]])
    n = n/np.linalg.norm(n)
    #self.n = Constant((n[0], n[1], n[2]))

    # Calculate the distribution of vertices around the plane
    # (sign of np.dot(p-P, n) determines which side of the plane p is on)
    vsplit = np.dot(basemesh.coordinates()-P, n)

    # Count each cells number of vertices on the "positive" side of the plane
    # Only cells with vertices on both sides of the plane intersect the plane
    operator = np.less
    npos = np.sum(vsplit[basemesh.cells()] < 0, 1)

    intersection_cells = basemesh.cells()[(npos > 0) & (npos < 4)]

    if len(intersection_cells) == 0:
        # Try to put "zeros" on other side of plane
        # FIXME: handle cells with vertices exactly intersecting the plane in a more robust manner.
        operator = np.greater
        npos = np.sum(vsplit[basemesh.cells()] > 0, 1)
        #cell_indices = (npos > 0) & (npos < 4)
        intersection_cells = basemesh.cells()[(npos > 0) & (npos < 4)]

    if crinkle_clip:
        cf = CellFunction("size_t", basemesh)
        cf.set_all(0)
        cf.array()[(npos>0) & (npos<4)] = 1
        mesh = create_submesh(basemesh, cf, 1)
    else:
        def add_cell(cells, cell):
            # Split cell into triangles
            for i in xrange(len(cell)-2):
                cells.append(cell[i:i+3])

        cells = []
        index = 0
        indexes = {}
        for c in intersection_cells:
            a = operator(vsplit[c], 0)
            positives = c[np.where(a==True)[0]]
            negatives = c[np.where(a==False)[0]]

            cell = []
            for pp_ind in positives:
                pp = basemesh.coordinates()[pp_ind]

                for pn_ind in negatives:
                    pn = basemesh.coordinates()[pn_ind]
                    if (pp_ind, pn_ind) not in indexes:
                        # Calculate intersection point with the plane
                        d = np.dot(P-pp, n)/np.dot(pp-pn, n)
                        ip = pp+(pp-pn)*d

                        indexes[(pp_ind, pn_ind)] = (index, ip)
                        index += 1

                    cell.append(indexes[(pp_ind, pn_ind)][0])


            add_cell(cells, cell)
        MPI.barrier(mpi_comm_world())

        # Assign global indices
        # TODO: Assign global indices properly
        dist = distribution(index)
        global_idx = sum(dist[:MPI.rank(mpi_comm_world())])
        vertices = {}
        for idx, p in indexes.values():
            vertices[idx] = (global_idx, p)
            global_idx += 1


        global_num_cells = MPI.sum(mpi_comm_world(), len(cells))
        global_num_vertices = MPI.sum(mpi_comm_world(), len(vertices))

        mesh = Mesh()

        # Return empty mesh if no intersections were found
        if global_num_cells == 0:
            mesh_editor = MeshEditor()
            mesh_editor.open(mesh, "triangle", 2, 3)

            mesh_editor.init_vertices(0)
            mesh_editor.init_cells(0)

            mesh_editor.close()
        else:

            # Distribute mesh if empty on any processors
            cells, vertices = distribute_meshdata(cells, vertices)

            # Build mesh
            mesh_editor = MeshEditor()
            mesh_editor.open(mesh, "triangle", 2, 3)

            mesh_editor.init_vertices(len(vertices))
            mesh_editor.init_cells(len(cells))

            for index, cell in enumerate(cells):
                mesh_editor.add_cell(index, cell[0], cell[1], cell[2])

            for local_index, (global_index, coordinates) in vertices.items():
                mesh_editor.add_vertex_global(int(local_index), int(global_index), coordinates)

            mesh_editor.close()
            mesh.topology().init(0, len(vertices), global_num_vertices)
            mesh.topology().init(2, len(cells), global_num_cells)


    if closest_region and mesh.size_global(0) > 0:
        assert MPI.size(mpi_comm_world())==1, "Extract closest region does not work in parallel"
        regions = compute_connectivity(mesh)
        i,d = mesh.bounding_box_tree().compute_closest_entity(Point(P))

        if d == MPI.min(mesh.mpi_comm(), d):
            v = regions[int(i)]
        else:
            v = 0

        v = MPI.max(mesh.mpi_comm(), v)
        mesh = create_submesh(mesh, regions, v)

    return mesh