예제 #1
0
 def run(deltax, dtscaling, filename):
     dim = 2
     kdiff = deltax**2  # cancel out deltax**2 in the diffusion CFL condition -> max_dt_diffusion = 1/dim
     kstf = 3000.  # make it large so the timestep restriction for the stf dominates
     dt_max_diff = 0.8 * 0.5 / kdiff * (deltax**2) / (dim)
     dt = dtscaling / (kdiff * dim * kstf) * (
         deltax**3
     )  # the assumed scaling with various factors. dtscaling is determined experimentally.
     params = dict(
         dt=dt,
         tend=dt * 20,
         out_intervall=dt * 10,
         stepper='euler',
         fn_out=filename,
         num_threads=2,
         kdiff=kdiff,
         kstf=kstf,
         levelset_reinit=False,
     )
     print 'running with', dt, dt_max_diff
     assert dt < dt_max_diff
     # initial condition is a spherical region.
     pprint.pprint(params)
     size = (50, 50, 20)
     ld = krebsutils.LatticeDataQuad3d(
         (0, size[0] - 1, 0, size[1] - 1, 0, size[2] - 1), deltax)
     ld.SetCellCentering((True, True, False))
     f_conc = lambda x, y, z: circle_distfunc(x, y, z, size[
         0] * 0.3 * deltax, (size[0] * 0.5 * deltax, size[1] * 0.5 * deltax,
                             size[2] * 0.5 * deltax))
     surfaceTensionForceTest(dicttoinfo(params), ld,
                             dict(conc_profile=f_conc))
예제 #2
0
def make_ld(params):
    n = params['ncells']
    h = (params['x1'] - params['x0']) / n
    ld = krebsutils.LatticeDataQuad3d((0, n - 1, 0, 0, 0, 0), h)
    ld.SetCellCentering((True, False, False))
    ld.SetOriginPosition((params['x0'], 0., 0.))
    return ld
예제 #3
0
def TestBasics():
    x0, x1, y0, y1, z0, z1 = bb = (0, 4, 0, 4, -3, 6)
    ld = krebs.LatticeDataQuad3d(bb, 100.)
    print ld.GetWorldBox()
    print ld.worldBox
    print ld.GetBox()
    print ld.box
    print ld.scale
    print ld.GetScale()
    print ld.shape
    print ld.GetWorldSize()
    print ld.worldSize

    ld2 = krebs.LatticeDataQuad3d(bb, 100.)
    print ld == ld2

    ld3 = krebs.LatticeDataQuad3d((0, 3, 0, 4, -3, 6), 100.)
    print ld == ld3
예제 #4
0
def testCurvature():
    ld = krebsutils.LatticeDataQuad3d((-10, 10, -10, 10, -10, 10), 1. / 20)
    ld.SetCellCentering((True, True, True))
    shape = ld.box
    print shape
    X, Y, Z = ld.scale * np.mgrid[shape[0, 0]:shape[0, 1] + 1,
                                  shape[1, 0]:shape[1, 1] + 1,
                                  shape[2, 0]:shape[2, 1] + 1]
    radius = 0.25
    phi = np.sqrt(Y * Y + Z * Z + X * X) - radius
    curv, force = calcCurvature(ld, np.asarray(phi, dtype=np.float32), False,
                                True)
    mask = np.logical_or(-ld.scale * 2. > phi, phi > ld.scale * 2)
    curv[mask] = 0.
    curv[0, ...] = 0.
    curv[-1, ...] = 0.
    curv[:, 0, :] = 0
    curv[:, -1, :] = 0
    curv[:, :, 0] = 0
    curv[:, :, -1] = 0

    def proj_(a, idx):
        if idx == 2:
            z = phi.shape[2] / 2
            ext = ld.worldBox[[0, 1, 2, 3]]
            return a[:, :, z], ext
            #---------------
        elif idx == 0:
            x = phi.shape[0] / 2
            ext = ld.worldBox[[2, 3, 4, 5]]
            return a[x, :, :], ext
            #---------------
        elif idx == 1:
            y = a.shape[1] / 2
            ext = ld.worldBox[[1, 2, 4, 5]]
            return a[:, y, :].transpose(), ext

    proj = lambda a: proj_(a, 1)

    if 0:
        phi_x, ext = proj(phi)
        pyplot.subplot(211)
        pyplot.imshow(phi_x, extent=ext)
        pyplot.colorbar()
        pyplot.contour(phi_x, levels=[0.], extent=ext)
        curv_x, ext = proj(curv)
        pyplot.subplot(212)
        pyplot.imshow(curv_x, extent=ext)
        pyplot.colorbar()
        pyplot.contour(curv_x, levels=[2. / radius], extent=ext)
        pyplot.show()

    f1, ext = proj_(force[0], 2)
    f2, ext = proj_(force[1], 2)
    pyplot.quiver(f1.transpose(), f2.transpose())
    pyplot.show()
예제 #5
0
def makeLd(graph, spacing, relative_offset):
    p = graph.nodes['position']
    pmin = np.amin(p, axis=0)
    pmax = np.amax(p, axis=0)
    s = pmax - pmin
    nc = np.maximum(1, np.asarray(s / spacing, dtype=np.int))
    nc = np.bitwise_and(np.bitwise_not(1),
                        np.bitwise_or(2, nc))  # divisible by 2!
    bb = np.vstack(([0, 0, 0], nc + 1)).T.reshape((6, ))
    ld = krebsutils.LatticeDataQuad3d(bb, spacing)
    ld.SetCellCentering([True, True, True])
    ld.SetOriginPosition(pmin + spacing * relative_offset)
    return ld
예제 #6
0
def runLevelsetRedistancingScheme():
    name = 'zalesak_redistanceing'
    params = dict(fn_out='zalesak_redistanceing')

    ld = krebsutils.LatticeDataQuad3d((0, 99, 0, 99, 0, 0), 1. / 100.)
    ld.SetCellCentering((True, True, False))

    f_distort = lambda w: (-1 if w < 0 else 1) * (abs(w)**(1. / 3.))
    f_conc = lambda x, y, z: f_distort(
        zalesakDisk((x, y, z), 0.33, (0.5, 0.5, 0.)))

    #    if not os.path.exists(name+'.h5'):
    krebsutils.set_num_threads(2)
    levelsetRedistancing(dicttoinfo(params), ld, dict(conc_profile=f_conc))
예제 #7
0
def runAdvectionDiffusionReactionAnalysis():
    params = dict(stepper='vsimexbdf2', tend=1., out_intervall=0.1)

    ld = krebsutils.LatticeDataQuad3d((0, 49, 0, 49, 0, 0), 1. / 50.)
    ld.SetCellCentering((True, True, False))

    #funcs have the arguments (x,y,z,t,conc)
    velocity = lambda x, y, z, t, c: (0.5, 0, 0)
    src_impl_clinear = lambda x, y, z, t, c: -0.01
    src_impl_cconst = lambda x, y, z, t, c: 0.
    src_expl = lambda x, y, z, t, c: 0.
    kdiff = lambda x, y, z, t, c: 0.0
    conc_profile = lambda x, y, z, t, c, : circle(x, y, z,
                                                  (0.2, 0.5, 0), 0.2, 0.01)

    name = 'cdrtest'
    convectionDiffusionReaction(name,
                                params,
                                ld,
                                conc_profile=conc_profile,
                                velocity=velocity,
                                src_impl_clinear=src_impl_clinear,
                                src_impl_cconst=src_impl_cconst,
                                src_expl=src_expl,
                                kdiff=kdiff)

    results = Results(name)

    mm = (1000000, -100000)
    for i, g in enumerate(results):
        a = np.asarray(g['conc'])
        mm = min(mm[0], a.min()), max(mm[1], a.max())
    print mm

    for i, g in enumerate(results):
        a = g['conc'][:, :, 0]
        pyplot.imshow(np.asarray(a),
                      vmin=mm[0],
                      vmax=mm[1],
                      extent=worldBox[:4])
        pyplot.show()
예제 #8
0
def testfieldsampling():
    c = np.asarray((40, 20, 1))
    bb = np.vstack((-c, c - 1)).transpose().reshape((6, ))
    ld = krebs.LatticeDataQuad3d(bb, 1.)
    ld.SetCellCentering((True, True, True))
    wbb = ld.worldBox
    print(ld)
    print("box: ")
    print(wbb)

    num = (bb[1] - bb[0]) * (bb[3] - bb[2])
    pos = np.random.uniform(wbb[0], wbb[1],
                            num), np.random.uniform(wbb[2], wbb[3],
                                                    num), 0.5 * np.ones(num)
    pos = np.asarray(pos, dtype=np.float32).transpose()

    a = np.asarray(make_test_array(c), dtype=np.float32)

    smpl = krebs.sample_field(pos, a, ld, linear_interpolation=True)

    print 'arange = %f %f' % (a.min(), a.max())
    print 'smpl range = %f %f' % (smpl.min(), smpl.max())

    img = a[:, ::-1, 1]
    img = img.transpose()
    theExtent = ld.worldBox
    #mpl change the interface here
    plt.imshow(img,
               extent=theExtent[0:4],
               interpolation='nearest',
               vmin=0,
               vmax=1)
    #plt.imshow(img, extent = ld.worldBox, interpolation='nearest', vmin=0, vmax=1)

    plt.scatter(pos[:, 0], pos[:, 1], c=smpl, vmin=0., vmax=1.)

    plt.show()
예제 #9
0
def runSTFTest():
    params = dict(
        tend=0.01,
        out_intervall=0.0001,
        stepper='impeuler',
        fn_out='sfttest',
        num_threads=2,
        kdiff=10.,
        kstf=0.5,
    )
    ld = krebsutils.LatticeDataQuad3d((0, 49, 0, 49, 0, 0), 1. / 50.)
    ld.SetCellCentering((True, True, False))
    extent = ld.worldBox[:4]
    #f_conc = lambda x,y,z: zalesakDisk((x,y,z), 0.3, (0.5,0.5,0.))
    f_conc = lambda x, y, z: circle_distfunc(x, y, z, 0.3, (0.5, 0.5, 0.))
    if not os.path.isfile('sfttest.h5'):
        surfaceTensionForceTest(dicttoinfo(params), ld,
                                dict(conc_profile=f_conc))

    rc = matplotlib.rc
    rc('font', size=8.)
    rc('axes', titlesize=10., labelsize=10.)
    rc('figure', **{'subplot.wspace': 0.15, 'subplot.hspace': 0.15})
    rc('savefig', facecolor='white')
    dpi = 100.
    results = Results('sfttest')
    ldface = (krebsutils.read_lattice_data_from_hdf(results.f['face_ld_0']),
              krebsutils.read_lattice_data_from_hdf(results.f['face_ld_1']))
    extface = tuple(q.worldBox[:4] for q in ldface)
    data = collections.defaultdict(list)
    for idx, group in enumerate(results):

        def show(a, ext):
            pyplot.imshow(np.asarray(a[..., 0]).transpose(),
                          extent=ext,
                          origin='bottom',
                          interpolation='nearest')

        def contour():
            return pyplot.contour(np.asarray(group['ls'][..., 0]).transpose(),
                                  levels=[0.],
                                  extent=extent,
                                  origin='lower')

        print "plotting %i" % idx
        if 1:
            pyplot.figure(figsize=(1200. / dpi, 1000. / dpi))

            #        pyplot.subplot(221)
            #        show(group['ls'], extent)
            #        pyplot.colorbar()
            #        contour()
            #        pyplot.subplot(222)
            #        show(group['rho'], extent)
            #        pyplot.colorbar()
            #        contour()

            pyplot.subplot(221)
            pyplot.plot(np.linspace(extent[0], extent[1], 50),
                        group['ls'][:, 25, 0])
            pyplot.gca().set(xlabel='x', ylabel=r'$\phi$')
            pyplot.gca().grid(color=(0.5, ) * 3)

            pyplot.subplot(222)
            pyplot.plot(np.linspace(extent[0], extent[1], 50),
                        group['rho'][:, 25, 0])
            pyplot.gca().set(xlabel='x', ylabel=r'$\rho$')
            pyplot.gca().grid(color=(0.5, ) * 3)

            pyplot.subplot(223)
            show(group['force_0'], extface[0])
            pyplot.colorbar()
            contour()
            pyplot.subplot(224)
            show(group['force_1'], extface[1])
            pyplot.colorbar()
            contour()
            pyplot.savefig("sfttest%04i.png" % idx, dpi=dpi)

        data['time'].append(group.attrs['time'])
        data['mass'].append(group.attrs['mass'])
        data['area'].append(group.attrs['area'])

    pyplot.figure(figsize=(1200. / dpi, 600. / dpi))
    pyplot.subplot(121)
    pyplot.plot(data['time'], data['mass'], marker='x')
    pyplot.gca().set(xlabel='t', ylabel='mass')
    pyplot.subplot(122)
    pyplot.plot(data['time'], data['area'], marker='+')
    pyplot.gca().set(xlabel='t', ylabel='area')
    pyplot.savefig('vstime.png')
예제 #10
0
def runLevelsetAdvectionScheme():
    gradient_approx_method = 'upwind'
    stepper = 'rk3'
    advection_method = "weno5"
    velocity_type = 'shear'  #'rotation'

    name = 'zalesak_%s_%s_%s_%s' % (velocity_type, gradient_approx_method,
                                    stepper, advection_method)
    params = dict(
        tend=math.pi * 2.,
        out_intervall=math.pi * 2. / 12,
        stepper=stepper,
        fn_out=name,
        advection_method=advection_method,
        gradient_approx_method=gradient_approx_method,
        num_threads=3,
    )
    ld = krebsutils.LatticeDataQuad3d((0, 99, 0, 99, 0, 0), 1. / 100.)
    ld.SetCellCentering((True, True, False))

    f_conc = lambda x, y, z: zalesakDisk((x, y, z), 1.)
    if velocity_type == 'shear':
        f_vel = lambda x, y, z: rotationalVelocityField((x, y, z), (0, 0, .1),
                                                        (0.5, 0.5, 0.), True)
    else:
        f_vel = lambda x, y, z: rotationalVelocityField((x, y, z), (0, 0, 1),
                                                        (0.5, 0.5, 0.), False)

    convectionLevelset(dicttoinfo(params), ld,
                       dict(conc_profile=f_conc, velocity_profile=f_vel))

    def levelsetshow(a):
        #t = np.max(np.abs(a))
        pyplot.imshow(np.asarray(a),
                      origin='bottom',
                      cmap=cm_ls,
                      vmin=-0.1,
                      vmax=0.1,
                      extent=ld.worldBox[:4])

    rc = matplotlib.rc
    rc('font', size=8.)
    rc('axes', titlesize=10., labelsize=10.)
    rc('pdf', compression=6, fonttype=42)
    rc('figure', **{'subplot.wspace': 0.2, 'subplot.hspace': 0.25})

    results = Results(name)
    pyplot.suptitle(name)
    pyplot.subplot(221, xlabel='x', ylabel='y', title='t=0')
    levelsetshow(results[0]['ls'][:, :, 0])
    pyplot.colorbar()

    pyplot.subplot(222, title=r't=2$\pi$')
    levelsetshow(results[-1]['ls'][:, :, 0])
    pyplot.colorbar()

    #    t, m = zip(*[ (g.attrs['time'], g.attrs['mass']) for g in results ])
    #    pyplot.subplot(223, title='mass loss', xlabel='t', ylabel='m', ylim=(0, max(m)*1.1))
    #    pyplot.plot(t, m, 'x-k')
    t, gnorm = results.f['gradientmeasure/time'], results.f[
        'gradientmeasure/gradnorm']
    pyplot.subplot(223,
                   title=r'$||\nabla d| -1|_\inf$',
                   xlabel='t',
                   ylabel='',
                   xlim=(-0.1 * params['tend'], params['tend'] * 1.1))
    pyplot.plot(t, gnorm, '-k')

    pyplot.subplot(224,
                   title=r'contours t=0 .. 2$\pi$',
                   xlabel='x',
                   ylabel='y')
    for i, g in enumerate(results[::2]):
        col = 'k' if i == 0 else 'r'
        pyplot.contour(np.asarray(g['ls'][:, :, 0]), [0.],
                       extent=ld.worldBox[:4],
                       colors=col)

    pyplot.savefig(name + '.pdf', dpi=180., papertype='a4')
    pyplot.show()