An abnormal event monitoring method for an agricultural product traceability chain

By establishing batch coding rules and event type dictionaries for agricultural product traceability links, deploying sensing devices and edge computing gateways, and constructing a multimodal anomaly detection model, the problems of limited coverage, delayed response, and insufficient data reliability in traditional agricultural product quality monitoring have been solved, achieving efficient and reliable anomaly event monitoring and source tracing.

CN121961354BActive Publication Date: 2026-06-09INST OF SOIL & FERTILIZER FUJIAN ACADEMY OF AGRI SCI +1

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
INST OF SOIL & FERTILIZER FUJIAN ACADEMY OF AGRI SCI
Filing Date
2026-03-30
Publication Date
2026-06-09

AI Technical Summary

Technical Problem

Traditional agricultural product quality monitoring suffers from problems such as limited monitoring coverage, delayed response, low traceability accuracy, insufficient multimodal data fusion capabilities, low accuracy in anomaly detection, and insufficient data reliability assurance.

Method used

By adopting batch coding rules and event type dictionaries, a traceability relationship model is established, sensor data acquisition devices and edge computing gateways are deployed, and time series prediction, visual anomaly, rule anomaly and graph anomaly models are constructed. Multimodal data fusion and anomaly detection are carried out, alarm packages are generated through evidence fusion strategy, and source location and impact range assessment are performed based on the traceability relationship model.

Benefits of technology

It has improved the efficiency and reliability of monitoring abnormal agricultural product quality, ensured the tamper-proof and traceability of data, significantly shortened response time, reduced the scope of blind recalls and over-treatment, and improved the accuracy of recalls/isolation and the efficiency of resource utilization.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121961354B_ABST
    Figure CN121961354B_ABST
Patent Text Reader

Abstract

This invention relates to the field of agricultural product quality monitoring, specifically to a method for monitoring abnormal events in the agricultural product traceability chain, comprising: S1: defining batch coding rules and an event type dictionary, and establishing a traceability relationship model; S2: based on the traceability relationship model, deploying sensor data acquisition devices at key control points in the agricultural product traceability chain, and deploying edge computing gateways at each location to complete the reliable uploading of data to the blockchain; S3: unifying data from different sources to a standard timeline, establishing association keys by batch, location, and device, and preprocessing the data; S4: constructing an anomaly detection model, including time-series prediction, visual anomaly, rule-based anomaly, and graph anomaly models, and performing anomaly detection based on the preprocessed data; S5: calculating risk scores using an evidence fusion strategy and obtaining output alarm packets; S6: based on the output alarm packets, performing source tracing and impact range assessment based on the traceability relationship model. This invention effectively improves the efficiency and reliability of agricultural product quality anomaly monitoring.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of agricultural product quality monitoring, and in particular to a method for monitoring abnormal events in the agricultural product traceability chain. Background Technology

[0002] Traditional agricultural product quality monitoring mainly relies on manual sampling, paper records, and post-event traceability. This has technical bottlenecks such as limited monitoring coverage, delayed response, and low traceability accuracy, making it difficult to meet the regulatory requirements of the complex and large-scale modern agricultural product supply chain.

[0003] Current agricultural product traceability and monitoring technologies face the following main technical challenges: First, the problem of multimodal data fusion in data collection. Agricultural product quality involves various heterogeneous data such as environmental parameters, process parameters, appearance characteristics, and testing data. Traditional systems lack effective multimodal data fusion and analysis capabilities, resulting in low accuracy in anomaly detection. Second, the problem of balancing real-time performance and accuracy in anomaly detection. Existing methods often use fixed thresholds or single models for anomaly judgment, which easily leads to high false alarm and false negative rates in the face of complex and ever-changing agricultural production environments. Third, the problem of the accuracy of anomaly tracing. Traditional traceability systems mainly rely on batch flow records for linear backtracking, lacking the ability to deeply analyze complex supply chain network relationships, making it difficult to accurately locate the source of anomalies and assess the scope of impact. Fourth, the problem of data credibility assurance. The traceability chain involves multiple entities and links, and data is easily tampered with or falsified, lacking effective mechanisms to ensure data integrity and authenticity. Summary of the Invention

[0004] To address the aforementioned problems, the present invention aims to provide an abnormal event monitoring method for agricultural product traceability links, effectively improving the efficiency and reliability of agricultural product quality anomaly monitoring.

[0005] To achieve the above objectives, the present invention adopts the following technical solution:

[0006] A method for monitoring abnormal events in the agricultural product traceability chain includes the following steps:

[0007] S1: Define batch coding rules and event type dictionary, and establish a traceability relationship model;

[0008] S2: Based on the traceability relationship model, sensor data acquisition devices are deployed at key control points in the agricultural product traceability chain, and edge computing gateways are deployed at each location to complete the trusted uploading of data to the blockchain.

[0009] S3: Unify data from different sources to a standard timeline, establish association keys by batch, location, and device, and preprocess the data;

[0010] S4: Construct anomaly detection models, including time-series prediction, visual anomaly, rule-based anomaly, and graph anomaly models, and perform anomaly detection based on preprocessed data;

[0011] S5: Unify the four types of results—time series model, visual model, rule hit, and graph anomaly—into an evidence vector, use an evidence fusion strategy to calculate the risk score, and obtain the output alarm package;

[0012] S6: Based on the output alarm packet, perform source tracing and impact assessment based on the traceability relationship model.

[0013] Furthermore, the definition of batch coding rules and event type dictionary is as follows: A unified batch coding rule is established, employing a multi-level coding structure to generate globally unique BatchID identifiers. The batch coding rule design adopts a six-segment coding format: category code - origin code - date code - field code - producer code - process version code. The event type dictionary covers the entire lifecycle of agricultural products, including production events, processing events, storage events, logistics events, sales events, and complaint events. Each type of event defines a standard event template and data format.

[0014] Furthermore, the traceability relationship model is based on graph theory. The graph structure design uses a directed acyclic graph to represent the batch flow relationship. Nodes represent specific batches, and edges represent conversion relationships. Each node contains BatchID, timestamp, geographical location, and responsible entity attributes. Each edge contains conversion type, conversion ratio, and quality loss attribute information. The relationship type definition includes direct conversion relationship, split relationship, merge relationship, packaging relationship, and storage relationship.

[0015] Furthermore, based on the traceability relationship model, sensor data acquisition devices are deployed at key control points in the agricultural product traceability chain, and edge computing gateways are deployed at each location to complete the trusted uploading of data to the blockchain, as detailed below:

[0016] The graph node-based sensor deployment strategy configures the appropriate type and number of sensors for each node based on the node type and node attributes in the traceability relationship model.

[0017] The data association design based on graph edge relationships targets the edge relationships in the traceability relationship model, deploying associated sensors at the corresponding operation points to ensure data continuity during batch conversion; the data identification and batch binding mechanism uses BatchID, NodeID, and EdgeID to identify the data collected by each sensor in three dimensions.

[0018] Edge computing gateways are deployed at each location node in the traceability relationship model to construct a distributed computing architecture that matches the graph structure. Based on the graph topology, the collaborative computing mechanism establishes communication connections between each edge gateway according to the adjacency relationship in the traceability relationship model, forming a computing network topology consistent with the traceability graph structure. The edge gateways of the upstream nodes transmit the processed data and features to the downstream nodes. The downstream nodes can perform correlation analysis and anomaly detection based on the upstream information, realizing cross-node collaborative reasoning and early warning.

[0019] A blockchain evidence storage mechanism deeply integrated with the traceability relationship model is established. The on-chain storage strategy of graph structure data uses the graph structure information in the traceability relationship model as the basic data structure of the blockchain. The generation, transformation and circulation events of each batch are recorded on the chain in the form of smart contracts to ensure the immutability of the traceability relationship. At the same time, the hash values ​​of key data collected by sensors are organized and stored according to the graph structure to form a digital evidence chain consistent with the physical traceability path.

[0020] Furthermore, the establishment of association keys by batch, location, and device is specifically as follows: The batch-level association key design uses BatchID defined in S1 as the primary key to establish a batch-level index: raw material batches, intermediate batches, and finished product batches form a tree-like association structure, supporting parent-child relationship queries between batches, aggregate queries of batches from the same source, and batch lifecycle tracking queries; simultaneously, a batch time window index is established to associate related batches with overlapping times, supporting cross-contamination analysis and parallel processing monitoring; the location-level association key design establishes a multi-level coding system for geographical locations; for mobile scenarios, trajectory segmentation technology is adopted to divide continuous GPS trajectories into spatial-temporal blocks according to time windows and geofences, establishing dynamic location association keys; the device-level association key design establishes a unique device ID for each data acquisition device, including device type, manufacturer, model, serial number, deployment location, and calibration status attribute information; a device capability matrix is ​​established to record the types of indicators that each device can collect, accuracy levels, and acquisition frequency technical parameters.

[0021] Furthermore, a time-series prediction and visual anomaly detection model for agricultural product traceability scenarios is constructed to perform intelligent anomaly identification on continuous monitoring data and image data, as detailed below:

[0022] The time series prediction anomaly detection model employs a multivariate time series prediction network based on the Transformer architecture, combined with LSTM-Autoencoder and GRU-VAE models to construct an integrated prediction framework. The model input includes multidimensional time series data, and captures long-term and short-term dependencies and mutual influences between variables through a self-attention mechanism to predict the numerical change trend within future time windows. Anomaly detection is achieved through a triple criterion of reconstruction error, prediction residual, and probability distribution deviation: when the deviation between the actual observed value and the predicted value exceeds a dynamic threshold, an anomaly alarm is triggered.

[0023] The visual anomaly detection model is based on a deep convolutional neural network and the Vision Transformer architecture, and constructs a multi-scale feature fusion visual anomaly detection system; it includes a defect detection subnetwork, a quality assessment subnetwork, and an abnormal behavior detection subnetwork.

[0024] Furthermore, the visual anomaly detection model is based on a deep convolutional neural network and a Vision Transformer architecture, constructing a multi-scale feature fusion visual anomaly detection system, as detailed below:

[0025] The backbone network architecture was designed using EfficientNet-B4 as the basic feature extractor, and model performance was optimized by uniformly scaling the network depth, width, and resolution. The network depth was calculated according to α. φ Scaling, network width according to β φ Scaling, input resolution according to γ φ Scaling, where φ is the composite coefficient, ultimately yields multi-layer feature maps at different resolutions, which can effectively capture rich feature information from fine-grained texture to coarse-grained semantics;

[0026] The feature pyramid network fusion mechanism uses a top-down path and lateral connections to construct a feature pyramid. High-level semantic features are fused with low-level detail features through upsampling. The features of each pyramid layer are aligned through 1×1 convolution dimensionality reduction and upsampling operations, ultimately generating a five-layer feature pyramid for anomaly detection tasks at different scales.

[0027] The multi-scale receptive field enhancement module introduces a dilated spatial pyramid pooling module after each feature map layer. It uses 3×3 convolutional kernels with different dilation rates to process the feature maps in parallel. It captures contextual information at different scales through convolutional branches of different receptive fields. Finally, it fuses multi-scale information through feature concatenation and 1×1 convolution.

[0028] The Vision Transformer branch is introduced to learn the global spatial relationships and long-range dependencies of images. It is deeply fused with local features of CNN to enhance the global understanding of anomaly detection. The ViT branch architecture and patch embedding mechanism divide the input image into a fixed-size patch sequence. Each patch is mapped to a high-dimensional vector representation through linear projection. At the same time, learnable classification tokens and positional codes are added to form a complete input sequence that is fed into the Transformer encoder. The patch embedding process preserves spatial positional information, enabling the model to learn the spatial relationships between different regions and global contextual information. The Transformer encoder uses a multi-head self-attention mechanism to learn the relationships between patches. Attention weights are calculated through the interaction of three matrices: query, key, and value. Each attention head focuses on a different feature subspace. Twelve attention heads process in parallel and are finally fused.

[0029] The CNN-ViT cross-modal feature fusion strategy is designed with a cross-attention fusion module to achieve effective interaction between CNN local features and ViT global features. Through the cross-attention mechanism, CNN features focus on the globally important regions learned by ViT, while ViT features focus on the local details captured by CNN. The two types of features are weighted and fused through element-wise multiplication and then processed by convolutional layers to finally obtain a fused feature representation that has both local accuracy and global consistency.

[0030] A multi-task detection head is constructed to simultaneously handle three sub-tasks: defect detection, quality assessment, and anomaly localization. End-to-end visual anomaly detection for agricultural products is achieved through joint loss function optimization. The decoupling of the defect detection head is based on an improved YOLO detection framework. The decoupled detection head separately predicts classification probabilities, bounding box regression parameters, and target confidence. The classification branch outputs multi-class defect probabilities through a sigmoid activation function, the regression branch directly outputs the position and size offset of the bounding box, and the confidence branch predicts the probability that the detection box contains the true target. The quality assessment head uses global average pooling to compress two-dimensional feature maps into one-dimensional feature vectors through global feature aggregation. A multilayer perceptron is then used to predict the classification of agricultural product quality levels, including maturity assessment, freshness assessment, and overall quality rating—multi-dimensional quality indicators—providing intelligent support for agricultural product grading and pricing.

[0031] Furthermore, rule-based and graph-based anomaly detection models based on expert knowledge and relationship mining are constructed to accurately identify compliance violations and supply chain structural anomalies, as detailed below:

[0032] The rule anomaly detection model constructs a multi-level rule engine system, including a regulatory compliance rule layer, an enterprise standard rule layer, and a logical consistency rule layer. The rule engine uses the Rete algorithm for real-pattern matching and inference, supporting condition combination, temporal logic, and numerical calculation. At the same time, a rule confidence evaluation mechanism is established to dynamically adjust rule weights based on historical verification results and expert feedback.

[0033] The graph anomaly detection model is based on graph neural networks and graph embedding technology to detect structural anomalies in traceability relationship networks. It constructs a dynamic supply chain graph using BatchID as nodes and flow relationships as edges, and learns the representation vectors of nodes and edges through graph neural networks. Anomaly detection is achieved through three dimensions: graph structure change detection, node behavior anomaly detection, and path anomaly detection.

[0034] Furthermore, the four types of results—time series model, visual model, rule hit, and graph anomaly—are unified into an evidence vector. An evidence fusion strategy is then used to calculate the risk score and obtain the output alarm packet, as detailed below:

[0035] The four types of heterogeneous detection results are converted into standardized evidence vectors, where the evidence vector structure design defines a unified evidence vector e. i Including the abnormal confidence level c i ∈[0,1], severity of anomaly s i ∈[0,1], Evidence credibility r i ∈[0,1], time urgency t i ∈[0,1, Spatial influence range a i ∈[0,1], historical consistency h i ∈[0,1] and business criticality b i ∈[0,1], forming e i =[c i ,s i ,r i ,t i ,a i ,h i ,b i ] T ;

[0036] The time-series model evidence vector transformation and time-series anomaly detection results are transformed using the following mapping function: Anomaly Confidence:

[0037] ;

[0038] in, For the predicted value, y t For the actual observed value, σ t Historical standard deviation; severity of outliers Calculation based on the 3σ criterion; credibility of evidence Based on model validation error calculation; time urgency t ts =exp(-λΔt) decays according to the duration of the anomaly;

[0039] Among them, MSE validation λ is the mean squared error of the time series model on the validation set; λ is the decay coefficient.

[0040] The formula for converting visual detection results from evidence vectors in a visual model is: Anomaly Confidence. Select the highest confidence detection box; anomaly severity Calculated based on the percentage of defective area;

[0041] Among them, conf j cls represents the target confidence of the j-th detection box. j The class confidence score for the j-th bounding box; max j (·) indicates taking the maximum value among all test results; area j Let be the area of ​​the j-th anomaly detection box; total_area is the reference total area;

[0042] Rule and graph model evidence vector transformation rule hit is converted to:

[0043]

[0044] Based on rule-weighted average;

[0045] The graph anomaly was converted to: Standardize,

[0046] Where μ and σ are the mean and standard deviation of historical outlier scores; w k The weight of the k-th rule; hit k This is the hit indication for the k-th rule; anomaly_score is the raw anomaly score output by the graph anomaly model.

[0047] An improved DS evidence theory is employed to achieve intelligent fusion of multi-source evidence. The comprehensive anomaly probability is calculated through combined reasoning using a trust function and a likelihood function. The basic probability assignment function is used to construct each evidence vector e. i Construct the basic probability assignment function m i Define the recognition framework Θ:

[0048] Θ={Normal, Abnormal, Unknown};

[0049] Wherein, Normal represents the normal hypothesis; Abnormal represents the abnormal hypothesis; and Unknown represents the unknown hypothesis.

[0050] The basic probability assignment calculation formula is as follows:

[0051] ;

[0052] Among them, w i For model weights; m i (·) represents the basic probability assignment for the i-th source of evidence; c i r represents the anomalous confidence level of the i-th source of evidence; i Let be the credibility of the i-th source of evidence;

[0053] Conflict coefficient calculation and conflict resolution: Calculating the conflict coefficient between pieces of evidence.

[0054] ,

[0055] When K > preset value, the evidence is considered highly conflicting; A and B are sets of propositions from the power set Θ of the identification framework; It is an empty set;

[0056] For multiple evidence sources, the recursive evidence fusion algorithm employs a recursive fusion strategy: first, it sorts the evidence sources by their credibility. Then calculate recursively:

[0057] ;

[0058] Where ⊕ is the DS combination operator;

[0059] m 1:k The m represents the composite BPA after fusing the first k evidence sources; k+1 The BPA for the (k+1)th (k+1)th evidence source; m 1:k+1 This represents the new composite BPA after incorporating the (k+1)th piece of evidence;

[0060] Trust function for the final fusion result:

[0061] Bel(Abnormal) = m(Abnormal);

[0062] Where Bel(Abnormal) is the trust function value for the abnormal proposition; m(Abnormal) is the quality of the fused basic probability assignment BPA on the abnormal proposition;

[0063] Likelihood function:

[0064] Pl(Abnormal) = 1 - m(Normal);

[0065] Wherein, Pl (Abnormal) is the upper bound of the likelihood of "abnormal propositions"; m (Normal) is the quality of the fused BPA on normal propositions;

[0066] Overall anomaly probability:

[0067] ;

[0068] Finally, the risk score is calculated based on the overall anomaly probability, and a structured alarm package is generated.

[0069] Furthermore, based on the output alarm packet, source tracing and impact assessment are performed using a traceability relationship model, as follows: Based on the traceability relationship model constructed in S1, the abnormal batches in the alarm packet are accurately traced and located. The root node and propagation path of the anomaly are tracked using a graph traversal algorithm. The impact range of the abnormal event is dynamically assessed using a graph propagation algorithm and a risk diffusion model, predicting potential risk propagation paths and the range of affected batches. The forward impact propagation path is calculated starting from the source node of the anomaly and proceeding along the forward edges of the traceability relationship graph. A modified PageRank algorithm is used to calculate the probability of each downstream node being affected. Based on the impact range assessment results, all potentially affected batches are identified, and differentiated emergency response strategies and handling recommendations are generated according to the risk level.

[0070] The present invention has the following beneficial effects:

[0071] 1. This invention uses batch coding rules, event type dictionaries and traceability relationship models as a unified semantic foundation to ensure that data across subjects and links can be consistently interpreted and associated within the same batch-event-relationship framework; and completes trusted on-chain data collection through key control point sensing and site edge gateways, so that the collected data has the evidentiary attributes of being tamper-proof, verifiable and traceable.

[0072] 2. This invention unifies multi-source data into a standard timeline and establishes association keys based on batch, location, and device, aligning four types of information—time series, visual, rule-based, and graph structure—under the same indexing system. It captures continuous change anomalies using time series prediction, identifies appearance defects and operational anomalies using visual models, covers strong constraints and known risks using rule-based models, and characterizes structural deviations in supply chain relationships using graph anomaly models. This invention can detect both sudden anomalies and gradual drift and hidden correlation anomalies.

[0073] 3. Based on the traceability relationship model, this invention performs reverse source tracing and positive impact propagation assessment on alarm batches, which significantly shortens response time, reduces the scope of blind recall and over-handling, and improves the accuracy of recall / isolation and resource utilization efficiency. Attached Figure Description

[0074] Figure 1 This is a flowchart of the method of the present invention. Detailed Implementation

[0075] The present invention will be further described in detail below with reference to the accompanying drawings and specific embodiments:

[0076] refer to Figure 1 In this embodiment, an abnormal event monitoring method for agricultural product traceability links is provided, including the following steps:

[0077] S1: Define batch coding rules and event type dictionary, and establish a traceability relationship model;

[0078] S2: Based on the traceability relationship model, sensor data acquisition devices are deployed at key control points in the agricultural product traceability chain, and edge computing gateways are deployed at each location to complete the trusted uploading of data to the blockchain.

[0079] S3: Unify data from different sources to a standard timeline, establish association keys by batch, location, and device, and preprocess the data; the preprocessing includes cleaning, verification, completion, and standardization.

[0080] S4: Construct anomaly detection models, including time-series prediction, visual anomaly, rule-based anomaly, and graph anomaly models, and perform anomaly detection based on preprocessed data;

[0081] S5: Unify the four types of results—time series model, visual model, rule hit, and graph anomaly—into an evidence vector, use an evidence fusion strategy to calculate the risk score, and obtain the output alarm package;

[0082] S6: Based on the output alarm packet, perform source tracing and impact assessment based on the traceability relationship model.

[0083] In this embodiment, batch coding rules and event type dictionaries are defined as follows: A unified batch coding rule is established, employing a multi-level coding structure to generate globally unique BatchID identifiers. The batch coding rule design adopts a six-segment coding format: category code - origin code - date code - field code - producer code - process version code. The category code uses the national standard classification system (e.g., vegetables VE, fruits FR, livestock LI, etc.), the origin code is coded according to administrative divisions, the date code uses the YYYYMMDD format, the field / workshop code combines GPS coordinates or internal numbering, and the producer code is associated with the enterprise's unified social credit code. The code, specifically the process version code, identifies the version iteration of the production process. The event type dictionary covers the entire life cycle of agricultural products, including production events (sowing, fertilizing, applying pesticides, harvesting), processing events (cleaning, sorting, sterilizing, packaging), warehousing events (warehousing, outbound, inventory, allocation), logistics events (loading, transportation, unloading, delivery), sales events (shelf placement, sales, returns), and complaint events (quality complaints, safety incidents). Each type of event defines a standard event template and data format to ensure the structured and standardized nature of traceability data. Strict mandatory field specifications have been established for each type of event to ensure the integrity and verifiability of traceability information. The time field specification requires all event records to be accurate to the second with a timestamp and to use the UTC standard time format, while also recording local time zone information; the location field specification includes GPS latitude and longitude coordinates, administrative division code, detailed address, and internal location code of the site; the subject field specification clearly identifies the responsible subject, including corporate legal person code, personal ID number, or operator employee number; the equipment / personnel field specification records the key equipment ID, model specifications, calibration status, and operator information involved in the event; the input / output batch relationship field describes the transformation, splitting, and merging relationships between batches through a directed graph structure, supporting modeling of complex batch flow relationships such as one-to-one, one-to-many, many-to-one, and many-to-many.

[0084] In this embodiment, the traceability relationship model is based on graph theory to support relationship modeling and traceability analysis of complex supply chain networks. The graph structure design uses a directed acyclic graph to represent batch flow relationships. Nodes represent specific batches, and edges represent transformation relationships (processing, packaging, mixing, etc.). Each node contains BatchID, timestamp, geographical location, and responsible entity attributes, while each edge contains transformation type, transformation ratio, and quality loss attribute information. Relationship types are defined as follows: direct transformation relationship (one-to-one transformation from raw material batch to finished product batch), splitting relationship (one batch is split into multiple sub-batch), merging relationship (multiple batches are mixed into a new batch), packaging relationship (combination of product batch and packaging material batch), and storage relationship (contact relationship between batches within the same storage unit). The data association mechanism uses BatchID as the primary key to establish a multi-dimensional association index between batches and events, indicators, entities, and equipment, supporting forward tracing (from raw materials to end products) and reverse tracing (tracing back from problematic products to the source). At the same time, it uses a spatiotemporal association algorithm to identify potential cross-contamination paths and the scope of impact propagation, providing a complete data foundation and relationship network support for subsequent anomaly detection and source tracing analysis.

[0085] In this embodiment, based on the traceability model, sensor data acquisition devices are deployed at key control points in the agricultural product traceability chain, and edge computing gateways are deployed at each location to complete the trusted uploading of data to the blockchain, as detailed below:

[0086] The graph-based sensor deployment strategy configures each node with the appropriate type and number of sensors based on the node types (production, processing, warehousing, logistics, and sales) and node attributes (processing capacity, risk level, and regulatory requirements) in the traceability model. Production nodes are equipped with environmental monitoring sensors (soil, meteorology, and plant protection); processing nodes are equipped with sensors for key process parameters (temperature, pressure, flow rate, and concentration); warehousing nodes are equipped with environmental status sensors (temperature, humidity, gas, and inventory); and logistics nodes are equipped with sensors for key transportation status (GPS, temperature, vibration, and door / sealant sensors).

[0087] The data association design based on graph edge relationships targets the edge relationships (transformation, segmentation, merging, mixing, storage) in the traceability relationship model. Corresponding sensors are deployed at the corresponding operation points to ensure data continuity during batch transformation. For example, feeding and output weighing sensors are deployed at the raw material to finished product transformation edge, sorting and counting sensors are deployed at the segmentation edge, mixing ratio monitoring equipment is deployed at the merging edge, and contact surface temperature and humidity sensors are deployed at the storage edge. The data identification and batch binding mechanism uses BatchID, NodeID, and EdgeID to 3D identify the data collected by each sensor, ensuring accurate correspondence between the data and specific batches, nodes, and transformation relationships. This supports subsequent graph-based anomaly propagation analysis and precise source tracing.

[0088] Edge computing gateways are deployed at each location node in the traceability relationship model to construct a distributed computing architecture that matches the graph structure. Based on the graph topology, the collaborative computing mechanism establishes communication connections between each edge gateway according to the adjacency relationship in the traceability relationship model, forming a computing network topology consistent with the traceability graph structure. The edge gateways of the upstream nodes transmit the processed data and features to the downstream nodes. The downstream nodes can perform correlation analysis and anomaly detection based on the upstream information, realizing cross-node collaborative reasoning and early warning.

[0089] A blockchain-based evidence storage mechanism deeply integrated with the traceability relationship model is established to achieve an organic combination of trusted data storage and relationship integrity verification. The on-chain storage strategy for graph structure data uses the graph structure information (node ​​attributes, edge relationships, batch flow paths) in the traceability relationship model as the basic data structure of the blockchain. The generation, transformation, and flow events of each batch are recorded on the chain in the form of smart contracts to ensure the immutability of the traceability relationship. At the same time, the hash values ​​of key data collected by sensors are organized and stored according to the graph structure to form a digital evidence chain consistent with the physical traceability path.

[0090] In this embodiment, association keys are established by batch, location, and device, as follows: The batch-level association key design uses BatchID defined in S1 as the primary key, establishing a batch-level index: raw material batches, intermediate batches, and finished product batches form a tree-like association structure, supporting parent-child relationship queries between batches, aggregate queries of batches from the same source, and batch lifecycle tracking queries; simultaneously, a batch time window index is established to associate related batches with overlapping times, supporting cross-contamination analysis and parallel processing monitoring; the location-level association key design establishes a multi-level geographic location coding system: an eight-level geographic coding system of province-city-county-township-village-specific address-GPS coordinates-indoor location, combined with the GeoHash algorithm to achieve fast spatial proximity retrieval; for mobile scenarios (transport vehicles, mobile devices), trajectory segmentation technology is used to divide continuous GPS trajectories into spatial-temporal blocks according to time windows and geofences, establishing dynamic location association keys; the device-level association key design establishes a unique device ID for each data acquisition device, including device type, manufacturer, model, serial number, deployment location, and calibration status attribute information; a device capability matrix is ​​established to record the types of indicators that each device can collect, accuracy levels, and technical parameters of collection frequency.

[0091] In this embodiment, a time-series prediction and visual anomaly detection model is constructed for agricultural product traceability scenarios. This model performs intelligent anomaly identification on continuous monitoring data and image data, as detailed below:

[0092] The time-series prediction anomaly detection model employs a multivariate time-series prediction network based on the Transformer architecture, combining LSTM-Autoencoder and GRU-VAE models to construct an integrated prediction framework. The model input includes multi-dimensional time-series data such as temperature, humidity, pH, and pressure. It captures long-term and short-term dependencies and the mutual influence between variables through a self-attention mechanism, predicting the numerical change trend within future time windows. Anomaly detection is achieved through a triple criterion of reconstruction error, prediction residual, and probability distribution deviation: when the deviation between the actual observed value and the predicted value exceeds a dynamic threshold (adaptively adjusted based on historical data statistical characteristics and seasonal patterns), an anomaly alarm is triggered, which can effectively identify time-series anomaly patterns such as temperature chain breaks, sudden humidity changes, abnormal pH fluctuations, and equipment failures.

[0093] The visual anomaly detection model is based on a deep convolutional neural network and the Vision Transformer architecture, constructing a multi-scale feature fusion visual anomaly detection system. It includes a defect detection sub-network (based on YOLOv8 and Faster R-CNN target detection algorithms to identify defects such as appearance damage, mold, pests, and foreign objects), a quality assessment sub-network (based on ResNet and EfficientNet classification networks to evaluate quality indicators such as maturity, freshness, and color), and an abnormal behavior detection sub-network (based on 3D CNN and optical flow analysis to monitor abnormal behaviors such as operational violations and abnormal equipment operation).

[0094] In this embodiment, the visual anomaly detection model is based on a deep convolutional neural network and the Vision Transformer architecture, constructing a multi-scale feature fusion visual anomaly detection system, as detailed below:

[0095] The backbone network architecture was designed using EfficientNet-B4 as the basic feature extractor, and model performance was optimized by uniformly scaling the network depth, width, and resolution. The network depth was calculated according to α. φ Scaling (α=1.2), network width according to β φ Scaling (β=1.1), input resolution according to γ φ Scaling (γ=1.15), where φ is the composite coefficient, finally obtains multi-layer feature maps with different resolutions, which are 1 / 4, 1 / 8, 1 / 16 and 1 / 32 times the size of the input image, respectively, which can effectively capture rich feature information from fine-grained texture to coarse-grained semantics;

[0096] The feature pyramid network fusion mechanism uses a top-down path and lateral connections to construct a feature pyramid. High-level semantic features are fused with low-level detail features through upsampling. The features of each pyramid layer are aligned through 1×1 convolution dimensionality reduction and upsampling operations, ultimately generating a five-layer feature pyramid for anomaly detection tasks at different scales.

[0097] The multi-scale receptive field enhancement module introduces a dilated spatial pyramid pooling module after each feature map layer. It uses 3×3 convolutional kernels with different dilation rates (1, 6, 12, 18) to process the feature maps in parallel. It captures contextual information at different scales through convolutional branches of different receptive fields. Finally, it fuses multi-scale information through feature concatenation and 1×1 convolution, which significantly improves the ability to identify defects in small targets and abnormal features in complex background environments, and provides rich multi-scale feature representations for subsequent anomaly detection.

[0098] This paper introduces the Vision Transformer branch to learn the global spatial relationships and long-distance dependencies of images, and deeply fuses them with local features of CNN to enhance the global understanding of anomaly detection. The ViT branch architecture and patch embedding mechanism divide the input image into a fixed-size patch sequence. Each patch is mapped to a high-dimensional vector representation through linear projection, and learnable classification tokens and positional codes are added to form a complete input sequence that is fed into the Transformer encoder. The patch embedding process preserves spatial positional information, enabling the model to learn the spatial relationships between different regions and global contextual information. It is particularly suitable for detecting anomaly patterns that require global judgment, such as overall color anomalies and shape deformations. The Transformer encoder uses a multi-head self-attention mechanism to learn the interrelationships between patches. Attention weights are calculated through the interaction of three matrices: query, key, and value. Each attention head focuses on a different feature subspace. The 12 attention heads process in parallel and are finally fused, which can simultaneously focus on local details and global structure, and learn the complete feature distribution of agricultural product surfaces and the global consistency of anomaly patterns. The CNN-ViT cross-modal feature fusion strategy designs a cross-attention fusion module to achieve effective interaction between CNN local features and ViT global features. Through the cross-attention mechanism, CNN features focus on the globally important regions learned by ViT, while ViT features focus on the local details captured by CNN. The two types of features are weighted and fused through element-wise multiplication and then processed by convolutional layers to finally obtain a fused feature representation that has both local accuracy and global consistency, providing more robust and discriminative feature input for multi-task anomaly detection heads.

[0099] A multi-task detection head is constructed to simultaneously handle three sub-tasks: defect detection, quality assessment, and anomaly localization. End-to-end visual anomaly detection for agricultural products is achieved through joint loss function optimization. The decoupling of the defect detection head is based on an improved YOLO detection framework. The decoupled detection head separately predicts classification probabilities, bounding box regression parameters, and target confidence. The classification branch outputs multi-category defect probabilities (moldy, damaged, pest-infested, foreign objects, etc.) through a sigmoid activation function, the regression branch directly outputs the position and size offset of the bounding box, and the confidence branch predicts the probability that the detection box contains the true target. This decoupling design of the three branches avoids mutual interference between different tasks, improving detection accuracy and convergence stability. The quality assessment head uses global average pooling to compress two-dimensional feature maps into one-dimensional feature vectors through global feature aggregation. A multilayer perceptron is then used to predict the classification of agricultural product quality levels, including maturity assessment (unripe, ripe, overripe), freshness assessment (fresh, average, not fresh), and overall quality rating (excellent, good, medium, poor), providing intelligent support for agricultural product grading and pricing.

[0100] In this embodiment, a rule anomaly and graph anomaly detection model based on expert knowledge and relationship mining is constructed to achieve accurate identification of compliance violations and supply chain structure anomalies, as detailed below:

[0101] The rule anomaly detection model constructs a multi-level rule engine system, including a regulatory compliance rule layer (mandatory standards such as pesticide use intervals, additive limits, and cold chain temperature requirements), an enterprise standard rule layer (enterprise-defined rules such as internal process parameter ranges, quality control indicators, and operating procedure requirements), and a logical consistency rule layer (business logic rules such as batch flow logic, temporal relationships, and quantity balance relationships). The rule engine uses the Rete algorithm for real-pattern matching and inference, supports condition combinations, temporal logic, and numerical calculations, and can detect anomalies such as violations, parameter exceedances, and logical contradictions in real time. Simultaneously, a rule confidence evaluation mechanism is established, dynamically adjusting rule weights based on historical verification results and expert feedback to reduce false alarms and improve rule usability.

[0102] The graph anomaly detection model, based on graph neural networks and graph embedding technology, detects structural anomalies in traceability relationship networks. It constructs a dynamic supply chain graph using BatchID as nodes and flow relationships as edges, and learns the representation vectors of nodes and edges through graph neural networks. Anomaly detection is achieved through three dimensions: graph structure change detection (new abnormal edges, changes in node degree distribution, and community structure evolution), node behavior anomaly detection (anomaly score propagation based on neighbor nodes), and path anomaly detection (abnormal path identification based on random walks and path embedding). It can identify graph structure anomalies such as sudden supplier replacement, abnormal batch mixing, illegal flow, and false traceability paths, providing crucial support for supply chain risk management.

[0103] In this embodiment, the four types of results—time series model, visual model, rule hit, and graph anomaly—are unified into an evidence vector. An evidence fusion strategy is used to calculate the risk score and obtain the output alarm packet, as detailed below:

[0104] The four types of heterogeneous detection results are converted into standardized evidence vectors, where the evidence vector structure design defines a unified evidence vector e. i Including the abnormal confidence level c i ∈[0,1], severity of anomaly s i ∈[0,1], Evidence credibility r i ∈[0,1], time urgency t i ∈[0,1, Spatial influence range a i ∈[0,1], historical consistency h i ∈[0,1] and business criticality b i ∈[0,1], forming e i =[c i ,s i ,r i ,t i ,a i ,h i ,b i ] T ;

[0105] The time-series model evidence vector transformation and time-series anomaly detection results are transformed using the following mapping function: Anomaly Confidence:

[0106] ;

[0107] in, For the predicted value, y t For the actual observed value, σ t Historical standard deviation; severity of outliers Calculation based on the 3σ criterion; credibility of evidence Based on model validation error calculation; time urgency t ts =exp(-λΔt) decays according to the duration of the anomaly;

[0108] Among them, MSE validation λ is the mean squared error of the time series model on the validation set; λ is the decay coefficient.

[0109] The formula for converting visual detection results from evidence vectors in a visual model is: Anomaly Confidence. Select the highest confidence detection box; anomaly severity Calculated based on the percentage of defective area;

[0110] Among them, conf jcls represents the target confidence of the j-th detection box. j The class confidence score for the j-th bounding box; max j (·) indicates taking the maximum value among all test results; area j Let be the area of ​​the j-th anomaly detection box; total_area is the reference total area;

[0111] Rule and graph model evidence vector transformation rule hit is converted to:

[0112]

[0113] Based on rule-weighted average;

[0114] The graph anomaly was converted to: Standardize,

[0115] Where μ and σ are the mean and standard deviation of historical outlier scores; w k The weight of the k-th rule; hit k This is the hit indication for the k-th rule; anomaly_score is the raw anomaly score output by the graph anomaly model.

[0116] An improved DS evidence theory is employed to achieve intelligent fusion of multi-source evidence. The comprehensive anomaly probability is calculated through combined reasoning using a trust function and a likelihood function. The basic probability assignment function is used to construct each evidence vector e. i Construct the basic probability assignment function m i Define the recognition framework Θ:

[0117] Θ={Normal, Abnormal, Unknown};

[0118] Wherein, Normal represents the normal hypothesis; Abnormal represents the abnormal hypothesis; and Unknown represents the unknown hypothesis.

[0119] The basic probability assignment calculation formula is as follows:

[0120] ;

[0121] Among them, w i For model weights; m i (·) represents the basic probability assignment for the i-th source of evidence; c i r represents the anomalous confidence level of the i-th source of evidence; i Let be the credibility of the i-th source of evidence;

[0122] Conflict coefficient calculation and conflict resolution: Calculating the conflict coefficient between pieces of evidence.

[0123] ,

[0124] When K > preset value, the evidence is considered highly conflicting; A and B are sets of propositions from the power set Θ of the identification framework; It is an empty set;

[0125] For multiple evidence sources, the recursive evidence fusion algorithm employs a recursive fusion strategy: first, it sorts the evidence sources by their credibility. Then calculate recursively:

[0126] ;

[0127] Where ⊕ is the DS combination operator;

[0128] m 1:k The m represents the composite BPA after fusing the first k evidence sources; k+1 The BPA for the (k+1)th (k+1)th evidence source; m 1:k+1 This represents the new composite BPA after incorporating the (k+1)th piece of evidence;

[0129] Trust function for the final fusion result:

[0130] Bel(Abnormal) = m(Abnormal);

[0131] Where Bel(Abnormal) is the trust function value for the abnormal proposition; m(Abnormal) is the quality of the fused basic probability assignment BPA on the abnormal proposition;

[0132] Likelihood function:

[0133] Pl(Abnormal) = 1 - m(Normal);

[0134] Wherein, Pl (Abnormal) is the upper bound of the likelihood of "abnormal propositions"; m (Normal) is the quality of the fused BPA on normal propositions;

[0135] Overall anomaly probability:

[0136] ;

[0137] Finally, the risk score is calculated based on the overall anomaly probability, and a structured alarm package is generated.

[0138] The multidimensional risk score calculation model calculates the overall risk score Rtotal by weighting four dimensions: anomaly probability, impact assessment, urgency, and business criticality.

[0139] ;

[0140] Impact assessment:

[0141]

[0142] Taking into account the severity, scope, and duration of the anomaly;

[0143] Urgency assessment

[0144]

[0145] Calculations are based on abnormal development trends, speed of change, and risk of propagation.

[0146] Business criticality C criticality Determined based on batch value, customer importance, and compliance requirements;

[0147] Dynamic threshold and alarm level determination establish an adaptive threshold system:

[0148] Low risk threshold τ low =μ R -0.5σ R medium risk threshold τ med =μ R +σ R High-risk threshold τ high =μ R +2σ R , where μ R σ R The mean and standard deviation of historical risk scores;

[0149] The alarm level determination rules are as follows:

[0150] .

[0151] The structured alarm packet generates alarm packet A, which contains the core elements: A={AlertID,BatchID,Timestamp,Level,Rtotal,Eevidence,Llocation,Ssuggestion};

[0152] Where Eevidence=[ets,evis,erule,egraph] is the evidence vector matrix, Llocation contains GPS coordinates, facility codes and specific location descriptions, and Ssuggestion generates handling suggestions based on rule engines and knowledge graphs; at the same time, an alarm aggregation mechanism is established to generate merged alarms for multiple low-level alarms in the same batch, at adjacent times and in similar locations through aggregation algorithms, avoiding alarm redundancy and improving handling efficiency, and providing decision-makers with accurate, timely and actionable abnormal alarm information.

[0153] In this embodiment, based on the output alarm packet, source tracing and impact assessment are performed using a traceability relationship model, as detailed below:

[0154] Based on the traceability relationship model built by S1, the abnormal batches in the alarm package are accurately traced and located, and the root node and propagation path of the abnormality are tracked by the graph traversal algorithm.

[0155] The reverse tracing path search algorithm starts with the alarm batch node and explores paths along the reverse edges of the traceability graph using a combination of depth-first search and breadth-first search. Depth-first search is used to find direct upstream traceability links, tracing key links such as raw material source, processing technology, and storage conditions. Breadth-first search is used to discover related batches involved in the splitting and merging operations of the same batch, ensuring the completeness and accuracy of traceability. The most likely source of anomalies is identified through path weight calculation, with weights comprehensively considering factors such as time sequence, batch conversion ratio, node risk level, and historical anomaly frequency. Multi-level traceability depth control and key node identification establish a multi-level traceability mechanism. The traceability depth is determined according to the severity of the anomaly and business needs. Minor anomalies are traced back to 1-2 levels of upstream nodes, while major anomalies can be traced back to the raw material source and planting stage. During the traceability process, key control nodes are identified, including raw material receiving points, key process nodes, quality inspection points, and storage handover points. These nodes are often the key links for the generation or spread of anomalies and require key attention and in-depth analysis. Anomaly propagation pattern analysis and root cause localization identify possible propagation patterns of anomalies by analyzing node attributes and edge weights in the traceability graph. These patterns include three types: vertical propagation (transmission along the upstream and downstream of the supply chain), horizontal propagation (diffusion within the same batch), and cross-propagation (cross-contamination between different batches). Combining multi-source information such as time-series data, equipment status, and operation records, causal reasoning algorithms are used to identify the root causes of anomalies and distinguish different types of root causes, such as equipment failure, operational errors, raw material problems, and environmental factors.

[0156] Using graph propagation algorithms and risk diffusion models, the impact range of abnormal events is dynamically assessed, and potential risk propagation paths and the range of affected batches are predicted. The calculation of the positive impact propagation path starts from the source node of the abnormality and analyzes the impact propagation along the forward edges of the traceability graph. A modified PageRank algorithm is used to calculate the probability of each downstream node being affected. The random walk probability in the algorithm is dynamically adjusted based on factors such as batch turnover ratio, time interval, and processing intensity. The propagation attenuation coefficient is set according to the purification capacity of the nodes (e.g., high-temperature sterilization, chemical disinfection, physical filtration). Processing nodes that can effectively purify contamination have higher attenuation coefficients, and the propagation probability decreases significantly after passing through such nodes. A time window constraint mechanism is established to define the impact range. Different impact time ranges are set according to the characteristics of the abnormality type. Microbial contamination anomalies have a long incubation period and propagation cycle; chemical contamination anomalies spread rapidly but their impact time is relatively fixed; and physical damage anomalies have a relatively limited impact range but require attention to the risk of subsequent secondary contamination. Through time window filtering, the impact assessment is limited to a reasonable time range, avoiding resource waste and panic caused by excessive expansion of the impact range. Multidimensional risk diffusion modeling and probability calculation construct a multidimensional risk diffusion model, comprehensively considering multiple factors such as pollution concentration decay, propagation medium characteristics, environmental conditions, and the effects of human intervention. A diffusion equation is established to describe the propagation law of risk in the supply chain network. The Monte Carlo simulation method is used to calculate the probability and degree of impact of each node. Through a large number of random samples, the propagation process under different conditions is simulated to obtain the probability distribution and confidence interval. At the same time, a risk superposition model is established. When a node is affected by multiple abnormal sources at the same time, the probability superposition formula is used to calculate the comprehensive risk level to avoid omissions and underestimations in risk assessment.

[0157] Based on the impact assessment results, all potentially affected batches are identified, and differentiated emergency response strategies and handling recommendations are generated according to risk levels.

[0158] The affected batches are classified and labeled according to their probability and severity of impact. They are divided into three levels: confirmed impact, suspected impact, and potential impact. Confirmed impact batches (impact probability > 80%) need to be recalled or isolated immediately. Suspected impact batches (impact probability 40%-80%) need to be subject to enhanced testing and monitoring. Potential impact batches (impact probability 10%-40%) need to be monitored and tracked preventively. Each affected batch is labeled and classified, and detailed information such as the impact path, impact degree, and impact time is recorded to establish a complete impact file for subsequent processing and accountability.

[0159] Those skilled in the art will understand that embodiments of the present invention can be provided as methods, systems, or computer program products. Therefore, the present invention can take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, the present invention 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.

[0160] This invention is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of the invention. 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 illustrations and / or block diagrams. Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.

[0161] 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.

[0162] 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.

[0163] The above description is merely a preferred embodiment of the present invention and is not intended to limit the present invention in any other way. Any person skilled in the art may make changes or modifications to the above-disclosed technical content to create equivalent embodiments. However, any simple modifications, equivalent changes, and modifications made to the above embodiments based on the technical essence of the present invention without departing from the scope of the present invention shall still fall within the protection scope of the present invention.

Claims

1. A method for monitoring abnormal events in the agricultural product traceability chain, characterized in that, Includes the following steps: S1: Define batch coding rules and event type dictionaries, and establish a traceability relationship model, including: establishing unified batch coding rules and using a multi-level coding structure to generate globally unique BatchID identifiers; the traceability relationship model is constructed based on graph theory, and the graph structure uses a directed acyclic graph to represent batch flow relationships, with nodes representing specific batches and edges representing conversion relationships. Each node contains BatchID, timestamp, geographical location, and responsible entity attributes, and each edge contains conversion type, conversion ratio, and quality loss attribute information; the relationship type definitions include direct conversion relationships, splitting relationships, merging relationships, packaging relationships, and storage relationships; S2: Based on the traceability relationship model, sensor data acquisition devices are deployed at key control points in the agricultural product traceability chain, and edge computing gateways are deployed at each location to complete the trusted uploading of data to the blockchain. S3: Unify data from different sources to a standard timeline, establish association keys by batch, location, and device, and preprocess the data; S4: Construct an anomaly detection model, including time-series prediction, visual anomaly, rule-based anomaly, and graph anomaly models, and perform anomaly detection based on preprocessed data; the graph anomaly model is based on graph neural networks and graph embedding technology to detect structural anomalies in the traceability relationship network, using BatchID as nodes and flow relationships as edges to construct a dynamic supply chain graph, and learning the representation vectors of nodes and edges through graph neural networks; anomaly detection is achieved through three dimensions: graph structure change detection, node behavior anomaly detection, and path anomaly detection; S5: Unify the four types of results—time series model, visual model, rule hit, and graph anomaly—into evidence vectors, calculate risk scores using evidence fusion strategies, and output alarm packages. This includes: converting the four types of heterogeneous detection results into standardized evidence vectors, using improved DS evidence theory to achieve intelligent fusion of multi-source evidence, calculating the comprehensive anomaly probability through combined reasoning of trust function and likelihood function, and finally calculating risk scores based on the comprehensive anomaly probability and generating structured alarm packages. S6: Based on the output alarm packet, perform source tracing and impact assessment based on the traceability relationship model.

2. The method for monitoring abnormal events in the agricultural product traceability chain according to claim 1, characterized in that, The batch coding rules and event type dictionary are defined as follows: The batch coding rules adopt a six-segment coding format of category code - place of origin code - date code - field code - producer code - process version code; The event type dictionary covers the entire life cycle of agricultural products, including production events, processing events, storage events, logistics events, sales events and complaint events. Each type of event defines a standard event template and data format.

3. The method for monitoring abnormal events in the agricultural product traceability chain according to claim 1, characterized in that, Based on the traceability model, sensor data acquisition devices are deployed at key control points in the agricultural product traceability chain, and edge computing gateways are deployed at each location to ensure reliable data uploading to the blockchain, as detailed below: The graph node-based sensor deployment strategy configures the appropriate type and number of sensors for each node based on the node type and node attributes in the traceability relationship model. The data association design based on graph edge relationships targets the edge relationships in the traceability relationship model, deploying associated sensors at the corresponding operation points to ensure data continuity during batch conversion; and establishing a data identification and batch binding mechanism, with each sensor's collected data being three-dimensionally identified using BatchID, NodeID, and EdgeID. Edge computing gateways are deployed at each location node in the traceability relationship model to construct a distributed computing architecture that matches the graph structure. Based on the graph topology-based collaborative computing mechanism, each edge computing gateway establishes a communication connection according to the adjacency relationship in the traceability relationship model, forming a computing network topology consistent with the graph structure in the traceability relationship model. The edge gateways of upstream nodes transmit the processed data and features to downstream nodes, and downstream nodes can perform correlation analysis and anomaly detection based on upstream information to achieve cross-node collaborative reasoning and early warning. A blockchain evidence storage mechanism deeply integrated with the traceability relationship model is established. The on-chain storage strategy of graph structure data uses the graph structure information in the traceability relationship model as the basic data structure of the blockchain. The generation, transformation and circulation events of each batch are recorded on the chain in the form of smart contracts to ensure the immutability of the traceability relationship. At the same time, the hash values ​​of key data collected by sensors are organized and stored according to the graph structure to form a digital evidence chain consistent with the physical traceability path.

4. The method for monitoring abnormal events in the agricultural product traceability chain according to claim 1, characterized in that, The establishment of association keys by batch, location, and equipment is as follows: The batch-dimensional association key design uses BatchID defined in S1 as the primary key to establish a batch hierarchical index: raw material batches, intermediate batches, and finished product batches form a tree-like association structure, supporting parent-child relationship queries between batches, aggregate queries of batches from the same source, and batch lifecycle tracking queries; at the same time, a batch time window index is established to associate related batches with overlapping times, supporting cross-contamination analysis and parallel processing monitoring; The location-level association key design establishes a multi-level coding system for geographic locations; for mobile scenarios, trajectory segmentation technology is adopted to divide continuous GPS trajectories into spatial-temporal blocks according to time windows and geofences, and establish dynamic location association keys; the device-level association key design establishes a unique device ID for each data acquisition device, which includes device type, manufacturer, model, serial number, deployment location, calibration status attribute information; Establish a device capability matrix to record the types of indicators that each device can collect, the accuracy level, and the technical parameters of the collection frequency.

5. The method for monitoring abnormal events in the agricultural product traceability chain according to claim 1, characterized in that, A time-series prediction and visual anomaly detection model for agricultural product traceability scenarios is constructed to perform intelligent anomaly identification on continuous monitoring data and image data, as detailed below: The time series prediction anomaly detection model employs a multivariate time series prediction network based on the Transformer architecture, combined with LSTM-Autoencoder and GRU-VAE models to construct an integrated prediction framework. The model input includes multidimensional time series data, and captures long-term and short-term dependencies and mutual influences between variables through a self-attention mechanism to predict the numerical change trend within future time windows. Anomaly detection is achieved through a triple criterion of reconstruction error, prediction residual, and probability distribution deviation: when the deviation between the actual observed value and the predicted value exceeds a dynamic threshold, an anomaly alarm is triggered. The visual anomaly detection model is based on a deep convolutional neural network and the Vision Transformer architecture, and constructs a multi-scale feature fusion visual anomaly detection system; it includes a defect detection subnetwork, a quality assessment subnetwork, and an abnormal behavior detection subnetwork.

6. The method for monitoring abnormal events in the agricultural product traceability chain according to claim 5, characterized in that, The visual anomaly detection model is based on a deep convolutional neural network and the Vision Transformer architecture, constructing a multi-scale feature fusion visual anomaly detection system, as detailed below: The backbone network architecture was designed using EfficientNet-B4 as the basic feature extractor, and model performance was optimized by uniformly scaling the network depth, width, and resolution. The network depth was calculated according to α. Scaling, network width according to β Scaling, input resolution according to γ Scaling, where, The composite coefficients ultimately yield multi-layer feature maps of different resolutions, which can effectively capture rich feature information from fine-grained texture to coarse-grained semantics. The feature pyramid network fusion mechanism uses a top-down path and lateral connections to construct a feature pyramid. High-level semantic features are fused with low-level detail features through upsampling. The features of each pyramid layer are aligned through 1×1 convolution dimensionality reduction and upsampling operations, ultimately generating a five-layer feature pyramid for anomaly detection tasks at different scales. The multi-scale receptive field enhancement module introduces a dilated spatial pyramid pooling module after each feature map layer. It uses 3×3 convolutional kernels with different dilation rates to process the feature maps in parallel. It captures contextual information at different scales through convolutional branches of different receptive fields. Finally, it fuses multi-scale information through feature concatenation and 1×1 convolution. The Vision Transformer branch is introduced to learn the global spatial relationships and long-range dependencies of images. It is deeply fused with local features of CNN to enhance the global understanding of anomaly detection. The ViT branch architecture and patch embedding mechanism divide the input image into a fixed-size patch sequence. Each patch is mapped to a high-dimensional vector representation through linear projection. At the same time, learnable classification tokens and positional codes are added to form a complete input sequence that is fed into the Transformer encoder. The patch embedding process preserves spatial positional information, enabling the model to learn the spatial relationships between different regions and global contextual information. The Transformer encoder uses a multi-head self-attention mechanism to learn the relationships between patches. Attention weights are calculated through the interaction of three matrices: query, key, and value. Each attention head focuses on a different feature subspace. Twelve attention heads process in parallel and are finally fused. The CNN-ViT cross-modal feature fusion strategy is designed with a cross-attention fusion module to realize the interaction between CNN local features and ViT global features. Through the cross-attention mechanism, CNN features focus on the globally important regions learned by ViT, while ViT features focus on the local details captured by CNN. The two types of features are weighted and fused through element-wise multiplication and then processed by convolutional layers to finally obtain a fused feature representation that has both local accuracy and global consistency. A multi-task detection head is constructed to simultaneously handle three sub-tasks: defect detection, quality assessment, and anomaly localization. End-to-end visual anomaly detection for agricultural products is achieved through joint loss function optimization. The defect detection head, based on an improved YOLO detection framework, uses decoupled detection heads to predict classification probabilities, bounding box regression parameters, and target confidence scores. The classification branch outputs multi-class defect probabilities through a sigmoid activation function, the regression branch directly outputs the position and size offset of the bounding box, and the confidence branch predicts the probability that the detection box contains a real target. The quality assessment head uses global average pooling to compress two-dimensional feature maps into one-dimensional feature vectors through global feature aggregation. A multilayer perceptron is then used to predict the classification of agricultural product quality grades, including maturity assessment, freshness assessment, and overall quality rating—multi-dimensional quality indicators—providing intelligent support for agricultural product grading and pricing.

7. The method for monitoring abnormal events in the agricultural product traceability chain according to claim 6, characterized in that, We construct rule-based and graph-based anomaly detection models based on expert knowledge and relationship mining to accurately identify compliance violations and supply chain structural anomalies, as detailed below: The rule anomaly detection model constructs a multi-level rule engine system, including a regulatory compliance rule layer, an enterprise standard rule layer, and a logical consistency rule layer. The rule engine uses the Rete algorithm to implement pattern matching and reasoning, and supports condition combination, temporal logic, and numerical calculation. At the same time, a rule confidence evaluation mechanism is established to dynamically adjust the rule weights based on historical verification results and expert feedback.

8. The method for monitoring abnormal events in the agricultural product traceability chain according to claim 7, characterized in that, The process involves unifying the four types of results—time series model, visual model, rule hit, and graph anomaly—into an evidence vector, employing an evidence fusion strategy to calculate risk scores, and obtaining output alarm packets, as detailed below: Standardized evidence vector structure design defines a unified evidence vector e i Including the abnormal confidence level c i ∈[0,1], severity of anomaly s i ∈[0,1], Evidence credibility r i ∈[0,1], time urgency t i ∈[0,1], Spatial influence range a i ∈[0,1], historical consistency h i ∈[0,1] and business criticality b i ∈[0,1], forming e i =[c i ,s i ,r i ,t i ,a i ,h i ,b i ] T ; Temporal model evidence vector transformation: Temporal anomaly detection results are transformed using the following mapping function: anomaly confidence. ; in, For the predicted value, y t For the actual observed value, σ t Historical standard deviation; severity of outliers Calculated based on the 3σ criterion; Evidence credibility Based on model validation error calculation; time urgency t ts =exp(-λΔt), decays according to the duration of the anomaly; Among them, MSE validation λ is the mean squared error of the time series model on the validation set; λ is the decay coefficient. Visual model evidence vector transformation, the formula for visual detection result transformation is: anomaly confidence. Take the highest confidence bounding box; anomaly severity Calculated based on the percentage of defect area; Among them, conf j cls represents the target confidence of the j-th detection box. j The class confidence score for the j-th bounding box; max j (·) indicates taking the maximum value among all test results; area j Let be the area of ​​the j-th anomaly detection box; total_area is the reference total area; Rule and graph model evidence vector transformation, rule hit transformation: Based on rule-weighted average; The graph anomaly was converted to: , where μ and σ are the mean and standard deviation of historical outlier scores; w k The weight of the k-th rule; hit k This is the hit indication for the k-th rule; anomaly_score is the raw anomaly score output by the graph anomaly model. An improved DS evidence theory is employed to achieve intelligent fusion of multi-source evidence. A comprehensive anomaly probability is calculated through combined reasoning using a trust function and a likelihood function, and a basic probability assignment function is constructed for each evidence vector e. i Construct the basic probability assignment function m i Define the recognition framework Θ: Θ={Normal, Abnormal, Unknown}; Wherein, Normal represents the normal hypothesis; Abnormal represents the abnormal hypothesis; and Unknown represents the unknown hypothesis; The basic probability assignment calculation formula is as follows: , ; Among them, w i For model weights; m i (·) represents the basic probability assignment for the i-th source of evidence; c i r represents the anomalous confidence level of the i-th source of evidence; i Let be the credibility of the i-th source of evidence; Conflict coefficient calculation and conflict resolution: Calculating the conflict coefficient between pieces of evidence. , When K > preset value, the evidence is considered highly conflicting; A and B are sets of propositions from the recognition framework Θ; It is an empty set; For multiple evidence sources, the recursive evidence fusion algorithm employs a recursive fusion strategy: first, it sorts the evidence sources by their credibility. Then calculate recursively: ; Where ⊕ is the DS combination operator; m 1:k The m represents the composite BPA after fusing the first k evidence sources; k+1 The BPA for the (k+1)th source of evidence; m 1:k+1 This represents the new composite BPA after incorporating the (k+1)th piece of evidence; The trust function for the final fusion result is: Bel(Abnormal) = m(Abnormal); Where Bel(Abnormal) is the trust function value for abnormal propositions; m(Abnormal) is the quality of the fused basic probability assignment BPA on abnormal propositions; Likelihood function: Pl(Abnormal) = 1 - m(Normal); Where Pl (Abnormal) is the upper bound of the likelihood of abnormal propositions; m (Normal) is the quality of the fused BPA on normal propositions; Overall anomaly probability: 。 9. The method for monitoring abnormal events in the agricultural product traceability chain according to claim 1, characterized in that, The process of tracing the source and assessing the impact based on the traceability relationship model, based on the output alarm packet, is as follows: Based on the traceability relationship model constructed in S1, the abnormal batches in the alarm packet are accurately traced and located. A graph traversal algorithm is used to track the root node and propagation path of the anomaly. A graph propagation algorithm and a risk diffusion model are used to dynamically assess the impact range of the abnormal event, predicting potential risk propagation paths and the range of affected batches. The forward impact propagation path is calculated starting from the source node of the anomaly and proceeding along the forward edges of the traceability relationship graph. A modified PageRank algorithm is used to calculate the probability of each downstream node being affected. Based on the impact range assessment results, all potentially affected batches are identified, and differentiated emergency response strategies and handling recommendations are generated according to the risk level.