We present a level set method for simulating capillary-controlled displacements with nonzero contact angles in porous media. The main feature of the method is a level set evolution velocity which is different in the pore space and solid phase. This augments the standard level set equation with an extra term such that, at steady state, the contact angle is enforced in the solid phase, whereas capillary and interfacial forces are balanced in the pore space. We employ the method to simulate quasistatic drainage and imbibition processes for different contact angles in several pore geometries, and to compute capillary pressure and fluid/fluid specific interfacial area curves in each case. We validate the method by comparing stable fluid configurations computed in idealized two-dimensional geometries and three-dimensional (3-D) straight tubes with known analytical solutions. Simulations performed in a subset of a 3-D sandstone image show that the developed method accounts for well-known pore-scale mechanisms such as piston-like invasion, Haines jump, interface coalescence, and retraction, swelling of wetting films and snap-off. The contact angle is formed by an intersection of the fluid/fluid interface and the void/solid boundary. Therefore, the solid matrix surrounding the pore space is discretized with at least an equal number of grid points as the size of the numerical stencil used to approximate the level set derivatives.
 Capillary control on fluid/fluid displacement in porous media is important to model in many applications of interest, including studies of residual water or oil in hydrocarbon reservoirs and long-term storage of supercritical CO2 in geological formations. In the context of CO2 storage, capillary pressure is directly related to two of the main trapping mechanisms—structural and residual (or capillary) trapping [e.g., Saadatpoor et al., 2010; MacMinn and Juanes, 2009; Juanes et al., 2010].
 In the structural trapping mechanism, upward CO2 migration due to buoyancy is prevented by a low-permeable formation layer, cap rock, or nonconductive fault. However, the CO2 could still be mobile and move laterally, or alternatively, the CO2 pressure could build up over time and exceed the entry pressure required for continued upward migration into the overburden low-permeable rock [Saadatpoor et al., 2008, 2010]. Thus, the structural trapping mechanism is regarded as unreliable because it could lead to leakage in an activated fault, for example. Once leakage or continued upward migration occurs, the CO2 pressure could decrease again and the water phase may snap off the CO2 in the layer below.
 The second mechanism—residual trapping—refers to the amount of CO2 left behind as isolated and trapped droplets that form within the water phase due to capillary forces during movement of the trailing edge of the CO2 plume [MacMinn and Juanes, 2009; Juanes et al., 2010]. This movement is described by an imbibition process, and the volume fraction of capillary trapped CO2 fluid constitutes the residual saturation. This mechanism is advantageous for CO2 storage, because the trapped fluid compartments are distributed over a large area and consequently this increases the sequestration potential by the chemical trapping mechanisms and minimizes the risk for leakage.
 An evaluation of the sequestration potential by structural and residual trapping requires knowledge of the CO2 capillary entry pressures to investigate capillary seal integrity, as well as drainage and imbibition capillary pressure curves in the various formation layers to determine residual saturations. It is well known that these properties depend on the formation wettability, and hence it is important to investigate the wetting properties of CO2/water/rock systems. Wettability is normally quantified at the pore scale as the contact angle θ that fluid drops form with the (flat) solid surface in the presence of another fluid and is measured through the wetting (often water) phase. Some grain surfaces may be intrinsically hydrophobic (θ > 90°), whereas neighboring ones are hydrophilic (θ < 90°). Wettability changes (e.g., from hydrophilic to hydrophobic) can be brought about by prolonged contact with nonaqueous phase or due to reactions on solid surface. In a study by Kim et al. , a contact angle increase from around 0° to 80° was observed in CO2/brine/silica systems due to reactions between CO2 and the silica surface. Espinoza and Santamarina  measured contact angles between CO2 and water on water-wet quartz and calcite minerals and observed values in the range 20°–40°. They also found that CO2 could be wetting relative to water on hydrophobic surfaces, such as oil-wet quartz. Bikkina  measured contact angles on quartz and calcite substrates and found values ranging between 30° and 90°.
 The above investigations suggest that pore-scale models for computing fluid distributions and capillary pressure curves for CO2 storage should account for nonzero contact angles. The common approach has been to perform calculations in pore networks of idealized geometry [e.g., Blunt, 2001]. Pore-network modeling can easily implement different contact angles since the pores and throats are straight, and wettability can differ pore by pore [van Dijke et al., 2002; Piri and Blunt, 2005]; however, it assumes simplified pore geometry and implements ad-hoc rules for interface transition from one pore (throat) element to the next. Therefore, while it is a fast method, it does not have the resolution we desire for fundamental understanding of pore-scale wettability and its influence on residual saturations and capillary pressure curves. More recently, advanced techniques have been developed to simulate multiphase displacements directly in three-dimensional (3-D) images of porous rocks. These include the pore-morphology-based methods [e.g., Hilpert and Miller, 2001; Silin et al., 2010], which are computationally efficient but calculate the shape of the fluid interfaces using a union of spheres approximation; the level set methods (LSM) [Prodanović and Bryant, 2006, 2009; Prodanović et al., 2010; Rodriguez et al., 2012], which calculate sharp fluid interfaces as surfaces of mean curvature at subgrid resolution; and the lattice Boltzmann methods (LBM) [e.g., Pan et al., 2004; Schaap et al., 2007; Ramstad et al., 2012]. In particular, LBM in the steady state limit approximates the solution to the Navier-Stokes equations directly in the imaged geometry. It is easily parallelizable making it a popular choice for porous media applications. Assuming ample resolution, two-phase LBM has been tested in straight-wall pores to resolve contact angles within two degrees of accuracy [Huang et al., 2007], with the accuracy somewhat diminished for the zero contact angle. The contact angle in the mentioned reference was computed by comparing the final fluid volume to the analytic solution, rather than measuring the angle directly thus the accuracy assessment in the pores of varied cross sections will be trickier. To date, we have not found papers on mixed wettability applications or accuracy evaluations in geometries with curved walls (i.e., neighboring surfaces of different wettability), though some are reportedly in preparation (C. Landry and M. Schaap, personal communication). LBM approximates Navier-Stokes equation and includes both viscosity and capillarity effects, whereas the level set methods described here model capillarity only (see section 'Method Description'). Standard two-phase LBM implementation [Shan and Chen, 1993] on D3Q19 lattice will require 38 floats per pore node, whereas LSM requires two, therefore, simulation in volumes of comparable sizes requires parallel LBM and serial LSM implementation, respectively. Further, LBM does not explicitly track interfaces: Boundary conditions (such as contact angle) are in effect applied to solid boundary nodes and somewhat misaligned with interfaces. Thus, we expect level set methods to perform better in complicated geometries, but that remains to be verified.
 The level set method [Osher and Fedkiw, 2003; Sethian, 1999] is an interface tracking method which describes the interfaces implicitly as the zero level set of a function ϕ which is one dimension higher than the interface. In this sense, it is similar to the phase-field method. Relationships between the level set method and the phase-field based interface tracking method for curvature-driven flow in the absence of a solid phase were discussed by Sun and Beckermann . The implicit description avoids the task of explicitly tracking each individual point of the interface, and inherent problem with tracking topological changes such as splitting or merging two interfaces. Therefore, the method is a good choice for modeling fluid distributions in porous media. The level set function ϕ assigns interior and exterior regions of the interface based on its sign. Interface evolution is governed by the level set equation
which can be equivalently written as
where Vn is the normal component of the velocity representing the forces in the problem of interest. Since the function ϕ is constant along the zero level set, the normal to the interface is given as , and thus . While there are many possible functions ϕ that can describe an interface, for numerical stability it is paramount that its gradients are neither large or small (we provide more technical details in section 'Method Description'). Level set methods are a mature field, and implementation of core routines for discretization and reinitalization are available in Fortran/C/C++ within Level Set Method Library LSMLIB (K. T. Chu and M. Prodanović, Level Set Method Library (LSMLIB), http://ktchu.serendipityresearch.org/software/lsmlib/index.html), as well as in MATLAB/Octave within Toolbox of Level Set Methods [Mitchell and Templeton, 2005].
Prodanović and Bryant  extended the application range of the level set method to model critical displacements events during drainage and imbibition as well as complete capillary pressure curves in 3-D rock images including fractures [Prodanović and Bryant, 2009; Prodanović et al., 2010]. In this problem, Vn represents the balance between capillary and interfacial forces. They introduced a second level set function, ψ, to describe the pore structure in which ψ = 0 represents the solid surfaces. A “no-penetration” constraint [Prodanović and Bryant, 2006; Sethian, 1999] was enforced at the end of each time step to prevent the fluid interfaces from invading the solid matrix. As a consequence, the zero level sets of ϕ is perfectly aligned with the solid surface in regions of the pore space occupied by the nonwetting fluid. The consistency with strongly wetting conditions and θ = 0° was demonstrated [Prodanović and Bryant, 2006]. This zero contact angle implementation for drainage and imbibition in porous materials is available in LSMPQS software (Level Set Method based Progressive Quasi-static (LSMPQS) algorithm software, http://users.ices.utexas.edu/∼masha/lsmpqs/index.html). The method enables access to all the details on topology of phases as well as interfaces. Topology changes of the interfaces (splitting during Haines jumps [Haines, 1927] in drainage, merging known as Melrose criterion [Melrose, 1965] during imbibition) are predicted by the method without manual intervention. These irreversible events contribute to significant hysteresis between capillary pressure versus saturation curves for drainage and imbibition.
 In this work, we develop a level set method for simulating capillary-controlled displacements with nonzero contact angles in pore geometries of arbitrary shape from 3-D rock images, and thereby extend the previous work by Prodanović and Bryant [2006, 2009] and Prodanović et al. . The presented evolution equation augments equation (2) with an extra term which imposes the contact angle in the solid phase. More precisely, a stepwise change is introduced in the level-set evolution velocity, and the steady state will give the correct contact angle boundary condition in the solid part of the computational domain, whereas the standard surface energy minimization is enforced in the void/pore space.
 Approaches that incorporate contact angles in level set methods for simulating dynamic contact lines, also including contact-angle hysteresis, have been proposed previously [Spelt, 2005; Liu et al., 2005; Li et al., 2010; Choi and Son, 2008; Lee et al., 2011]. However, most of these studies consider the flow of a droplet on flat solid surfaces, and the contact angle is formed by adding local reconstruction steps of ϕ around the contact lines in the reinitialization procedure [Spelt, 2005; Liu et al., 2005; Li et al., 2010]. Lee et al.  utilized the solid-void signed distance function ψ to derive an evolution equation for the fluid level set ϕ in the solid phase to form the contact angle, whereas the standard level set advection equation was applied in the void space. While their solid-phase equation is similar to our contact-angle term, we combine the pore-space and solid-phase terms into a single evolution equation to be valid in the entire computational domain, which is more applicable to solid surfaces of arbitrary complexity. Finally, Zhao et al.  introduced a variational approach for problems involving both the solid and void domains in which the interfacial tensions are different and related to the contact angle by Young's equation. An evolution equation that accounts for nonzero contact angles were derived based on constrained energy minimization of the system.
 The level set approach for modeling capillary-controlled displacements in porous media with contact angles is presented in section 'Method Description', followed by a description of the numerical implementation in section 'Numerical Implementation'. Computations of capillary pressure curves for drainage and imbibition at different contact angles are presented in section 'Simulation Examples' in several two-dimensional (2-D) and 3-D pore geometries. A discussion of computational issues is provided in section 'Discussion', followed by conclusions and a summary in section 'Summary and Conclusions'.
2. Method Description
 Our objective is to model slow, quasistatic displacement of immiscible fluids. Thus, at each stage of the simulation we assume Young-Laplace equation is presumed valid, that is,
Pc is capillary pressure, Pn and Pw denote the nonwetting and wetting fluid phase pressures, respectively, σ is interfacial tension, and κ0 is the interface curvature (strictly speaking twice the mean curvature of the interface). If the interfacial tension is constant, the equilibrium interface is a constant curvature interface with κ0 = Pc/σ. Despite apparent simplicity, 3-D constant curvature interfaces are not unique and thus are nontrivial to compute, especially in presence of complex solid walls. We further assume that the contact angle of the fluid/fluid/solid system is known and given.
 Level set description of the interface makes it easier to compute the interface curvature, as well as the contact angle between surfaces. We next describe the geometry of the problem in terms of level sets. The pore and solid space locations are defined by a function ψ: ψ > 0 represents the pore space, ψ < 0 defines the solid matrix, and consequently ψ = 0 defines the solid walls. Similarly, the nonwetting/wetting fluid locations are defined by the function ϕ, in which ϕ < 0 represents nonwetting fluid and ϕ > 0 represents wetting fluid as well as solids. The fluid interface(s) throughout the domain are described implicitly by the portion of ϕ = 0 that is located within the pore space (ψ > 0). Figure 1 gives a schematic of the setup.
 Physically, if the capillary pressure of the system is set externally (by natural pressure differences or an experimental boundary condition) and the fluid-fluid interface is not in equilibrium, then the interface will move and adjust its shape trying to get to equilibrium state. Thus, if , the interface will increase its curvature to support the higher capillary pressure and if the difference is negative, the interface will decrease its curvature “relax” in response to the relatively smaller capillary pressure. Therefore, in order to find equilibrium constant curvature interface(s) in the pore space (where ψ > 0), we solve the standard surface energy minimization problem [Chopp and Sethian, 1993],
 The steady state, nontrivial solution to this problem (note that t is simply an iteration parameter, and not physical time) is a constant curvature interface κϕ = κ0. κϕ is the curvature of the level sets of ϕ and can be calculated as:
 Equation (4) will in essence define the zero level set speed (in direction normal to itself) within the pore space, .
 While there is no physical movement of fluids within the solid walls, we nevertheless describe the contact angle boundary conditions by assigning an appropriate velocity field inside the solid matrix. Assuming for a moment that is defined, we find the steady state solution to the following level set evolution equation:
 Heaviside function H above (or rather, its smoothed numerical counterpart [see Osher and Fedkiw, 2003]) helps indicate the pore space as follows:
is a smoothing parameter that determines the width of the transition and Δx is the voxel (numerical cell) length. Note that both velocities in equation (6) are changing with the level set evolution. The steady state solution of the above equation will then satisfy Young-Laplace equation in the pore space, and the appropriate contact angle boundary condition near the solid wall.
 We complete the above formulation by defining appropriate . The contact angle boundary condition requires that the scalar product of the unit normals and to the level sets of ψ and ϕ is:
 At the intersection of the zero level sets, points into the pore space, and points into the wetting phase. Thus, the contact angle is given by θ = 180° − β (recall Figure 1).
 This yields the following equation within the solid phase (where ψ < 0):
where is the sign function that ensures that the contact angle propagates away from the solid walls, and therefore ensures numerical stability. We adopt the expression for S suggested by Peng et al. :
 The velocity within the solid wall now becomes
 We can check that propagates ϕ values away from the solid wall boundary by multiplying with the gradient of ψ:
which demonstrates that the sign of the scalar product is the same as the sign of ψ, respecting the propagation direction.
 Equations (4) and (9) are now combined using equation (6). This yields
where C ∼ 1/Δx is a constant that ensures appropriate scaling between the contact angle and curvature parts of the level set velocity at different numerical spacings.
 Equation (13) follows the standard level set velocity form with a normal, advective, and diffusive/parabolic term, as is made explicit in the expressions below:
 As ψ is static, we could set it to a signed distance function, such that , simplifying the implementation of the above expression.
 During evolution of the level sets by equation (2), it is important to reinitialize ϕ occasionally so that its gradient becomes neither too large nor too small. This is a standard practice in level set methods in order to preserve numerical stability. One method proposed by Sussman et al.  is to reinitialize ϕ to a signed distance function by iterating the following equation to a stationary state,
S(ϕ) is a sign function; an example implementation is shown in equation (10).
3. Numerical Implementation
 The method requires level sets describing the porous geometry and the initial fluid configuration as input: both can be defined using a segmented pore-scale image of a real medium or analytically (in cases of idealized geometry). The corresponding signed distance functions for these two geometries, ψ and ϕ, respectively, are computed by conventional reinitialization using equation (15). In this procedure, the gradients of the level set functions are discretized using the third-order weighted essentially nonoscillatory (WENO) scheme and Godunov's method for upwinding [Osher and Fedkiw, 2003], whereas the third-order Runge-Kutta method is applied for the update in time.
 We assume mirror-reflected boundary conditions at the boundaries of the computational domain, that is, the stencils involving boundary voxels in the discretization schemes are mirrored across the boundary. However, in fluid invasion simulations, we add a two-voxel thick layer of pore space occupied with the invading fluid to the computational domain at the face(s) selected as inlet and combine it with linear extrapolation. This is somewhat akin to a fluid reservoir located at the inlet and it prevents the zero level set ϕ = 0 from “leaving” the computational domain. We also provide a 2-D approximation to the initial configuration of the invading fluid in the first voxel layer inside the porous sample at the inlet boundary. We find this configuration using a 2-D semianalytic method [Frette and Helland, 2010], which is based on extending the Mayer & Stowe—Princen method [e.g., Ma et al., 1996] for computing capillary entry pressures and capillary pressure curves in tubes with arbitrary, yet constant cross sections. Alternatively, a slightly compressible model [Prodanović and Bryant, 2006] can be used to initialize ϕ.
 Capillary-controlled fluid displacements through porous media are simulated by solving equation (13) until steady state is achieved for each consecutive input value of interface curvature κ0. In the simulation of a drainage process, a sequence of increasing curvatures are given as input, and for imbibition a sequence of decreasing curvatures are provided. Equation (13) is discretized similarly as equation (15), except for the additional parabolic curvature term (see equation (14), discretized with central differences) and the advective term (see equation (14), discretized using WENO and a standard upwind scheme [Sethian, 1999; Osher and Fedkiw, 2003]). The update in time-like parameter t is still performed based on the third-order Runge-Kutta method, and the time step for each iteration is determined based on the Courant-Friedreichs-Lewy (CFL) condition. Reinitialization of ϕ is performed periodically by solving equation (15).
 The fluid configuration is considered to have reached capillary equilibrium when the error of ϕ between the last two reinitializations is sufficiently small (in proximity of the fluid-fluid interface). This convergence criterion is expressed as
where Ω is the entire computational domain and ϕn and ϕm represent the values of ϕ after the last two reinitializations performed at the end of time steps n and m, respectively, with m > n. Furthermore, tol is a tolerance value which is set equal to 0.002 in the simulations presented in this work. Equation (16) is also employed as convergence criterion for the reinitialization procedure itself (see equation (15)). In that case, n and m represent two consecutive time iteration steps, and ϵ is replaced by to ensure that the evolution of the zero level sets of ϕ occurs in a region, where ϕ satisfies equation (15) with high accuracy.
 The wetting-phase saturation Sw and the fluid-fluid specific interfacial area anw are calculated when the fluid configuration has reached steady state for each given κ0. These quantities are determined based on volume and surface integrals as:
respectively. The volume of the porous sample is given by V, and δ(ϕ) is the smoothed delta function defined as [Osher and Fedkiw, 2003]
 Because the zero level sets of ϕ intersect the solid domain in the computations, visualization of each fluid inside the pore space are performed by computing the isosurfaces at ϕ = 0 after performing the operations
for viewing the nonwetting fluid, and
for viewing the wetting fluid.
4. Simulation Examples
 We first perform simulations with different contact angles in idealized geometries where we can validate the method against analytical solutions. We start with equilateral triangle cross section. We then use a 2-D pore throat between two discs, followed by a 3-D straight tube with a realistic, irregular cross section in order to investigate the capability of the method to find capillary entry pressures for piston-like displacements as well as the associated equilibrium fluid configurations before and after invasion. The results are compared against known analytical solutions and the convergence behavior for critical displacement events is demonstrated. Subsequently, we explore the performance of the method in 3-D pore geometries in which analytical solutions do not exist. A sphere-pack pore example shows the anticipated shapes of wetting-phase rings around sphere contacts for different contact angles. Finally, we perform simulations in a small subset of a 3-D sandstone image. As expected, we observe hysteresis behavior in Pc (Sw) and anw (Sw) relationships for drainage and imbibition processes.
 Disconnections and mergers of fluid volumes are the result of spontaneous events that are particular to capillarity-controlled displacements of one fluid by another in pores of irregular cross sections. These events are specifically apparent in the 3-D geometries of nonconstant cross section. At the grain scale, fluid displacement occurs as a series of movements of the fluid/fluid meniscus. Many of these movements entail splitting and merging of menisci. As menisci move, they encounter critical locations in the void space. From such locations, a meniscus can spontaneously but discontinuously jump to a new, stable location in order to minimize energy. Haines  first noted this phenomenon as air displaced water from draining columns of sand or glass beads. Its counterpart during imbibition is more difficult to observe: Melrose  proposed that during imbibition the jump occurred when two menisci just come into contact and thus strongly depends on local geometry. The cumulative effect of these irreversible events is observed as hysteresis in measured capillary-pressure-saturation curves.
 All computations were performed using a single processor (Intel(R) Core(TM) i7–2600 CPU at 3.40 GHz and with 8.00 GB RAM). The 2-D simulations finish within half an hour, whereas the most time-consuming 3-D simulations in the sandstone sample take up to one week. In all simulations, we use the following parameters: , and Δx = 1 unless specified otherwise.
4.1. Two-Dimensional Pore Geometries
 We test the method by finding the equilibrium solutions for two fluids in an equilateral triangular pore. The triangle has sides of length L. In each simulation, we specify a contact angle θ and a meniscus curvature κ0 which is related to capillary pressure by Young-Laplace's equation. The curvature is chosen such that the analytic solution intersects the pore wall L/3 from a vertex. We have chosen L = 1, and run simulations for lattice spacings, Δx, ranging from 1/16 to 1/128 and for contact angles θ = 0°, 20°, and 40°. Figure 2 shows the high resolution (i.e., Δx = 1/128) simulations together with the analytical results. The zero contour of ϕ is located at approximately 1.5 Δx to about 1.0 Δx away from the analytical results for θ = 0° to θ = 40°, respectively. Note that the zero level set of ϕ is also shown in the solid phase (ψ < 0) in order to demonstrate the angle it forms with the solid surface (the zero contour of ψ). The nonwetting and wetting phases can be obtained by using equations (20) and (21), respectively.
 The error between the analytic solution and the simulations is defined as
where ϕtrue is the signed distance function with a zero contour that corresponds to the analytic solution. Figure 3 shows that the error scales proportional to the resolution.
 Figure 4 illustrates the capabilities of the model to simulate cases, where the contact angle is a function of position. The pore throat is bounded by two disks with radii ten times the width of the pore throat, and the pore throat width is set to unity. In these simulations, we have used a resolution Δx = 1/20 and ϕ is reinitialized every 50 iterations. Figure 4 (top) shows a case where θ = 60° for x ≤ 0 and θ = 30° for x > 0 (mixed wettability model), and the Figure 4 (bottom) shows a case where the top surface has θ = 10° and the bottom surface has θ = 80° (fractional wettability model). In these simulations, the nonwetting fluid is introduced from the left.
 The critical curvature for the two cases were found by changing the curvature in steps of 0.01 and monitoring the stability of the solutions. The simulations put the critical curvatures between 1.63 and 1.64 for the top case (cf. analytic solution 1.74) and between 1.13 and 1.14 for the bottom case (cf. analytic solution 1.2). The surfaces with critical curvature for each of the two cases are shown in cyan color in Figure 4 and the analytic solutions are shown in blue. The position of the front is located within one grid point from the analytic result for the top case, and stops within two grid points of the analytic result for the bottom case. An outtake of stable configurations are shown to illustrate the evolution of fluid interface as the curvature is increased. The initial curvature for the top pore throat is 0.5, and then increased by 0.2 in every subsequent step. In Figure 4 (bottom), the initial curvature is 0.8 and is increased in steps of 0.05. The configurations are shown in alternate green and red colors with increasing curvature.
4.2. Three-Dimensional Pore Geometries
 We perform simulations in 3-D geometries using the presented contact-angle level set method (CA-LSM) for θ > 0°. A standard LSM [Helland et al., 2011] which is based on the work of Prodanović and Bryant  is used in simulations at strongly wetting conditions (θ = 0°), because it has been validated more extensively and is also computationally more efficient than CA-LSM. However, we present one CA-LSM simulation with θ = 0° to demonstrate that both methods give similar results. In LSM, the evolution equation is given by equation (4), and the “no-penetration” constraint is enforced at the end of each time step to prevent invasion of the zero level set of ϕ into the solid phase, resulting in a zero contact angle at the void/solid boundaries [Prodanović and Bryant, 2006]. Reinitialization with equation (15) is performed every three time steps in all simulations.
4.2.1. Capillary Tube With Constant Cross Section
 A 3-D capillary tube with irregular but constant cross-sectional shape is considered first. The cross section is a simply connected and closed pore space which is extracted from a 2-D scanning electron microscopy (SEM) image of Bentheim sandstone. In such capillary-tube geometries, piston-like invasion is energetically always the most favorable displacement, and possible mechanisms for hysteresis, such as growth of wetting-phase films from the pore corners during imbibition until the wetting phase snaps off the nonwetting phase occupied in the pore center, can only occur if piston-like invasion is topologically impossible [e.g., Hui and Blunt, 2000]. We consider a drainage process in which the tube is initially occupied by the wetting fluid and the nonwetting fluid is injected from the bottom opening. Stable fluid configurations during drainage are determined at each specified interface curvature κ0. The size of the computational domain is 74 × 101 × 35 voxels, and the initial fluid configuration at the inlet is calculated by the semianalytic method [Frette and Helland, 2010].
 Figure 5 shows stable fluid configurations at curvature values just below and above the entry curvatures for piston-like invasion of the nonwetting fluid, as computed with LSM for θ = 0° and CA-LSM for θ = 30° and 60°. In all cases, the nonwetting fluid invades the wider region of the pore first, followed by simultaneous invasion into the smaller region and the narrow constriction located in between. The saddle shapes of the interfaces in the constrictions, as indicated by the middle column in Figure 5, suggest that the two principal radii of curvatures have opposite sign in these locations: This is not possible to achieve if spherical interfaces are assumed. A smaller amount of wetting fluid resides in the corners after invasion for increasing contact angles. For θ = 60°, all the remaining wetting fluid is displaced during invasion into the smaller region and the connected constriction.
 Level-set simulated κ0 (Sw)-curves are presented in Figure 6 and compared with calculations performed with the semianalytic method [Frette and Helland, 2010]. These curves can easily be converted to capillary-pressure-saturation curves based on equation (3). The results are consistent because the same critical displacement events occur with both methods. The semianalytic method calculates 2-D configurations and entry curvatures by assuming the length of the capillary tube is sufficiently large. Thus, far away from the invading interface, it is assumed that any interface existing in a tube corner can be approximated as a circular arc in the cross section since the principal radius of curvature along the tube length is infinite. The semianalytic method determines saturation based on such 2-D cross-sectional configurations, whereas in the level set simulations the complete 3-D geometry is utilized to compute saturation by equation (17). This effect is clearly visible in Figure 6: The presence of the nonwetting phase at the inlet results in smaller wetting-phase saturations in the level set simulations as compared with the semianalytic method. The saturation difference is expected to become smaller if the tube length is increased. However, the critical curvatures for piston-like invasion into the different parts of the pore, as computed with the two methods, compare well. Similar level set computations of entry curvature for piston-like invasion into 3-D tubes with idealized cross sections, such as the equilateral triangle, exhibit excellent agreement with analytical solutions, as shown in section 'Effect of Resolution Near Solid Surfaces'.
 Figure 6 also includes results from a CA-LSM simulation with θ = 0°. The results are in good agreement with the LSM simulation, even though CA-LSM slightly underestimates the wetting-phase saturation compared to LSM. This is in agreement with the 2-D CA-LSM computations in the equilateral triangle (Figure 2) in which the simulated interfaces are located slightly closer to the corners than the analytical solution.
 Figure 7 shows the relative error of ϕ calculated from equation (16) as a function of time iteration for selected curvature steps during the level set simulations in the capillary tube. Before invasion, relaxation to new equilibrium fluid configurations upon increased curvatures occurs while the error develops a monotonically decreasing trend as a function of iteration until convergence is obtained. However, for the curvature steps in which piston-like invasion occurs, the error starts eventually to increase toward a maximum at breakthrough and decreases subsequently. We observe a similar trend during simulations of Haines jumps in realistic 3-D porous geometries in which the nonwetting fluid may invade several larger pores before the interface reaches a stable position in a constricted pore throat.
4.2.2. Sphere-Pack Pore
 A 3-D pore defined by four touching spheres is considered next. All spheres have equal radii R = 20 voxels, and the size of the computational domain is 66 × 66 × 62 voxels. The space surrounding the spheres constitutes the pore space, whereas the spheres represent solid grains. Upward invasion of the nonwetting fluid is simulated assuming the pore space is initially occupied with the wetting phase. During this drainage process, the wetting fluid becomes isolated in the space near the sphere contacts because the nonwetting fluid invades the rather large void space between the spheres and the boundaries first. As interface curvature is increased, the isolated wetting phase compartment decreases in size to adjust itself to the new curvature. At a critical curvature, the space between the spheres is invaded by nonwetting fluid, and the remaining wetting fluid exists in the form of separate pendular rings surrounding the sphere contacts. The pendular ring takes the shape of a nodoid at positive curvatures [e.g., Bear et al., 2011]. This process could also represent drainage due to evaporation or concentration changes of dissolved gas in a liquid-gas system [Bear et al., 2011].
 CA-LSM simulations are performed for drainage processes with contact angles 15°, 30°, 45°, and 60°, whereas the case with zero contact angle is simulated with LSM. Figure 8 shows isolated wetting-phase configurations at two different interface curvatures for three of the assumed wetting conditions in a subset of the domain containing 553 voxels. At equal curvature, the isolated wetting-phase compartment decreases in size with increasing contact angle. For the cases θ = 0° and θ = 15°, well developed wetting-phase rings exist around the sphere contacts when the wetting phase between the spheres are displaced. However, these rings are thin and appear as discontinuous wetting-phase fragments when the corresponding displacements occur for the larger contact angles. This is attributed to effects of the resolution around the sphere contacts, which not only affects the fluid configuration but also the computation and visualization of the static solid/void signed distance function.
 The interface curvatures are plotted as functions of saturation in Figure 9. The exterior pore space is large compared to the space between the spheres, and therefore the most relevant displacements for illustrating capillary behavior occur in our examples for Sw < 0.1, as shown in Figure 9 (right). As expected, the curvature level decreases as the contact angle is increased, and the isolated wetting fluid compartment decreases in size as curvature increases. Separate pendular rings form around each of the six sphere contacts at wetting-phase saturations between 0.005 and 0.01 when the nonwetting fluid invades the space between the spheres.
 Specific fluid/fluid interfacial area is calculated during the simulations with nonzero contact angles only, using equation (18). The results are plotted against saturation in Figure 10. In the case with θ = 0°, the fluid interfaces are perfectly aligned with the solid surface in the regions, where the nonwetting fluid occupies the pore space, and therefore computations of fluid/fluid interfacial area with LSM would require a different formula than equation (18) to avoid including a large contribution from nonwetting fluid/solid area in the results. Figure 10 shows that the level of anw decreases consistently with increasing θ. A local increase of anw at Sw ≈ 0.01 is observed because of the changing shape of the isolated wetting fluid compartments as curvature is increased. Interfacial area decreases abruptly when the isolated pendular rings form, as expected.
 An imbibition process with θ = 30° is simulated by decreasing the curvature stepwise from the drainage value at which the six different pendular rings formed. At this saturation reversal point, the rings appear as discontinuous wetting fluid fragments. As curvature is reduced during imbibition, well-developed rings with increasing thickness are formed. These rings are stable during imbibition for curvatures ranging from κ0 = 0.64 to κ0 = 0.05. When κ0 is reduced further, the contact lines of the different rings meet, resulting in invasion of the wetting fluid into the entire space between the spheres. Hence, the drainage and imbibition processes exhibit hysteresis, as shown in Figure 11 by the resulting κ0 (Sw) curves. Figure 12 shows the configuration at the smallest curvature with stable rings and the configuration after pore filling during imbibition. A pendular ring between two spheres is stable at all positive curvatures and takes the shape of a nodoid [Bear et al., 2011]. However, if more spheres are involved, the rings will cease to exist when the contact lines coincide, which is in agreement with our simulation. The imbibition process modeled here by swelling of isolated rings around sphere contacts could be representative of condensation [Bear et al., 2011].
4.2.3. Three-Dimensional Subset of a Sandstone Image
 We further perform simulations in a realistic sandstone geometry. A small subset of size 60 × 60 × 70 voxels is extracted from a tomographic data set of Castlegate sandstone which is freely available on http://xct.anu.edu.au/network_comparison/. Upward invasion into the sample is simulated with θ = 0° using LSM, and with θ = 20° and 40° using CA-LSM. As in the previous simulation example, nonwetting fluid is placed in the pore spaces in the first voxel layer inside the sample at the inlet boundary, and the remaining pore space is initially occupied by the wetting fluid.
 Figure 13 shows stable configurations of the nonwetting phase at four different interface curvatures. Several well-known pore filling mechanisms occur in these simulations. Large saturation changes due to piston-like invasion and Haines jumps are observed. The method accounts for coalescence of opposite interfaces, resulting in drainage of pore throats. This can be observed by comparing the visualizations for θ = 20° at κ0 = 0.5 and κ0 = 0.6, for example. Similar displacement events occur for all three contact angles, albeit at different interface curvatures. Furthermore, the fluid interfaces tend to find stable positions farther into the pore throats for increased contact angles. In the configurations for θ = 20°, the amount of remaining wetting fluid in pore-space constrictions is typically larger than in the corresponding configurations at equal curvature for θ = 40°. However, at κ0 = 1, most of the bypassed wetting fluid is displaced and the two configurations are similar. The structure of the wetting fluid at Sw ≈ 0.1 and different curvature values are shown in Figure 14. The wetting phase distribution is similar for all three contact angles, although the extent of small isolated wetting-phase droplets located in the crevices of the pore space is larger for θ = 0°.
 Interface curvature is plotted as a function of saturation in Figure 15 (left) for the three drainage processes. The small sample size and the large pore connected to the inlet boundary prevent the development of a pronounced entry pressure for all the simulated wetting conditions. The curves exhibit similar trends except for θ = 0° in which the curvature increases sharply at Sw ≈ 0.5. The simulated interface curvatures are scaled with contact angle and plotted versus saturation in Figure 15 (right) in an attempt to produce a unique curve. The results show that the curves coincide for saturations between 0.5 and 1, whereas a reduced gap develops between the data computed for zero and nonzero contact angles at smaller saturations due to the aforementioned sharp curvature increase at Sw ≈ 0.5.
 Specific fluid/fluid interfacial area is computed in a subset of the sandstone sample. Five voxel layers at the inlet boundary are neglected to avoid contributions in the area calculations from pores that are connected to the inlet and occupied with nonwetting fluid initially. The results are shown in Figure 16. Again, the curve computed for θ = 20° is located at a higher level than the curve computed for θ = 40°. The curves exhibit qualitatively the same bell shape as measured data [Culligan et al., 2006].
 Level set simulation of imbibition after drainage is performed for the wetting case θ = 20°. The curvature at the reversal point is κ0 = 1.0 and the corresponding initial fluid configuration for the imbibition process is shown in Figure 13 (row 4, column 2). Figure 17 presents stable configurations of the nonwetting fluid during imbibition at specified curvature values. These configurations demonstrate interface retraction during imbibition. Swelling of the wetting fluid occurs along the pore walls in pore throats and constrictions as curvature is decreased, whereas the nonwetting fluid tends to occupy the larger pores. Eventually, the wetting phase snaps off the nonwetting phase and the constriction becomes filled with wetting fluid. An example of this behavior can be observed in the pore throat located in the lower, front part of the sample in which a thick wetting film has formed along the pore-throat wall at κ0 = 0.3 (image in the middle), while for κ0 = 0.25 snap-off has occurred and the nonwetting fluid has retracted to the adjacent larger pores (image to the right).
 The κ0 (Sw) curves for the drainage and imbibition process are shown in Figure 18. The imbibition curve appears to be smoother than the drainage curve. This could be attributed to wetting films that expands smoothly during imbibition, whereas piston-like invasion dominates the drainage process. The corresponding anw (Sw)-curves are presented in Figure 19. The imbibition curve is located above the drainage curve with a much higher peak value. Such a behavior has been found in other studies [e.g., Rodriguez et al., 2012] and could also be explained by an interfacial area increase due to swelling of wetting films and that the nonwetting fluid preferentially retracts to the larger pore spaces.
5.1. Effect of Resolution Near Solid Surfaces
 The extension of ϕ into the solid is crucial to the formation of nonzero contact angles in the described scheme. Thus, it is important to have high enough resolution in both the pore space and the solid phase to obtain accurate results. Here, we investigate the effect of solid phase resolution by computing capillary-controlled displacements during drainage in geometries comprising two tubes with equilateral triangular cross sections that are separated by a varying number of voxels, . The maximal inscribed radii in the tubes are given by R1 = 8Δx and R2 = 6Δx, and the contact angle is set to θ = 30°. The analytically derived entry curvatures for piston-like invasion of the nonwetting phase [e.g., Ma et al., 1996] are κ0,1 = 0.201 and κ0,2 = 0.268 in voxel units.
 Level set simulations are performed first for the case when the side walls of the two tubes are facing each other. The resulting drainage κ0 (Sw) curves are presented in Figure 20 together with the analytical solution. For d ≤ 2Δx, invasion into both tubes occur at a single curvature value which is significantly lower than the two analytical values, suggesting that the two tubes are treated as one bigger pore in the simulations. For d = 3Δx and d = 4Δx, invasion occurs at two distinct entry curvatures. The entry curvature in the large tube agrees well with the analytical value. The simulated entry curvature in the small tube is still lower than the analytical value, indicating that the invasion here is influenced by the configuration changes in the large tube. For d ≥ 5Δx, the simulated and analytical entry curvatures in both tubes show excellent agreement. Fluid configurations just below and above entry curvature are shown in Figure 21 for d = 2Δx and d = 6Δx. The zero level set of ϕ is visualized in both the solid phase and pore space, and hence equation (20) was not employed here. Similar level set simulations are also performed for the case when a side wall in the largest tube is facing an edge of the smaller tube. The simulated κ0 (Sw) curves are shown in Figure 22 and indicate that there is no effect of the separation distance d in this case as all the curves are identical.
 The above results demonstrate the importance of having high resolution in the solid phase in the rock images that are taken as input to the simulations. In the sandstone image employed in section 'Simulation Examples', the “worst-case scenario” in which a thin solid wall of width d ≤ 2Δx separates two different pores was absent. However, it is reasonable to assume that the displacements in a pore have had a small effect on the configuration changes in pores located in the immediate vicinity. This could explain some of the differences in the results for zero and nonzero contact angles at Sw < 0.5 in Figure 15.
 A potential remedy to these effects could be to increase the resolution of the rock images or employ adaptive grid refinement [Berger and Colella, 1989] in bands around the solid surfaces.
5.2. Effect of Curvature Step on Capillary Pressure Curves
 We implemented a quasistatic method: Each step, we present has (presumably) converged to the desired curvature. If the simulation is stopped before reaching equilibrium, however, and one moves onto the next step (with a different curvature), the fluid might take a slightly different path through the pore space. This is because the pore and throat sizes and their spatial arrangement are not the same in the entire pore space. Further, pore space variability has another consequence on capillary pressure curves obtained in simulation. Let us assume we simulate drainage in a small medium and in the process sample curvatures (capillary pressure) in the range [κ1, κ2]. We can guarantee that the same curve will be obtained for two different samplings of the range as long as the curvature step size dκ in both cases is smaller than the difference between any two throat critical curvatures. These statements follow from the conceptual method development described in section 'Method Description'.
5.3. Phase Trapping
 Fluid phase trapping is not yet included in our proposed method, and consequently, fluid compartments that have become isolated will adjust themselves to new capillary equilibrium configurations when the capillary pressure is changed. Different pore sizes and specifically large aspect (pore to throat size) ratios of neighboring pore spaces will typically increase trapping. This was specifically studied by Prodanović and Bryant  and Prodanović et al.  using the zero-contact angle method. Isolated blobs remain at their own capillary pressure that is different from the one recorded in experiments or reported from simulations (that equals the difference between boundary values). They ultimately add to residual saturations in either drainage or imbibition. The relative permeability can significantly change due to the change in fluid configuration, especially in imbibition where trapped blobs remain in the middle of the pores.
 Contact angle would likely influence the level of trapping in a nonlinear way: while reducing the chance of snap-off in some pores in less than perfectly wetting conditions, it increases the chance of bypassing others. Therefore, while nonzero contact angle will typically steepen the drainage curve, and possibly completely alter the imbibition path: if the wetting fluid is not perfectly wetting some pore might not be able to imbibe at all and will become completely surrounded by wetting fluid.
 Phase trapping is an important mechanism we want to study using the developed method. The trapping requires additional code infrastructure that is not standard for level set methods (cluster search algorithm and separate level set functions recording trapped blobs that would otherwise disappear during simulation) and is somewhat nontrivial as wetting and nonwetting phases have to be treated separately. The incorporation of a volume preservation scheme for the trapped phase is the next planned extension of the developed method. Since trapping is more relevant in larger porous media samples (with wider pore-throat distributions) that we will study in more detail in future, we do not deem that the lack of trapping implementation undermines the present study.
5.4. Code Optimization
 One of the main advantages of the developed method is that it includes nonzero contact angles within the standard form of a level set evolution equation (14). Standard (W)ENO and upwinding schemes are used for the hyperbolic and advective terms, and central differencing for curvature terms, all of which can be readily parallelized. Another standard method for speeding up level set codes is to use narrow band methods [Peng et al., 1999], where calculations are only conducted for a set of points in the neighborhood of the zero level set. Ideally, this will reduce the problem to the same dimension as the surface, which decreases the computational burden and increases the scalability, but can be somewhat tricky to parallelize.
6. Summary and Conclusions
 In this work, we have introduced a method to incorporate nonzero contact angle boundary conditions for immiscible displacement in porous media using a variational level set framework. The main idea is to assign different velocities in the solid and pore space. The velocity in the solid domain enforces the contact angle and the velocity in the pore space accounts for the minimization of the fluid-fluid interface. These velocities are expressed as gradients of levels sets and are easily incorporated into standard level set codes.
 Quasistatic drainage and imbibition processes are simulated for different contact angles in several pore geometries using the developed method. The model is validated based on computations in idealized 2-D pore geometries and 3-D tubes with constant cross sections that compare well with the analytical solutions. Simulations in a 3-D sphere-pack pore and a 3-D sandstone image demonstrate that the model accounts for the expected mechanisms during capillary-controlled displacement at the pore scale. Piston-like invasion, Haines jumps, and interface coalescence are observed during drainage, whereas interface retraction, swelling of wetting films, and snap-off is observed during imbibition. Computed capillary pressure and interfacial area curves exhibit qualitatively similar trends as measured data. It is also demonstrated that the developed level set model accounts for situations, where the signs of the principal radii of curvature are different. Finally, preliminary simulations with nonuniform contact angles in a 2-D pore throat suggest that mixed and fractional wettability situations can be accommodated.
 Financial support for E. Jettestuen and J. O. Helland was provided by the Research Council of Norway through the CLIMIT program, ConocoPhillips, and the Ekofisk coventurers, including TOTAL, ENI, Statoil, and Petoro. The authors thank Dmitriy Silin at LBNL for helpful comments.