Chronic postsurgical pain (CPSP) affects 10–50% of surgical patients and is a major contributor to long-term opioid use and reduced quality of life. Current predictive models treat patients independently and fail to capture how risk evolves over time or how postoperative opioid trajectories influence divergence in outcomes. We propose a dynamic graph neural network (GNN) framework in which patients are modeled as nodes and similarity-based edges evolve over time based on opioid prescription patterns, pain scores, and preoperative psychological factors. The model includes (1) a patient graph with static preoperative features, (2) a temporal edge update mechanism, (3) a GNN message-passing layer that aggregates information from dynamically connected patients, and (4) a prediction head estimating CPSP risk at 3, 6, and 12 months. By modeling changing patient relationships after surgery, the framework captures how similar patients may diverge or converge depending on postoperative management, enabling more accurate and personalized CPSP risk prediction using longitudinal electronic health record data.
Chronic postsurgical pain (CPSP) persists for at least three months following a surgical procedure and has been documented in 10–50% of patients across major surgery types, including thoracic, amputation, cardiac, breast, and hernia repairs [1, 2]. The transition from acute to chronic pain represents a critical window during which biological healing interacts with psychological vulnerability and pharmacological management to determine long-term outcomes [3, 4]. Risk factors for CPSP extend beyond surgical variables to include preoperative psychological distress, with elevated scores on the Pain Catastrophizing Scale (PCS), General Anxiety Disorder-7 (GAD-7), and Patient Health Questionnaire-9 (PHQ-9) consistently predicting worse pain outcomes [5, 6].
Opioid prescription patterns following surgery have emerged as powerful predictors of CPSP, with initial dose, refill frequency, and total morphine milligram equivalents (MME) over the first postoperative weeks distinguishing patients who will develop persistent pain from those who recover normally [7, 8]. However, patients are not isolated cases—two individuals with identical preoperative psychological profiles may have dramatically different outcomes based on their postoperative opioid management, and their similarity to other patients evolves over time as clinical trajectories unfold [9, 10].
The observation that patient similarity changes over time motivates a relational modeling approach: a patient who initially resembles a low-risk cohort may gradually align with a high-risk group if they request multiple opioid refills and report escalating pain scores [11, 12]. Conversely, a high-risk preoperative profile may resolve into a normal recovery trajectory if postoperative pain is well-controlled and opioid use tapers appropriately [13, 14]. These dynamics suggest that predictive models should update the relational structure among patients continuously rather than treating patient similarity as fixed from baseline.
Table 1 clarifies why the proposed framework is not merely a temporal extension of conventional prediction, but a distinct relational modeling strategy in which patient similarity itself becomes a dynamic clinical signal.
Table 1. Conceptual distinction between static patient-level prediction, static relational modeling, and dynamic graph-based CPSP trajectory prediction
Analytical dimension | Conventional patient-level models (logistic regression / XGBoost) | Static graph neural network | Proposed dynamic graph neural network framework |
Fundamental unit of analysis | Individual patient treated as an independent observation | Patient embedded within a fixed similarity graph | Patient embedded within an evolving similarity graph |
Representation of patient similarity | Not explicitly modeled | Modeled once at baseline | Recalculated repeatedly over postoperative time |
Use of preoperative psychological factors | Incorporated as fixed predictors | Incorporated as node features and initial graph structure | Incorporated as static node features and baseline similarity prior |
Use of postoperative opioid information | Usually collapsed into summary variables | May be appended as temporal node features but relational structure remains fixed | Used both as dynamic node information and as a driver of changing inter-patient connectivity |
Handling of temporal clinical evolution | Limited; often based on aggregated snapshots | Partial; node states may evolve but graph structure does not | Explicitly models temporal change in both node state and edge weight |
Capacity to reflect convergence or divergence between patients | Absent | Weak, because neighborhoods remain unchanged | Strong, because patients can become more or less similar over time |
Clinical interpretation of relational change | Not available | Restricted to baseline similarity patterns | Directly linked to evolving opioid trajectory and pain trajectory similarity |
Ability to capture peer-context effects | None | Present but static | Present and time-sensitive |
Suitability for identifying emerging CPSP risk transitions | Limited | Moderate | High |
Trajectory phenotype support | Usually external to the model | Possible but less naturally aligned with evolving neighborhoods | Intrinsically compatible with resolving, chronic low, chronic high, and intermittent trajectories |
Main conceptual strength | Simplicity and familiar clinical interpretability | Introduces relational inductive bias | Integrates individual risk, temporal evolution, and dynamic relational reasoning |
Main conceptual limitation | Ignores inter-patient structure | Assumes baseline similarity remains clinically valid over time | Requires dense longitudinal data and careful validation of edge update meaning |
This paper presents a conceptual framework for CPSP trajectory prediction based on a dynamic graph neural network (GNN) with temporal edge updates [15, 16]. The framework models patients as nodes in a graph where edges represent similarity of opioid prescription histories and preoperative psychological assessments, and these edge weights are recalculated at each time step to reflect recent pain scores and medication patterns [17, 18]. By combining static preoperative features with dynamic postoperative measurements, the framework aims to capture both stable risk factors and evolving clinical states within a unified relational architecture.
CPSP is defined as pain that develops after a surgical procedure, persists for at least three months, and cannot be attributed to alternative causes such as infection or malignancy [1, 2]. Incidence varies substantially by procedure type, with reported rates of 30–50% after thoracic and amputation surgeries, 20–30% after cardiac surgery, and 10–20% after breast cancer surgery and hernia repair [5, 6]. The socioeconomic burden of CPSP includes prolonged disability, reduced return-to-work rates, and substantial healthcare utilization, making accurate preoperative risk stratification a clinical priority [7, 8].
Preoperative psychological assessments have consistently demonstrated predictive value for CPSP outcomes across multiple surgical populations [19, 20]. The Pain Catastrophizing Scale measures maladaptive cognitive and emotional responses to anticipated or actual pain, while the GAD-7 and PHQ-9 screen for anxiety and depression, each independently associated with postoperative pain trajectories [21, 22]. Higher scores on these instruments predict not only greater acute postoperative pain intensity but also increased likelihood of persistent pain at 6 and 12 months after surgery, with effect sizes comparable to surgical factors [23, 24].
Postoperative opioid prescribing patterns exhibit substantial heterogeneity, with some patients requiring only a few days of low-dose opioids and others escalating to chronic use over months [25, 26]. Key trajectory features include total MME dispensed in the first week, number of refill requests, and the slope of opioid dose change over time [27, 28]. Opioid-naïve patients who receive high initial doses are at particular risk for prolonged use, whereas patients with preoperative opioid tolerance may require different trajectory modeling approaches [10, 29].
Dynamic GNNs extend static graph deep learning to settings where both node features and graph structure evolve over discrete or continuous time [3, 9]. Temporal graph networks (TGNs) incorporate recurrent modules that update node embeddings based on sequences of events, while EvolveGCN uses recurrent neural networks to evolve GCN parameters across time steps [4, 13, 14]. These architectures have been applied to social network analysis, traffic forecasting, and healthcare settings including electronic health record modeling, but their application to CPSP trajectory prediction remains unexplored [11, 16].
The proposed architecture consists of three sequential stages operating on a dynamic patient graph with N nodes corresponding to individual surgical patients [17, 18]. In the first stage, an initial graph is constructed using static preoperative features (psychological scores, demographics, surgical type) with edges connecting patients whose preoperative profiles are similar based on a k-nearest neighbors criterion. In the second stage, a temporal edge update module recalculates edge weights at each weekly time step using recent opioid prescription data and pain scores. In the third stage, a GNN performs message passing across the updated graph at each time step, feeding the resulting patient embeddings into a trajectory prediction head that outputs CPSP risk at 3, 6, and 12 months [12, 15].
Figure 1 illustrates the proposed dynamic graph neural network architecture in which baseline psychological similarity defines the initial patient graph and weekly opioid-pain evolution progressively reshapes inter-patient connectivity for multi-horizon chronic postsurgical pain prediction.

Figure 1. A dynamic graph neural network is used, where baseline psychological similarity forms the initial patient graph and weekly opioid–pain changes update connections for multi-horizon chronic postsurgical pain prediction.
The framework assumes access to longitudinal electronic health record (EHR) data containing preoperative psychological assessments (PCS, GAD-7, PHQ-9), postoperative opioid prescription records with dosage and fill dates, and serial pain scores (0–10 numeric rating scale) collected during routine clinical follow-up [25, 26]. A second assumption is that the surgical cohort contains sufficient patient volume to construct meaningful patient neighborhoods, typically several hundred to thousands of cases with complete data on key variables. A third assumption is that missing data patterns—common in real-world EHR systems for pain scores and refill records—can be addressed through imputation or masking strategies without violating the graph update mechanism [27, 28].
Four design principles guide the framework development. First, the temporal edge update mechanism must be transparent and clinically interpretable: clinicians should understand why two patients become more connected over time (e.g., similar opioid tapering patterns) [19, 20]. Second, the graph architecture should accommodate irregularly spaced clinical observations through time-aware aggregation modules. Third, relational reasoning should complement rather than replace patient-level risk factors, meaning that final predictions integrate both individual static features and neighborhood information. Fourth, the framework must support trajectory clustering to identify clinically meaningful subgroups such as resolving pain, chronic low intensity, chronic high intensity, and intermittent pain patterns [21, 22].
Each patient node is initialized with a static feature vector comprising preoperative psychological scores from validated instruments including the PCS (range 0–52), GAD-7 (0–21), and PHQ-9 (0–27), as these have been identified as robust presurgical predictors of CPSP across multiple cohorts [23, 24]. Additional static features include patient age (years), sex, surgical type encoded categorically (breast, thoracic, orthopedic, abdominal, other), and prior chronic pain history documented preoperatively [1, 2]. The preoperative psychological measures are collected during standard pre-anesthesia evaluation or surgical clinic visits, typically within 30 days before the procedure, ensuring that all static features are available at the time of model deployment [5, 6].
Edges in the initial graph are defined based on similarity of preoperative psychological profiles and surgical type, operationalized as the Euclidean distance between standardized static feature vectors [10, 29]. For each patient, the k nearest neighbors (with k selected via validation) are connected with edge weights inversely proportional to feature distance, ensuring that patients with similar preoperative risk profiles form local neighborhoods. Surgical type is included as a mandatory matching constraint for a subset of edges, reflecting clinical knowledge that recovery trajectories differ substantially across procedures such as total knee arthroplasty versus breast lumpectomy [20, 21].
Dynamic node features are updated at weekly intervals post-surgery, capturing the evolving clinical status of each patient through time-stamped measurements recorded in the EHR [22, 23]. The core dynamic features include weekly total MME dispensed aggregated from prescription fills, count of opioid refill requests submitted during the week, binary indicator of emergency department visits for pain, and reported average pain score (0–10) from patient-reported outcomes or clinical assessments. These temporal features are aligned across patients using a fixed weekly time grid from postoperative week 1 through week 12, with missing values handled through forward imputation or learned masking [24, 25].
At each weekly time step t, the edge weight between patient i and patient j is recalculated based on the similarity of their recent opioid use and pain trajectories over the preceding observation window [26, 27]. Patients who have both escalated their opioid dose (increasing MME) and reported worsening pain scores become more strongly connected, whereas a patient whose opioids are tapering appropriately becomes less connected to an escalating peer even if their preoperative scores were similar [28, 29]. This recalcation operationalizes the clinical hypothesis that postoperative management patterns, rather than preoperative status alone, drive eventual CPSP outcomes, and that patients effectively "change risk groups" as their trajectories evolve [4, 13].
The edge weight update function combines three terms: the change in opioid MME from the previous week to the current week (Δopioid), the change in reported pain score (Δpain), and the static preoperative similarity computed at baseline [10, 11]. Formally,
At each weekly time step t, a graph convolutional layer aggregates information from neighboring patients according to the updated edge weights (t), producing a new embedding for each patient node that incorporates both its own dynamic features and those of its temporally similar peers [15, 25]. The message passing operation follows the formulation introduced by Kipf and Welling, where each node's representation is updated as a normalized sum of neighbor representations multiplied by the current edge weights, followed by a learnable linear transformation and non-linear activation [9, 15]. For CPSP prediction, this mechanism enables a patient with escalating opioid use to receive information from other patients who have followed similar escalating trajectories, potentially revealing shared patterns of transition to chronic pain that would be invisible to patient-independent models [3, 4].
After message passing at each time step produces a sequence of patient embeddings for T weekly time points, a recurrent neural network with long short-term memory (LSTM) or gated recurrent units compresses this sequence into a fixed-dimensional trajectory representation [26, 27]. The time-aware aggregation module processes embeddings in chronological order, maintaining a hidden state that captures how the patient's relational context has evolved over the postoperative period [13, 14]. This design choice is motivated by evidence that the order and timing of opioid dose changes and pain score fluctuations carry prognostic information, with early high-dose exposure followed by rapid tapering potentially differing from delayed but persistent low-dose use [10, 11].
The final trajectory representation from the time-aware aggregation module is passed through a multilayer perceptron with sigmoid activation to produce the probability of CPSP at 3 months post-surgery, with additional output heads providing probabilities at 6 and 12 months for longitudinal risk assessment [28, 29]. Beyond binary CPSP classification, the framework also outputs predicted pain intensity categories (mild, moderate, severe) at each time point by applying a softmax layer over the trajectory representation [12, 17]. The model further produces a risk trajectory type—specifically classifying patients into categories such as resolving pain, chronic low intensity, chronic high intensity, or intermittent pain—enabling clinicians to distinguish between patients who will recover spontaneously and those who require early pain management intervention [18, 19].
The primary prediction task is binary classification of CPSP status at 3 months post-surgery, defined according to established criteria as pain persisting beyond the expected healing time without alternative explanation, with a secondary task of predicting pain intensity categorized as mild (1–3), moderate (4–6), or severe (7–10) on the numeric rating scale [20, 21]. These prediction tasks align with clinical guidelines for CPSP risk stratification and with the outcomes measured in major prospective cohort studies such as the Acute to Chronic Pain Signatures (A2CPS) study, which has collected multimodal biomarkers and clinical data to support predictive model development [22, 23]. The framework outputs predictions for each patient at the time of hospital discharge or at the first postoperative follow-up visit, using only data available up to the prediction time point to ensure clinical utility [24, 25].
Beyond point predictions at fixed time horizons, the framework performs trajectory clustering by assigning each patient to one of four clinically meaningful trajectory types based on their complete postoperative sequence of pain scores and opioid use patterns [26, 27]. The resolving pain type shows decreasing pain and opioid use reaching near-zero levels by week 8; chronic low intensity shows persistent mild pain with minimal opioid use; chronic high intensity shows persistent moderate-to-severe pain with ongoing or escalating opioid requirements; and intermittent pain shows fluctuating pain scores above moderate threshold at multiple time points interspersed with low-pain periods [28, 29]. Assignment to trajectory type is achieved by computing a patient's sequence of hidden embeddings across all time steps, comparing this sequence to prototype trajectories learned during training, and outputting the closest prototype match as an interpretable clinical label [4, 13].
For binary CPSP classification at 3, 6, and 12 months, the framework should report the area under the receiver operating characteristic curve (AUROC) and the F1 score to balance precision and recall, given that CPSP prevalence in typical surgical populations ranges from 10–30% and class imbalance is expected [10, 11]. For pain intensity prediction (mild, moderate, severe), macro-averaged F1 across the three categories provides an appropriate metric that weights each intensity level equally regardless of prevalence. For trajectory type assignment, the framework requires both macro F1 and calibration metrics (e.g., expected calibration error) to ensure that predicted probabilities for each trajectory class reflect true underlying frequencies [12, 17].
Validation of the temporal edge update mechanism requires both quantitative and qualitative analyses to confirm that updated edge weights correspond to clinically plausible similarity evolution [18, 19]. Quantitatively, one can examine whether patients assigned to the same predicted trajectory type (e.g., chronic high intensity) have higher mean edge weights among themselves than across trajectory types at later time steps, while such within-type edge weight elevation may be absent at baseline. Qualitatively, clinical co-investigators should review case examples of patient pairs whose edge weight increased substantially over time, verifying that shared patterns of opioid refill requests and pain score trajectories justify stronger connectivity from a clinical perspective [20, 21].
The dynamic GNN framework should be compared against three baseline approaches using the same train-validation-test split and outcome definitions [22, 23]. The first baseline is a static GNN with no temporal edge updates, where the initial preoperative graph structure remains fixed throughout all time steps, isolating the benefit of dynamic edge recalculation. The second baseline is logistic regression with static preoperative features (psychological scores, age, sex, surgical type) plus summary opioid features (total MME week 1), representing conventional clinical risk modeling. The third baseline is XGBoost using the same feature set, capturing non-linear interactions among static and aggregated dynamic features but lacking relational structure [24, 25]. Superior performance of the dynamic GNN across AUROC and calibration metrics would support the claim that evolving patient similarity captured through temporal edge updates adds predictive value beyond static features and fixed graph structures [26, 27].
The framework requires longitudinal EHR data with regular pain score documentation and opioid prescription tracking across all patients in the cohort, but real-world clinical settings exhibit substantial missingness on both dimensions, particularly for patient-reported pain outcomes [28, 29]. Missing data patterns are unlikely to be completely at random—patients with escalating pain may have more frequent clinical encounters and thus more complete pain score records—potentially introducing bias into edge weight calculations and trajectory assignments [9, 15]. Additionally, the framework assumes that the frequency of clinical observations is sufficient to reconstruct weekly trajectories, but patients who miss follow-up visits or fill prescriptions at irregular pharmacies may have sparse data that violates this assumption [3, 4].
Table 2 translates the proposed architecture into a clinically interpretable implementation matrix by linking each technical module to its data requirements, inferential role, validation objective, and translational risk.
Table 2. Framework-to-clinic mapping of dynamic graph components, data dependencies, interpretive outputs, and validation targets for chronic postsurgical pain prediction
Framework component | Primary data inputs | Computational role | Clinical meaning | Expected output artifact | Key validation target | Principal implementation risk |
Static node initialization | PCS, GAD-7, PHQ-9, age, sex, surgical type, prior chronic pain | Defines each patient’s baseline representation before postoperative evolution | Encodes presurgical vulnerability and baseline clinical context | Static patient feature vector | Baseline discriminative utility and feature completeness | Incomplete psychological screening in routine practice |
Baseline graph construction | Standardized preoperative features; k-nearest neighbors; surgical-type constraint | Establishes initial patient neighborhoods | Groups patients with comparable preoperative risk profiles | Weighted baseline patient graph | Clinical plausibility of neighborhood composition | Over-connection of superficially similar but clinically distinct patients |
Weekly dynamic node update | Weekly MME, refill requests, ED visits for pain, pain score, missingness indicators | Refreshes postoperative patient state over time | Tracks evolving recovery or deterioration after surgery | Time-indexed dynamic feature sequence | Temporal completeness and correct alignment to postoperative week | Irregular documentation and informative missingness |
Temporal edge update mechanism | Δopioid, Δpain, baseline similarity | Recalculates inter-patient connectivity at each time step | Models convergence toward or divergence from shared postoperative pain-opioid patterns | Updated edge weight matrix at week t | Whether rising within-trajectory similarity emerges over time | Edge changes may reflect prescribing culture rather than true patient similarity |
Dynamic GNN message passing | Updated graph plus current node states | Shares information across temporally similar peers | Allows relational amplification of clinically relevant trajectory patterns | Time-specific patient embeddings | Incremental value over non-relational models | Noise propagation through unstable graph neighborhoods |
Time-aware aggregation | Ordered embedding sequence across postoperative weeks | Compresses longitudinal relational history into a patient trajectory representation | Preserves timing and order of postoperative evolution | Final trajectory embedding | Sensitivity to early escalation versus late persistence | Sequence sparsity and variable follow-up density |
Multi-horizon prediction head | Trajectory embedding | Produces CPSP risk probabilities at 3, 6, and 12 months | Supports staged risk stratification and early intervention timing | Binary risk outputs, severity probabilities | AUROC, F1, calibration | Performance drift across institutions and surgery types |
Trajectory phenotype assignment | Full hidden sequence or trajectory prototypes | Maps longitudinal course into interpretable clinical categories | Distinguishes recovery from persistent pain phenotypes | Resolving, chronic low, chronic high, intermittent labels | Prototype coherence and subgroup separability | Over-simplification of heterogeneous recovery patterns |
Comparative evaluation layer | Same data split across all models | Tests whether dynamic relational updating adds value | Demonstrates whether dynamic GNN logic is clinically justified | Benchmark comparison vs static GNN, logistic regression, XGBoost | Superiority in discrimination and calibration | Apparent gain may arise from data density rather than graph logic |
Translational deployment interface | Risk outputs plus trajectory type | Converts model outputs into actionable care pathways | Supports referral, tapering review, and closer monitoring | Clinical decision support recommendation tier | Usability and decision relevance | Misinterpretation of probabilistic outputs in practice |
A fundamental limitation is the distinction between correlation and causation: two patients may become strongly connected because they share the same discharging surgeon who prescribes high-dose opioids routinely, rather than because their underlying pathophysiology or pain trajectories are meaningfully similar [13, 14]. Temporal edge updates risk capturing practice patterns and healthcare system artifacts rather than patient-specific biological or psychological states, potentially limiting generalizability across institutions with different prescribing cultures. Validation across multiple surgical types and healthcare systems is necessary before clinical deployment, as the relationship between opioid trajectories and CPSP may differ substantially for breast cancer surgery versus total joint arthroplasty versus trauma surgery [1, 16].
This paper has presented a conceptual framework for predicting chronic postsurgical pain trajectories using a graph neural network with temporal edge updates applied to preoperative psychological assessments and postoperative opioid prescription histories. The framework models patients as nodes in a dynamic graph where edge weights are recalculated at weekly intervals based on evolving similarity of opioid use patterns and pain scores, enabling relational reasoning that captures how patients transition between risk groups over time.
The key advantages of this framework over conventional predictive approaches are threefold. First, it explicitly models the clinical observation that patient similarity changes after surgery—two individuals with identical preoperative risk profiles may diverge or converge based on their postoperative management trajectories. Second, it leverages relational information from temporally similar peers to improve individual patient predictions, effectively sharing statistical strength across patients who are following comparable courses. Third, its trajectory clustering outputs provide interpretable clinical categories (resolving pain, chronic low, chronic high, intermittent) that align with how clinicians conceptualize postoperative recovery patterns.
Several limitations must be addressed before clinical implementation. The framework requires longitudinal EHR data that may be incomplete or inconsistently collected across different healthcare settings, and missing pain scores particularly pose challenges for edge update validity. Furthermore, temporal edge updates risk capturing provider-level prescribing patterns rather than patient-level pathophysiology, necessitating rigorous validation across diverse surgical populations and healthcare systems to establish generalizability.
Future work should focus on implementing this framework on large surgical cohorts such as the National Surgical Quality Improvement Program (NSQIP), Optum, or TriNetX databases, which contain the requisite combination of preoperative psychological measures, longitudinal opioid prescription records, and serial pain assessments. Prospective validation studies following the A2CPS consortium model [22, 23] would be particularly valuable for establishing whether dynamic GNN predictions translate into actionable early interventions—such as targeted pain psychology referral or structured opioid tapering protocols—for patients identified as transitioning toward chronic high-intensity pain trajectories.
None
None
None
None
Open Access This article is licensed under a Creative Commons Attribution 4.0 International License, which permits use, sharing, adaptation, 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 changes were made. 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/4.0/.