A Method and System for Monitoring and Self-Correcting Billing Flow Based on Digital Twins
By constructing a monitoring and self-correction method for the volume and cost accounting business flow of the power operation and maintenance system using digital twin technology, this method solves the problems of business semantic perception, causal relationship positioning, and risk prevention under complex accounting rules in the power operation and maintenance system. It realizes automatic monitoring, accurate traceability, and proactive defense, and improves the fairness and compliance of power trade settlement.
Patent Information
- Application Number
- CN202611349268.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2026-09-02
- Publication Date
- 2026-11-17
- Estimated Expiration
- 2046-09-02
AI Technical Summary
Existing power operation and maintenance systems suffer from problems such as lack of business semantic awareness, difficulty in locating causal relationships, lack of traceability in the accounting process, and insufficient risk prevention measures when faced with complex quantity and cost accounting rules. This results in untimely electricity billing and insufficient system risk resistance.
We adopt a digital twin-based method for monitoring and self-correcting the data flow of billing and accounting. By constructing a digital twin with the same architecture as the production end, we achieve parameter alignment and verification. Combined with MerkleTree hash verification, Wasserstein distance monitoring and causal inference technology, we perform anomaly location and logical correction, and construct a lineage graph for tracing. This supports accurate tracing and proactive risk defense across the entire chain.
It enables automatic monitoring and full-chain traceability of quantity-based billing operations, improves the fairness and transparency of electricity trade settlement, shortens the fault assessment time, and enhances the robustness and credibility of the system.
Smart Images

Figure CN122864922B_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the field of power information processing and big data intelligent monitoring technology, specifically relating to a method and system for monitoring and self-correcting the data flow of billing and accounting based on digital twins. Background Technology
[0002] Billing and accounting are the core of electricity marketing operations, encompassing the entire process from meter reading collection (meter reading), data cleaning, core billing calculations, to auditing and billing. Policies such as tiered pricing, time-of-use pricing, and spot market settlement have made accounting rules increasingly complex, placing extremely high demands on system stability and transparency. Although existing power operation and maintenance systems possess basic monitoring capabilities, the following technical bottlenecks remain in the face of highly complex accounting logic:
[0003] First, there is a lack of business semantic awareness. Traditional monitoring only focuses on underlying IT resources, making it difficult to identify hidden risks such as "system operation is normal but billing calculation is incorrect" caused by rule configuration errors or operator logic anomalies. Second, causal relationship localization is difficult. Data dependencies in each stage of quantity-based billing are complex, lacking causal relationships between stages. Manual troubleshooting is time-consuming and inefficient, severely impacting the timeliness of electricity billing. Third, the accounting process is not traceable or reproducible. Existing database models typically only retain the final calculation results, lacking complete algorithm version fingerprints, execution environment contexts, and data lineage graphs. In the event of billing disputes, it is difficult to reproduce the calculation process at a specific historical moment, resulting in "accounting logic that cannot be self-verified," reducing business credibility. Fourth, risk prevention and governance methods are lacking. When facing changes in electricity pricing policies or peak business periods, there is a lack of means to conduct stress simulations and strategy verification in non-production environments. The passive response mode cannot achieve configuration simulation verification and automatic correction, and the system's risk resistance capability needs to be improved.
[0004] In summary, the existing power operation and maintenance monitoring system is characterized by "emphasizing physical resources over business semantics," "emphasizing isolated monitoring over causal relationships," and "emphasizing result storage over process backtracking." Under this model, operation and maintenance work relies heavily on expert experience, and in the face of increasingly complex power trading rules and massive amounts of accounting data, it is difficult to achieve accurate prediction of logical risks and rapid closed-loop self-healing of faults. Summary of the Invention
[0005] To address the shortcomings of existing technologies, this invention provides a digital twin-based method and system for monitoring and self-correcting the data volume and billing accounting business flow. This system deeply integrates business logic semantics, enables automatic monitoring of data volume and billing accounting business, supports precise traceability across the entire chain, possesses proactive risk defense capabilities, and ensures the fairness and transparency of electricity trade settlement.
[0006] To achieve the above objectives, the technical solution adopted by the present invention is as follows:
[0007] Firstly, a method for monitoring and self-correcting the volume-based billing business flow based on digital twins is provided, including: reading the volume-based billing business flow from the production end and extracting the volume-based billing parameters from the production end as input to a bidirectional closed-loop volume-based billing business digital twin with the same architecture as the production end, to achieve parameter alignment between the production end and the twin end; verifying the volume-based billing results from the production end based on the volume-based billing parameters; when the verification result meets the set alarm threshold, triggering structural causal root cause localization to identify the real business link that caused the billing anomaly and to trace the billing source; and performing stress pre-test verification on the corrected billing logic based on the set monitoring indicators; and sending the corrected billing logic that has passed the stress pre-test verification to the production end.
[0008] Furthermore, a MerkleTree-based hash verification mechanism is employed to align parameters between the production end and the twin end. This includes: sorting all records of the time-of-use electricity price tables on both the production end and the twin end in ascending order by primary key to obtain an ordered record sequence; taking several ordered record sequences as a data block, concatenating the field values of all records in each data block in a predetermined order to form a string S_block; and calculating the SHA-256 hash value of the string S_block as the leaf node hash of that data block. The process involves using all leaf node hashes as the bottom layer, concatenating the hashes of adjacent leaf nodes, and recalculating the SHA-256 hash. This process is repeated layer by layer upwards to build a binary Merkle Tree, ultimately yielding the root node hash value H_root. The same sorting, partitioning, and hash calculation process is performed on the same data table to obtain the production-side root hash H_root and the twin-side root hash H_root'. H_root and H_root' are compared; if they are inconsistent, the difference localization process begins—recursively comparing the hashes of the left and right child nodes from top to bottom along the Merkle Tree. The comparison continues downwards from the child node branch where the hashes are inconsistent until the specific leaf node with the data difference is located, i.e., the corresponding data block. Then, all records within that data block are compared row by row, comparing the primary key and field values to precisely locate the inconsistent record rows and the differing fields. The current value of the record is then retrieved from the production side, and incremental repair is performed on the twin side. After repair, the hash values of each node on the path from the leaf node to the root node are recalculated, and the root hash is verified again until they are consistent.
[0009] Furthermore, on the twin platform, monitoring indicators are defined for each stage of the data collection and billing process, from data acquisition to billing, including: Meter reading stage: monitoring the success rate of remote meter reading and the completeness of the load curve; Billing stage: monitoring the accuracy of tiered billing and the execution time of distributed operators for multi-rate billing of large industrial users; Audit stage: defining the intelligent audit interception rate; Billing stage: monitoring the success rate of bill generation for tens of millions of users and the peak IO throughput.
[0010] Furthermore, non-intrusive desensitization processing is performed on the billing and accounting business flow at the twin end, including: using bytecode dynamic instrumentation technology or non-intrusive proxy technology to capture billing execution snapshots before and after the "electricity billing calculation function" and perform dynamic desensitization on user sensitive identifiers; identifying and performing order-preserving encryption on user's real name, detailed electricity address, and load readings accurate to the household.
[0011] Furthermore, the volume-based cost accounting results on the production side are verified based on the volume-based cost accounting parameters, including: verifying the daily distribution in the volume-based cost accounting parameters. Compared with historical baseline All sample values are merged and sorted in ascending order to obtain a unique sorted value sequence. , k is the number of unique values; calculate the daily distribution. Compared with historical baseline In value sequence Cumulative distribution function on:
[0012]
[0013]
[0014] in, Distribution for the day The cumulative distribution function on the given value sequence Historical baseline Take any value The cumulative distribution function value at that location, The total number of users on that day. This represents the total number of historical baseline samples;
[0015] Calculate the first-order Wasserstein distance:
[0016]
[0017] in, Distribution for the day Compared with historical baseline The first-order Wasserstein distance, The first unique value in the sorted sequence Each possible value The first unique value in the sorted sequence Each possible value Distribution for the day exist The cumulative distribution function value at that location, Historical baseline exist The cumulative distribution function value at that location;
[0018] Based on weighted distance, the anomaly score for each sample point x is calculated using the improved isolated forest algorithm:
[0019]
[0020] in, For sample points With a sample size of Outlier scores in isolated forests For sample points The expected value of the weighted path length in each tree. This is the normalization term for the average path length of a binary search tree. , For the first Harmonic number, sample size That is, the total number of users on that day;
[0021] Single-sample anomaly detection logic:
[0022]
[0023] in, This is the threshold for single-sample anomaly detection;
[0024] If the threshold for the percentage of abnormal samples in the global drift red alarm rule is set at 0.5%, then the global anomaly detection logic is as follows:
[0025]
[0026] The specific distribution offset values are displayed through a graphical dashboard. Anomaly score for each sample point Global decision result .
[0027] Furthermore, structural causal root cause localization includes: obtaining a multi-dimensional observation matrix for a set time period before and after the alarm trigger time. For multidimensional observation matrix After performing mean-removal preprocessing, whitening is then performed to obtain the whitening matrix. Using the FastICA algorithm to extract from the whitening matrix The separation matrix is estimated to obtain the independent component estimates; the causal order of the variables in the independent component estimates is determined by stepwise regression, and the causal strength matrix B is output.
[0028] external temperature To control the variables, calculate Fixed power consumption With billing amount Partial correlation coefficient between :
[0029]
[0030] in, The Pearson correlation coefficient between electricity consumption and billing amount. The correlation coefficient between electricity consumption and temperature. The correlation coefficient between billing amount and temperature;
[0031] Significance test using Fisher's Z-transform:
[0032]
[0033] in, For statistical purposes, To control the external temperature Post-consumption of electricity With billing amount The partial correlation coefficient between them;
[0034] calculate Value: Statistic after FisherZ transformation Approximately follows the mean Standard deviation is The standard normal distribution, where The number of sample data pairs used in the partial correlation coefficient calculation; Convert to two-tailed test value:
[0035]
[0036] in, The cumulative distribution function of the standard normal distribution:
[0037]
[0038] The significance test is used to exclude cases where normal peak summer electricity consumption is mistakenly identified as a calculation error: if If the null hypothesis that the partial correlation coefficient is zero is rejected, it is determined that there is a significant association between electricity consumption and billing amount driven by factors other than temperature; if If so, the null hypothesis is accepted, and the association is determined to be mainly driven by the common factor of temperature. This causal path should be excluded to avoid misjudging the normal peak electricity consumption in summer as a billing error.
[0039]
[0040] in, The causal strength matrix is the th Line 1 The absolute difference between the element values in the column before and after the intervention. and These are the first and second causal strength matrices before and after the intervention, respectively. Line 1 The element values of the column;
[0041] like threshold If the cause-effect relationship is mainly driven by common factors, it should be eliminated; otherwise, it should be retained.
[0042] Output the top three candidate root variables and their causal strength.
[0043] Furthermore, the root cause objects identified based on structural causal root cause localization are subjected to accounting and tracing. For each accounting request, a globally unique TraceID is generated at the entry point and runs through the entire call chain; the transaction GTID is obtained when writing to the database; the CommitID is obtained and cached when the application starts; and the version number of the highest-performing stored procedure currently executed is queried during the first database access. ;
[0044] Establish mapping relationship ;in, To calculate the timestamp of the request, A unique identifier for the user. This is the calculated electricity bill amount;
[0045] Establish a bloodline chart , where the set of nodes edge set Indicates the data flow relationship; any user bill Backtracking through the complete path:
[0046]
[0047] in, The raw battery data is located via GTID. For the corresponding version of the stored procedure logic, This corresponds to the Java operator logic.
[0048] Furthermore, stress simulation verification of the revised accounting logic is performed, including: redeploying the revised accounting logic to the twin client; driving the twin client to run the revised billing process to simulate continuous billing results for a future set time period; evaluating the billing results according to the defined monitoring indicators for each stage of the data collection and billing process; if all monitoring indicators are ≤120% of the baseline value and the number of ERROR-level logs is 0, the simulation is successful.
[0049] Furthermore, the revised accounting logic, verified through stress simulation, is sent to the production end. This includes: verifying the revised accounting logic through the command gateway and conducting dual-person review and approval. After the command gateway verification and dual-person review and approval are passed, the logic is sent from the reverse control layer to the production configuration center on the production end. The production configuration center senses and refreshes the production application parameter cache in real time. If the simulated billing verification fails or the dual-person review is not approved, the system automatically performs the following fallback operations and then switches to manual intervention mode: 1) Generate an anomaly analysis report and send it to the operation and maintenance team and the billing expert team; 2) Mark the IP address of the accounting node that caused the anomaly and the anomaly time window in the monitoring dashboard on the twin end for manual investigation and location.
[0050] In a second aspect, a digital twin-based service flow monitoring and self-correction system for volume-based billing is provided, comprising a storage medium and a processor; the storage medium is used to store instructions; the processor is used to operate according to the instructions to execute the digital twin-based service flow monitoring and self-correction method for volume-based billing described in the first aspect.
[0051] Compared with the prior art, the beneficial effects achieved by the present invention are as follows:
[0052] (1) This invention reads the quantity and fee accounting business flow of the production end and extracts the quantity and fee accounting parameters of the production end as the input of the bidirectional closed-loop quantity and fee accounting business digital twin constructed with the same architecture as the production end, so as to realize the parameter alignment between the production end and the twin end; the quantity and fee accounting result of the production end is verified based on the quantity and fee accounting parameters. When the verification result meets the set alarm threshold, the structural causal root cause location is triggered to identify the real business link that causes the accounting abnormality and perform accounting source tracing. The modified accounting logic is subjected to stress pre-test verification based on the set monitoring indicators; the modified accounting logic that has passed the stress pre-test verification is sent to the production end; it can deeply integrate business logic semantics, realize automatic monitoring of quantity and fee accounting business, support full-link accurate source tracing, have risk active defense capability, and ensure the fairness and transparency of power trade settlement;
[0053] (2) This invention achieves a leap from IT resource monitoring to deep business semantic awareness, eliminating the risk of accounting black boxes. Traditional monitoring can only detect hardware anomalies such as server crashes, making it difficult to identify logical vulnerabilities such as online systems but incorrect electricity billing. This invention, by constructing a digital twin containing a mirrored data layer and an operator logic layer, extends its monitoring reach into core business semantics such as tiered electricity pricing and time-of-use rate switching. Through a multi-dimensional evaluation matrix, it achieves real-time quantification of the execution accuracy, data entry latency, and billing throughput of tens of millions of accounting tasks, ensuring the transparency and fairness of electricity billing, a core link in electricity trade.
[0054] (3) This invention introduces distribution drift and causal inference technology to achieve minute-level accurate loss assessment and attribution for complex accounting anomalies. Addressing the pain points of high coupling between various stages of quantity-based billing and the extremely slow manual troubleshooting of fault sources, the invention innovatively introduces Wasserstein distance monitoring to monitor bill output distribution. Compared to traditional single-point threshold alarms, this technology can keenly capture structural billing deviations caused by policy configuration biases. Combined with the LiNGAM structural causal model, the system can automatically remove pseudo-correlation between indicators, accurately pinpointing whether the anomaly is caused by asynchronous electricity price parameters or operator logic defects, reducing the traditional manual attribution time of several hours to minute-level automated diagnosis;
[0055] (4) This invention constructs an operator-level backtracking system with a closed-loop evidence chain, enhancing the credibility of billing dispute resolution; through JavaAgent bytecode instrumentation and code fingerprinting technology, a complete data lineage map containing original data, computational operators, execution environment, and output is established for each accounting task. When facing user billing disputes or audit verification, the system can reproduce the logical context of a specific historical moment with one click in an isolated sandbox, providing tamper-proof technical evidence. This operator-level backtracking capability solves the problem of accounting logic being unable to prove itself in heterogeneous environments, greatly enhancing the compliance and credibility of electricity marketing business;
[0056] (5) This invention establishes a proactive defense mechanism based on simulation pre-monitoring to ensure robust production during sensitive periods such as electricity price policy adjustments. To address the risks posed by frequent adjustments to electricity policies, this invention utilizes a digital twin as a strategy testing ground, employing simulated loads generated by an LSTM prediction model for stress pre-monitoring. In the policy correction issuance phase, a security barrier consisting of an instruction verification gateway and dual-person review is added to ensure that any logical changes undergo sufficient equivalence verification before reaching the production system. This shift from passive patching to proactive simulation governance significantly enhances the robustness of the core power accounting system in the face of complex policy environments. Attached Figure Description
[0057] Figure 1 This is a schematic diagram of the main process of a digital twin-based method for monitoring and self-correcting the data flow of billing and accounting. Detailed Implementation
[0058] The present invention will be further described below with reference to the accompanying drawings. The following embodiments are only used to more clearly illustrate the technical solution of the present invention, and should not be used to limit the scope of protection of the present invention.
[0059] A method for monitoring and self-correcting the volume-based billing business flow based on digital twins includes: reading the volume-based billing business flow from the production end and extracting the volume-based billing parameters from the production end as input to a bidirectional closed-loop volume-based billing business digital twin with the same architecture as the production end, to achieve parameter alignment between the production end and the twin end; verifying the volume-based billing results from the production end based on the volume-based billing parameters; when the verification result meets the set alarm threshold, triggering structural causal root cause localization to identify the real business link causing the billing anomaly and perform billing source tracing; and performing stress pre-test verification on the corrected billing logic based on the set monitoring indicators; and sending the corrected billing logic that has passed the stress pre-test verification to the production end.
[0060] 1. Read the volume and fee accounting business flow from the production end and extract the volume and fee accounting parameters from the production end. Use these parameters as input to construct a bidirectional closed-loop volume and fee accounting business digital twin with the same architecture as the production end, so as to achieve parameter alignment between the production end and the twin end.
[0061] like Figure 1 As shown, this invention presents a digital twin-based method for monitoring and self-correcting the data flow of billing and utilities. Taking the implementation of a provincial power company's summer time-of-use tiered pricing policy for large industrial users as an example, the invention details its specific engineering implementation process.
[0062] S1. Construct a bidirectional closed-loop digital twin of the billing and utilities accounting business with the same architecture as the production side: Based on the power grid marketing system architecture, establish a digital twin including a mirror data layer, an accounting operator logic layer, and a reverse control layer. Utilize Change Data Capture (CDC) technology to synchronize the tiered electricity tariff thresholds, time-of-use pricing period files, and user billing multipliers from the production side in real time. Combined with GTID transaction identifiers, ensure that the electricity price parameters referenced by the twin remain consistent with the production environment within seconds when the twin performs accounting in the mirror environment. Through the MerkleTree hash comparison mechanism, identify and correct rate version offsets between the production and mirror databases to ensure simulation accuracy.
[0063] The original binlog log streams of the four core parameter tables in the production-side MySQL 8.0 database are read from the volume and cost accounting business flow, as shown in Table 1.
[0064] Table 1: Partial raw binlog log streams from the production end
[0065]
[0066] Simultaneously, JVM startup parameters and GC logs in the production environment are collected. The JVM startup parameters in the production environment include: initial heap size -Xms, maximum heap size -Xmx, young generation to old generation ratio -XX:NewRatio, core thread count and maximum thread count of the thread pool.
[0067] Environment Simulation Alignment and Terminology Conventions: First, a digital twin with an architecture completely identical to the production accounting system is deployed in a cloud-isolated environment. This digital twin comprises a three-layer architecture: the mirror data layer stores data in an independent mirror database; the accounting operator logic layer carries the exact same billing algorithm code as the production system and runs in a containerized sandbox physically isolated from the production environment; the reverse control layer is responsible for securely distributing the correction policies verified by the digital twin to the production system.
[0068] The system reads the JVM runtime parameters of the production environment's computational application via the JMX interface, obtaining the initial heap memory size (-Xms), maximum heap memory size (-Xmx), young generation to old generation ratio (-XX:NewRatio), core thread count of the thread pool, and maximum thread count. In this invention, the initial heap memory size is 4GB, the maximum heap memory size is 8GB, the young generation to old generation ratio is 2, the core thread count of the thread pool is 200, and the maximum thread count is 500. Subsequently, in a Docker container in a cloud-isolated environment, the computational operator service sandbox is started with the exact same JVM startup parameters (-Xms4G-Xmx8G-XX:NewRatio=2). After the sandbox starts, by comparing the GC logs of the production environment and the sandbox environment, including YoungGC frequency, FullGC counts, and pause times, the generational size of the sandbox's heap memory is fine-tuned until the GC behavior deviates from the production environment by no more than 5%, ensuring that the execution context of the twin operator is physically consistent with the production environment.
[0069] Strong data consistency synchronization: The CDC component (DebeziumCDC, change data capture, this invention uses Debezium2.0) is registered as a production MySQL Slave node with server-id=100. server-id=100 ensures that it does not conflict with the server-id of the production MySQL. It continuously pulls the binlog event stream of the production database through the GTID protocol and sets binlog_format=ROW and binlog_row_image=FULL.
[0070] When the production side executes an UPDATE statement to adjust the peak electricity price for large industrial users from 1.20 yuan / kWh to 1.50 yuan / kWh, the CDC component extracts the value before the change, the value after the change, and the global transaction identifier (GTID), such as 3E11FA47-71CA-11E1-9E33-C80AA9429562:1-1005. The parsed change record is then encapsulated into a JSON message and written to the corresponding Kafka topic, such as cdc-tou-period, with 6 partitions set to support parallel consumption.
[0071] The mirrored data consumer service on the twin continuously pulls Kafka messages and replays DML operations in the mirrored database in monotonically increasing GTID order. The mirrored database uses MySQL 8.0, the same version as the production database. The consumer service records the highest GTID currently consumed (e.g., 3E11FA47-71CA-11E1-9E33-C80AA9429562:1-1005) as a flag for resuming interrupted data transmissions. When replaying a transaction for a specific GTID fails on the twin, such as due to primary key conflicts or constraint violations, the consumer service pauses consumption, records the failed GTID and exception stack trace, sends an alarm notification for manual intervention, and resumes synchronization from that GTID after repair, ensuring strong data consistency.
[0072] MerkleTree (SHA-256 hash verification algorithm) consistency check:
[0073] Arrange all records of the tou_time_period table (i.e., the time-of-use electricity price period table) on the production side and the twin side in ascending order according to the primary key voltage_level, season, period_type to obtain an ordered record sequence R=[r1,r2,...,r_N0], where N0 is the total number of records in the table, approximately 500.
[0074] A data block is formed with K=1000 records. Since the table contains less than 1000 records, the entire table is considered as one data block. For each data block, the field values of all its records are concatenated in a fixed order (voltage_level||season||period_type||start_time||end_time||price_rate), with the fields connected by the special delimiter "||", forming the string S_block.
[0075] Calculate the SHA-256 hash value of the string S_block, and output a 32-byte hexadecimal string, which will be used as the leaf node hash of this data block. Using all leaf node hashes as the bottom layer, concatenate the hashes of adjacent leaf nodes and calculate SHA-256 again, building a binary Merkle Tree layer by layer upwards, finally obtaining the root node hash value H_root. Perform the exact same sorting, block partitioning, and hash calculation process on the same data table on the twin side, obtaining the production-side root hash H_root and the twin-side root hash H_root' respectively.
[0076] Compare H_root and H_root': If they match (H_root == H_root'), the table data is considered fully synchronized and the verification passes; if they do not match, the difference localization process begins—recursively comparing the hashes of the left and right child nodes from top to bottom along the MerkleTree, continuing the comparison downwards into the child node branch with inconsistent hashes until the specific leaf node with the data difference is located, i.e., the corresponding data block. Then, all records within that data block are compared row by row for primary key and field values to precisely locate inconsistent record rows and differing fields. For example, the end_time of a record during a peak period is 15:00:00 on the production side and 14:00:00 on the mirror side. Finally, the CDC component retrieves the current value of the record from the production side, executes an UPDATE statement on the twin side for incremental repair, and after the repair is completed, recalculates the hash values of each node on the path from the leaf node to the root node, and verifies the root hash again until they match.
[0077] After the above processing, a digital twin environment is obtained that is physically isolated from the production environment and has a completely consistent logical architecture, including a three-layer architecture of mirror data layer, accounting operator logic layer and reverse control layer; the MerkleTree root hash of the four types of parameter tables in the mirror database is completely consistent with the corresponding tables in the production end, and the data synchronization latency is ≤200ms; the GC behavior of the sandbox JVM deviates from that of the production environment by ≤5%.
[0078] After the above mirror data synchronization and verification are successful, the system automatically enters the S2 stage to establish a multi-dimensional performance monitoring system based on the real-time synchronization indicators between the mirror data and the production environment.
[0079] S2. Establish a multi-dimensional business performance monitoring indicator system: Define monitoring indicators for the five key links of data collection and billing.
[0080] Based on the raw scattered data intercepted by the probe at each stage: the meter reading result log returned by the meter reading system, including success / failure status and the number of data points collected; the AOP interception record of the billing operator method call, including the single execution time, input electricity value, and output electricity amount; the interception record of the auditing system, including the interception reason code and the number of intercepted bills; the JDBC write record of the billing system, including the number of writes and write time, etc.; the system adopts a time window aggregation algorithm to aggregate the raw data reported by each accounting node with a fixed time window Δt=60 seconds, and calculates the matrix elements one by one according to the formula in Table 2:
[0081] Table 2: Formulas for Calculating Matrix Elements
[0082]
[0083] The specific implementation of each data collection method is as follows: read the execution time of JVM layer operators through the JMX interface; intercept the billing service method through Spring AOP aspect (@Around advice) and record the input parameters, output results and execution time; record the number of SQL executions and response time through JDBC interceptor (implementing the StatementInterceptor interface); and extract meter reading and billing statistics data through ELK log parsing and Logstash's grok filter.
[0084] Standardized time series index vector Where d is the total number of indicators T represents the vector transpose, and each index value is accompanied by a timestamp accurate to the second, such as 2026-07-15T10:00:00Z,p 22 =156,p 23 =99.92%, continuously written to the InfluxDB time series database, with a retention period of 90 days, including 30 days for hot data and 60 days for cold data.
[0085] The twin-end defines monitoring indicators for each stage of the data collection and billing process, from data acquisition to billing, including: Meter reading stage: monitoring the success rate of remote meter reading and the completeness of the load curve; Billing stage: monitoring the accuracy of tiered billing and the execution time of distributed operators for multi-rate billing of large industrial users; Audit stage: defining the intelligent audit interception rate; Billing stage: monitoring the success rate of bill generation for tens of millions of users and the peak IO throughput.
[0086] After the above-mentioned indicator data is stored in time series, it provides a historical baseline data benchmark for the distribution offset detection in S4. At the same time, the billing execution snapshot collected in S3 will be combined with these indicators to provide a data basis for causal analysis for root cause localization in S5.
[0087] S3. Non-intrusive de-identified collection of billing data: A lightweight collection agent is deployed at the billing calculation node. Utilizing bytecode dynamic instrumentation technology or non-intrusive agent technology, memory snapshots are captured before and after the billing operator executes the electricity calculation function. The agent has a built-in de-identification engine that identifies and performs order-preserving encryption (OPE) on the user's real name, detailed electricity address, and load readings accurate to the household level. This ensures that while supporting monitoring needs such as sorting by electricity consumption from highest to lowest, it also meets the requirements for graded and classified protection of energy data.
[0088] On the twin end, non-intrusive desensitization processing is performed on the billing business flow. Using bytecode dynamic instrumentation technology or non-intrusive proxy technology, billing execution snapshots are captured before and after the electricity billing calculation function, and dynamic desensitization is performed on user sensitive identifiers; the user's real name, detailed electricity address, and load readings accurate to the household are identified and encrypted with order preservation. This mainly involves the bytecode (.class files) of the billing operator classes being loaded by the JVM of the accounting application, including TieredPricingCalculator, TimeOfUseCalculator, IndustrialPowerCalculator, BasicPowerCalculator, etc.; input parameters of the original methods called during business operation, such as Java objects containing plaintext sensitive information (User(user object) {userId(user unique identifier)="U10023456",name(name)="Zhang San",address(electricity address)="No.1, xx Road, Xuanwu District, Nanjing City",powerLoad(electricity load)=3240.5}); and the source code files (.java files) of the billing operator projects.
[0089] JavaAgent bytecode instrumentation, ASM 9.0 framework: At application startup, a collection agent is mounted via `-javaagent: / opt / agents / pricing-collector-agent-1.0.jar=config= / opt / agents / collector.conf`. The agent intercepts the bytecode loaded by the JVM through the `ClassFileTransformer` interface, uses the ASM 9.0 framework to parse the bytecode structure, and locates the billing methods annotated with `@PricingFunction` or whose method names match the regular expression `^(calculate|compute|execute|calc).*$`.
[0090] Bytecode enhancement is performed on the identified target method: Bytecode instructions are inserted at the method entry point to obtain the current timestamp (System.currentTimeMillis()), current thread ID, input parameters, and the currently loaded electricity price version number. These are encapsulated into an `ExecutionSnapshot` object and written to the memory buffer `ConcurrentLinkedQueue`. Input parameters include: userId, electricity consumption, voltage level, electricity consumption category (userCategory), and billingDate. Bytecode instructions are also inserted at the method exit point, triggered by both normal return and exception throwing, to obtain the execution time, electricity fee return value, and intermediate calculation variables, including: the electricity consumption segment values for each tier (firstTierConsumption, secondTierConsumption, thirdTierConsumption), the electricity consumption for each time period (peakConsumption, flatConsumption, valleyConsumption), the basic electricity fee (basicCharge), and the power factor adjustment fee (powerFactorAdjustment). The `ExecutionSnapshot` object is then completed. The JVM loads the modified bytecode, and subsequent calls to the billing method trigger the capture of the level execution snapshot.
[0091] Abstract Syntax Tree (AST) parsing using JavaCompilerAPI: During the project build phase, specifically the Maven generate-sources phase, the JavaCompilerAPI (javax.tools.JavaCompiler) is used to parse the billing operator source code, generating an AST containing a complete syntactic structure. Method declarations, control flow structures, variable read / write operations, and method call information are extracted from the AST. The control flow structure includes if-else branches, for / while loops, and switch statements. An intra-operator data flow graph is constructed: variables are used as nodes, and the write-to-read data flow direction is used as directed edges. For example, input variable totalConsumption → intermediate variable firstTierConsumption calculated by Math.min → secondTierConsumption → output variable finalAmount. The data flow graphs between operators are connected through method call relationships, forming an operator-level business dependency graph covering all accounting logic.
[0092] Dynamic data masking: The data masking engine uses predefined sensitive field matching rules (regular expressions). (userId|userName|address|phone|meterId). Identify sensitive fields in the execution snapshot. For string-type sensitive fields such as user name and detailed electricity address, the Boldyreva Order Preservation Encryption (OPE) scheme is used for encryption: the OPE key is obtained from the Key Management Service (KMS). The OPE key uses AES-256 and the key ID is ope-key-prod-001. The plaintext string is converted into a byte array using UTF-8 encoding. The OPE mapping function is applied to each byte in the byte array—mapping the plaintext field [0, 255] to the ciphertext field [0, 65535], maintaining a monotonically increasing order. < Then Enc ( ) <Enc( The mapping function is generated through hypergeometric random sampling, and the mapped ciphertext value is encoded as a hexadecimal string. For numerically sensitive fields such as electricity load readings, OPE encryption is also used to support subsequent statistical operations such as "sorting by electricity consumption"; non-sensitive billing intermediate values are not encrypted to maintain the readability of monitoring and analysis.
[0093] The de-identified ExecutionSnapshot object has its sensitive fields replaced with OPE ciphertext: userId:"U10023456" → userId_enc:"8A3F2C1E" (ciphertext), address:"No.1, xx Road, Xuanwu District, Nanjing" → address_enc:"5B9E7D4F2C1A8E3D"; the generated operator-level business dependency graph is stored in JSON format, containing a list of nodes and edges; the de-identified data is stored in an Elasticsearch index (pricing-snapshots-YYYY.MM.DD) and retained for 30 days.
[0094] The desensitized execution snapshot output by S3 will serve as the data source for user feature vectors in S4 distribution drift detection, and also as the core basis for operator-level backtracking in S6 lineage tracing.
[0095] 2. Verify the quantity and cost accounting results on the production side based on the quantity and cost accounting parameters. When the verification result meets the set alarm threshold, trigger the structural cause-effect root cause location to identify the real business link that caused the accounting anomaly and perform accounting source tracing. Based on the set monitoring indicators, perform stress pre-performance verification of the corrected accounting logic.
[0096] S4. Business Distribution Drift Detection and Visualization: A visual dashboard is built based on a digital twin. Wasserstein distance (also known as bulldozer distance) is used to monitor the daily electricity revenue distribution across the province / city. If a group-wide electricity bill deviation occurs due to adjustments in time-of-use pricing strategies, traditional threshold alarms may fail. However, Wasserstein distance can identify structural shifts in the overall bill amount distribution curve and utilize an improved isolated forest algorithm, combined with a time decay factor, to eliminate historical seasonal electricity consumption fluctuations, accurately locating business anomalies.
[0097] This step performs distribution drift detection based on the billing results synchronized from the S1 mirror data layer, the historical metrics from the S2 time-series storage, and the billing snapshots from the S3 de-identified storage.
[0098] Step S1: Same-day billing results synchronized with the mirror data layer – the set of all electricity bills for large industrial users for the day extracted from the bill_result table. N represents the total number of users on that day, with approximately 10 million large industrial users in the province; the historical normal baseline distribution stored in InfluxDB during step S2 is... Take data of the same date type that has no abnormal alarms in the past 30 days, M approximately 300 million records; in step S3, the user's 4-dimensional feature vector u = [electricity consumption, voltage level code, electricity usage type code, bill amount]ᵀ is stored in the de-identified billing execution snapshot.
[0099] Wasserstein distance calculation:
[0100] The daily distribution of the data usage and fee calculation parameters Compared with historical baseline All sample values are merged and sorted in ascending order to obtain a unique sorted value sequence. , This represents the number of unique values after deduplication. Calculate each value separately. and The cumulative distribution function (CDF) on the sorted value sequence:
[0101]
[0102]
[0103] in, Distribution for the day The cumulative distribution function on the given value sequence Historical baseline Take any value The cumulative distribution function value at point N is the total number of users on that day, and M is the total number of historical baseline samples.
[0104] Calculate the first-order Wasserstein distance (first-order bulldozer distance):
[0105]
[0106] in, Distribution for the day Compared with historical baseline The first-order Wasserstein distance, The first unique value in the sorted sequence Each possible value The first unique value in the sorted sequence Each possible value Distribution for the day exist The cumulative distribution function value at that location, Historical baseline exist The cumulative distribution function value at that location.
[0107] This is calculated by multiplying the absolute value of the cumulative probability difference in each interval by the interval length, and then summing the results over all intervals. This distance value reflects the cumulative area of the daily electricity bill distribution curve shifted to the right or left relative to the historical normal curve. The larger the area, the more users' electricity bills are simultaneously experiencing the same abnormal shift, indicating a group-wide billing logic error, rather than an individual user anomaly. Under normal operating conditions, W1 is typically between 0.5 and 2.0 yuan. When a deviation in the electricity pricing rules causes a structural shift in the bill, such as a misconfiguration of the peak-hour end time during daylight saving time from 15:00:00 to 14:00:00, peak-hour electricity consumption is mistakenly charged at peak electricity prices, resulting in a systemic increase in bill amounts for a large number of users, with W1 surging to over 5.0 yuan, triggering system detection.
[0108] Weighted path analysis and outlier score calculation, defining the weighted distance function:
[0109]
[0110] in, Two user feature vectors and The weighted Euclidean distance between them For the first Weights of dimensional features and The first two samples are respectively the first two samples. 3D eigenvalues; weight vector Electricity consumption and bill amount contributed the most, which was determined by the variance contribution rate of historical outlier samples.
[0111] The time decay factor applies to the weights of historical baseline samples, with the weight decreasing the further away from the current time.
[0112]
[0113] in, For historical samples in time Attenuation weight at the location, The current monitoring time is the Unix timestamp, and t is the time when the historical sample occurred. It is a natural constant. The attenuation coefficient is... This corresponds to a half-life of approximately 100 days, meaning the weight of samples from 100 days ago decays to [a certain value]. .
[0114] Based on weighted distance, the anomaly score for each sample point x is calculated using the improved isolated forest algorithm:
[0115]
[0116] in, For sample points Anomaly scores in an isolated forest with a sample size of N Let x be the expected value of the weighted path length of a sample point in each tree. Split points are selected based on the variance contribution rate of each dimension, with the electricity consumption and bill amount dimensions having a probability of 35% and 30%, respectively. The normalization term for the average path length of a binary search tree is calculated using the following formula:
[0117]
[0118] in, For the first Harmonic number, sample size That is, the total number of users on that day, in this embodiment Ten thousand households.
[0119] Single-sample anomaly detection logic:
[0120]
[0121] in, The threshold for single-sample anomaly detection; the preset threshold for single-sample anomaly detection. Based on historical data Calibration principle: Under normal operating conditions, 99.7% of the samples have anomaly scores below 0.62.
[0122] Assuming the global drift red alarm rule's abnormal sample percentage threshold is 0.5%, corresponding to 50,000 households, the global anomaly detection logic is as follows:
[0123]
[0124] If the percentage of global anomalies exceeds 0.5%, a global offset in the billing logic is determined, triggering a red alert. The specific distribution offset values are displayed on a graphical dashboard. Anomaly score for each sample point Global decision result The graphical dashboard highlights a heatmap showing the distribution of user groups that have experienced drift.
[0125] Once the percentage of the above-mentioned anomalies exceeds 0.5% and triggers a red alert, the system automatically enters the S5 structure causal root cause localization stage to accurately identify the real business process that caused the anomaly.
[0126] S5. Structural Causal Root Cause Localization: Upon identifying an anomaly in electricity billing calculation in a certain area, the tLiNGAM structural causal model is used to automatically learn a directed acyclic graph from multi-dimensional indicators, prioritizing file synchronization delay over loading of old billing rule versions over electricity billing calculation errors. Partial correlation testing is introduced to eliminate false alarms caused by sudden load surges due to extreme weather conditions, thereby accurately identifying whether the business disruption is due to incorrect peak electricity price parameter configuration or database connection pool exhaustion.
[0127] This step is automatically initiated after a red alert is triggered in S4, and multidimensional data within the abnormal time window is retrieved for causal analysis.
[0128] Obtain the multidimensional observation matrix within a set time window before and after the alarm trigger time, such as the time window from the first 30 minutes to the last 10 minutes. :
[0129]
[0130] in, For the first The variables at time... The observed values, Total number of variables: 8 performance indicators collected in step S2 The data includes the CDC synchronization delay in milliseconds for the five types of data tables in step S1, the average execution time of the ten key operators in step S3, and external temperature data obtained from the meteorological interface at an hourly granularity.
[0131] Cause-effect graph construction: based on observation data Perform mean-removal preprocessing.
[0132]
[0133] in, This is the mean-removed, centered matrix. This is the original observation matrix. Let be the expectation of the observation matrix, i.e., the mean vector.
[0134] Then, a whitening process is performed to obtain the whitening matrix. , This is the whitening transformation matrix. The FastICA algorithm is used to transform the whitening matrix... The separation matrix is estimated, yielding independent component estimates. The causal order of the variables is determined through stepwise regression: the variable with the strongest correlation between the independent component and the residuals of all other variables is selected as the first exogenous variable, removed, and the remaining variables are recursively processed until all variables are ordered. The causal strength matrix is then calculated. Transforming into strict lower triangular form yields a directed acyclic causal topological graph of "parameter configuration → operator execution → bill output", from which the causal strength matrix is output. Causality strength matrix (This is a 22×22 matrix, where non-zero elements represent causal edges between variables, and numerical values represent the causal strength.)
[0135] Partial correlation test and causal intervention analysis: using external temperature To control the variables, calculate Fixed power consumption With billing amount Partial correlation coefficient between :
[0136]
[0137] in, The Pearson correlation coefficient between electricity consumption and billing amount. The correlation coefficient between electricity consumption and temperature. The correlation coefficient between billing amount and temperature;
[0138] Significance test using Fisher's Z-transform:
[0139]
[0140] in, For statistical purposes, To control the external temperature Post-consumption of electricity With billing amount The partial correlation coefficient between them.
[0141] calculate Value: Statistic after FisherZ transformation Approximately follows the mean Standard deviation is The standard normal distribution, where The number of sample data pairs used in the partial correlation coefficient calculation. Convert to two-tailed test value:
[0142]
[0143] in, The cumulative distribution function of the standard normal distribution:
[0144]
[0145] In this embodiment, the specific value is calculated by calling Python's scipy.stats.norm.sf(abs(z_fisher))*2 or Java's org.apache.commons.math3.distribution.NormalDistribution.cumulativeProbability(z).
[0146] The significance test is used to exclude cases where normal peak summer electricity consumption is mistakenly identified as a calculation error: if If the null hypothesis that the partial correlation coefficient is zero is rejected, it is determined that there is a significant association between electricity consumption and billing amount driven by factors other than temperature, that is, the accounting anomaly is not solely caused by temperature; if If so, the null hypothesis is accepted, and the correlation is determined to be mainly driven by the common factor of temperature. In layman's terms, when the external temperature factor is fixed, the correlation between electricity load and normal electricity cost is no longer significant, indicating that temperature is the real common driving factor. That is, high summer temperature → increased air conditioning load → natural increase in electricity cost. This causal path should be excluded to avoid misjudging the normal summer peak electricity consumption as a billing error.
[0147] After incorporating the temperature node into the causal graph, perform causal intervention analysis—fixing the value of the temperature variable, i.e., the do operator: setting... Remove all pointers The edge,
[0148] After excluding the temperature factor, the causal strength matrix was recalculated. Differences before and after intervention:
[0149]
[0150] in, The causal strength matrix is the th Line 1 The absolute difference between the element values in the column before and after the intervention. and These are the first and second causal strength matrices before and after the intervention, respectively. Line 1 The element values of the column.
[0151] like threshold This indicates that the cause-effect relationship is mainly driven by common factors, and these factors should be eliminated and... Set to 0; otherwise, retain.
[0152] The structured root cause analysis results in the output of the top three candidate root cause variables and their causal strengths. For example, {"RootCause":"tou_time_period.end_time","ErrorType":"Parameter_Mismatch","CausalStrength":0.78,"Contribution":"45%"}, which precisely pinpoints the configuration error of the end time field in the time-of-use electricity pricing table.
[0153] Once the root cause is located, such as a mismatch in the tou_time_period.end_time field, the system automatically enters the S6 full-link lineage tracing and logic stress simulation stage, where the operators involved in the root cause are subjected to refined tracing and the corrected logic is simulated and verified.
[0154] S6. End-to-End Lineage Tracing and Logical Stress Simulation: A unified lineage identifier is introduced to heterogeneously associate the tiered logical updates in SQL stored procedures with the code commit IDs of Java accounting operators. When disputes arise, such as electricity bill refunds or subsidies, the logical context of the "moment of dispute occurrence" is reconstructed in an isolated sandbox through the mapping of TraceID and GTID. A simulated load is generated using a Long Short-Term Memory (LSTM) prediction model, and a pre-simulation of electricity price rule switching is conducted in the sandbox to verify the actual impact of the new policy implementation on system stress.
[0155] This step is automatically initiated after the specific root cause is located in S5. It performs operator-level tracing of the billing logic involved in the root cause and performs stress pre-testing and verification of the corrected logic in an isolated sandbox.
[0156] Root cause objects located by S5, such as the erroneous Java class TimeOfUseCalculator and its end_time field; disputed user's original electricity consumption data retrieved based on TraceID and GTID; the currently deployed billing operator code CommitID, such as a3f8e2c1; the SQL stored procedure version number, read from the Flyway table, such as V2.3.1; and hourly granular time-series electricity load data for each voltage level and electricity consumption type over the past 7 days.
[0157]
[0158] in, This represents the total number of time steps, corresponding to 7 days × 24 hours, each... It is a 6-dimensional vector, including residential 10kV, residential 35kV, general industrial and commercial 10kV, general industrial and commercial 35kV, large industrial 10kV, and large industrial 35kV, used to construct a lineage map.
[0159] Lineage graph construction: For each accounting request, a globally unique TraceID is generated at the entry point using MDC.put("traceId",UUID.randomUUID().toString()), which is then used throughout the entire call chain. During database writes, the transaction GTID is obtained via SELECT@@gtid_next. At application startup, the CommitID is obtained via gitrev-parseHEAD and cached. On the first database access, the highest-version stored procedure currently executed is queried from the flyway_schema_history table. .
[0160] Establish mapping relationship Where Timestamp is the timestamp of the calculation request, UserID is the user's unique identifier, and Amount is the calculated electricity bill amount.
[0161] Establish a bloodline chart , where the set of nodes edge set Indicates the data flow relationship; any user bill The entire path can be traced back:
[0162]
[0163] in, The raw battery data is located via GTID. For the corresponding version of the stored procedure logic, This corresponds to the Java operator logic. The graph is stored in the Neo4j graph database. The complete lineage path can be queried in milliseconds using TraceID. For example, from trace-20260716-143022-001, one can trace back to the TimeOfUseCalculator.calculate() method in GTID3E11FA47:1-1005 and CommitIDa3f8e2c1.
[0164] LSTM simulation load generation: The LSTM model structure specifically consists of the input layer. Each time step has 6-dimensional features; the first LSTM layer has 128 hidden units with return_sequences=True; the second LSTM layer has 128 hidden units with return_sequences=False; the dropout layer has a dropout rate of 0.2; the fully connected output layer has 6 neurons, corresponding to the prediction load of 6 user classes; the activation function is ReLU; the learner rate of the Adam optimizer is 0.001; the loss function is mean squared error (MSE); training is conducted for 100 epochs with an early stopping strategy: the validation set loss stops if it does not decrease for 10 consecutive epochs. Training is performed using historical load data from the past 90 days, with 80% as the training set and 20% as the validation set, employing a sliding window—predicting the next 24 hours based on the past 168 hours.
[0165] The LSTM model outputs simulated load data for the next 24 hours:
[0166]
[0167] in, For the predicted load sequence for the next 24 hours, to These represent the predicted load values for hours 169 to 192, each a 6-dimensional vector, for a total of 24 time points.
[0168] Stress simulation verification: Deploy the revised accounting logic, such as changing end_time from 14:00:00 to 15:00:00, to the isolation sandbox. Use the 24-hour simulated load data generated by LSTM. Data is injected into the sandbox mirror layer in chronological order—written to the meter_reading simulation table at hourly granularity. Each record contains user ID, timestamp, electricity consumption, voltage level, and electricity usage type. This drives the twin to run the corrected billing process, simulating continuous billing for 24 hours.
[0169] Monitor five performance metrics and compare them with historical benchmarks from step S2: CPU utilization ≤ 80%, heap memory utilization ≤ 75%, average processing time per bill ≤ 200ms, active database connection pool ≤ 70% of maximum connection count (maximum connection count 200), and transaction processing per second (TPS) ≥ 1.5 times the production peak (production peak 500 TPS, target ≥ 750 TPS). If all metrics are ≤ 120% of the benchmark value and the number of ERROR-level logs is 0, the simulation passes. Output a complete lineage graph database (e.g., using Neo4j storage); a 24-hour simulated load curve generated by LSTM; a sandbox simulation performance evaluation report, including scatter plots of TPS throughput and response time; and simulation status flags. .
[0170] Once the pre-rehearsal status is PASS, the system automatically enters the S7 closed-loop strategy self-correction and security deployment phase; if the pre-rehearsal fails, it automatically switches to manual intervention mode, where engineers adjust and correct the strategy before re-executing the S6 pre-rehearsal.
[0171] Third, the revised accounting logic, which has passed the stress simulation verification, is sent to the production end.
[0172] S7. Closed-Loop Strategy Self-Correction and Secure Distribution: System-generated parameter correction strategies, such as automatically correcting erroneous electricity price version numbers, must be verified through the command gateway. The gateway compares the simulated billing amount in the twin with the historical average in the production environment; if the difference exceeds 5%, it will forcibly block the process. For sensitive transactions involving price adjustments, a dual-person review logic must be triggered. Only after verification in an isolated environment can the strategy be distributed to the production system from the reverse control layer, achieving closed-loop risk management. If the simulated billing verification fails, the system will trigger an alarm and switch to manual intervention mode.
[0173] This step is automatically initiated after the S6 pre-run passes, and the verified and effective correction strategies are distributed to the production system through the security isolation barrier to complete the closed-loop governance.
[0174] Step S6 pre-review and verification of the correction strategy—structured JSON instruction format, for example, the correction instruction generated when the root cause is located in the mismatch of the end time of the time-of-use electricity pricing table:
[0175] {
[0176] "operationId":"FIX-20260716-001",
[0177] "operationType":"UPDATE",
[0178] "target":"tou_time_period",
[0179] "conditions":{"voltage_level":10,"season":"SUMMER","period_type":"PEAK"},
[0180] "changes":{"end_time":"15:00:00","price_rate":1.50},
[0181] "reason":"Root cause identification: Peak period end time misconfigured (causality strength 0.78)",
[0182] "timestamp":"2026-07-16T14:30:22Z"
[0183] }
[0184] Command verification gateway verification: The first step is to execute a simulated billing in the mirrored data layer of the twin, using the correction logic that has passed the S6 pre-run verification, to calculate the total electricity bill for all users after the simulated billing. :
[0185]
[0186] in, For the first The simulated bill amount for each user after applying the correction strategy in the twin, where N is the total number of users on that day. (This embodiment...) Ten thousand households.
[0187] The second step is to retrieve the historical average values of the production environment:
[0188]
[0189] in, This represents the historical average total electricity cost. The total number of users on that day. The historical days selected are those within the most recent 7 days before the correction that were without anomalies, excluding the alarm date and the day before and after it. For the first Heavenly The actual bill amount for each user.
[0190] The third step is to calculate the deviation rate. :
[0191]
[0192] Judgment logic: when When the automatic threshold check passes. If the deviation can be reasonably explained by the expected price adjustment range in the policy announcement (e.g., the policy announcement requires an 8% increase in peak electricity prices), then the theoretical price adjustment range will be compared with the pre-entered data. ,like If it passes, then allow it; otherwise, forcibly block it.
[0193] Dual-person review and approval: For sensitive correction strategies involving changes to electricity price standard values or tiered threshold changes, the system automatically triggers a dual-person review mechanism: sending review request cards to two billing experts with approval authority. The cards include a summary of the simulated billing results and the deviation rate. Distribution drift detection score. Reviewers independently view the simulation results on the twin monitoring interface, and after confirming their accuracy, enter their electronic signatures to complete the approval process. Only after both reviewers have approved the results can the distribution process begin.
[0194] Secure write-back deployment: Policies verified through the gateway and double-checked are deployed from the reverse control layer to the production configuration center (Apollo / Nacos) via a RESTful API. The RESTful API uses HTTPS two-way authentication and is located at ` / api / v1 / config / publish`. The configuration center uses the `@ApolloConfigChangeListener` mechanism to monitor and refresh the production application parameter cache in real time. If the modification targets operator code, a blue-green deployment approach is used—the new version is deployed to the green environment, verified, and then the traffic is switched before updating the blue environment.
[0195] Abnormal fallback and manual intervention bypass path: If Furthermore, if the issue cannot be explained by policy adjustments, i.e., the simulated billing verification fails or the dual review is not approved, the system will automatically perform the following fallback operation before switching to manual intervention mode:
[0196] 1) Combine the root cause analysis results from S5, the pre-run verification data from S6, and the simulated accounting deviation rate. Wasserstein distance value Once the "Anomaly Analysis Report" (PDF format) is generated, it will be sent to the maintenance duty team and billing expert team via email and WeChat Work.
[0197] 2) Highlight the IP address of the accounting node that has an anomaly and the time window of the anomaly in the twin monitoring dashboard, and display the anomaly distribution details by operator dimension for quick location during manual investigation;
[0198] 3) After manual repair is completed, the maintenance engineer can upload the repair script SQL or code patch through the management interface. The system will automatically re-execute the S6 pre-run and S7 verification process. Only after the verification is passed can the distribution process begin.
[0199] This fallback path ensures that the system still has full fault handling capabilities even when automated correction fails the security check, preventing process blockage due to automation failure.
[0200] Finally, the correct configuration parameters are written into the production environment, such as... , The log includes a closed-loop self-healing work order log covering the entire lifecycle from alarm to location, pre-simulation, and issuance; the production system's billing distribution has returned to normal, and the Wasserstein distance has fallen back to [value missing]. Yuan.
[0201] After the correction command is successfully sent to the production system, the system automatically returns to S1 to enter the next monitoring cycle, re-monitoring the consistency of the mirrored data and the billing distribution status. Thus, the process from S1 to S7 is completed as follows: Figure 1The complete closed-loop monitoring and self-correction process shown realizes full-link automated closed-loop governance, from anomaly detection to root cause localization, pre-simulation verification, policy correction, security deployment, and effect verification.
[0202] Example 2
[0203] Based on the digital twin-based data usage and billing service flow monitoring and self-correction method described in Embodiment 1, this embodiment provides a digital twin-based data usage and billing service flow monitoring and self-correction system, including a storage medium and a processor; the storage medium is used to store instructions; the processor is used to perform operations according to the instructions to execute the digital twin-based data usage and billing service flow monitoring and self-correction method described in Embodiment 1.
[0204] Those skilled in the art will understand that embodiments of this application can be provided as methods, systems, or computer program products. Therefore, this application can take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, this application can take the form of a computer program product embodied on one or more computer-usable storage media (including, but not limited to, disk storage, CD-ROM, optical storage, etc.) containing computer-usable program code.
[0205] This application is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of this application. It will be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, generate instructions for implementing the flowchart... Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.
[0206] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The function specified in one or more boxes.
[0207] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.
[0208] The embodiments of the present invention have been described above with reference to the accompanying drawings. However, the present invention is not limited to the specific embodiments described above. The specific embodiments described above are merely illustrative and not restrictive. Those skilled in the art can make many other forms under the guidance of the present invention without departing from the spirit and scope of the claims. All of these forms are within the protection scope of the present invention.
Claims
1. A method for monitoring and self-correcting the data-driven billing process based on digital twins, characterized in that, include: Read the volume and fee accounting business flow from the production end and extract the volume and fee accounting parameters from the production end. Use these parameters as input to construct a bidirectional closed-loop volume and fee accounting business digital twin with the same architecture as the production end, so as to achieve parameter alignment between the production end and the twin end. The quantity and cost accounting results on the production side are verified based on the quantity and cost accounting parameters. When the verification result meets the set alarm threshold, the structural cause and effect root cause location is triggered to identify the real business link that caused the accounting anomaly and to trace the accounting source. Based on the set monitoring indicators, the revised accounting logic is subjected to stress pre-performance verification. The revised accounting logic, which has passed the stress simulation verification, is then sent to the production end. This includes verifying the quantity and cost accounting results on the production side based on quantity and cost accounting parameters, including: The daily distribution of the data usage and fee calculation parameters Compared with historical baseline All sample values are merged and sorted in ascending order to obtain a unique sorted value sequence. , The number of unique values is calculated; the daily distribution is calculated separately. Compared with historical baseline In value sequence Cumulative distribution function on: in, Distribution for the day The cumulative distribution function on the given value sequence Historical baseline Take any value The cumulative distribution function value at that location, The total number of users on that day. This represents the total number of historical baseline samples; Calculate the first-order Wasserstein distance: in, Distribution for the day Compared with historical baseline The first-order Wasserstein distance, The first unique value in the sorted sequence Each possible value The first unique value in the sorted sequence Each possible value Distribution for the day exist The cumulative distribution function value at that location, Historical baseline exist The cumulative distribution function value at that location; Based on weighted distance, the anomaly score for each sample point x is calculated using the improved isolated forest algorithm: in, For sample points With a sample size of Outlier scores in isolated forests For sample points The expected value of the weighted path length in each tree. This is the normalization term for the average path length of a binary search tree. , For the first Harmonic number, sample size That is, the total number of users on that day; Single-sample anomaly detection logic: in, This is the threshold for single-sample anomaly detection; If the threshold for the percentage of abnormal samples in the global drift red alarm rule is set at 0.5%, then the global anomaly detection logic is as follows: The specific distribution offset values are displayed through a graphical dashboard. Anomaly score for each sample point Global decision result ; Structural causal root cause localization includes: Obtain the multi-dimensional observation matrix for a set time period before and after the alarm trigger time. For multidimensional observation matrix After performing mean-removal preprocessing, whitening is then performed to obtain the whitening matrix. Using the FastICA algorithm to extract from the whitening matrix The separation matrix is estimated to obtain the independent component estimates; the causal order of the variables in the independent component estimates is determined by stepwise regression, and the causal strength matrix B is output. external temperature To control the variables, calculate Fixed power consumption With billing amount Partial correlation coefficient between : in, The Pearson correlation coefficient between electricity consumption and billing amount. The correlation coefficient between electricity consumption and temperature. The correlation coefficient between billing amount and temperature; Significance test using Fisher's Z-transform: in, For statistical purposes, To control the external temperature Post-consumption electricity With billing amount The partial correlation coefficient between them; calculate Value: Statistic after Fisher Z transformation Approximately follows the mean Standard deviation is The standard normal distribution, where The number of sample data pairs used in the partial correlation coefficient calculation; Convert to two-tailed test value: in, The cumulative distribution function of the standard normal distribution: The significance test is used to exclude cases where normal peak summer electricity consumption is mistakenly identified as a calculation error: if If the null hypothesis that the partial correlation coefficient is zero is rejected, it is determined that there is a significant association between electricity consumption and billing amount driven by factors other than temperature; if If so, the null hypothesis is accepted, and the association is determined to be mainly driven by the common factor of temperature. This causal path should be excluded to avoid misjudging the normal peak electricity consumption in summer as a billing error. After excluding the temperature factor, the causal strength matrix was recalculated. Differences before and after intervention: in, The causal strength matrix is the th Line number The absolute difference between the element values in the column before and after the intervention. and These are the first and second causal strength matrices before and after the intervention, respectively. Line number The element values of the column; like threshold If the cause-effect relationship is mainly driven by common factors, it should be eliminated; otherwise, it should be retained. Output the top three candidate root variables and their causal strength; For root cause objects identified based on structural causal root cause localization, a source tracing process is performed. For each tracing request, a globally unique TraceID is generated at the entry point and persists throughout the entire call chain. The transaction GTID is obtained during database writes; the CommitID is obtained and cached during application startup; and the version number of the highest-performing stored procedure is queried during the first database access. ; Establish mapping relationship ;in, To calculate the timestamp of the request, A unique identifier for the user. This is the calculated electricity bill amount; Establish a bloodline chart , where the set of nodes edge set Indicates the data flow relationship; any user bill Backtracking through the complete path: in, The raw battery data located via GTID. For the corresponding version of the stored procedure logic, This corresponds to the Java operator logic.
2. The method for monitoring and self-correcting the data-driven billing process based on digital twins as described in claim 1, characterized in that, A MerkleTree-based hash verification mechanism is used to align parameters between the production and twin ends, including: Arrange all records of the time-of-use electricity pricing tables of the production end and the twin end in ascending order by primary key to obtain an ordered record sequence; A data block is formed by taking a number of ordered record sequences as a data block. For each data block, the field values of all its records are concatenated in a set order to form a string S_block. Calculate the SHA-256 hash value of the string S_block and use it as the leaf node hash of the data block. ; Take all leaf node hashes as the bottom layer, concatenate the hashes of two adjacent leaf nodes and calculate SHA-256 again, build a binary Merkle Tree layer by layer upwards, and finally obtain the root node hash value H_root; Perform the same sorting, block and hash calculation process on the same data table to obtain the production end root hash H_root and the twin end root hash H_root' respectively. If H_root and H_root' are inconsistent, the difference localization process begins—recursively comparing the hashes of the left and right child nodes from top to bottom along the MerkleTree. The comparison continues downwards through the child node branch where the hashes are inconsistent, until the specific leaf node with the data difference is located, i.e., the corresponding data block. Then, all records within that data block are compared row by row, comparing the primary key and each field value to precisely locate the inconsistent record row and the differing field. Next, the current value of that record is retrieved from the production end, and incremental repair is performed on the twin. After repair, the hash values of each node on the path from the leaf node to the root node are recalculated, and the root hash is verified again until they are consistent.
3. The method for monitoring and self-correcting the data-driven billing process based on digital twins as described in claim 1, characterized in that, Define monitoring indicators for each stage of the data collection and billing process on the twin platform, including: Meter reading process: Monitoring the success rate of remote meter reading via monitoring terminals and the completeness of load curves; Billing process: monitoring the accuracy of tiered billing and processing the execution time of multi-rate billing for large industrial users using distributed operators; Review process: Define the intelligent review interception rate; Billing process: Monitor the success rate of bill generation for tens of millions of users and the peak IO throughput.
4. The method for monitoring and self-correcting the data-driven billing process based on digital twins as described in claim 3, characterized in that, Non-intrusive anonymization processing is performed on the data usage and cost accounting workflow on the twin platform, including: Using bytecode dynamic instrumentation or non-intrusive proxy technology, the billing execution snapshot is captured before and after the "electricity billing calculation function", and dynamic desensitization is performed on sensitive user identifiers; the user's real name, detailed electricity address, and load readings accurate to the household are identified and encrypted in order.
5. The method for monitoring and self-correcting the data-driven billing process based on digital twins according to claim 4, characterized in that, The revised accounting logic was subjected to stress simulation verification, including: The revised accounting logic is redeployed to the twin client; the twin client is driven to run the revised billing process to simulate continuous billing results for a future set time period; The billing results are evaluated according to the defined monitoring indicators for each stage of the data collection and billing process. If all monitoring indicators are ≤120% of the baseline value and the number of ERROR-level logs is 0, the pre-run is considered successful.
6. The method for monitoring and self-correcting the data-driven billing process based on digital twins according to claim 5, characterized in that, The revised accounting logic, verified through stress simulation, is then sent to the production side, including: The revised accounting logic, which has passed the stress simulation verification, undergoes command gateway verification and dual-person review and approval. After the command gateway verification and dual review and approval are passed, the command is sent from the reverse control layer to the production configuration center on the production side. The production configuration center senses and refreshes the production application parameter cache in real time. If the simulated billing verification fails or the dual review is not approved, the system will automatically perform the following fallback operation before switching to manual intervention mode: 1) Generate an anomaly analysis report and send it to the maintenance team and the billing expert group; 2) Mark the IP address of the accounting node that caused the anomaly and the time window of the anomaly in the monitoring instrument panel of the twin end for manual investigation and location.
7. A data-driven billing and accounting business flow monitoring and self-correction system based on digital twins, characterized in that, Including storage media and processor; The storage medium is used to store instructions; The processor is configured to operate according to the instructions to execute the digital twin-based data flow monitoring and self-correction method for data volume and cost accounting as described in any one of claims 1 to 6.
Citation Information
Patent Citations
Electric charge settlement optimization method, device and equipment
CN121836127A
Intelligent distribution box self-healing fault diagnosis method and system
CN122153710A
