Implantable peripheral nerve electrical stimulation pain relief device based on ecap feedback and control method thereof

By using an implantable peripheral nerve electrical stimulation device based on ECAP feedback, and utilizing nerve signal acquisition-feedback electrodes and a closed-loop control system, the limitations of existing technologies in the treatment of neuropathic pain, such as limited efficacy, significant side effects, and high surgical risks, have been addressed, achieving precise analgesia and long-term stable therapeutic effects.

CN122208945APending Publication Date: 2026-06-16XIEHE HOSPITAL ATTACHED TO TONGJI MEDICAL COLLEGE HUAZHONG SCI & TECH UNIV

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
XIEHE HOSPITAL ATTACHED TO TONGJI MEDICAL COLLEGE HUAZHONG SCI & TECH UNIV
Filing Date
2026-03-16
Publication Date
2026-06-16

AI Technical Summary

Technical Problem

Existing treatments for neuropathic pain, such as medication and spinal cord stimulation (SCS), have limited efficacy, significant side effects, high surgical risks, and poor electrode stability, making them difficult to meet the long-term needs of patients with intractable pain.

Method used

An implantable peripheral nerve electrical stimulation device based on ECAP feedback is adopted. ECAP signals are acquired through nerve signal acquisition-feedback electrodes. A closed-loop control system is constructed using convolutional neural networks and Transformer modules to identify pain status in real time and adaptively adjust stimulation parameters. Combined with a wireless charging module, a fully implantable design is achieved, avoiding electrode displacement and infection risks.

Benefits of technology

It achieves precise activation of pain nerves, reduces surgical trauma and complications, provides stable and long-lasting analgesia, and improves patient compliance and quality of life.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122208945A_ABST
    Figure CN122208945A_ABST
Patent Text Reader

Abstract

The application discloses an implantable peripheral nerve electric stimulation analgesia device based on ECAP feedback and a control method thereof. The device comprises a shell implanted under the skin, a control module, an output module and a battery module arranged in the shell; a nerve signal acquisition-feedback electrode comprising an acquisition electrode and a stimulation electrode is wrapped and fixed on the surface of the peripheral nerve adventitia without penetrating the bundle membrane; the control module comprises a contrast learning module and a CNN-Transformer module; the contrast learning module comprises an encoding network; in the training stage, the ECAP signal is labeled as pain and health samples and the encoding network is trained, so that the two types of states form distinguishable reference representations in the latent space; in the running stage, the real-time ECAP signal is mapped to the latent space, and the similarity with the reference representation is judged to be abnormal; when the abnormality is judged, the CNN-Transformer module is triggered to output a stimulation strategy control signal, and the electric stimulation pulse is adjusted through the output module. The application is accurate in treating peripheral neuralgia, has small trauma and stable analgesia.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the fields of medical devices and neuromodulation technology, and in particular to an implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback and its control method. Background Technology

[0002] The conventional treatment for neuropathic pain (NP) remains primarily medication-based, with commonly used agents including antidepressants, anticonvulsants, topical lidocaine preparations, and opioids. Pregabalin, gabapentin, amitriptyline, and 5% lidocaine patches are recommended as first-line treatments and can relieve pain in some patients. When first-line treatments are insufficient or cannot be tolerated by patients, tramadol and other opioids are considered second-line options. However, large-scale studies have shown that these drugs generally provide limited relief in only about 40%–60% of patients, and long-term use is often accompanied by drowsiness, dizziness, gastrointestinal reactions, and even the risk of addiction, leaving patients physically and mentally exhausted by the dual burden of drug side effects and intractable pain. The limitations of drug efficacy have prompted clinicians to continuously seek minimally invasive interventions and neuromodulation techniques as supplementary methods.

[0003] Following the introduction of the pain "gating" theory in 1967, spinal cord stimulation (SCS) was introduced into clinical practice and gradually became an important alternative to the treatment of refractory pain (NP). The basic idea of ​​SCS is to place electrodes in the epidural space corresponding to the spinal cord segment of the affected skin. Low-frequency pulses of 40–70 Hz are used to activate the low-threshold Aβ fibers of the posterior columns of the spinal cord, inhibiting pain signals through ascending and descending electrical activity, thereby achieving analgesia. Over the decades, with improvements in electrode materials, optimization of stimulation parameters, and the emergence of closed-loop feedback technology, the overall safety and comfort of SCS have continuously improved, and it has gained affirmation from numerous randomized controlled trials and real-world studies.

[0004] However, the limitations of SCS are also obvious. First, it relies on a wide-area electric field generated by the spinal cord's dorsal column for analgesia, making it difficult to focus on a single nerve segment. Nerve fibers in non-target areas are often stimulated synchronously, leading to discomfort such as numbness and foreign body sensation in non-lesion areas. Its effectiveness for axial midline back pain is only 30%–50%, and for pain spanning multiple segments, an increased number of electrodes is required to cover all lesions, significantly increasing surgical complexity. Second, the electric field focus is greatly affected by cerebrospinal fluid levels; changes in patient position can cause stimulation drift, requiring approximately 40% of patients to readjust stimulation parameters daily to maintain efficacy. Third, electrode implantation requires laminectomy or percutaneous puncture into the epidural space, with a postoperative risk of epidural hematoma of approximately 1%–2% and infection of 3%–5%. Once complications occur, secondary surgery is often required, prolonging hospital stays and significantly increasing costs. Even more challenging is that traditional linear electrodes have a displacement rate of over 20% within one year post-surgery, especially in the highly mobile C5–C7 region of the neck. Once the electrode shifts, the analgesic area and the pain area become misaligned, drastically reducing the therapeutic effect. Furthermore, the success rate of repositioning under X-ray fluoroscopy is less than 60%, placing a continuous burden on patients and the medical team.

[0005] In summary, drug therapy for NP (numerical pain) fails to meet clinical needs due to limited efficacy and significant side effects. While SCS (subtraction analgesia) offers a new analgesic pathway, it is limited by issues such as targeting accuracy, surgical risks, and electrode stability, making it difficult to achieve long-term effectiveness in many patients with intractable pain. This reality urgently requires the development of more efficient, safe, convenient, and economical neuromodulation technologies to provide new solutions for intractable neuropathic pain. Summary of the Invention

[0006] The purpose of this invention is to address the shortcomings of the aforementioned background technology and provide an implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback and its control method.

[0007] In a first aspect, the present invention provides an implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback, comprising: A housing for implantation between human subcutaneous tissue and muscle fascia layer. The housing contains a control module, an output module and a battery module. The battery module is electrically connected to the control module and the output module respectively for power supply. The neural signal acquisition-feedback electrode is electrically connected to the control module and the output module inside the housing via loop wires. The neural signal acquisition-feedback electrode includes an acquisition electrode and a stimulation electrode. It is wrapped around and fixed to the surface of the epineurium of the target peripheral nerve without penetrating the perineum, and is used to contact the target peripheral nerve. The acquisition electrodes are used to acquire evoked compound action potential (ECAP) signals from the target peripheral nerve. The control module includes a contrastive learning module and a CNN-Transformer module. The contrastive learning module contains an encoding network. During the training phase, based on the patient's pain feedback, the ECAP signals are labeled as pain samples and healthy samples. The encoding network is trained through contrastive learning to form distinguishable reference representations of pain and healthy states in the latent space. During the operation phase, the real-time ECAP signals are mapped to the latent space via the encoding network. The similarity between the mapping result and the reference representation is used to determine whether it is an abnormal state. When an abnormal state is determined, the CNN-Transformer module is triggered to output a stimulation strategy control signal, and the output module adjusts the electrical stimulation pulses released by the stimulation electrodes to the peripheral nerve.

[0008] The neural signal acquisition-feedback electrode includes a flexible electrode wire, which contains an acquisition electrode wire and a stimulation electrode wire. The acquisition electrode wire includes an upstream acquisition electrode wire and a downstream acquisition electrode wire for acquiring signals at different points. An insulating spacer layer is provided between the acquisition electrode wire and the stimulation electrode wire. The flexible electrode wire is wrapped around the surface of the target peripheral nerve at least twice and fixed by knotting or snapping to form a stable closed-loop stimulation path.

[0009] The process of acquiring the evoked compound action potential (ECAP) signal of the target peripheral nerve using the acquisition electrode includes: acquiring the ECAP signal of the target peripheral nerve at a sampling frequency of not less than 4 kHz; amplifying the acquired signal through a front-end amplification circuit; filtering out background noise through a filtering circuit; and converting the amplified and filtered analog signal into a digital signal through an analog-to-digital converter circuit; wherein the acquisition electrode is a hoop-type electrode, which is arranged around the target peripheral nerve.

[0010] The contrastive learning module includes an encoder and a decoder. The encoder sequentially comprises a convolutional layer, a recurrent neural network layer, and a fully connected layer, used to progressively extract local features from the input ECAP signal, capture temporal dependencies, and then map them to a low-dimensional latent space to obtain latent representations. The decoder is used to reconstruct the latent representations into the input signal. During the training phase, a weighted sum of reconstruction loss and contrastive loss is used as the total loss function, where the contrastive loss is calculated based on the representation distance between positive and negative sample pairs, so that pain states and healthy states form distinguishable cluster distributions in the latent space. The training process uses an adaptive moment estimation optimizer to update the model parameters.

[0011] The CNN-Transformer module includes a lightweight CNN module and a Transformer module. The lightweight CNN module sequentially includes: a preprocessing layer, which uses one-dimensional convolution to downsample and extract features from the C-channel input signal, where C is the actual number of channels of the acquisition electrode; a multi-scale convolutional group, which contains multiple parallel one-dimensional depthwise separable convolutional branches, each branch using at least two different convolutional kernel sizes to capture signal features at different time scales, and the multi-branch outputs are fused element-wise and then recalibrated through a channel attention module; and a downsampling layer, which uses one-dimensional max pooling to downsample the fused features in the time dimension. During the training phase, the lightweight CNN module calculates waveform reconstruction loss and peak localization loss using a waveform reconstruction decoding head and a peak detection head, respectively, and combines them with a weighted combination of sparse regularization terms as the training loss. The waveform reconstruction decoding head and the peak detection head only participate in the training process.

[0012] The Transformer module includes: an input processing layer that reshapes the multi-channel one-dimensional features output by the lightweight CNN module into a token sequence and adds positional encoding to preserve temporal information; a Transformer encoder that uses a multi-head self-attention mechanism to capture long-range temporal dependencies in the signal; and an output regression layer that maps the encoder output to current adjustment values ​​through a fully connected layer. The current adjustment values ​​are continuous values ​​representing the increase or decrease in the current of the stimulating electrode. The training loss of the Transformer module includes the mean square error loss of the current adjustment values ​​and the cross-frame consistency loss by applying smoothing constraints to the current adjustment value outputs of adjacent frames.

[0013] The housing also includes a wireless charging module, which is electrically connected to the battery module and is used to wirelessly charge the battery module.

[0014] The housing is provided with a suspension and fixing structure for fixing to human fibrous tissue. The suspension and fixing structure is an elastic hook at each of the four corners of the housing. The elastic hook includes a mounting shell and a hook. A connecting spring is fixedly installed inside the mounting shell. A length rod that is slidably connected to the mounting shell is fixedly installed at one end of the connecting spring. A hook is fixedly installed at one end of the length rod. One side of the mounting shell is fixedly connected to the housing.

[0015] The circuit wire passes through the outer layer of human muscle tissue that naturally exists between the shell and the target peripheral nerve, establishing an electrical and signal connection between the nerve signal acquisition-feedback electrode and the shell.

[0016] Secondly, the present invention provides a control method for an implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback, comprising: acquiring evoked compound action potential (ECAP) signals of the target peripheral nerve; during the training phase, labeling the ECAP signals as pain samples and healthy samples based on patient pain feedback and training the encoding network through comparative learning, so that the pain state and the healthy state form distinguishable reference representations in the latent space; during the operation phase, mapping the real-time ECAP signals to the latent space through the encoding network, and determining whether it is an abnormal state based on the similarity between the mapping result and the reference representation; when it is determined to be an abnormal state, triggering the output stimulation strategy control signal and adjusting the electrical stimulation pulses released by the stimulation electrodes to the peripheral nerve.

[0017] Peripheral nerve stimulation (PNS) has the following advantages over spinal cord stimulation (SCS): ① PNS can be implanted in the distal part of the limb according to the pain nerve innervation area, with less impact on overall body activity and greatly improving the patient's quality of life; ② PNS is more convenient to care for because it is implanted in the periphery, so it can be implanted for a longer period of time. Currently, the longest PNS device approved by the FDA in clinical use abroad can be implanted for 60 days. The longer the treatment time, the better the long-term effect; ③ PNS operation does not involve surgery in the spinal canal, which reduces the risk. The peripheral nerve is located superficially, and the electrode implantation is simple to operate, easy to fix and not easy to displace. In addition, it is less expensive than SCS.

[0018] Current clinical data show that even with semi-implantable peripheral nerve stimulation (SNS) products with a treatment cycle of up to 60 days, only 74% of patients experienced 50% pain relief, and 27% of patients still experienced significant pain after device removal. This is attributed to insufficient treatment duration. This invention employs a fully implantable technique, significantly reducing the risk of infection. Combined with external percutaneous wireless inductive charging technology, it promises to achieve permanent treatment, providing a cure for patients with intractable pain. Furthermore, this invention directly wraps the nerve signal acquisition-feedback electrode around a single peripheral nerve trunk, achieving a 360° uniform electric field without affecting surrounding tissues. The ECAP-CNN-Transformer closed-loop algorithm is used to fine-tune stimulation parameters in real time, ensuring the effective activation volume remains locked on the target nerve fiber bundle. This not only precisely addresses peripheral neuralgia but also allows for the creation of independent cuffs for multiple segments and branches of peripheral nerves, achieving precise "bundle-by-bundle" coverage, significantly improving targeting and eliminating blind spots that are difficult to pinpoint with SNS. The implantation layer is located only subcutaneously between the skin and muscle fascia, without entering the epidural space. This minimizes surgical trauma and shortens operation time, reducing high-risk complications such as cerebrospinal fluid leakage and spinal canal infection. An integrated wireless charging module and long-life battery allow for percutaneous inductive charging, avoiding the need for secondary surgery due to battery depletion and significantly reducing the overall surgical and maintenance burden. The neural signal acquisition-feedback electrode uses a flexible biocompatible material to form a slight adhesion with the target nerve, and a suspension fixation structure buffers traction stress. Its encircling geometry and wire tension relief design ensure that the electrode moves synchronously with limb movement without slippage, fundamentally reducing the probability of displacement, breakage, and failure. Combined with closed-loop ECAP monitoring, the system can also detect stimulus mismatch in extreme situations and issue an alarm, further ensuring the stability of long-term analgesic effects.

[0019] The beneficial effects of this invention are as follows: 1. This invention constructs a closed-loop control mechanism based on evoked compound action potential (ECAP) signals, which can identify abnormal changes in the patient's state in real time and adaptively adjust stimulation parameters. Compared with traditional fixed-output open stimulation systems, ECAP feedback closed-loop control can automatically adjust the stimulation intensity, making the stimulation intensity precisely match the patient's needs. This overcomes the problem of efficacy fluctuation caused by constant stimulation output in existing technologies, thereby providing a more stable and lasting analgesic effect.

[0020] 2. This invention introduces a convolutional neural network model, improving the intelligence level of stimulation strategy formulation. The control system extracts features and recognizes patterns from the acquired signals through machine learning, automatically identifies pain states using a contrastive learning module, and adaptively outputs stimulation strategies through a CNN-Transformer module. This allows for the generation of personalized optimal stimulation parameters based on the neural feedback of different patients, providing a more scientific and efficient control method for closed-loop electrical stimulation therapy for pain.

[0021] 3. This invention employs a nerve signal acquisition-feedback electrode to stably encapsulate the electrode on the target peripheral nerve, ensuring the spatial positioning stability of electrical signal acquisition and stimulation. The nerve signal acquisition-feedback electrode surrounds the nerve periphery without penetrating nerve tissue, avoiding damage to the epineurium and perineurium. Furthermore, it isolates electromyographic interference through insulating encapsulation, ensuring signal quality. The outer layer of the electrode is encapsulated with a highly biocompatible material (such as hydrogel), improving the safety of long-term implantation and reducing tissue stimulation and rejection reactions.

[0022] 4. The system of this invention is a fully implantable, integrated structure with no externally exposed stimulators, effectively reducing the risk of electrode displacement and interference from external devices on therapeutic efficacy. Compared to semi-implantable peripheral nerve stimulation systems that require externally worn devices, the fully implantable design of this invention eliminates the burden of daily carrying and maintenance of external devices for patients, significantly improving patient compliance and quality of life. Patients can receive treatment continuously for a long period without affecting their daily activities, avoiding recurrent pain caused by electrode removal or device displacement.

[0023] 5. This invention integrates a wireless charging module, supporting external energy transfer to charge the implanted device. Compared to traditional systems that require periodic surgical battery replacement or percutaneous wired charging, this invention achieves power sustainability through wireless charging, ensuring the long-term continuous operation of the device. Patients only need to charge the device periodically using a non-invasive method, reducing maintenance difficulty and infection risk, and significantly improving the convenience of long-term use.

[0024] 6. The system of this invention can monitor the nerve signals related to the patient's pain in real time and adjust the intensity of stimulation accordingly, responding promptly to fluctuations in pain levels. This closed-loop real-time feedback control allows the stimulation output to automatically increase or decrease as the pain intensifies or subsides, avoiding the shortcomings of traditional devices that require manual, delayed adjustments. This ensures a continuous and stable analgesic effect, achieving precise management and immediate relief of pain. Attached Figure Description

[0025] The present invention will be further described with reference to the accompanying drawings, but the embodiments in the drawings do not constitute any limitation on the present invention. For those skilled in the art, other drawings can be obtained based on the following drawings without creative effort.

[0026] Figure 1 This is a schematic diagram illustrating the connection principle of an implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback provided by the present invention.

[0027] Figure 2 This is a schematic diagram of the external structure of the shell of an implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback provided by the present invention. Figure 3This is a schematic diagram of the internal structure of an implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback provided by the present invention. Figure 4 This is a schematic diagram of the suspension and fixation structure of an implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback provided by the present invention. Figure 5 This is a schematic diagram of the nerve signal acquisition-feedback electrode structure of an implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback provided by the present invention.

[0028] Among them, 100-shell; 101-suspension fixing structure (111-mounting shell; 112-connecting spring; 113-length rod; 114-hook); 200-control module; 300-output module; 400-battery module; 500-wireless charging module; 600-loop wire; 700-nerve signal acquisition-feedback electrode (701-acquisition electrode; 701-1-upstream acquisition electrode line; 701-2-downstream acquisition electrode line; 702-stimulation electrode; 703-insulating spacer layer); 800-target peripheral nerve. Detailed Implementation

[0029] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0030] Please see Figures 1-3 As shown, this embodiment provides an implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback, comprising: The housing 100 is used for implantation between the subcutaneous tissue and the muscle fascia layer of the human body. The housing 100 is equipped with a control module 200, an output module 300 and a battery module 400. The battery module 400 is electrically connected to the control module 200 and the output module 300 respectively for power supply. The neural signal acquisition-feedback electrode 700, preferably a Cuff electrode in this embodiment, is electrically connected to the control module and output module inside the housing via a loop wire 600. The neural signal acquisition-feedback electrode 700 includes an acquisition electrode 701 and a stimulation electrode 702. It is wrapped around and fixed to the surface of the epineurium of the target peripheral nerve 800 without penetrating the perineum, and is used to contact the target peripheral nerve. The acquisition electrode 701 is used to acquire the evoked compound action potential (ECAP) signal of the target peripheral nerve; the control module 200 includes a contrastive learning module and a CNN-Transformer module; the contrastive learning module includes an encoder network (in this embodiment, the encoder network is specifically implemented by an encoder consisting of a convolutional layer, a GRU recurrent neural network layer, and a fully connected layer connected in sequence; the convolutional layer extracts the local waveform features of the ECAP signal, the GRU layer captures the temporal dependence in the time series, and the fully connected layer maps the GRU output to a low-dimensional latent space to obtain the latent representation); it also includes a decoder for reconstructing the latent representation into an input signal to assist training. During the training phase, ECAP signals are labeled as pain samples and healthy samples based on patient pain feedback. The encoding network is trained through contrastive learning (specifically, the weighted sum of reconstruction loss and contrastive loss is used as the total loss function during training, where the contrastive loss is calculated based on the representation distance between positive and negative sample pairs, so that samples of the same category cluster in the latent space and samples of different categories are far apart; the reconstruction loss ensures that the latent representation extracted by the encoding network retains the core waveform information of the original ECAP signal; the training process uses an adaptive moment estimation optimizer to update the model parameters), so that pain state and healthy state form distinguishable reference representations in the latent space. In this embodiment, the reference representation specifically refers to the cluster center vectors of each category of samples in the latent space after being mapped by the encoding network, i.e., the reference prototype vectors for the pain category and the health category; training data is always collected by the same set of acquisition electrodes after implantation, with channel configuration and preprocessing parameters completely consistent with deployment and operation, ensuring that the number of input channels is strictly the same during the training and operation phases; after training, the encoding network weights and the aforementioned reference representation are permanently stored in the non-volatile memory of the control module; during the operation phase, the real-time ECAP signal is mapped to the latent space through the encoding network, and the similarity between the mapping result and the reference representation (in this embodiment) is used to determine the optimal data acquisition method. In this example, cosine similarity is used to determine whether an abnormal state is detected. Specifically, when the cosine similarity between the real-time representation and the pain category reference representation exceeds a preset threshold θ and this condition is met for N consecutive frames (N≥3), an abnormal state is detected. The threshold θ is determined to be the optimal operating point through ROC curve analysis on the validation set during the training phase, with a typical value range of 0.5~0.8. The multi-frame confirmation mechanism can effectively avoid false triggering caused by occasional noise. When an abnormal state is detected, the CNN-Transformer module is triggered to output a stimulation strategy control signal, and the output module adjusts the electrical stimulation pulses released by the stimulation electrodes to the peripheral nerves.

[0031] For the above technical solutions, please refer to Figure 5As shown, the neural signal acquisition-feedback electrode 700 includes a flexible electrode wire, within which are acquisition electrode wires and stimulation electrode wires serving as acquisition electrode 701 and stimulation electrode 702. The acquisition electrode wire includes an upstream acquisition electrode wire 701-1 and a downstream acquisition electrode wire 701-2 for acquiring signals from different points. Several microelectrode contacts are spaced apart along the length of the wire on both the upstream and downstream acquisition electrode wires. Each contact is led out through an independent wire to form an independent acquisition channel. Thus, the upstream and downstream acquisition electrode wires together constitute C acquisition channels (in this embodiment, C=16, i.e., 8 microelectrode contacts are arranged upstream and downstream), achieving multi-channel parallel acquisition to improve signal spatial resolution. An insulating spacer layer 703 is provided between the acquisition electrode wire and the stimulation electrode wire. The flexible electrode wire is wound around the surface of the target peripheral nerve 800 at least twice and fixed by knotting or snapping, forming a stable closed-loop stimulation path.

[0032] In the above technical solution, the process of acquiring the evoked compound action potential (ECAP) signal of the target peripheral nerve using the acquisition electrode includes: acquiring the ECAP signal of the target peripheral nerve at a sampling frequency of not less than 4 kHz; amplifying the acquired signal through a front-end amplification circuit; filtering out background noise through a filtering circuit; and converting the amplified and filtered analog signal into a digital signal through an analog-to-digital converter circuit. The acquisition electrode is a hoop-type electrode that is arranged around the target peripheral nerve.

[0033] The following are the similarities between the characteristics of the training and deployment data and the data preprocessing process: Signal source: C-channel ECAP signal (C is consistent with the actual number of channels on the implanted electrode; in this embodiment, C=16), sampling rate 8kHz (meeting the time resolution of 100-500μs pulse width for the N1 peak), each HDF5 file stores 300 seconds of continuous raw data (2,400,000 sampling points / channel). Metadata includes stimulation parameters: amplitude 0.1-10mA (0.1mA step), pulse width 200-500μs (10μs step), frequency 20-100Hz (1Hz step). It is important to note that the training data for this system is always acquired using the same set of implanted electrodes, with the same channel configuration and preprocessing parameters as during deployment and operation. This ensures that the number of input channels for the model is strictly the same during the training and runtime phases, eliminating any channel mismatch issues.

[0034] The signal chain is configured with a high-pass filter (0.1Hz cutoff) to eliminate baseline drift and a low-pass filter (3kHz cutoff) to suppress high-frequency noise. The input impedance is >1GΩ. Stimulus trigger timestamps are recorded synchronously with an accuracy of ±1μs.

[0035] Data preprocessing workflow Baseline drift reduction: Apply medium-range filtering (800 points / 100ms window) or second-order polynomial fitting per channel (computationally efficient 6.4 times higher than double exponential). Polynomial coefficients are fitted using least squares, with residuals <0.5% of signal amplitude.

[0036] Stimulus artifact elimination: After setting the stimulus to zero using the hard threshold method, a 2ms window (16 sampling points) is used; under alternating stimulation mode, abnormal trials other than ±3σ need to be excluded when calculating the median of the artifact template to ensure template stability.

[0037] Normalization: Linear normalization is performed channel by channel to [-1, 1], the formula is (x x(min)) / (x(max) x(min)×2 1. Preserve the relative amplitude relationship.

[0038] Data optimization Framing strategy: Sliding window of 256 points / frame (32ms), step size of 64 points (8ms, 75% overlap), generating a C×256 two-dimensional tensor (C=16 in this embodiment). 300 seconds of data can be divided into 37,497 frames / channel.

[0039] Time warp: random stretching / compression ±10%, cubic spline interpolation resampling to the original length (interpolation error <0.1%).

[0040] Additive noise: Gaussian white noise, SNR=20dB (noise standard deviation = signal standard deviation / 10).

[0041] Channel discard: Randomly block about 10% of channels (in this embodiment, C=16, block 1-2 channels) to simulate poor electrode contact.

[0042] Input data for training the model The training input format for the contrastive learning module is as follows: The preprocessed and optimized data above comes from C channels (C=16 in this embodiment), with a sampling rate of 8kHz, which can meet the time resolution of 100-500μs pulse width. Each HDF5 file stores 300 seconds of raw data, and each channel signal has 2,400,000 sampling points. The input ECAP signal is processed into a three-dimensional tensor with a shape of (batch_size, num_channels, seq_length), as described below: batch_size: The number of samples per batch, usually set to 64, for parallel computation of the model (Note: 64 here is the training batch size, unrelated to the number of signal acquisition channels; the number of signal acquisition channels C=16, determined by the number of physical contacts of the implanted electrodes). During training, the batch size affects the stability of gradient calculation and the convergence speed of model training.

[0043] num_channels: The number of channels for the ECAP signal, equal to the actual number of channels C of the acquisition electrodes (C=16 in this embodiment). The ECAP signal comes from C different electrode contact channels, and each channel records a time series.

[0044] seq_length: The length of each frame of the signal, assumed to be 256 time steps (32ms signal). Each time step represents the amplitude of the signal at that moment.

[0045] Therefore, the shape of the input data is (batch_size, C, 256), which is (64, 16, 256). The first dimension, 64, represents the training batch size (not the number of signal channels). The second dimension, 16, represents the number of signal acquisition channels, C (equal to the actual number of channels implanted in the electrodes, consistent between training and runtime). The third dimension, 256, represents the number of time steps per frame. The training input format of the CNN-Transformer module differs from that of the contrastive learning module. It uses a sequential batch organization method, organizing consecutive frames into a frame sequence in chronological order before batch input. For details on the specific format, please refer to the description of the CNN-Transformer module training section later.

[0046] The contrastive learning module includes: encoder Convolutional layers: Convolutional layers extract local features through convolution operations. Assume the output of the convolution operation is... The calculation formula is as follows: ; in It is the input signal; It is a convolution kernel; It is a bias term; Indicates the convolution operation; GRU layer: Uses GRU to capture timing dependencies, assuming the input is... The output is , ; The formula for the GRU layer is as follows: ; ; ; ; in To update the door; To reset the door; This represents the current output state. This is the candidate hidden state; Fully connected layer: Maps the output of the GRU to a low-dimensional latent space, assuming the output is... ,but: ; in This is the weight matrix; For bias terms; Contrast loss function: Assume the encoder output is Positive samples and For negative samples, the comparison loss is used. The calculation formula is: ; in yes and The inner product of positive and negative samples represents the similarity between them. It is a temperature coefficient used to scale the result of the inner product, controlling the difficulty of contrastive learning; It represents the number of negative samples, typically all samples in a batch; decoder Decoder layer: The decoder takes the latent representation from the encoder and reconstructs the input signal, assuming the latent representation is... The reconstructed signal is ,but: ; in and These are the weights and biases in the decoder; Loss function: Reconstruction loss measures the decoder output. With the original input signal The difference between them is expressed using mean squared error (MSE): ; Where B is the batch size; C is the number of channels; and T is the time step per channel. and These are the values ​​of the original signal and the reconstructed signal at the b-th sample, c-th channel, and t-th time step, respectively. Total loss The total loss is the weighted sum of the reconstruction loss and the contrast loss: ; in It is a hyperparameter that adjusts the weights of contrast loss and reconstruction loss; Training details Optimizer: The Adam optimizer is used to update the model's parameters. Adam's update rules are as follows: ; ; ; ; Where η is the learning rate; β1 and β2 are the exponential decay rates of momentum. and These are the first-order moment estimate and the second-order moment estimate of the gradient, respectively. It is the gradient of the loss function with respect to the parameters; Training process Batch size: 64 per batch; Positive and negative sample generation: Select positive and negative samples from the dataset based on VAS scores; Training rounds: The maximum number of training rounds is set to 100 rounds. An early stopping strategy is adopted, that is, after each round of training, the model performance is evaluated on the validation set (using the weighted sum of reconstruction loss and contrastive loss as the evaluation metric). Training is stopped when the validation set loss does not decrease for 10 consecutive rounds, and the model weights with the lowest validation set loss are backtracked and selected as the final model to prevent overfitting.

[0047] Parameter settings in the specific implementation logic: Input layer Input data: The shape of each signal is as follows That is, the batch size B is 64, the number of channels C is 16 (consistent with the number of channels of the acquisition electrode), and the time step T is 256.

[0048] Input layer: This layer has no learning parameters; it simply receives the raw input signal data.

[0049] Convolutional layer (Conv1D) Number of convolution kernels: 64; Kernel size: 3; Step size: 1; Input shape: ; Output shape: (B, F, T) (Due to the use of "same" padding, the output time steps are the same as the input; where F=64 is the number of convolution kernels). Convolutional layer parameters: weight matrix The shape is (3, C, 64), where 3 is the size of the convolution kernel, C is the number of input channels (C=16 in this embodiment), and 64 is the number of convolution kernels.

[0050] Bias term The shape is (64).

[0051] GRU layer Input shape: (B, F, T), after passing through a convolutional layer (F=64).

[0052] Output shape: The output of GRU contains 128 features (i.e., output dimensions).

[0053] GRU layer parameters: Weight matrix: The shape is Input and the hidden state of the previous time step.

[0054] The shape is .

[0055] The shape is .

[0056] Bias term: , , The shape is .

[0057] Fully connected layer (Dense) Input shape: , from the GRU layer.

[0058] Shape: The latent space is represented by features with a feature dimension of 64.

[0059] Fully connected layer parameters: weight matrix The shape is This represents the conversion from 128 dimensions to 64 dimensions.

[0060] Bias term The shape is (64).

[0061] Contrastive Learning Module The contrastive learning module directly uses the output from the fully connected layers to compute the similarity between positive and negative samples. It does not introduce new parameters; instead, it computes the latent representations from the encoder. And perform similarity calculation.

[0062] Decoder Input shape: The output comes from the fully connected layer.

[0063] Output shape: The reconstructed signal has the same output shape as the input signal.

[0064] Decoder parameters: weight matrix The shape is (64, C×T), which means that the potential space is mapped from a 64-dimensional space to an output space of C×T = 16×256 = 4,096 (in this embodiment, C=16, T=256).

[0065] Bias term The shape is (C×T) = 4,096.

[0066] Total parameter calculation Convolutional layer parameters: convolution kernel 3×C×64 = 3×16×64 = 3,072 parameters.

[0067] Bias term : 64 parameters.

[0068] Total convolutional layer parameters: 3,072 + 64 = 3,136 parameters.

[0069] GRU layer parameters: Weight matrix: One parameter.

[0070] One parameter.

[0071] One parameter.

[0072] Bias term: , , The input bias and hidden bias of each gate are combined into a single bias vector (dimension 128), and there are a total of 128×3=384 bias parameters for the three gates.

[0073] Total GRU layer parameters: 24576×3+384=73728+384=74112 parameters.

[0074] Fully connected layer parameters: weight matrix 128 × 64 = 8192 parameters.

[0075] Bias term : 64 parameters.

[0076] Total number of fully connected layer parameters: 8192 + 64 = 8256 parameters.

[0077] Decoder parameters: weight matrix 64×(C×T)=64×4096=262,144 parameters (in this embodiment, C=16, T=256).

[0078] Bias term C×T = 4096 parameters.

[0079] Total decoder parameters: 262,144 + 4,096 = 266,240 parameters.

[0080] Total number of parameters Adding up the parameters of all the layers above, we get the total number of network parameters: Total Parameters = 3,136 + 74,112 + 8,256 + 266,240 = 351,744.

[0081] Summarize Convolutional layer: There are a total of 3,136 parameters (kernel_size×C×filters+bias = 3×16×64+64).

[0082] GRU layer: There are a total of 74,112 parameters.

[0083] Fully connected layer: There are a total of 8256 parameters.

[0084] Decoder: There are a total of 266,240 parameters.

[0085] After the encoder and decoder have been jointly trained using reconstruction loss and contrastive loss (Phase 1), the encoder is capable of mapping pain signals and health signals to discriminative clusters in the latent space. To further improve the discrimination accuracy and simplify the inference process during the runtime phase, in Phase 2, a classification head is added to the latent representation E3 obtained from the contrastive learning module, enabling the model to directly output classification results (i.e., distinguishing between pain signals and health signals). This classification head will learn how to determine which category a sample belongs to based on the latent representation.

[0086] Category header design Input: latent representation Its shape is (B, 64).

[0087] Classification layer: Add a fully connected layer to map the latent representations to the category space. Assuming the output has two categories (pain, health), the output dimension is 2.

[0088] ; in The shape is (64,2), which means that the 64-dimensional latent representation is mapped to 2 categories.

[0089] Bias term The shape is (2), which is the bias term of the two categories.

[0090] Activation function: The softmax activation function is used to transform the output into a probability distribution for each class.

[0091] ; This will generate an output of shape (B,2), representing the probability that each sample belongs to the "pain" category and the "health" category.

[0092] Cross-Entropy Loss To optimize the classification head, we use cross-entropy loss, a common loss function for classification tasks, which measures the difference between the predicted probability distribution and the true label.

[0093] ; is the true label of the b-th sample, and c represents the category (0 for healthy, 1 for pain).

[0094] It is the probability predicted by the model that the class belongs to category c.

[0095] Phase 2 loss function In Phase 2, the encoder weights are frozen (or fine-tuned with a smaller learning rate), and only the classifier head parameters are optimized. The loss function for Phase 2 is the classification loss: L stage2 = L classification ; where L classification The aforementioned cross-entropy loss. If the encoder is fine-tuned simultaneously in stage two, the total loss function is: L stage2 = L reconstruction + λ2·L classification Where λ2 is a hyperparameter that adjusts the weights of reconstruction loss and classification loss; in this embodiment, λ2 = 0.5.

[0096] Training process Positive and negative sample generation: Positive and negative samples are generated based on the patient's VAS score. Scores of 3 or higher are labeled as "pain," and scores below 3 are labeled as "healthy." The training of the contrastive learning module consists of two phases: Phase 1 (Representation Learning): By minimizing L... total = L reconstruction + λ1·L contrastiveThe encoder and decoder are trained jointly, where λ1 is a hyperparameter that adjusts the contrastive loss weights. In this embodiment, λ1=1.0, so that pain and health states form distinguishable clusters in the latent space. The maximum number of training epochs is set to 100 epochs. An early stopping strategy is adopted: training stops when the validation set loss does not decrease for 10 consecutive epochs, and the model weights with the lowest validation set loss are selected. Phase 2 (Classification Fine-tuning): The encoder weights are fixed, and a classification head is added to the latent representation E3. The classification head is minimized by adjusting L... classification The training classifier head parameters are set to a maximum of 50 training rounds. The early stopping strategy is also adopted. Training is stopped when the classification accuracy on the validation set does not improve for 10 consecutive rounds. The model weight with the highest accuracy on the validation set is selected. After the training in the second stage is completed, the running stage directly outputs the pain / health category judgment through the classifier head.

[0097] Classified output and operational phase integration After two phases of training, the model directly outputs the classification result through the classification head based on the latent representation E3. Using the softmax activation function, the probability distribution of the output categories is determined: Category 0: Health signal; Category 1: Pain signal. For a new sample, the model outputs the probability of the sample belonging to each category, ultimately selecting the category with the highest probability as the prediction result. During the runtime phase, when the probability of the classification head outputting the "pain" category exceeds a preset threshold θ (combined with the aforementioned multi-frame confirmation mechanism, N consecutive frames are judged as a pain state), it is determined to be an abnormal state, triggering the CNN-Transformer module to output the stimulus policy control signal. During deployment, the decoder does not participate in inference, only retaining the weights of the encoder and classification head. That is, the abnormal state judgment during the runtime phase is achieved by directly outputting the category probability through the classification head, replacing the aforementioned principle description based on comparing cosine similarity with the reference representation; the classification head has learned the optimal decision boundary between pain and health states in the latent space during the second phase of training, essentially equivalent to optimizing the cosine similarity threshold judgment.

[0098] The CNN-Transformer module includes a lightweight CNN module and a Transformer module, wherein the lightweight CNN module includes... Network structure: Input: ECAP signal frames at 256 time points across C channels, where C is the actual number of channels on the acquisition electrode; ① Preprocessing layer: 1D convolution (kernel=7, stride=2, padding=3, input channel C, output channel 16) + BN + ReLU6, number of parameters = 7×C×16; ② Multi-scale convolutional groups, parallel structure: Branch 1: Deep convolutional layer (DWConv1d, kernel_size=3, 16 channels, groups=16, number of parameters=3×16=48) + pointwise convolutional layer (1×1Conv, 16→32→16 channels, equivalent number of parameters=16×32=512), branch parameter count=48+512=560; Branch 2: Deep convolutional layer (DWConv1d, kernel_size=3, 16 channels, groups=16, number of parameters=3×16=48) + pointwise convolutional layer (1×1Conv, 16→32→16 channels, equivalent number of parameters=32×16=512), branch parameter count=48+512=560; Branch 3: Deep convolutional layer (DWConv1d, kernel_size=5, 16 channels, groups=16, number of parameters=5×16=80) + pointwise convolutional layer (1×1Conv, 16→32→16 channels, equivalent number of parameters=32×16=512), branch parameter count=80+512=592; The three-branch outputs are fused into 16 channels through element-wise addition, and then passed through the SE attention module (squeeze 16→4, excitation 4→16), with a parameter count of 16×4+4×16=128. ③ Downsampling layer: MaxPool1d(kernel_size=3, stride=2), outputting a one-dimensional feature sequence with 16 channels × T' time steps (T' is determined by the input time step after 1D convolution with stride=2 and max pooling with stride=2, in this embodiment 256→128→63, i.e. T'=63); Total number of parameters: 7C×16+(560+560+592)+128 = 112C+1,840 (In this embodiment, when C=16, the total number of parameters = 1,792+1,840=3,632). Loss function: During the training phase of the lightweight CNN module, in order to guide the CNN to extract high-quality waveform features, two auxiliary training heads are set after the CNN backbone network. These auxiliary heads only participate in loss calculation and gradient backpropagation during training and do not participate in deployment inference. (1) Waveform reconstruction decoding head: The transposed convolution structure is adopted to progressively upsample the feature sequence of the 16-channel × T' time step output by the CNN to restore it to the same dimension as the original input signal (C channels × T time steps), and output the reconstructed signal. The waveform reconstruction loss MSE is calculated by comparing the original input signal y with the original input signal y; this auxiliary task forces the CNN features to retain the core waveform information of the original ECAP signal. (2) Peak detection head: A 1×1 convolution with Sigmoid activation function is used to output a peak probability value between 0 and 1 for each time step of the CNN output feature sequence. The peak localization loss (in the form of Focal Loss) is calculated with the pre-labeled real peak labels (obtained from the N1, P1 and other feature peak positions of ECAP signals in clinical data). This auxiliary task guides the CNN to focus on the physiologically significant peak features in the ECAP signal.

[0099] The two auxiliary training heads mentioned above are jointly optimized with the CNN backbone network during the CNN training phase. After training, only the weights of the CNN backbone network are retained for subsequent joint training and deployment inference with the Transformer.

[0100] The composite loss consists of three parts: ① Waveform reconstruction loss MSE: T=256: Total number of time points; y t: True signal amplitude; : Reconstruct the signal amplitude (i.e., the output of the aforementioned waveform reconstruction decoder); ②Peak positioning loss: ; N: Number of peak values ​​marked; The probability that the model predicts the peak value; =2: Adjusts the weights of easy and difficult samples; Category weights: 0.8 for peak points and 0.2 for off-peak points; ③ Sparse regularization term L1 constraint: ; : Weights of the first layer convolutional kernel; ; Total loss: .

[0101] The Transformer module includes: enter Feature map of 16×T': This feature map is derived from the ECAP signal features extracted earlier using CNN, where: 16: Represents the number of feature channels extracted by CNN; T': Represents the number of time steps per channel after CNN downsampling (T'=63 in this embodiment). Output Current adjustment value: The output is a continuous value representing the increase or decrease of current; Since the current range fluctuates between ±0.3mA in each frame, the model aims to predict this value through a regression task. Transformer model architecture Input processing The input features (16 channels × T' time steps) need to be processed by the Transformer; they are reshaped into a token sequence of length T', with each token having a feature dimension of 16 (i.e., the number of output channels of the CNN), which serves as the input to the Transformer encoder. Location encoding: Since the input data is a time-series feature map, location encoding is used to help the model understand the temporal or spatial order in the data; Transformer uses location encoding to capture the dependencies between different time points; Transformer encoder Multi-head self-attention mechanism: The core of the Transformer encoder is the multi-head self-attention mechanism, which is used to capture the long-range dependencies between T'=63 time steps within a single frame of ECAP signal (intra-frame temporal modeling). The model focuses on different parts of the feature map through the self-attention mechanism, thereby understanding the global and local dependencies within the signal frame. The temporal smoothness between frames is constrained by the cross-frame consistency loss during the training phase (inter-frame temporal constraint), which does not depend on the Transformer's attention mechanism. Input dimension: Features are reshaped into sequences of length T' (T'=63 in this example) with a feature dimension of 16 per token; Number of heads: Four attention heads are used, each with a dimension of 4 (total feature dimension 16 ÷ 4 heads = 4 / head); each head learns different features in the signal; Output layer Regression layer: The output of the Transformer model is mapped to the current adjustment value through a fully connected layer; this regression layer transforms the model's output features into a continuous value representing the magnitude of the current adjustment. Output value: A single floating value, such as +0.2mA or -0.1mA; Total parameters of the Transformer module: The multi-head self-attention layer contains four projection matrices: Q, K, V, and output. Each projection matrix has a shape of (16,16) plus a bias term (16), for a total of 4 groups, with a parameter count of 4 × (16 × 16 + 16) = 1,088. The two normalization layers each contain 16 γ and β parameters, with a parameter count of 2 × (16 + 16) = 64. The feedforward network contains two fully connected layers (16 → 64 → 16), with a parameter count of (16 × 64 + 64) + (64 × 16 + 16) = 2,128. The positional encoding uses fixed sinusoidal encoding and does not contain learning parameters. The output regression layer is a fully connected layer (16 → 1), with a parameter count of 16 + 1 = 17. The total parameters of the Transformer module are 1,088 + 64 + 2,128 + 17 = 3,297.

[0102] The training dataset for the CNN-Transformer module is constructed as follows: During the clinical calibration phase, patients are subjected to electrical stimulation pulses of varying intensities, and each frame of the ECAP signal and its corresponding stimulation current parameters are recorded synchronously. Clinicians determine the optimal current adjustment (the magnitude of increase or decrease, in mA) for the current frame based on the patient's pain feedback (e.g., changes in VAS scores) and the trend of the N1 peak amplitude of the ECAP signal, and use this as the label for the true current adjustment value of that frame. Specifically, during the clinical calibration phase, clinicians make a current adjustment decision at second-level intervals (e.g., every 1-5 seconds) based on the patient's real-time pain feedback and changes in the ECAP signal. The current adjustment amount corresponding to this decision is uniformly assigned to all ECAP signal frames within that time interval as their true current adjustment value labels. For example, when the N1 peak amplitude of the ECAP signal significantly decreases relative to the baseline and the patient reports increased pain, the clinician labels it with a positive current adjustment value (e.g., +0.1 mA); conversely, a negative adjustment value is labeled. This results in a training sample set in the format of (multi-channel ECAP signal frame sequence, real current adjustment value), which is used for supervised regression training of the CNN-Transformer module.

[0103] The CNN-Transformer module employs a sequential batch training strategy. Preprocessed consecutive frames are organized chronologically into fixed-length frame sequences, each containing S consecutive ECAP signal frames (S=16 in this embodiment). During training, each training batch contains 32 such sequences, meaning each batch has a data shape of (32, S, C, 256). For each frame in each sequence, the CNN-Transformer model independently performs forward inference, outputting the corresponding scalar current adjustment value for that frame; thus, each sequence generates S temporally adjacent predicted outputs f1, f2, …, f s .

[0104] loss function Since this is a regression task, the loss function needs to minimize the difference between the predicted current adjustment value and the actual value; the most common loss function is the mean squared error (MSE). (1) Mean Square Error (MSE) The CNN-Transformer model performs forward inference independently on each frame of the ECAP signal, outputting the scalar current adjustment value corresponding to that frame. Assuming a training batch contains 32 sequences, each with S frames, then the batch contains a total of M = 32 × S frames (in this embodiment, M = 32 × 16 = 512), where the model prediction output for the i-th frame is f. i (Scalar, unit mA), the corresponding actual current adjustment value is labeled y. i (Scalar, obtained from the clinical calibration phase). The mean squared error loss is averaged over the M frames of this batch: L current = (1 / M) · Σ(i=1..M) (y i -f i )²; Where M = 32 × S is the total number of frames in the current batch, y i and f i All are scalars. The squared error is calculated independently for each frame, and then the average value within the batch is taken as the MSE loss for that batch.

[0105] (2) Cross-frame consistency loss Cross-frame consistency loss is calculated within each sequence. For a continuous sequence containing S frames, the model processes each frame and produces S temporally adjacent outputs f1, f2, …, f s (Each f is a scalar current adjustment value, in mA), the cross-frame consistency loss is: L cos = (1 / (S-1)) · Σ(t=2..S) (f t -f t-1 )²; Where S is the sequence length (S=16 in this embodiment), f t and f t-1 These are the model prediction outputs (scalars) for frame t and frame (t-1) in the same sequence, respectively. The cross-frame consistency loss for each batch is L of 32 sequences. cos The average value of the loss is used. The gradient of this loss is backpropagated through the model's shared weights, guiding the model to learn to produce smooth and consistent current adjustment values ​​for similar ECAP inputs. This allows for the natural generation of temporally smooth stimulus strategies even during independent inference on a frame-by-frame basis during runtime.

[0106] (3) Total loss The total loss for each training batch is a weighted sum of the MSE loss and the cross-frame consistency loss: L = β·L current + α·L cos Where L current For the aforementioned mean square error loss, L cos For the aforementioned cross-frame consistency loss, β=1.0 is the weight of the principal regression loss, and α=0.1 is the weight of the smoothing regularization. Training details Training strategy: Optimizer: AdamW, suitable for weight decay, provides better regularization; Learning rate: 3e-4; Gradient clipping threshold: 1.0, to prevent gradient explosion; Batch size: Each batch contains 32 frame sequences, and each sequence contains S=16 consecutive ECAP signal frames, that is, each batch contains a total of 32×S=512 frames. The training employs a two-stage strategy: The first stage involves training the CNN independently, using the same (32, S, C, 256) format for sequential batches of training data. However, the loss functions (waveform reconstruction loss, peak localization loss, and sparse regularization term) in this stage are calculated independently frame by frame, without considering inter-frame temporal relationships. The sequence structure is used only to maintain data organization consistency. The maximum number of training epochs is 100, employing an early stopping strategy. The weighted sum of waveform reconstruction loss and peak localization loss on the validation set is used as a monitoring metric. Training stops and the optimal weights are selected when this metric fails to decrease for 15 consecutive epochs. The second stage involves joint training of the CNN and Transformer, freezing the weights of the preprocessing layers and multi-scale convolutional groups in the first two layers of the CNN (only fine-tuning the downsampling layers). In this stage, an intra-sequence cross-frame consistency loss is added to the frame-by-frame MSE loss, utilizing the sequence structure to constrain the smoothness of output in adjacent frames. The maximum number of training epochs is also 100, employing an early stopping strategy. The mean square error of the current adjustment value on the validation set is used as a monitoring metric. Training stops and the optimal weights are selected when this metric fails to decrease for 15 consecutive epochs.

[0107] The decoded stimulation parameters constitute the stimulation strategy control signal, which is sent to the digital-to-analog converter (DAC) and pulse generator in the output module. Specifically, the output module 300 includes a DAC, a constant current source pulse generator, and a parameter mapping unit. The current adjustment value output by the CNN-Transformer module is a scalar continuous value (unit mA). This value is superimposed on the current reference current value by the parameter mapping unit to obtain the updated target stimulation current amplitude. The DAC uses a 16-bit precision DAC to convert the digital current amplitude signal into an analog control voltage. The constant current source pulse generator generates a constant current biphasic square wave pulse with a corresponding amplitude according to the control voltage. The pulse width and stimulation frequency are set by the clinician during the initial calibration phase and stored in the non-volatile memory of the control module (in this embodiment, the pulse width is 200μs by default, and the stimulation frequency is 50Hz by default). During the operation phase, the CNN-Transformer module only dynamically adjusts the current amplitude. The output module also includes an overcurrent protection circuit and a charge balancing circuit. The overcurrent protection circuit automatically cuts off the output when the output current exceeds the safe upper limit (10mA in this embodiment). The charge balancing circuit ensures that the net charge injected into the nerve tissue is zero in each stimulation cycle to prevent electrode corrosion and tissue damage. The pulse generator refreshes the corresponding electrical parameters accordingly and drives the stimulation electrodes to output adjusted electrical pulses to act on the target peripheral nerve.

[0108] Regarding the workflow after device implantation, the complete deployment process of this invention includes the following stages: (i) Implantation and calibration stage: The first 1-2 weeks after device implantation is the clinical calibration period. During this stage, the device operates in open-loop preset mode. Clinicians set fixed stimulation parameters (current amplitude, pulse width, and frequency) based on experience. At the same time, electrodes continuously record the patient's ECAP signal. The patient periodically reports the VAS pain score. The above data is transmitted to the externally paired tablet or dedicated programmer through the low-power Bluetooth communication unit integrated in the control module 200; (ii) Model training stage: After receiving the ECAP signal data and pain labels collected during the calibration period, the external programmer completes the training of the contrast learning module and the CNN-Transformer module on an external computing platform (such as a portable workstation equipped with a GPU). The training cycle is usually several hours to one day; (iii) Model deployment stage: After the trained model weights are quantized by INT8, the external programmer writes them into the non-volatile memory of the control module inside the shell through the Bluetooth communication unit. After writing, the device automatically switches to closed-loop operation mode; (iv) Closed-loop operation stage: The device operates autonomously according to the process of the aforementioned operation stages and no longer requires the continuous participation of external devices. If subsequent changes in the patient's condition lead to a decline in the effectiveness of closed-loop control, the calibration phase can be restarted to collect new data and update the model.

[0109] In terms of deployment, the control module 200 integrates a low-power edge inference chip (such as an ARM Cortex-M series microcontroller with a hardware neural network acceleration unit). In this embodiment, when C=16, the total parameters of the encoding network of the contrast learning module are approximately 85,000 (3,136 convolutional layers + 74,112 GRU layers + 8,256 fully connected layers), and the total parameters of the CNN-Transformer module are 3,632 + 3,297 = 6,929. The total deployed model parameters (85,504 encoding network + 130 classification heads + 6,929 CNN-Transformer) are 92,563, with the scale controlled at the level of hundreds of thousands (only the inference weights of the encoding network and CNN-Transformer module need to be fixed during the deployment phase; the decoder and CNN auxiliary training head used during the training phase do not participate in the deployment). After INT8 quantization, the storage occupied is no more than 200KB, and single-frame inference can be completed on a low-power microcontroller with millisecond-level latency. After the contrastive learning module is trained, the weights of the encoding network and the reference representations (in this embodiment, the reference prototype vectors for pain and health categories, i.e., the cluster centers of each category sample in the latent space after being mapped by the encoding network) are permanently stored in the non-volatile memory of the control module. During the operation phase, after the real-time ECAP signal is mapped to the latent space by the encoding network to obtain the latent representation, the classification head outputs the category probability based on the mapping result. When the pain category probability output by the classification head exceeds the preset threshold θ (θ is determined to be the optimal operating point through ROC curve analysis on the validation set during the training phase, with a typical value range of 0.5~0.8), and this condition is met for N consecutive frames (N≥3), it is determined to be an abnormal state and the CNN-Transformer module is triggered to output the stimulus strategy control signal. The above multi-frame confirmation mechanism can effectively avoid false triggering caused by occasional noise.

[0110] In some optional embodiments, a wireless charging module 500 is also provided inside the housing. The wireless charging module 500 is electrically connected to the battery module 400 and is used to wirelessly charge the battery module 400.

[0111] In some optional embodiments, the battery module 400 is electrically connected to the control module 200 and is used to supply power to the various functional units within the control module 200. The control module 200 also includes a low-power control unit, a power management circuit, and a timed wake-up circuit. The low-power control unit is used to output a sleep control signal to the power management circuit after completing a preset working cycle. The power management circuit responds to the sleep control signal by cutting off the power supply to other functional units except for the timed wake-up circuit and the low-power control unit so that the system enters a sleep mode. The timed wake-up circuit generates a wake-up signal after the sleep mode has lasted for a preset duration and sends it to the power management circuit. The power management circuit then restores the power supply to each functional unit, thereby enabling the system to automatically operate according to the set working-sleep cycle to reduce overall power consumption and extend battery life.

[0112] In some optional embodiments, the battery module 400 is disposed in the power supply cavity inside the housing, and its positive and negative terminals are electrically connected to the control module and the output module respectively via a power management circuit, for continuously supplying power to the control module and the output module.

[0113] In some alternative embodiments, please refer to Figure 4 As shown, the housing 100 is provided with a suspension and fixing structure 101 for fixing with human fibrous tissue. The suspension and fixing structure 101 is an elastic hook provided at each of the four corners of the housing. The elastic hook includes a mounting shell 111 and a hook 114. A connecting spring 112 is fixedly installed inside the mounting shell 111. A length rod 113 that is slidably connected to the mounting shell 111 is fixedly installed at one end of the connecting spring 112. A hook 114 is fixedly installed at one end of the length rod 113. One side of the mounting shell 111 is fixedly connected to the housing 100.

[0114] In some alternative embodiments, the loop wire passes through the outer layer of human muscle tissue naturally present between the housing and the target peripheral nerve, establishing an electrical and signal connection between the nerve signal acquisition-feedback electrode and the housing, thereby avoiding fluid short circuits and reducing the impact of mechanical traction on the nerve.

[0115] This embodiment also provides a control method for an implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback, including acquiring the evoked compound action potential (ECAP) signal of the target peripheral nerve; during the training phase, the ECAP signal is labeled as pain samples and healthy samples based on the patient's pain feedback, and the encoding network is trained through contrastive learning (in this embodiment, a weighted sum of contrastive loss and reconstruction loss is used for training, see the training details of the aforementioned contrastive learning module), so that the pain state and the healthy state form distinguishable reference representations in the latent space; during the operation phase, the real-time ECAP signal is mapped to the latent space through the encoding network, and whether it is an abnormal state is determined based on the similarity between the mapping result and the reference representation (in this embodiment, cosine similarity is used in combination with a multi-frame confirmation mechanism, see the aforementioned deployment implementation section); when an abnormal state is determined, an output stimulation strategy control signal is triggered, and the electrical stimulation pulses released by the stimulation electrodes to the peripheral nerve are adjusted.

[0116] The collaborative mechanism between the aforementioned contrastive learning module and the CNN-Transformer module constitutes the core technical means of this invention, and its relationship with the technical effect is as follows: The contrastive learning module compresses high-dimensional multi-channel ECAP signals into low-dimensional latent representations through an encoding network, and uses a contrastive loss function to make pain states and health states form distinguishable cluster distributions in the latent space (i.e., the reference representations). This mapping process transforms the complex waveform patterns of the original bioelectric signals into quantifiable and comparable mathematical representations, thereby achieving objective and automated identification of pain states, replacing the traditional approach that relies on manually setting fixed thresholds or subjective scoring; In the CNN-Transformer module, the multi-scale one-dimensional depthwise separable convolution of the lightweight CNN captures ECAP signal features at different time scales (the change in the N1 peak amplitude at short time scales and the change in the overall waveform envelope at long time scales), and the Transformer's multi-head self-attention mechanism models long-range dependencies across time steps. The combination of the two enables the current adjustment value output by the model to accurately track the dynamic changes in neural activation states, achieving millisecond-level closed-loop feedback control. The technical effects of the above-mentioned technical means are as follows: compared with the traditional open-loop stimulation system with fixed parameters, the present invention can adaptively adjust the stimulation intensity according to real-time neural feedback, avoid overstimulation or understimulation, and significantly improve the accuracy and long-term stability of analgesia.

[0117] Regarding the consistency guarantee between training data and model deployment: This system requires that the ECAP signal data used during the training phase must be acquired by the same set of acquisition electrodes implanted in the patient, with the exact same number of channels C, sampling rate, filtering parameters, and preprocessing procedures as the deployment and operation. This constraint ensures that the inter-channel correlation patterns learned by the encoding network during training perfectly match the inter-channel correlation patterns of the actual input data during runtime, fundamentally eliminating the risk of model failure due to inconsistencies in the dimensions or distribution drift between training and runtime data. When different numbers of channels are configured for the acquisition electrodes in practical applications, the encoding network only needs to be retrained using training data with the corresponding number of channels, and the input channel parameters C in the model architecture are adjusted accordingly. The aforementioned channel dropout data augmentation strategy further enhances the robustness of the encoding network to individual channel signal loss or poor electrode contact.

[0118] The above are merely specific embodiments of the present invention, but the scope of protection of the present invention is not limited thereto. Any variations or substitutions that can be easily conceived by those skilled in the art within the technical scope disclosed in the present invention should be included within the scope of protection of the present invention. Contents not described in detail in this specification belong to prior art known to those skilled in the art.

Claims

1. An implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback, characterized in that, include: A housing for implantation between human subcutaneous tissue and muscle fascia layer. The housing contains a control module, an output module and a battery module. The battery module is electrically connected to the control module and the output module respectively for power supply. The neural signal acquisition-feedback electrode is electrically connected to the control module and the output module inside the housing via loop wires. The neural signal acquisition-feedback electrode includes an acquisition electrode and a stimulation electrode. It is wrapped around and fixed to the surface of the epineurium of the target peripheral nerve without penetrating the perineum, and is used to contact the target peripheral nerve. The acquisition electrodes are used to acquire evoked compound action potential (ECAP) signals of the target peripheral nerve; the control module includes a contrastive learning module and a CNN-Transformer module; the contrastive learning module contains an encoding network, which, during the training phase, labels the ECAP signals as pain samples and healthy samples based on the patient's pain feedback, and trains the encoding network through contrastive learning, so that the pain state and the healthy state form a distinguishable reference representation in the latent space; During the operation phase, the real-time ECAP signal is mapped to the latent space through the encoding network. The similarity between the mapping result and the reference representation is used to determine whether it is an abnormal state. When it is determined to be an abnormal state, the CNN-Transformer module is triggered to output a stimulation strategy control signal, and the output module is used to adjust the electrical stimulation pulses released by the stimulation electrodes to the peripheral nerves.

2. The implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback as described in claim 1, characterized in that: The neural signal acquisition-feedback electrode includes a flexible electrode wire, which contains an acquisition electrode wire and a stimulation electrode wire. The acquisition electrode wire includes an upstream acquisition electrode wire and a downstream acquisition electrode wire for acquiring signals at different points. An insulating spacer layer is provided between the acquisition electrode wire and the stimulation electrode wire. The flexible electrode wire is wrapped around the surface of the target peripheral nerve at least twice and fixed by knotting or snapping to form a stable closed-loop stimulation path.

3. The implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback as described in claim 1, characterized in that: The process of acquiring the evoked compound action potential (ECAP) signal of the target peripheral nerve using the acquisition electrode includes: acquiring the ECAP signal of the target peripheral nerve at a sampling frequency of not less than 4 kHz; amplifying the acquired signal through a front-end amplification circuit; filtering out background noise through a filtering circuit; and converting the amplified and filtered analog signal into a digital signal through an analog-to-digital converter circuit; wherein the acquisition electrode is a hoop-type electrode, which is arranged around the target peripheral nerve.

4. The implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback as described in claim 1, characterized in that: The contrastive learning module includes an encoder and a decoder. The encoder sequentially comprises a convolutional layer, a recurrent neural network layer, and a fully connected layer, used to progressively extract local features from the input ECAP signal, capture temporal dependencies, and then map them to a low-dimensional latent space to obtain latent representations. The decoder is used to reconstruct the latent representations into the input signal. During the training phase, a weighted sum of reconstruction loss and contrastive loss is used as the total loss function, where the contrastive loss is calculated based on the representation distance between positive and negative sample pairs, so that pain states and healthy states form distinguishable cluster distributions in the latent space. The training process uses an adaptive moment estimation optimizer to update the model parameters.

5. The implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback as described in claim 1, characterized in that: The CNN-Transformer module includes a lightweight CNN module and a Transformer module; The lightweight CNN module sequentially includes: a preprocessing layer, which uses one-dimensional convolution to downsample and extract features from the C-channel input signal, where C is the actual number of channels of the acquisition electrode; a multi-scale convolutional group, which contains multiple parallel one-dimensional depthwise separable convolutional branches, each branch using at least two different convolutional kernel sizes to capture signal features at different time scales, and the multi-branch outputs are fused element-wise and then recalibrated through a channel attention module; and a downsampling layer, which uses one-dimensional max pooling to downsample the fused features in the time dimension. During the training phase, the lightweight CNN module calculates waveform reconstruction loss and peak localization loss using a waveform reconstruction decoding head and a peak detection head, respectively, and combines them with a weighted combination of sparse regularization terms as the training loss. The waveform reconstruction decoding head and the peak detection head only participate in the training process.

6. The implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback as described in claim 5, characterized in that: The Transformer module includes: an input processing layer that reshapes the multi-channel one-dimensional features output by the lightweight CNN module into a token sequence and adds positional encoding to preserve temporal information; a Transformer encoder that uses a multi-head self-attention mechanism to capture long-range temporal dependencies in the signal; and an output regression layer that maps the encoder output to current adjustment values ​​through a fully connected layer. The current adjustment values ​​are continuous values ​​representing the increase or decrease in the current of the stimulating electrode. The training loss of the Transformer module includes the mean square error loss of the current adjustment values ​​and the cross-frame consistency loss by applying smoothing constraints to the current adjustment value outputs of adjacent frames.

7. The implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback as described in claim 1, characterized in that: The housing also includes a wireless charging module, which is electrically connected to the battery module and is used to wirelessly charge the battery module.

8. The implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback as described in claim 1, characterized in that: The housing is provided with a suspension and fixing structure for fixing to human fibrous tissue. The suspension and fixing structure is an elastic hook at each of the four corners of the housing. The elastic hook includes a mounting shell and a hook. A connecting spring is fixedly installed inside the mounting shell. A length rod that is slidably connected to the mounting shell is fixedly installed at one end of the connecting spring. A hook is fixedly installed at one end of the length rod. One side of the mounting shell is fixedly connected to the housing.

9. The implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback as described in claim 1, characterized in that: The circuit wire passes through the outer layer of human muscle tissue that naturally exists between the shell and the target peripheral nerve, establishing an electrical and signal connection between the nerve signal acquisition-feedback electrode and the shell.

10. The control method for the implantable peripheral nerve electrical stimulation analgesia device based on ECAP feedback as described in claim 1, characterized in that: This includes acquiring evoked compound action potential (ECAP) signals from the target peripheral nerve; during the training phase, the ECAP signals are labeled as pain samples and healthy samples based on the patient's pain feedback, and the encoding network is trained through contrastive learning, so that the pain state and the healthy state form a distinguishable reference representation in the latent space. During the operation phase, the real-time ECAP signal is mapped to the latent space through the coding network, and whether it is an abnormal state is determined based on the similarity between the mapping result and the reference representation. When an abnormal state is detected, the output stimulation strategy control signal is triggered, and the electrical stimulation pulses released by the stimulation electrodes to the peripheral nerves are adjusted.