def test_saving_loading_and_sphere(self):
        # domain physical_sizes (edge length of square)
        length = 8 + 4 * rand()
        R = 17 + 6 * rand()  # sphere radius
        res = 2  # nb_grid_pts
        x_c = length * rand()  # coordinates of center
        y_c = length * rand()
        x = np.arange(res, dtype=float) * length / res - x_c
        y = np.arange(res, dtype=float) * length / res - y_c
        r2 = np.zeros((res, res))
        for i in range(res):
            for j in range(res):
                r2[i, j] = x[i] ** 2 + y[j] ** 2
        h = np.sqrt(R ** 2 - r2) - R  # profile of sphere

        S1 = Topography(h, h.shape)
        with tmp_dir() as dir:
            fname = os.path.join(dir, "surface")
            S1.to_matrix(fname)
            S2 = read_matrix(fname)
            self.assertTrue(np.allclose(S2.heights(), S1.heights()))

        S3 = make_sphere(R, (res, res), (length, length), (x_c, y_c))
        self.assertTrue(np.array_equal(S1.heights(), S2.heights()))
        self.assertTrue(np.array_equal(S1.heights(), S3.heights()))
Beispiel #2
0
    def test_saving_loading_and_sphere(self):
        # domain physical_sizes (edge length of square)
        length = 8 + 4 * rand()
        R = 17 + 6 * rand()  # sphere radius
        res = 2  # nb_grid_pts
        x_c = length * rand()  # coordinates of center
        y_c = length * rand()
        x = np.arange(res, dtype=float) * length / res - x_c
        y = np.arange(res, dtype=float) * length / res - y_c
        r2 = np.zeros((res, res))
        for i in range(res):
            for j in range(res):
                r2[i, j] = x[i]**2 + y[j]**2
        h = np.sqrt(R**2 - r2) - R  # profile of sphere

        S1 = Topography(h, h.shape)
        with tmp_dir() as dir:
            fname = os.path.join(dir, "surface")
            S1.save(fname)
            # TODO: datafiles fixture may solve the problem
            # For some reason, this does not find the file...
            # S2 = read_asc(fname)
            S2 = S1

        S3 = make_sphere(R, (res, res), (length, length), (x_c, y_c))
        self.assertTrue(np.array_equal(S1.heights(), S2.heights()))
        self.assertTrue(np.array_equal(S1.heights(), S3.heights()))
def test_squeeze():
    x = np.linspace(0, 4 * np.pi, 101)
    y = np.linspace(0, 8 * np.pi, 103)
    h = np.sin(x.reshape(-1, 1)) + np.cos(y.reshape(1, -1))
    surface = Topography(h, (1.2, 3.2)).scale(2.0)
    surface2 = surface.squeeze()
    assert isinstance(surface2, Topography)
    np.testing.assert_allclose(surface.heights(), surface2.heights())
def test_constrained_conjugate_gradients():
    # punch radius:
    r_s = 20.0
    # equivalent Young's modulus
    E_s = 3.56
    for nx, ny in [(256, 256), (256, 255), (255, 256)]:
        for disp0, normal_force in [(None, 15), (0.1, None)]:
            sx = sy = 2.5 * r_s
            substrate = FreeFFTElasticHalfSpace((nx, ny), E_s, (sx, sy))
            x_range = np.arange(nx).reshape(-1, 1)
            y_range = np.arange(ny).reshape(1, -1)
            r_sq = (sx / nx * (x_range - nx // 2)) ** 2 + \
                   (sy / ny * (y_range - ny // 2)) ** 2
            surface = Topography(
                np.ma.masked_where(r_sq > r_s ** 2, np.zeros([nx, ny])),
                (sx, sy)
            )
            system = make_system(substrate, surface)
            try:
                result = system.minimize_proxy(offset=disp0,
                                               external_force=normal_force,
                                               pentol=1e-4)
            except substrate.FreeBoundaryError as err:
                if False:
                    import matplotlib.pyplot as plt
                    fig, ax = plt.subplots()

                    # ax.pcolormesh(substrate.force /
                    # surface.area_per_pt,rasterized=True)
                    plt.colorbar(ax.pcolormesh(surface.heights(),
                                               rasterized=True))
                    ax.set_xlabel("")
                    ax.set_ylabel("")

                    ax.legend()

                    fig.tight_layout()
                    plt.show(block=True)

                raise err
            offset = result.offset
            forces = -result.jac
            converged = result.success

            # Check that calculation has converged
            assert converged

            # Check that target values have been reached
            if disp0 is not None:
                np.testing.assert_almost_equal(offset, disp0)
            if normal_force is not None:
                np.testing.assert_almost_equal(-forces.sum(), normal_force)

            # Check contact stiffness
            np.testing.assert_almost_equal(
                -forces.sum() / offset / (2 * r_s * E_s),
                1.0, decimal=2)
def test_hard_wall_bearing_area(comm):
    # Test that at very low hardness we converge to (almost) the bearing
    # area geometry
    pnp = Reduction(comm)
    fullsurface = open_topography(os.path.join(FIXTURE_DIR, 'surface1.out'))
    fullsurface = fullsurface.topography(
        physical_sizes=fullsurface.channels[0].nb_grid_pts)
    nb_domain_grid_pts = fullsurface.nb_grid_pts
    substrate = PeriodicFFTElasticHalfSpace(nb_domain_grid_pts,
                                            1.0,
                                            fft='mpi',
                                            communicator=comm)
    surface = Topography(
        fullsurface.heights(),
        physical_sizes=nb_domain_grid_pts,
        decomposition='domain',
        subdomain_locations=substrate.topography_subdomain_locations,
        nb_subdomain_grid_pts=substrate.topography_nb_subdomain_grid_pts,
        communicator=substrate.communicator)

    plastic_surface = PlasticTopography(surface, 1e-12)
    system = PlasticNonSmoothContactSystem(substrate, plastic_surface)
    offset = -0.002
    if comm.rank == 0:

        def cb(it, p_r, d):
            print("{0}: area = {1}".format(it, d["area"]))
    else:

        def cb(it, p_r, d):
            pass

    result = system.minimize_proxy(offset=offset, callback=cb)
    assert result.success
    c = result.jac > 0.0
    ncontact = pnp.sum(c)
    assert plastic_surface.plastic_area == ncontact * surface.area_per_pt
    bearing_area = bisect(
        lambda x: pnp.sum((surface.heights() > x)) - ncontact, -0.03, 0.03)
    cba = surface.heights() > bearing_area
    # print(comm.Get_rank())
    assert pnp.sum(np.logical_not(c == cba)) < 25
Beispiel #6
0
def test_positions_and_heights():
    X = np.arange(3).reshape(1, 3)
    Y = np.arange(4).reshape(4, 1)
    h = X + Y

    t = Topography(h, (8, 6))

    assert t.nb_grid_pts == (4, 3)

    assert_array_equal(t.heights(), h)
    X2, Y2, h2 = t.positions_and_heights()
    assert_array_equal(X2, [
        (0, 0, 0),
        (2, 2, 2),
        (4, 4, 4),
        (6, 6, 6),
    ])
    assert_array_equal(Y2, [
        (0, 2, 4),
        (0, 2, 4),
        (0, 2, 4),
        (0, 2, 4),
    ])
    assert_array_equal(h2, [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)])

    #
    # After detrending, the position and heights should have again
    # just 3 arrays and the third array should be the same as .heights()
    #
    dt = t.detrend(detrend_mode='slope')

    np.testing.assert_allclose(dt.heights(), [(0, 0, 0), (0, 0, 0), (0, 0, 0),
                                              (0, 0, 0)],
                               atol=1e-15)

    X2, Y2, h2 = dt.positions_and_heights()

    assert h2.shape == (4, 3)
    assert_array_equal(X2, [
        (0, 0, 0),
        (2, 2, 2),
        (4, 4, 4),
        (6, 6, 6),
    ])
    assert_array_equal(Y2, [
        (0, 2, 4),
        (0, 2, 4),
        (0, 2, 4),
        (0, 2, 4),
    ])
    np.testing.assert_allclose(h2, [(0, 0, 0), (0, 0, 0), (0, 0, 0),
                                    (0, 0, 0)],
                               atol=1e-15)
def test_fourier_interpolate_nyquist(plot=False):
    # asserts that the interpolation follows the "minimal-osciallation"
    # assumption for the nyquist frequency

    topography = Topography(np.array([[1], [-1]]), physical_sizes=(1., 1.))
    interpolated_topography = topography.interpolate_fourier((64, 1))

    if plot:
        import matplotlib.pyplot as plt
        fig, ax = plt.subplots()

        x, y = topography.positions()
        ax.plot(x.flat, topography.heights().flat, "+")

        x, y = interpolated_topography.positions()
        ax.plot(x.flat, interpolated_topography.heights().flat, "-")
        fig.show()

    x, y = interpolated_topography.positions()
    np.testing.assert_allclose(interpolated_topography.heights(),
                               np.cos(2 * np.pi * x), atol=1e-14)
Beispiel #8
0
def constrained_conjugate_gradients(substrate, topography, hardness=None,
                                    external_force=None, offset=None,
                                    initial_displacements=None,
                                    initial_forces=None,
                                    pentol=None, prestol=1e-5,
                                    mixfac=0.1,
                                    maxiter=100000,
                                    logger=None,
                                    callback=None,
                                    verbose=False):
    """
    Use a constrained conjugate gradient optimization to find the equilibrium
    configuration deflection of an elastic manifold. The conjugate gradient
    iteration is reset using the steepest descent direction whenever the
    contact area changes.
    Method is described in I.A. Polonsky, L.M. Keer, Wear 231, 206 (1999)
    Parameters
    ----------
    substrate : elastic manifold
        Elastic manifold.
    topography: SurfaceTopography object
        Height profile of the rigid counterbody
    hardness : array_like
        Hardness of the substrate. Pressure cannot exceed this value. Can be
        scalar or array (i.e. per pixel) value.
    external_force : float
        External force. Constrains the sum of forces to this value.
    offset : float
        Offset of rigid surface. Ignore if external_force is specified.
    initial_displacements : array_like
        Displacement field for initializing the solver. Guess an initial
        value if set to None.
    initial_forces: array_like
        pixel forces field for initializing the solver. Is computed from
        initial_displacements if none
    pentol : float
        Maximum penetration of contacting regions required for convergence.
    prestol : float
        maximum pressure outside the contact region allowed for convergence
    maxiter : float
        Maximum number of iterations.
    logger: ContactMechanics.Tools.Logger
        reports status and values at each iteration
    callback: callable(int iteration, array_link forces, dict d)
        called each iteration. The dictionary contains additional scalars
    verbose: bool
        If True, more scalar quantities are passed to the logger
    Returns
    -------
    Optimisation result
        x: displacements
        fun: elastic energy
        jac: forces
        active_set: points where forces are not constrained to 0 or hardness
        offset: offset i rigid surface, results from the optimization processes
           when the external_force is constrained
    """

    if substrate.nb_subdomain_grid_pts != substrate.nb_domain_grid_pts:
        # check that a topography instance is provided and not only a numpy
        # array
        if not hasattr(topography, "nb_grid_pts"):
            raise ValueError("You should provide a topography object when "
                             "working with MPI")

    reduction = Reduction(substrate.communicator)

    # surface is the array holding the data assigned to the processsor
    if not hasattr(topography, "nb_grid_pts"):
        surface = topography
        topography = Topography(surface,
                                physical_sizes=substrate.physical_sizes)
    else:
        surface = topography.heights()  # Local data

    # Note: Suffix _r deontes real-space _q reciprocal space 2d-arrays

    nb_surface_pts = np.prod(topography.nb_grid_pts)
    if pentol is None:
        # Heuristics for the possible tolerance on penetration.
        # This is necessary because numbers can vary greatly
        # depending on the system of units.
        pentol = topography.rms_height_from_area() / (
                10 * np.mean(topography.nb_grid_pts))
        # If pentol is zero, then this is a flat surface. This only makes
        # sense for nonperiodic calculations, i.e. it is a punch. Then
        # use the offset to determine the tolerance
        if pentol == 0:
            pentol = (offset + reduction.sum(surface[...]) / nb_surface_pts) \
                     / 1000
        # If we are still zero use an arbitrary value
        if pentol == 0:
            pentol = 1e-3

    surf_mask = np.ma.getmask(
        surface)  # TODO: Test behaviour with masked arrays.

    if logger is not None:
        logger.pr('maxiter = {0}'.format(maxiter))
        logger.pr('pentol = {0}'.format(pentol))

    if offset is None:
        offset = 0

    if initial_displacements is None:
        u_r = np.zeros(substrate.nb_subdomain_grid_pts)
    else:
        u_r = initial_displacements.copy()

    # slice of the local data of the computation subdomain corresponding to the
    # topography subdomain. It's typically the first half of the computation
    # subdomain (along the non-parallelized dimension) for FreeFFTElHS
    # It's the same for PeriodicFFTElHS
    comp_slice = [slice(0, max(0, min(
        substrate.nb_grid_pts[i] - substrate.subdomain_locations[i],
        substrate.nb_subdomain_grid_pts[i])))
                  for i in range(substrate.dim)]
    if substrate.dim not in (1, 2):
        raise Exception(
            ("Constrained conjugate gradient currently only implemented for 1 "
             "or 2 dimensions (Your substrate has {}.).").format(
                substrate.dim))

    comp_mask = np.zeros(substrate.nb_subdomain_grid_pts, dtype=bool)
    comp_mask[tuple(comp_slice)] = True

    surf_mask = np.ma.getmask(surface)
    if surf_mask is np.ma.nomask:
        surf_mask = np.ones(topography.nb_subdomain_grid_pts, dtype=bool)
    else:
        comp_mask[tuple(comp_slice)][surf_mask] = False
        surf_mask = np.logical_not(surf_mask)
    pad_mask = np.logical_not(comp_mask)
    N_pad = reduction.sum(pad_mask * 1)
    u_r[comp_mask] = np.where(u_r[comp_mask] < surface[surf_mask] + offset,
                              surface[surf_mask] + offset,
                              u_r[comp_mask])

    result = optim.OptimizeResult()
    result.nfev = 0
    result.nit = 0
    result.success = False
    result.message = "Not Converged (yet)"

    # Compute forces
    # p_r = -np.fft.ifft2(np.fft.fft2(u_r)/gf_q).real
    if initial_forces is None:
        p_r = substrate.evaluate_force(u_r)
    else:
        p_r = initial_forces.copy()
        u_r = substrate.evaluate_disp(p_r)

    result.nfev += 1
    # Pressure outside the computational region must be zero
    p_r[pad_mask] = 0.0

    # iteration
    delta = 0
    delta_str = 'reset'
    G_old = 1.0
    t_r = np.zeros_like(u_r)

    tau = 0.0
    for it in range(1, maxiter + 1):
        result.nit = it

        # Reset contact area (area that feels compressive stress)
        c_r = p_r < 0.0
        # TODO: maybe np.where(self.interaction.force < 0., 1., 0.)

        # Compute total contact area (area with compressive pressure)
        A_contact = reduction.sum(c_r * 1)

        # If a hardness is specified, exclude values that exceed the hardness
        # from the "contact area". Note: "contact area" here is the region that
        # is optimized by the CG iteration.
        if hardness is not None:
            c_r = np.logical_and(c_r, p_r > -hardness)

        # Compute total are treated by the CG optimizer (which exclude flowing)
        # portions.
        A_cg = reduction.sum(c_r * 1)

        # Compute gap
        g_r = u_r[comp_mask] - surface[surf_mask]
        if external_force is not None:
            offset = 0
            if A_cg > 0:
                offset = reduction.sum(g_r[c_r[comp_mask]]) / A_cg
        g_r -= offset

        # Compute G = sum(g*g) (over contact area only)
        G = reduction.sum(c_r[comp_mask] * g_r * g_r)

        if delta_str != 'mix' and not (hardness is not None and A_cg == 0):
            # t = (g + delta*(G/G_old)*t) inside contact area and 0 outside
            if delta > 0 and G_old > 0:
                t_r[comp_mask] = c_r[comp_mask] * (
                        g_r + delta * (G / G_old) * t_r[comp_mask])
            else:
                t_r[comp_mask] = c_r[comp_mask] * g_r

            # Compute elastic displacement that belong to t_r
            # substrate (Nelastic manifold: r_r is negative of Polonsky,
            # Kerr's r)
            # r_r = -np.fft.ifft2(gf_q*np.fft.fft2(t_r)).real
            r_r = substrate.evaluate_disp(t_r)
            result.nfev += 1
            # Note: Sign reversed from Polonsky, Keer because this r_r is
            # negative of theirs.
            tau = 0.0
            if A_cg > 0:
                # tau = -sum(g*t)/sum(r*t) where sum is only over contact
                # region
                x = -reduction.sum(c_r * r_r * t_r)
                if x > 0.0:
                    tau = \
                        reduction.sum(c_r[comp_mask] * g_r * t_r[comp_mask]) \
                        / x
                else:
                    G = 0.0

            p_r += tau * c_r * t_r
        else:
            # The CG area can vanish if this is a plastic calculation. In that
            # case we need to use the gap to decide which regions contact. All
            # contact area should then be the hardness value. We use simple
            # relaxation algorithm to converge the contact area in that case.

            if delta_str != 'mixconv':
                delta_str = 'mix'

            # Mix pressure
            # p_r[comp_mask] = (1-mixfac)*p_r[comp_mask] + \
            #                 mixfac*np.where(g_r < 0.0,
            #                                 -hardness*np.ones_like(g_r),
            #                                 np.zeros_like(g_r))
            # Evolve pressure in direction of energy gradient
            # p_r[comp_mask] += mixfac*(u_r[comp_mask] + g_r)
            p_r[comp_mask] = (1 - mixfac) * p_r[
                comp_mask] - mixfac * hardness * (g_r < 0.0)
            mixfac *= 0.5
            # p_r[comp_mask] = -hardness*(g_r < 0.0)

        # Find area with tensile stress and negative gap
        # (i.e. penetration of the two surfaces)
        mask_tensile = p_r >= 0.0
        nc_r = np.logical_and(mask_tensile[comp_mask], g_r < 0.0)
        # If hardness is specified, find area where pressure exceeds hardness
        # but gap is positive
        if hardness is not None:
            mask_flowing = p_r <= -hardness
            nc_r = np.logical_or(nc_r, np.logical_and(mask_flowing[comp_mask],
                                                      g_r > 0.0))

        # For nonperiodic calculations: Find maximum pressure in pad region.
        # This must be zero.
        pad_pres = 0
        if N_pad > 0:
            pad_pres = reduction.max(abs(p_r[pad_mask]))

        # Find maximum pressure outside contacting region and the deviation
        # from hardness inside the flowing regions. This should go to zero.
        max_pres = 0
        if reduction.sum(mask_tensile * 1) > 0:
            max_pres = reduction.max(p_r[mask_tensile] * 1)
        if hardness:
            A_fl = reduction.sum(mask_flowing)
            if A_fl > 0:
                max_pres = max(max_pres,
                               -reduction.min(p_r[mask_flowing] + hardness))

        # Set all tensile stresses to zero
        p_r[mask_tensile] = 0.0

        # Adjust pressure
        if external_force is not None:
            psum = -reduction.sum(p_r[comp_mask])
            if psum != 0:
                p_r *= external_force / psum
            else:
                p_r = -external_force / nb_surface_pts * np.ones_like(p_r)
                p_r[pad_mask] = 0.0

        # If hardness is specified, set all stress larger than hardness to the
        # hardness value (i.e. truncate pressure)
        if hardness is not None:
            p_r[mask_flowing] = -hardness

        if delta_str != 'mix':
            if reduction.sum(nc_r * 1) > 0:
                # The contact area has changed! nc_r contains area that
                # penetrate but have zero (or tensile) pressure. They hence
                # violate the contact constraint. Update their forces and
                # reset the CG iteration.
                p_r[comp_mask] += tau * nc_r * g_r
                delta = 0
                delta_str = 'sd'
            else:
                delta = 1
                delta_str = 'cg'

        # Check convergence respective pressure
        converged = True
        psum = -reduction.sum(p_r[comp_mask])
        if external_force is not None:
            converged = abs(psum - external_force) < prestol

        # Compute new displacements from updated forces
        # u_r = -np.fft.ifft2(gf_q*np.fft.fft2(p_r)).real
        new_u_r = substrate.evaluate_disp(p_r)
        maxdu = reduction.max(abs(new_u_r - u_r))
        u_r = new_u_r
        result.nfev += 1

        # Store G for next step
        G_old = G

        # Compute root-mean square penetration, max penetration and max force
        # difference between the steps
        if A_cg > 0:
            rms_pen = sqrt(G / A_cg)
        else:
            rms_pen = sqrt(G)
        max_pen = max(0.0,
                      reduction.max(c_r[comp_mask] * (surface[surf_mask] +
                                                      offset -
                                                      u_r[comp_mask])))
        result.maxcv = {"max_pen": max_pen,
                        "max_pres": max_pres}

        # Elastic energy would be
        # e_el = -0.5*reduction.sum(p_r*u_r)

        if delta_str == 'mix':
            converged = converged and maxdu < pentol and \
                        max_pres < prestol and pad_pres < prestol
        else:
            converged = converged and rms_pen < pentol and \
                        max_pen < pentol and maxdu < pentol and \
                        max_pres < prestol and pad_pres < prestol

        log_headers = ['status', 'it', 'area', 'frac. area', 'total force',
                       'offset']
        log_values = [delta_str, it, A_contact,
                      A_contact / reduction.sum(surf_mask * 1), psum,
                      offset]

        if hardness:
            log_headers += ['plast. area', 'frac.plast. area']
            log_values += [A_fl, A_fl / reduction.sum(surf_mask * 1)]
        if verbose:
            log_headers += ['rms pen.', 'max. pen.', 'max. force',
                            'max. pad force', 'max. du', 'CG area',
                            'frac. CG area', 'sum(nc_r)']
            log_values += [rms_pen, max_pen, max_pres, pad_pres, maxdu, A_cg,
                           A_cg / reduction.sum(surf_mask * 1),
                           reduction.sum(nc_r * 1)]
            if delta_str == 'mix':
                log_headers += ['mixfac']
                log_values += [mixfac]
            else:
                log_headers += ['tau']
                log_values += [tau]

        if converged and delta_str == 'mix':
            delta_str = 'mixconv'
            log_values[0] = delta_str
            mixfac = 0.5
        elif converged:
            if logger is not None:
                log_values[0] = 'CONVERGED'
                logger.st(log_headers, log_values, force_print=True)
            # Return full u_r because this is required to reproduce pressure
            # from evalualte_force
            result.x = u_r  # [comp_mask]
            # Return partial p_r because pressure outside computational region
            # is zero anyway
            result.jac = -p_r[tuple(comp_slice)]
            result.active_set = c_r
            # Compute elastic energy
            result.fun = -reduction.sum(
                p_r[tuple(comp_slice)] * u_r[tuple(comp_slice)]) / 2
            result.offset = offset
            result.success = True
            result.message = "Polonsky converged"
            return result

        if logger is not None and it < maxiter:
            logger.st(log_headers, log_values)
        if callback is not None:
            d = dict(area=np.int64(A_contact).item(),
                     fractional_area=np.float64(
                         A_contact / reduction.sum(surf_mask)).item(),
                     rms_penetration=np.float64(rms_pen).item(),
                     max_penetration=np.float64(max_pen).item(),
                     max_pressure=np.float64(max_pres).item(),
                     pad_pressure=np.float64(pad_pres).item(),
                     penetration_tol=np.float64(pentol).item(),
                     pressure_tol=np.float64(prestol).item())
            callback(it, p_r, d)

        if isnan(G) or isnan(rms_pen):
            raise RuntimeError('nan encountered.')

    if logger is not None:
        log_values[0] = 'NOT CONVERGED'
        logger.st(log_headers, log_values, force_print=True)

    # Return full u_r because this is required to reproduce pressure
    # from evalualte_force
    result.x = u_r  # [comp_mask]
    # Return partial p_r because pressure outside computational region
    # is zero anyway
    result.jac = -p_r[tuple(comp_slice)]
    result.active_set = c_r
    # Compute elastic energy
    result.fun = -reduction.sum(
        (p_r[tuple(comp_slice)] * u_r[tuple(comp_slice)])) / 2
    result.offset = offset
    result.message = "Reached maxiter = {}".format(maxiter)
    return result
def test_window_topography():
    nx, ny = 27, 13
    sx, sy = 1.3, 1.7
    h = np.ones((nx, ny))

    t = Topography(h, physical_sizes=(sx, sy),
                   periodic=True).window(direction='x')
    np.testing.assert_almost_equal(t.heights()[0, ny // 2], 1.0)
    np.testing.assert_almost_equal((t.heights()**2).sum() / (nx * ny), 1.0)

    t = Topography(h, physical_sizes=(sx, sy),
                   periodic=False).window(direction='x')
    np.testing.assert_almost_equal(t.heights()[0, ny // 2], 0.0)
    assert t.heights()[nx // 2, 0] > 1.0
    np.testing.assert_almost_equal((t.heights()**2).sum() / (nx * ny), 1.0)

    t = Topography(h, physical_sizes=(sx, sy),
                   periodic=False).window(direction='y')
    np.testing.assert_almost_equal(t.heights()[nx // 2, 0], 0.0)
    assert t.heights()[0, ny // 2] > 1.0
    np.testing.assert_almost_equal((t.heights()**2).sum() / (nx * ny), 1.0)

    t = Topography(h, physical_sizes=(sx, sy),
                   periodic=False).window(direction='radial')
    np.testing.assert_almost_equal(t.heights()[0, 0], 0.0)
    np.testing.assert_almost_equal(t.heights()[nx // 2, 0], 0.0)
    np.testing.assert_almost_equal((t.heights()**2).sum() / (nx * ny), 1.0)

if __name__ == '__main__':
    nx, ny = 128, 128

    sx = 0.005  # mm
    sy = 0.005  # mm

    x = np.arange(0, nx).reshape(-1, 1) * sx / nx - sx / 2
    y = np.arange(0, ny).reshape(1, -1) * sy / ny - sy / 2
    X = x * np.ones_like(y)
    Y = y * np.ones_like(x)

    topography = Topography(-np.sqrt(x**2 + y**2) * 0.1,
                            physical_sizes=(sx, sy))
    Max_Height = (-1) * np.min(topography.heights())

    alpha = np.arctan(10)

    fig, ax = plt.subplots()
    plt.colorbar(ax.pcolormesh(X, Y, topography.heights()), label="heights")
    ax.set_aspect(1)
    ax.set_xlabel("x (mm)")
    ax.set_ylabel("y (mm)")

    fig, ax = plt.subplots()
    ax.plot(x, topography.heights()[:, ny // 2])
    ax.set_title("the max height is {0:.6f}mm".format(Max_Height))
    ax.set_aspect(1)
    ax.set_xlabel("x (mm)")
    ax.set_ylabel("heights (mm)")