Medical consumable inventory abnormity early warning method based on artificial intelligence
By using edge hardware collaboration and lock-free state merging calculation, the network congestion and warning delay problems of medical consumables inventory warning methods in high-concurrency scenarios are solved, and real-time and reliable inventory anomaly warning is achieved.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- MEDICAL TECH SERVICE (BEIJING) CO LTD
- Filing Date
- 2026-03-24
- Publication Date
- 2026-04-24
AI Technical Summary
Existing medical consumables inventory early warning methods suffer from problems such as network congestion, high early warning delay, and data inconsistency in high-concurrency scenarios, and cannot meet the needs of real-time early warning.
An AI-based inventory anomaly early warning method is adopted, which utilizes edge hardware collaboration, lock-free state merging calculation and a simplified binary protocol. It achieves lock-free enqueueing and lock-free state merging through a circular buffer, radix tree and CRDT algorithm. Combined with memory snapshots and write-ahead log files, it reduces server processing pressure and network load.
It achieves continuity and efficiency in inventory data collection under high-concurrency scenarios, reduces the risk of network congestion and I/O paralysis, and ensures the accuracy and reliability of real-time early warning.
Smart Images

Figure CN121920933A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the fields of medical consumables management and artificial intelligence technology, and in particular to an artificial intelligence-based method for early warning of abnormal medical consumables inventory. Background Technology
[0002] Medical consumables are core materials for medical institutions to carry out clinical diagnosis and treatment, surgical procedures, and emergency care. The stability and accurate management of their inventory are directly related to the continuity, safety, and economy of medical services. With the development of medical Internet of Things (IoT) technology, terminal devices such as smart consumable cabinets, RFID access doors, and PDA barcode scanners are widely used in consumable management, realizing the automatic collection of inventory changes. However, this also brings the challenge of processing massive amounts of concurrent data.
[0003] Existing medical consumables inventory early warning methods generally suffer from the following technical defects: With weak concurrent processing capabilities, during peak logistics periods such as early shift handover and concentrated surgical preparation, tens of thousands of concurrent data requests generated instantly by hundreds or thousands of terminal nodes can easily lead to network congestion, frequent server thread context switching and lock contention, which in turn can cause I / O paralysis. The early warning delay is high. Traditional methods rely on relational databases and query inventory status by periodically polling SQL statements, which has a significant time lag and cannot meet the real-time early warning requirements of emergency consumables. Inventory accumulation operations in high-concurrency scenarios are prone to data overwriting, and data inconsistency can easily occur due to network jitter when synchronizing across systems (such as ERP and HIS systems). Therefore, an AI-based early warning method for abnormal medical consumable inventory is proposed to address the aforementioned issues. Summary of the Invention
[0004] The purpose of this invention is to propose an artificial intelligence-based early warning method for abnormal inventory of medical consumables in order to solve the above-mentioned problems.
[0005] To achieve the above objectives, the present invention adopts the following technical solution: AI-based methods for early warning of abnormal medical consumable inventory include: Receive serialized inventory change data packets sent concurrently from multiple external terminal devices; utilize the comparison and exchange atomic instructions of the underlying processor to perform a mutex-free push-queue operation on the change data packets in a pre-allocated circular buffer in off-heap memory; A global real-time state snapshot of physical consumables is constructed in main memory, where the leaf nodes of the snapshot point to a conflict-free copy data type address block containing positive and negative accumulation vectors. Extract data packets from the circular buffer and route them, then perform lock-free state merging calculations on the corresponding positive or negative accumulation vectors; The calculated real-time absolute value is compared with the static baseline threshold stored in the same memory cache line by performing bitwise operations. Before the lock-free merge calculation is executed, the serialized inventory change data packet is written to the underlying write-ahead log file.
[0006] Preferably, the step of receiving serialized inventory change data packets concurrently sent from multiple external terminal devices, and utilizing the compare-and-swap atomic instructions of the underlying processor to perform a mutex-free push-and-queue operation on the change data packets in a pre-allocated circular buffer in off-heap memory, specifically includes: When the RFID antenna array or photoelectric sensor detects the physical displacement of the consumable, the MCU does not immediately trigger a network request. Instead, it converts the sensed signal into a local hardware interrupt and runs a deterministic micro-state machine in the edge memory, establishing a time sliding window. ; exist Within the window, if the same consumable unique code undergoes multiple on / off signal transitions, the state machine only samples the final stable state when the window closes and calculates the net change. At the edge, the system pushes the net change data onto the stack through bit operations and assembles it into a continuous byte stream data frame.
[0007] Preferably, the method further includes: A contiguous circular buffer is pre-allocated in the off-heap memory of the server. Meaningless bytes are explicitly filled before and after the queue pointer variable to force critical pointers to be isolated in different physical cache lines. The underlying circular buffer uses a one-dimensional array. The system directly calls the underlying CPU. Atomic instructions, their logical formulas are as follows: ,in This is a pointer to the memory address of the tail of the current queue. The old cursor value expected by the thread. The new cursor value calculated for the thread; When a thread writes, it executes a while loop; first, it reads the current cursor. Try using Update it to .
[0008] Preferably, the step of constructing a global real-time state snapshot of the physical consumables in main memory, wherein the leaf nodes of the snapshot point to a conflict-free replicated data type address block containing a positive accumulation vector and a negative accumulation vector, specifically includes: The worker threads inside the engine act as consumers, constantly polling the consumer pointer of the circular buffer to obtain newly arriving data packets; After extracting the unique physical identity code of the consumable from the byte stream, the streaming engine parses or extracts the SKU identifier segment representing the consumable type and performs a lightweight bitwise hash operation on the SKU identifier segment. By taking the modulo of the hash value, all change events of the same type of consumables are routed to the same preset processing thread that is bound to an independent CPU core; The engine builds a highly optimized radix tree in memory as a real-time inventory snapshot library for all consumable SKUs in the hospital; The unique code of the consumable is segmented into bytes and mapped to a hierarchical path of a tree; the leaf nodes of the tree store a memory address pointer to an off-heap memory block; The memory block is pre-allocated with a composite data structure for executing the CRDT algorithm, as well as a static safety stock threshold for consumables.
[0009] Preferably, the method further includes: The worker thread maintains a time window or spatial threshold in memory; During the time window, all addition and subtraction operations belonging to the same SKU are first algebraically accumulated and merged. When window closure is triggered, the worker thread carries the aggregated net change value to access the global state tree for final deduction and warning determination; Before merging data into leaf nodes and pre-calculating the current total inventory for threshold verification, the system inserts a StoreStore barrier instruction; before reading the safety red line for comparison, it inserts a LoadLoad barrier instruction.
[0010] Preferably, the step of extracting data packets from the circular buffer, routing them, and performing lock-free state merging calculations on the corresponding positive or negative accumulation vectors specifically includes: In the leaf nodes of the radix tree of the streaming computing engine, a single integer inventory variable is not stored. Instead, a contiguous memory space is allocated for each SKU to build a positive and negative counter for a state-type CRDT. Assuming the server has allocated Each independent worker thread processes bus data, and the data structure is strictly defined as two strings of length 1. One-dimensional integer array: Increase the vector : Record the operation of adding consumables; Reduce vector : Record the deduction operations for consumables; At this point, the real-time absolute inventory value of consumables in memory is obtained. ; The routing engine uses a hash algorithm to ensure that the first... Each worker thread is only responsible for updating. and ; When thread Deductions are required When using consumables, thread Only ordinary assembly accumulation instructions need to be executed. Perform atomic accumulation.
[0011] Preferably, the pseudo-shared memory row isolation padding technique is as follows: In definition and When using vectors, use cached lines for padding, and explicitly fill the array elements with meaningless placeholder variables to ensure... and They are absolutely distributed across different physical cache lines; Due to total inventory Distributed across vectors, a lazy evaluation strategy of folding on demand is employed.
[0012] Preferably, the step of performing a bitwise comparison between the calculated real-time absolute value and the static baseline threshold stored in the same memory cache line specifically includes: When initializing the leaf nodes of the cardinality tree, in addition to the allocated CRDT vector space, an integer constant is allocated within the same cache line range to store the static security threshold of the consumables. ; When the CRDT status is folded, the latest absolute value of inventory is obtained. Then, directly use the underlying bitwise arithmetic instructions; the system will and The data is sent to the CPU's arithmetic logic unit for fast comparison instructions.
[0013] Preferably, each consumable node maintains a bit identifier; when When the condition changes from False to True, the comparison instruction not only calculates the difference, but also directly flips the bit flag through bit operations; Only when it breaks down for the first time Or, restore it to the safety line plus a tolerance level. Only then will an interrupt be generated; Once the conditions are met, the Worker thread currently performing the merge calculation will immediately suspend subsequent calculations, become an interrupt generator, and package the current environment context into a warning event object.
[0014] Preferably, the step of writing the serialized inventory change data packet to the underlying write-ahead log file before the merge calculation is performed in the lock-free state specifically includes: The system pre-allocates a series of fixed-size log file segments at the underlying operating system level; when a serialized change data packet arrives at the terminal, the binary data packet is directly appended to the end of the currently active log file; In addition to the global radix tree, the system backend also maintains a read-only memory table based on a skip list data structure; when logs are appended to the write-ahead log, the event index is also inserted into the skip list using the consumable ID and timestamp as a combination key; The system starts a collector mounted on the CRDT radix tree and reads the consumable nodes marked with dirty bits in the radix tree in fixed time window steps; The collector cancels and merges all concurrent deductions and additions of high-value consumables in memory to generate a standard SQL statement or API request, which is then sent asynchronously to the traditional ERP system.
[0015] In summary, due to the adoption of the above technical solution, the beneficial effects of the present invention are: 1. This invention uses edge hardware collaborative deduplication, employs a DFA micro state machine and a time sliding window to filter hardware interference and dirty data, reducing the processing pressure on the core server; it uses a simplified binary protocol to encapsulate data, reducing network load and parsing overhead; and it achieves mutex-free enqueueing through off-heap memory lock-free circular buffer, CPU CAS atomic instructions and spin retry mechanism, avoiding thread blocking and context switching.
[0016] 2. This invention combines thread affinity routing to allocate the same consumable change event to a thread bound to an independent CPU core, reducing the probability of multi-threaded contention; enabling the system to support tens of thousands of concurrent terminal requests, increasing throughput by several orders of magnitude compared to traditional methods, avoiding network congestion and I / O paralysis during peak periods, and ensuring the continuity and efficiency of inventory data collection. Attached Figure Description
[0017] Further details, features, and advantages of this application are disclosed in the following description of exemplary embodiments in conjunction with the accompanying drawings, in which: Figure 1 This is a flowchart of the method of the present invention. Detailed Implementation
[0018] Several embodiments of this application will now be described in more detail with reference to the accompanying drawings to enable those skilled in the art to implement this application. This application may be embodied in many different forms and for various purposes and should not be limited to the embodiments set forth herein. These embodiments are provided to make this application thorough and complete, and to fully convey the scope of this application to those skilled in the art. The embodiments described do not limit this application.
[0019] Unless otherwise defined, all terms used herein (including technical and scientific terms) shall have the same meaning as commonly understood by one of ordinary skill in the art to which this application pertains. It will be further understood that terms such as those defined in commonly used dictionaries shall be interpreted as having a meaning consistent with their meaning in the relevant field and / or the context of this specification, and shall not be interpreted in an idealized or overly formal sense unless expressly defined herein.
[0020] Example 1
[0021] Its specific implementation method is combined with the appendix Figure 1 Please provide a detailed explanation.
[0022] Appendix Figure 1 The flowchart of the AI-based medical consumables inventory anomaly early warning method provided in this embodiment of the invention illustrates the complete steps from receiving serialized inventory change data packets sent concurrently from multiple external terminal devices to writing the serialized inventory change data packets into the underlying write-ahead log file before merging and calculating in a lock-free state.
[0023] In this embodiment, it includes: Receive serialized inventory change data packets sent concurrently from multiple external terminal devices; utilize the comparison and exchange atomic instructions of the underlying processor to perform a mutex-free push-queue operation on the change data packets in a pre-allocated circular buffer in off-heap memory, where the cursor variable of the circular buffer is filled with cache line isolation to eliminate false sharing; Specifically, it includes: The core technical problem addressed in this step is: during peak periods of medical consumables logistics (such as early shift handover and centralized surgical preparation), when hundreds or thousands of IoT terminal nodes (smart consumable cabinets, high-value consumables RFID access doors, PDA barcode scanners) generate tens of thousands of concurrent data requests instantaneously, how to avoid network congestion and I / O paralysis of the receiving server due to thread context switching and lock contention.
[0024] The technical solution in this step does not rely on conventional HTTP long connections and JSON messages, but instead involves a deep reconstruction from three dimensions: edge hardware preprocessing, a custom compact binary protocol, and a lock-free circular queue based on CPU instructions at the receiving end.
[0025] Edge hardware collaboration and deduplication: To reduce the processing load on core servers, the defense line must be moved forward to edge computing nodes (such as the microcontrollers (MCUs) built into smart cabinets).
[0026] Hardware interrupts and state machine jitter mitigation: When the RFID antenna array or photoelectric sensor detects the physical displacement of consumables, the MCU does not immediately trigger a network request, but instead converts the sensing signal into a local hardware interrupt; a deterministic micro-state machine (DFA) runs in the edge memory, establishing a microsecond-level time sliding window. (e.g., 500ms); Local spatiotemporal convergence: in Within the window, if the same consumable unique code (EPC code) experiences multiple on / off signal transitions (a typical hardware interference caused by multipath reflection of RF signals), the state machine only samples the final stable state when the window closes, calculating the net change (e.g., -1 or +1). This is considered edge-side hard cleaning, filtering out over 90% of dirty data.
[0027] A modeless, minimal binary serialization protocol: Abandoning the bulky and CPU-intensive JSON or XML formats, the system pushes net change data onto a stack at the edge using bitwise operations, assembling it into a highly customized continuous byte stream data frame. Data frame structure definition: Define a fixed-length micro data packet (e.g., a total length of only 16 bytes), including: Header (1 Byte): Contains the protocol version number and operation type enumeration value (e.g., 0x01 represents outbound, 0x02 represents inbound). Timestamp (4 Bytes): Uses Unix second-level timestamps since the system epoch, discarding milliseconds for precision to compress size; DeviceNodeID (3 Bytes): A globally unique hash value prefix for the terminal hardware MAC address; SKU / EPCIdentifier (7 Bytes): A unique physical identification code for consumables; DeltaValue(1Byte): A signed integer representing the amount of change (e.g., -2 means two are taken).
[0028] Technical Results: Through extreme bit-level compression, even with 10,000 terminals reporting concurrently, the total network load is only 160KB. By employing persistent TCP-based socket connections and utilizing the NIO (Non-blocking I / O) model, these byte streams are directly pushed to the core server, eliminating redundant overhead from HTTP headers.
[0029] Contiguous memory allocation for the core (circular buffer design based on the Disruptor pattern): Once data arrives at the server, traditional architectures either place it in a blocking queue (such as RabbitMQ or Kafka) or directly start a new thread to write it to the database, which will face serious lock contention issues. This solution pre-allocates a contiguous circular buffer in the server's off-heap memory.
[0030] Memory Layout and Cache Line Padding: Modern CPU caches typically load data in 64-byte cache lines. If the "producer pointer" and "consumer pointer" of a circular queue happen to fall within the same cache line, frequent modifications by different CPU cores can cause the entire cache line to become invalid repeatedly. This solution explicitly pads the queue pointer variables with meaningless bytes (e.g., 7 long variables) before and after them, forcing critical pointers to be isolated in different physical cache lines, ensuring that multi-core CPUs can operate independently at high speed.
[0031] Arrays instead of linked lists: The circular buffer uses a one-dimensional array instead of a linked list structure. Because arrays are allocated contiguously in physical memory, they perfectly match the CPU's spatial locality principle, allowing the CPU prefetcher to load subsequent nodes into the L1 / L2 cache at the most efficient speed.
[0032] Lock-free queuing mechanism based on CPU atomic instructions: When hundreds or thousands of network receiving threads (producers) attempt to write decoded, changed data into a circular buffer, absolutely no operating system-level mutexes or synchronized blocks should be used.
[0033] CAS instruction call: The system directly calls the underlying CPU's CAS instruction. The (Compare-And-Swap) atomic instruction has the following logical formula: ,in This is a pointer to the memory address of the tail of the current queue. The old cursor value expected by the thread. The new cursor value calculated for the thread (i.e. ); Spin-Wait: When a thread is writing, it executes a while loop; first, it reads the current cursor. Try using Update it to ; If another concurrent thread has already modified the cursor, the CPU will return failure; the thread will not enter a blocked sleep state (to avoid expensive context switching), but will immediately execute a spin, reread the latest cursor, and try again. The process continues until the write operation is successful. Because the write operation only involves memory assignment and has an extremely short spin time, its throughput is several orders of magnitude higher than that of locking mechanisms.
[0034] A global real-time state snapshot of physical consumables is constructed in main memory based on a radix tree, where the leaf nodes of the snapshot point to a conflict-free copy data type address block containing positive and negative accumulation vectors. Specifically, it includes: The core technical problem addressed in this step is: how to build a high-speed state merging and checking mechanism to match the massive amounts of changing data that are poured into memory at nanosecond speeds, thus completely eliminating the disk I / O bottleneck of relational databases when calculating inventory and issuing warnings.
[0035] We take over all real-time inventory calculations by designing a pure in-memory streaming engine and a lock-free topology snapshot tree.
[0036] Zero-copy consumer routing and event multicast: Memory cursor tracing: The worker threads inside the engine act as consumers, constantly polling the consumer pointer of the circular buffer to obtain newly arriving data packets; HashingRouting by ID: In order to maximize the use of multi-core CPUs and prepare for subsequent lock-free merging, the streaming engine extracts the unique physical identity code (EPC) of the consumables from the byte stream, parses or extracts the SKU identifier segment representing the consumable type, and performs a lightweight bitwise hash operation on the SKU identifier segment. By using hash value modulo, all change events of the same consumable type are routed to the same preset processing thread that is bound to an independent CPU core; this thread affinity design reduces the probability of multiple threads operating on the same consumable data block at the same time.
[0037] Construction of the topology of a pure in-memory global state tree: Instead of using a traditional lock-protected hash table (such as ConcurrentHashMap, which still has segmented locks at its underlying level) in memory, the engine builds a highly optimized radix tree (RadixTree or TrieTree) as a real-time inventory snapshot of all consumable SKUs in the hospital.
[0038] The path is the code: the unique code of the consumable (such as a 24-bit EPC character) is divided into bytes and mapped to a hierarchical path of a tree; the leaf nodes of the tree do not directly store a simple integer inventory number (such as "5 left"), but store a memory address pointer to an off-heap memory block. State vector placeholder: This memory block is pre-allocated with a composite data structure (i.e., CRDT, a conflict-free copy data type algorithm) for executing the algorithm. Vector sum Vectors (which will be detailed in the next step), and the static safety stock threshold for consumables; Technical effect: When querying or preparing to update the status of a consumable, this can be achieved by traversing this tree. Time complexity ( The tree structure provides absolutely deterministic addressing (where the code length is usually a very small constant). It naturally avoids the degradation of linked list traversal caused by hash collisions, ensuring that regardless of whether the inventory contains hundreds or hundreds of thousands of items, the addressing time remains at an extremely low sub-microsecond level.
[0039] Micro-batch processing and time-space dual sliding window computation: Although extremely fast addressing is already possible, updating the main state tree and performing alert checks for every tiny change popped from the circular buffer would still waste computational resources. Therefore, the system introduces a memory-based micro-batch processing mechanism.
[0040] Two-ended window functions: The worker thread maintains a very small time window in memory (e.g., ...). =10ms) or a space threshold (such as 1000 events); Local merging: During this time window, all addition and subtraction operations belonging to the same SKU are first merged by algebraic accumulation in the private CPU L1 Cache of the worker thread; For example, if the orthopedics department takes away 5 screws and returns 2 within 10ms, the thread directly calculates the net change value of all add and remove operations on the same SKU in that local area as -3.
[0041] Batch commit: When the window closure is triggered, the worker thread carries the aggregated net change value to access the global state tree for final deduction and warning judgment; this "local merging, global commit" architecture reduces the number of bus memory barrier instruction calls by two orders of magnitude.
[0042] Transaction boundaries and visibility control for memory snapshots: To ensure that the system does not read the wrong half of the state due to instruction reordering without locking, this system uses memory barriers (Fences) at the code level.
[0043] Barrier instructions: Before merging micro-batch data into leaf nodes and pre-calculating the current total inventory for threshold verification, the system explicitly inserts a StoreStore barrier instruction to ensure that previous write operations are visible to all other threads; before reading the safety red line for comparison, a LoadLoad barrier instruction is inserted. Among them, the StoreStore barrier instruction and the LoadLoad barrier instruction are core memory barrier instructions used at the computer's underlying level to ensure the visibility of memory operations and avoid CPU instruction reordering. Their specific details are explained below in the context of this system scenario: StoreStore Barrier Directive: The StoreStore barrier directive is used to enforce that all memory write operations before the barrier (i.e., writing CRDT status data to the cardinality tree leaf nodes after micro-batch data merging) must be completed before any memory write operations after the barrier are executed, to prevent CPU reordering of write instructions. If the system business strongly depends on the write operation being immediately absolutely visible to all other worker threads, then a StoreLoad barrier directive or a FullMemoryFence should be explicitly inserted after the write is completed to ensure that all threads can read the latest inventory merging results, providing an accurate and strongly consistent data foundation for threshold verification; LoadLoad barrier instruction: It is used to force and ensure that all memory read operations before the barrier (i.e., reading the CRDT status data pre-stored in the leaf nodes of the cardinality tree) can be completed before the operation of reading the safety red line threshold after the barrier is executed. This avoids the logical error of "reading the threshold first and then reading the latest inventory data" caused by CPU instruction reordering, and ensures that the inventory data and threshold data used for threshold comparison are the latest and accurate, thus ensuring the correctness of the warning judgment.
[0044] Results: This control at the compiler and CPU assembly level ensures that memory snapshots maintain strict strong consistency even when faced with tens of millions of QPS of concurrent requests, laying a completely reliable physical memory foundation for the CRDT algorithm and rapid early warning.
[0045] In response to the data packets extracted from the circular buffer by the streaming engine and routed according to the unique identifiers they contain, a lock-free state merging calculation that conforms to the commutative law is performed on the corresponding positive or negative accumulation vector using a single accumulation instruction at the processor level. Specifically, it includes: The core technical problem addressed in this step is: after abandoning the row lock and pessimistic lock mechanisms of relational databases, how to ensure that the final inventory value in the memory stack is absolutely accurate and that the entire state merging process does not cause thread blocking when multiple physical department terminals concurrently submit deduction or increase instructions for the same popular consumable (such as disposable syringes) to the server's main memory within the same microsecond-level time window.
[0046] Conventional concurrent accumulation operations (such as i=i+1) are divided into three independent instructions at the assembly level: "read-modify-write back". Under high concurrency, data overwriting is very likely to occur.
[0047] This solution introduces a conflict-free replicated data type in distributed systems and performs deep adaptation and variant optimization on it in a single-machine multi-core shared memory architecture.
[0048] Memory-level PN-Counter (positive and negative counter) vector structure mapping: In the leaf nodes of the RadixTree of the streaming computing engine, instead of storing a single integer inventory variable, a contiguous memory space is allocated for each SKU (unique identifier of consumables) to build a state-based PN-Counter. Assuming the server has allocated Each independent worker thread processes the bus data, and the data structure is strictly defined as two strings of length 1. A one-dimensional integer array (or vector): Increase the vector : It is specifically for recording the entry, return, and other additions of consumables; Reduce vector : It is specifically for recording the deduction operations such as the issuance and loss reporting of consumables; At this point, the real-time absolute inventory value of consumables in memory is obtained. The mathematical identity is expressed as: ; Thread affinity and lock-free commutativity combined: This structural design utilizes the commutative and associative properties of addition, thereby eliminating the need for locks at the physical level.
[0049] Single write, multiple read: The routing engine uses a hash algorithm to ensure that the first... Each worker thread is only responsible for updating. and These two belong to their own memory slots; other concurrent threads (such as the first one) When processing the same consumable, each thread will only update [the resource]. and .
[0050] Instruction-level atomic operations: When a thread Deductions are required When handling consumables, thanks to the front-end hash routing that ensures strict thread affinity and a single-write, multi-read architecture, threads... Only ordinary assembly accumulator instructions need to be executed (such as the LOCKXADD instruction in the x86 architecture, without the LOCK prefix), for Perform atomic accumulation: Because no other thread will write to it. Therefore, there is no lock contention at all.
[0051] False shared memory row isolation padding technique: In a multi-core CPU architecture, if and Because they were too close together, they were loaded into the same 64-byte CPU cache line, and thread 1 modified it. This will invalidate the entire cache line, forcing thread 2 to read from main memory again. This leads to extremely severe performance degradation (i.e., false sharing).
[0052] Space-to-time optimization: To solve this purely low-level computer problem, this system defines... and When using vectors, the cache line padding technique is forced. At the Java / C++ level, meaningless placeholder variables (such as seven long variables) are explicitly filled between array elements to ensure... and These caches are distributed across different physical cache lines. This underlying spatial layout optimization maximizes the L1 cache hit rate of multi-core CPUs, pushing state merging throughput close to the hardware limit.
[0053] On-demand collapsing of the final state view: Due to total inventory Distributed across vectors, this system does not employ the inefficient strategy of recalculating the sum with each change. Instead, it adopts a lazy evaluation strategy of collapsing on demand. Only when subsequent steps require threshold verification or when the front-end dashboard initiates a read request, does the system use SIMD (Single Instruction Multiple Data) vectorized instructions to add the entire array in parallel within one clock cycle and synthesize the final view.
[0054] Perform a register-level bitwise operation comparison between the real-time absolute value obtained by combining the lock-free state and the static bottom-line threshold co-located in the same memory cache line; When it is determined that the real-time absolute value breaches the static bottom-line threshold, without querying an external relational database, trigger a memory-level pseudo-interrupt signal through the flipping of the state machine identification bit, encapsulate the warning event, and multicast it to associated nodes through a zero-copy network interface; Specifically, it includes: The core technical problem solved in this step is that after abandoning the relational database, the traditional mechanism of periodically polling the database through SQL statements (such as SELECT WHERE stock < threshold) to detect inventory anomalies completely fails. Moreover, there must be a time difference in periodic polling (Polling), which cannot meet the time-sensitive warning requirements for life-saving consumables.
[0055] Therefore, based on the previously constructed memory snapshot, this system proposes a warning trigger architecture that combines state mutation-driven (State-MutationDriven) and memory address offset comparison to achieve truly what-you-see-is-what-you-get zero-latency warnings.
[0056] Off-heap memory co-location and bit-level comparison of threshold constants: To pursue extreme speed, the inventory safety bottom line (preset static safety threshold ) cannot be stored in an external configuration table or database.
[0057] Spatial co-location: When initializing the leaf nodes of the radix tree, in addition to the allocated CRDT vector space, the system allocates an integer constant within the same cache line range adjacent to the address space to store the static safety threshold of the consumables ; This data co-location (DataColocation) ensures that when the CPU fetches the inventory variable for calculation, the threshold constant will also be prefetched (Prefetch) into the L1 Cache along with the same cache line, achieving zero overhead in memory access time.
[0058] Zero-distribution decision engine: When the CRDT state undergoes folding calculation to obtain the current latest inventory absolute value , the system does not call any upper-layer business decision-making components, but directly uses low-level bitwise arithmetic instructions; the system sends and to the ALU (Arithmetic Logic Unit) of the CPU for a fast comparison instruction (such as CMP); Inventory absolute value Obtaining process: Confirm data source: Obtain the CRDT positive and negative counter vector corresponding to the current consumable SKU, i.e., the increment vector. and reduction vector Both vectors have a length equal to the number of server worker threads. ; Parallel summation: System calls SIMD vectorized instructions are used to perform the operation in parallel. Summing all elements of a vector ( )and Summing all elements of a vector ( This process is completed within one CPU clock cycle, ensuring computational efficiency; Calculate the final inventory value: strictly follow the preset mathematical identity. The latest absolute value of inventory is obtained through subtraction. ; Application of results: Apply the calculated results Used for subsequent threshold verification or front-end dashboard display, completing an on-demand folding calculation.
[0059] State machine flips and hardware-level pseudo-interrupt generation: Traditional software typically only logs a message saying "Insufficient stock." This solution borrows from the underlying hardware interrupt handling mechanism of the operating system and designs a pure memory-level event interrupt system.
[0060] Flip-FlopTrigger: Each consumable node maintains a bit flag (BitFlag) Is_Alerting; when The comparison instruction not only calculates the difference in the nanosecond that the condition changes from False to True, but also directly flips the bit flag Is_Alerting through bitwise OR operations. Critical threshold determination: To avoid an "Alert Storm" caused by inventory fluctuating precisely around the threshold (removing one alert, returning one to cancel an alert), the system introduces Schmitt trigger logic with a hysteresis effect. Only when the threshold is first breached... Or, restore it to the safety line plus a tolerance level. (Right now An interrupt will only be generated when ( ). Tolerance Explanation: For pre-configured static constants bound to consumable SKUs, during the initialization of the leaf nodes of the RadixTree, they are associated with static thresholds. Synchronous allocation within the same cache line memory space enables synchronous prefetching during CPU memory access, without adding extra memory access overhead; Basis for value selection: The value is set by the system administrator based on the clinical usage frequency, replenishment cycle and emergency needs of the consumables, following the principle of dynamic adaptation for high-frequency consumables and fixed value for low-frequency consumables. For example, frequently used emergency consumables (such as disposable syringes). The value should be 10% to 20% of the average daily consumption of the consumable to ensure a replenishment buffer; this applies to low-frequency specialized consumables (such as orthopedic screws). The values are fixed constants (such as 1 to 2), balancing the accuracy of early warnings with system efficiency; Activation and Maintenance: After configuration, it corresponds to the SKU. Binding storage allows for dynamic adjustments to batches or individual SKUs via the system backend interface. After adjustment, the data is immediately synchronized to the corresponding memory block of the base tree leaf node without requiring a system restart. This adapts to the dynamic needs of hospital consumables management and further mitigates the impact of early warning storms.
[0061] Interrupt Context Packaging: Once the conditions are met, the Worker thread currently performing the merge calculation will immediately suspend subsequent calculations, becoming an interrupt generator, and packing the current environment context (consumable EPC pointer, breakdown timestamp, current inventory) into a single interrupt generator. The difference gap quantity is packaged into an extremely compact, immutable AlertEventObject.
[0062] Zero-copy alert distribution and gateway multicast: Once an early warning event is generated, the head nurse or the material dispatch center must be notified as quickly as possible.
[0063] Outbound RingBus: The alerted object is instantly pushed into a lock-free ring bus specifically responsible for outbound communication. This echoes the mechanism at the input end.
[0064] Direct memory-mapped transmission: The system's network I / O module (such as the Netty gateway) acts as a consumer, listening to the external bus. When an emergency shortage event is detected, the gateway utilizes the operating system's zero-copy technology (such as sendfile or direct manipulation of DirectByteBuffer) to directly write the byte sequence of the alerted object from memory to the TCP protocol stack's socket send buffer, and then pushes it to the smart terminal screen of the relevant person through a long connection (WebSocket / gRPC) multicast.
[0065] By co-locating data and thresholds in physical memory, simulating state machine flipping during hardware interrupts, and implementing zero-copy network output, a high-speed early warning channel is constructed that flows entirely between the CPU L1 cache, memory, and network card. This transforms the system's early warning action from a slow "business approval process" into a millisecond- or even nanosecond-level "computer hardware-level instruction reflection mechanism."
[0066] Before the lock-free merge calculation is executed, the serialized inventory change data packets are written to the underlying write-ahead log file in a sequential append manner using memory mapping technology; at the same time, the merged incremental snapshot is asynchronously micro-batch synchronized to the external third-party system in the background based on the log structure merge tree to ensure eventual consistency. Specifically, it includes: This step abandons the traditional relational database (such as MySQL's InnoDB engine) B+ tree-based "in-place update" mechanism and designs an asynchronous streaming persistence pipeline that "append-only" specifically for the massive and high-frequency write scenarios of the medical IoT.
[0067] Ultimate sequential writing using memory-mapped files (mmap) and write-ahead logging (WAL): Any attempt to modify an inventory deduction event in the CRDT state tree in memory must first be recorded as an immutable event snapshot before entering the merge logic.
[0068] Append-Only: The system pre-allocates a series of fixed-size (e.g., 64MB) log file segments at the underlying operating system level; when the serialized change data packet of the terminal (containing timestamp, terminal ID, consumable unique code, deduction amount) arrives, the system does not perform any lookup or update operation, but directly appends the binary data packet to the end of the currently active log file; Kernel-level zero-copy (mmap): To avoid frequent data copying between user space and kernel space, this system calls the operating system's mmap (Memory-Mapped Files) system call. This allows the application layer to directly manipulate physical memory pages (PageCache) via pointers, while the specific timing of "flush" is delegated to the operating system's background thread (such as Linux's pdflush) to be completed asynchronously via DMA (Direct Memory Access).
[0069] Technical Benefits: Hard disk drives (HDDs) have extremely long seek times, and random overwrites on solid-state drives (SSDs) can lead to severe write amplification. This solution physically converts high-concurrency random write requests into pure sequential I / O. This makes the log write speed almost equivalent to the physical bandwidth limit of the disk (e.g., several GB per second for NVMe SSDs), ensuring that the lock-free computing engine at the front end will never experience thread suspension while waiting for disk I / O.
[0070] MemTable and SSTable (immutable ordered string table) based on LSM-Tree architecture: WAL only solves the problem of preventing data loss, but for historical billing queries or rapid recovery after a system restart, the retrieval efficiency of sequential logs is extremely low (time complexity is O(n log n)). Therefore, this system constructs an LSM-Tree storage structure specifically for medical IoT event streams.
[0071] SkipListMemTable: In addition to the global radix tree, the system background also maintains a read-only memory table based on the skiplist data structure. When logs are appended to the write-ahead logging (WAL), the event index is also inserted into this skiplist using the consumable ID and timestamp as a composite key. The skiplist ensures that the data always maintains its lexicographical order in memory.
[0072] MinorCompaction: When the size of the MemTable reaches a preset threshold (e.g., 128MB), the system immediately generates a new empty MemTable to receive the new data by replacing the atomic pointer, while the old MemTable becomes "immutable".
[0073] Generating the SSTable (SortedStringTable): A separate, low-priority background I / O thread is awakened and dumps this immutable MemTable directly to the physical disk, generating a read-only ordered data block (SSTable). Since the data is already sorted in memory, this disk write is also a very fast sequential write.
[0074] Eventual consistency across systems and asynchronous compensation protocols: The hospital's financial settlement still relies on relational databases (Oracle / SQL Server) of traditional ERP or HIS systems.
[0075] Background Snapshot Cursor: This system does not require every inbound and outbound transaction to be immediately synchronized to the ERP. The system starts an "asynchronous snapshot collector" mounted on the CRDT radix tree. The collector reads the consumable nodes marked with the dirty bit in the radix tree in a fixed time window (e.g., every 5 seconds, or after accumulating 1000 changes). Aggregation and UPSERT (Batch Update Insertion): The collector cancels and merges all concurrent deductions and increases of a certain model of high-value consumables in memory within 5 seconds (for example, if 10 are taken away and 3 are returned within 5 seconds, the net change is -7); then, the collector generates a standard SQL statement or API request (UPDATEinventorySETstock=stock-7WHEREsku='xxx'), and sends it asynchronously to the traditional ERP system in a micro-batching manner; Idempotency Guarantee: To prevent data retransmission due to network jitter, each micro-batch processing session is accompanied by an incrementing global transaction version number (EpochVersion). The ERP system receiver is configured with an anti-replay filter; if the received version number is less than or equal to the currently processed version, it is discarded directly. This ensures that, even in a complex distributed network, the data between the two systems can achieve robust eventual consistency after a short delay.
[0076] Deterministic State Machine Rebuild after a system crash: In the face of extreme situations like sudden power outages, this system achieves millisecond-level recovery without losing a single piece of data, based on the following methods: Checkpointing mechanism: The system's background thread serializes the full absolute value state of the current CRDT cardinality tree during idle time (such as 3 am) every day, saves it as a physical snapshot file, and records the corresponding WAL log offset at this time.
[0077] Replay Engine: When the server crashes and restarts abnormally, the recovery program first loads the most recent physical snapshot file into memory, instantly restoring the state to 3 AM. Then, starting from the recorded log offset, it rapidly reads subsequent WAL append logs, re-executing all CRDT lock-free addition and subtraction logic like playing a videotape (because addition and subtraction satisfy the commutative law, even if the replay order deviates slightly from the actual occurrence, the final inventory value will be absolutely consistent). This compresses what might have been a data reconciliation and recovery process that took hours into just a few seconds.
[0078] The above formulas are all dimensionless calculations. The formulas are derived from software simulations based on a large amount of collected data to obtain the most recent real-world results. The preset parameters in the formulas are set by those skilled in the art according to the actual situation.
[0079] The foregoing has only described certain exemplary embodiments of the present invention by way of illustration. Undoubtedly, those skilled in the art can modify the described embodiments in various ways without departing from the spirit and scope of the present invention. Therefore, the foregoing drawings and descriptions are illustrative in nature and should not be construed as limiting the scope of protection of the claims of the present invention.
[0080] It should be noted that, in this document, the use of relational terms such as "first" and "second" is merely for distinguishing one entity or operation from another, and does not necessarily require or imply any such actual relationship or order between these entities or operations. Furthermore, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, article, or apparatus. Without further limitations, an element defined by the phrase "comprising one..." does not exclude the presence of other identical elements in the process, method, article, or apparatus that includes the element.
[0081] It should be understood that in the various embodiments of this application, the order of the above-mentioned processes does not imply the order of execution. The execution order of each process should be determined by its function and internal logic, and should not constitute any limitation on the implementation process of the embodiments of this application.
[0082] Those skilled in the art will recognize that the units and algorithm steps of the various examples described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, or a combination of computer software and electronic hardware. Whether these functions are implemented in hardware or software depends on the specific application and design constraints of the technical solution. Those skilled in the art can use different methods to implement the described functions for each specific application, but such implementation should not be considered beyond the scope of this application.
[0083] Those skilled in the art will understand that, for the sake of convenience and brevity, the specific working processes of the systems, devices, and units described above can be referred to the corresponding processes in the foregoing method embodiments, and will not be repeated here.
[0084] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.
[0085] In addition, the functional units in the various embodiments of this application can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit.
[0086] The above description is merely a specific embodiment of this application, but the scope of protection of this application is not limited thereto. Any variations or substitutions that can be easily conceived by those skilled in the art within the scope of the technology disclosed in this application should be included within the scope of protection of this application. Therefore, the scope of protection of this application should be determined by the scope of the claims.
[0087] The foregoing has only described certain exemplary embodiments of the present invention by way of illustration. Undoubtedly, those skilled in the art can modify the described embodiments in various ways without departing from the spirit and scope of the present invention. Therefore, the foregoing drawings and descriptions are illustrative in nature and should not be construed as limiting the scope of protection of the claims of the present invention.
Claims
1. A method for early warning of abnormal inventory of medical consumables based on artificial intelligence, characterized in that, include: Receive serialized inventory change data packets sent concurrently from multiple external terminal devices; By utilizing the comparison and swap atomic instructions of the underlying processor, a mutex-free push-queue operation is performed on the changing data packets in a pre-allocated circular buffer in off-heap memory. A global real-time state snapshot of physical consumables is constructed in main memory, where the leaf nodes of the snapshot point to a conflict-free copy data type address block containing positive and negative accumulation vectors. Extract data packets from the circular buffer and route them, then perform lock-free state merging calculations on the corresponding positive or negative accumulation vectors; The calculated real-time absolute value is compared with the static baseline threshold stored in the same memory cache line by performing bitwise operations. Before the lock-free merge calculation is executed, the serialized inventory change data packet is written to the underlying write-ahead log file.
2. The method for early warning of abnormal medical consumable inventory based on artificial intelligence according to claim 1, characterized in that, Receives serialized inventory change data packets concurrently sent from multiple external terminal devices; utilizes the compare-and-swap atomic instructions of the underlying processor to perform a lock-free push-and-enqueue operation on the change data packets in a pre-allocated circular buffer in off-heap memory, specifically including: When the RFID antenna array or photoelectric sensor detects the physical displacement of the consumable, the MCU does not immediately trigger a network request. Instead, it converts the sensed signal into a local hardware interrupt and runs a deterministic micro-state machine in the edge memory, establishing a time sliding window. ; exist Within the window, if the same consumable unique code undergoes multiple on / off signal transitions, the state machine only samples the final stable state when the window closes and calculates the net change. At the edge, the system pushes the net change data onto the stack through bit operations and assembles it into a continuous byte stream data frame.
3. The method for early warning of abnormal medical consumable inventory based on artificial intelligence according to claim 2, characterized in that, Also includes: A contiguous circular buffer is pre-allocated in the off-heap memory of the server. Meaningless bytes are explicitly filled before and after the queue pointer variable to force critical pointers to be isolated in different physical cache lines. The underlying circular buffer uses a one-dimensional array. The system directly calls the underlying CPU. Atomic instructions, their logical formulas are as follows: ,in This is a pointer to the memory address of the tail of the current queue. The old cursor value expected by the thread. The new cursor value calculated for the thread; When a thread writes, it executes a while loop; first, it reads the current cursor. Try using Update it to .
4. The method for early warning of abnormal inventory of medical consumables based on artificial intelligence according to claim 1, characterized in that, A global real-time state snapshot of the physical consumables is constructed in main memory, where the leaf nodes of the snapshot point to a conflict-free copy data type address block containing both positive and negative accumulation vectors, specifically including: The worker threads inside the engine act as consumers, constantly polling the consumer pointer of the circular buffer to obtain newly arriving data packets; After extracting the unique physical identity code of the consumable from the byte stream, the streaming engine parses or extracts the SKU identifier segment representing the consumable type and performs a lightweight bitwise hash operation on the SKU identifier segment. By taking the modulo of the hash value, all change events of the same type of consumables are routed to the same preset processing thread that is bound to an independent CPU core; The engine builds a highly optimized radix tree in memory as a real-time inventory snapshot library for all consumable SKUs in the hospital; The unique code of the consumable is segmented into bytes and mapped to a hierarchical path of a tree; the leaf nodes of the tree store a memory address pointer to an off-heap memory block; The memory block is pre-allocated with a composite data structure for executing the CRDT algorithm, as well as a static safety stock threshold for consumables.
5. The method for early warning of abnormal medical consumable inventory based on artificial intelligence according to claim 4, characterized in that, Also includes: The worker thread maintains a time window or spatial threshold in memory; During the time window, all addition and subtraction operations belonging to the same SKU are first algebraically accumulated and merged. When window closure is triggered, the worker thread carries the aggregated net change value to access the global state tree for final deduction and warning determination; Before merging data into leaf nodes and pre-calculating the current total inventory for threshold verification, the system inserts a StoreStore barrier instruction; before reading the safety red line for comparison, it inserts a LoadLoad barrier instruction.
6. The method for early warning of abnormal medical consumable inventory based on artificial intelligence according to claim 1, characterized in that, Data packets are extracted from the circular buffer and routed. Lock-free state merging calculations are then performed on the corresponding positive or negative accumulation vectors, specifically including: In the leaf nodes of the radix tree of the streaming engine, a single integer inventory variable is not stored. Instead, a contiguous memory space is allocated for each SKU to build a positive and negative counter for a state-type CRDT. Assuming the server has allocated Each independent worker thread processes bus data, and the data structure is strictly defined as two strings of length 1. One-dimensional integer array: Increase the vector : Record the operation of adding consumables; Reduce vector : Record the deduction operations for consumables; At this point, the real-time absolute inventory value of consumables in memory is obtained. ; The routing engine uses a hash algorithm to ensure that the first... Each worker thread is only responsible for updating. and ; When thread Deductions are required When using consumables, thread Only ordinary assembly accumulation instructions need to be executed. Perform atomic accumulation.
7. The method for early warning of abnormal medical consumable inventory based on artificial intelligence according to claim 6, characterized in that, False shared memory row isolation padding technique: In definition and When using vectors, use cached lines for padding, and explicitly fill the array elements with meaningless placeholder variables to ensure... and They are absolutely distributed across different physical cache lines; Due to total inventory Distributed across vectors, a lazy evaluation strategy of folding on demand is employed.
8. The method for early warning of abnormal inventory of medical consumables based on artificial intelligence according to claim 1, characterized in that, The calculated real-time absolute value is compared with the static baseline threshold stored in the same memory cache line using bitwise operations, specifically including: When initializing the leaf nodes of the cardinality tree, in addition to the allocated CRDT vector space, an integer constant is allocated within the same cache line range to store the static security threshold of the consumables. ; When the CRDT status is folded, the latest absolute value of inventory is obtained. Then, directly use the underlying bitwise arithmetic instructions; the system will and The data is sent to the CPU's arithmetic logic unit for rapid comparison.
9. The method for early warning of abnormal inventory of medical consumables based on artificial intelligence according to claim 8, characterized in that, Each consumable node maintains a bit identifier; when When the condition changes from False to True, the comparison instruction not only calculates the difference, but also directly flips the bit flag through bit operations; Only when it breaks down for the first time Or, restore it to the safety line plus a tolerance level. Only then will an interrupt be generated; Once the conditions are met, the Worker thread currently performing the merge calculation will immediately suspend subsequent calculations, become an interrupt generator, and package the current environment context into a warning event object.
10. The method for early warning of abnormal inventory of medical consumables based on artificial intelligence according to claim 1, characterized in that, Before the lock-free merge calculation is executed, the serialized inventory change data packet is written to the underlying write-ahead log file, specifically including: The system pre-allocates a series of fixed-size log file segments at the underlying operating system level; when a serialized change data packet arrives at the terminal, the binary data packet is directly appended to the end of the currently active log file; In addition to the global radix tree, the system backend also maintains a read-only memory table based on a skip list data structure; when logs are appended to the write-ahead log, the event index is also inserted into the skip list using the consumable ID and timestamp as a combination key; The system starts a collector mounted on the CRDT radix tree and reads the consumable nodes marked with dirty bits in the radix tree in fixed time window steps; The collector cancels and merges all concurrent deductions and additions of high-value consumables in memory to generate a standard SQL statement or API request, which is then sent asynchronously to the traditional ERP system.
Citation Information
Patent Citations
Design data unified storage and management method based on ships
CN121388013A
Concurrency control-based retail end online management method and system
CN121684802A
Abnormal data real-time filtering method and system based on edge calculation in dynamic environment system
CN121691084A
Write-write conflict detection for multi-master shared storage database
WO2020119050A1