An optimization framework for battery health management in vehicle-to-grid systems integrating transformer-based degradation prediction and grid service requirements - PMC Skip to main content An official website of the United States government Here's how you know Here's how you know Official websites use .gov A .gov website belongs to an official government organization in the United States. Secure .gov websites use HTTPS A lock ( Lock Locked padlock icon ) or https:// means you've safely connected to the .gov website. Share sensitive information only on official, secure websites. Search Log in Dashboard Publications Account settings Log out Search… Search NCBI Primary site navigation Search Logged in as: Dashboard Publications Account settings Log in Search PMC Full-Text Archive Search in PMC Journal List User Guide PERMALINK Copy As a library, NLM provides access to scientific literature. Inclusion in an NLM database does not imply endorsement of, or agreement with, the contents by NLM or the National Institutes of Health. Learn more: PMC Disclaimer | PMC Copyright Notice Sci Rep . 2026 Mar 6;16:12258. doi: 10.1038/s41598-026-38862-4 Search in PMC Search in PubMed View in NLM Catalog Add to search An optimization framework for battery health management in vehicle-to-grid systems integrating transformer-based degradation prediction and grid service requirements Chaochun Zhong Chaochun Zhong 1 Guangzhou Institute of Measurement and Testing Technology, Guangzhou, 510000 Guangdong China Find articles by Chaochun Zhong 1, ✉ , Qingliang Ma Qingliang Ma 1 Guangzhou Institute of Measurement and Testing Technology, Guangzhou, 510000 Guangdong China Find articles by Qingliang Ma 1 , Mingzhu Ren Mingzhu Ren 1 Guangzhou Institute of Measurement and Testing Technology, Guangzhou, 510000 Guangdong China Find articles by Mingzhu Ren 1 , Lei Xiong Lei Xiong 1 Guangzhou Institute of Measurement and Testing Technology, Guangzhou, 510000 Guangdong China Find articles by Lei Xiong 1 Author information Article notes Copyright and License information 1 Guangzhou Institute of Measurement and Testing Technology, Guangzhou, 510000 Guangdong China ✉ Corresponding author. Received 2025 Oct 28; Accepted 2026 Jan 31; Collection date 2026. © The Author(s) 2026 Open Access This article is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License, which permits any non-commercial use, sharing, distribution and reproduction in any medium or format, as long as you give appropriate credit to the original author(s) and the source, provide a link to the Creative Commons licence, and indicate if you modified the licensed material. You do not have permission under this licence to share adapted material derived from this article or parts of it. The images or other third party material in this article are included in the article’s Creative Commons licence, unless indicated otherwise in a credit line to the material. If material is not included in the article’s Creative Commons licence and your intended use is not permitted by statutory regulation or exceeds the permitted use, you will need to obtain permission directly from the copyright holder. To view a copy of this licence, visit http://creativecommons.org/licenses/by-nc-nd/4.0/ . PMC Copyright notice PMCID: PMC13079827 PMID: 41792153 Abstract The paper propose an optimal charging and discharging strategy for electric vehicle (EV) batteries based on Vehicle-to-Grid (V2G) technology, aiming to minimize battery degradation while satisfying grid demand constraints. The method employs a Transformer-based model to predict the Battery Capacity Degradation (BCD), which is integrated into an optimization framework to balance battery lifespan and grid service efficiency. The optimization problem incorporates penalty terms to mitigate power fluctuations and introduces ramp rate constraints to limit abrupt changes in charging and discharging power. Additionally, it incorporates time-of-use (TOU) electricity pricing to maximize economic returns under dynamic pricing conditions. The objective function combines battery degradation cost, power fluctuation penalties, and revenue gains, leading to a theoretically derived and experimentally validated optimal scheduling algorithm suitable for engineering applications. Experimental results demonstrate the effectiveness of the proposed approach in achieving a trade-off between battery health and grid service performance, highlighting its applicability in intelligent energy systems. Introduction In recent years, the adoption of electric vehicles (EVs) has accelerated rapidly, driven by increasing environmental concerns and advances in battery technologies. A key enabler of this transition is the Vehicle-to-Grid (V2G) system, which allows bidirectional energy flow between EVs and the power grid, effectively transforming EVs into distributed energy storage units. While V2G offers advantages such as grid stabilization and renewable energy integration, frequent charge–discharge cycles can accelerate battery degradation, raising concerns about long-term battery health and economic viability. Current research on V2G optimization primarily focuses on minimizing energy costs and satisfying grid demands, often overlooking the impact of charging/discharging strategies on battery lifespan. Traditional approaches employ electrochemical models 1 or equivalent circuit models 2 to estimate the State of Charge (SOC), but these methods struggle to cope with dynamic operating conditions. Although machine learning techniques—particularly those used for SOC estimation 3 —have shown promise, few studies integrate degradation-aware optimization. Optimization frameworks for V2G systems are typically based on linear programming 4 or dynamic programming 5 ; however, these methods may fail to fully capture the nonlinear characteristics of battery wear. Model Predictive Control (MPC) 6 has been applied to handle real-time constraints, but existing implementations often neglect critical aspects such as power fluctuation penalties 7 and ramp rate constraints 8 . Furthermore, while time-of-use (TOU) pricing is recognized as a key economic driver, its integration with battery degradation models remains underexplored. This paper proposes a novel approach that integrates Transformer-based battery capacity degradation prediction with a constrained optimization framework to minimize battery degradation while meeting grid requirements. The Transformer architecture, originally developed for natural language processing 10 , has since demonstrated strong performance in time series forecasting 11 . Our optimization framework includes three key constraints: (1) penalty terms to suppress power fluctuations, (2) ramp rate limits to reduce mechanical stress, and (3) TOU pricing to align charging and discharging actions with economic incentives. Unlike prior work that treats degradation as a secondary concern, our method leverages a data-driven Transformer model to predict BCD, enabling more accurate estimation of battery wear. The main contributions of this work are threefold. First, we introduce a Transformer-based battery capacity degradation prediction model capable of capturing nonlinear degradation patterns under varying operational conditions. Second, we formulate a multi-objective optimization problem that balances battery health, grid service quality, and economic return, incorporating realistic constraints often overlooked in previous studies. Third, we compare the practicality and cost-effectiveness of classical algorithms and particle swarm optimization (PSO) in engineering applications, and validate the effectiveness of the proposed V2G scheduling method. The remainder of this paper is organized as follows: Section “ Theoretical analysis ” reviews related work on V2G optimization and battery degradation modeling. Section “ Background and preliminary concepts ” provides background on the Transformer architecture and optimization constraints. Section “ Battery capacity degradation modeling and optimization method ” details the proposed battery capacity degradation modeling and optimization framework. Section “ Experiment and data analysis ” presents the experimental setup and results. Finally, Section “ Conclusion and future work ” discusses insights and future research directions. Theoretical analysis In Vehicle-to-Grid (V2G) systems, the optimization of electric vehicle (EV) charging and discharging strategies has been extensively studied from various perspectives. Existing approaches can be broadly categorized into three groups: (1) scheduling strategies that account for battery degradation, (2) grid-oriented optimization methods, and (3) economically driven strategies. Research on battery degradation Early studies on battery degradation primarily relied on electrochemical models to estimate capacity fade. While accurate, these models required detailed knowledge of battery chemistry and involved high computational complexity 12 . To improve practicality, subsequent research adopted simplified empirical models—such as the rainflow counting method based on depth of discharge (DOD) and charging rates 13 —to estimate battery wear. In recent years, data-driven approaches, particularly machine learning models, have emerged as powerful tools for predicting degradation under dynamic operating conditions 14 . Significant progress has been made recently to integrate degradation awareness directly into V2G optimization frameworks rather than treating it solely as a post-optimization assessment. For instance, Liu and Zhang 15 incorporated battery aging costs into an electric vehicle path optimization model, balancing charging and switching strategies. Khezri et al. 16 proposed a Mixed-Integer Linear Programming (MILP) approach that jointly optimizes V2G scheduling with calendar and cycle aging constraints. Similarly, Singh et al. 17 developed a multi-agent framework for P2P energy trading that accounts for battery degradation within V2X services. However, a significant trade-off between model fidelity and computational efficiency remains a key challenge in these emerging studies. Optimization frameworks based on Mixed-Integer Linear Programming (MILP) inevitably require linearizing the battery degradation curves to ensure solvability. Such piecewise linear approximations fail to fully capture the convex, nonlinear characteristics of capacity fade, particularly under the high-frequency charge–discharge cycles inherent to V2G, where degradation rates accelerate non-linearly at extreme SOC levels. Furthermore, while macro-level strategies focusing on path optimization or P2P market trading successfully address routing and economic incentives, they often overlook the micro-scale mechanical stress induced by rapid power fluctuations. These approaches typically utilize simplified energy throughput models that lack the temporal attention mechanisms needed to identify damaging operation sequences. Consequently, there is an urgent need for a scheduling method that leverages advanced deep learning (e.g., Transformers) to precisely model these nonlinear, time-dependent degradation patterns, integrated within a nonlinear programming solver (e.g., SLSQP) to simultaneously satisfy strict grid ramp-rate constraints and minimize physical battery wear. Therefore, this paper focuses on developing a multi-objective optimization framework that leverages a Transformer-based model to capture nonlinear degradation patterns, integrated directly into a nonlinear programming solver to jointly optimize system performance and long-term battery health. Economically driven strategies Time-of-Use (TOU) pricing has long been a primary factor in optimizing EV charging costs 18 . Game-theoretic approaches have been proposed to model energy trading between aggregators and grid operators 19 . Reinforcement learning methods have also shown promise in adapting to dynamic pricing environments 20 . Nonetheless, existing economic optimization strategies tend to prioritize short-term financial returns while neglecting long-term battery health, potentially leading to accelerated capacity degradation. The proposed method differs from previous studies in several key aspects. First, the Transformer-based battery capacity degradation model more accurately captures nonlinear degradation patterns compared to conventional equivalent circuit models. Second, the optimization framework simultaneously considers battery health (via a degradation-aware objective), grid stability (via ramp rate constraints), and economic incentives (via TOU pricing) in a unified formulation. Finally, the inclusion of a power fluctuation penalty explicitly addresses a practical issue often overlooked in theoretical studies—battery degradation induced by rapid charge–discharge transitions. This integrated approach bridges the gap between battery lifespan considerations and grid service requirements in V2G systems. Background and preliminary concepts To establish the foundation for the proposed method, this section introduces key concepts related to battery degradation modeling, the Transformer architecture, and optimization constraints specific to V2G systems. Understanding these components is essential for analyzing the interplay between battery health, grid stability, and economic factors discussed in the subsequent sections. Battery degradation mechanisms The degradation of lithium-ion batteries primarily manifests in two forms: capacity fade and power fade. Capacity fade refers to the reduction in total charge storage capability, typically caused by the growth of the solid electrolyte interphase (SEI) layer 21 . Power fade, on the other hand, results from increased internal resistance due to the degradation of electrode materials 22 . Both phenomena are influenced by operational factors such as the amplitude of State of Charge (SOC) fluctuations, charge–discharge rates, and temperature variations 23 . The relationship between SOC and degradation is nonlinear; extreme high or low SOC levels can accelerate capacity loss. Empirical studies have shown that operating outside the nominal voltage range can significantly increase degradation rates, with each additional 0.1 V in battery voltage potentially doubling the degradation rate 24 . This nonlinearity motivates the use of a Transformer-based battery capacity degradation prediction method, as traditional linear models or simplified physical models fail to fully capture these complex dependencies. Transformer for time series forecasting The Transformer architecture has demonstrated outstanding performance in modeling sequential data 25 . Its self-attention mechanism allows the model to learn long-range dependencies in time series, making it particularly suitable for predicting battery capacity degradation trajectories. A standard Transformer consists of an encoder–decoder structure with multiple attention heads. Each attention head computes a weighted sum of input features, enabling the model to focus on relevant temporal patterns 26 . Positional encoding is added to preserve temporal order, which is crucial for battery capacity degradation sequences where timing affects degradation. The Transformer’s ability to handle variable-length sequences aligns well with V2G applications, where charging and discharging durations can vary significantly. Optimization constraints in V2G systems Three key constraints govern practical V2G operation: power fluctuation limits, ramp rate limits, and time-of-use (TOU) pricing considerations. The power fluctuation penalty prevents excessive changes in charging/discharging power, which can induce mechanical stress in battery components 27 . These penalties are typically modeled as quadratic functions to suppress large variations between consecutive time steps. Ramp rate constraints define the maximum allowable rate of power change (in kW/min), safeguarding both battery health and grid stability 28 . These constraints are especially critical during transitions between charging and discharging modes, as abrupt changes can accelerate battery degradation and violate grid reliability requirements. TOU pricing introduces economic incentives by varying electricity prices throughout the day 29 . The optimization process must account for these price fluctuations while balancing battery wear factors, forming a multi-objective trade-off between immediate profit and long-term battery health. These constraints collectively shape the feasible solution space for V2G optimization and require careful mathematical modeling as discussed in Section “ Battery capacity degradation modeling and optimization method ”. The Transformer-based battery capacity degradation prediction provides the necessary degradation model to appropriately balance these competing objectives. Battery capacity degradation modeling and optimization method The proposed method integrates Transformer-based battery capacity degradation prediction with a constrained optimization framework to achieve optimal charging and discharging strategies for V2G systems. This section presents the technical details of our approach, beginning with the Transformer architecture used for battery capacity degradation prediction, followed by the formulation of the optimization problem, and finally the incorporation of operational constraints. Transformer-based battery capacity degradation prediction The capacity-loss prediction model employed in this study is based on the Transformer architecture, which has demonstrated superior performance in time series forecasting tasks 10 , 11 . Unlike traditional electrochemical models that require detailed knowledge of battery chemistry and involve high computational complexity 12 , or simplified empirical models such as the rainflow counting method 13 , the Transformer-based approach offers a data-driven alternative that can capture complex nonlinear degradation patterns without explicit physical modeling. Our V2G battery degradation dataset from the University of Maryland 30 , 31 contains sequential measurements of four key operational parameters: (1) State of Charge (SOC) representing the current energy level, (2) charge/discharge current indicating power flow direction and magnitude, (3) temperature affecting electrochemical reaction rates, and (4) historical capacity degradation reflecting cumulative battery wear. These features exhibit three critical characteristics that motivate our model selection: (a) long-range temporal dependencies,current capacity loss depends not only on recent operational history but also on accumulated stress from prior cycles 27 ; (b) nonlinear multi-factor interactions, battery degradation is influenced by complex coupling among SOC fluctuations, charge/discharge rates (C-rate), and temperature variations 23 ; and (c) variable-length sequences, V2G charging and discharging durations vary significantly across operational scenarios. To address these data characteristics, the Transformer architecture provides three corresponding mathematical mechanisms. First, the self-attention mechanism enables the model to capture long-range dependencies by computing weighted relationships across the entire time sequence. For our dataset with T time steps, the model forms an attention matrix of size T × T, allowing current capacity prediction at time t to attend to all historical states from t = 1 to t − 1, thereby capturing cumulative degradation effects 25 . Second, the multi-head attention mechanism processes our four input features in parallel subspaces, allowing the model to simultaneously learn different interaction patterns—for instance, one attention head may specialize in SOC-temperature coupling while another captures current-degradation relationships 26 . Third, unlike recurrent architectures with fixed-length hidden states, Transformers process variable-length sequences without architectural constraints, naturally accommodating the irregular charging/discharging patterns in V2G operations. Input Feature Formulation: Let x_t = [SOCt, I_t, T_t, ΔC_t − 1] ∈ ℝ 4 denote the feature vector at time t, where: SOCt ∈ [0, 1] represents the normalized state of charge from the Maryland dataset I t is the charge (+) or discharge (−) current in Amperes T t is the battery temperature in degrees Celsius ΔC t−1 is the previous capacity loss estimate in Ah The input sequence X = [x 1 , x 2 , …, x T ] ∈ ℝT × 4 contains the complete operational history for each charging/discharging cycle. Self-Attention Mechanism for Temporal Dependencies: The core innovation of the Transformer is the self-attention mechanism, which computes importance weights among all time steps in our battery operational sequence. For our four-dimensional input features X, the mechanism first projects them into three different representation spaces through learned linear transformations:Q = XW Q , K = XW K ,V = XW V. Where WQ, WK, WV ∈ ℝ 4 × dᵏ are learned projection matrices that transform our four input features into d_k-dimensional representations. The attention mechanism then computes scaled dot-products: 1 where head_h = Attention(QW_hQ, KW_hK, VW_hV). This multi-head structure is particularly valuable for our multi-dimensional battery data because different attention heads can specialize in different feature interactions 26 . For example: Head 1 may learn to correlate SOC fluctuations with capacity loss (modeling depth-of-discharge effects). Head 2 may capture temperature-current interactions (modeling thermal stress). Head 3 may track cumulative degradation patterns over long sequences. The final concatenation and projection WO combines these specialized representations into a unified degradation prediction. Model Architecture : The encoder consists of N identical layers, each containing a multi-head self-attention sub-layer followed by a position-wise fully connected feed-forward network. Residual connections and layer normalization are applied around each sub-layer to facilitate training and improve gradient flow. The decoder similarly consists of N identical layers with an additional encoder-decoder attention sub-layer. The final output projects through a linear layer to predict battery capacity degradation loss ΔC_t for the next time step. Training Objective : The model is trained using mean squared error loss between predicted capacity loss ΔĈ_t and actual measurements ΔC_t from the Maryland dataset : 2 3 The decoder similarly consists of identical layers with an additional encoder-decoder attention sub-layer. The final output projects through a linear layer and softmax to predict battery capacity degradation loss for the next time step. The model is trained using mean squared error loss between predicted and actual capacity degradation measurements. Formulation of the optimization problem The optimization problem aims to determine the optimal charging/discharging power that minimizes battery degradation while satisfying grid constraints and maximizing economic benefits. The objective function combines three key components: 4 Battery degradation is typically correlated with the depth of discharge (DoD), state of charge (SOC) level, and charge/discharge rates. Commonly used models—such as the Ah-throughput model or semi-empirical models—introduce nonlinear characteristics to capture these effects. 5 As shown in formula ( 4 ), term incorporates three nonlinear degradation-related components: term , representing the nonlinear response of electrode stress; term , accounting for the nonlinear effect of charge/discharge rates based on electrochemical kinetics; and term , capturing the effective cycle depth under nonlinear superposition based on fatigue accumulation. The corresponding mathematical formulations are presented as follows. 6 7 8 In addition to the nonlinearity of term in formula ( 3 ), term is also nonlinear, which significantly increases the overall nonlinearity of the objective function. Given the presence of multiple nonlinear components in the objective function, this study characterizes the V2G scheduling problem as a standard nonlinear programming (NLP) problem. In general, the gradient of the degradation cost function is given by: 9 For example, taking partial derivative with respect to A yields: 10 For differentiable functions with continuous first-order derivatives, the local optimum point must satisfy: 11 Hence, accurate gradient information enables efficient convergence to a local optimum by guiding the descent along the gradient direction. n case , it represents the steepest ascent direction of function on each dimension. Taking a common battery degradation function as an example, its gradient with respect to discharge power can be expanded as the following structure 12 is the SOC state at time , is the optimal SOC range, is the nonlinear factor controlling the penalty degree, and is the sensitive factor of SOC position, such as temperature, health status coupling terms, etc. This gradient expresses the sensitivity of the physical system to key states such as “battery overcharge/over-discharge” and can be propagated layer by layer through the chain rule and state transition formulas. Gradients can generally be obtained efficiently through the following methods: Analytical Differentiation: For differentiable objective functions, the gradient expressions can be derived explicitly. Automatic Differentiation (AD): Mainstream optimization frameworks support structured reverse-mode differentiation. Finite Difference Approximation: When the objective function is available in closed form but its derivatives are unknown, gradient information can still be approximated via finite difference methods. Sequential Quadratic Programming (SQP): A class of iterative optimization algorithms that solve constrained nonlinear optimization problems by approximating the objective function and constraints with quadratic subproblems, using gradient information (obtained analytically, via automatic differentiation, or numerical approximation) to find the optimal solution. For optimization problems with well-defined objective functions, many existing approaches are built upon and extended from Particle Swarm Optimization (PSO). This class of algorithms simulates collaborative behavior in swarm intelligence to iteratively search for optimal solutions within the solution space. The primary advantages of PSO lie in its gradient-free nature, implementation simplicity, and favorable performance in certain low-dimensional, unconstrained or weakly constrained continuous optimization problems. As a model-free global search method, each particle in PSO represents a complete solution vector: 13 However, during the optimization process, particles cannot inherently satisfy the dynamic evolution relationship of . Typically, penalty functions are incorporated into the objective function to constrain solutions that violate system dynamics: 14 Nevertheless, while penalty functions can penalize infeasible solutions, they cannot ensure physical feasibility. This limitation arises because particle updates are global and discontinuous, whereas the capacity evolution is inherently time-dependent and accumulative. Specifically, a particle generates a solution vector [P₁, P₂, …, PT], but the feasibility of this sequence with respect to SOC dynamics cannot be verified a priori. This is because the position updates in PSO do not preserve the physical evolution relationship. Particles move in a stochastic search space, which often results in a high proportion of solutions violating the physical dynamic constraints, thus failing to accurately replicate the underlying physical laws. Moreover, under high-dimensional constraints, the probability of obtaining feasible solutions through random sampling or iterative updates decreases exponentially, leading to a very low feasible solution rate. 15 From the formula, it can be seen that when , even if the feasible region volume is 10%, the proportion of overall feasible solutions approaches 0, and PSO will “blindly search” in the infeasible space, thus having no learning value. In practical engineering applications, this implies that when using PSO, over 99% of the generated solutions are infeasible, failing to satisfy critical constraints such as charging/discharging safety, grid requirements, and battery lifespan. Moreover, the algorithm expends a substantial number of iterations exploring physically meaningless points. This issue constitutes a major challenge for applying similar heuristic algorithms in real-world engineering scenarios, significantly increasing implementation costs. Based on the above analysis and considering engineering practicality, this study selects the Sequential Quadratic Programming (SLSQP) algorithm to solve the nonlinear programming problem. The SLSQP method begins by constructing the Lagrangian function as follows. 16 is the Lagrange multiplier for the formula/inequality constraint. Combining the objective function, at the iteration point , use a quadratic model to approximate the original problem. 17 uses the quasi-Newton approximation of the Hessian to process curvature, with the formula as follows: 18 19 Regarding the V2G problem, when the iteration point enters a high attenuation region (e.g., SOC > 80%), the gradient difference contains the local convexity information of the objective function , and automatically enhances positive definiteness ( ), avoiding iteration divergence in non-convex regions. And the update of formula ( 17 ) satisfies , forcing to approach the true curvature in the search direction , which avoids the exponential term of the analytical computation function, with a single update complexity of only , adapting to rapid updates in engineering applications. Integration of degradation cost and constraints The optimization problem incorporates several practical constraints to ensure feasible operation: Power Capacity Constraints: 20 where and represent the minimum and maximum allowable power levels. Ramp Rate Constraints: 21 where is the maximum allowable ramp rate. SOC Boundary Constraints: 22 maintaining the battery within safe operating limits. Energy Balance Constraint: 23 where is the charge/discharge efficiency and is the nominal battery capacity. The optimization problem is solved using a sequential quadratic programming approach, which handles the nonlinear objective function and constraints efficiently. The transformer model provides real-time updates to the degradation cost estimates, enabling adaptive optimization as battery conditions evolve. The overall overview of the V2G system is shown in Fig. 1 . Fig. 1. Open in a new tab Overview of the V2G system. Experiment and data analysis Battery degradation model modeling To ensure the reproducibility of the proposed method and address the specific configuration of the Transformer-based model, we provide a comprehensive summary of the dataset selection, data preprocessing steps, model hyperparameters, and training protocol. Implementation Details The experimental data is derived from the University of Maryland (CALCE) Battery Research Dataset. We selected the LiCoO2/Graphite (CX2-36) 30 , 31 battery cells cycled at room temperature to validate the model’s ability to capture nonlinear degradation patterns. Detailed experimental settings, including the data split strategy, sequence generation parameters, and the specific hyperparameters used for the Transformer model, are listed in Table 1 . Table 1. Detailed experimental settings and hyperparameters. Category Parameter/item Value/description Dataset and preprocessing Data source University of Maryland (CALCE) dataset Cell type LiCoO2/Graphite prismatic cells (CX2-36) Ambient temperature 25 °C Data split (Train/Val/Test) 60%/20%/20% Normalization method Min–Max scaling (range [0,1]) Sequence length (L) 50 time steps (Look-back window) Smoothing filter Moving average (window size = 10) Transformer model Encoder layers (N) 3 Attention heads (h) 4 Model dimension 64 Feed-forward dim 128 Dropout rate 0.1 Training protocol Optimization algorithm Adam optimizer Initial learning rate 0.001 (decay rate: 0.95 per 10 epochs) Batch size 64 Loss function Mean squared error (MSE) Early stopping Patience: 20 epochs Open in a new tab As observed in the Fig. 2 , the Transformer model demonstrates strong tracking capability in the battery capacity prediction task. The predicted values (orange dashed line) closely follow the overall trend of the true values (blue solid line), indicating that the model successfully captures the dynamic variation patterns of battery capacity. Fig. 2. Open in a new tab BCD prediction. According to the results in Table 2 , the Mean Squared Error (MSE) is 0.286%, indicating that the average deviation between the predicted and true values is controlled within 0.3%, which represents a high level of accuracy in the field of battery capacity prediction. Considering practical application scenarios, an error of 0.286% corresponds to an average deviation of approximately 0.286 Ah for a battery with a full capacity of 100 Ah. This precision is sufficient to meet control requirements in most operating conditions of battery management systems. Compared to traditional Coulomb counting methods—which typically exhibit errors between 1 and 3%—these results highlight the significant effectiveness of Transformer-based modeling. Table 2. Model evaluation. MSE MAE (%) RMSE (%) 0.286% 0.116 0.341 Open in a new tab The Mean Absolute Error (MAE) of 0.116% indicates the absence of significant outliers in the model predictions; the error distribution is relatively uniform without large localized deviations. The Root Mean Square Error (RMSE) of 0.341%, closely aligned with the MAE (with a ratio of approximately 1.19), suggests a concentrated error distribution without severe outliers. In summary, the Transformer-based approach adopted in this study for modeling the multi-input feature capacity degradation model is successful and demonstrates high predictive accuracy. V2G charge–discharge strategy System parameters and constraint settings To evaluate the proposed scheduling method, we simulated a V2G system with specific operational constraints. These parameters were selected to reflect a typical residential EV charging scenario while adhering to the grid’s safety requirements.The optimization problem defined in Section “ Formulation of the optimization problem ” was solved using the parameters detailed in Table 3 . The time horizon is set to 24 h with a discrete time step of 1 h. The battery capacity and power limits are based on a standard mid-range electric vehicle battery pack configuration. Table 3. V2G System parameters and constraint values. Symbol Parameter description Value Unit Enom Nominal Battery Capacity 60 kWh Pmax Maximum Charging Power 15 kW Pmin Maximum Discharging Power − 15 kW SOCmax Upper SOC Limit 0.9 – SOCmin Lower SOC Limit 0.2 – SOCinit Initial SOC (t = 0) 0.5 – Η Charge/Discharge Efficiency 0.95 – Rmax Ramp Rate Limit 3 kW/min Δt Time Step Duration 1 Hour T Optimization Horizon 24 Hours Open in a new tab This study conducts a comprehensive performance analysis of three algorithms—Sequential Quadratic Programming (SLSQP), Constrained Optimization BY Linear Approximation (COBYLA), and Particle Swarm Optimization (PSO)—in the context of energy storage system scheduling optimization. These algorithms respectively represent classical numerical optimization, derivative-free robust optimization, and heuristic global optimization paradigms. By comparing their performance across multiple dimensions including charge–discharge strategies, battery utilization, economic benefits, and computational efficiency, this work provides a holistic evaluation of solution characteristics for energy storage system optimization problems. To ensure a rigorous comparison between the deterministic algorithms (SLSQP, COBYLA) and the heuristic algorithm (PSO), we standardized the termination tolerances and constraint-handling mechanisms where applicable.1. Algorithm Hyperparameters: Specific hyperparameters for each algorithm are detailed in Table 4 . For PSO, we selected a population size of 100 and a maximum of 500 iterations to ensure sufficient exploration of the high-dimensional solution space (D = 24). The inertia weight decreases linearly from 0.9 to 0.4 to balance global exploration and local exploitation. Table 4. Comparison of algorithm results. SLSQP COBYLA PSO COST − 19.81 − 18.63 20.12 Battery metric loss 0.7295 0.7296 0.7294 Time (s) 3.61 1.4 8.33 Fina SOC 0.8 0.8 0.8 Open in a new tab Comparison Fairness : It is important to note that the algorithms were not restricted to a fixed computational time budget. Instead, they were configured with comparable convergence tolerances (for SLSQP/COBYLA) or sufficient iteration counts (for PSO) to allow each algorithm to reach its best possible solution. The computation times reported in Table 4 therefore reflect the inherent efficiency of each algorithm in reaching these solutions. PSO Constraint Handling and Feasibility: Unlike SLSQP and COBYLA, which handle constraints natively via Lagrangian multipliers or linear approximations, standard PSO requires an external mechanism to handle infeasible solutions. We adopted the Static Penalty Function method. The unconstrained objective function is modified as: 24 where is a large penalty coefficient (set to ) for constraint . As shown in Fig. 3 , from the perspective of charging strategies, the three algorithms exhibit distinctly different characteristics. Both SLSQP and COBYLA demonstrate high sensitivity to electricity price signals, scheduling stable charging power of approximately 4 kW during the low-price period from hours 0 to 4 (around 0.3–0.4 RMB/kWh), followed by high-power charging during the secondary low-price period from hours 17 to 21. Notably, the COBYLA algorithm adopts a more aggressive charging strategy during the later charging phase (hours 20 to 24), reaching charging power of about 14 kW—approximately 27% higher than SLSQP’s 11 kW. This difference reflects the distinct optimization trajectories taken by the two deterministic algorithms when handling constraint boundaries. Fig. 3. Open in a new tab Algorithm comparison. In contrast, the PSO algorithm’s charging strategy significantly deviates from the optimal trajectory. It begins with approximately -10 kW in the initial phase and gradually adjusts to only about 6 kW of charging power, which is far below the theoretical optimum. This conservative charging behavior indicates that PSO suffers from premature convergence issues when addressing high-dimensional continuous optimization problems, failing to fully exploit economic opportunities during low-price periods. Evaluation of discharge strategy optimization The formulation of the discharge strategy is directly related to maximizing the economic returns of the energy storage system. Experimental results show that both the SLSQP and COBYLA algorithms scheduled approximately − 10 kW of discharge power during the high electricity price period from hour 13 to 17 (approximately 1.2–1.5 RMB/kWh), achieving significant peak-valley arbitrage effects. This strategy reflects the effective utilization of objective function gradient information by deterministic optimization algorithms, enabling precise identification of optimal discharge timing and corresponding power scheduling decisions. In contrast, the PSO algorithm exhibits notable deficiencies in discharge strategy formulation. It allocated insufficient discharge power during high-price periods, missing key arbitrage opportunities. Particularly during the price peak hours (13–16), PSO failed to schedule adequate discharge power, resulting in a suboptimal strategy that directly impacted the economic performance of the energy storage system. Comprehensive evaluation of battery utilization Battery utilization is a critical indicator for assessing the economic performance of the energy storage system. Analysis of the SOC curves reveals that both SLSQP and COBYLA algorithms achieve high battery utilization. Under both algorithms, the battery charges to a high SOC of approximately 0.9 during low-price periods and discharges to a low SOC of around 0.2 during high-price periods, achieving a battery utilization rate of 70%, thereby fully exploiting the economic value of the energy storage system. By comparison, the SOC variation under the PSO-controlled battery is only about 0.3, indicating significantly lower battery utilization. This low utilization directly reflects the performance shortcomings of PSO in energy storage optimization scheduling, demonstrating its inability to effectively balance battery operational constraints with the goal of economic maximization. Tabular data further corroborate these findings. The battery degradation metrics for the three algorithms are very close—0.7295 (SLSQP), 0.7296 (COBYLA), and 0.7294 (PSO)—indicating that physical battery constraints are effectively satisfied, with performance differences mainly attributable to economic optimization outcomes. Economic benefits and computational efficiency analysis To comprehensively evaluate the proposed scheduling strategy, this section analyzes the economic performance and computational efficiency of the three algorithms. The evaluation consists of a baseline scenario analysis (based on the single price profile in Section “ V2G charge–discharge strategy ”) and a stochastic robustness analysis (based on 100 randomly generated price profiles) to validate the method’s generalizability. Baseline economic performance In the baseline scenario, the three algorithms exhibit significant differences in economic outcomes. As detailed in Table 4 , the SLSQP algorithm achieves the optimal economic result with a total cost of -19.81 RMB (representing a net profit), indicating maximal economic gain. COBYLA follows closely with a cost of -18.63 RMB, showing comparable efficiency to SLSQP in a deterministic environment. The slight difference (1.18 RMB) suggests that both deterministic algorithms can effectively exploit arbitrage opportunities under fixed constraints. Conversely, the PSO algorithm demonstrates poor economic performance, incurring a positive cost of 20.12 RMB (a net loss). This failure to achieve profitability aligns with its conservative charge–discharge strategy observed in Fig. 3 , where it failed to discharge sufficient power during peak price periods. The significant performance gap (39.93 RMB) between SLSQP and PSO underscores that heuristic global search methods may struggle to locate feasible, economically optimal solutions in high-dimensional spaces with strict physical constraints. Statistical robustness and sensitivity analysis To address the uncertainty inherent in real-world electricity markets and validate the robustness of the proposed approach, we extended the evaluation to include 100 stochastic price profiles. These profiles were generated by introducing random fluctuations to the baseline TOU price curve. The statistical results for profit, success rate, and capacity loss are summarized in Table 5 and visualized in Fig. 4 . Table 5. Statistical results of algorithm performance across 100 stochastic price profiles. Algorithm Success rate (%) Profit mean (RMB) Profit Std Capacity loss mean (Ah) SLSQP 100 23.67 15.28 0.0009 COBYLA 91 27.62 14.52 0.0009 PSO 100 − 9.2 10.62 0.0009 Open in a new tab s. Fig. 4. Open in a new tab Statistical results under multiple price curves. Statistical analysis of results under various price conditions is as follows: Algorithm Reliability: The SLSQP algorithm demonstrated superior robustness, achieving a 100% success rate across all 100 scenarios . In contrast, COBYLA failed to find feasible solutions in 9.0% of the cases (91.0% success rate). This instability suggests that while COBYLA is effective in standard scenarios, it may violate strict boundary constraints (e.g., ramp rates or SOC limits) under extreme price volatility. Economic Viability: As shown in Fig. 4 , SLSQP maintained a stable positive profit (Mean: 23.67 RMB). Although COBYLA achieved a slightly higher mean profit (27.62 RMB) in its successful runs, this “advantage” is compromised by its lower reliability. The higher profit in COBYLA likely stems from more aggressive charging/discharging behaviors that occasionally push the system beyond feasible limits, leading to solution failure. Consistent with the baseline results, PSO consistently yielded negative returns (Mean: -9.20 RMB), confirming its unsuitability for this application. Degradation Control: Notably, the Capacity Loss for both valid SLSQP and COBYLA solutions remained extremely low (Mean: 0.0009) with negligible standard deviation. This confirms that the proposed Transformer-based degradation constraints effectively protect battery health regardless of price fluctuations. Computational efficiency evaluation Computational efficiency is critical for real-time scheduling. As shown in the timing results, COBYLA exhibits the fastest solving speed (Mean: 0.38 s in batch tests, 1.4 s in baseline), which is advantageous for high-frequency control . SLSQP follows with a mean time of 1.06 s (3.61 s in baseline), which is still well within the 1-h dispatch interval requirement. While PSO is relatively fast in the batch test (0.83 s), its stochastic nature leads to inconsistent convergence times (up to 8.33 s in the baseline) and, more importantly, poor solution quality. Conclusion on Algorithm Selection: Although COBYLA offers the highest theoretical profit and speed, its 9% failure rate poses a significant risk for grid operations where reliability is paramount. SLSQP strikes the optimal balance: it guarantees 100% feasibility, delivers competitive economic returns (only marginally lower than COBYLA), and strictly minimizes battery degradation. Therefore, SLSQP is identified as the most suitable algorithm for the proposed robust V2G scheduling framework. Conclusion and future work This paper proposes a V2G scheduling method that integrates the Transformer architecture with nonlinear constrained optimization, aiming to maximize economic benefits while simultaneously accounting for battery degradation and grid stability. The approach constructs a Transformer-based battery capacity degradation prediction model that effectively captures the nonlinear dynamic characteristics of battery degradation. Realistic constraints such as power fluctuation penalties, ramp rate limits, and time-of-use (TOU) pricing are incorporated into the optimization framework, enabling a multi-objective balance among battery health, grid service quality, and economic returns. Experimental results demonstrate that the proposed method achieves superior performance across key metrics including SOC prediction accuracy, battery utilization, economic efficiency, and computational cost. The method attains optimal scheduling strategies with minimal computational overhead while satisfying all constraints. Overall, this work bridges the gap between theoretical modeling and practical application, validating the importance and feasibility of integrating battery degradation modeling with optimal control in V2G systems. Although this study has made significant progress in V2G system modeling and optimization, further research is needed on the coupling between degradation and temperature effects. The current model primarily considers battery capacity degradation as the main driver of degradation and does not systematically account for the influence of temperature variations on degradation mechanisms. Future work may incorporate multi-physics modeling approaches or multimodal learning models to enhance the robustness of degradation prediction. Author contributions C.Z. conceived the research idea, developed the overall methodology, and supervised the study. Q.M. designed and implemented the Transformer-based SOC degradation model, and conducted the main experiments. M.R. formulated the optimization problem and performed algorithm comparisons. L.X. collected the data, prepared Figs. 1 , 2 , and 3 , and contributed to the result analysis. C.Z. and Q.M. wrote the main manuscript text. All authors discussed the results and reviewed the final manuscript. Funding Research on metering methods and device development for electric vehicle charging stations for ultra-fast charging and vehicle-to-grid interaction(2024MK156);Research on the Degradation Mechanism of Power Battery State of Charge and Cooperative Charge–Discharge Scheduling Strategy in V2G Scenarios (2025MK166). Data availability Battery Data: https://calce.umd.edu/data Declarations Competing interests The authors declare no competing interests. Footnotes Publisher’s note Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations. References 1. Daigle, M & Kulkarni C. S. Electrochemistry-based battery modeling for prognostics, in Annual Conference of the Prognostics and Health Management Society (2013). 2. You, H. W., Bae, J. I., Cho, S. J., Lee, J. M. & Kim, S. H. Analysis of equivalent circuit models in lithium-ion batteries. AIP Adv. (2018). 3. Buchicchio, E. et al. Battery SOC estimation from EIS data based on machine learning and equivalent circuit model. Energy 283 , 128461 (2023). [ Google Scholar ] 4. Tenfen, D. & Finardi, E. C. A mixed integer linear programming model for the energy management problem of microgrids. Electr. Power Syst. Res. 122 , 19–28 (2015). [ Google Scholar ] 5. Zhang, L. & Li, Y. Optimal management for parking-lot electric vehicle charging by two-stage approximate dynamic programming. IEEE Trans. Smart Grid 8 (4), 1722 (2015). [ Google Scholar ] 6. Nguyen, H. T. & Choi, D. H. Distributionally robust model predictive control for smart electric vehicle charging station with V2G/V2V capability. IEEE Trans. Smart Grid 14 (6), 4621 (2023). [ Google Scholar ] 7. Jia, Y. et al. Peer-to-peer energy trading using prediction intervals of renewable energy generation. IEEE Trans. Ind. Inf. 4 (2), 1454 (2022). [ Google Scholar ] 8. Zheng, Z., Han, F., Li, F. & Zhu, J. Assessment of marginal emissions factor in power systems under ramp-rate constraints. CSEE J. Power Energy Syst. 1 (4), 37 (2015). [ Google Scholar ] 9. Zhao, S & Ming, Z. Modeling demand response under time-of-use pricing, in 2014 International Conference on Power System Technology (2014). 10. Kalyan, K. S., Rajasekharan, A. & Sangeetha. S. Ammus: A survey of transformer-based pretrained models in natural language processing. arXiv preprint arXiv:2108.05542 (2021). 11. Zhou, H., Zhang. S., Peng, J., Zhang, S., Li, J., et al. Informer: Beyond efficient transformer for long sequence time-series forecasting, Iin Proceedings of the AAAI Conference on Artificial Intelligence (2021). 12. Lyu, C. et al. In situ monitoring of lithium-ion battery degradation using an electrochemical model. Appl. Energy 250 , 685 (2019). [ Google Scholar ] 13. Fioriti, D. et al. Battery lifetime of electric vehicles by novel rainflow-counting algorithm with temperature and C-rate dynamics: Effects of fast charging, user habits, vehicle-to-grid and climate zones. J. Energy Storage 59 , 106458 (2023). [ Google Scholar ] 14. Yang, Y. A machine-learning prediction method of lithium-ion battery life based on charge process for different applications. Appl. Energy 292 , 116897 (2021). [ Google Scholar ] 15. Liu, H. & Zhang, A. Electric vehicle path optimization research based on charging and switching methods under V2G. Sci. Rep. 14 (1), 30843 (2024). [ DOI ] [ PMC free article ] [ PubMed ] [ Google Scholar ] 16. Khezri, R., Steen, D., Wikner, E. & Tuan, L. A. Optimal V2G scheduling of an EV with calendar and cycle aging of battery: An MILP approach. IEEE Trans. Transp. Electrif. 10 (4), 10497–10507 (2024). [ Google Scholar ] 17. Singh, A., Sampath, L. P. M. I., Nguyen, D. H., Gooi, H. B. & Nguyen, H. D. A multi-agent framework for p2p energy trading with ev aggregators supporting v2x services. IEEE Trans. Veh. Technol. 73 (12), 18548–18559 (2024). [ Google Scholar ] 18. Yang, S. Y., Woo, J. R. & Lee, W. Assessing optimized time-of-use pricing for electric vehicle charging in deep vehicle-grid integration system. Energy Econ. 138 , 107852 (2024). [ Google Scholar ] 19. Rizwan, M. et al. IOTA-based game-theoretic energy trading with privacy-preservation for V2G networks. IEEE Trans. Intell. Transp. Syst. 10 (2), 217–231 (2024). [ Google Scholar ] 20. Kumar, P. P., Nuvvula, R. S. S., Tan, C. C. et al. Energy-aware vehicle-to-grid (V2G) scheduling with reinforcement learning for renewable energy integration. IEEE Trans. Smart Grid (2024). 21. Li, R. et al. Modelling solvent consumption from SEI layer growth in lithium-ion batteries. J. Electrochem. Soc. 169 (6), 060516 (2022). [ Google Scholar ] 22. Pender, J. P. et al. Electrode degradation in lithium-ion batteries. ACS Nano 14 (2), 1243 (2020). [ DOI ] [ PubMed ] [ Google Scholar ] 23. Abdulla, K. et al. Optimal operation of energy storage systems considering forecasts and battery degradation. IEEE Trans. Smart Grid 9 (3), 2086–2096 (2016). [ Google Scholar ] 24. Zhu, J. et al. Investigation of lithium-ion battery degradation mechanisms by combining differential voltage analysis and alternating current impedance. J. Power Sources 448 , 227575 (2020). [ Google Scholar ] 25. Ahmed, S. et al. Transformers in time-series analysis: A tutorial. Circ. Syst. Signal Process. 42 (12), 7433 (2023). [ Google Scholar ] 26. Feng, Y. & Cheng, Y. Short text sentiment analysis based on multi-channel CNN with multi-head attention mechanism. IEEE Access 9 , 19854–21986 (2021). [ Google Scholar ] 27. Bucci, G. et al. The effect of stress on battery-electrode capacity. J. Electrochem. Soc. 164 (4), A645 (2017). [ Google Scholar ] 28. Uriarte, F. M. et al. Microgrid ramp rates and the inertial stability margin. IEEE Trans. Power Syst. 30 (6), 3209 (2015). [ Google Scholar ] 29. Almahmoud, Z. et al. Dynamic pricing in smart grids under thresholding policies. IEEE Trans. Smart Grid 10 (3), 3415 (2018). [ Google Scholar ] 30. UNIVERSITY OF MARYLAND Battery research data. Retrieved from https://calce.umd.edu/data 31. Saxena, S., Hendricks, C. & Pecht, M. Cycle life testing and modeling of graphite/LiCoO 2 cells under different state of charge ranges. J. Power Sources 327 , 394–400 (2016). [ Google Scholar ] Associated Data This section collects any data citations, data availability statements, or supplementary materials included in this article. Data Availability Statement Battery Data: https://calce.umd.edu/data Articles from Scientific Reports are provided here courtesy of Nature Publishing Group ACTIONS View on publisher site PDF (1.9 MB) Cite Collections Permalink PERMALINK Copy RESOURCES Similar articles Cited by other articles Links to NCBI Databases Cite Copy Download .nbib .nbib Format: AMA APA MLA NLM Add to Collections Create a new collection Add to an existing collection Name your collection * Choose a collection Unable to load your collection due to an error Please try again Add Cancel Follow NCBI NCBI on X (formerly known as Twitter) NCBI on Facebook NCBI on LinkedIn NCBI on GitHub NCBI RSS feed Connect with NLM NLM on X (formerly known as Twitter) NLM on Facebook NLM on YouTube National Library of Medicine 8600 Rockville Pike Bethesda, MD 20894 Web Policies FOIA HHS Vulnerability Disclosure Help Accessibility Careers NLM NIH HHS USA.gov Back to Top