A method and system for precise positioning of cattle in a barn
The cattle positioning system, optimized through Bluetooth beacon networks and adaptive algorithms, solves the problems of positioning accuracy and anti-interference in enclosed pen environments, achieving high-precision cattle location identification and pen affiliation, and supporting intelligent management and health early warning.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- GUIZHOU YILIAN DIGITAL TECHNOLOGY CO LTD
- Filing Date
- 2026-03-06
- Publication Date
- 2026-06-26
AI Technical Summary
In enclosed pen environments, existing cattle positioning technologies suffer from poor signal transmission stability, insufficient positioning accuracy, weak anti-interference capabilities, and difficulties in dynamic and static correlation, making it difficult to achieve high-precision cattle location identification and pen affiliation.
A beacon network is constructed using Bluetooth beacon networks and topology adaptive algorithms. RSSI signal strength and RTT ranging data are fused together. The positioning results are optimized using Bayesian probability models and adaptive robust resettable flow algorithms. The signal propagation path is optimized by combining grid maps and low-diameter wiring decomposition techniques to achieve accurate matching of cattle with pen locations.
It improves the accuracy and stability of cattle positioning, reduces positioning errors by 35-45%, achieves stable positioning in high-density cattle environments, supports behavioral analysis and management decisions, and provides early warning of health abnormalities.
Smart Images

Figure CN122283589A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of intelligent animal husbandry technology, specifically to a method and system for precise positioning of cattle in barns. Background Technology
[0002] In livestock farming, precise location and tracking of cattle are crucial for modern intelligent farming management. By understanding the distribution of the herd, individual behavioral patterns, and health status in real time, farms can achieve intelligent management such as precise feeding, timely intervention in abnormal behaviors, and disease early warning. However, traditional cattle location technology faces many challenges in practical applications, especially in enclosed pen environments.
[0003] Currently, common animal tracking technologies mainly include GPS-based outdoor tracking systems and RFID-based short-range identification systems. GPS tracking systems provide good positioning results in open environments, but in enclosed environments such as pens, signal attenuation and multipath effects lead to a significant decrease in positioning accuracy, or even complete failure to obtain effective positioning information. While RFID technology can identify cattle, its positioning accuracy is limited, and identification requires the animal to be close to the reading device, which cannot meet the needs of real-time, continuous tracking.
[0004] In recent years, some wireless signal-based indoor positioning technologies, such as Wi-Fi, ZigBee, or UWB, have begun to be applied in cattle shed environments. These technologies estimate location by measuring parameters such as signal strength, time of arrival, or time difference of arrival, combined with triangulation or fingerprint matching algorithms. However, these technologies still have some technical problems in practical applications: signal stability is greatly affected by the environment, positioning accuracy is insufficient (usually at the meter level), system deployment costs are high, and the positioning algorithms lack robustness in dynamic environments, failing to effectively adapt to the complex interference caused by the movement of multiple cattle in the cattle shed.
[0005] The main problems with existing technologies include: first, poor signal transmission stability in enclosed pen environments, resulting in insufficient positioning accuracy; second, existing algorithms cannot effectively handle the complex interference and environmental changes caused by dense movement of cattle; third, high system deployment and maintenance costs, making it difficult to promote and apply in large-scale farms; and fourth, the lack of a mechanism to effectively link dynamic positioning data with static pen structure, making it impossible to accurately determine the specific pen location of the cattle.
[0006] Therefore, there is an urgent need for a low-cost, high-precision cattle positioning technology that is adaptable to the pen environment, capable of overcoming complex environmental interference and accurately identifying the location of cattle and determining their pen affiliation. Summary of the Invention
[0007] The purpose of this invention is to solve the technical problems of insufficient positioning accuracy, weak anti-interference ability, and difficulty in dynamic and static correlation of cattle in the existing technology in the closed pen environment, and to provide a method and system for accurate positioning of cattle in the pen.
[0008] To achieve the above objectives, the present invention adopts the following technical solution:
[0009] A method and system for precise positioning of cattle in a barn includes: deploying a Bluetooth beacon network within the barn; collecting an environmental feature dataset of the barn; constructing a Bluetooth beacon node deployment coordinate map based on the environmental feature dataset; installing Bluetooth beacon nodes in the barn according to the deployment coordinate map; and constructing the Bluetooth beacon network using a topology adaptive algorithm. Positioning tags are installed on the cattle, and RSSI signal strength data and RTT ranging data between the positioning tags and each Bluetooth beacon node are collected. The RSSI signal strength data and RTT ranging data are fused using a second-order improved algorithm for edge estimation via independent set query to generate... An initial set of coordinates for the cattle's positions is generated. Based on the structural features of the pens, a grid map is established. The grid map is optimized using a low-diameter wiring decomposition technique and a fully dynamic algorithm for drawing wrenches, generating optimized position data. A static structure database for the pens is established, and a Bayesian probability model is constructed using the initial set of coordinates to generate a mapping relationship between cattle and pens. Based on the optimized position data and the mapping relationship, the positioning results are optimized using an adaptive robust resettable flow algorithm to generate the final positioning result. A virtual geofence is established based on the final positioning result to monitor and generate real-time status warning information for the cattle.
[0010] Preferably, the deployment of the Bluetooth beacon network within the enclosure includes: comprehensively analyzing and measuring the physical structure, size, material, and signal interference sources of the enclosure to generate the environmental feature dataset; designing the Bluetooth beacon node deployment coordinate map using a triangular mesh topology based on the environmental feature dataset; installing the Bluetooth beacon nodes on the top and side walls of the enclosure according to the deployment coordinate map, initializing and configuring each node to establish a basic beacon network; collecting the actual RSSI signal strength data of each node and constructing an initial signal strength matrix through mutual measurement; and running the topology adaptive algorithm based on the initial signal strength matrix to dynamically adjust the beacon transmission power and communication parameters to form the Bluetooth beacon network.
[0011] Preferably, the step of installing a positioning tag on the cattle, collecting RSSI signal strength data and RTT ranging data between the positioning tag and each Bluetooth beacon node, and fusing the RSSI signal strength data and RTT ranging data using a secondary improved algorithm for edge estimation via independent set query to generate an initial position coordinate set for the cattle includes: establishing communication between the positioning tag and each Bluetooth beacon node, collecting RSSI signal strength data from multiple beacon nodes, and preprocessing the data using sliding window filtering and outlier removal; calculating the actual distance based on the round-trip time between the positioning tag and each Bluetooth beacon node to form a multilateral ranging dataset; treating the RSSI signal strength data and the RTT ranging data as edges in a graph, and applying independent set query technology for secondary improvement of edge estimation to reduce the impact of environmental factors on ranging accuracy; and calculating the initial position coordinates of the cattle using the least squares method based on the improved edge estimation results and the principles of trilateration and multilateral positioning.
[0012] Preferably, the step of establishing a grid map based on the structural features of the enclosure, and optimizing the grid map using a low-diameter wiring decomposition technique to achieve a fully dynamic algorithm for the drawing wrench, generating optimized location data, includes: establishing a three-dimensional digital model containing walls, partitions, and feeding areas based on the enclosure layout to generate a basic environment model; dividing the basic environment model into grids according to a preset precision, assigning physical attribute labels to each grid cell to form an attribute grid map; using the Bluetooth beacon network to perform signal strength sampling measurements within the enclosure, mapping the sampling data to the grid map to generate a signal propagation characteristic layer; based on the grid map, applying low-diameter wiring decomposition technique to achieve a fully dynamic algorithm for the drawing wrench, simplifying the signal propagation path in complex environments into a subset of paths; performing matching analysis between the initial location coordinate set and the grid map, optimizing the positioning results through a probability distribution model, and outputting the optimized location data.
[0013] Preferably, the step of establishing a static structure database for cattle pens and constructing a Bayesian probability model based on the initial location coordinate set to generate a mapping relationship between cattle and pens includes: measuring and defining different functional areas within the pens, and establishing the static structure database for cattle pens; analyzing the activity patterns and dwelling area preferences of cattle based on historical location data to generate activity heatmaps and time distribution models; and constructing the Bayesian probability model based on the static structure database for cattle pens and the activity pattern analysis results to calculate the conditional probability of cattle appearing in a specific pen.
[0014] Preferably, the construction of the Bayesian probability model includes: constructing a state transition probability matrix to describe the probability distribution of cattle moving between different pens; calculating the prior probability of cattle appearing in a specific pen in each time period based on the activity heatmap and time distribution model; and learning model parameters from historical data through maximum likelihood estimation and expectation maximization algorithms.
[0015] Preferably, the step of optimizing the positioning result based on the optimized location data and the mapping relationship using an adaptive robust resettable flow algorithm to generate the final positioning result includes: integrating the optimized location data and the mapping relationship, and combining the accelerometer data worn by the cattle to form a multidimensional feature vector; applying clustering analysis and anomaly detection algorithms to identify and eliminate interference factors that may cause positioning deviations; constructing an adaptive robust algorithm based on flow network theory to transform the positioning problem into a flow allocation problem and dynamically adjust the weights of different information sources; designing trigger conditions and reset strategies to reset the algorithm parameters when significant positioning drift or environmental changes are detected; applying Kalman filtering and trajectory smoothing techniques to the optimized positioning result to eliminate jumps and jitter, and outputting the final positioning result.
[0016] Preferably, the step of establishing a virtual geofence based on the final positioning result and monitoring and generating cattle status early warning information in real time includes: defining a multi-level virtual geofence based on pen layout and management needs, including permitted activity areas, restricted areas, and abnormal warning areas; comparing the final positioning result with the virtual geofence in real time to determine the cattle's location status and identify boundary crossing behavior; and applying a time-series pattern mining algorithm based on continuous positioning data and acceleration sensor information to identify the cattle's behavioral characteristics.
[0017] Preferably, the generation of cattle status early warning information includes: detecting potential abnormal behaviors by comparing historical behavior patterns and current behavior characteristics, and triggering early warnings at corresponding levels; displaying the location results, fence status, and behavior analysis in an intuitive way on the management system interface; providing historical data query and statistical analysis functions, and supporting trend analysis and prediction.
[0018] A cattle positioning system within a barn includes: a deployment module for deploying a Bluetooth beacon network within the barn, collecting an environmental feature dataset of the barn, constructing a Bluetooth beacon node deployment coordinate map based on the environmental feature dataset, installing Bluetooth beacon nodes in the barn according to the deployment coordinate map, and constructing the Bluetooth beacon network using a topology adaptive algorithm; and a data acquisition module for attaching positioning tags to the cattle, collecting RSSI signal strength data and RTT ranging data between the positioning tags and each Bluetooth beacon node, and fusing the RSSI signal strength data and RTT ranging data using a secondary improved algorithm for edge estimation via independent set query to generate an initial position coordinate set for the cattle. The system includes: a map optimization module for establishing a raster map based on the structural features of the pens, optimizing the raster map using a low-diameter wiring decomposition technique and a fully dynamic algorithm to generate optimized location data; a generation module for establishing a static structure database of the pens, constructing a Bayesian probability model based on the initial location coordinate set, and generating a mapping relationship between cattle and pens; a positioning optimization module for optimizing the positioning results based on the optimized location data and the mapping relationship using an adaptive robust resettable flow algorithm to generate the final positioning result; and an early warning module for establishing a virtual geofence based on the final positioning result, monitoring and generating real-time status warning information for the cattle.
[0019] The beneficial effects of this invention are as follows:
[0020] The improved algorithm for edge estimation through independent set query treats RSSI and RTT ranging data as edges in a graph for secondary estimation, effectively reducing the impact of environmental factors on ranging accuracy. Compared with the single signal source positioning method, the positioning error is reduced by 35-45%.
[0021] The low-diameter wiring decomposition technique is used to realize the full dynamic algorithm of the diagram wrench, which simplifies the signal propagation path in complex environments into an optimized set of sub-paths, improving the accuracy and computational efficiency of the signal propagation model, and enabling the system to efficiently process large-scale signal propagation networks.
[0022] By employing an adaptive robust resettable flow algorithm, the localization problem is transformed into a flow network optimization problem. When significant localization drift or environmental changes are detected, the system parameters can be quickly reset, ensuring the stability and accuracy of the localization system in high-density cattle environments.
[0023] Based on a Bayesian probability model, association rules between dynamic positioning and static pen structure were constructed, realizing the intelligent matching of precise cattle positioning with their pen locations, providing a reliable basis for behavior analysis and management decisions.
[0024] By integrating precise positioning data, acceleration sensor information, and historical behavior patterns, a multi-level abnormal behavior detection model was established, enabling early warning of abnormal cattle health and improving the level of intelligent breeding management. Attached Figure Description
[0025] To more clearly illustrate the technical solutions of the embodiments of this disclosure, the drawings used in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of this disclosure. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0026] Figure 1 A flowchart illustrating a method and system for precise positioning of cattle in a barn, as provided in this application embodiment;
[0027] Figure 2 This is a schematic diagram of a method and system for precise positioning of cattle in a pen, provided in an embodiment of this application. Detailed Implementation
[0028] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0029] To make the objectives, technical solutions, and advantages of the present invention clearer, the present invention will be further described in detail below with reference to specific embodiments and accompanying drawings.
[0030] Example 1
[0031] like Figure 1 As shown, this embodiment provides a method for locating cattle in a pen, including the following steps:
[0032] S1: Deploy a Bluetooth beacon network within the enclosure, collect environmental feature datasets of the enclosure, construct a Bluetooth beacon node deployment coordinate map based on the environmental feature datasets, install Bluetooth beacon nodes in the enclosure according to the deployment coordinate map, and construct a Bluetooth beacon network using a topology adaptive algorithm.
[0033] In this embodiment, a comprehensive environmental survey of the barn was first conducted, collecting environmental characteristic data including the barn's three-dimensional spatial dimensions, wall material properties, column locations, and functional zoning layout. Technicians used a laser rangefinder to measure the barn's length, width, and height, recording the type and thickness of materials such as concrete walls and metal railings, as different materials exhibit significantly different attenuation characteristics for 2.4GHz Bluetooth signals. Simultaneously, the locations of fixed facilities such as feed troughs and waterers needed to be marked, and the density distribution of cattle was observed at different times, as cattle bodies absorb and attenuate signals by 5-8 dB.
[0034] Based on the collected data, a 3D digital model of the pen was constructed using wireless network planning software, and signal propagation simulation parameters were configured. The propagation, reflection, and attenuation processes of Bluetooth signals were simulated using a ray tracing algorithm to generate coverage heatmaps and accuracy distribution maps. A multi-objective optimization algorithm (such as a genetic algorithm) was employed to find the optimal balance between coverage, positioning accuracy, and cost, determining the 3D coordinates of each beacon. Optimization required that at least three beacon signals could be received at any location within the pen, the geometrical precision factor (GDOP) in critical areas was less than 3, and the beacon installation height was set at 3-3.5 meters to avoid obstruction by cattle.
[0035] On-site installation is carried out based on the generated deployment coordinate map. Each installation point is precisely located using a laser rangefinder, and the beacons are fixed to pillars, beams, and other locations using expansion bolts or clamps. After installation, a beacon network is constructed using a topology adaptive algorithm. This algorithm automatically discovers adjacent beacon nodes, establishes communication links, forms a mesh topology, and dynamically adjusts network routing based on signal quality to ensure the reliability and real-time performance of data transmission.
[0036] S2: Install positioning tags on cattle, collect RSSI signal strength data and RTT ranging data between the positioning tags and each Bluetooth beacon node, and fuse the RSSI signal strength data and RTT ranging data through a secondary improved algorithm of edge estimation using independent set query to generate the initial position coordinate set of the cattle.
[0037] In this embodiment, the first step is to attach a positioning tag to each cow. These tags are typically ear tags or collars. Ear tags weigh approximately 15-25 grams, are fixed to the cow's ear, have an IP67 waterproof and dustproof rating, and include a built-in Bluetooth 5.0 chip and lithium battery, providing a battery life of 12-18 months. During installation, each cow is assigned a unique tag ID, and a mapping relationship between the cow's file and the tag ID is established in the system, recording basic information such as breed, age, and weight. The tag actively sends signals at a set broadcast interval (usually 500-1000 milliseconds) while simultaneously receiving broadcast signals from surrounding beacon nodes.
[0038] The positioning tag establishes bidirectional communication with each Bluetooth beacon node, collecting two types of key ranging data. RSSI (Received Signal Strength Indicator) data reflects the degree of signal power attenuation and can estimate distance using a logarithmic distance path loss model, but it is susceptible to environmental multipath effects and obstruction by cattle, with errors reaching 2-3 meters. RTT (Round-Trip Time) data calculates distance by measuring the signal's round-trip propagation time, offering higher accuracy (error approximately 0.5-1 meter), but requires time synchronization and precise timestamp exchange between the beacon and the tag. The system continuously collects RSSI and RTT data between the tag and all visible beacons (typically 3-6), acquiring 10-20 samples per second.
[0039] The collected raw data contains noise and outliers, requiring fusion processing using a secondary improved algorithm for edge estimation via independent set query. This algorithm first performs Kalman filtering on the RSSI data to reduce noise and eliminate transient fluctuations. Then, it identifies reliable beacon-tag connections using the independent set query method, discarding edges with poor signal quality or severe occlusion. Next, it performs a secondary improvement on edge estimation, using RTT data to correct the distance estimated by RSSI, and obtains a more accurate distance estimate through weighted fusion (RTT weight 0.6-0.7, RSSI weight 0.3-0.4). Finally, using trilateration or least squares methods, based on the fused distance data and beacon coordinates, it calculates the two-dimensional or three-dimensional position coordinates of the cattle, generating an initial position coordinate set to provide basic data for subsequent trajectory optimization.
[0040] It should be noted that the Independent Set Query for Edge Estimation with Quadratic Refinement Algorithm (ISQ-EE) is an advanced positioning algorithm specifically designed for fusing multi-source ranging data. The core idea of this algorithm is to treat RSSI signal strength data and RTT round-trip time delay ranging data as "edges" in a graph structure. It identifies and filters high-quality ranging edges using independent set theory, and then employs a quadratic optimization method to fine-tune the edge weights and distance estimates, ultimately generating a reliable initial set of position coordinates. This algorithm is particularly suitable for scenarios with multipath effects, signal obstruction, and ranging errors in complex indoor environments, effectively improving positioning accuracy and robustness.
[0041] The ISQ-EE algorithm is based on graph theory, set theory, and optimization theory. First, the algorithm models the localization problem as a weighted graph structure: the nodes in the graph include Bluetooth beacon nodes with known locations and cattle tag nodes to be located; edges represent the distance measurement relationships between nodes; and the weights of the edges reflect the quality and reliability of the distance measurement data. In a pen environment, due to factors such as cattle movement, metal fence obstruction, and multipath reflection, the quality of different distance measurement edges varies greatly. Some edges may be severely interfered with, providing incorrect distance estimates. If all edges are used directly for localization calculations, the localization results will deviate significantly from the true location.
[0042] The introduction of independent set lookup techniques solves this problem. In graph theory, an independent set is a subset of nodes in a graph where no two nodes are connected by an edge. The algorithm extends this concept to edge selection: by constructing an "edge conflict graph," where each ranging edge is a node, if the ranging results of two edges are geometrically contradictory (e.g., a triangle formed by three edges severely violates the triangle inequality), an edge is connected between these two nodes to indicate a conflict. The algorithm then finds the maximal independent set in this edge conflict graph, i.e., selects a subset of non-conflicting, geometrically consistent ranging edges. This process is essentially a robust edge filtering process that automatically excludes low-quality and contradictory ranging data.
[0043] After selecting a high-quality edge set, the algorithm enters the second improvement stage. This stage employs a nonlinear least squares optimization method to construct an objective function that minimizes the ranging error. Let the position of the cow tag be... , No. The known locations of the beacon nodes are: The distance estimate provided by the ranging edge is Then the Euclidean distance is The objective function is defined as the weighted sum of squared distance errors of all selected edges:
[0044]
[0045] in It is the set of edges selected by independent set query. It is the first The weight of an edge reflects its reliability. The weight is dynamically calculated based on the quality indicators of RSSI and RTT data; for example, the higher the signal strength and the smaller the RTT measurement variance, the greater the weight.
[0046] The "secondary" in "secondary improvement" has two meanings: First, the objective function adopts the squared error form, making the optimization process more sensitive to large errors and effectively suppressing the influence of outliers; second, the optimization process employs an iterative refinement strategy. After the initial solution, the weights of the edges are readjusted based on the residual distribution, reducing the weights of edges with large residuals or eliminating them entirely, before performing a second optimization. This two-round optimization mechanism further enhances the algorithm's robustness to outlier data.
[0047] A complete implementation of the ISQ-EE algorithm includes the following detailed steps:
[0048] Step 1: Data Preprocessing and Quality Assessment. The algorithm first receives the raw RSSI and RTT data. For RSSI data, a logarithmic distance path loss model is used to convert the signal strength into a distance estimate. This model is expressed as:
[0049]
[0050] in It refers to the signal strength at a reference distance (usually 1 meter). This is the path loss index, which typically ranges from 2.5 to 4.0 in a fenced environment; the specific value is determined through on-site calibration. For RTT data, the distance estimate is:
[0051]
[0052] in It's the speed of light. This is the round-trip time. Since Bluetooth signals travel at near the speed of light, this formula provides a relatively accurate distance estimate.
[0053] Next, the algorithm performs a quality assessment on each ranging edge and calculates a quality score. The quality assessment comprehensively considers multiple factors: the stability of RSSI signal strength (measured by calculating the variance of RSSI within a short time window; the smaller the variance, the more stable the signal); the consistency of RTT measurements (the standard deviation of multiple RTT measurements; the smaller the standard deviation, the more reliable the measurement); the rationality of geometric distribution (the line-of-sight conditions between beacon nodes and tags, determined by the fence structure database to identify any significant obstructions); and the consistency between RSSI and RTT ranging results (the smaller the difference between the two, the higher the quality score). The quality score is normalized to between 0 and 1. Edges with scores below a preset threshold (e.g., 0.3) are marked as low-quality edges and their weight is reduced or they are excluded in subsequent processing.
[0054] Step 2: Construct the ranging graph and the edge conflict graph. The algorithm constructs the ranging graph. , where the node set Includes all Bluetooth beacon nodes and cattle tag nodes to be located, edge set Includes all available ranging edges. Each edge Additional attributes: Start and end node IDs, distance estimate quality score Data source (RSSI, RTT, or fusion).
[0055] Then, construct the edge conflict graph. The node set is the edge set of the ranging graph. edge set This represents the conflict relationship between edges. Conflict determination is based on a geometric consistency check: for any three edges... If they form a triangle (i.e., connect the three nodes), check if the triangle inequality is satisfied:
[0056]
[0057] If the violation of the triangle inequality exceeds a tolerance threshold (considering ranging error, typically set to 20%), then at least one of the three edges is deemed to have a serious error. The algorithm further analyzes the problem by comparing the quality scores of each edge, marking the edge with the lowest quality as a suspicious edge and adding a conflicting edge between it and the other two edges in the edge conflict graph. This process is performed on all possible triangle combinations, ultimately yielding a complete edge conflict graph.
[0058] Step 3: Independent Set Query and Edge Selection. The maximum independent set query algorithm is executed on the edge conflict graph. Since finding the maximum independent set is an NP-hard problem, the algorithm uses a greedy approximation: First, all edges are sorted in descending order of quality score; then, starting with the edge with the highest quality, edges are added to the independent set sequentially. For each added edge, all edges that conflict with it are removed from the candidate set; this process is repeated until the candidate set is empty. While this greedy strategy cannot guarantee finding the globally optimal maximum independent set, it can quickly find a high-quality approximate solution and prioritizes retaining high-quality edges.
[0059] To further optimize edge selection, the algorithm also considers geometric coverage. If the selected set of independent edges is too concentrated in spatial distribution (e.g., all beacon nodes are located on the same side of the cows), it will lead to a decrease in positioning accuracy. Therefore, the algorithm introduces a geometric diversity reward during the greedy selection process: if the addition of an edge can significantly improve the spatial distribution of beacon nodes (e.g., by increasing ranging constraints in different directions), its priority is increased. The final set of selected independent edges... It ensures both geometric consistency and good spatial coverage.
[0060] Step 4: Fusing RSSI and RTT data. For edges selected into the independent set, if both RSSI and RTT ranging data are available, the algorithm fuses the data to obtain a more accurate distance estimate. The fusion uses a weighted average method:
[0061]
[0062] Weight and The weights are dynamically determined based on their respective measurement uncertainties. RTT ranging is generally more accurate but is significantly affected by multipath effects, while RSSI ranging has lower accuracy but is less sensitive to occlusion. RTT has a higher weight when line-of-sight is good; RSSI has a relatively higher weight when occlusion exists. Specific weights are calculated using Bayesian estimation methods, taking into account measurement variance and environmental context information.
[0063] Step 5: Initial position calculation. Based on the selected edge set. Based on the fused distance estimates, a nonlinear least squares optimization problem is constructed. The objective function, as previously described, is the weighted sum of squared distance errors. The optimization variable is the 3D position of the cattle tags. The algorithm employs the Levenberg-Marquardt (LM) method, an iterative optimization algorithm that combines the advantages of gradient descent and the Gauss-Newton method, and is particularly effective for nonlinear least squares problems.
[0064] The LM algorithm requires an initial position estimate as the starting point for iterations. The initial position is calculated using a simple centroid method: select the 3 to 4 beacon nodes with the highest mass scores, draw spheres with their positions as centers and the distance measurement results as radii, and find the approximate intersection point of these spheres as the initial position. Although this initial estimate may not be precise enough, it provides a reasonable starting point for LM iterations.
[0065] The LM algorithm iteratively updates the position estimate. In each iteration, it calculates approximate values for the Jacobian and Hessian matrices of the objective function, then solves a system of linear equations to obtain the position update. This iterative process continues until the improvement in the objective function is less than a preset threshold (e.g., ...). Or, the maximum number of iterations (e.g., 100) is reached. The initial position solution result is then obtained. .
[0066] Step 6: Residual Analysis and Weight Adjustment. After the initial solution is completed, the algorithm calculates the residual for each edge, which is the difference between the actual distance and the distance estimate:
[0067]
[0068] Analyze the residual distribution to identify outlier edges. If the residual of an edge is significantly larger than that of other edges (e.g., the residual is more than 3 times the median), it is determined that the edge may still have a large error and its weight needs to be reduced. The algorithm uses robust M-estimation theory and recalculates the edge weights using the Huber loss function or the Tukey double-weight function.
[0069]
[0070] in It is a weighting function. It is a robust standard deviation estimate of the residuals. The Huber function assigns linear weights to small residuals and constant weights to large residuals, thereby limiting the impact of outliers. The Tukey function, on the other hand, sets residuals to zero completely for those exceeding a certain threshold, thus thoroughly eliminating extreme outliers.
[0071] Step 7: Secondary Optimization Solution. Using the adjusted weights, reconstruct the optimization problem and execute the LM algorithm again. This optimization uses the initial solution as the basis for the final solution. As initial values, they can usually converge quickly to a more accurate solution. Since the influence of abnormal edges has been suppressed, the results of the secondary optimization are usually closer to the true position than the initial results.
[0072] The algorithm can be iterated further, performing a third and fourth optimization, adjusting the weights each time based on the new residuals. However, in practice, it has been found that two optimizations are usually sufficient, and further iterations result in diminishing returns and increase computation time. Therefore, the algorithm defaults to performing two optimizations, i.e., "secondary improvement".
[0073] Step 8: Multiple Hypothesis Testing and Final Selection. To further improve robustness, the algorithm can generate multiple location hypotheses. In the independent set selection stage, instead of selecting the largest independent set, the top few independent sets with the highest quality scores (e.g., the top 3) are selected. Quadratic optimization is performed on each independent set to obtain multiple candidate locations. Then, a consistency check is used to select the final location: the distances between candidate locations are calculated. If most candidate locations are clustered within a small area (e.g., less than 0.5 meters apart), their weighted average is taken as the final location; if candidate locations are scattered, the candidate with the smallest objective function value (i.e., the smallest fitting error) is selected as the final location, but this location is marked as having low confidence to alert subsequent processing modules.
[0074] Step 9: Output the initial position coordinate set. The algorithm outputs the initial position coordinates of the cows. The system also includes relevant quality metrics: location accuracy estimation (calculated based on the covariance matrix during the optimization process, typically expressed as the semi-axis length of the 95% confidence ellipsoid), confidence score (between 0 and 1, comprehensively reflecting the reliability of the positioning results), the number and quality distribution of edges used, and residual statistics. This information provides crucial reference for subsequent map optimization and positioning optimization modules.
[0075] S3: Based on the structural features of the enclosure, a grid map is established, and the grid map is optimized using the low-diameter wiring decomposition technology to realize the full dynamic algorithm of the drawing wrench, generating optimized location data.
[0076] Based on the characteristics of the pen environment, a refined grid map is constructed, and a fully dynamic algorithm for the diagram wrench is implemented through low-diameter wiring decomposition, optimizing the signal propagation model and improving positioning accuracy. Based on the actual pen layout, a 3D digital model including structural elements such as walls, partitions, and feeding areas is established to generate a basic environmental model. The basic environmental model is then gridded according to a preset precision, and each grid cell is assigned a physical attribute label to form an attribute grid map. Using the Bluetooth beacon network established in step S1, signal strength sampling measurements are performed within the pen, and the sampled data is mapped onto the grid map to generate a signal propagation characteristic layer. Based on the grid map, a fully dynamic algorithm for the diagram wrench is implemented using low-diameter wiring decomposition technology, simplifying the signal propagation path in complex environments into several sub-path sets. The initial position coordinate set obtained in step S2 is matched and analyzed with the grid map, and the positioning results are optimized through a probability distribution model, outputting grid-matched and corrected position data.
[0077] It should be noted that the Low-Diameter Routing Decomposition for Fully Dynamic Graph Spanner Algorithm (LDRD-FDGS) is an advanced graph optimization algorithm specifically designed to handle dynamically changing spatial topologies. This algorithm abstracts a raster map into a weighted graph structure and decomposes a complex graph into multiple smaller-diameter sub-clusters using low-diameter routing decomposition technology. A graph spanner structure is then constructed on each sub-cluster, significantly reducing the number of edges while maintaining approximate path lengths. Its fully dynamic nature allows the algorithm to efficiently handle dynamic insertion and deletion operations of nodes and edges, adapting to dynamic scenarios such as cattle movement and obstacle changes in a pen environment. The core objective of the algorithm is to optimize the initial position coordinates, constraining them to physically reachable spatial locations, eliminating unreasonable positioning results such as "wall-penetrating" and "boundary crossing" caused by ranging errors, while maintaining computational efficiency to support real-time positioning applications.
[0078] The LDRD-FDGS algorithm integrates computational geometry, graph theory, and dynamic data structure theory. First, understanding the concept of a graph wrench is crucial. Given a weighted graph... ,in It is a set of nodes. It is an edge set. It is an edge weight function, a graph wrench. yes A subgraph (i.e. ), to satisfy the requirements Any two nodes and They are in The shortest path distance in With The shortest path distance in The stretch factor constraint is satisfied between them:
[0079]
[0080] in This is called the stretch factor. The significance of the graph wrench is that it approximates the distance relationships of the original graph with fewer edges, thereby significantly reducing the computational complexity of subsequent path planning and distance lookup.
[0081] In the scenario of fence location, each grid cell in a raster map corresponds to a node in the graph. Adjacent walkable grid cells are connected by edges, and the edge weights represent the movement cost (usually Euclidean distance). Since raster maps typically contain thousands to tens of thousands of nodes, directly performing path optimization calculations on the complete graph is extremely costly. The graph wrench technique significantly improves computational efficiency while ensuring path quality by retaining key edges and removing redundant edges.
[0082] Low-diameter routing decomposition (LDD) is key to building high-quality graph wrenches. The diameter of a graph is defined as the maximum value of the shortest path between any two nodes. A smaller diameter leads to more efficient communication and path planning between nodes. However, for large-scale raster maps, the overall diameter is often very large. LDD decomposition decomposes the graph into multiple sub-clusters with smaller diameters. Each cluster contains local graph wrenches, and clusters are connected by a small number of bridging edges. This hierarchical structure is similar to the "main road-branch road" system in road networks: dense connections within clusters ensure local reachability, while sparse connections between clusters ensure global connectivity, achieving an optimal balance between edge count and path quality.
[0083] The decomposition process employs a randomized clustering algorithm. The algorithm randomly selects a set of central nodes, and each central node expands outwards to form a cluster, with the expansion radius controlled within a certain range. Within (i.e., the diameter of the cluster does not exceed) Key parameters The choice affects the quality of decomposition: Too small a cluster size results in an excessive number of clusters and high overhead for inter-cluster connections. Excessive cluster size leads to high internal complexity and poor local optimization performance. The algorithm, through theoretical analysis and experimental tuning, selects... (in Using the number of nodes as the optimal value, it theoretically guarantees the number of logarithmic clusters and the diameter of logarithmic clusters.
[0084] The fully dynamic nature is another core innovation of the algorithm. Traditional graph wrench algorithms are usually static, meaning they construct the wrench only once the graph structure is determined, making it inefficient for handling subsequent graph changes. In a barn environment, cattle movement causes dynamic changes in the accessibility of certain areas (e.g., cattle gathering causes temporary blockage of passageways), and adjustments to barn facilities alter the distribution of obstacles. The fully dynamic algorithm maintains a dynamic graph wrench structure, supporting efficient edge insertion and deletion operations, with a time complexity of O(log n) for each operation. Far lower than rebuilding the entire wrench Complexity.
[0085] Dynamic maintenance is achieved through a hierarchical data structure. The algorithm maintains a multi-layered graph wrench, each corresponding to a different time scale. The bottom layer is the real-time layer, reflecting the latest graph changes, with a high update frequency but small coverage; the middle layer is the buffer layer, periodically merging changes from the bottom layer, with a medium update frequency; the top layer is the stable layer, reflecting a long-term stable graph structure, with a low update frequency but global coverage. Query operations are executed in parallel across multiple layers, and the results from each layer are merged to obtain the final answer. Insertion or deletion operations first operate on the bottom layer. When the accumulated changes at the bottom layer reach a certain scale, a batch merging of the upper layers is triggered. This delayed batch processing mechanism amortizes the update cost.
[0086] The specific mechanism for position optimization is as follows: Given initial position coordinates The algorithm first locates the corresponding grid cell on the grid map. If the cell is walkable (i.e., not a wall or obstacle), the location is valid; if the cell is impassable, the location needs to be projected to the nearest walkable cell. The projection process is not a simple nearest neighbor search, but a constraint path search based on a graph wrench: starting from the initial location, it finds the nearest physically reachable node on the graph wrench and corrects the location to the grid center corresponding to that node. This graph wrench-based projection ensures that the corrected location is not only spatially close to the initial location but also topologically reachable, avoiding incorrectly projecting the location to physically isolated areas (e.g., projecting the location from one room to another room on the other side of a wall).
[0087] A complete implementation of the LDRD-FDGS algorithm includes the following detailed steps:
[0088] Step 1: Raster Map Construction and Graph Abstraction. The algorithm first constructs a raster map based on the structural features of the barn. The three-dimensional space of the barn is discretized into regular cubic raster cells. The raster resolution is determined according to the positioning accuracy requirements, typically set to 0.2 meters to 0.5 meters. Each raster cell is marked as either passable or impassable. Passable cells include spaces where cattle can move, such as passageways, lying areas, and feeding areas; impassable cells include physical obstacles such as walls, fences, equipment, and water troughs. Raster markings are obtained from barn CAD drawings or on-site measurements and stored in a three-dimensional array.
[0089] raster map converted to graph structure Each passable grid cell corresponds to a node, and the node coordinates are the 3D coordinates of the grid center. If the corresponding grid cells of two nodes are spatially adjacent (including face adjacency, edge adjacency, and point adjacency, a total of 26 neighbor directions) and both are passable, then an edge is added between them. The edge weight is the Euclidean distance between the two nodes; for example, the edge weight for face adjacency is the grid side length. The weight of an adjacent edge is The weight of the edge adjacent to the point is For large-scale graphs, the number of nodes can reach tens of thousands or even hundreds of thousands, and the number of edges is several times the number of nodes. Directly processing such dense graphs is computationally very expensive.
[0090] Step 2: Low-diameter wiring decomposition. The algorithm performs low-diameter wiring decomposition, transforming the image... The decomposition process is divided into multiple low-diameter clusters. The decomposition process employs a randomized Ball-Growing algorithm.
[0091] First, set the cluster diameter parameter. Calculated based on the graph size, typically ,in It is a constant (e.g.) ), It refers to the number of nodes. For example, for a graph containing 10,000 nodes, Units (in terms of grid side length).
[0092] Then, initialize all nodes to an unassigned state, and the cluster set is empty. Iteratively execute the following process: randomly select a node from the unassigned nodes. As the cluster center; from The process begins with a restricted breadth-first search (BFS), with the search radius limited to a certain value. Add all unassigned nodes found in the search to the new cluster. ; cluster Add to the cluster set and mark all nodes in the cluster as assigned; repeat the above process until all nodes are assigned to a cluster.
[0093] The clusters generated in this process have the following property: the diameter of each cluster does not exceed [a certain value]. (because the distance from any two nodes within a cluster to the center does not exceed) The distance between them does not exceed The number of clusters is (in the two-dimensional case) or (In the three-dimensional case), because the spatial volume covered by each cluster is approximately The total space volume is approximately Clusters may overlap (boundary nodes may be contained in multiple clusters), but the degree of overlap is limited.
[0094] Step 3: Constructing the intra-cluster graph wrench. For each cluster... Construct a local diagram wrench within it. The cluster-wide wrench construction uses a greedy algorithm:
[0095] initialization An empty graph (containing clusters) (All nodes but no edges). Cluster All edges within the boundary are sorted in ascending order of their weights. Each edge is examined sequentially. :calculate and In the present The shortest path distance in (If they are not connected, the distance is infinite); if (in It is the target stretch factor, usually taken as... arrive If the edge is... join in Otherwise, skip the edge (because the existing path is good enough). Continue processing the next edge until all edges have been examined.
[0096] This greedy algorithm guarantees the generation of... It is a cluster One - Wrench: For any two nodes within a cluster and They are in The shortest path distance in the cluster graph does not exceed the shortest path distance in the original cluster graph. The algorithm prioritizes retaining shorter sides and only adds longer sides when necessary. The number of edges in the cluster graph is usually much smaller than the number of edges in the original cluster graph, thus achieving sparsity.
[0097] Step 4: Selection of inter-cluster bridging edges. After the intra-cluster wrench is constructed, connections need to be established between clusters to ensure global connectivity. The selection of inter-cluster bridging edges is crucial: too few bridging edges may lead to some cluster pairs being unable to connect or the paths being too long; too many bridging edges negate the purpose of sparsity.
[0098] The algorithm employs a boundary node matching strategy: for each cluster Identify its set of boundary nodes That is, a node that is connected to other clusters by an edge; for a cluster Each boundary node Find it in the original image All edges connecting a node to other clusters are potential bridging edge candidates; for each pair of neighboring clusters... Choose the connection with the smallest weight. The strip edge is used as a bridging edge (usually) arrive Add global map wrench .
[0099] This strategy ensures sufficient connections between adjacent clusters to maintain path quality, while controlling the overall number of edges by limiting the number of bridging edges. Theoretical analysis shows that the total number of bridging edges is... It is much smaller than the number of sides of the original graph. .
[0100] Step 5: Global graph wrench construction. Construct all cluster-level wrenches. Merging the inter-cluster bridging edges yields the global graph wrench. The global graph wrench has the following properties: its node set is the same as the original graph (containing all passable grids); its edge set is a subset of the edge set of the original graph, and the number of edges is . Much smaller than the original image Count of edges (In a dense raster graph, each node has approximately 26 neighbors, and the total number of edges is approximately...) For any two nodes in the original graph and They are in The shortest path distance in the equation satisfies (The stretching factor squared is because the path may cross multiple clusters, and each cluster introduces...) Stretching may also introduce inter-cluster bridging. (twice the stretch).
[0101] In practical applications, This is a commonly used choice, in which case the global stretch factor is... This means that the path length in the graph wrench does not exceed four times the shortest path in the original graph. This stretching factor is acceptable in practice because positioning applications are more concerned with the topological reachability of paths than with the exact shortest path, and a four-fold stretch results in a reduction of tens of times in the number of edges and a computational speedup.
[0102] Step 6: Dynamically maintain data structure initialization. To support fully dynamic operations, the algorithm initializes a multi-layer graph wrench structure. (Settings...) Layer (usually) arrive One wrench is needed for each floor maintenance. The bottom layer Initially empty, used to receive real-time updates; intermediate layer arrive Initially empty, serving as a buffer layer; top layer Initialize the global graph wrench built in the previous steps , serving as a stable foundation layer.
[0103] Each layer is associated with a timestamp and a change counter, recording the last update time and the cumulative number of changes for that layer. A layer merging threshold is set: when the number of changes for a layer exceeds the threshold... (For example, , , This triggers a merge operation with the upper layer.
[0104] Step 7: Position Optimization. Given initial position coordinates... Algorithm execution location optimization:
[0105] First, the continuous coordinates are discretized to a raster index. The raster index is then calculated. :
[0106]
[0107] in This is the grid side length. Check the grid. Walkability: If the grid is walkable, the initial position is valid and no correction is needed; output... If the grid is impassable, it needs to be projected onto a passable area.
[0108] The projection process is based on the nearest reachable node search using a graph wrench. From the raster... Starting from the beginning, search for passable grid cells within its 26-neighborhood. If found, adjust the position to the center of that grid cell; if none are passable within the 26-neighborhood (i.e., the initial position is deep inside obstacles), expand the search area. Perform Dijkstra's shortest path search on the above, with the goal of finding the distance... Nearest passable node .
[0109] Distance metrics use a weighted combination:
[0110]
[0111] in It is Euclidean distance. It is the shortest path distance in the diagram wrench. It is a reference node (usually the nearest passable node). and These are weighting coefficients (e.g.) This metric balances spatial proximity and topological reachability: the Euclidean distance term ensures that the corrected position is spatially close to the initial position, while the graph distance term ensures that the corrected position is topologically reachable, avoiding crossing physical barriers.
[0112] The search process is performed on a graph wrench, which significantly speeds up the process by leveraging the wrench's sparsity. The optimal node is found. Then, the position was corrected to Corresponding grid center coordinates This serves as the optimized position output.
[0113] Step 8: Dynamic Update Processing. When the enclosure environment changes (e.g., a temporary fence is erected, or a passage is blocked), the graph structure needs to be updated. Dynamic update operations include simultaneous deletion and insertion:
[0114] Edge deletion operation: Given the edge to be deleted The algorithm is first implemented at the underlying level. In the middle of the record deletion operation, increment the change counter; check Is it on the top floor? If it is in the middle, mark the edge as "to be deleted", but do not remove it immediately. Remove from the middle (delayed deletion); if the underlying change counter exceeds the threshold. Triggering Merging: Collection All delete operations in batches are applied to Rebuild The affected part; similarly, when Changes accumulate to a threshold At that time, towards Merging, ultimately spreading to the top level. .
[0115] Edge insertion operation: Given the edge to be inserted The algorithm is at the underlying level. Add the edge to the list and increase the change counter; check... If the graph wrench condition is met (i.e., whether the distance between certain node pairs has been shortened), the edge is retained; otherwise, it is marked as a redundant edge and may be removed during subsequent merging. The insertion operation is also propagated to the upper layer through inter-layer merging.
[0116] Query operations (such as shortest path search in location optimization) are executed in parallel across multiple levels: at the bottom level... Search upwards, considering the latest changes; at the top level The system performs an upper-level search, utilizing a stable global structure; it then merges the results from both layers to select the optimal path. This multi-layered query mechanism ensures that the query results reflect the latest changes while maintaining global optimality.
[0117] Step 9: Performance Optimization and Caching. To further improve performance, the algorithm implements several optimization techniques:
[0118] Spatial Indexing: Using KD-trees or R-trees to spatially index nodes accelerates nearest neighbor and range queries. When performing location projection, the spatial index is first used to quickly locate the candidate node set, and then an exact search is performed on the candidate set, avoiding traversing all nodes.
[0119] Path caching: For frequently queried node pairs, the shortest path between them is cached. The cache uses an LRU (Least Recently Used) strategy to limit its size. When the graph structure is updated, affected cached items are invalidated. Path caching is particularly effective in cattle location scenarios because cattle typically move within fixed areas, and location queries exhibit spatial locality.
[0120] Incremental update: When the graph changes only slightly (e.g., only a few edges are deleted or inserted), the incremental update algorithm is used. This involves recalculating only the affected local regions, rather than reconstructing the entire graph. Incremental update is achieved by maintaining edge dependencies: recording the "support set" of each edge, which is the set of node pairs that depend on that edge; when an edge is deleted, only the paths of the node pairs in the support set need to be recalculated, and the relevant edge is updated.
[0121] Parallelization: The graph wrench construction and query operations exhibit good parallelism. Intra-cluster wrench construction can be executed in parallel because different clusters are independent of each other; multi-level queries can be executed in parallel, and the results are finally merged. The algorithm implementation employs multi-threaded parallelism, making full use of multi-core processors to further improve performance.
[0122] Step 10: Output the optimized location data. The algorithm outputs the optimized location coordinates. And related quality metrics: optimization type (no correction, neighborhood projection, graph search projection), correction distance (Euclidean distance between positions before and after optimization), topological distance (shortest path distance between positions before and after optimization on the graph wrench), and confidence (calculated based on correction distance and topological distance; the smaller the correction distance, the higher the confidence).
[0123] These optimized location data serve as inputs for subsequent Bayesian probabilistic models and positioning optimization, ensuring that all locations are physically reachable, avoiding unreasonable positioning results, and laying the foundation for the accuracy and reliability of the entire positioning system.
[0124] Technical Implementation Examples
[0125] The following example illustrates the operation of the LDRD-FDGS algorithm. Assume a medium-sized dairy barn with dimensions of 40m x 30m and a height of 3m, discretized using a 0.5m grid resolution. The barn includes four lying areas, two feeding areas, several passageways, and some equipment areas.
[0126] Grid map construction phase: The pen space was discretized into 80×60×6=28800 grid units. Based on the pen structure data, accessible and inaccessible grids were marked. Approximately 18,000 grids (62.5%) were accessible, including passageways, bedding areas, and feeding areas; approximately 10,800 grids (37.5%) were inaccessible, including walls, fences, and equipment.
[0127] Construction Graph There are 18,000 walkable grid cells corresponding to 18,000 nodes. For each node, its 26 neighbors are checked, and if a neighbor is also walkable, an edge is added. After counting, the graph contains approximately 18,000 nodes and approximately 110,000 edges (an average of about 6 edges per node, because many nodes are located near boundaries or obstacles and have fewer than 26 neighbors).
[0128] Low-diameter wiring decomposition stage: Setting cluster diameter parameters Each grid unit is approximately 49 meters (based on a 0.5-meter grid). This diameter is sufficient to cover the main area of the enclosure, but not so large as to treat the entire enclosure as a cluster.
[0129] Execute the randomized Ball-Growing algorithm: In the first iteration, randomly select nodes. (Assuming the passageway is located in the center of the enclosure), from Start by executing BFS, with a radius limit of 1. One unit. Since the enclosure dimensions are 80×60 mm, with a radius of 49 mm, it can cover almost most of the area, but is limited by walls and obstacles, the actual cluster... It contains approximately 8,000 nodes (mainly the central passageway and adjacent sleeping areas).
[0130] In the second iteration, nodes are randomly selected from the remaining unassigned nodes. (Assuming the area is located in the upper left corner of the dormitory area), forming a cluster. It contains approximately 4000 nodes. In the third iteration, [the following was selected]. (The feeding area in the lower right corner) forms a cluster. It contains approximately 3500 nodes. In the fourth iteration, [the following was selected]. (The lower left corner of the sleeping area) forms a cluster. It contains approximately 2,500 nodes.
[0131] After four iterations, all 18,000 nodes were assigned to four clusters. Note that there is overlap between clusters: nodes in the boundary region may be contained in multiple clusters, but the total number of overlapping nodes does not exceed 1,000.
[0132] Cluster intragraph wrench construction phase: for clusters (8000 nodes, approximately 50000 edges), execute a greedy wrench algorithm for construction, stretching factor. The algorithm sorts the 50,000 edges by weight and examines them sequentially. The first 1,000 edges (with the lowest weight, usually adjacent edges) are almost entirely added to the wrench, because initially the graph is empty, and any edge can shorten the distance. As the wrench becomes denser, more and more subsequent edges are skipped. For example, consider the 5,000th edge. At that time, it was discovered and The current wrench is already connected via other paths, with a distance of [distance missing]. less than Therefore, we skip that edge.
[0133] Ultimately, cluster wrench It contains approximately 12,000 edges, only 24% of the original number, achieving significant sparsity. Similarly, the wrench for constructing other clusters: Approximately 6000 edges, Approximately 5500 edges, Approximately 4000 edges.
[0134] Inter-cluster bridging edge selection phase: Identifying boundary nodes between clusters. For example, cluster... and The boundary is the intersection of the central passage and the upper left ledge area, with approximately 50 boundary node pairs. Among these 50 node pairs, the 5 edges with the lowest weights are selected as bridging edges and added to the global wrench. Similarly, bridging edges are selected for the other cluster pairs. A total of approximately 60 bridging edges are added (4 clusters, 6 cluster pairs, approximately 10 bridging edges per pair).
[0135] Global graph wrench construction phase: Merge all intra-cluster wrenches and bridging edges to obtain the global graph wrench. . It contains 18,000 nodes and approximately 27,560 edges (12,000 + 6,000 + 5,500 + 4,000 + 60). Compared to the original graph's 110,000 edges, the number of edges has been reduced by 75%, significantly reducing the computational complexity in subsequent calculations.
[0136] S4: Establish a static structure database for the stalls, and construct a Bayesian probability model based on the initial position coordinate set to generate a mapping relationship between cattle and stalls.
[0137] In this embodiment, a static structure database for each stall is first established, recording attributes such as the unique number of each stall, spatial boundary coordinates (coordinates of the four corner points), geometric dimensions, functional type (dairy cow stall, dry cow stall, etc.), and maximum capacity. The database is stored in a spatial database format, supporting efficient spatial query operations.
[0138] A Bayesian probabilistic model is constructed using an initial set of location coordinates to infer the affiliation of cattle to their respective stalls through conditional probability. The model calculates the posterior probability P(stall|location) of a cattle belonging to a specific stall given its location. The prior probability P(stall) is set based on historical statistical data, reflecting the frequency of cattle occurrence in different stalls. The likelihood probability P(location|stall) is calculated using a spatial distance function; the probability approaches 1 when the location coordinates fall inside the stall, and decays according to a Gaussian distribution when outside the boundary, with the decay parameter σ set to 0.5-1.0 meters.
[0139] The model incorporates temporal constraints and uses Markov chains to calculate pen transition probabilities. The probability of transitioning between adjacent pens is 0.3-0.5, while that between distant pens is 0.01-0.05, consistent with the continuity of cattle movement. The model also considers time factors, indicating that cattle are more likely to be in the feed trough area during feeding hours and in the resting area during resting hours. Bayesian inference is used to calculate the posterior probability distribution of each cow across all pens, selecting the pen with the highest probability as its current affiliation. A mapping relationship between cow IDs and pen numbers is generated and recorded with timestamps to form a dynamically linked data stream.
[0140] S5: Based on the optimized location data and the mapping relationship, the positioning result is optimized by an adaptive robust resettable flow algorithm to generate the final positioning result.
[0141] In this embodiment, based on the optimized location data from step S3 and the mapping relationship from step S4, the positioning results are deeply optimized using an adaptive robust resettable flow algorithm. This algorithm first establishes a spatiotemporal constraint model, treating the cattle's position sequence as continuous flow data. It then uses Kalman filtering or particle filtering techniques to predict the cattle's next position, considering the continuity constraints of the cattle's movement speed (typically 0.5-1.5 m / s) and direction of movement during the prediction.
[0142] The adaptive mechanism dynamically adjusts the filtering parameters based on the location reliability. When a decline in location data quality is detected (e.g., severe RSSI fluctuations or a decrease in the number of visible beacons), the process noise covariance is automatically increased to relax the constraints on the motion model; when the data quality is good, the noise covariance is decreased to improve trajectory smoothness. Robustness is reflected in outlier detection and handling. The algorithm identifies outliers that deviate from the normal trajectory (e.g., sudden jumps of more than 3 meters) using RANSAC or M-estimation methods, marks them as outliers, and removes or corrects them.
[0143] A resettable flow mechanism handles prolonged occlusion or signal loss. When a cow enters a signal blind zone for more than a set threshold (e.g., 30 seconds), the algorithm triggers a reset operation, clearing the historical state buffer and reinitializing the filter. Once the signal is restored, combined with the stall mapping constraint (the cow must be in its assigned stall or adjacent lane), it quickly converges to the correct position. The algorithm outputs a final positioning result after spatiotemporal smoothing, anomaly removal, and physical constraint correction, improving positioning accuracy to 0.3-0.5 meters, significantly improving trajectory continuity and rationality, and meeting practical application requirements.
[0144] It should be noted that the Adaptive Robust Resettable Flow Algorithm (ARRF) is an advanced multi-source data fusion and state estimation algorithm specifically designed for high-precision positioning optimization in complex and dynamic environments. This algorithm models the positioning problem as a network flow optimization problem, where multiple data sources (optimized location data, pen mapping relationships, historical trajectories, sensor measurements, etc.) serve as input nodes to the flow. It dynamically balances the contributions of each data source through an adaptive weight adjustment mechanism, employs robust estimation techniques to suppress the influence of outliers and noise, and features a resettable mechanism to address systematic biases and cumulative errors. The core innovation of the algorithm lies in transforming the traditional point estimation problem into a flow optimization problem. It achieves optimal fusion of multi-source information through flow allocation and path selection, while ensuring robustness and long-term stability under various abnormal conditions through three major mechanisms: adaptive, robust, and resettable. This algorithm is particularly suitable for cattle positioning scenarios in pen environments with complex conditions such as interference from multiple cattle, signal obstruction, and equipment failure.
[0145] The ARRF algorithm's technical principles are based on network flow theory, robust statistics, and adaptive control theory. First, understand the core idea of flow network modeling: abstract the localization optimization problem into a directed weighted flow network. ,in It is a set of nodes, including source nodes (representing various data sources), intermediate processing nodes (representing fusion and optimization steps), and sink nodes (representing the final localization result); It is a directed edge set, representing the data flow path; It is a capacity function that defines the maximum flow of each edge (representing the upper limit of the reliability of the data source); It is a weighting function that defines the unit flow cost of each edge (representing the reciprocal of data quality).
[0146] In this network, the goal of localization optimization is to find the optimal flow allocation scheme from the source node to the sink node, minimizing the total cost while satisfying flow conservation and capacity constraints. The advantages of this modeling approach are: it can naturally integrate multiple heterogeneous data sources, with each data source acting as an independent source node, its contribution reflected in the flow rate; it can flexibly express the dependencies and constraints between data sources through network topology and edge capacity limitations; the optimization process has clear mathematical meaning, namely, a minimum cost flow problem, with efficient solution algorithms; and the flow allocation results intuitively reflect the actual contributions of each data source, facilitating analysis and debugging.
[0147] The adaptive mechanism is the algorithm's first core feature. In the pen environment, the quality of each data source is dynamically changing: Bluetooth signal strength fluctuates with cattle movement and environmental changes; pen mapping becomes more uncertain when cattle are at pen boundaries; and historical trajectories lose their reference value when cattle behavior changes abruptly. The adaptive mechanism dynamically adjusts the weights and capacities of corresponding edges in the flow network by monitoring the performance metrics of data sources in real time. This allows high-quality data sources to receive a larger flow allocation (i.e., higher weight), while the contribution of low-quality data sources is automatically suppressed.
[0148] Adaptive weight adjustment is based on innovation sequence analysis. An innovation sequence is a sequence of differences between observed and predicted values, reflecting the unpredictability and noise level of the data source. For each data source... The algorithm maintains a sliding window (typically containing the most recent 10 to 30 observations) and calculates the statistical properties of the innovation sequence within the window, including the mean. ,variance and autocorrelation coefficient Based on these statistics, the quality score of the data source is calculated. :
[0149]
[0150] in These are weighting coefficients, which respectively control for the impact of variance, bias, and correlation on quality assessment. Quality Score Normalized to between 0 and 1, a higher score indicates a more reliable data source. The weights of corresponding edges in the flow network are set to... The capacity is set to (in (This is the maximum capacity constant), thus enabling quality-driven flow allocation.
[0151] Robustness is the second core characteristic of the algorithm. In practical applications, outliers inevitably occur in data sources: Bluetooth signals may experience sudden changes in distance due to multipath interference, pen mapping may be incorrect due to cattle crossing pens, and sensor malfunctions may cause measurement failures. Traditional least squares estimation is extremely sensitive to outliers; a single outlier can cause the entire estimation result to deviate significantly. Robust estimation techniques, by employing loss functions and estimation methods that are insensitive to outliers, significantly improve the algorithm's resistance to interference.
[0152] The ARRF algorithm employs the M-estimation framework to achieve robustness. M-estimation replaces the traditional squared loss function... Replace it with a more robust loss function, such as the Huber loss function:
[0153]
[0154] Or Tukey's double-weight function:
[0155]
[0156] in It's about adjusting parameters to control the tolerance for outliers. The Huber function uses a squared penalty (similar to least squares) for small residuals and a linear penalty for large residuals, limiting the impact of outliers; the Tukey function is more aggressive, penalizing outliers exceeding a threshold. The residuals are completely truncated, thus eliminating extreme outliers.
[0157] In the flow network framework, robustness is achieved through the cost function of the edges. Let the data source be... The provided observation values are The current estimated value is The residual is Then the traffic cost of the edge corresponding to the data source is:
[0158]
[0159] in It is the flow through that edge. It is a robust loss function. It is an estimate of the standard deviation of the data source. This cost design automatically assigns higher costs to data sources with larger residuals (which may contain outliers) and allocates less traffic during traffic optimization, thereby reducing their impact on the final result.
[0160] The resettable mechanism is the third core feature of the algorithm. During long-term operation, the positioning system may encounter the accumulation of systematic biases: sensor drift causes measurement reference shifts, environmental changes cause signal propagation models to fail, and the algorithm's internal state gradually deviates from the true state due to numerical errors. These problems cannot be completely solved by adaptive and robust mechanisms because they affect the system's baseline rather than individual observations. The resettable mechanism clears accumulated errors and restores the system to a healthy state through periodic or triggered state resets.
[0161] The resettable mechanism comprises three levels: data-level reset, parameter-level reset, and model-level reset. Data-level reset clears the observation buffer and historical data, forcing the system to estimate only based on the most recent observations; suitable for situations where an overall degradation in the quality of the data source is detected. Parameter-level reset restores adaptive parameters (such as weights and capacity) to their default or safe values, eliminating potential parameter drift; suitable for situations where abnormal parameter fluctuations are detected. Model-level reset reinitializes the state estimator and filters, restoring the system state to a known reliable state; suitable for situations where state estimates diverge or deviate significantly.
[0162] Reset triggers a multi-dimensional health monitoring system. The algorithm continuously monitors key system metrics, including: the statistical characteristics of the innovation sequence (e.g., a sudden increase in variance, indicating a decline in predictive ability); the skewness and kurtosis of the residual distribution (deviation from a normal distribution, indicating a systematic bias); the stability of traffic allocation (frequent and large fluctuations, indicating unstable data source quality); and the physical reasonableness of the estimation results (e.g., velocity or acceleration exceeding a reasonable range). When one or more of these metrics exceed a preset threshold, a reset operation of the corresponding level is triggered.
[0163] The flow optimization solution employs a minimum-cost flow algorithm. Given a flow network and the cost functions of each edge, the algorithm seeks a flow allocation scheme from source nodes to sink nodes that minimizes the total cost. Since the cost function includes a robust loss term, the optimization problem is nonlinear, and an Iteratively Reweighted Least Squares (IRLS) method is used to solve it. In each iteration, the IRLS method calculates the weights of each data source based on the current estimate, then solves the weighted least squares problem to obtain a new estimate, repeating this process until convergence. This iterative approach naturally achieves robust estimation because the weights are adjusted according to the residual size in each iteration, gradually reducing the impact of outliers.
[0164] A complete implementation of the ARRF algorithm includes the following detailed steps:
[0165] Step 1: Flow Network Construction. The algorithm first constructs a localization-optimized flow network structure. The network contains the following node types:
[0166] Data source nodes: Each data source corresponds to one source node, including Bluetooth ranging source (providing distance estimation based on RSSI and RTT), field mapping source (providing field position constraints based on Bayesian probability), historical trajectory source (providing position prediction based on motion models), IMU sensor source (providing inertial navigation estimation based on acceleration and gyroscopes), and map constraint source (providing reachability constraints based on grid maps). Each source node There is an initial flow supply This indicates the amount of available information in the data source.
[0167] Fusion nodes: Intermediate processing nodes responsible for integrating information from different data sources. These include spatial fusion nodes (fusion of data sources providing location information), temporal fusion nodes (fusion of current observations and historical states), and constraint fusion nodes (fusion of hard and soft constraints). Fusion nodes satisfy the flow conservation principle: inflow equals outflow.
[0168] Sink node: Final location result node The sink node receives all the merged traffic; the inflow represents the total confidence level of the location results. The sink node has a traffic requirement. It is typically set to the sum of the supplies from all source nodes to ensure that all information is utilized.
[0169] The network edges connect source nodes to merge nodes, merge nodes to sink nodes, and between merge nodes. Each edge... It has the following attributes: capacity Limit the maximum flow of this edge; weight This represents the cost per unit of flow; flow rate , representing the actual allocated flow (optimization variable).
[0170] Specific construction process: Create 5 data source nodes (Bluetooth ranging) to (Map constraints) Set the initial supply to 100 units for all units; create 3 merge nodes. (Spatial integration) (Time fusion) (Constraint Fusion); Create 1 sink node Set the demand to 500 units (5 sources × 100); add edges: from each source node to the spatial fusion node. The capacity is initialized to 100, and the weight is initialized to 1.0; from Time fusion node With a capacity of 500 and a weight of 0.5; from To the constraint fusion node With a capacity of 500 and a weight of 0.3; from Remittance node The capacity is 500 and the weight is 0.1.
[0171] Step 2: Data Source Quality Assessment. For each data source, the algorithm calculates its current quality score, which is used for subsequent weight and capacity adjustments.
[0172] For Bluetooth ranging sources Quality assessment is based on signal strength stability and ranging consistency. The algorithm maintains a sliding window of the most recent 20 RSSI measurements and calculates the RSSI variance. Simultaneously, the consistency score is calculated by comparing the results of RSSI ranging and RTT ranging.
[0173]
[0174] in The consistency score ranges from 0 to 1; the closer the two ranging results are, the higher the score. The overall quality score is:
[0175]
[0176] For column mapping source Quality assessment is based on the concentration of Bayesian posterior probabilities. If the posterior probability of a certain column is much higher than that of other columns (e.g., ...), ... This indicates that the mapping result is reliable and has a high quality score; if the posterior probabilities of multiple columns are close (e.g., the highest probability), it indicates that the mapping result is reliable and has a high quality score. This indicates that the mapping is uncertain and the quality score is low. The specific calculation uses an entropy measure:
[0177]
[0178]
[0179] in It represents the maximum entropy (the entropy when all fields have equal probability). The smaller the entropy, the higher the quality score.
[0180] For the source of historical trajectory The quality assessment is based on the prediction error of the motion model. The algorithm uses a Kalman filter or particle filter to maintain the cattle's motion state and predict its position at the next moment. The predicted position is compared with the actual observed position (a fusion result from other data sources), and the prediction error is calculated. The mass fraction is:
[0181]
[0182] in This is an acceptable prediction error threshold (e.g., 1 meter). The more accurate the prediction, the higher the quality score.
[0183] For IMU sensor source The quality assessment is based on the degree of drift in inertial measurements. The position estimate provided by the IMU accumulates drift over time, and the algorithm assesses the current degree of drift by comparing the IMU estimate with other high-precision data sources (such as Bluetooth ranging). Let the drift distance be... The mass fraction is:
[0184]
[0185] in This is the maximum acceptable drift (e.g., 5 meters). The smaller the drift, the higher the mass fraction.
[0186] For map constraint sources The quality assessment is based on the consistency between the location and the map. A high quality score is awarded if the current location is estimated to be within a passable area and far from obstacles; a low quality score is awarded if the location is close to obstacle boundaries or located in an impassable area. Let the distance from the location to the nearest obstacle be... The mass fraction is:
[0187]
[0188] in This is the safe distance threshold (e.g., 0.5 meters). The farther away from the obstacle, the higher the quality score, but the upper limit is 1.
[0189] Step 3: Adaptive weight and capacity adjustment. Based on the calculated quality score, the algorithm dynamically adjusts the weights and capacities of each edge in the flow network.
[0190] For data source To the fusion node The capacity of the edge is adjusted as follows:
[0191]
[0192] in This is the base capacity (e.g., 100 units). Higher quality data sources receive larger capacities and can contribute more traffic.
[0193] The weights are adjusted as follows:
[0194]
[0195] in It is a small constant (e.g., 0.01) to prevent division by zero. High-quality data sources receive lower weights (lower costs) and are preferred in traffic optimization.
[0196] The adjustment process employs a smoothing mechanism to avoid drastic fluctuations in weights and capacities. The new value is merged with the old value using an exponential moving average.
[0197]
[0198]
[0199] in and This is the smoothing factor (usually between 0.7 and 0.9), which controls the adjustment speed. A larger smoothing factor results in smoother adjustments and improved stability; a smaller smoothing factor results in faster adjustments and improved responsiveness.
[0200] Step 4: Observation Data Collection and Residual Calculation. The algorithm collects observation data from each data source at the current time and calculates the residuals estimated relative to the current location.
[0201] Bluetooth ranging source Provide distance observation ,in Is it up to the The distance to each beacon. Let the current position be estimated as... beacon The position is The residual is:
[0202]
[0203] Field mapping source Provide column position constraints ,in It is a column The central location, This is the posterior probability that a cow is located in that pen. The residual is defined as the distance between the location estimate and the center of the most likely pen:
[0204]
[0205] in It is the center position of the column with the highest posterior probability.
[0206] Historical Trajectory Source Provide location prediction The current position is predicted from the previous state using a motion model. The residual is:
[0207]
[0208] IMU sensor source Provide inertial navigation estimation The position is obtained based on the integration of acceleration and gyroscope readings. The residual is:
[0209]
[0210] Map Constraint Source Provide reachability constraints That is, the nearest passable location. If If the path is passable, the residual is 0; otherwise, the residual is the distance to the nearest passable location.
[0211]
[0212] Step 5: Robust Weight Calculation. Based on the residuals, the algorithm uses a robust loss function to calculate a robust weight for each observation, which is then used for subsequent weighted optimization.
[0213] For the Bluetooth ranging source For each observation, the normalized residual is:
[0214]
[0215] in This is an estimate of the standard deviation of the ranging error (typically 0.5 to 1 meter). Robust weights are calculated using the Huber loss function:
[0216]
[0217] in This is the Huber threshold (typically 1.345, corresponding to 95% efficiency). Observations with residuals less than the threshold have a weight of 1 (full weight), while observations with residuals greater than the threshold have their weights reduced inversely to limit their impact.
[0218] Similarly, robust weights are calculated for observations from other data sources. For the field mapping source, considering the uncertainty of the posterior probability, the weights are adjusted as follows:
[0219]
[0220] That is, the product of Huber weight and maximum posterior probability, ensuring that only field constraints with high confidence receive larger weights.
[0221] Step 6: Optimize the flow. Based on the adjusted weights, capacity, and robust weights, the algorithm solves the minimum cost flow problem to obtain the optimal flow allocation.
[0222] The objective function to be optimized is:
[0223]
[0224] The constraints include: flow conservation constraint (for each intermediate node, the inflow equals the outflow); capacity constraint (the flow of each edge does not exceed its capacity); non-negativity constraint (the flow is non-negative); and supply-demand constraint (the outflow of the source node equals the supply, and the inflow of the sink node equals the demand).
[0225] Since the objective function includes a nonlinear robust loss term, the IRLS method is used for iterative solution. The IRLS algorithm framework is as follows:
[0226] Initialization: Set initial position estimation You can use the position from the previous time step or a weighted average of multiple data sources; set an iteration counter. .
[0227] Iterative steps: Estimate based on current position Calculate the residuals of all observations. Robust weights are calculated based on residuals. Constructing a weighted least squares problem:
[0228]
[0229] in It is a data source Observation models (such as for Bluetooth ranging) Solve the weighted least squares problem to obtain a new location estimate. Check convergence conditions: If (like Stop if the number of iterations reaches the maximum number (e.g., 20 times) or the maximum number of iterations is reached; otherwise, Return to the iteration step.
[0230] The weighted least squares problem can be solved using either the normal equation method or the gradient descent method. For linear or approximately linear observation models, the normal equation method is more efficient; for highly nonlinear models, the gradient descent method is more stable.
[0231] Step 7: Traffic Allocation Analysis. After optimization, the algorithm analyzes the optimal traffic allocation and extracts the actual contribution of each data source.
[0232] For each data source Its contribution is defined as the proportion of the total flow from the source node to the sink node out of the total flow:
[0233]
[0234] The contribution score reflects the weight of the data source in the final localization result. High-quality data sources contribute more, while low-quality or abnormal data sources contribute less.
[0235] The algorithm also analyzes the stability of traffic allocation and calculates the changes in contribution over consecutive time intervals:
[0236]
[0237] If the contribution of a certain data source fluctuates frequently and significantly (e.g.) If the occurrence of consecutive occurrences indicates that the data source is of unstable quality and may need to be reset or excluded.
[0238] Step 8: Health Monitoring and Reset Trigger. The algorithm continuously monitors the system's health status and detects whether a reset operation needs to be triggered.
[0239] The monitoring indicators include: innovation sequence variance (calculate the innovation sequence variance over the most recent 30 time points; if it exceeds three times the historical average, a warning is triggered); residual distribution skewness (calculate the skewness of residuals from all data sources; if the absolute value is greater than 1, it indicates a systematic bias); flow allocation entropy (calculate the entropy of contribution; if the entropy is too low, it indicates over-reliance on a single data source, posing a risk); and physical rationality (check the estimated velocity and acceleration; if it exceeds the physiological limits of the cattle, a warning is triggered).
[0240] Reset trigger rules: If any monitoring indicator exceeds the threshold for 3 consecutive time periods, a data-level reset is triggered; if any two monitoring indicators exceed the threshold at the same time, a parameter-level reset is triggered; if all monitoring indicators exceed the threshold or the physical rationality is seriously violated, a model-level reset is triggered.
[0241] Step 9: Reset Operation Execution. Execute the corresponding reset operation based on the triggered reset level.
[0242] Data-level reset: Clears observation buffers and historical data from all data sources; resets innovative sequences and residual statistics; retains current weight and capacity settings; from the next time step, estimates are made only based on new observations. The impact of a data-level reset is relatively small, typically recovering within 1 to 2 seconds.
[0243] Parameter-level reset: Restores the weights of all data sources to their default values (e.g., ...). ); Restore the capacity of all data sources to the base value (e.g. Clears the history of adaptive adjustment; retains the current position estimate and state; restarts the adaptive adjustment process. The impact of parameter-level reset is moderate, and recovery typically occurs within 5 to 10 seconds.
[0244] Model-level reset: Reinitializes the position estimate using observations from the most reliable current data source (usually Bluetooth ranging) as initial values; resets the internal states of all filters and state estimators; clears all historical data and statistics; restores all parameters to their default values; and rebuilds the system state from scratch. Model-level reset has a significant impact, typically requiring 10 to 30 seconds to recover to a steady state, but it completely eliminates accumulated errors and systematic biases.
[0245] After the reset operation is completed, the algorithm records the reset event, including the trigger time, trigger reason, reset level, and recovery time, for subsequent analysis and system optimization.
[0246] Step 10: Final Location Result Output. The algorithm outputs the optimized final location result, including: location coordinates. Precise location in three-dimensional space; location covariance matrix , representing the uncertainty in location estimation, is typically a 3×3 symmetric positive definite matrix; confidence score The reliability of the positioning results is comprehensively reflected by calculations based on traffic allocation, residual size, and data source quality; the contribution of each data source is also considered. This reflects the weight of each data source in the final result; health status indicators, including innovation sequence variance, residual distribution statistics, and flow allocation entropy, are used for monitoring and debugging.
[0247] These outputs not only provide the location results themselves, but also rich metadata to help users evaluate the quality of the results and provide reliable input for subsequent geofencing determination and behavior analysis.
[0248] S6: Based on the final positioning result, establish a virtual geofence, monitor in real time and generate early warning information on the status of cattle.
[0249] In this embodiment, a multi-layered virtual geofence is defined based on the pen layout and breeding management needs. Permitted activity areas include spaces where cattle can normally move around, such as lying areas, feeding areas, and activity areas. Restricted areas include equipment areas, personnel passageways, and other areas where cattle should not enter. Abnormal warning areas include areas that remain stationary for extended periods and dangerous areas that require special attention. Each fenced area has a clearly defined boundary polygon and triggering rules.
[0250] The final location results are compared with virtual geofences in real time, and a point-within-a-polygon determination algorithm is used to determine the current location status of the cattle. When a cattle is detected to be outside the permitted activity area or entering a restricted area, it is identified as boundary trespassing, and the time, location, and duration of the trespassing are recorded. Based on continuous location data and accelerometer sensor information, temporal features are extracted, and temporal pattern mining algorithms, including dynamic time warping and hidden Markov models, are applied to identify the behavioral characteristics of the cattle, such as grazing, resting, wandering, and socializing patterns.
[0251] A historical behavior pattern database is established to record the typical behavioral characteristics and temporal distribution of each cow. Current behavioral characteristics are compared with historical behavioral patterns to calculate similarity. When the similarity is below a preset threshold, it is detected as a potential abnormal behavior. Abnormal behaviors include prolonged stillness, abnormal activity, frequent wandering, and abnormal social interaction. Based on the type and severity of the abnormality, corresponding levels of alerts are triggered, including prompt alerts, warning alerts, and emergency alerts.
[0252] The system displays location results, fence status, and behavior analysis results through a visual interface, including real-time location maps, trajectory playback, heat maps, and behavior statistics charts. It provides historical data query functionality, supporting filtering by time, cattle ID, behavior type, and other criteria. Statistical analysis functions are also provided, including activity duration statistics, area dwell time analysis, and behavior frequency statistics, supporting trend analysis and forecasting to assist in livestock management decisions.
[0253] Example 2
[0254] This embodiment is a further refinement of step S1 in embodiment 1, deploying a Bluetooth beacon network within the enclosure, including the following steps:
[0255] S1.1: Preliminary analysis of the pen environment:
[0256] A comprehensive analysis and measurement of the physical structure, dimensions, materials, and signal interference sources of the enclosures are conducted to generate the aforementioned environmental feature dataset.
[0257] Specifically, in this embodiment, environmental pre-analyzers use a laser rangefinder to comprehensively measure the enclosures, recording basic dimensional parameters such as length, width, height, and wall thickness. Simultaneously, they identify the main materials within the enclosures, such as concrete walls, metal partitions, and wooden structures, as these materials have different effects on signal propagation. Furthermore, they identify potential sources of signal interference, such as motors, high-power electrical appliances, and metal feeding troughs. All this information is compiled into an environmental feature dataset, containing the enclosure's geometric parameters, material distribution, and the locations of interference sources.
[0258] S1.2: Optimized layout of Bluetooth beacon nodes:
[0259] Based on the environmental feature dataset, a triangular mesh topology is used to design the deployment coordinate map of the Bluetooth beacon node.
[0260] Specifically, based on the environmental feature dataset, a triangular mesh topology structure was used for beacon node layout design. The triangular mesh topology ensures uniformity and redundancy of signal coverage, with each location covered by at least three beacon nodes, meeting the basic requirements of trilateration. The layout algorithm considered the following principles: First, the spacing between beacon nodes was controlled within the range of 15-25 meters to ensure sufficient signal strength; second, beacon nodes were avoided near strong interference sources; third, priority was given to deployment on the top of the barn to reduce the impact of cattle blocking the signal; fourth, supplementary nodes were added in signal blind spots or areas with weak coverage. Finally, an optimal beacon deployment coordinate map was generated, indicating the precise installation location of each beacon node.
[0261] S1.3: Hardware Installation and Initialization Configuration:
[0262] According to the deployment coordinate diagram, the Bluetooth beacon nodes are installed on the top and side walls of the enclosure, and each node is initialized and configured to establish a basic beacon network.
[0263] Specifically, based on the optimal beacon deployment coordinates, Bluetooth 5.3 beacon nodes are installed on the top and side walls of the enclosure. Each beacon node uses a waterproof and dustproof housing, meeting IP67 protection standards to withstand the humid environment of the enclosure. Expansion bolts are used for fixing during installation to ensure stability. After installation, each node is initialized and configured, including setting a unique node ID, configuring the transmit power (usually +4dBm), setting the broadcast interval (usually 100ms), and configuring the communication channel. All nodes are connected to the central server through a gateway device, forming the basic beacon network.
[0264] S1.4: Beacon Node Self-Test and Calibration:
[0265] Collect the actual RSSI signal strength data of each node and construct an initial signal strength matrix through mutual measurement.
[0266] Specifically, after deployment, a beacon node self-test procedure is initiated. Each beacon node scans the signals of other surrounding beacon nodes and records the received RSSI values. Since the locations of the beacon nodes are known, the actual distance between any two nodes can be calculated. By collecting RSSI data between all node pairs, an initial signal strength matrix is constructed. The rows and columns of this matrix represent different beacon nodes, and the matrix elements represent the RSSI values between corresponding node pairs. This matrix reflects the actual signal propagation characteristics of the enclosure environment, providing foundational data for subsequent topology adaptive optimization.
[0267] S1.5: Adaptive optimization of network topology:
[0268] Based on the initial signal strength matrix, the topology adaptive algorithm is run to dynamically adjust the beacon transmission power and communication parameters to form the Bluetooth beacon network.
[0269] Specifically, based on the initial signal strength matrix, a topology adaptive algorithm is run to optimize the network parameters. The algorithm aims to minimize signal interference and energy consumption between nodes while ensuring coverage quality. The algorithm first analyzes the signal strength matrix, identifying node pairs with excessively strong signals (potentially causing interference) and those with excessively weak signals (affecting positioning accuracy). For excessively strong signals, the transmission power of the relevant nodes is appropriately reduced; for excessively weak signals, the transmission power is increased or broadcast parameters are adjusted. The optimization process is iterative, with signal strength remeasured after each adjustment until the preset performance indicators are met. This ultimately forms a stable and reliable Bluetooth beacon network with optimal node parameters, providing a high-quality signal foundation for subsequent cattle positioning.
[0270] Example 3
[0271] This embodiment is a further refinement of step S2 in embodiment 1, which involves installing positioning tags on cattle, collecting positioning data, and generating an initial set of position coordinates, including the following steps:
[0272] S2.1: Design of a cattle location tagging system:
[0273] The design incorporates a low-power, lightweight positioning tag for cattle, integrating a Bluetooth 5.3 communication module and an accelerometer to ensure data acquisition and transmission capabilities.
[0274] Specifically, in this embodiment, the positioning tag adopts a lightweight design principle, with a total weight controlled within 50 grams to ensure that it does not affect the normal activities of the cattle. The tag shell is made of food-grade TPU material, which has waterproof, dustproof, and impact-resistant properties, meeting the IP67 protection level. The tag integrates a low-power Bluetooth 5.3 communication chip, which supports BLE long-range mode and direction detection function, with a maximum transmit power of +8dBm, a receive sensitivity of -95dBm, and a communication distance of up to 100 meters. At the same time, the tag integrates a low-power triaxial accelerometer with a sampling rate configurable from 10-100Hz to capture the movement status of the cattle. The power supply uses a 220mAh lithium polymer battery with a high-efficiency energy management unit, extending the tag's standby time to 45 days through dynamic power adjustment technology. The tag is fixed by an adjustable neck strap design, which is made of elastic nylon material with a built-in steel wire anti-cutting structure and a special locking mechanism, making it easy to install and remove while preventing accidental fall-off.
[0275] S2.2: RSSI signal acquisition and preprocessing:
[0276] The positioning tag establishes communication with each of the Bluetooth beacon nodes, collects RSSI signal strength data from multiple beacon nodes, and performs preprocessing through sliding window filtering and outlier removal.
[0277] Specifically, each cow wears a tracking tag that periodically (twice per second by default) scans the surrounding Bluetooth beacon signals and records the signal strength values received from each beacon node. The signal acquisition process employs a time-division scanning strategy: the tag first performs a 2-second active scan in high-power mode, then switches to a low-power passive listening mode for 8 seconds, repeating this cycle to optimize the balance between energy consumption and data acquisition frequency. For each beacon node, a triplet of data is recorded: beacon ID, RSSI value (in dBm), and timestamp.
[0278] Because RSSI data is easily affected by environmental noise, multipath effects, and occultation, the raw data often contains abnormal fluctuations and noise. Therefore, a multi-level preprocessing technique is employed. First, a sliding window mid-range filtering algorithm is applied, processing the RSSI data stream with a window length of 5 seconds to effectively eliminate transient noise. Let the current time be... Filtered RSSI value The median value within the window:
[0279]
[0280] Secondly, a weighted average method is used to fuse data from multiple consecutive windows, assigning higher weight to the most recent data. Let the weighted RSSI value be... :
[0281]
[0282] Third, an outlier detection algorithm is applied, based on Mahalanobis distance, to identify and remove RSSI values that significantly deviate from the expected distribution. For the collected data points... Calculate its Mahalanobis distance ,like (in If the value is the standard deviation of the Mahalanobis distance, it is considered an outlier and removed.
[0283] Finally, a preliminary distance estimate is performed using a path loss model on the preprocessed RSSI data. Let the signal strength at the reference point be... (Typically around -60dBm), environmental attenuation factor is (The distance was calibrated to 2.7-3.2 in a cowshed environment), then... The estimation formula is:
[0284]
[0285] Through this series of preprocessing techniques, more stable and reliable signal strength information is extracted from the noisy raw RSSI data. The preprocessed RSSI dataset contains beacon IDs, optimized RSSI values, timestamps, and preliminary distance estimates, serving as key inputs for subsequent fusion processing.
[0286] S2.3: Implementation of RTT (Round-Trip Tolerance) Multi-sided Ranging:
[0287] Based on the round-trip time between the positioning tag and each Bluetooth beacon node, the actual distance is calculated to form a polygon ranging dataset.
[0288] Specifically, this embodiment utilizes the RTT (Round-Trip Time) function of Bluetooth 5.3 to achieve more accurate distance measurement. RTT technology calculates distance by measuring the round-trip time from the transmission of a wireless signal to the reception of a response, and has higher accuracy than RSSI.
[0289] The ranging process is as follows: The tag device sends an RTT ranging request packet to each beacon node, which includes the tag ID and timestamp. After receiving the request, the beacon node records the reception time. After processing, at time Send back a response packet; the tag receives the response packet at the time specified in the original text. Actual RTT value The calculation is as follows:
[0290]
[0291] in This eliminates the processing delay of beacon nodes and thus removes the impact of that delay.
[0292] To improve ranging accuracy, an averaging method based on multiple measurements is employed. By default, each tag performs 8 RTT measurements for each visible beacon, discarding the maximum and minimum values before averaging to form a single ranging result. A smoothing factor is used. (Set to 0.3) Perform an exponentially weighted update, current RTT value The calculation is as follows:
[0293]
[0294] in For the new measurement value, This is the previous RTT value.
[0295] Considering the potential for non-line-of-sight (NLOS) signal propagation in a cattle shed environment, a machine learning-based NLOS detection and compensation mechanism is introduced. By analyzing the RTT distribution characteristics, possible NLOS paths are identified, and correction coefficients are applied. The corrected distance... The calculation is as follows:
[0296]
[0297] in To measure distance, This represents the non-line-of-sight probability (between 0 and 1). This is the correction factor (determined through on-site calibration, typically 0.15-0.25).
[0298] To optimize energy consumption, the RTT measurement frequency is dynamically adjusted according to positioning requirements: the frequency is reduced (once every 5-10 seconds) when the cattle are stationary or moving at low speed, and increased (once every 1-2 seconds) when they are moving quickly. The RTT ranging results, together with the IDs and timestamps of each beacon node, form a multilateral ranging dataset. This dataset includes the beacon ID, RTT measurement value (in nanoseconds), converted distance (in meters), and quality indicators.
[0299] S2.4: Improved edge estimation for independent set queries:
[0300] The RSSI signal strength data and the RTT ranging data are regarded as edges in a graph. The independent set query technique is used to perform a second improvement on edge estimation, thereby reducing the impact of environmental factors on ranging accuracy.
[0301] Specifically, the innovation of this embodiment lies in treating the two ranging results, RSSI and RTT, as "edges" in graph theory, and applying independent set query technology to improve the secondary edge estimation, which significantly improves the positioning accuracy.
[0302] In this model, each beacon node is considered a graph. Vertex in The distance estimates from the labels to each beacon constitute the edge... Each edge has two weights: the distance estimate derived from RSSI. Distance value measured by RTT .
[0303] The core idea of the independent set query technique is to find non-adjacent subsets of vertices (i.e., independent sets) in a graph, and then optimize the overall edge estimation by analyzing the edge weight characteristics within these independent sets. The specific implementation steps are as follows:
[0304] First, construct a distance graph: based on the deployment locations of the beacon nodes, calculate the actual distances between each node to generate a complete graph. .
[0305] Secondly, edge weight initialization: For each edge from a label to a beacon, the initial distance estimate is calculated based on RSSI and RTT data. and .
[0306] Third, consistency check: for any three beacon nodes , , Test the triangle inequality Does it meet the requirements? If not, mark the relevant edge as a "suspicious edge".
[0307] Fourth, independent set partitioning: using a greedy algorithm to partition the graph... Divided into multiple independent sets Ensure that the distance between nodes within each independent set is greater than 1. (in (for ideal communication radius).
[0308] Fifth, quadratic edge estimation: for each independent set Nodes within Calculate the weighted distance estimate from the label. :
[0309]
[0310] Among them, weight and The values are dynamically adjusted according to environmental conditions, with initial values of 0.3 and 0.7 respectively, reflecting higher reliability of RTT measurement.
[0311] Sixth, graph learning optimization: Construct a graph learning model based on independent sets, by minimizing the objective function. Further optimize edge weights:
[0312]
[0313] in Given the known actual distance between beacons. This is the balance factor (usually taken as 0.5-0.8). Represents a node Distance to the label.
[0314] Seventh, edge weight update: The above optimization problem is solved iteratively by gradient descent to update the distance estimates from the labels to each beacon.
[0315] This improved edge estimation technique based on independent set queries is particularly suitable for complex environments like cattle pens, effectively mitigating multipath effects and signal attenuation. The Adaptive Robust Resettable Flow Algorithm (ARRF) is an advanced multi-source data fusion and state estimation algorithm specifically designed for high-precision positioning optimization in complex dynamic environments. This algorithm models the positioning problem as a network flow optimization problem, where multiple data sources (optimized location data, pen mapping relationships, historical trajectories, sensor measurements, etc.) serve as input nodes to the flow. It dynamically balances the contributions of each data source through an adaptive weight adjustment mechanism, employs robust estimation techniques to suppress the impact of outliers and noise, and features a resettable mechanism to address systematic biases and cumulative errors. The core innovation of the algorithm lies in transforming the traditional point estimation problem into a flow optimization problem. It achieves optimal fusion of multi-source information through flow allocation and path selection, while ensuring robustness and long-term stability under various abnormal conditions through three major mechanisms: adaptability, robustness, and resettableness. This algorithm is particularly suitable for cattle positioning scenarios in pen environments with complex conditions such as interference from multiple cattle, signal obstruction, and equipment failure.
[0316] The influence of factors such as non-line-of-sight propagation is considered. Experiments show that compared with simply using RSSI or RTT, this method can reduce positioning errors by 35-45%. After this step, optimized distance estimation results are generated, including the best distance estimates from the tag to each beacon, confidence scores, and timestamps.
[0317] S2.5: Trilateral / Multilateral Fusion Positioning Calculation:
[0318] Based on the improved edge estimation results, and combined with the principles of trilateration and multilateral positioning, the initial position coordinates of the cattle are calculated using the least squares method.
[0319] Specifically, based on the optimized distance estimation results, a trilateration and multi-location fusion algorithm is used to calculate the initial spatial coordinates of the cattle.
[0320] Set up beacon nodes The known coordinates are The optimal distance estimate from the tag to the beacon is: The unknown coordinates of the label are In theory, the following should be satisfied:
[0321]
[0322] for beacon nodes ( A system of equations is constructed. Due to errors in actual measurements, this system of equations typically has no exact solution. Weighted least squares method is used to minimize the objective function. :
[0323]
[0324] Among them, weight Reflecting the The reliability of a distance measurement result is determined by the quality of the edge estimation.
[0325] To improve computational efficiency, Taylor series expansion was used to linearize the nonlinear equation system, and then the Gauss-Seidel iterative method was employed for solution. The maximum number of iterations was set to 20, and the convergence threshold was set to 0.05 m.
[0326] In special cases, if there are fewer than three available beacons or the geometric distribution is poor (e.g., approximately collinear), switch to hybrid positioning mode: combine the previous position, the cattle's movement model, and available ranging data to estimate the current position. Let the current position estimate be... The position at the previous moment was The estimated speed is The time interval is The current measurement location is The hybrid positioning model is then:
[0327]
[0328] in and This is the balance coefficient, which is dynamically adjusted based on measurement reliability.
[0329] In addition, spatial constraints of the cattle shed environment were considered. By comparing with a pre-established pen model, physically impossible location estimates (such as those inside the walls or outside the pen) were eliminated, and the results were adjusted for constraints.
[0330] After trilateration / multilateration localization calculation, the initial position coordinate set of the cattle is output, including three-dimensional coordinates. The data includes timestamps, location accuracy assessments, and reliability metrics. These data will serve as important inputs for subsequent steps, including further location optimization and field association.
[0331] Example 4
[0332] This embodiment is a further refinement of step S3 in embodiment 1, which establishes a raster map based on the structural features of the fence and optimizes the location data, including the following steps:
[0333] S3.1: Digital Modeling of the Pen Environment:
[0334] A basic environmental model is generated by creating a three-dimensional digital model of the pen layout, including walls, partitions, and feeding areas.
[0335] Specifically, in this embodiment, digital modeling of the enclosure environment is the foundation for achieving precise positioning, providing the positioning system with the ability to understand the environment. The modeling process begins with a comprehensive measurement of the enclosure using laser measurement and 3D scanning technologies. A portable laser rangefinder (accuracy ±2mm) is used to measure the main dimensions of the enclosure, including length, width, height, and wall thickness. For complex structures, a 3D laser scanner is used to collect point clouds, with a scanning resolution set to 5mm@10m to ensure sufficient spatial details are captured.
[0336] After point cloud data collection is completed, multi-site scan data are merged into a unified point cloud model using point cloud registration algorithms (such as ICP and Iterative Closest Point algorithm). Subsequently, point cloud denoising and thinning algorithms are applied to remove outliers and optimize data volume, forming a simplified point cloud model that retains key features.
[0337] Next, the point cloud data is converted into a structured 3D model. This process first involves plane detection and segmentation to identify major structural surfaces such as walls, floors, and ceilings; then feature extraction is performed to identify key facilities such as railings, feeding troughs, and waterers; finally, parametric modeling is used to convert the identified structures into regular geometric shapes to build a complete CAD model.
[0338] The elements in the model are categorized by function and assigned semantic attributes, mainly including: basic structure (walls, floors, ceilings, beams, columns, etc., each structure includes material attributes such as concrete, wood, etc.), functional zones (pens, feeding areas, activity areas, milking areas, etc., each area has clearly defined boundaries and functional attributes), facilities and equipment (feeding troughs, waterers, partitions, doors, passages, etc., including precise location and size information), and sensor nodes (Bluetooth beacons, environmental sensors, etc., recording their installation location and coverage area).
[0339] After completing the basic modeling, environmental characteristic parameters need to be added, such as the signal propagation characteristics of different areas (reflection coefficient, attenuation coefficient, etc.). These parameters are obtained through field testing and provide a basis for subsequent signal propagation simulation. The final generated basic environmental model is stored in a standard format, containing complete geometric information, spatial relationships, and attribute data. The model accuracy is controlled within ±5cm to ensure the accuracy of subsequent rasterization processing.
[0340] S3.2: Rasterization and Attribute Tagging:
[0341] The basic environment model is divided into raster segments according to a preset precision, and each raster unit is assigned a physical attribute label to form an attribute raster map.
[0342] Specifically, based on the constructed 3D environment model, the continuous space is converted into a discrete raster representation, and physical properties are assigned to each raster unit. The rasterization segmentation employs an adaptive precision strategy: larger raster units (e.g., 20cm × 20cm) are used in open areas, while finer raster units (e.g., 5cm × 5cm) are used in structurally complex or functionally important areas (e.g., partitions, doorways). A default base raster precision of 10cm × 10cm is used to form a voxel mesh in 3D space.
[0343] The rasterization process uses ray casting and occupancy probability calculation. For each raster cell, multiple rays are emitted through the environment model, and the number and location of intersections between the rays and the model surface are calculated to determine whether the raster is occupied and the type of occupancy. Occupancy probability. The calculation formula is:
[0344]
[0345] in The number of intersections between the ray and the model surface. This represents the total number of rays (typically 16-32 rays per grid).
[0346] Grid cells are classified into three categories based on their occupancy status: Free grid (occupancy probability < 0.2, indicating freely passable space), Occupied grid (occupancy probability > 0.8, indicating space occupied by a solid structure), and Unknown grid (occupancy probability between 0.2 and 0.8, indicating space with an uncertain status).
[0347] For each grid cell, the following physical attributes are further assigned: structural attributes (indicating the structural type of the grid, such as walls, fences, ground, etc.), material attributes (recording the grid material, such as concrete, metal, plastic, etc., which affect signal propagation characteristics), functional attributes (marking the functional area of the grid, such as pen, feeding area, passage, etc.), access attributes (indicating whether cattle can pass through the grid, such as passable, impassable, conditionally passable), and signal characteristics (estimated signal reflectivity, attenuation coefficient, and other parameters).
[0348] For special areas or facilities, semantic tags are added, such as drinking points, feeding points, and milking area entrances. This semantic information helps with subsequent behavior recognition and analysis. Raster attribute assignment uses a multi-level inheritance mechanism: first, basic attributes are inherited from the larger region to which the raster belongs; then, attributes are rewritten or supplemented based on specific location and function.
[0349] To optimize storage and computation efficiency, an octree structure is used to store raster data, hierarchically dividing the space to reduce storage requirements while maintaining accuracy. Furthermore, adjacent rasters with the same attributes can be merged into larger units, further improving efficiency. After rasterization and attribute labeling, an attribute raster map is generated, containing complete spatial layout and attribute information.
[0350] S3.3: Signal propagation characteristic mapping:
[0351] Signal strength is sampled and measured within the enclosure using the Bluetooth beacon network, and the sampled data is mapped onto the grid map to generate a signal propagation characteristic layer.
[0352] Specifically, based on actual measurement data, signal propagation characteristics are mapped onto a grid map to form a signal propagation characteristic layer, providing environmental parameters for subsequent positioning algorithms. The signal characteristic mapping adopts a three-stage method: initial measurement, data interpolation, and theoretical correction.
[0353] First, representative locations (typically the intersections of a 5m x 5m grid) are selected within the enclosure for signal strength measurements. Personnel carrying calibration equipment record RSSI and RTT data from all visible beacons at each measurement point, along with precise location coordinates, forming a measurement dataset. For each measurement point... Record the following data: precise coordinates From each beacon Received signal strength to each beacon RTT measurement value Environmental parameters (such as temperature and humidity).
[0354] Due to the limited number of measurement points, signal characteristic interpolation is required for the entire space. Kriging interpolation is used for spatial interpolation, as this method considers the spatial correlation between data points and is particularly suitable for interpolation in heterogeneous environments. Let the value of the point to be predicted be... The value of the measured point is known. The weighting coefficient is (Determined by the spatial variogram), the interpolation formula is:
[0355]
[0356] After interpolation, the theoretical signal propagation model is combined with the measured data to theoretically correct the signal characteristics. Signal propagation in the indoor environment follows a logarithmic distance path loss model. Let the signal strength at the reference distance (1m) be... The path loss index is The distance is Environmental noise is (following a mean of 0 and a standard deviation of) If the distribution follows a normal pattern, then the RSSI value is:
[0357]
[0358] Based on measured data, customized path loss parameters were calculated for different areas and materials within the enclosure. For example, for open areas... The values are typically 2.0-2.5, while in densely spaced areas they can reach 3.5-4.0. These parameters are mapped onto the corresponding raster cells, forming a parameter layer.
[0359] In addition to path loss, multipath effects and signal diffraction are also considered. By analyzing the fluctuation characteristics of signal intensity, regions with severe multipath effects are identified and marked as "multipath factors" on a grid map. Similarly, based on the principles of geometric optics, the diffraction effects of the signal at various edge structures (such as corners and railings) are calculated and the corresponding parameters are recorded.
[0360] For signal obstruction scenarios, a "penetration loss matrix" is defined to represent the additional loss a signal experiences when passing through different numbers and types of obstacles. For example, a signal may experience an additional loss of 4-6 dB when passing through a metal fence, and 7-9 dB when passing through an adult cow.
[0361] Finally, all signal characteristic parameters are integrated onto the raster map to form a multi-layered signal propagation characteristic layer, including: a basic path loss layer (recording the path loss index of each area). Multipath effect layer (marks severe multipath areas and intensity), obstacle penetration layer (records signal penetration characteristics at different locations), signal fluctuation layer (marks unstable signal areas).
[0362] S3.4: Implementation of the low-diameter wiring decomposition algorithm:
[0363] Based on the grid map, a fully dynamic algorithm for the graph wrench is implemented by applying low-diameter wiring decomposition technology, which simplifies the signal propagation path in complex environments into a subset of paths.
[0364] Specifically, this embodiment implements a fully dynamic algorithm for the graphical wrench based on low-diameter wiring decomposition technology, which is one of the core innovations of this system. This algorithm significantly improves positioning efficiency and accuracy in complex environments by optimizing the representation and calculation of signal propagation paths.
[0365] In traditional positioning algorithms, signal propagation from the transmitter to the receiver is typically simplified to a straight-line model, neglecting phenomena such as reflection, diffraction, and scattering in complex environments. This algorithm, however, transforms the signal propagation problem into a path planning problem in graph theory, more accurately simulating actual signal propagation behavior.
[0366] First, a signal propagation map is constructed based on the attribute grid map. Vertices in the diagram Represents the center point and edge of the grid cell. This represents the signal propagation link between adjacent grid cells. For each edge... Assign weights , indicating that the signal comes from spread to The loss or cost. Weighting calculations consider multiple factors; let the physical distance be... The path loss factor is The reflection / diffraction factor is Material influencing factor is ,but:
[0367]
[0368] The core idea of Low-Diameter Routing is to decompose a complex network into multiple sub-networks, minimizing the diameter (the maximum distance between any two points in the network) of each sub-network, thereby accelerating path calculation. The specific algorithm steps are as follows:
[0369] The first step, graph partitioning: using the multilevel spectral clustering algorithm to partition the signal propagation graph. Divided into Sub-image Each subgraph represents a relatively independent signal propagation area.
[0370] Step 2, low-diameter wiring within the region: For each subgraph An improved Johnson algorithm is applied to calculate the approximate shortest path between all pairs of nodes. Its core principle is to construct a sparse shortest path tree, ensuring that the path length between any two points in the subgraph does not exceed a fraction of the theoretical shortest path length. times ( It is usually set to 0.2).
[0371] The third step is inter-regional connectivity optimization: identifying key connection points (i.e., "boundary nodes") between subgraphs and pre-computing the optimal paths between these nodes. These pre-computed paths form "cross-regional highways," greatly accelerating cross-regional path queries.
[0372] Step 4, Graph Spanner Construction: Based on the above calculation results, construct... -spanner, which is a space containing the original image. subset graph , satisfy the Any two points , They are in The shortest path length in them does not exceed their length in Shortest path length times ( This is called the stretch factor, which typically takes a value of 1.5-2.5. This greatly simplifies the graph structure while preserving path properties.
[0373] The fifth step is fully dynamic maintenance: When the environment changes (such as changes in signal obstruction due to cattle movement), instead of rebuilding the entire graph, the affected areas are updated locally. This incremental update mechanism gives the algorithm a "fully dynamic" characteristic, enabling it to adapt to real-time changes in the environment.
[0374] In its implementation, a hierarchical index structure is used to store path information: the top-level index stores the "high-speed channel" between areas, the middle-level index stores the path between major nodes within each area, and the bottom-level index stores local detailed paths. During a query, multi-level paths are quickly combined based on the start and end points to achieve [the desired query result]. Path lookup with time complexity (where (Number of nodes).
[0375] This low-diameter wiring decomposition technique enables the system to efficiently process large-scale signal propagation networks consisting of tens of thousands of nodes, calculating the optimal signal path for each beacon-tag pair. Compared to traditional line-of-sight propagation models, this algorithm considers the actual propagation path of the signal, enabling more accurate prediction of signal propagation behavior, especially in enclosure environments with obstacles and complex structures. The path subset output by the algorithm contains optimized path information between nodes, providing crucial support for subsequent localization results and grid map matching.
[0376] S3.5: Matching the location results with the raster map:
[0377] The initial set of location coordinates is matched and analyzed with the grid map. The positioning results are optimized using a probability distribution model, and the optimized location data is output.
[0378] Specifically, the initial set of location coordinates is matched with the constructed raster map, and the localization results are optimized using a probability distribution model. The matching of the localization results with the raster map employs a particle filter framework, a Bayesian filtering method suitable for nonlinear, non-Gaussian systems. This method approximates the posterior probability distribution using a large number of particles (representing possible location states).
[0379] The matching process first involves determining the initial position coordinates of each cow. generate A particle (usually) Each particle represents a possible positional hypothesis. The initial distribution of the particles follows a normal distribution centered at the initial coordinates, which is related to the positioning uncertainty. Let the particles... It follows a normal distribution with a mean of 1. The covariance matrix is (Determined by the uncertainty estimate provided by the positioning algorithm):
[0380]
[0381] For each particle Calculate its likelihood in the current raster map. Likelihood is the degree of matching between the location and the observed data. The likelihood calculation considers multiple factors: consistency of physical constraints (assessing whether the location meets physical constraints, such as not being inside a wall or suspended in mid-air), consistency of signal observations (comparing the difference between the theoretical signal strength at the location and the actual observed value), consistency of motion state (assessing whether the location conforms to the kinematic characteristics of cattle, such as speed and acceleration limits), and consistency of historical trajectory (considering the continuity with historical locations).
[0382] The specific formula for calculating likelihood is as follows, assuming the physical constraint consistency is... Signal observation consistency is Consistency of motion state Consistency of historical trajectory The corresponding weights are respectively , , , (If the sum is 1), then:
[0383]
[0384] For example, the likelihood of signal observation consistency is calculated as follows: assuming from the beacon... The observed signal strength is ,particle The predicted signal strength at the location is beacon The standard deviation of signal fluctuation is ,but:
[0385]
[0386] After calculating the likelihood of all particles, importance sampling and resampling are performed on the particles based on their likelihood, retaining high-likelihood particles and discarding low-likelihood particles. The resampled particle set better represents the posterior probability distribution of the positions.
[0387] The final position estimate is obtained by calculating the weighted average of the resampled particles. Let the particles be... The weight is (Proportional to its likelihood), then the location estimate for:
[0388]
[0389] The uncertainty in position estimation is also calculated, represented by the covariance matrix of the particle distribution:
[0390]
[0391] To handle special circumstances in the enclosure environment, several key extensions were implemented: multimodal processing (retaining multiple candidate locations when the location probability distribution shows multiple peaks, and further validating them in subsequent data), and terrain adaptation (based on the height information of the raster map, ... Coordinates are limited to a reasonable range to avoid non-physical states such as "suspended" or "passing through walls"), and dynamic obstacle handling is implemented (considering other cows as dynamic obstacles and updating the dynamic layer of passable areas).
[0392] Example 5
[0393] This embodiment is a further refinement of step S4 in embodiment 1, establishing a static structure database for the columns and constructing a Bayesian probability model, including the following steps:
[0394] S4.1: Establishing Static Structure Data for Columns:
[0395] The different functional areas within the enclosure are measured and defined, and a static structure database of the enclosure is established.
[0396] Specifically, the static structural data of the stalls is a digital representation of the physical space of the cattle shed, providing a basic reference for subsequent dynamic positioning and static stall association. In this embodiment, high-precision measuring equipment is used to conduct detailed mapping of each functional area within the stalls. The measurement work uses a total station (accuracy ±2mm) and a handheld laser rangefinder to record the precise dimensions, positions, and relative relationships of each structural unit. The measurement content includes, but is not limited to: the dimensions and spacing of the bedding pens (typically 1.2-1.3m wide and 2.4-2.7m long), the length and depth of the feeding troughs, the width of the passageways, the area of the activity area, and the specific locations of various facilities (such as waterers, cattle brushes, and milking equipment).
[0397] Based on measurement data, a hierarchical pen data model is constructed. At the top level, the pen is divided into several main functional zones, such as lying areas, feeding areas, exercise areas, and milking areas. Each zone contains clearly defined boundaries (represented by polygons) and functional attributes. Functional zones are further subdivided into specific pen units, such as individual lying areas, feeding positions, and specific activity spaces. Each pen unit records the following key information: geometric information (including center point coordinates, boundary polygons, area, and shape parameters), type information (such as functional types like lying areas, feeding positions, and watering positions), topological relationships (connections to adjacent pens, forming a spatial topological network), usage constraints (such as maximum capacity per session, applicable cattle types, etc.), and reference coordinates (a set of reference points used to correlate with dynamic positioning results).
[0398] S4.2: Analysis of Cattle Activity Patterns
[0399] Based on historical location data analysis, the activity patterns and preferred areas of stay of cattle are analyzed to generate activity heatmaps and time distribution models.
[0400] Specifically, this embodiment analyzes historical location data to uncover the spatiotemporal patterns of cattle activities, generating activity heatmaps and time distribution models to provide behavioral support for subsequent dynamic and static correlation.
[0401] First, cattle location data for a period of time (usually 2-4 weeks) is collected and preprocessed. Preprocessing includes outlier filtering, data normalization, and time alignment to ensure data quality. The preprocessed location data contains cattle IDs, timestamps, and 3D coordinate information, forming the basic dataset.
[0402] Spatiotemporal pattern analysis is conducted from two dimensions: spatial distribution analysis and time series analysis.
[0403] Spatial distribution analysis mainly includes the following steps:
[0404] First, spatial density estimation: using the kernel density estimation (KDE) method, the frequency of cattle occurrence at various locations in the pen is calculated, generating an activity heatmap. Let the historical location points be... The kernel function is (A Gaussian kernel is usually chosen), with bandwidth parameters as follows: (Determines the smoothness), then the position density function for:
[0405]
[0406] Second, spatial clustering: Apply density-based clustering algorithms (such as DBSCAN or OPTICS) to identify areas where cattle frequently stay. These areas usually correspond to specific functional areas (such as pen, feeding area, etc.).
[0407] Third, activity path analysis: Trajectory mining technology is used to identify the common movement paths of cattle and construct a path frequency map. A trajectory segmentation and classification method based on a Hidden Markov Model is employed to decompose the original trajectory data into meaningful movement segments.
[0408] Time series analysis focuses on the temporal patterns of cattle activity:
[0409] First, periodic analysis: Time-frequency analysis of positioning data is performed, and fast Fourier transform (FFT) or wavelet transform is used to identify periodic patterns of activity, such as daily cycles and feeding cycles.
[0410] Second, time-slice statistics: Divide the day into multiple time periods (such as every hour or every 30 minutes), analyze the location distribution characteristics of cattle in each time period, and generate a time-varying heat map.
[0411] Third, state transition analysis: Establish a Markov chain model of cattle transitioning between different functional areas, and calculate the state transition probability matrix. ,in Indicates cattle from the region Move to area The probability of.
[0412] Furthermore, by combining spatial distribution with time series data, a spatiotemporal joint distribution model is constructed. This model can be represented as a conditional probability distribution: This refers to the probability of a cow appearing at a specific location, given a time and a cow's ID.
[0413] For group behavior patterns, the interactions and collective behavioral characteristics among cattle were also analyzed. Social network analysis methods were used to identify social structures within the herd (such as dominance and intimacy relationships) and their impact on spatial distribution. This group dynamics information helps in understanding and predicting cattle distribution in complex scenarios.
[0414] To address individual differences, personalized activity models are built for each cow, capturing its unique behavioral preferences and habits. For example, some cows may have fixed penning preferences or specific feeding time patterns. These individual models are continuously learned and updated from new data using Bayesian methods.
[0415] Ultimately, multi-dimensional activity pattern models are generated, including: spatial dimensions (activity heatmaps, functional area preferences, common path networks), temporal dimensions (activity time series patterns, periodic features, state transition probabilities), individual dimensions (personalized behavioral characteristics, habit preference parameters), and group dimensions (social network structure, collective behavioral patterns). These activity pattern models serve as important inputs for the next step, helping to build more accurate Bayesian probabilistic models.
[0416] S4.3: Construction of Bayesian Probability Model
[0417] By combining the static structure database of the stalls and the analysis results of the activity patterns, the Bayesian probability model is constructed to calculate the conditional probability of cattle appearing in a specific stall.
[0418] Specifically, after mastering the static structure data of the stalls and the activity patterns of the cattle, a Bayesian probability model is constructed to calculate the conditional probability of cattle appearing in a specific stall, providing a mathematical basis for the dynamic-static correlation.
[0419] Bayesian probabilistic models, based on Bayes' theorem, combine prior knowledge with observed data to infer the most likely state. In this embodiment, the core of the model is computation. That is, given the location result ,time Wagyu ID The cattle are located in specific pen units. The posterior probability.
[0420] According to Bayes' theorem:
[0421]
[0422] in: It is a likelihood function, representing the number of cows in the pen. Location results are generated at that time. The probability; It is the prior probability, representing the number of cows. In time Appear in the column The probability; It is the marginal likelihood, which can be regarded as a normalization constant.
[0423] The model building process consists of the following key steps:
[0424] The first step is to model the likelihood function: the likelihood function The relationship between the location results and the actual column positions was modeled. Assuming the location results... Represented as coordinates and its uncertainty Then the likelihood function can be expressed as a multivariate Gaussian distribution:
[0425]
[0426] in For the location results Go to column The Mahalanobis distance takes into account the shape and orientation of the field.
[0427] The second step is to construct the prior probabilities: prior probabilities Constructed based on the results of activity pattern analysis, it comprises three main components:
[0428] a) Time-conditional probability Based on historical data, the correlation between time and pen location is analyzed. For example, cattle are more likely to appear in the pen between 5 and 7 a.m. and more likely to appear in the feeding area between 9 and 11 a.m.
[0429] b) Individual preferences : Capture the pen preferences of specific cattle, such as a cow that may always choose the same pen location.
[0430] c) State transition probability : Describe the cattle from the previous column Move to the current field The probability was used to model the continuity of activities.
[0431] These three parts are integrated through a hybrid model, with weights set as follows: , , (satisfy ):
[0432]
[0433] The weights are dynamically adjusted based on the reliability of the data.
[0434] The third step is parameter estimation and learning: model parameters are learned from historical data using maximum likelihood estimation (MLE) or maximum a posteriori estimation (MAP). The expectation-maximization (EM) algorithm is used to handle latent variables and incomplete data. Parameter updates follow an online learning model, continuously optimizing model parameters as new data is collected.
[0435] The fourth step is the model's adaptive mechanism: To adapt to changes in the environment and behavior, the model introduces an adaptive learning rate and a forgetting mechanism. More recent observations receive higher weights, while older data gradually loses influence. (Learning rate...) Based on prediction accuracy Dynamically adjusted, with a base learning rate. :
[0436]
[0437] The fifth step is spatial constraint integration: The physical constraints of the columns are integrated into the model to ensure the continuity and rationality of the probability distribution in space. For example, the probability distribution between adjacent columns should transition smoothly, while the probability distribution in areas separated by walls should be discontinuous. This is achieved using Markov Random Fields (MRFs), introducing a potential function for spatial adjacency relationships.
[0438] Step 6, Multimodal processing: When cattle may be in multiple pens at the same time (such as at the boundary between two pens), the model supports a multimodal posterior distribution, which can represent multiple possible pen assignments and their probabilities.
[0439] The model output is a conditional probability matrix. ,in Indicates the first The first cow in The probability of each column cell. This matrix contains both spatial dimensions (different columns) and temporal dimensions (probabilities change over time), forming a spatiotemporal probability field.
[0440] Bayesian probabilistic models not only consider current observations but also integrate historical data, spatial constraints, and domain knowledge. They can effectively handle data uncertainty and noise, providing a probabilistic theoretical foundation for the next step of defining dynamic and static association rules.
[0441] S4.4: Training the Bayesian probability model:
[0442] Model parameters are learned from historical data using maximum likelihood estimation and expectation maximization algorithms.
[0443] Specifically, in this embodiment, the Bayesian probability model is trained using the Expectation-Maximization (EM) algorithm, which is an iterative optimization method suitable for handling probability models containing latent variables.
[0444] The training process is as follows:
[0445] The first step is data preparation: Collect historical location datasets, including cattle IDs, timestamps, location coordinates, and actual location in the field (determined through manual annotation or other reliable methods). Divide the dataset into a training set (80%) and a validation set (20%).
[0446] The second step is parameter initialization: Initialize the model parameters, including the parameters of the likelihood function (such as uncertainty). ), parameters of prior probabilities (such as time conditional probability) Individual preferences State transition probability ) and mixed weights Initial values can be set based on domain knowledge or using random initialization.
[0447] Step 3, EM algorithm iteration:
[0448] E-step (Expectation Step): Given the current parameter estimates, compute the posterior probability distribution of the latent variables. In this model, the latent variable is the true pen location of the cattle. For each sample in the training set, compute the posterior probability of the cattle being located in each pen. .
[0449] M-step (maximization step): Based on the posterior probabilities calculated in the E-step, update the model parameters to maximize the log-likelihood of the data. Specifically:
[0450] Update the likelihood function parameters: by maximizing renew .
[0451] Update prior probability parameters:
[0452] Time conditional probability : Statistically determine the frequency of cattle appearing in each pen within each time period.
[0453] Individual preferences : Count the frequency of each cow appearing in each pen.
[0454] State transition probability : Statistical analysis of cattle from their stalls Move to column The frequency.
[0455] Update Mixed Weights Find the weight combination that maximizes the accuracy of the validation set through grid search or gradient optimization methods.
[0456] Step 4, Convergence Criterion: Calculate the log-likelihood value of the current iteration. If the difference from the previous iteration is less than a preset threshold (e.g., ...), then... If the maximum number of iterations is reached (e.g., 100 times), then the iteration stops.
[0457] Step 5, Model Validation: Use the validation set to evaluate model performance and calculate metrics such as prediction accuracy, precision, and recall. If the performance does not meet the requirements, adjust the model structure or hyperparameters and retrain.
[0458] Step 6, Online Learning Mechanism: After model deployment, new data is continuously collected, and incremental learning is performed regularly (e.g., daily or weekly) to update model parameters. Incremental learning uses a weighted update strategy, where new data receives higher weights and older data gradually loses weight, enabling the model to adapt to changes in the environment and behavior.
[0459] Through this training process, the Bayesian probabilistic model can learn the activity patterns of cattle and the correlation patterns between pen locations from historical data, providing accurate prior knowledge and probabilistic inference capabilities for real-time positioning.
[0460] S4.5: Real-time correlation matching and updates:
[0461] The initial set of position coordinates is matched with the set of association rules in real time to determine the current pen position of the cattle, and the association model is continuously updated based on new data.
[0462] Specifically, this embodiment performs real-time matching between the initial set of position coordinates and the set of association rules to determine the current pen location of the cattle, and continuously updates the association model based on new data. This is the execution phase of the entire dynamic and static association algorithm, transforming the preparatory work in the preceding steps into a real-time running system function.
[0463] The real-time correlation and matching process employs a stream processing architecture, continuously receiving and processing location data streams. The processing flow is as follows:
[0464] The first step, data reception and preprocessing, involves receiving the raw location coordinate stream from the positioning engine. Each record contains the cattle ID, timestamp, 3D coordinates, and accuracy assessment. Preprocessing operations include: data integrity checks (detecting and marking missing or anomalous data), coordinate system transformation (converting global coordinates to the pen's local coordinate system), time alignment (ensuring data timestamp synchronization and handling potentially delayed data), and noise filtering (applying Kalman filtering or moving average smoothing to handle positioning noise).
[0465] The second step, state tracking and history maintenance: Maintain a historical state record for each cow, including: current associated state (ID of the column and association strength), state timestamp (the time point when the current state was entered), and historical state sequence (most recent). Each state and its duration, Typically 10-20), motion parameters (current velocity, acceleration, and direction of motion). This state information is stored using in-memory data structures (such as hash tables and circular buffers), supporting sub-millisecond-level fast access.
[0466] The third step is Bayesian inference: For each newly arrived location data point, Bayesian probability model inference is performed to calculate the posterior probability of a cow being located in each pen. Select the column with the highest posterior probability as the primary association, and retain the column with the second highest probability as the secondary association (if applicable).
[0467] Step 4, Application of Association Rules: Apply predefined association rules for validation and adjustment.
[0468] Probability threshold rule: If the highest posterior probability exceeds the threshold... If the value is 0.75-0.85, the association is confirmed; otherwise, it is marked as "uncertain".
[0469] Spatial containment rule: Verify whether the positioning coordinate point is within the field boundary polygon.
[0470] Time Duration Rule: Requires cattle to stay in a specific pen for more than a minimum threshold time. The association was confirmed only after that. Different types of fields have different settings. Values, for example, 60 seconds for a pen, 30 seconds for a feeding spot, and 10 seconds for a passageway.
[0471] State transition conditions: Determine whether a state change should be triggered, including spatial conditions (the probability of the new location must exceed a certain threshold). (Typically 0.7), time condition (the time spent in the original column should exceed...) ), physical feasibility (there is a physical connection path between the two fields), and the persistence of change (the new position remains stable for longer than the confirmation time). (Usually 10-15 seconds).
[0472] Step 5, Generate Association Results: Generate association results, including: primary association (the most likely pen position of the cow), association strength (the confidence level of the association, between 0 and 1), secondary association (the second best pen position options and their probabilities, if applicable), and status flags (such as "stable", "in transition", or "uncertain").
[0473] Step 6, Online Model Update: This not only executes static rules but also continuously learns and adapts to new data. This includes short-term adaptation (dynamically adjusting threshold parameters to respond to changes in data quality), medium-term learning (updating the state transition probability matrix hourly to reflect recent behavioral patterns), and long-term optimization (re-evaluating Bayesian model parameters daily or weekly to improve overall accuracy). The update process employs incremental learning methods to avoid computationally intensive full retraining and maintain system responsiveness.
[0474] Step 7, Anomaly Detection and Handling: Continuously monitor the association process, detect and handle anomalies: location jump (when location data shows a rapid change that is not physically possible, activate the smoothing or rollback mechanism), association uncertainty (when the association strength is below the threshold for a long time, trigger multi-source data fusion for auxiliary judgment), data interruption (when the location data stream is interrupted, predict possible locations based on historical patterns, while reducing certainty), conflict resolution (when multiple cows are determined to be in the same single cow pen, apply a conflict resolution strategy based on probability and history).
[0475] Step 8, Result Caching and Distribution: Processed correlation results enter a multi-level caching system: real-time cache (saves the latest results, supporting millisecond-level queries), short-term storage (saves recent 1-24 hour history, supporting trend analysis), and long-term database (archives complete history, supporting data mining and pattern recognition). Correlation results are distributed to downstream applications via message queues or publish-subscribe mechanisms, supporting concurrent access from multiple clients.
[0476] The real-time association matching and update mechanism ensures the continuous and accurate maintenance of the mapping relationship between cattle and their pen locations, while adapting to dynamic changes in the environment and behavior. The processing result—the mapping relationship between cattle and their pen locations—serves as one of the key inputs for the next step, supporting subsequent adaptive and robust algorithms for higher-level positioning optimization.
[0477] Example 6
[0478] This embodiment is a further refinement of step S5 in embodiment 1, which optimizes the localization result through an adaptive robust resettable flow algorithm, including the following steps:
[0479] S5.1: Multi-source data fusion preprocessing:
[0480] By integrating the optimized location data and the mapping relationship, and combining it with the accelerometer data worn by the cattle, a multi-dimensional feature vector is formed.
[0481] Specifically, after obtaining the optimized location data and the mapping relationship between cattle and stalls in the previous steps, this embodiment further integrates the acceleration sensor data to form a multi-dimensional feature vector, providing comprehensive input information for the subsequent adaptive robust algorithm.
[0482] The core idea of multi-source data fusion is to intelligently integrate data from different sources and with different characteristics to extract more valuable information and overcome the limitations of a single data source. The data sources to be fused mainly include three categories: location data, field-related data, and accelerometer sensor data.
[0483] The data acquisition and preprocessing process is as follows:
[0484] First, location data processing: Obtain the raster-matched and corrected location data from step S3, including three-dimensional coordinates. (Representing the precise location of the cattle), velocity vector (Calculated from continuous position differences), position covariance matrix (representing position uncertainty), timestamp (accurate to milliseconds). Preprocessing operations include time series alignment, outlier detection, and smoothing. An adaptive exponential smoothing algorithm is used to process the position series; let the smoothed position be denoted as . The current location is The smoothed position at the previous time step was Smoothing factor is :
[0485]
[0486] Smoothing factor Dynamically adjust based on data quality; when noise is high... Take the smaller value (approximately 0.2) when the data is stable. Take the larger value (approximately 0.6).
[0487] Second, pen association data processing: The mapping relationship between cattle and pens is obtained from step S4, including the primary associated pen ID (the pen where the cattle are most likely currently located), the association probability vector (the probability distribution of association with each pen), the state duration (the duration of the current association state), and the state transition flag (indicating whether a pen transition is in progress). Entropy filtering is applied to the association probability distribution to identify high-uncertainty situations (such as being located at the intersection of multiple pens). Entropy value. The calculation formula is as follows: Let the column... The probability of association is :
[0488]
[0489] when When the value exceeds a preset threshold (usually 1.5), it is marked as a "high uncertainty" state.
[0490] Third, accelerometer data processing: The accelerometer integrated in the positioning tag worn by the cattle provides triaxial acceleration data. The sampling rate is 10Hz. Acceleration data preprocessing includes: signal filtering (using a Butterworth low-pass filter with a cutoff frequency of 5Hz to remove high-frequency noise), gravity separation (separating gravity components and dynamic acceleration components), attitude estimation (combining triaxial data to estimate the cattle's approximate posture, such as standing, lying down, walking, etc.), and activity intensity calculation (assessing activity intensity based on acceleration variance). Activity intensity indices are defined. (Activity Index), set , , The variances are respectively , , :
[0491]
[0492] And Mapped to a standardized 0-100 range, representing the intensity of the activity.
[0493] Fourth, feature extraction and vector construction: Based on the preprocessed multi-source data, a series of features are extracted to construct a multi-dimensional feature vector. The main features include:
[0494] Location characteristics: Normalized spatial coordinates (Relative position relative to the fence boundary), rate of change of position (displacement magnitude in the short term 1s and medium term 10s), direction of movement (direction of movement expressed in angle), and position uncertainty (covariance eigenvalue of position estimation).
[0495] Pen characteristics: Pen type code (e.g., 1 for resting, 2 for feeding, 3 for activity area, etc.), association probability (association probability value with the current pen), pen dwell time (cumulative time in the current pen, normalized), pen change frequency (frequency index of recent pen changes).
[0496] Behavioral characteristics: Activity intensity (activity index based on acceleration calculation) ), posture coding (standing as 1, lying down as 2, walking as 3, etc.), activity patterns (frequency domain features, representing periodic behavior patterns), and abnormal indicators (the degree of deviation from typical behavior patterns).
[0497] Time features: time encoding (encoding a 24-hour day as a cyclical feature), feeding cycle indicators (position relative to feeding time), and historical behavior matching degree (similarity with behavior in the same historical period).
[0498] Environmental characteristics: surrounding cattle density (number of other cattle in the vicinity), pen temperature and humidity (temperature and humidity data recorded by environmental sensors, if available), and light condition coding (1 during the day or 0 at night).
[0499] These features are standardized to ensure consistent data ranges across dimensions, typically normalized to [a specific value]. or The interval. The standardized formula is as follows, assuming the original value is... The minimum value is The maximum value is The mean is The standard deviation is :
[0500] or
[0501] Finally, all features are integrated into a 35-50 dimensional feature vector, with each dimension representing an aspect of the cattle's state or environment. This high-dimensional feature vector serves as input data for subsequent anomaly identification and adaptive robust algorithms, providing a comprehensive representation of the cattle's state.
[0502] S5.2: Identification of Abnormal Interference Factors:
[0503] Cluster analysis and anomaly detection algorithms are applied to identify and eliminate interfering factors that may cause positioning errors.
[0504] Specifically, after obtaining the multidimensional feature vector, this embodiment applies clustering analysis and anomaly detection algorithms to identify interference factors that may cause positioning deviations, providing an interference feature set for subsequent adaptive robust algorithms.
[0505] The identification of abnormal interference factors employs a multi-level, multi-angle detection strategy, using different methods to identify various interference situations that may affect positioning accuracy. The main identification process is as follows:
[0506] First, signal quality anomaly detection: This involves analyzing the quality indicators of the raw signal data to identify potential signal anomalies. This includes RSSI jitter detection (calculating the standard deviation of RSSI within a short time window; exceeding a threshold, typically 4-6 dBm, is considered signal jitter) and signal mutation detection (identifying abrupt changes in RSSI or RTT using a rapid change detector, such as in…). Changes within seconds exceeded The analysis includes the following: signal loss patterns (analyzing beacon signal loss patterns, such as periodic or sudden loss); and multipath characteristics (detecting characteristic patterns of multipath propagation through signal waveform analysis). For each type of signal anomaly, a severity index is calculated. (Severity Index), ranging from 0 to 1, indicates the degree of impact of the anomaly.
[0507] Second, spatial consistency check: By analyzing the spatial consistency of location data, potential positioning anomalies are detected. These include physical constraint violations (checking if the location violates physical constraints, such as passing through walls or exceeding speed limits), trajectory discontinuities (identifying jumps or discontinuities in the trajectory), velocity anomalies (detecting velocity changes that do not conform to the normal kinematic characteristics of cattle), and jitter patterns (analyzing the jitter characteristics and frequency properties of the location time-series data). Mahalanobis distance using a sliding window is used to detect position anomalies. Let the current position vector be... The average of historical positions is covariance is Then the Mahalanobis distance for:
[0508]
[0509] when When the value exceeds a threshold (usually 3.0), it is marked as a spatial anomaly.
[0510] Third, cluster analysis and pattern recognition: Cluster analysis is applied to historical data to identify different patterns in location quality. This includes DBSCAN clustering (density-based clustering to identify data distribution patterns in the feature space), Gaussian Mixture Model (GMM) (using multiple Gaussian distributions to fit feature data and identify various state patterns), and time series pattern mining (applying Dynamic Time Warping (DTW) algorithm to identify recurring patterns in time series). Through cluster analysis, data is divided into several categories such as "normal," "slightly disturbed," "moderately disturbed," and "severely disturbed," and feature centers and boundaries of each category are extracted.
[0511] Fourth, classification of specific interfering factors: Based on the above analysis, the detected anomalies are further classified into specific interfering factors:
[0512] a) Signal reflection interference: Characterized by large RSSI fluctuations, obvious multipath characteristics, and frequent positional jitter; caused by metal equipment, wall reflections, or large water surfaces; severity calculation, assuming RSSI variance is... Multi-path metrics are The position jitter index is The corresponding weight is , , The severity of reflected interference for:
[0513]
[0514] b) Signal blockage interference: characterized by a sudden drop in signal strength, loss of some beacon signals, and decreased positioning accuracy; caused by dense gathering of cattle, movement of large equipment, and human activities; the detection method is to monitor sudden changes in signal strength and spatial distribution.
[0515] c) Interference from multiple cattle aggregation: characterized by high cattle density in local areas and cross-interference of signals from multiple location tags; caused by cattle aggregation due to feeding, watering or special management activities; detected by analyzing cattle density maps and group behavior patterns.
[0516] d) Environmental electromagnetic interference: characterized by a decline in signal quality across the entire area and periodic interference patterns; caused by the starting of motor equipment, high-power electrical appliances, and external radio frequency sources; detected by spectrum analysis and time-frequency feature extraction.
[0517] e) Hardware abnormal interference: characterized by continuous abnormality of a single tag and sudden drop in battery power; caused by tag failure, battery depletion, or antenna damage; detection methods include isolated point analysis and equipment status monitoring.
[0518] Fifth, spatiotemporal characterization of disturbance factors: For the identified disturbance factors, their spatiotemporal characteristics are further analyzed: spatial distribution (the location distribution of disturbance in the enclosure, identifying "disturbance hotspots"), temporal patterns (the temporal regularity of disturbance occurrence, such as its correlation with feeding time), persistence characteristics (the typical duration and decay pattern of disturbance), and spread trends (how disturbance spreads or contracts spatially). These spatiotemporal characteristics are visualized using heatmaps, time series analysis, and spatial interpolation methods.
[0519] Sixth, Severity Assessment of Interference: Calculate a severity index for each identified interference factor, assuming the interference intensity is... Duration of time is The spatial coverage area is Historical impact The severity of the interference for:
[0520]
[0521] The severity score ranges from 0 to 100 and is divided into five levels: very weak (<20), mild (20-40), moderate (40-60), severe (60-80) and extreme (>80).
[0522] Finally, the output interference feature set includes information such as interference type, spatiotemporal distribution, severity, and impact range. This information is crucial for subsequent adaptive robust algorithms and resettable mechanisms, enabling the system to respond to various types of interference in a targeted manner and improve localization robustness.
[0523] S5.3: Adaptive Robust Flow Algorithm Design:
[0524] An adaptive robust algorithm based on flow network theory is constructed to transform the localization problem into a flow allocation problem and dynamically adjust the weights of different information sources.
[0525] Specifically, based on the interference features identified in the preceding steps, this embodiment constructs an adaptive robust flow algorithm, which transforms the localization problem into a flow allocation problem, dynamically adjusts the weights of different information sources, and improves the localization accuracy and stability of the system in complex environments.
[0526] For a detailed implementation of the adaptive robust flow algorithm, please refer to Example 1, which will not be repeated here.
[0527] S5.4: Resettable mechanism implementation:
[0528] The design incorporates triggering conditions and a reset strategy to reset the algorithm parameters when significant location drift or environmental changes are detected.
[0529] Specifically, this embodiment designs triggering conditions and a reset strategy to quickly reset algorithm parameters and restore system stability when significant positioning drift or environmental changes are detected. The resettable mechanism is a key complement to the adaptive robust algorithm, enabling the system to recover quickly from severe abnormal states and avoiding error accumulation and amplification.
[0530] The resettable mechanism is designed following the principles of "rapid detection, accurate location, lightweight recovery, and gradual stabilization," and is implemented as follows:
[0531] The first step is to design trigger conditions: monitor multiple indicators and design hierarchical trigger conditions to ensure that it can respond quickly to serious anomalies without being overly sensitive and causing frequent resets.
[0532] a) Level 1 trigger condition (mild intervention): Residual fluctuation (continuous) A point, usually The standardized residuals exceed the threshold. (Typically 2.5), confidence decline (the confidence index for location estimation falls below the threshold). (Typically 0.7) and prediction bias (the difference between the actual observation and the predicted value exceeds the preset range).
[0533] b) Secondary trigger condition (moderate reset): Positional jump (position estimation exceeds the physical possibility of a jump, such as speed exceeding...) Model divergence (the iterative process does not converge or the parameter values are outside the reasonable range), sensor anomaly (abnormal patterns or inconsistencies are detected in the sensor data).
[0534] c) Level 3 trigger conditions (complete reset): system crash (algorithm enters an unrecoverable error state), drastic environmental change (significant changes in the pen environment are detected, such as large-scale equipment movement), long-term drift (cumulative error exceeds the acceptable limit).
[0535] The trigger assessment employs a fuzzy logic framework, comprehensively considering multiple indicators to avoid overreaction caused by a single anomaly. Let the residual score be... Confidence level is The prediction bias is Position jump rating is Then the score will be triggered. for:
[0536]
[0537] in It is a fuzzy logic function.
[0538] The second step is to diagnose the cause of the anomaly: after the triggering conditions are met, the cause of the anomaly is diagnosed to provide a basis for subsequent targeted reset.
[0539] a) Diagnostic feature extraction: temporal features (time pattern of anomaly occurrence, duration and evolution trend), spatial features (distribution characteristics of anomaly in space, whether it is a local or global phenomenon), data features (which data sources or processing links show anomalies), and correlation analysis (correlation between anomalies and environmental events or system states).
[0540] b) Fault mode classification: Based on the extracted features, anomalies are classified into preset fault modes: sensor failure (such as beacon failure, tag power depletion), environmental interference (such as electromagnetic interference, large-scale metal equipment movement), algorithm problems (such as parameter drift, model misfit), and special scenarios (such as abnormal cattle behavior, high-density clustering).
[0541] c) Impact Scope Assessment: Assess the scope and extent of the abnormal impact: single-cattle impact (affecting only the location of a single cattle), regional impact (affecting all locations within a specific area), and systemic impact (affecting the entire location system).
[0542] The third step is a targeted reset strategy: based on the diagnostic results, a targeted reset is performed, restoring only the affected components instead of a full system restart.
[0543] a) Data-level reset: Clear the observation buffer (clear abnormal observation data to prevent contamination of subsequent processing), replace outliers (replace outliers with reasonable default values or historical averages), and adjust the sampling rate (temporarily increase the sampling rate to accelerate the accumulation of new data).
[0544] b) Parameter-level reset: Flow weight reset (restores the flow weights of affected paths to default or safe values), estimator parameter reset (resets the internal parameters of the robust estimator), threshold dynamic adjustment (temporarily relaxes or tightens relevant decision thresholds).
[0545] c) Model-level reset: State estimate reset (resets the state estimator to a reliable historical state), covariance matrix reset (increases the uncertainty estimate to reflect the low confidence after the reset), and prediction model switching (switches to a more conservative prediction model).
[0546] The fourth step is a smooth recovery mechanism: after a reset, the system will not immediately resume full-load operation, but will ensure stability through a smooth transition.
[0547] a) Progressive Trust Restoration: Define a trust growth function, assuming a minimum trust level of... Maximum trust level is The time constant is Trust level for:
[0548]
[0549] Data weights are adjusted based on trust levels, with the base weight set as follows: :
[0550]
[0551] As new data accumulates, trust gradually increases, and the system smoothly transitions to a normal state.
[0552] b) Multi-stage recovery process: Safety mode (0-3s, using highly conservative parameters, with stability as the primary goal), transition mode (3-10s, gradually introducing more data sources and adjusting parameters to approach normal values), normal mode (>10s, complete recovery, restoring all functions and accuracy).
[0553] c) Adaptive recovery speed: The recovery speed is dynamically adjusted based on data quality. High-quality data (accelerates the recovery process, quickly returning to normal); low-quality data (extends recovery time, ensuring thorough verification of system stability).
[0554] Step 5: Reset Event Logging and Analysis: Record each reset event in detail for future improvements: event timestamps and triggering conditions, diagnostic results and reset strategies, recovery process and effectiveness evaluation, and potential improvement suggestions. These records are analyzed regularly to identify system weaknesses and improvement opportunities, continuously optimizing the reset mechanism and overall algorithm.
[0555] Step 6, Scenario-based Reset Templates: Pre-set reset templates are provided for common scenarios, enabling "one-click response": Cattle Herd Gathering Template (optimizes parameter settings for densely populated scenarios), Equipment Maintenance Template (handles beacon maintenance or replacement scenarios), and Pen Renovation Template (addresses system incompatibility caused by environmental structural changes). Each template includes complete triggering conditions, diagnostic criteria, and reset strategies, which can be fine-tuned according to actual needs.
[0556] The resettable mechanism significantly improves the system's robustness, enabling the positioning system to self-recover under various abnormal conditions and avoiding prolonged service interruptions or accumulated errors. This mechanism works closely with the adaptive robust flow algorithm to form a complete anti-interference system, ensuring high-precision positioning in complex dynamic environments.
[0557] S5.5: Filtering and Smoothing Processing
[0558] Kalman filtering and trajectory smoothing techniques are applied to the optimized positioning results to eliminate jumps and jitters, and the final positioning result is output.
[0559] Specifically, as the final step in adaptive robust positioning optimization, this embodiment applies Kalman filtering and trajectory smoothing techniques to the optimized positioning results to eliminate jumps and jitters, and outputs the final accurate cattle location information.
[0560] The core objective of filtering and smoothing is to remove noise and irregular fluctuations while retaining useful information, making the trajectory smoother and more natural, and maintaining accurate tracking of the actual motion. The specific implementation is as follows:
[0561] The first step is to design a multi-level filtering architecture: adopt a multi-level filtering architecture to gradually improve signal quality.
[0562] a) Pre-filtering: median filter (removes spike noise and isolated outliers), bandpass filter (preserves positional changes within a reasonable frequency range), outlier detector (identifies and marks possible outliers to provide a reference for subsequent processing).
[0563] b) Main filters: Extended Kalman Filter (EKF) or Unscented Kalman Filter (UKF) (core state estimator), Particle Filter (for handling strongly nonlinear or non-Gaussian distributions), Complementary Filter (for fusing data with different frequency characteristics).
[0564] c) Post-filtering: RTS (Rauch-Tung-Striebel) smoother (offline smoothing of completed trajectory segments), spline curve fitting (geometric optimization of trajectories when stationary or moving at low speeds), and physical constraint adjustment (ensuring that the final trajectory meets physical possibilities).
[0565] The second step is the implementation of the extended Kalman filter: The extended Kalman filter is the core algorithm in the main filtering stage, and its implementation details are as follows:
[0566] a) Definition of state-space model: state vector for It includes position, velocity, and acceleration; observation vector for It includes position observation and acceleration measurement; the state transition equation is: ,in For process noise; the observation equation is: ,in To observe noise.
[0567] State transition function Using a constant acceleration motion model, let the time interval be... The random variation term of acceleration is (Modeled as Gaussian white noise):
[0568]
[0569]
[0570]
[0571] and The directions are similar.
[0572] b) Adaptive noise covariance: The key innovation of EKF is process noise. and observation noise Adaptive adjustment of the matrix. Adaptive process noise, assuming a mixing coefficient of . The basic process noise is The dynamic process noise is (Based on innovation sequence estimation):
[0573]
[0574] The observation noise is adaptive, and each element is r. i (k) (Dynamically adjusted based on the real-time reliability of the corresponding sensor):
[0575]
[0576] c) Robustness enhancement techniques: innovation limiting (limiting excessively large innovation items to prevent the influence of outliers), incremental updates (performing large adjustments in stages to avoid state jumps), covariance monitoring (detecting the numerical stability of the covariance matrix and performing regularization when necessary), and multiple hypothesis tracking (maintaining multiple state hypotheses under highly uncertain conditions).
[0577] The third step is context-aware trajectory smoothing: intelligent trajectory smoothing is performed by combining environmental context information.
[0578] a) Activity-based variable smoothing: The smoothing parameters are dynamically adjusted according to the cattle's activity level. At rest (strong smoothing to minimize positional fluctuations), at low speeds (medium smoothing to maintain a natural trajectory), and at high speeds (light smoothing to preserve motion details).
[0579] b) Geographically Aware Path Alignment: Optimize trajectories using knowledge of enclosure structure. This includes: channel alignment (automatically aligning trajectories within channels to the channel centerline), enclosure snapping (snapping trajectories to enclosures based on probability when approaching their boundaries), and obstacle avoidance (ensuring smoothed trajectories do not cross physical obstacles).
[0580] c) Behavior-related trajectory patterns: Specific smoothing patterns are applied based on the identified behaviors. These include feeding behavior (restricting forward and backward movement while preserving lateral movement), resting behavior (strong smoothing, almost fixed position), and social behavior (preserving relative positional relationships with other cattle).
[0581] The fourth step is trajectory segmentation and condition processing: Instead of treating the entire trajectory as a single entity, it is intelligently segmented and differentiated strategies are applied.
[0582] a) Trajectory segmentation strategy: speed threshold segmentation (identifying moving and stationary segments based on speed changes), direction change segmentation (using large-angle turns as segmentation points), and behavior change segmentation (segmenting at points of behavior pattern change).
[0583] b) Segmented specialization: stationary segment (applying stable point estimation to almost eliminate all fluctuations), straight-line movement segment (using linear regression to optimize trajectory shape), turning segment (applying spline curves to maintain a smooth transition), complex motion segment (preserving more details and reducing smoothing intensity).
[0584] The fifth step is multi-timescale optimization: applying optimization techniques at multiple timescales to balance real-time response and trajectory quality.
[0585] a) Short sliding window (1-3 seconds): Real-time noise suppression provides instant smoothing; fast response to behavior changes; low-latency processing, suitable for real-time applications.
[0586] b) Intermediate batch processing (10-30 seconds): Apply RTS smoother for forward-backward smoothing; optimize local trajectory continuity; eliminate boundary effects of short-term sliding windows.
[0587] c) Long-term trajectory optimization (>60 seconds): Global trajectory shape optimization; identification and correction of long-term drift; alignment with historical behavior patterns.
[0588] Step 6, Quality Assessment and Adaptive Control: Continuously evaluate the effectiveness of filtering and smoothing, and dynamically adjust processing parameters.
[0589] a) Smoothing quality indicators: smoothing measure (mean square value of the second derivative of the curve), fidelity measure (mean square error before and after processing), physical rationality (rationality of velocity and acceleration distribution).
[0590] b) Smoothing-fidelity balance control: Define the objective function, and let the smoothness be... Fidelity is The weight is and :
[0591]
[0592] Adaptive weight adjustment and To balance smoothness and fidelity based on application requirements, gradient descent is implemented to find the optimal balance point.
[0593] The output of filtering and smoothing is high-quality cattle location time-series data with the following characteristics: significantly reduced location noise and smooth, natural trajectories; preservation of meaningful movement patterns and behavioral characteristics; physical rationality, conforming to cattle kinematics; consistency with environmental structure, without violating spatial constraints; real-time updates, with latency controlled within an acceptable range (<200ms).
[0594] This optimized location data serves as the foundational input for subsequent geofencing and behavior monitoring modules, significantly improving the accuracy and reliability of the entire system. End users see smooth, consistent cattle movement trajectories and accurate location information, maintaining high quality even in complex pen environments and with multiple cattle commotion.
[0595] Example 7
[0596] This embodiment is a further refinement of step S6 in embodiment 1, establishing a virtual geofence based on the final positioning result and generating early warning information, including the following steps:
[0597] S6.1: Virtual Geofencing Definition:
[0598] Based on the layout and management needs of the enclosures, a multi-layered virtual geofence is defined, including permitted activity areas, restricted areas, and abnormal warning areas.
[0599] Specifically, in this embodiment, based on the layout and management needs of the barn, a multi-layered virtual geofence is defined to provide a spatial reference framework for cattle location monitoring and abnormal behavior early warning.
[0600] Virtual geofences are virtual boundaries defined on a digital map. When cattle enter, leave, or remain in a specific area, corresponding monitoring and early warning mechanisms can be triggered. The fence definition includes the following levels:
[0601] The first layer, permitted activity areas, defines the areas where cattle can normally move around, including resting areas, feeding areas, activity areas, and passageways. Cattle activity within these areas is considered normal behavior and does not trigger warnings. Each permitted activity area is defined as a polygon, containing a sequence of boundary coordinate points and area attributes (such as function type, capacity limits, etc.).
[0602] The second layer, restricted areas, defines areas where cattle should not enter or may only enter under specific conditions. These include equipment rooms, medicine storage areas, and staff offices. When cattle enter a restricted area, a low-level alert is triggered, notifying management to check the situation. Restricted areas are also defined as polygons and have access control rules attached (such as time restrictions, cattle type restrictions, etc.).
[0603] The third layer, the abnormal warning zone, defines areas requiring special attention, including hazardous areas (such as deep water pools and steep slopes), isolation areas (such as isolation pens for sick cattle), and special functional areas (such as milking areas and treatment areas). When cattle enter an abnormal warning zone, a high-level alert is triggered, requiring immediate response from management. The definition of an abnormal warning zone includes polygonal boundaries, warning levels, and response procedures.
[0604] The fourth layer is dynamic fencing: fencing that is dynamically adjusted based on time, environmental conditions, or management needs. For example, certain areas may be designated as restricted zones at night and open during the day; or restricted zones may be temporarily set up during cleaning and disinfection. Dynamic fencing includes time conditions, environmental conditions, and state transition rules.
[0605] Fence definitions are stored in GeoJSON or a similar format, supporting complex geometries (such as polygons, circles, and composite shapes). Each fence contains the following attributes: Fence ID (unique identifier), Fence Name (descriptive name), Geometry (boundary definition), Fence Type (allow, restrict, abnormal warning), Warning Level (low, medium, high, urgent), Time Condition (valid time period), Applicable Object (specific cattle or herd), Trigger Rules (entry, exit, stay time, etc.), and Response Action (notification, recording, triggering device, etc.).
[0606] The fence definition supports hierarchical management, allowing you to define the containment relationship between parent and child fences, facilitating batch management and rule inheritance. For example, the entire enclosure can be defined as a parent fence, and the various functional areas within it can be defined as child fences.
[0607] S6.2: Real-time location and fence determination:
[0608] The final location result is compared with the virtual geofence in real time to determine the location status of the cattle and identify boundary crossing behavior.
[0609] Specifically, this embodiment compares the final accurate positioning result with the virtual geofence in real time to determine the location status of the cattle and identify boundary crossing behavior.
[0610] Real-time location and fence determination employs a high-efficiency spatial query algorithm to ensure low-latency response. The determination process is as follows:
[0611] The first step is location data reception: receiving the final positioning result from the filtering and smoothing module, which includes the cow ID, timestamp, and 3D coordinates. And positional accuracy assessment.
[0612] The second step is spatial index lookup: using a spatial index structure (such as an R-tree or quadtree) to quickly find fences that contain or are near the current location. The spatial index organizes fences by spatial location and supports... Time complexity of the query (where (Total number of fences).
[0613] The third step is to determine if the point is within the polygon: For the candidate fences found, the point-in-polygon algorithm is used to determine whether the cow's location is inside the fence. The ray casting algorithm is used: a ray is cast from the location point in any direction, and the number of intersections between the ray and the polygon boundary is counted; if the number of intersections is odd, the point is inside the polygon; if it is even, the point is outside the polygon.
[0614] Step 4, Fence Status Determination: Based on the results of the polygon determination and the fence type, determine the fence status of the cattle.
[0615] Within the permitted activity area: the status is "normal" and no alert is triggered.
[0616] Within the restricted area: The status is "Restricted area out of bounds", triggering a low-level warning and checking whether the access conditions (such as time, cattle type, etc.) are met.
[0617] Within the abnormal warning area: the status is "Abnormal area entered", triggering a high-level warning and requiring immediate response.
[0618] Not within any defined fence: The status is "Unknown area", triggering a medium-level warning, indicating possible location errors or incomplete fence definition.
[0619] Step 5, Boundary Crossing Detection: By comparing the current state with historical states, boundary crossing events are detected.
[0620] Entry event: Cattle enter the enclosure from outside the enclosure, or from one enclosure to another.
[0621] Leaving event: Cattle leave from inside the enclosure to outside the enclosure, or leave from one enclosure to another.
[0622] Staying event: Cattle stay in a specific enclosure for more than a preset time threshold.
[0623] Step 6, Time Condition Verification: For fences with time conditions, verify whether the current time is within the valid time period. If the fence is invalid at the current time, ignore the judgment result for that fence.
[0624] Step 7, Trigger Rule Evaluation: Based on the fence's trigger rules, evaluate whether an alert or other response action should be triggered. For example, some fences may only trigger an alert after the cattle have stayed for a certain period of time, rather than triggering it immediately.
[0625] Step 8: Result Output and Recording: Output the fence determination result, including the cattle ID, timestamp, current fence ID, fence status, trigger event type, and warning level. Simultaneously, record the determination result in the database for historical querying and statistical analysis.
[0626] The output of real-time location and fence determination is the location status judgment result, which serves as an important input for subsequent abnormal behavior detection and early warning. Through efficient spatial query and determination algorithms, real-time response capability is ensured, with determination latency typically controlled within 10ms.
[0627] S6.3: Behavioral Pattern Recognition and Analysis
[0628] Based on continuous positioning data and accelerometer sensor information, a time-series pattern mining algorithm is applied to identify the behavioral characteristics of cattle.
[0629] Specifically, this embodiment uses continuous positioning data and acceleration sensor information, and applies a time-series pattern mining algorithm to identify the behavioral characteristics of cattle, providing a basis for abnormal behavior detection.
[0630] Behavioral pattern recognition employs a multi-level, multi-modal analysis method, combining location information, motion characteristics, and physiological signals to comprehensively characterize the behavioral state of cattle. The recognition process is as follows:
[0631] The first step is feature extraction: extracting behavior-related features from continuous positioning data and accelerometer sensor information.
[0632] Location characteristics: dwell time (duration of stay in a specific location or area), movement distance (cumulative movement distance over a period of time), movement speed (average speed and maximum speed), movement direction (main movement direction and frequency of direction change), and spatial distribution (size and shape of the activity range).
[0633] Motion characteristics: acceleration statistics (mean, variance, peak value, etc.), frequency domain characteristics (main frequency components extracted by FFT), posture angles (body tilt angles based on acceleration estimation), and gait characteristics (step frequency, stride length, etc., extracted by acceleration periodicity analysis).
[0634] Temporal characteristics: activity periods (active periods and rest periods), periodicity (daily cycle, feeding cycle, etc.), and duration (duration of various behavioral states).
[0635] The second step is behavioral state classification: Based on the extracted features, the cattle's behavior is classified into several basic states. Common behavioral states include:
[0636] Feeding behavior: Characterized by staying in the feeding area with head down (estimated by acceleration posture), moving slowly or remaining still.
[0637] Drinking behavior: Characterized by brief pauses near the water dispenser and frequent head movements (with significant fluctuations in acceleration).
[0638] Resting behavior: characterized by prolonged stillness in the resting area, with the body horizontal (posture angle close to 0 degrees) and minimal change in acceleration.
[0639] Standing behavior: characterized by stillness or slight movement, with the body upright (at a relatively large angle of posture) and small changes in acceleration.
[0640] Walking behavior: characterized by continuous movement at a moderate speed, with periodic changes in acceleration (gait characteristics).
[0641] Social behavior: Characterized by approaching other cattle, similar movement patterns, and possible physical contact (acceleration mutation).
[0642] Rumination behavior: characterized by stillness or slow movement, with regular up-and-down head movements (periodic fluctuations in acceleration, with a frequency of about 1-2 Hz).
[0643] Abnormal behavior: Characterized by behaviors that deviate from normal patterns, such as remaining still for a long time, frequent and rapid movement, or activity in abnormal areas.
[0644] The third step is to build a behavior recognition model: use machine learning methods to build a behavior recognition model.
[0645] a) Model Selection: Choose a suitable classification model based on data characteristics and application requirements. Commonly used models include: Random Forest (suitable for handling high-dimensional features and has good generalization ability), Support Vector Machine (SVM, suitable for small sample learning and clear classification boundaries), Deep Neural Network (DNN, suitable for complex pattern recognition and requires a large amount of training data), Hidden Markov Model (HMM, suitable for time series data and can model state transitions), and Long Short-Term Memory Network (LSTM, suitable for long-term dependencies and can capture the temporal dynamics of behavior).
[0646] This embodiment prioritizes the use of the random forest model because it has fast training speed, good interpretability, and is not sensitive to parameters.
[0647] b) Training Data Preparation: Collect a labeled behavioral dataset containing samples of various behavioral states. Annotations can be obtained through manual observation, video analysis, or expert knowledge. Divide the dataset into a training set (70%), a validation set (15%), and a test set (15%).
[0648] c) Model Training: Train the random forest model using the training set. Set model parameters such as the number of decision trees (usually 100-500), maximum tree depth, minimum number of leaf node samples, etc. Use cross-validation during training to optimize model parameters and prevent overfitting.
[0649] d) Model Evaluation: Evaluate model performance using a test set, calculating metrics such as accuracy, precision, recall, and F1 score. If performance does not meet requirements (e.g., accuracy <85%), adjust feature selection or model parameters and retrain.
[0650] e) Model Deployment: Deploy the trained model to the real-time system for online inference on new data. Inference latency is controlled within 50ms to ensure real-time performance.
[0651] The fourth step is temporal pattern mining: In addition to identifying instantaneous behavioral states, we also mine temporal patterns of behavior to identify behavioral sequences and transition rules.
[0652] a) Behavior sequence extraction: Combine the continuous behavioral state recognition results into a behavior sequence, such as "standing → walking → eating → drinking → lying down".
[0653] b) Frequent Pattern Mining: Using sequence pattern mining algorithms (such as PrefixSpan or SPADE), frequently occurring behavioral sequence patterns are identified. These patterns reflect the typical daily activity patterns of cattle.
[0654] c) Abnormal pattern detection: Identify abnormal behavioral sequences that deviate from frequent patterns, such as "resting → resting → resting" (prolonged inactivity) or "walking → walking → walking" (hyperactivity).
[0655] d) State transition analysis: Construct a behavioral state transition diagram and analyze the transition probabilities and time distributions between states. Abnormal state transitions (such as going directly from eating to resting, skipping drinking) may indicate health problems.
[0656] Step 5, Individual Behavior Modeling: Build a personalized behavior model for each cow to capture its unique behavioral patterns and habits.
[0657] a) Baseline behavior establishment: Based on historical data, establish behavioral baselines for each cow, including typical activity times, feeding frequency, resting time, etc.
[0658] b) Deviation detection: Real-time comparison of current behavior with baseline behavior to calculate the degree of deviation. Significant deviations may indicate health problems, environmental changes, or management issues.
[0659] c) Adaptive updates: The behavioral baseline is not static, but is adaptively updated over time to reflect the growth of cattle, seasonal changes, and management adjustments.
[0660] Step 6, Group Behavior Analysis: In addition to individual behavior, group behavior patterns are analyzed to identify collective activities and social interactions.
[0661] a) Group activity detection: Identify activities performed by multiple cattle simultaneously, such as grazing or resting together.
[0662] b) Social network analysis: Based on the spatial proximity and interaction frequency among cattle, a social network graph is constructed to identify social relationships (such as dominance-subordination relationships, close partners, etc.).
[0663] c) Group anomaly detection: Identify anomalies at the group level, such as a large number of cattle gathering in a certain area at the same time (which may indicate feed problems or environmental problems).
[0664] The output of behavior pattern recognition and analysis is a set of behavior features, including the current behavior state, behavior sequence, degree of deviation, and anomaly indicators. This information serves as the core input for the next step of abnormal behavior detection and early warning.
[0665] S6.4: Abnormal Behavior Detection and Early Warning:
[0666] By comparing historical behavior patterns with current behavior characteristics, potential abnormal behaviors can be detected, triggering warnings at the corresponding levels.
[0667] Specifically, this embodiment detects potential abnormal behaviors by comparing historical behavior patterns with current behavior characteristics, triggers corresponding level of early warning, and achieves proactive monitoring of cattle health and welfare.
[0668] Abnormal behavior detection employs a multi-level, multi-dimensional analysis approach, comprehensively considering factors such as location, behavior, time, and environment. The detection process is as follows:
[0669] The first step, definition and classification of abnormalities: Based on the knowledge of livestock experts and analysis of historical data, various abnormal behaviors and their characteristics are defined. Common abnormal behaviors include:
[0670] Health abnormalities: prolonged inactivity (may indicate illness or injury), significantly decreased feed intake (may indicate digestive problems or disease), frequent lying down and standing up (may indicate pain or discomfort), abnormal gait (may indicate hoof disease or leg problems), and reduced rumination time (may indicate rumen problems).
[0671] Abnormal behavior: activity at abnormal times (such as frequent activity late at night), staying in abnormal areas (such as remaining motionless in a corner for a long time), social isolation (staying away from the herd and acting alone), and aggressive behavior (frequent conflicts with other cattle).
[0672] Abnormal environmental responses: no response to feeding time (may indicate illness or stress), avoidance of specific areas (may indicate problems in the area, such as slippery ground, equipment noise, etc.), herd panic (a large number of cattle moving rapidly at the same time, which may indicate fright or danger).
[0673] Abnormal production: Abnormal behaviors in cows about to give birth (such as frequent lying down, restlessness, seeking hiding places, etc., may indicate that calving is imminent) and estrus behaviors (such as mounting, accepting mounting, restlessness, etc.).
[0674] The second step is anomaly detection algorithms: multiple anomaly detection algorithms are used to identify abnormal behavior from different perspectives.
[0675] a) Threshold-based detection: Normal range thresholds are set for various behavioral indicators; exceeding these thresholds is considered abnormal. For example, if cattle move less than 50 meters in 24 hours (the normal range is 200-800 meters), their activity is considered abnormal. Thresholds can be fixed (based on expert knowledge) or adaptive (based on historical data statistics).
[0676] b) Statistical-based detection: Using statistical methods to detect data points that deviate from the normal distribution. For example, using the Z-score method, assuming the historical mean of a certain behavioral indicator is... The standard deviation is The current value is Then the Z-score is:
[0677]
[0678] like If it does not, it is considered an anomaly (3-sigma rule).
[0679] c) Machine learning-based detection: Training anomaly detection models, such as Isolation Forest, One-Class SVM, or Autoencoder. These models learn normal patterns from normal data and are able to identify anomalous data that deviates from the normal patterns.
[0680] The Isolation Forest algorithm constructs decision trees randomly and calculates the average path length of the samples. Outlier samples typically have shorter path lengths (making them easier to isolate), while normal samples have longer path lengths. Let the average path length of the samples be... Then abnormal scores for:
[0681]
[0682] in As the normalization factor, This represents the sample size. An anomaly score close to 1 indicates an anomaly, while a score close to 0 indicates normality.
[0683] d) Rule-based detection: Rules are defined based on expert knowledge, such as "If cattle stay in the pen area for more than 18 hours and their activity level is below 10, they are considered to have abnormal health." Rules can be simple if-then rules or complex logical expressions.
[0684] The third step is multi-dimensional fusion judgment: single-dimensional anomaly detection may produce false alarms, so multi-dimensional fusion judgment is adopted to make a final judgment by combining multiple detection results.
[0685] a) Evidence accumulation: Collect the outputs of various detection algorithms as "evidence" of anomalies. Each piece of evidence has a confidence level, indicating its reliability.
[0686] b) Fusion Strategy: Employing methods such as voting mechanisms, weighted averaging, or Bayesian fusion to synthesize multiple pieces of evidence for a final judgment. For example, using a weighted average, let the anomaly scores of each detection algorithm be... The weight is The abnormal scores after fusion for:
[0687]
[0688] like If the value exceeds a preset threshold (e.g., 0.7), it is considered abnormal.
[0689] c) Duration verification: The abnormal state must last for a certain period of time (e.g., 30 minutes) before it is confirmed as a true abnormality to avoid false alarms caused by instantaneous fluctuations.
[0690] The fourth step is to classify the warning levels: Based on the severity and urgency of the anomaly, the warning levels are classified.
[0691] Low-level warning (attention): Slight deviation from the normal pattern, which may be normal fluctuation. Attention is recommended, but immediate intervention is not necessary. For example, feeding time is 10% shorter than usual.
[0692] Medium-level warning (caution): Significant deviation from normal patterns; it is recommended to focus on checking during the next patrol. For example, no activity observed for 2 consecutive hours.
[0693] High-level warning: Significant deviation from normal patterns; prompt investigation and intervention are recommended. Examples include inactivity for 6 consecutive hours or the appearance of marked pain.
[0694] Emergency Warning (Emergency): An extremely unusual situation that may endanger the lives or safety of cattle, requiring immediate response. For example, cattle entering a dangerous area or showing signs of a serious health crisis.
[0695] Step 5, Early Warning Information Generation: Generate structured early warning information, including the following:
[0696] Warning ID (unique identifier), Cattle ID (affected cattle), Timestamp (time of anomaly occurrence), Warning Level (low, medium, high, emergency), Anomaly Type (health anomaly, behavioral anomaly, etc.), Anomaly Description (detailed description of the anomaly), Detection Basis (data and algorithm that triggered the warning), Recommended Measures (recommended response measures), Relevant Data (location, behavioral characteristics, historical comparison, etc.).
[0697] Step 6, Warning Distribution and Response: Distribute the warning information to management personnel through multiple channels.
[0698] Real-time notifications: Notify management personnel via mobile app push, SMS or telephone to ensure that emergency alerts reach them in a timely manner.
[0699] The management system displays warning information, providing detailed data and analysis results on the management system interface.
[0700] Record archiving: Record all warning information in the database for subsequent analysis and auditing.
[0701] Response tracking: Record the management personnel's response to the warning, including the response time, the measures taken, and the results.
[0702] Step 7, Early Warning Effectiveness Evaluation: Continuously evaluate the effectiveness of the early warning system and optimize the detection algorithm and early warning strategy.
[0703] Accuracy assessment: Statistically assess the accuracy (true positive rate) and false positive rate of early warning, and adjust the detection threshold and algorithm parameters.
[0704] Response timeliness assessment: Analyze the time from the occurrence of an anomaly to the response of management personnel, and optimize the early warning distribution mechanism.
[0705] Feedback on effectiveness: Collect feedback from managers on the early warnings to understand which early warnings are valuable and which are false alarms, and improve the system accordingly.
[0706] The output of abnormal behavior detection and early warning is an early warning information stream, which notifies managers in real time of abnormal situations that require attention, helping to identify and handle problems early and improve the health and welfare of cattle.
[0707] S6.5: Data Visualization and Management Interface
[0708] The system displays location results, fence status, and behavior analysis in an intuitive way on the management system interface, and provides historical data query and statistical analysis functions, supporting trend analysis and prediction.
[0709] Specifically, this embodiment displays the positioning results, fence status, and behavior analysis in an intuitive way on the management system interface, and provides historical data query and statistical analysis functions, providing a comprehensive decision support tool for aquaculture managers.
[0710] Example 8
[0711] like Figure 2 As shown, this embodiment provides a cattle positioning system within a barn, comprising:
[0712] The deployment module is used to deploy a Bluetooth beacon network within the enclosure, collect environmental feature datasets of the enclosure, construct a Bluetooth beacon node deployment coordinate map based on the environmental feature datasets, install Bluetooth beacon nodes in the enclosure according to the deployment coordinate map, and construct the Bluetooth beacon network through a topology adaptive algorithm;
[0713] The data acquisition module is used to install positioning tags on cattle, collect RSSI signal strength data and RTT ranging data between the positioning tags and each Bluetooth beacon node, and fuse the RSSI signal strength data and RTT ranging data using a second-order improved algorithm for edge estimation through independent set query to generate an initial set of coordinates for the cattle.
[0714] The map optimization module is used to establish a raster map based on the structural features of the enclosure, and to optimize the raster map using a low-diameter wiring decomposition technique and a fully dynamic algorithm of the map wrench, generating optimized location data;
[0715] The generation module is used to establish a static structure database of the cattle pens, construct a Bayesian probability model based on the initial position coordinate set, and generate a mapping relationship between cattle and pens.
[0716] The positioning optimization module is used to optimize the positioning results based on the optimized location data and the mapping relationship using an adaptive robust resettable flow algorithm to generate the final positioning result;
[0717] The early warning module is used to establish a virtual geofence based on the final positioning result, and to monitor and generate early warning information about the cattle's status in real time.
[0718] The apparatus in this application embodiment can execute the method provided in this application embodiment, and the implementation principle is similar. The actions performed by each module in the apparatus of each embodiment of this application correspond to the steps in the method of each embodiment of this application. For detailed functional descriptions of each module of the apparatus, please refer to the descriptions in the corresponding methods shown above, which will not be repeated here.
[0719] Although embodiments of the invention have been shown and described, it will be understood by those skilled in the art that various changes, modifications, substitutions and alterations can be made to these embodiments without departing from the principles and spirit of the invention, the scope of which is defined by the appended claims and their equivalents.
Claims
1. A method and system for precise positioning of cattle in a barn, characterized in that, include: A Bluetooth beacon network is deployed within the enclosure. An environmental feature dataset of the enclosure is collected. A Bluetooth beacon node deployment coordinate map is constructed based on the environmental feature dataset. Bluetooth beacon nodes are installed in the enclosure according to the deployment coordinate map. A Bluetooth beacon network is constructed using a topology adaptive algorithm. Location tags are installed on cattle, and RSSI signal strength data and RTT ranging data between the location tags and each Bluetooth beacon node are collected. The RSSI signal strength data and RTT ranging data are fused by a second-order improved algorithm for edge estimation using independent set query to generate the initial location coordinate set of the cattle. Based on the structural features of the enclosure, a grid map is established, and the grid map is optimized using a low-diameter wiring decomposition technique to achieve a fully dynamic algorithm for the drawing wrench, generating optimized location data. Establish a static structure database for the stalls, and construct a Bayesian probability model based on the initial position coordinate set to generate a mapping relationship between cattle and stalls; Based on the optimized location data and the mapping relationship, the positioning results are optimized using an adaptive robust resettable flow algorithm to generate the final positioning result; A virtual geofence is established based on the final positioning results, and the status warning information of cattle is monitored in real time.
2. The method according to claim 1, characterized in that, The deployment of a Bluetooth beacon network within the enclosure includes: A comprehensive analysis and measurement of the physical structure, dimensions, materials, and signal interference sources of the enclosures are conducted to generate the aforementioned environmental feature dataset; Based on the environmental feature dataset, a triangular mesh topology structure is used to design the deployment coordinate map of the Bluetooth beacon node. According to the deployment coordinate diagram, the Bluetooth beacon nodes are installed on the top and side walls of the enclosure, and each node is initialized and configured to establish a basic beacon network. Collect actual RSSI signal strength data from each node and construct an initial signal strength matrix through mutual measurement; Based on the initial signal strength matrix, the topology adaptive algorithm is run to dynamically adjust the beacon transmission power and communication parameters to form the Bluetooth beacon network.
3. The method according to claim 1, characterized in that, The process involves installing positioning tags on cattle, collecting RSSI signal strength data and RTT ranging data between the positioning tags and each Bluetooth beacon node, and fusing the RSSI signal strength data and RTT ranging data using a second-order improved algorithm for edge estimation via independent set query to generate an initial set of coordinates for the cattle, including: The positioning tag establishes communication with each of the Bluetooth beacon nodes, collects RSSI signal strength data of multiple beacon nodes, and performs preprocessing through sliding window filtering and outlier removal. Based on the round-trip time between the positioning tag and each of the Bluetooth beacon nodes, the actual distance is calculated to form a polygon ranging dataset; The RSSI signal strength data and the RTT ranging data are regarded as edges in a graph. The independent set query technique is applied to perform a second improvement on edge estimation, thereby reducing the impact of environmental factors on ranging accuracy. Based on the improved edge estimation results, and combined with the principles of trilateration and multilateral positioning, the initial position coordinates of the cattle are calculated using the least squares method.
4. The method according to claim 1, characterized in that, Based on the structural features of the enclosure, a grid map is established. A low-diameter wiring decomposition technique is used to implement a fully dynamic algorithm for the drawing wrench, optimizing the grid map and generating optimized location data, including: A basic environmental model is generated by creating a three-dimensional digital model of the pen layout, including walls, partitions, and feeding areas. The basic environment model is divided into rasterized segments according to a preset precision, and each raster unit is assigned a physical attribute label to form an attribute raster map. The signal strength is sampled and measured within the enclosure using the Bluetooth beacon network, and the sampled data is mapped onto the grid map to generate a signal propagation characteristic layer. Based on the grid map, a full dynamic algorithm for the graphic wrench is implemented by applying low-diameter wiring decomposition technology, which simplifies the signal propagation path in complex environments into a subset of paths. The initial set of location coordinates is matched and analyzed with the grid map. The positioning results are optimized using a probability distribution model, and the optimized location data is output.
5. The method according to claim 1, characterized in that, The process of establishing a static structure database for cattle pens, constructing a Bayesian probability model based on the initial set of position coordinates, and generating a mapping relationship between cattle and pens includes: Measure and define different functional areas within the enclosure, and establish a static structure database for the enclosure. Based on historical location data analysis, the activity patterns and preferred areas of stay of cattle are analyzed to generate activity heatmaps and time distribution models; By combining the static structure database of the stalls and the analysis results of the activity patterns, the Bayesian probability model is constructed to calculate the conditional probability of cattle appearing in a specific stall.
6. The method according to claim 5, characterized in that, The construction of the Bayesian probability model includes: Construct a state transition probability matrix to describe the probability distribution of cattle moving between different pen positions; Based on the activity heatmap and time distribution model, the prior probability of cattle appearing in a specific pen in each time period is calculated. Model parameters are learned from historical data using maximum likelihood estimation and expectation maximization algorithms.
7. The method according to claim 1, characterized in that, Based on the optimized location data and the mapping relationship, the positioning result is optimized using an adaptive robust resettable flow algorithm to generate the final positioning result, including: By integrating the optimized location data and the mapping relationship, and combining it with the accelerometer data worn by the cattle, a multi-dimensional feature vector is formed; Cluster analysis and anomaly detection algorithms are applied to identify and eliminate interfering factors that may cause positioning errors. An adaptive robust algorithm based on flow network theory is constructed to transform the localization problem into a flow allocation problem and dynamically adjust the weights of different information sources. Design trigger conditions and reset strategies to reset algorithm parameters when significant positioning drift or environmental changes are detected; Kalman filtering and trajectory smoothing techniques are applied to the optimized positioning results to eliminate jumps and jitters, and the final positioning result is output.
8. The method according to claim 1, characterized in that, The process of establishing a virtual geofence based on the final positioning result, and monitoring and generating real-time status warning information for cattle includes: Based on the layout and management needs of the enclosures, a multi-layered virtual geofence is defined, including permitted activity areas, restricted areas, and abnormal warning areas; The final location result is compared with the virtual geofence in real time to determine the location status of the cattle and identify boundary crossing behavior; Based on continuous positioning data and accelerometer sensor information, a time-series pattern mining algorithm is applied to identify the behavioral characteristics of cattle.
9. The method according to claim 8, characterized in that, The generated cattle status warning information includes: By comparing historical behavior patterns with current behavior characteristics, potential abnormal behaviors can be detected and corresponding warnings can be triggered. The location results, fence status, and behavior analysis are displayed intuitively on the management system interface; It provides historical data query and statistical analysis functions, and supports trend analysis and forecasting.
10. A cattle positioning system within a barn, characterized in that, include: The deployment module is used to deploy a Bluetooth beacon network within the enclosure, collect an environmental feature dataset of the enclosure, construct a Bluetooth beacon node deployment coordinate map based on the environmental feature dataset, install Bluetooth beacon nodes in the enclosure according to the deployment coordinate map, and construct a Bluetooth beacon network through a topology adaptive algorithm. The data acquisition module is used to install positioning tags on cattle, collect RSSI signal strength data and RTT ranging data between the positioning tags and each Bluetooth beacon node, and fuse the RSSI signal strength data and RTT ranging data through a secondary improved algorithm of edge estimation using independent set query to generate the initial position coordinate set of the cattle. The map optimization module is used to establish a grid map based on the structural features of the enclosure, and to optimize the grid map using a low-diameter wiring decomposition technique to achieve the full dynamic algorithm of the map wrench, thereby generating optimized location data. The generation module is used to establish a static structure database of the stalls, construct a Bayesian probability model in combination with the initial position coordinate set, and generate the mapping relationship between cattle and stalls. The positioning optimization module is used to optimize the positioning results based on the optimized location data and the mapping relationship using an adaptive robust resettable flow algorithm to generate the final positioning result. The early warning module is used to establish a virtual geofence based on the final positioning result, and to monitor and generate early warning information about the cattle's status in real time.