Exemplo n.º 1
0
def df2(xs, mesh, vx, vy, i, j):
    """
    Evaluate the model for the 2nd derivatives at the 10 locations of the domain
    at times ``t``.

    It returns a flatten version of the system, i.e.:
    y_1(t_1)
    ...
    y_10(t_1)
    ...
    y_1(t_4)
    ...
    y_10(t_4)
    """
    assert i == 1 or i == 2
    assert j == 1 or j == 2
    ############################################################################
    ############################################################################
    ##### ------------------ Solve the transport equation ---------------- #####
    ############################################################################

    Rd = 2.  # Retardation factor

    convCoeff = fp.CellVariable(mesh=mesh, rank=1)
    convCoeff()[0, :] = vx
    convCoeff()[1, :] = vy
    time = fp.Variable()
    # --- Make Source ---
    q0 = make_source_der_2(xs, mesh, time, i, j)
    # The solution variable
    var = fp.CellVariable(name="variable", mesh=mesh, value=0.)
    # Define the equation
    eqC = fp.TransientTerm(Rd) == -fp.ConvectionTerm(coeff=convCoeff) + q0

    # Solve
    d2U = []
    timeStepDuration = 0.005
    steps = 400
    for step in range(steps):
        time.setValue(time() + timeStepDuration)
        eqC.solve(var=var, dt=timeStepDuration)
        if step == 99 or step == 199 or step == 299 or step == 399:
            d2U = np.hstack([
                d2U,
                np.array([
                    var()[8 * 50 + 14],
                    var()[8 * 50 + 34],
                    var()[18 * 50 + 14],
                    var()[18 * 50 + 34],
                    var()[28 * 50 + 14],
                    var()[28 * 50 + 34],
                    var()[38 * 50 + 14],
                    var()[38 * 50 + 34],
                    var()[48 * 50 + 14],
                    var()[48 * 50 + 34]
                ])
            ])

    return d2U
Exemplo n.º 2
0
def forward(xs):

    nx = 21
    ny = nx
    dx = 1. / 51
    dy = dx
    rho = 0.05
    q0 = 1. / (np.pi * rho**2)
    T = 0.3
    mesh = fp.Grid2D(dx=dx, dy=dy, nx=nx, ny=ny)

    time = fp.Variable()
    sourceTerm_1 = fp.CellVariable(name="Source term", mesh=mesh, value=0.)

    for i in range(sourceTerm_1().shape[0]):
        sourceTerm_1()[i] = q0 * np.exp(-(
            (mesh.cellCenters[0]()[i] - xs[0])**2 +
            (mesh.cellCenters[1]()[i] - xs[1])**2) /
                                        (2 * rho**2)) * (time() < T)

    # The equation
    eq = fp.TransientTerm() == fp.DiffusionTerm(
        coeff=1.) + sourceTerm_1  # + sourceTerm_2

    # The solution variable
    phi = fp.CellVariable(name="Concentration", mesh=mesh, value=0.)

    #if __name__ == '__main__':
    #    viewer = fp.Viewer(vars=phi, datamin=0., datamax=3.)
    #    viewer.plot()

    x = np.arange(0, nx) / nx
    y = x

    data = []
    dt = 0.005
    steps = 60
    for step in range(steps):
        time.setValue(time() + dt)
        eq.solve(var=phi, dt=dt)
        #if __name__ == '__main__':
        #    viewer.plot()
        #if step == 14 or step == 29 or step == 44 or  step == 59:
        #    dl = phi()[0]
        #    dr = phi()[nx-1]
        #    ul = phi()[nx**2 - nx]
        #    ur = phi()[nx**2 - 1]
        #    print phi().shape
        #    data = np.hstack([data, np.array([dl, dr, ul, ur])])

    #if __name__ == '__main__':
    #    raw_input("Transient diffusion with source term. Press <return> to proceed")

    return phi().reshape(nx, nx)
def df2(xs, mesh, i, j):
    """
    Evaluate the model for the 2nd derivatives at the four corners of the domain
    at times ``t``.

    It returns a flatten version of the system, i.e.:
    y_1(t_1)
    ...
    y_4(t_1)
    ...
    y_1(t_4)
    ...
    y_4(t_4)
    """
    assert i == 1 or i == 2
    assert j == 1 or j == 2
    nx = 25
    ny = nx
    dx = 0.04
    dy = dx
    mesh = fp.Grid2D(dx=dx, dy=dy, nx=nx, ny=ny)
    time = fp.Variable()
    q0 = make_source_der_2(xs, mesh, time, i, j)
    D = 1.
    # Define the equation
    eq = fp.TransientTerm() == fp.DiffusionTerm(coeff=D) + q0
    # Boundary conditions

    # The solution variable
    phi = fp.CellVariable(name="Concentraion", mesh=mesh, value=0.)

    # Solve
    dt = 0.005
    steps = 60
    d2U = []
    for step in range(steps):
        eq.solve(var=phi, dt=dt)
        if step == 14 or step == 29 or step == 44 or step == 59:
            dl = phi()[0]
            #dr = phi()[24]
            ul = phi()[600]
            #ur = phi()[624]
            #d2U = np.hstack([d2U, np.array([dl, dr, ul, ur])])
            d2U = np.hstack([d2U, np.array([dl, ul])])

    return d2U
def df(xs, mesh, i):
    """
    Evaluate the model for the derivatives at the four corners of the domain
    at times ``t``.

    It returns a flatten version of the system, i.e.:
    y_1(t_1)
    ...
    y_4(t_1)
    ...
    y_1(t_4)
    ...
    y_4(t_4)
    """
    assert i == 1 or i == 2
    time = fp.Variable()
    q0 = make_source_der(xs, mesh, time, i)
    D = 1.
    # Define the equation
    eq = fp.TransientTerm() == fp.DiffusionTerm(coeff=D) + q0
    # Boundary conditions 
    
    # The solution variable
    phi = fp.CellVariable(name = "Concentraion", mesh=mesh, value=0.)
    
    # Solve
    dt = 0.005
    steps = 60
    dU = []
    for step in range(steps):
        eq.solve(var=phi, dt=dt)
        if step == 14 or step == 29 or step == 44 or  step == 59:
            dc = phi()[12]
            #dr = phi()[24]
            uc = phi()[612]
            #ur = phi()[624]
            #dU = np.hstack([dU, np.array([dl, dr, ul, ur])])
            dU = np.hstack([dU, np.array([dc, uc])])
    
    return dU
def f(xs, mesh):
    """
    Evaluate the model for the concentration at the four corners of the domain
    at times ``t``.

    It returns a flatten version of the system, i.e.:
    y_1(t_1)
    ...
    y_4(t_1)
    ...
    y_1(t_4)
    ...
    y_4(t_4)
    """
    time = fp.Variable()
    q = make_source(xs, mesh, time)
    D = 1.
    # Define the equation
    eq = fp.TransientTerm() == fp.DiffusionTerm(coeff=D) + q
    # Boundary conditions

    # The solution variable
    phi = fp.CellVariable(name="Concentraion", mesh=mesh, value=0.)

    # Solve
    dt = 0.005
    steps = 60
    U_sol = []
    for step in range(steps):
        eq.solve(var=phi, dt=dt)
        if step == 14 or step == 29 or step == 44 or step == 59:
            dl = phi()[0]
            #dr = phi()[24]
            ul = phi()[600]
            #ur = phi()[624]
            #U_sol = np.hstack([U_sol, np.array([dl, dr, ul, ur])])
            U_sol = np.hstack([U_sol, np.array([dl, ul])])

    return U_sol
Exemplo n.º 6
0
if params['restart']:
    phi, = fp.tools.dump.read(filename=params['restart'])
    mesh = phi.mesh

    X, Y = mesh.faceCenters

    Lx = mesh.communicator.MaxAll(max(X)) - mesh.communicator.MinAll(min(X))
    Ly = mesh.communicator.MaxAll(max(Y)) - mesh.communicator.MinAll(min(Y))

    # scanf("%g") simulator
    # https://docs.python.org/3/library/re.html#simulating-scanf
    scanf_g = "[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?"
    pattern = ".*t=({g})\.tar\.gz".format(g=scanf_g)
    elapsed = re.match(pattern, params['restart']).group(1)
    elapsed = fp.Variable(name="$t$", value=float(elapsed))
else:
    Lx = params['Lx']
    Ly = params['Ly']

    dx, nx = _dnl(dx=params['dx'], nx=None, Lx=Lx)
    dy, ny = _dnl(dx=params['dx'], nx=None, Lx=Ly)

    mesh = fp.PeriodicGrid2D(dx=dx, nx=nx, dy=dy, ny=ny)

    phi = fp.CellVariable(mesh=mesh, name="$\phi$", value=0., hasOld=True)

    elapsed = fp.Variable(name="$t$", value=0.)
    
x, y = mesh.cellCenters[0], mesh.cellCenters[1]
X, Y = mesh.faceCenters[0], mesh.faceCenters[1]
Exemplo n.º 7
0
totaltime = params['totaltime']
dt = params['dt']
Lx = params['Lx']
Ly = params['Ly']

nx = params['nx']

ny = int(nx * Ly / Lx)
dx = Lx / nx
dy = Ly / ny

mesh = fp.PeriodicGrid2DLeftRight(nx=nx, dx=dx, ny=ny, dy=dx)
xx, yy = mesh.cellCenters[0], mesh.cellCenters[1]
XX, YY = mesh.faceCenters[0], mesh.faceCenters[1]

elapsed = fp.Variable(name="$t$", value=0.)

eta = fp.CellVariable(mesh=mesh, name="$eta$", hasOld=True)
eta.constrain(1., where=YY == 0.)
eta.constrain(0., where=YY == 0.5)

eta.value = eta_fp(xx, yy, 0.)

eq = (fp.TransientTerm() == -4 * eta * (eta - 1) * (eta - 0.5) +
      fp.DiffusionTerm(coeff=kappa_fp) + eq_fp(xx, yy, elapsed))

start = time.time()

while elapsed.value <= totaltime:
    eta.updateOld()
    eq.solve(var=eta, dt=dt)
Exemplo n.º 8
0
mesh = eta.mesh
xx, yy = mesh.cellCenters[0], mesh.cellCenters[1]
XX, YY = mesh.faceCenters[0], mesh.faceCenters[1]

eta.constrain(1., where=YY == 0.)
eta.constrain(0., where=YY == 0.5)

if parallelComm.procID == 0:
    dt = data.categories["dt_exact"]
else:
    dt = None

dt = parallelComm.bcast(dt)

elapsed = fp.Variable(name="$t$", value=startfrom * dt)

# linearize double-well
m_eta = 2 * (1 - 2 * eta)
dm_eta_deta = -4.
DW = m_eta * eta * (eta - 1)
dDW_deta = dm_eta_deta * eta * (eta - 1) + m_eta * (2 * eta - 1)
eq = (fp.TransientTerm() == (DW - dDW_deta * eta) +
      fp.ImplicitSourceTerm(coeff=dDW_deta) +
      fp.DiffusionTerm(coeff=kappa_fp) + eq_fp(xx, yy, elapsed))

solver = eq.getDefaultSolver()
print "solver:", repr(solver)

for step in range(1, numsteps + 1):
    eta.updateOld()
Exemplo n.º 9
0
print Vy

vx = fp.CellVariable(name="x-component velocity", mesh=mesh, value=Vx)
vy = fp.CellVariable(name="y-component velocity", mesh=mesh, value=Vy)
viewerVx = fp.Viewer(vars=vx, datamin=-0.1, datamax=0.1)
viewerVx.plot()
viewerVy = fp.Viewer(vars=vy, datamin=-4., datamax=0.)
viewerVy.plot()

if __name__ == '__main__':
    raw_input("Velocity field. Press <return> to proceed")

convCoeff = fp.CellVariable(mesh=mesh, rank=1)
convCoeff()[0, :] = Vx
convCoeff()[1, :] = Vy
time = fp.Variable()

var = fp.CellVariable(name="variable", mesh=mesh)

# --- Make source term
rho = 0.35
q0 = 1. / (np.pi * rho**2)
T = 0.3
xs_1 = np.array([1.25, 2.])
sourceTerm_1 = fp.CellVariable(name="Source term", mesh=mesh, value=0.)
for i in range(sourceTerm_1().shape[0]):
    sourceTerm_1()[i] = q0 * np.exp(-(
        (mesh.cellCenters[0]()[i] - xs_1[0])**2 +
        (mesh.cellCenters[1]()[i] - xs_1[1])**2) / (2 * rho**2)) * (time() < T)

eqC = fp.TransientTerm(
Exemplo n.º 10
0
def run_model(bp_radius,
              shelf_radius,
              gap_radius,
              alpha=1.15,
              k_hd30=.0471,
              k_mp24=.0390,
              cold=50.,
              hot=300.,
              outdir=None,
              verbose=True,
              max_fev=2000,
              dr=.001,
              dz=.001,
              foam_h=25.4e-3 * 4,
              units='SI'):
    '''
    Everything is SI units for now.
    '''
    t0 = time.time()
    ###########################################################################
    # Some parameters.  These are things I probably shouldn't change.
    # HD30 height
    # hd30_h = 1 * 25.4e-3
    hd30_h = foam_h + 1
    # Foam thermal conductivity
    # HD30 .0471 W/m*K at 283 K
    # MP24 .0390 W/m*K at 283 K
    hd30 = lambda T: (k_hd30 / 283**alpha) * T**alpha
    mp24 = lambda T: (k_mp24 / 283**alpha) * T**alpha
    ###########################################################################
    foam_radius = bp_radius + shelf_radius + gap_radius
    nr = int(foam_radius / dr)
    nz = int(foam_h / dz)
    parameters = {
        'hot': hot,
        'cold': cold,
        'hd30_height': hd30_h,
        'hd30': hd30(283),
        'mp24': mp24(283),
        'alpha': alpha,
        'bp_radius': bp_radius,
        'foam_radius': foam_radius,
        'shelf_radius': shelf_radius,
        'gap_radius': gap_radius,
        'dr': dr,
        'dz': dz,
        'nr': nr,
        'nz': nz,
        'foam_height': foam_h,
        'units': units
    }
    if verbose:
        print 'backplate:\t{:.3f} m\nfoam:\t\t{:.3f} m\ngap:\t\t{:.4f} m'.format(
            bp_radius, foam_radius, gap_radius)

    mesh = fipy.meshes.CylindricalGrid2D(nr=nr,
                                         Lr=foam_radius,
                                         nz=nz,
                                         Lz=foam_h)
    T = fipy.CellVariable(name='Temperature',
                          mesh=mesh,
                          value=hot,
                          hasOld=True)
    # Set constrai nts: top sides and shelf at 300 K
    # bp at 50 K
    T.constrain(hot, mesh.facesTop)
    T.constrain(hot, mesh.facesRight)
    x, y, = mesh.faceCenters
    bp_mask = (x < bp_radius) & (y == 0)
    T.constrain(cold, mesh.facesBottom & bp_mask)
    if shelf_radius > 0:
        shelf_mask = (x > (bp_radius + gap_radius)) & (y == 0)
        T.constrain(hot, mesh.facesBottom & shelf_mask)

    # set the thermal conductivity for 1 in of HD30 and 3 in of MP24
    x, y, = mesh.cellCenters
    k_var = fipy.Variable(array=np.zeros(len(x)))
    T.updateOld()
    res = 10
    i = 0
    while res > 1e-3:
        k_var = fipy.Variable(array=np.zeros(len(x)))
        k_var.setValue(hd30(T), where=y <= hd30_h)
        k_var.setValue(mp24(T), where=y >= hd30_h)
        K = fipy.CellVariable(mesh=mesh, value=k_var())
        eq = fipy.DiffusionTerm(coeff=K)
        res = eq.sweep(var=T)
        T.updateOld()
        if verbose or (i % 250 == 0 and i > 0):
            print i, res
            sys.stdout.flush()
        i += 1
        if i >= max_fev:
            return None

    if verbose:
        print '{:d} iterations'.format(i)
        print 'residual: {:f}'.format(res)
        print 'Time to run: {:.1f}'.format(time.time() - t0)
    t0 = time.time()

    if outdir is not None:
        f = open(os.path.join(outdir, 'results.pkl'), 'w')
        pickle.dump(T, f)
        f.close()
        f = open(os.path.join(outdir, 'parameters.pkl'), 'w')
        pickle.dump(parameters, f)
        f.close()

    if verbose:
        print 'Time to save: {:.1f}'.format(time.time() - t0)
    return K, T