WorksComputer Science
PILL-CoDe: Inverse Design of Polypills via Automatic Differentiation for Prescribed Drug-Release Kinetics
Abstract
Polypills are single oral dosage forms that combine multiple active pharmaceutical ingredients and excipients, enabling fixed-dose combination therapies, coordinated multi-phase release, and precise customization of patient-specific treatment protocols. Recent advances in additive manufacturing facilitate the physical realization of multi-material excipients, offering superior customization of target release profiles. However, polypill formulations remain tuned by ad hoc parameter sweeps. The current design workflows are ill-suited for the systematic exploration of the high-dimensional space of shapes, compositions, and release behaviors. We present PILL-CoDe, a polypill co-design framework that simultaneously optimizes tablet geometry and excipient distribution to match prescribed drug-release kinetics. The framework couples a supershape parametrization of the pill geometry with a coordinate-based neural network representation of the excipient distribution, and governs dissolution through a coupled system of modified Allen-Cahn and Fickian diffusion equations. Implemented in JAX, the entire pipeline is end-to-end differentiable, with automatic differentiation providing exact sensitivities for gradient-based co-optimization of shape and composition under manufacturability constraints. We demonstrate the method through single-phase and multi-excipient case studies, showing accurate matching of both monotonic and non-monotonic target release profiles.
Introduction
Personalized multidrug tablets, often referred to as polypills, enable patient-specific release profile by combining multiple active pharmaceutical ingredients and excipients [1]. Simultaneously, Additive manufacturing of pills has emerged as a promising approach for creating tailored dosages over time through direct specification of geometry, internal architecture, and material distribution from digital designs. Furthermore, additive manufacturing enables point-of-care production to improve supply-chain resilience and quality of care by reducing lead times [2, 3]. Five additive technologies dominate pharmaceutical research: binder jet printing [4], fused deposition modeling [5], semi-solid extrusion [6], selective laser sintering [7], and stereolithography [8, 9]. Aprecia’s ZipDose™ platform (2008) first showed binder jet printing could produce orally disintegrating, high-dose formulations [10], and parallel extrusion- and inkjet-based studies established that geometry and internal architecture can be tuned to modulate drug-release kinetics [11, 12], a principle reinforced by the 2015 FDA approval of Spritam (levetiracetam) as the first 3D-printed tablet [13]. Building on this foundation, reconfigurable “chemistry-on-demand” systems [14, 15], defense and regulatory initiatives toward point-of-care production [2, 3, 16–18], and space-based in-situ manufacturing efforts [20] [19] together signal a broader shift toward distributed, on-demand pharmaceutical production.
Figure 1. Graphical abstract: Given (a) a design domain and a set of candidate materials, the framework employs multimaterial inverse design governed by phase-field dissolution kinetics to tailor the polypill release profile. By coupling a supershape parametrized geometry with a neural material distribution, the framework co-optimizes (b) the geometry and internal material distribution, yielding (c) a design that matches the target release curve.
The ability to prescribe release kinetics depends on both the external geometry and the internal material arrangement of the dosage form. Geometry controls the exposed surface area and the evolving diffusion length during dissolution, while the placement of excipients and active ingredients determines where fast- and slow-dissolving regions are encountered as the tablet erodes. Experimental studies in pharmaceutical additive manufacturing have shown that changing tablet shape, infill architecture, shell thickness, and material composition can substantially alter dissolution and release behavior [21, 22, 23, 24]. These observations suggest that geometry-only design is intrinsically limited: it can modulate release through surface exposure, but it cannot independently prescribe when different ingredients or excipient-controlled dissolution rates become active. Co-design therefore expands the reachable set of release profiles by coupling shape-controlled interface evolution with material-controlled local dissolution kinetics.
Despite recent technical advances and emerging regulatory interest, systematic design tools for efficiently exploring the geometry and material layout of multi-ingredient tablets remain limited [25]. Three limitations are particularly relevant.
First, existing inverse-design methods do not jointly optimize tablet geometry and multi-ingredient composition. Panetta et al. [26] introduced a “shape-from-release” framework that couples a differentiable dissolution model with PDE-constrained inverse design and fabrication-aware regularization, demonstrating close agreement between simulated and measured release curves for single-material, 3D-printed structures. Altunay et al. [27] extended this idea to multi-material tablets by optimizing the spatial distribution of a single active ingredient, carried by two materials, within a fixed capsule-shaped geometry to match prescribed release profiles under uncertainty. However, neither approach co-optimizes tablet geometry together with the spatially varying composition of multiple active ingredients, which is central to polypill design. This distinction is important because geometry primarily changes the time evolution of exposed surface area, whereas material placement determines which local dissolution rates and ingredients are exposed at different stages of erosion. Our formulation treats both geometry and per-voxel composition of multiple active ingredients and excipients as coupled design variables.
Second, prior formulations rely on simplified geometric dissolution models rather than coupled dissolution-diffusion transport. Existing inverse-design approaches idealize release as a front-propagation problem governed by an Eikonal equation, where local slowness or surface velocity is prescribed algebraically from the design density or material fractions [26, 27]. This approximation is computationally attractive and can be effective when dissolution is well stirred or reaction limited. However, it does not explicitly resolve dissolved-drug concentration fields, local concentration buildup near the dissolving interface, saturation effects, or diffusion-limited transport through the surrounding medium. These effects are central to classical dissolution theory, including Noyes-Whitney and Nernst-Brunner type models, where the dissolution rate depends on the difference between saturation and local concentration and on diffusive transport away from the interface [28, 29]. To capture these mechanisms, we model the evolving tablet interface with a modified Allen-Cahn phase-field equation and couple it to Fickian diffusion of the dissolved species. While direct experimental validation of Allen-Cahn phase-field dissolution models for pharmaceutical tablets remains limited, phase-field formulations have been used and validated for moving-interface dissolution and precipitation problems in related transport settings [30, 31] [32, 33]. In the present work, this formulation provides a differentiable diffuse-interface model of pharmaceutical dissolution that is more physically expressive than prescribed front-speed models, while remaining suitable for gradient-based inverse design.
Third, there remains a gap between physics-based inverse design (e.g., topology optimization [34]) and controlled-release tablet design. Physics-informed inverse design has been widely used to design structures, fluids, heat-transfer systems, and multi-material layouts by embedding governing equations directly inside the optimization loop [35, 36]. This paradigm is particularly well suited to controlled-release inverse design because the desired performance is not a static geometric feature, but a time-dependent functional response generated by coupled transport, moving interfaces, and material heterogeneity. However, applying this idea to richer dissolution physics is challenging because hand-derived adjoint sensitivities become increasingly cumbersome as the forward model gains physical fidelity. We address this barrier by using automatic differentiation through the discretized forward solver, together with implicit differentiation of the nonlinear solve, to obtain exact discrete sensitivities for the coupled dissolution-diffusion model. This makes the co-design of tablet geometry and multi-ingredient composition tractable under a physics-informed inverse-design framework.
As mentioned above, existing methods model dissolution as a geometric front-propagation process, which is effective under well-stirred, reaction-limited conditions [26] but does not explicitly resolve the coupled dissolution-diffusion kinetics that can govern drug release in multi-material systems where local concentration buildup modulates the dissolution rate [37, 38]. [27] note that incorporating such coupling “would require significantly more numerical side work to define the adjoint equation for the gradients of the objective functions.” In this paper, we address this limitation by formulating a differentiable, coupled dissolution–diffusion model and integrating it into a gradient-based optimization framework with automated sensitivity analysis, thereby enabling the systematic co-design of geometry and spatially varying compositions under under a coupled dissolution-diffusion formulation.
More specifically, the contributions of this paper are:
We introduce a hybrid design parameterization in which supershapes define the global tablet geometry to enforce a connected, monolithic dosage form, while coordinate-based neural networks encode the internal multi-material distribution with high spatial flexibility.
We develop a differentiable dissolution-diffusion simulator that couples a modified Allen-Cahn phase-field model for interface evolution with Fickian diffusion of dissolved species, allowing local concentration buildup and saturation effects to influence release kinetics.
We formulate a physics-informed inverse design framework for controlled-release of active ingredients, where the governing dissolution-diffusion equations are embedded directly in the optimization loop and sensitivities are computed automatically through the discretized solver.
We demonstrate that co-designing geometry and excipient distribution expands the reachable set of release profiles compared with geometry-only optimization, enabling accurate matching of both monotonic and non-monotonic instantaneous release-rate profiles.
Proposed Method
This study addresses the concurrent optimization of polypill geometry and constituent material distribution to achieve prescribed drug release profiles. We begin by assuming a computational domain subject to boundary conditions governing pill dissolution. The polypill is modeled as a heterogeneous carrier matrix composed of multiple spatially distributed excipients embedding an active ingredient [23] [1, 39]. The excipients function as medically inert materials that govern the dissolution kinetics, thereby controlling the drug release profile while the aggregate dosage remains fixed by the prescribed active ingredient concentration [39, 40]. We assume the initial active ingredient concentration is uniform throughout the solid domain, while the surrounding solvent is initially devoid of any active ingredient. Furthermore, we assume the availability of distinct excipients, each characterized by a unique dissolution constant. The excipient material distribution is initialized uniformly with equal volume fractions for each excipient. The central premise of this work is that the drug release profile is governed by two design factors: first, the pill geometry, which dictates the evolving surface area available for solvent interaction [21] [41]; and second, the spatial distribution of excipients [39], which modulates the local dissolution rate at the solid-solvent interface. Consequently, the design objective is to determine the optimal pill geometry and spatial material distribution (Figure 2(a)) to achieve prescribed target dissolution kinetics (Figure 2(b)).
Figure 2. (a) Given a computational domain , we optimize the pill shape (region where ) and the distribution of excipients so that the resulting dissolution kinetics match the prescribed target shown in (b).
To this end, we propose a multi-material inverse design framework that simultaneously optimizes the shape of the pill and the excipient material distribution. Our goal is to maximize design space to match complex kinetics, while enforcing topological connectivity required for manufacturability. In particular, we use supershapes [42, 43] to parameterize the exterior shape (§ 2.2.1), ensuring a connected design, while a coordinate-based NN represents [44] the excipient distribution to maximize design freedom (§ 2.2.2). Furthermore, the dissolution process is governed by a modified Allen-Cahn phase-field equation [31] [45], coupled with a Fickian model for diffusion [46, 47].
We begin by detailing the governing physics and corresponding finite element formulations in § 2.1 and § 2.4, respectively. We then describe the hybrid design representation in § 2.2. This is followed by the derivation of effective material properties from the phase and excipient distributions in § 2.3. Finally, § 2.5 presents the optimization formulation, including the objective function, constraints, loss function, sensitivity analysis, and the numerical optimization procedure.
Governing Equations
The coupled dissolution and diffusion kinetics are modeled within a computational domain , which encompasses both the dissolving polypill and the surrounding solvent medium. The state of the system is defined by two field variables: the phase-field variable , and the concentration field . The phase-field variable serves as an indicator function, where denotes the solid pill domain (i.e., excipient and active ingredient), denotes the solvent, and intermediate values represent the diffuse solid-fluid interface. The concentration field represents the mass of the dissolved solute per unit volume.
We assume the domain is initialized with a uniform concentration (Equation (3c)), corresponding to an undissolved pill and a solvent initially devoid of solute. The initial phase field defines the initial geometry of the polypill (Equation (1c)), which is optimized. To model the dissolution process, we assume an infinite sink condition for the solvent boundaries to prevent saturation [29]. Consequently, we enforce a zero-Dirichlet boundary condition for the concentration (Equation (3b)) and a zero-flux Neumann condition (Equation (1b)) for the phase field along outward normal on the domain boundary .
The evolution of the pill interface is governed by a modified Allen-Cahn equation [30] [32, 48], augmented with a dissolution forcing term derived from Nernst-Brunner kinetics [29] [47]. The governing dissolution equation can then be expressed as:
where is the interface mobility, is the double-well potential barrier height, and is the interface thickness parameter. The potential density function is defined as [49], ensuring stable minima at the pure phases. The dissolution forcing term, , couples the phase evolution to the concentration field [29] [33, 37]:
Here, is the dissolution rate constant, is the solid density, and is the saturation solubility. The term localizes the dissolution driving force to the solid-solvent interface. The concentration-dependent factor reduces the local dissolution rate as the solute concentration approaches saturation near the interface. This is consistent with classical dissolution theory, in which the overall dissolution rate depends on the relative rates of interfacial and transport processes, with diffusion through the unstirred region often playing a rate-controlling role [29] [38, 50].
Simultaneously, the transport of the dissolved solute is governed by the diffusion equation [30] [33, 46] (neglecting any advection effects), can be expressed as:
where is the diffusion coefficient, and the source term accounts for the mass transfer from the solid phase to the solution, ensuring mass conservation [28, 29] [37]:
Furthermore, the concentration boundary condition models an idealized in vitro sink-condition setting. Thus, the concentration field may evolve within the domain and develop local gradients near the dissolving interface, while the surrounding medium acts as an ideal sink.
The coupled system of residuals and is spatially discretized and solved using standard finite element procedures as detailed in § 2.4.
Design Representation
Having established the governing equations, we now define the design parameterization strategy. Recall that the optimization objective is two-fold: (a) to determine the overall shape of the polypill, and (b) to optimize the spatial distribution of excipients within the solid domain.
To ensure the optimized design constitutes a single, connected pill rather than fragmented collection of particulates, we require that the pill designed be a topologically connected domain. Simultaneously, to maximize the tailorability of the release profile, we seek to promote material heterogeneity within the pill’s interior.
Consequently, we adopt a hybrid parameterization strategy. In particular, we utilize supershapes to define the global geometry, ensuring a monolithic structure (§ 2.2.1), while employing coordinate-based neural networks to represent the internal material distribution, thereby enabling high resolution design representation independent of mesh resolution. (§ 2.2.2).
Phase Field using Supershapes
To enforce topological connectivity and avoid domain fragmentation, we employ a geometric parameterization based on supershapes (Gielis curves) [42, 43]. Defined as a generalization of super-quadrics [42], this formulation provides a versatile parametrization for generating a broad spectrum of continuous geometries, spanning from standard convex forms (e.g., capsules) to complex non-convex (e.g., multi-lobed) structures, using a compact set of parameters.
We define the pill geometry in a local polar coordinate system . The radial boundary distance, , is governed by the reduced-order Gielis equation:
Here, and denote the semi-axis scaling factors, controls the rotational symmetry (number of lobes), and is the curvature exponent related to the squareness parameter (Figure 3).
Figure 3. Variations in the supershape’s parameters.
Furthermore, to enable arbitrary positioning and orientation within the computational domain, we apply an affine transformation to the global coordinates . In particular, we let denote the translation vector and denote the rotation angle. The local coordinates used to evaluate the polar parameters can then be obtained via (Equation (6)):
where is the standard 2D rotation matrix.
To map this implicit shape onto the finite element mesh for the dissolution simulation (§ 2.4), we begin by defining a radial distance field . Recall that strict Euclidean signed distance fields (SDF) are often used in feature mapping methods in TO [51, 52]. We instead utilize an approximation that preserves the zero-level set boundary and differentiability, rendering it sufficient for our inverse-design formulation. This field is defined as:
where and . This formulation ensures that inside the pill, outside, and on the boundary. This approximation is computationally simpler than recomputing a true signed distance field after each geometry update, while preserving the zero-level set of the supershape.
Finally, to obtain a differentiable approximation of the phase-field variable , we project the radial distance field into a smooth density field using a hyperbolic tangent projection (Figure 4) [53]:

Figure 4. (a) The supershape as defined by its parameters (, , , ). (b) The radial distance field. (c) The phase-field variable obtained upon projecting the distance field.
here, governs the steepness of the solid-solvent interface; in our experiments, we set . This projection maps to the material interior (where ) and to the exterior solvent (where ).
Finally, we note that the configuration of the pill is described by a set of seven parameters, , comprising the translation coordinates , the orientation angle , the semi-axis scaling factors , the squareness parameter , and the rotational symmetry order . Collectively, the supershape design vector can be defined as in Equation (9) which is further subject to optimization,
Material Distribution using Neural Networks
Having obtained the pill’s geometry, we now define the material distribution of the excipients. In particular, we let denote the presence of the s-th excipient at spatial coordinate , where . While a physically realizable design requires a discrete material assignment , we relax this condition for continuous gradient-based optimization, allowing . The material composition at any point is thus defined by the vector , subject to the partition of unity constraint .
To parameterize this spatially varying material field, we employ a coordinate-based neural network (Figure 5) [44, 54, 55]. Unlike conventional TO approaches where design variables are explicitly defined on the finite element discretization, this neural representation offers several distinct advantages for multi-material design: (a) the network architecture naturally enforces the partition of unity constraint via its output activation; (b) the design is decoupled from the simulation mesh, allowing for a compact set of design variables (network weights) independent of mesh resolution; (c) the material field is analytically defined everywhere, facilitating the recovery of crisp, high-resolution designs during post-processing; and (d) the analytic definition enables the precise computation of spatial gradients via back-propagation, which is critical for obtaining sharp material interfaces.
Figure 5. The neural network maps spatial coordinates to the material distribution.
The proposed network architecture consists of the following components:
Input Layer: The network accepts the spatial coordinates ( in 2-Dimensions) as input.
Fourier Projection: The Euclidean coordinates are mapped to a higher-dimensional feature space using a Fourier projection layer [56]. This (a) mitigates the spectral bias of standard multi-layer perceptrons, (b) enables the representation of high-frequency spatial variations, and (c) promotes faster convergence [54].
Hidden Layers: The feature vector is processed through a series of two dense hidden layers (with 40 neurons each) with ReLU activation functions [57].
4. Output Layer: The final layer consists of neurons corresponding to the excipient volume fractions. A Softmax activation function is applied to the output, intrinsically satisfying the requirements and .
The trainable weights and biases of this network constitute the primary design variables for the material distribution. The weights are initialized using the Xavier normal scheme [58] and subsequently updated to yield a spatially uniform material distribution, assigning equal volume fractions to each constituent excipient phase.
Material Model
With the pill geometry and the internal excipient distribution established, we now define the constitutive relations governing the local material properties. To model the effective diffusivity across the domain, we employ a smooth interpolation between the solvent and solid phases. The diffusion coefficient is defined as:
where is the diffusivity of the drug in the solvent medium, and is assigned a small, non-zero value to maintain numerical stability of the diffusion operator while ensuring negligible transport within the solid pill. The interpolation function is chosen as a standard quintic polynomial [49]:
Next, we define the local dissolution kinetics. Given a set of excipients with intrinsic dissolution rate constants , the effective dissolution rate field is computed using a linear mixture rule based on the local excipient volume fractions:
Equation (12) serves as a continuous interpolation that enables gradient-based optimization of the material assignment. It is not intended to capture microstructural effects such as porosity changes or constituent interactions that may arise in physical multi-material dissolution [59]. Its purpose is to map the relaxed excipient fractions to an effective local dissolution rate during intermediate optimization iterates. Note that while this rate field is defined throughout the computational domain, the physical dissolution process is localized to the solid-solvent interface. This localization is explicitly enforced by the term in the governing dissolution forcing function (Equation (2)). Finally, we assume that other material constants including the interface mobility , double well potential , interface thickness , solid mass density , and the saturation concentration are predefined constants, independent of the excipients and the phase.
With the pill’s geometry, material distribution, and effective property fields defined, we now proceed to discuss the finite element simulation of the dissolution and diffusion process in the next section.
Finite Element Analysis
With the initial phase and the spatially varying effective material properties established, the dissolution of the pill is computed by solving the coupled nonlinear governing equations (Equation (1) and Equation (3)). In particular, we employ standard finite element analysis (FEA) to obtain the spatio-temporal distribution of the phase and concentration fields.
For spatial discretization, the domain is meshed using four-noded quadrilateral element. The phase field and concentration are approximated using standard bilinear shape functions. For temporal discretization, we employ an implicit, first-order backward Euler scheme. This yields the following system of semi-discrete residual equations at time step :
where the mass matrix (), stiffness matrices (, ) and force vectors (, ) are defined as:
Here, denotes the shape function vector and the gradient matrix. Observe that the stiffness matrix , and the force vectors and render the residuals coupled.
The coupled non-linear system is solved using a Newton-Raphson iterative scheme. The solver is implemented within the JAX [60] framework and integrated with PETSc [61] for scalable linear algebra. Crucially, the implementation ensures the entire simulation framework is end-to-end differentiable, facilitating the computation of sensitivities via automatic differentiation [62].
Optimization Formulation
Having established our governing equations and procedures to solve them, the design representation, and the material model we now outline the key components of the design optimization framework.
Design Variables
Recall that the optimization problem concurrently determines two aspects of the design: (i) the geometry of the pill, governed by the geometric parameters of the supershape, and (ii) the distribution of the excipients, governed by the weights of the coordinate-based neural network. The complete design state is therefore defined by the aggregate set of variables .
Furthermore, while the neural network weights are unconstrained variables, the parameters of the supershape are bounded to ensure the generated shapes remain physically meaningful and within the computational domain. We define the lower and upper bounds for the geometric parameters as and , respectively:
To incorporate these box constraints into an unconstrained gradient-based optimization framework, we perform the optimization over a set of latent, unconstrained variables . The physical design variables are then recovered via a sigmoid projection and rescaling to the prescribed bounded intervals:
Objective
The primary goal of the proposed framework is to solve the inverse design problem: determining the optimal pill geometry and excipient distribution such that the resulting drug release kinetics match an a priori prescribed target profile. We achieve this by minimizing the discrepancy between the release history of the current design iteration and the target trajectory.
First, we quantify the drug release kinetics by computing the instantaneous rate of mass change of the solid pill. Utilizing the discrete phase-field solution derived from the FEA, the mass evolution rate at time step is approximated as:
where is the solid density, is the time step size, denotes the volume of element , and the summation is performed over all elements in the domain. The optimization problem is then formulated as the minimization of the Mean Squared Error (MSE) between the simulated mass rate profile and the target profile over the total simulation time :
where is the total number of time steps. This objective function drives the optimizer to update the geometric and material design variables such that the dissolution kinetics align with the desired drug release profile.
Grayness Constraint
Recall that while we relaxed to to enable gradient based optimization, physical realizability necessitates a discrete material assignment where . To drive the excipient distribution towards this binary state, we impose a global grayness suppression constraint:
where the term is a slack variable governed by a continuation strategy standard in TO. The parameter is initialized with a sufficiently large value, allowing the optimizer to explore the design space with intermediate material mixtures (gray regions). As the optimization proceeds, is reduced toward zero, strictly penalizing intermediate values and forcing the design variables to converge to the binary bounds .
Volume Constraint
To satisfy therapeutic and logistical requirements, the design may need to retain a minimum quantity of specific excipients. Towards this, we define the normalized volume deficit for the -th material relative to the total volume of the solid pill as:
where is the minimum required volume fraction for excipient , is the element volume, and is the total volume of the solid domain. We aggregate the constraints for all materials using a smooth minimum formulation to define the global constraint :
where (=10 in our experiments) is a sharpness parameter. Satisfying ensures that the volume fraction of every constituent satisfies , thereby meeting the required threshold.
Optimization Problem
Collecting the objective, PDEs, grayness and volume constraints the optimization problem can be expressed as:
We now consider solving the NN-based optimization problem in Equation (22). Neural networks are designed to minimize a loss function using well-known optimization techniques such as Adam procedure ([63, 64]). This is particularly convenient in the present setting because the design variables are the network weights, so the optimization is carried out in a nonlinear implicit design space. We therefore convert the constrained minimization problem into a loss function minimization by employing a log-barrier scheme as proposed in [65, 66]. Specifically, the loss function is defined as
where,
and is the initial objective. The constraint penalty parameter is updated at each iteration as (where, and in our experiments), making the enforcement of the constraint stricter as the optimization progresses. The gradient-based Adam optimizer [63] is used to minimize Equation (27).
Sensitivity Analysis
A critical step in gradient-based inverse design is the computation of sensitivities, which are the derivatives of the objective and constraint functions with respect to the design variables [67–69]. The sensitivity analysis for this work is particularly involved due to the coupling of transient, nonlinear dissolution kinetics with a hybrid design parameterization integrating supershapes and neural networks.
To address this complexity, we construct an end-to-end differentiable pipeline using the automatic differentiation (AD) capabilities of the JAX framework [60]. This allows us to avoid the laborious and error-prone process of manually deriving complex sensitivity expressions. By implementing the entire forward analysis, from the supershape geometric mapping and neural material distribution to the nonlinear finite element solver, the framework computes the required derivatives to machine precision using reverse-mode AD.
Furthermore, we emphasize on two specific challenges inherent to our physics simulation. The first arises from the use of iterative schemes, such as the Newton-Raphson method, to solve the nonlinear coupled phase-field equations. A naive application of AD would unroll the derivative computation through every solver iteration, a process that is both computationally expensive and memory-intensive. To avoid the prohibitive cost, we apply the Implicit Function Theorem (IFT) [68, 70], which enables the direct computation of derivatives from the final converged solution, thereby bypassing the need to backpropagate through the iterative solution history.
The second challenge stems from the transient nature of the simulation, which creates a significant memory bottleneck for the adjoint sensitivity method. An adjoint analysis requires access to the state history (concentration and phase fields) from all previous time steps to compute the gradient at the current step, and storing this entire state history is often infeasible for long simulations. We mitigate this issue by employing a checkpointing scheme [71, 72].
This technique stores the system’s state at select time steps, and during the reverse-time adjoint solve, states between these checkpoints are recomputed on the fly. This method significantly reduces memory requirements at the cost of a moderate increase in computation time, rendering the analysis of long-duration transient problems feasible.
Algorithm
This section summarizes the optimization framework. The iterative procedure updates the pill geometry and the internal excipient distribution to minimize the error between the simulated and target release profiles. The algorithm steps are:
Initialization: The computational domain and the finite element mesh are defined. The material constants: specifically the solid density , potential barrier , interface thickness and mobility are assigned, and the target release profile is prescribed. The lower and upper bounds for the supershape parameters, and , are specified (§ 2.5.1). The geometric design variables are initialized as the mean of these box constraints. The neural network weight are initialized to assign equal volume fractions to each constituent excipient phase (§ 2.2.2).
Shape Generation: In each iteration, the physical geometric parameters are recovered from the latent variables using the sigmoid projection (Equation (16)). The supershape radius is computed (Equation (5)), and the radial distance field from Equation (7) is projected to the smooth phase field (Equation (8)).
Material Distribution: The spatial coordinates are passed through the coordinate-based neural network (Figure 5) to generate the excipient distribution field , ensuring the partition of unity constraint (§ 2.2.2).
Property Mapping: The phase field and material distribution are mapped to the finite element mesh to define the spatially varying effective material properties. The local dissolution rate is computed via the mixture rule (Equation (12)), and the diffusion coefficient is interpolated (Equation (10)).
Finite Element Analysis: The coupled system of nonlinear transient equations (Equations (1) and (3)) are solved using standard finite element procedures to simulate the dissolution process (§ 2.4). The initial phase field for the simulation is defined by the optimizer output from Step 2. The solution yields the time-dependent phase and concentration fields, which are used to compute the instantaneous mass release rate (Equation (17)).
Loss and Constraint Computation: The objective function is evaluated as the mean squared error between the simulated and target profiles (Equation (18)). The grayness constraint and volume constraint are computed using Equations (19) and (21) respectively. The total loss is computed by aggregating the objective and the log-barrier penalty term for the constraints (Equation (27)).
Sensitivity Analysis: The gradients of the total loss with respect to the design variables, and , are computed using automatic differentiation (§ 2.6). This step leverages end-to-end differentiability of the JAX implementation to backpropagate gradients through the transient physics solver.
Update: The design variables are updated using the Adam optimizer. The grayness slack, log-barrier penalty, are updated according to a continuation scheme to gradually enforce the constraints.
Termination: Steps 2 through 8 are repeated until the convergence criteria are met or the maximum number of iterations is reached.
Results
In this section, we conduct several experiments to illustrate the proposed framework. All experiments are conducted on a MacBook M5 Pro using the JAX library [60] in Python. Further, we adopt a non-dimensional formulation. Unless otherwise specified, the default parameters for all numerical examples are as follows:
Mesh : A structured bilinear quadrilateral mesh with elements is used. A domain of size is used.
Neural network: A network with 2 hidden layers; with 40 neurons in each layer is used.
Constraints: We enforce a grayness constraint governed by a continuation strategy, where the slack variable is initialized to 2 and linearly decremented by per iteration to a final value of . Additionally, we impose a minimum volume fraction requirement of 5% () for each excipient.
Optimizer: The ADAM optimizer [63] with a learning rate of is used. To improve stability, a gradient clip with a norm threshold of 1 is used.
Convergence: The optimization is terminated either till a maximum of 100 iteration or when .
Materials: We adopt a non-dimensional parameter set for all numerical experiments. The specific material properties, including diffusivities, saturation concentration, density, and Allen–Cahn coefficients, are reported in Table 1, while the dissolution constants for our excipients are provided in Table 2.
| Parameter | Default value |
| 1.0 | |
| 5.0 | |
| 140 | |
Table 1. Default material properties.
| Material | Color | () |
| 0 | Pink | 0.1 |
| 1 | Blue | 0.5 |
| 2 | Green | 1.0 |
| 3 | Yellow | 5.0 |
| 4 | White | 0.0 |
Table 2. Multi-material dissolution rate constants.
Validation of Hypothesis
The central hypothesis of this work posits that the expanded design freedom offered by multi-material inverse design is required for tailoring dissolution kinetics to complex, non-monotonic target profiles. In this section, we validate this hypothesis by comparing the performance of single-material geometric optimization against the proposed multi-material framework.
We begin by establishing a baseline for a simple release scenario. We prescribe a simple, approximately monotonic target release curve (see Figure 6(a)). For this case, we restrict the design space to a single excipient material with a dissolution rate constant of . We then optimize the phase distribution as dictated by the supershape parameters to match the target profile. As illustrated in Figure 6, the optimizer successfully converges to a geometry that matched the target release curve, demonstrating that optimization of phase distribution is sufficient for simple release behaviors.

Figure 6. (a) Comparison of the mass release rate, where the optimized release profile (solid green) matches the monotonic target release (dashed red). (b) The corresponding optimized geometry.
However, advanced drug delivery applications often demand complex, modulated release profiles that differ from standard monotonic decay kinetics. To investigate this, we consider a non-monotonic target curve characterized by an initial slow release rate, followed by a rapid acceleration in release, and finally a sharp decay (see Figure 7(a)). We attempt to match this target using the single-material strategy, optimizing only the phase distribution via the supershape parameters. As shown in Figure 7((a) and (b)), the optimization fails to capture the transition from slow onset to rapid release. This result highlights the inherent limitations of a single-material design space, where the dissolution rate mainly depends on the evolving surface area of the pill.

Figure 7. (a) Comparison of mass release rates, demonstrating the failure of the single-material design (solid green) to match the non-monotonic target release curve (dashed red). (b) The corresponding optimized geometry. (c) Performance of the multi-material design, where the optimized release profile matches the complex target trajectory. (d) The corresponding multi-material design.(e) Performance of a target profile with burst-dominated release, gradual decay, and a mild late-time increase. (f) The corresponding optimized multi-material design.
To circumvent this limitation, we introduce multiple excipient materials. We concurrently optimize the phase distribution (via supershape parameters) and the internal material distribution (via the neural network representation). Spatially varying the excipient composition with distinct dissolution constants (see Table 2) expands the achievable release kinetics beyond those dictated by exposed surface area alone. Consequently, the multi-material design matches the complex target profile (Figure 7 (c) and (d)). Quantitatively, the single-material design (Figure 7 (a)) yields a normalized MSE of (normalized RMSE of 17.4%), indicating its limited ability to match the non-monotonic target. In contrast, the multi-material design (Figure 7 (c)) achieves a normalized MSE of (normalized RMSE of 0.98%). This result validates our hypothesis that the expanded design freedom of multi-material TO is essential for realizing complex release behaviors. Furthermore, the optimized material distribution in Figure 7(c, d) provides physical insight into how the optimizer exploits multi-material design freedom. The non-monotonic target demands three phases: slow initial release, rapid acceleration, and sharp decay. To achieve this, the optimizer places the slowest-dissolving excipient (Pink) at the pill periphery, suppressing early release while the solvent interacts primarily with this resistant outer shell. The fastest-dissolving excipient (Yellow) is concentrated in the interior; once the outer shell erodes, a large surface area of this rapidly dissolving material is exposed, producing the sharp peak in the release curve near . The subsequent decay follows as this region is consumed and the remaining solid volume diminishes. In contrast, the single-material design (Figure 7(a,b)) can only modulate release through the evolving surface area, which for convex geometries decreases monotonically. As a result, it cannot reproduce the non-monotonic profile.
To further illustrate the scope of the method, we include an additional representative target profile beyond the non-monotonic example discussed earlier. This example exhibits a burst-dominated release profile, with a high initial release rate followed by gradual decay and a mild late-time increase. The corresponding optimized design and release curve are illustrated in Figure 7(e,f); the optimizer yields a normalized MSE of (normalized RMSE of 0.25%), indicating excellent agreement with the prescribed target. Similar orders of normalized MSE values were observed across the other multi-material examples.
While these results demonstrate that the framework can match a range of qualitatively distinct release behaviors, the achievable set is not unbounded. As the present discussion is restricted to the dissolution-dominated regime studied here under the idealized sink-condition setting. In these examples, the computed response corresponds to net mass transfer from the solid to the solvent, so the release rate is nonnegative and, under full dissolution, decays to zero as the remaining solid is consumed. Hence, target profiles that require sustained growth near the end of the release window, nonzero terminal release, or negative release are outside the achievable set of the current model. Very sharp discontinuities or narrow pulses are also difficult to reproduce exactly because the diffuse-interface formulation and implicit time stepping smooth the release dynamics.
More broadly, the reachable set of release profiles is governed jointly by geometry and material distribution. Geometry controls the exposed interface area over time, while the constituent layout controls which local dissolution rates are encountered by that interface. A precise analytical characterization of this reachable set is beyond the scope of the present work, because the interface area evolves nonlinearly during dissolution and depends jointly on geometry and material arrangement. The grayness and volume constraints further restrict this set by enforcing discrete material assignments and limiting the admissible proportions of fast- and slow-dissolving excipients.
Effect of Initialization
Having demonstrated the necessity of multi-material inverse design, we now investigate the influence of design initialization on optimization result. Given the inherent non-convexity and non-linearity of the coupled dissolution-transport problem, we anticipate that the optimization landscape contains multiple distinct local minima.
To explore this, we first initialize the phase distribution using a supershape parametrization corresponding to a highly lobed geometry (referred to as the “spike” design). We prescribe the complex target release profile shown in Figure 8. The specific parameter bounds for this initialization are detailed in Table 3.

Figure 8. Convergence history of the multi-material inverse design. The sequence (top to bottom) shows the update of the design and release curve from initialization (Epoch 0) to the final optimized state (Epoch 100).
| Design Type | Curvature () | Lobes () | Scale () |
| Spike | [0.5, 2.0] | [5, 11] | [0.1, 0.4] |
| Circle | [1.67, 2.0] | [1, 3] | [0.1, 0.4] |
| Sunflower | [2.5, 4.0] | [10, 14] | [0.1, 0.4] |
Table 3. Supershape parameter bounds for different design initializations. Here, governs the curvature and denotes the rotational symmetry/number of lobes.
Consistent with previous results, the multi-material inverse design successfully converges to a design that matches the target release curve. Figure 8 illustrates the convergence behavior. The initial design exhibits poor performance with a significant deviation from the target release curve. However, subsequent iterations substantially modify both the supershape parameters (phase distribution) and the neural network weights (material distribution), achieving a good fit by the 100th iteration. Crucially, the final design satisfies the grayness constraint, ensuring discrete material allocation without nonphysical mixing, and satisfies the minimum material fraction constraint. The optimization converges in approximately 30 minutes, averaging 10 Newton-Raphson iterations per time step (over 100 total time steps) for the combined forward and backward computation. Finally, the temporal evolution of the optimized “spike” design is depicted in Figure 9, visualizing the progressive dissolution of the multi-material interface.
Figure 9. Dissolution of the optimized pill.
While the “spike” initialization yields a dissolution rate that closely matches the target, the resulting design (Figure 8) may pose challenges regarding fabrication and patient ingestibility due to its sharp geometric features. To obtain designs more suitable for practical application, we explore alternative initializations—specifically “circle” and “sunflower” geometries by imposing constraints on the supershape parameters. By bounding the extent of the shape parameters (see Table 3), we constrain the optimizer to explore regions of the design space characterized by smoother designs favorable for ingestion.
Despite these geometric restrictions, the optimizer successfully matches the target release curve for both the circle Figure 10((a) and (b)) and sunflower initializations Figure 10((c) and (d)). This non-uniqueness demonstrates that the proposed framework is robust, capable of identifying various distinct local optima that yield equivalent functional performance (release profiles). This flexibility allows designers to select optimal configurations based on additional criteria, such as manufacturability or ingestibility, without compromising the release kinetics.
Figure 10. Optimization results for “circle” and “sunflower” initializations. (a, c) Release profiles demonstrate that the optimized designs accurately track the target profile. (b, d) The corresponding topologies.
Case Study: Effect of Pill Degradation
To demonstrate the framework’s capability in incorporating environmental parameters, we examine a design scenario based on the degradation of pharmaceuticals. For instance, we draw motivation from a critical logistical challenge in long-duration spaceflight: the in-situ fabrication of therapeutics using degraded feedstock. Prolonged exposure to the space environment induces chemical instability in stored pharmaceuticals. For instance, data [73] from the ISS indicates that Clavulanate formulations exhibit a loss of dissolution performance; specifically, samples stored for 880 days show a dissolution efficacy (-value) of only 4.4%.
Towards this, we formulate a simplified inverse design problem that addresses two concurrent challenges: (1) the degradation of stored feed-stock’s dissolution kinetics, and (2) the logistical constraints of limited resupply. We assume an inventory consisting of heavily aged, moderately aged and fresh excipients. The non-dimensional excipients for these three supplies are shown in Figure 11.
Figure 11. Dissolution rate constants plotted for three available feedstock grades—fresh, moderately aged, and heavily aged.
We now apply the proposed framework under different minimum volume utilization requirements defined by . For example, we consider four cases for different minimum volume usage requirement. The obtained release curve along with the material distribution is shown in Figure 12. We observe that we are able to closely match the target dissolution profile by varying the excipient distribution. Notably, as expected, as the volume fraction constraint of heavily aged material increases, the optimizer adapts by allocating a greater volume fraction to the degraded excipient (green). This experiment showcases the utility of our framework to design pills on demand taking into account environmental factors. This case study serves to validate the framework’s utility in ensuring therapeutic robustness under conditions of material uncertainty and logistical scarcity assuring medication reliability in remote, resource-constrained environments. Furthermore, this case study is intended as an illustrative proof-of-concept for incorporating degraded-material constraints into the inverse-design framework, rather than as a mechanistic model of the underlying physicochemical degradation pathways.
Figure 12. Optimized for varying minimum volume fraction constraints .
Conclusions
This work introduces a computational framework for the co-optimization of the geometry and excipient material distribution of polypills to achieve a specified drug release profile. In particular, we employ a hybrid design representation that couples supershapes with a coordinate-based neural network. This formulation parameterizes the pill’s geometry to ensure a connected domain while simultaneously representing the spatially heterogeneous distribution of excipients with varying dissolution kinetics. We integrate these differentiable representations into a multiphysics environment governed by a modified Allen-Cahn phase field dissolution equation and Fickian diffusion for the simultaneous optimization of pill shape and material composition. Numerical experiments validate our central hypothesis: the co-design yields dosage forms with release profiles that match complex target kinetics.
The present study offers several avenues for future research. First, the dissolution analysis included only a single active ingredient and assumed constant material parameters such as diffusivity and mobility. A more complex model would involve considering multiple active ingredients, the effects of the active ingredient on dissolution kinetics, and environmental factors such as temperature, and the solvent’s chemical reactivity. Furthermore, extending the framework toward in vivo relevance would require modeling the gastrointestinal environment, including finite fluid volumes, local concentration buildup, absorptive transport across the intestinal wall, spatially varying pH, mucus-associated transport barriers, and fluid-motion effects such as peristaltic advection [74–76]. Second, the material properties used in this work were primarily for illustration. The practical implementation of this framework will require the use of comprehensive, experimentally validated material datasets that account for pH-dependency, complex excipient-drug interactions, and factors such as chemical stability, storage shelf-life, and material compatibility. Third, while the optimization formulation utilized grayness constraints to ensure physical validity, it did not explicitly account for additive manufacturing constraints such as minimum feature size or print resolution. Incorporating manufacturing filters and extending the framework to 3D supershapes or fully volumetric density-based parameterizations will be essential to expand design freedom while ensuring connectivity and physical realizability. However, a practical 3D extension will likely require dedicated acceleration strategies, such as reduced-order or surrogate models [77] and GPU-based implementations [78], to keep the transient nonlinear multiphysics optimization computationally tractable. Fourth, the transient and nonlinear governing equations often exhibited numerical stiffness rendering the simulations computationally demanding. Consequently, the development of specialized algorithms for nonlinear transient inverse design remains a critical challenge [79, 80]. Fifth, while we considered a deterministic design scenario, incorporating manufacturing, environmental and material uncertainty remains a significant interest. Sixth, while we considered a single scale designs, advances in additive manufacturing offer the ability to fabricate multi-scale structures that permit greater customization. Seventh, future work should integrate patient-specific factors to model the release curve, fully realizing the potential of personalized medication. Finally, experimental validation of our optimized designs using 3D-printed prototypes is a crucial area for future investigation to verify the computational predictions.
Data Availability and Replication of Results
The Python code is available at https://github.com/DEL-KU/PILL-CoDe
Declaration of Competing Interest
The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.
Declaration of generative AI and AI-assisted technologies in the manuscript preparation process
During the preparation of this manuscript, the authors used Google’s Gemini, OpenAI’s ChatGPT, and Anthropic’s Claude to improve the language and readability. After using these tools, the authors reviewed and edited the content as needed and take full responsibility for the content of the publication.
References
- [10]FierceBiotech, Mit-based startup nabs $30m for first 3-d printed drug approved by fda, accessed 2025-10-26 (aug 2015).
- [20]National Aeronautics and Space Administration, In space for earth!, https://www.nasa.gov/wp-content/uploads/2023/10/in-space-production-applications-overview-october-2023.pdf (2023).
- [21]A. Goyanes, P. R. Martinez, A. Buanz, A. W. Basit, S. Gaisford, Effect of geometry on drug release from 3d printed tablets, International journal of pharmaceutics 494 (2) (2015) 657–663.DOI
- [22]A. Goyanes, M. Kobayashi, R. Martinez-Pacheco, S. Gaisford, A. W. Basit, Fused-filament 3d printing of drug products: Microstructure analysis and drug release characteristics of pva-based caplets, International journal of pharmaceutics 514 (1) (2016) 290–295.DOI
- [23]S. A. Khaled, J. C. Burley, M. R. Alexander, J. Yang, C. J. Roberts, 3d printing of five-in-one dose combination polypill with defined immediate and sustained release profiles, Journal of controlled release 217 (2015) 308–314.DOI
- [24]M. Sadia, B. Arafat, W. Ahmed, R. T. Forbes, M. A. Alhnan, Channelled tablets: An innovative approach to accelerating drug release from 3d printed tablets, Journal of controlled release 269 (2018) 355–363.DOI
- [25]A. A. Konta, M. García-Piña, D. R. Serrano, Personalised 3d printed medicines: which techniques and polymers are more successful?, Bioengineering 4 (4) (2017) 79.DOI
- [26]J. Panetta, H. Mohammad, E. Luci, V. Babaei, Shape from release: Inverse design and fabrication of controlled release structures, ACM Transactions on Graphics 41 (6) (2022) 1–16. doi:10.1145/3550454.3555456.
- [27]R. Altunay, J. Suuronen, E. Immonen, L. Roininen, J. Hämäläinen, Computational design of personalized drugs via robust optimization under uncertainty, arXiv preprint arXiv:2507.16470 (2025).arxiv.org/abs/2507.16470
- [28]A. Dokoumetzidis, P. Macheras, A century of dissolution research: from noyes and whitney to the biopharmaceutics classification system, International journal of pharmaceutics 321 (1-2) (2006) 1–11.pubmed.ncbi.nlm.nih.gov/16920290
- [29]J. Siepmann, F. Siepmann, Mathematical modeling of drug dissolution, International journal of pharmaceutics 453 (1) (2013) 12–24.DOI
- [30]Z. Xu, P. Meakin, Phase-field modeling of solute precipitation and dissolution, The Journal of chemical physics 129 (1) (2008).DOI
- [31]Z. Xu, H. Huang, X. Li, P. Meakin, Phase field and level set methods for modeling solute precipitation and/or dissolution, Computer Physics Communications 183 (1) (2012) 15–19.DOI


