An Improved Intelligent Control System for Temperature and Humidity in a Pig House

: The temperature and humidity control of a pig house is a complex multivariable control problem. How to keep the temperature and humidity in a pig house within a normal range is the problem to be solved in this paper. The traditional threshold-based environmental control system cannot meet this requirement. In this paper, an intelligent control system of temperature and humidity in a pig house based on machine learning and a fuzzy control algorithm is proposed. We use sensors to collect the temperature and humidity in the pig house and store these data in chronological order. Then, we use these time series data to train the GRU model and then use the GRU model to predict the temperature and humidity change curve in the pig house in the next 24 hours. Finally, the mathematical model of the pig house and related equipment is established, and the output power of the related equipment is calculated based on the prediction results of GRU so as to effectively regulate the indoor temperature and humidity. The experimental results show that compared with the threshold-based environmental control system, our system reduces the abnormal temperature and humidity by about 90%.


Introduction
Modern confined animal production buildings are typically classified as intensive livestock production houses and are prominently used for the production of milk, eggs, and a variety of meats.Such livestock buildings (LB) are ventilated with natural and/or mechanical ventilation systems.In practice, the continuous release of sensible and latent heat, CO2 from animals, and NH3 released from manure contaminate the animal's environment.The contaminated indoor environment affects animal health and the productivity of the operation [1].Therefore, a ventilation system (VS), an integral part of livestock buildings, maintains a hospitable environment for the animal.
The traditional individual breeding method has low production efficiency, requires a large investment, and poses a high risk to biological assets, which are difficult to create scale economy effects.Large-scale, remote, less populated, and intelligent breeding plays an important role in improving production efficiency, protecting the environment and reducing both labor costs and the probability of epidemics.Big data, the Internet of Things, and 5G make intelligent management of the breeding industry infinitely possible [2].

Effects of Temperature on the Growth of Commercial Pigs in Large-Scale Breeding Houses
The appropriate temperature is the precondition to ensure the normal development and reproduction of pigs.Pigs are thermostatic animals that maintain a dynamic balance of heat production and heat dissipation through physiological regulation.When the ambient temperature gradually increases (heat stress), in order to reduce heat production, pigs reduce activity and food intake and increase water intake, slowing growth and even leading to negative weight gain [3].When the temperature is low (cold stress), the heat dissipation of pigs increases and feed intake increases in order to maintain heat balance.According to Johnson et al. [4], the feed intake of fattening pigs at the high temperature of 28~35 • C can be reduced by 24.1~29.7%compared with the standard daily feed intake; the daily gain is 6.8-28% lower than the expected daily gain.Raising pigs is a process of biological transformation.The chemical energy of the feed is converted into energy in the animal's body.In terms of net energy, the balance between producing and maintaining energy frequently varies.When the ambient temperature is suitable, maintenance energy decreases, production energy increases, and the feed utilization rate is improved.Feed utilization rates can be expressed by the ratio of net energy produced to total energy intake.When the temperature changes between low and high critical temperatures (T1~T2), the physiological regulation of pigs is weak, and the feed utilization rate is at its highest.When the temperature is higher than T2, the skin blood vessels of pigs expand, increasing the body surface temperature, bringing the body heat to the body surface, increasing epidermis water permeability and accelerating the respiratory rate; pigs can change their breathing mode to improve evaporation and heat dissipation.This process increases the proportion of maintenance energy, thus reducing feed utilization efficiency.When the ambient temperature is lower than T1, there is reduced respiratory frequency in pigs and increased metabolic heat production in the body to compensate for the excessive heat loss by consuming a large amount of feed and, at the same time, the amount of activity is increased; the chemical energy in the body will be converted into maintenance energy through exercise, which leads to a decrease in feeding efficiency.In an environment where there are continuously high temperatures, the resistance of pigs significantly decreases, the body heat balance is destroyed, and the body temperature increases; this can lead to comas, heat radiation diseases, and even death in severe cases.In a low-temperature environment, pigs can contract peripheral blood vessels in order to keep warm, causing local frostbite.Low temperatures can cause respiratory and digestive tract diseases but can also often cause rheumatism, arthritis, and other diseases.Low temperature has a greater impact on piglets, and according to statistics, half of dead piglets either freeze to death or die from cold-related diseases.For newborn piglets in low-temperature environments, incidences of diarrhea and other diseases significantly increase.When the ambient temperature is higher than 33~35 • C, semen quality, sperm count, and the motility of boars decrease.Sows can often develop anestrus and behavioral anestrus (ovulation without estrous symptoms); the estrous cycle is prolonged, and the conception rate is reduced.In a study by Quiniou et al. [5], when the temperature reached 28.4 • C, the semen collection of boars decreased by 24 ml, the sperm motility decreased, and the conception rate during estrus decreased by 5.7%.When the temperature reached 27.7 • C, the litter weight decreased by 1.56 kg, and the fertility rate decreased by 13.02%.

Limitations of Threshold-Based Controllers
At present, the most popular temperature control system on the market is based on a threshold, which is low-cost and easy to use.For example, Qing Du [6] designed an intelligent monitoring system for chicken coops.The system monitors the indoor temperature change in real time.When the indoor temperature exceeds the threshold, the system dynamically adjusts the output power of the temperature control device based on the difference between the indoor temperature and the threshold.The larger the difference is, the higher the output power is until the indoor temperature restores the target temperature.Yiguang et al. [7] developed an intelligent environmental control system for animal houses based on an ARM M3 single-chip microcomputer.This system consisted of an environmental control box, system software, server, and mobile terminals.The environmental control box was composed of a single-chip microcomputer, ferroelectric, SIM card module, relay, display screen, electric frequency converter, and other electronic hardware components.This box had three functions, including data collection, device control, and data transmission and communication.This system integrated computer technologies with multi-sensor data fusion technology to collect real-time data pertaining to temperature, relative humidity, light intensity, ammonia, and hydrogen sulfide in animal houses.When the actual measured data exceeded the preset range, the system could automatically control the house environment by switching the fans and other equipment on or off.The preset parameters of the environmental control box can be remotely modified on a PC or cell phone and allow the real-time operation of the system.
Although this control method can restore the indoor temperature to normal, it cannot avoid abnormal temperatures.Because this method takes the abnormal temperature as the condition for the device to be turned on, the device will be turned on only if the temperature is abnormal.Therefore, this control strategy cannot always keep the temperature in a suitable range.

Related Work
The work mainly involves machine learning, mathematical modeling, and fuzzy control algorithms.
In terms of machine learning, our work draws on the work of Svetozarevic et al. [8].They proposed a fully black-box, data-driven joint control method for indoor temperature and bidirectional electric vehicle charging.The approach is an end-to-end, data-driven approach that uses historical data to obtain control strategies for multi-output (MIMO) control problems in the architecture-mobile coupling domain.The authors use recurrent neural networks (RNNs) to simulate room temperature and discuss the influence of weather forecasts on model accuracy.A deep deterministic policy gradient (DDPG) algorithm is used to find a continuous MIMO control strategy to control the heating/cooling systems and charge/discharge power of bidirectional electric vehicles.The simulation results show that, while saving energy and cost, this method minimizes the violation of comfort, achieves the desired comfort limit, and provides sufficient energy for the next trip of electric vehicles.Inspired by the use of recurrent neural networks to simulate room temperature by Svetozarevic, we decided to use GRU to simulate the temperature and humidity in pig houses.The GRU network is an improvement of RNN, which solves the problem that traditional neural networks cannot process sequence data, and the data set we use is a time series data set.
In terms of the fuzzy control algorithm, our work draws on the research of Gao and Enriko et al.In the study of Gao et al. [9], error E and error change rate Ec are taken as the inputs of the fuzzy PID controller, and ∆KP, ∆KI, and ∆KD are taken as the outputs of the fuzzy PID controller.According to the experience of field engineers and the theory of experts, the fuzzy subsets of inputs E and Ec and outputs ∆KP, ∆KI, and ∆KD are divided into seven grades: "positive big (PB), positive middle (PM), positive small (PS), zero (ZO), negative small (NS), negative medium (NM), and negative large (NB)".The universe of temperature error E and error change rate Ec is [−2,2], and the quantified grades are {−2, −1.5, −0.5, 0, 0.5, 1, 1.5, 2}.The universe of humidity error E and error change rate Ec is [−10,10], and the quantified level is {−10, −8, −6, −4, −2, 0, 2, 4, 6, 8, 10}.According to the structural characteristics of brooder houses and the growth environment of chicks and other parameters, the microclimate simulation model of brooder houses was established using the physical law of energy balance.The simulation results show that the control strategy meets the temperature and humidity control requirements and verify the effectiveness of the control strategy and model.The experimental results can guide the actual environmental control of brooder houses.Enriko et al. [10] developed a chicken coop prototype that focuses on temperature control systems on smart poultry farms via the PID control approach.The sensor utilized is a DHT22 sensor with a calibration accuracy of 96.88 percent.The PID response was found to be satisfactory for the system with Kp = 10, Ki = 0, and KD = 0.1, and the time necessary for the system to reach the specified temperature was 121 s with a 1.03% inaccuracy.In our system, the input of the fuzzy controller is the difference between the real-time temperature and the target temperature, the fuzzy control rule is the formula derived from the heat balance, and the output is the output power of the equipment.

Contribution of This Paper
This article has the following key contributions: (1) We recommend using the GRU network to model the indoor temperature.We train the GRU model with more than 40,000 historical data, each of which includes indoor temperature, outdoor temperature, outdoor humidity, outdoor wind direction, outdoor wind speed, and outdoor air pressure.(2) According to the prediction results of the GRU model, the controller can start the relevant control equipment in advance before the temperature becomes abnormal so that the indoor temperature can always be kept within a normal range.(3) In the process of temperature control, due to the influence of many factors, such as the heat exchange of indoor and outdoor air and the heat exchange between the walls of the piggery and the outside world, there may be a large gap between the predicted results of the GRU model and the actual temperature values, resulting in the final control effect not being ideal.In view of this, we use a fuzzy control algorithm to flexibly adjust the output power of the equipment according to the gap between the predicted results and the actual value so as to achieve an ideal control effect.(4) We have designed and implemented a complete temperature regulation system, which can accurately adjust the temperature in the pigsty and effectively avoid abnormal temperatures.

Methodology
Figure 1 shows the adjustment process of temperature and humidity, which mainly includes three steps: (1) Training GRU model: in order to improve the training efficiency and accuracy of the model, the data set is preprocessed, and the important parameters of the model are adjusted.(2) Formulate macro-regulation strategy: calculate the output power of related equipment according to the predicted results of the GRU model and the relevant parameters of the equipment.(3) Making micro-regulation strategy: the prediction results of the GRU model will be affected by the heat exchange of indoor and outdoor air, the heat exchange between the walls of the piggery and the outside world, as well as the heat and moisture produced by the pigs, which leads to the deviation between the predicted results of GRU model and the actual value.At this point, if the temperature and humidity are adjusted according to the calculation results of the second step, the temperature and humidity may not be restored to the target value within a specified period of time.Therefore, we introduce the fuzzy control algorithm.The fuzzy controller will adjust the indoor temperature and humidity according to the values collected by the sensor in real time, so as to achieve the purpose of accurate adjustment.(4) The balance controller: after formulating the temperature and humidity regulation strategy, the balance controller will adjust the temperature and humidity, respectively, according to the strategy.(5) After the temperature and humidity are restored to the target value, go back to step (1) and start the next round of temperature and humidity adjustment.The dataset used in this section was provided by Zhenjiang Hongxiang Automation Technology Co., Ltd.These data sets were collected by equipment arranged at a pig farm in Liangshan County, Shandong Province, China.The elements of the data set include indoor temperature, indoor humidity, outdoor temperature, outdoor humidity, outdoor wind direction, outdoor wind speed, and outdoor air pressure.The dataset is time series data, and the interval between adjacent data is 5 min.

Data Preprocessing
Due to sensor damage, temporary failure, and other factors, the measured value of the sensor may be abnormal, which seriously affects the accuracy of the GRU model.Therefore, we preprocessed the dataset before training the model.In addition, in order to improve the convergence speed and accuracy of the GRU model, we also normalized the dataset.

Abnormal Data Detection
The outliers are those that have unreasonable values in the data set.The frequency of abnormal data in the entire data set is very small, and their characteristics are significantly different from normal data.Commonly used methods for detecting abnormal data include outlier detection based on proximity degree [11], density-based outlier detection [12][13][14], clustering-based outlier detection [15,16], and so on.This paper uses the isolation forest algorithm [17] to detect anomalous data.
The isolation forest algorithm is suitable for the anomaly detection of continuous data.Different from other anomaly detection algorithms that use quantitative indicators, such as distance and density, to describe the degree of alienation between samples, the isolation forest algorithm detects outliers by isolating sample points [18].

Exceptional Data Handling
After detecting the abnormal data, it is necessary to correct the abnormal data.This paper uses the simple moving average method [19] to process abnormal data.The moving average method is a commonly used method to predict one or more future periods of data with a group of recent actual data values.The calculation formula of the simple moving average method is as follows: where F t denotes the predicted value for the next period; A t−1 , A t−2 , A t−3 , and A t−n represent the actual values of the previous period, the first two periods, the first three periods, and the previous n periods, respectively; n is the number of periods of the moving average.

Data Normalization
Different evaluation indicators often have different dimensions and dimension units, which will affect the results of data analysis.In order to eliminate the dimensional impact between indicators, data standardization is required to solve the comparability between data indicators.After the original data are standardized, all indicators are in the same order of magnitude, which is suitable for comprehensive comparative evaluation.In addition, the data normalization processing also has the advantage of improving the convergence speed and accuracy of the model.
Normalization is to limit the data to a certain range.This paper adopts Min-Max standardization, and the calculation formula is shown as follows: where minA and maxA are the minimum and maximum values of attribute A, respectively.Mapping an original value x of A to a value x ′ between 0 and 1 was performed by max-min normalization.

Processing of Prediction Results of GRU Model
We obtained the weather forecast data for the next 24 hours from the third-party platform.The time interval of these data is 1 hour.Therefore, the time interval of the temperature predicted by the GRU model is also 1 hour.However, the data we want are continuous.Therefore, we use the weighted average method to calculate the temperature T (t) at time t.The calculation formula is as follows: In the formula, the temperatures of time t1 and t2 have been predicted by the GRU model; that is, T (t1) and T (t2) are known, and the temperatures at any other time between t1 and t2 are not predicted by the GRU model.The time t is between t1 and t2.
Similarly, humidity is treated in the same way.

Parameter Adjustment of GRU
We adjusted the important parameters of the GRU model, including the number of samples batch_size, the length of parameter time series Seq and the number of training rounds epoch.
First of all, we carried out an experiment on adjusting the parameter batch_size.We set Seq = 100, epoch = 100 and learning rate α = 0.001.The curve of the partial loss function is shown in Figure 2

Formulate the Macroscopic Regulation Strategies of Temperature
The temperature regulation of a pig house is mainly divided into cooling and heating.The cooling equipment mainly includes fans and wet curtains, and the heating equipment mainly includes heaters.In this section, we will derive the output power of each device in different scenarios.
Figure 5 shows the process of macroscopically adjusting the indoor temperature.The specific process is as follows: (1) First of all, the GRU model will predict the temperature change curve T(t) in the next 24 h.(2) Compare T(t) with the high-temperature threshold Thigh and the low-temperature threshold Tlow.If Tlow < T(t) < Thigh, it shows that the temperature is not abnormal and directly enters the micro-regulation mode of temperature; if T(t) ≤ Tlow, the controller begins to formulate a heating strategy; if T(t) ≥ Thigh, the controller begins to formulate a cooling strategy.(3) If an exception occurs, the controller will run the device in accordance with the policy.(4) After macro-adjustment, the indoor temperature will not necessarily return to the target temperature, and then it will enter the micro-adjustment mode.(5) After the micro-adjustment mode, the indoor temperature returns to the target temperature, and the controller enters the next round of regulation.

Macro-Adjustment Strategy 2.3.1. Formulate the Macroscopic Regulation Strategies of Temperature
The temperature regulation of a pig house is mainly divided into cooling and heating.The cooling equipment mainly includes fans and wet curtains, and the heating equipment mainly includes heaters.In this section, we will derive the output power of each device in different scenarios.
Figure 5 shows the process of macroscopically adjusting the indoor temperature.The specific process is as follows: (1) First of all, the GRU model will predict the temperature change curve T(t) in the next 24 h.(2) Compare T(t) with the high-temperature threshold T high and the low-temperature threshold T low .If T low < T(t) < T high , it shows that the temperature is not abnormal and directly enters the micro-regulation mode of temperature; if T(t) ≤ T low , the controller begins to formulate a heating strategy; if T(t) ≥ T high , the controller begins to formulate a cooling strategy.(3) If an exception occurs, the controller will run the device in accordance with the policy.(4) After macro-adjustment, the indoor temperature will not necessarily return to the target temperature, and then it will enter the micro-adjustment mode.(5) After the micro-adjustment mode, the indoor temperature returns to the target temperature, and the controller enters the next round of regulation.The output power of the temperature control device is determined by the severity of the temperature change.Assume that the temperature change curve predicted by the GRU model is T(t).The severity of the temperature change is represented by the absolute value of the derivative of the temperature curve T(t) at time t.The calculation formula is as follows: The value of d at each time is different, which means that the output power of the temperature control equipment should be changed frequently.For temperature control equipment, if the output power of the equipment is frequently adjusted in a short time, the equipment will be damaged, and the service life of the equipment will be shortened.Therefore, we divide the operating time of the equipment into multiple smaller time periods according to the severity of the temperature change, and the output power of the equipment is the same in each time period.Each time period must satisfy the following conditions: the severity of temperature change d ≤ 0.5, or 0.5 < d ≤ 1, or d > 1.
For the heating process, the minimum output power of the heater is calculated as follows: The output power of the temperature control device is determined by the severity of the temperature change.Assume that the temperature change curve predicted by the GRU model is T(t).The severity of the temperature change is represented by the absolute value of the derivative of the temperature curve T(t) at time t.The calculation formula is as follows: The value of d at each time is different, which means that the output power of the temperature control equipment should be changed frequently.For temperature control equipment, if the output power of the equipment is frequently adjusted in a short time, the equipment will be damaged, and the service life of the equipment will be shortened.Therefore, we divide the operating time of the equipment into multiple smaller time periods according to the severity of the temperature change, and the output power of the equipment is the same in each time period.Each time period must satisfy the following conditions: the severity of temperature change d ≤ 0.5, or 0.5 For the heating process, the minimum output power of the heater is calculated as follows: P t i , t j represents the minimum output power of the heating equipment in the time period t i , t j ; C represents the specific heat capacity of the air; ρ represents the density of the air; V represents the volume of the breeding house; T target and T low represent the target temperature and low-temperature threshold, respectively; DA represents the operating time of the heating equipment; η represents the efficiency of the heating equipment.
During the cooling process, the fan draws the indoor air away so that the outdoor air enters the room through the water curtain.When the flowing air passes through the wet curtain, the water in the wet curtain will absorb the heat in the air and evaporate, taking away a large amount of latent heat so that the temperature of the air passing through the wet curtain is lowered, so as to achieve the purpose of cooling.When the wet curtain is working, the water pump needs to be turned on.Whether the water pump is turned on or not is related to the outdoor temperature and the target temperature.Specifically, when the outdoor temperature is greater than the target temperature, the water pump is turned on; when the outdoor temperature is lower than or equal to the target temperature, the water pump is turned off.
The formula for calculating the minimum output power of the fan is as follows: T high , T target , and T out represent the high-temperature threshold, target temperature, and outdoor temperature, respectively; S represents the cross-sectional area of the air inlet; k represents the cooling efficiency of the wet curtain (if the water pump is not turned on, k is 0); P t i , t j represents the minimum output power of the fan in the time period t i , t j ; and p represents the corresponding increase in the output power of the fan for every 1m/s increase in the wind speed at the air inlet.

Formulate the Macroscopic Regulation Strategies of Humidity
The humidity regulation process is similar to temperature, but the difference is the calculation formula of equipment output power.Assume that the humidity change curve is H (t). The calculation formula for the severity of humidity change at time t is as follows: For the humidification process, the minimum output power of the humidifier is calculated as follows: In the formula, P t i , t j represents the minimum output power of the humidifier in the time period t i , t j ); p represents the energy consumption of the humidifier to transport a unit volume of water into the air; V represents the volume of the breeding house; ρ is the density of air; ts is the number of air changes; and C is the loss coefficient.
For the dehumidification process, the minimum output power of the dehumidifier is calculated as follows: In the formula, p represents the energy consumption of the dehumidifier to remove the moisture per unit volume in the air; V1 represents the volume of the breeding house; V2 represents the fresh air volume; and C represents the loss coefficient.

Micro-Adjustment Strategy
Figure 6 shows the micro-adjustment process based on the fuzzy control algorithm, as described below: (1) First, compare whether the absolute value of the difference between the actual value A(t) (temperature/humidity) measured by the sensor and the target value Target is less than the threshold H.If |A(t)-Target| < H, the room temperature/humidity has been restored to near the target value, and the current adjustment process is over; otherwise, continue to the next step.(2) If A(t)-Target > 0, it is necessary to formulate the cooling/dehumidification strategy; otherwise, the heating/humidification strategy should be established.(3) The controller operates the equipment according to the policy, and the running time is Duration.(4) Go back to step (1) and repeat the above steps.

Micro-Adjustment Strategy
Figure 6 shows the micro-adjustment process based on the fuzzy control algorithm, as described below: (1) First, compare whether the absolute value of the difference between the actual value A(t) (temperature/humidity) measured by the sensor and the target value Target is less than the threshold H.If |A (t)-Target| < H, the room temperature/humidity has been restored to near the target value, and the current adjustment process is over; otherwise, continue to the next step.(2) If A(t)-Target > 0, it is necessary to formulate the cooling/dehumidification strategy; otherwise, the heating/humidification strategy should be established.(3) The controller operates the equipment according to the policy, and the running time is Duration.(4) Go back to step (1) and repeat the above steps.Figure 7 shows the internal structure of the fuzzy controller.The fuzzy controller first receives an input, e.The parameter e is the difference between the value measured by the sensor and the target value.The calculation formula is as follows: The fuzzy interface divides the difference e into three fuzzy sets: positive, zero, and negative.The specific division of the fuzzy set is shown in the following table (H is a threshold, | e | < H indicates that the actual value is very close to the target value, so there is no need to continue to run the equipment).Figure 7 shows the internal structure of the fuzzy controller.The fuzzy controller first receives an input, e.The parameter e is the difference between the value measured by the sensor and the target value.The calculation formula is as follows: e = A(t) − T target (10) The fuzzy interface divides the difference e into three fuzzy sets: positive, zero, and negative.The specific division of the fuzzy set is shown in the following Table 1 (H is a threshold, |e| < H indicates that the actual value is very close to the target value, so there is no need to continue to run the equipment).

Condition Fuzzy Set e < -H Positive -H ≤ e ≤ H Zero e > H Negative
In the fuzzy rule and inference engine stage, the controller will do the following: if e is in a positive fuzzy set, then a heating/humidification strategy is needed; if e is in a negative fuzzy set, then a cooling/dehumidification strategy is needed; otherwise, stop the equipment.
In the defuzzification stage, the controller will calculate the output power of the relevant equipment according to the decision results of the inference engine.If the controller needs to make a heating strategy, the formula for calculating the minimum output power of heaters during the time period (t, t+Duration) is as follows: If the controller needs to make a cooling strategy, the formula for calculating the minimum output power of fans in the time period (t, t+Duration) is as follows: If a humidification strategy is required, the formula for calculating the minimum output power of the humidifiers is as follows: If a dehumidification strategy is required, the formula for calculating the minimum output power of dehumidifiers is as follows:

Temperature and Humidity Balance Mechanism
In this system, humidity is severely affected during temperature regulation.For example, when the fans are turned on, outdoor air enters the pig house, and the outdoor air is too dry, which will cause the indoor humidity to fall below the threshold.When opening the wet curtain, the humidity in the room may be higher than the threshold due to the evaporation of water vapor.Therefore, we adjusted the temperature first and adjusted the humidity after the temperature returned to the target value.In the fuzzy rule and inference engine stage, the controller will do the following: if e is in a positive fuzzy set, then a heating/humidification strategy is needed; if e is in a negative fuzzy set, then a cooling/dehumidification strategy is needed; otherwise, stop the equipment.
In the defuzzification stage, the controller will calculate the output power of the relevant equipment according to the decision results of the inference engine.If the controller needs to make a heating strategy, the formula for calculating the minimum output power of heaters during the time period (t, t+Duration) is as follows: If the controller needs to make a cooling strategy, the formula for calculating the minimum output power of fans in the time period (t, t+Duration) is as follows: If a humidification strategy is required, the formula for calculating the minimum output power of the humidifiers is as follows: If a dehumidification strategy is required, the formula for calculating the minimum output power of dehumidifiers is as follows:

Temperature and Humidity Balance Mechanism
In this system, humidity is severely affected during temperature regulation.For example, when the fans are turned on, outdoor air enters the pig house, and the outdoor air is too dry, which will cause the indoor humidity to fall below the threshold.When opening the wet curtain, the humidity in the room may be higher than the threshold due to the evaporation of water vapor.Therefore, we adjusted the temperature first and adjusted the humidity after the temperature returned to the target value.

Experimental Setup
Our experimental site was provided by Zhenjiang Hongxiang Automation Technology Co., Ltd.The experimental site is located in Liangshan County, Jining City, Shandong Province.We conducted an experiment for six months.

System Framework
Our system needs a lot of data processing and calculation and needs to complete these operations in a short time, so the computing power of the CPU is relatively high.In addition, when we predict indoor temperature, we need to obtain weather forecast data from third-party platforms.Therefore, it is unrealistic to rely solely on the controller to achieve these functions.We divide the system into two parts: cloud platform and terminal.
Figure 8 shows the framework of the system.The cloud platform is responsible for the following modules: data preprocessing, training the GRU model, obtaining weather forecast data, predicting indoor temperature, and formulating macro-adjustment strategies.The terminal device includes a controller and a plurality of acquisition nodes.The controller is responsible for formulating micro-adjustment strategies, controlling the operation of equipment and uploading data.The acquisition node is responsible for collecting data.The cloud platform and the controller communicate through 4G or WIFI, and the controller and collection nodes communicate through the ZigBee network.

Experimental Setup
Our experimental site was provided by Zhenjiang Hongxiang Automation Technology Co., Ltd.The experimental site is located in Liangshan County, Jining City, Shandong Province.We conducted an experiment for six months.

System Framework
Our system needs a lot of data processing and calculation and needs to complete these operations in a short time, so the computing power of the CPU is relatively high.In addition, when we predict indoor temperature, we need to obtain weather forecast data from third-party platforms.Therefore, it is unrealistic to rely solely on the controller to achieve these functions.We divide the system into two parts: cloud platform and terminal.
Figure 8 shows the framework of the system.The cloud platform is responsible for the following modules: data preprocessing, training the GRU model, obtaining weather forecast data, predicting indoor temperature, and formulating macro-adjustment strategies.The terminal device includes a controller and a plurality of acquisition nodes.The controller is responsible for formulating micro-adjustment strategies, controlling the operation of equipment and uploading data.The acquisition node is responsible for collecting data.The cloud platform and the controller communicate through 4G or WIFI, and the controller and collection nodes communicate through the ZigBee network.

Experimental Equipment
The cloud platform uses the Elastic Compute Service.The terminal equipment includes a controller and two acquisition nodes.The shape of the controller and acquisition node is shown in the following Figure 9: Agriculture 2022, 12,1987 14 of 21

Experimental Equipment
The cloud platform uses the Elastic Compute Service.The terminal equipment includes a controller and two acquisition nodes.The shape of the controller and acquisition node is shown in the following figure: The acquisition node includes multiple sensors: temperature, humidity, carbon dioxide, and ammonia.The sensor involved in this paper is a temperature and humidity sensor.The temperature and humidity sensor used in this paper is TH10S-B-H, the temperature acquisition range is -40~120 ℃, the humidity acquisition range is 0~100% RH, the temperature accuracy is 0.1 ℃, the humidity accuracy is 0.1 RH, the temperature error is ± 0.2 ℃, and the humidity error is ±2% RH.

Experimental Site Setting
Figure 10 shows the cross-section of the experimental site.The fans and the wet curtains are located on opposite sides of the breeding house.There are 4 heaters, 2 collection nodes, and 2 vents in the farm.The controller is fixed on the outside of the wall of the breeding house.Two humidifiers and dehumidifiers are located near the middle of the breeding house.Below the pigsty is the manure removal area.When the fan is running, the outdoor air enters the room through the wet curtain and is sent to the breeding area through the air inlet.The indoor air is sent to the outside through the fan.
The air intake is located in the ceiling of the pigsty, allowing the air to disperse obliquely into the living area.The study by Hao Li et al. [20] proved that the convective heat transfer coefficient of the pigs in pens with the downward inlet was, on average, 60.4% higher than those with the upward inlet.The acquisition node includes multiple sensors: temperature, humidity, carbon dioxide, and ammonia.The sensor involved in this paper is a temperature and humidity sensor.The temperature and humidity sensor used in this paper is TH10S-B-H, the temperature acquisition range is −40~120 • C, the humidity acquisition range is 0~100% RH, the temperature accuracy is 0.1 • C, the humidity accuracy is 0.1 RH, the temperature error is ± 0.2 • C, and the humidity error is ±2% RH.

Experimental Site Setting
Figure 10 shows the cross-section of the experimental site.The fans and the wet curtains are located on opposite sides of the breeding house.There are 4 heaters, 2 collection nodes, and 2 vents in the farm.The controller is fixed on the outside of the wall of the breeding house.Two humidifiers and dehumidifiers are located near the middle of the breeding house.Below the pigsty is the manure removal area.When the fan is running, the outdoor air enters the room through the wet curtain and is sent to the breeding area through the air inlet.The indoor air is sent to the outside through the fan.
The air intake is located in the ceiling of the pigsty, allowing the air to disperse obliquely into the living area.The study by Hao Li et al. [20] proved that the convective heat transfer coefficient of the pigs in pens with the downward inlet was, on average, 60.4% higher than those with the upward inlet.

Explanation of Relevant Experimental Data
The total duration of the experiment was 6 months.The historical data were mainly collected in the first five months to adjust the superparameters of the GRU model.These data include indoor temperature, indoor humidity, outdoor temperature, outdoor humidity, outdoor air pressure, outdoor wind direction, and outdoor wind speed.The interval between two adjacent data is 5 min.
When correcting the abnormal data, we set the parameter n in formula (1) to 6 because the temperature of the pigsty will not change much in half an hour.
In the following month, the experiment of adjusting indoor temperature and humidity was carried out.Each prediction of the GRU model predicts the curve of temperature and humidity in the next 24 h (in Section 4.2, we will use experiments to explain why it is 24 h).When calculating the output power of the related equipment, we set the parameter DA in formulas ( 5), ( 6), (8), and (9) to 5 min, the Duration in formulas ( 11), ( 12), (13), and (14) to 10 s, and the threshold H of 2.4 sections to 0.5 °C/1% (temperature/humidity).In other words, in each process of adjusting temperature and humidity, the total time of macro-adjustment is 5 min.The micro-adjustment mode will be entered after 5 min.If the difference between the indoor temperature/humidity and the target temperature/humidity is greater than 0.5/1%, the controller will run for 10 s according to the output power calculated by the fuzzy control algorithm.Then, check whether the indoor temperature/humidity returns to the target temperature/humidity.If the difference between the indoor temperature/humidity and the target temperature/humidity is still greater than 0.5/1%, the controller will recalculate the output power of the equipment according to the fuzzy control algorithm and continue to run for 10 s.Repeat this process until the difference between the indoor temperature/humidity and the target temperature/humidity is less than 0.5/1%.Each time a regulation process is completed, the GRU model re-predicts the temperature/humidity curve in the next 24 h to prepare for the next adjustment.
In addition, the GRU model is not static.Every 24 h, the cloud platform retrains the GRU model based on historical data from the last 3 months.

Explanation of Relevant Experimental Data
The total duration of the experiment was 6 months.The historical data were mainly collected in the first five months to adjust the superparameters of the GRU model.These data include indoor temperature, indoor humidity, outdoor temperature, outdoor humidity, outdoor air pressure, outdoor wind direction, and outdoor wind speed.The interval between two adjacent data is 5 min.
When correcting the abnormal data, we set the parameter n in formula (1) to 6 because the temperature of the pigsty will not change much in half an hour.
In the following month, the experiment of adjusting indoor temperature and humidity was carried out.Each prediction of the GRU model predicts the curve of temperature and humidity in the next 24 h (in Section 4.2, we will use experiments to explain why it is 24 h).When calculating the output power of the related equipment, we set the parameter DA in formulas ( 5), ( 6), (8), and (9) to 5 min, the Duration in formulas ( 11), ( 12), (13), and (14) to 10 s, and the threshold H of 2.4 sections to 0.5 • C/1% (temperature/humidity).In other words, in each process of adjusting temperature and humidity, the total time of macroadjustment is 5 min.The micro-adjustment mode will be entered after 5 min.If the difference between the indoor temperature/humidity and the target temperature/humidity is greater than 0.5/1%, the controller will run for 10 s according to the output power calculated by the fuzzy control algorithm.Then, check whether the indoor temperature/humidity returns to the target temperature/humidity.If the difference between the indoor temperature/humidity and the target temperature/humidity is still greater than 0.5/1%, the controller will recalculate the output power of the equipment according to the fuzzy control algorithm and continue to run for 10 s.Repeat this process until the difference between the indoor temperature/humidity and the target temperature/humidity is less than 0.5/1%.Each time a regulation process is completed, the GRU model re-predicts the temperature/humidity curve in the next 24 h to prepare for the next adjustment.
In addition, the GRU model is not static.Every 24 h, the cloud platform retrains the GRU model based on historical data from the last 3 months.

Analysis of Experimental Results
This section provides a detailed analysis of the experimental results of the key steps, including the detection of abnormal data, the prediction results of the GRU model, and the comparison with the adjustment effect of the threshold-based controller.

Detection of Abnormal Data
We conducted 9000 anomaly detection experiments in the TensorFlow environment.In order to simulate scenarios with different proportions of abnormal data, we inserted different proportions of outliers into the historical data.
Table 2 shows the detection results of the isolation forest algorithm.We can see that when the proportion of outliers is less than or equal to 1%, the detection accuracy of temperature and humidity is almost 100%.When the proportion of abnormal values is less than or equal to 5%, the detection accuracy of temperature and humidity can still remain above 95%.However, in contrast, the accuracy of humidity dropped significantly.When the proportion of outliers is less than or equal to 10%, the anomaly detection accuracy of temperature and humidity drops below 90%.In the actual process of temperature and humidity adjustment in pig houses, the abnormal rate of data collected by sensors is basically below 1%.Therefore, the experimental results of the isolation forest algorithm meet the expectations, and the next steps can be carried out on this basis.

Prediction Results of the GRU Model
We trained the GRU model with 3 consecutive months of historical data and used the GRU model to predict the temperature and humidity of the next month.
Figures 11 and 12 show the predicted results of temperature and humidity for 30 consecutive days.As can be seen from Figures 11a and 12a, the predicted values of temperature and humidity are basically consistent with the actual values.From Figures 11b and 12b, we find that with the passage of time, the MSE between the predicted value of temperature and humidity and the actual value shows an increasing trend.For the first 1 day, the MSE for temperature was kept below 0.025, and the error for humidity was kept below 0.3.After more than one day, the mean square error of temperature exceeds 0.025.After more than 5 days, the error of temperature and humidity has changed greatly, and the error gradually becomes larger.
Table 3 shows the maximum error of temperature and humidity in different time periods.It can be seen from the table that the maximum error of temperature and humidity gradually increases with the passage of time.On the first day, the maximum error in temperature and humidity was the smallest.From day 1 to day 5, the maximum error in temperature nearly doubled, and humidity remained the same.After the fifth day, the maximum error of temperature and humidity is more than two times that of the first day.Table 3 shows the maximum error of temperature and humidity in different time periods.It can be seen from the table that the maximum error of temperature and humidity gradually increases with the passage of time.On the first day, the maximum error in temperature and humidity was the smallest.From day 1 to day 5, the maximum error in temperature nearly doubled, and humidity remained the same.After the fifth day, the maximum error of temperature and humidity is more than two times that of the first day.Based on the analysis of the above figures and tables, we found that the prediction results of the GRU model had the best accuracy on the first day.After more than one day, although the prediction results of the GRU model can still maintain good accuracy, the Table 3 shows the maximum error of temperature and humidity in different time periods.It can be seen from the table that the maximum error of temperature and humidity gradually increases with the passage of time.On the first day, the maximum error in temperature and humidity was the smallest.From day 1 to day 5, the maximum error in temperature nearly doubled, and humidity remained the same.After the fifth day, the maximum error of temperature and humidity is more than two times that of the first day.Based on the analysis of the above figures and tables, we found that the prediction results of the GRU model had the best accuracy on the first day.After more than one day, although the prediction results of the GRU model can still maintain good accuracy, the Based on the analysis of the above figures and tables, we found that the prediction results of the GRU model had the best accuracy on the first day.After more than one day, although the prediction results of the GRU model can still maintain good accuracy, the error increases geometrically compared to the first day.The reason is that for time series data, the data at a certain moment has the strongest correlation with the data at its adjacent moments, and the longer the time distance, the weaker the correlation, and even the correlation between each other can be ignored.From the perspective of time distance, the first day is closest to the training data set of the GRU model, so the accuracy of the prediction results is the highest.The farther the other time is from the training data set of the GRU model, the lower the accuracy of the prediction results.
Therefore, in order to ensure the accuracy of the prediction results of the GRU model, we recommend retraining the GRU model every 24 h.In this way, the temperature error can be kept below 0.4 • C, and the humidity error can be kept below 3%.

Comparison with Threshold-Based Controller
We replaced the controller of the system with the threshold-based controller designed by Qing Du et al. [6] and carried out a one-month experiment.

Evaluation Indicators
We use the length of time that the indoor temperature is in an abnormal state every day to measure the system's ability to avoid abnormal temperatures.
where Total represents the length of the day when the indoor temperature or humidity is in abnormal states; n represents the total number of temperature or humidity anomalies per day; E i and S i represent the end time and start time of the i-th temperature or humidity anomaly, respectively.

Evaluation of the Adjustment Effect
Figure 13 shows the adjustment effect of the two controllers.From the picture, we can see that under the adjustment of the threshold-based controller, the room temperature is abnormal for 20~30 min every day, and our controller reduces it to less than 5 min.However, our expectation is to completely eliminate the temperature anomaly, and the experimental results are not consistent with our expectations.Next, we analyze the regulation process of the controller and find out the reason why the temperature anomaly is not completely eliminated.We find that the temperature may be in an abnormal state at the beginning of each temperature adjustment.Figure 14 shows a complete cooling process.In the previous minute, the room temperature was abnormal.The reason for this phenomenon is that when training the GRU model, we did not consider the effect of the damp and heat produced by the pigs on the indoor temperature.In the process of cooling, pigs will continue to release heat to the outside world, so the indoor temperature is briefly above the high-temperature threshold at the beginning of the operation of the equipment.As a result, the five-minute macro adjustment mode is unable to restore the room temperature to the target temperature.However, in the following micro-adjustment mode, the controller will restore the indoor temperature to an acceptable range; that is, the difference between the indoor temperature and the target temperature is within our preset threshold of 0.5 • C.

Conclusions
This paper designs and implements an improved intelligent control system for the temperature and humidity of a piggery, which mainly includes data preprocessing, training a GRU model, macro-adjustment, micro-adjustment, and other modules.In the data preprocessing module, we use the isolated forest algorithm to detect abnormal data with an accuracy of more than 99%.Before training the GRU model, we adjusted the important parameters of the model, which greatly improved the efficiency and accuracy of the

Conclusions
This paper designs and implements an improved intelligent control system for the temperature and humidity of a piggery, which mainly includes data preprocessing, training a GRU model, macro-adjustment, micro-adjustment, and other modules.In the data preprocessing module, we use the isolated forest algorithm to detect abnormal data with an accuracy of more than 99%.Before training the GRU model, we adjusted the important parameters of the model, which greatly improved the efficiency and accuracy of the training model.In the terminal controller module, we combined the prediction results of the GRU model with the fuzzy control algorithm to eliminate the influence of humidity and heat generated by the pigs and other factors on the temperature in the piggery and achieved a good regulation effect.
Compared with the threshold-based controller, our controller reduces the abnormal temperature in the pigsty by about 90%.The deficiency is that the zero anomalies of temperature and humidity cannot be realized.Another disadvantage is that the adjustment effect of the system is very dependent on historical data, and the adequacy of historical data directly determines the prediction accuracy of the GRU model.
In a word, the adjustment effect of the system has basically reached our expected effect.It is a useful tool for regulating the temperature and humidity in a piggery.

Figure 1 .
Figure 1.The flow chart of temperature and humidity regulation process includes four steps: training GRU model, formulating macro-adjustment strategies, formulating micro-adjustment strategies, and balance controller.

Figure 4 .
Figure 4. Parameter epoch adjustment experiment.The X-axis represents the value of epoch, and the Y-axis represents the mean square error.

Figure 4 .
Figure 4. Parameter epoch adjustment experiment.The X-axis represents the value of epoch, and the Y-axis represents the mean square error.

Figure 5 .
Figure 5. Flow chart of macroscopic regulation of indoor temperature.

Figure 5 .
Figure 5. Flow chart of macroscopic regulation of indoor temperature.

Figure 6 .
Figure 6.Flow chart of microcosmic regulation of room temperature.

Figure 6 .
Figure 6.Flow chart of microcosmic regulation of room temperature.

Figure 7 .
Figure 7. Internal structure of fuzzy controller.

Figure 7 .
Figure 7. Internal structure of fuzzy controller.

Figure 8 .
Figure 8. System framework.The framework of the system is mainly divided into two parts: cloud platform and terminal equipment.

Figure 8 .
Figure 8. System framework.The framework of the system is mainly divided into two parts: cloud platform and terminal equipment.

Figure 9 .
Figure 9.The shape of the controller and the acquisition node.Figure (a) is the controller, figure (b) is the acquisition node.

Figure 9 .
Figure 9.The shape of the controller and the acquisition node.Figure (a) is the controller, figure (b) is the acquisition node.

Figure 10 .
Figure 10.Cross-sectional view of experimental site.

Figure 10 .
Figure 10.Cross-sectional view of experimental site.

Figure 11 .Figure 12 .
Figure 11.Predicted results of temperature for 30 consecutive days.Figure (a) is a graph of the actual temperature and the predicted temperature, and Figure (b) is the mean square error of the actual temperature and the predicted temperature.

Figure 11 .Figure 11 .Figure 12 .
Figure 11.Predicted results of temperature for 30 consecutive days.Figure (a) is a graph of the actual temperature and the predicted temperature, and Figure (b) is the mean square error of the actual temperature and the predicted temperature.

Figure 12 .
Figure 12.Predicted results of humidity for 30 consecutive days.Figure (a) is a graph of actual humidity and predicted humidity, and Figure (b) is the mean square error of actual humidity and predicted humidity.

Figure 13 .
Figure 13.Comparison of the adjustment effect.The X-axis represents the date, and the Y-axis represents the total amount of time that the temperature is abnormal each day.

Figure 13 .
Figure 13.Comparison of the adjustment effect.The X-axis represents the date, and the Y-axis represents the total amount of time that the temperature is abnormal each day.

Figure 13 .
Figure 13.Comparison of the adjustment effect.The X-axis represents the date, and the Y-axis represents the total amount of time that the temperature is abnormal each day.

Figure 14 .
Figure 14.A complete cooling process.The controller reduces the indoor temperature from 22 °C to 20.2 °C in 6 min and stores the indoor temperature every 30 s.

Figure 14 .
Figure 14.A complete cooling process.The controller reduces the indoor temperature from 22 • C to 20.2 • C in 6 min and stores the indoor temperature every 30 s.

Table 1 .
Fuzzy sets are divided according to the relationship between e and H.

Table 1 .
Fuzzy sets are divided according to the relationship between e and H.

Table 2 .
The average value of outlier detection results for three different scales, each scale carried out 3000 experiments.

Table 3 .
The maximum error of temperature and humidity in different time periods.

Table 3 .
The maximum error of temperature and humidity in different time periods.