A Context-Recognition-Aided PDR Localization Method Based on the Hidden Markov Model

Indoor positioning has recently become an important field of interest because global navigation satellite systems (GNSS) are usually unavailable in indoor environments. Pedestrian dead reckoning (PDR) is a promising localization technique for indoor environments since it can be implemented on widely used smartphones equipped with low cost inertial sensors. However, the PDR localization severely suffers from the accumulation of positioning errors, and other external calibration sources should be used. In this paper, a context-recognition-aided PDR localization model is proposed to calibrate PDR. The context is detected by employing particular human actions or characteristic objects and it is matched to the context pre-stored offline in the database to get the pedestrian’s location. The Hidden Markov Model (HMM) and Recursive Viterbi Algorithm are used to do the matching, which reduces the time complexity and saves the storage. In addition, the authors design the turn detection algorithm and take the context of corner as an example to illustrate and verify the proposed model. The experimental results show that the proposed localization method can fix the pedestrian’s starting point quickly and improves the positioning accuracy of PDR by 40.56% at most with perfect stability and robustness at the same time.


Introduction
Nowadays, with the rapid development of computing technology, the demand for location based services (LBS) is rapidly increasing [1]. Global navigation satellite systems (GNSS) have been successfully used for outdoor scenarios; however, it is difficult to use it indoors because of signal attenuation [2].
Recently, various novel indoor localization techniques have been proposed, such as infrared light, Bluetooth, ultrasound, wireless local area networks (WLAN) [3], micro-electro-mechanical system (MEMS) and cellular network [4]. Among these methods, techniques based on smartphone sensors have attracted much more attention because of the popularity of mobile phones [5]. However, some of them require additional infrastructures such as access points (AP) and base stations. Thus, in this paper, we mainly concentrate on Personal Dead-reckoning (PDR), in which only the inertial sensor of the phone is used [6]. This relative localization method measures and tracks the momentary location and trajectory of a walking person dependently using the smartphone without any external sensors. Unfortunately, PDR's main problem lies in the fact that the positioning errors will accumulate over time very quickly due to the drift caused by noise, especially for the low-cost and low-performance sensors used in smartphones.
Different solutions can be used to eliminate the positioning errors in PDR: (1) an improved PDR algorithm, which makes the step detection, estimation of stride length and heading more

The Structure of Context-Recognition-Aided PDR Localization Method Based on HMM
The structure of context-recognition-aided PDR localization method based on HMM is shown in Figure 1, and is mainly divided into three parts: PDR positioning, context recognition and the matching algorithm. Inertial sensors of smartphones, including accelerometer, gyroscope, and magnetic meter, are used in PDR to estimate the occurrence of steps, stride length and heading [5]. For each step, the user's position can be predicted by: calculated by the nonlinear model proposed in [6] using acceleration measured by the accelerometer. Moreover, θi is the heading of this step and considering the low accuracy of smartphone and the impact of various magnetic devices indoors, it is constrained to four directions [φ1,φ2,φ3,φ4] using Equation (2) proposed in [17] after the moving direction is measured by the gyroscope and the magnetic meter, as shown in Figure 2.  Based on this, position of the user will be updated after the detection of each step [18]. As mentioned above, an initial position is required at the beginning of the position estimation process, and calibration information is required to reduce error accumulation. In our method, the recognized context's position pre-stored in the database is employed to calibrate PDR using the HMM matching algorithm. Inertial sensors of smartphones, including accelerometer, gyroscope, and magnetic meter, are used in PDR to estimate the occurrence of steps, stride length and heading [5]. For each step, the user's position can be predicted by: calculated by the nonlinear model proposed in [6] using acceleration measured by the accelerometer. Moreover, θ i is the heading of this step and considering the low accuracy of smartphone and the impact of various magnetic devices indoors, it is constrained to four directions [φ 1 ,φ 2 ,φ 3 ,φ 4 ] using Equation (2) proposed in [17] after the moving direction is measured by the gyroscope and the magnetic meter, as shown in Figure 2.

The Structure of Context-Recognition-Aided PDR Localization Method Based on HMM
The structure of context-recognition-aided PDR localization method based on HMM is shown in Figure 1, and is mainly divided into three parts: PDR positioning, context recognition and the matching algorithm. Inertial sensors of smartphones, including accelerometer, gyroscope, and magnetic meter, are used in PDR to estimate the occurrence of steps, stride length and heading [5]. For each step, the user's position can be predicted by: calculated by the nonlinear model proposed in [6] using acceleration measured by the accelerometer. Moreover, θi is the heading of this step and considering the low accuracy of smartphone and the impact of various magnetic devices indoors, it is constrained to four directions [φ1,φ2,φ3,φ4] using Equation (2) proposed in [17] after the moving direction is measured by the gyroscope and the magnetic meter, as shown in Figure 2.  Based on this, position of the user will be updated after the detection of each step [18]. As mentioned above, an initial position is required at the beginning of the position estimation process, and calibration information is required to reduce error accumulation. In our method, the recognized context's position pre-stored in the database is employed to calibrate PDR using the HMM matching algorithm. Based on this, position of the user will be updated after the detection of each step [18]. As mentioned above, an initial position is required at the beginning of the position estimation process, and calibration information is required to reduce error accumulation. In our method, the recognized context's position pre-stored in the database is employed to calibrate PDR using the HMM matching algorithm.
In this paper, we define a characteristic scene as the context including its type and feature, where type can be corner, stairs, ramp etc. and the corresponding feature is the corner's orientation θ, the height of the stairs h and the orientation of the ramp δ, respectively. It should be noted that the contexts at different position with the same type and feature are considered as the different contexts. As we will show in Section 3, these contexts can be detected using sensors mounted on the smartphone.
For a specific environment, all contexts s can be prior surveyed offline and stored in a set S = {s 1 , . . . , s k , . . . , s N }, where N is the total number of contexts in this environment. The position of every context s is pre-stored in a database.
During a practical positioning phase, the contexts a pedestrian passed form a context time series . . s t P which is arranged chronologically, where s t i ∈ S and t i is the time index when the pedestrian passed the context s t i . This time series S satisfies the Markov property: that is, the current context s t i is independent of all the contexts prior to s t i−1 . However, as the pedestrian walks, the contexts we detected online form an observed context time series where o t i is the detected event containing the type and feature of a context and t i is the time index when context o t i is recognized. It should be noted that the length of O may be different from the length of the theoretical sequence S because of misses and false detections during context recognition. For example, we define the orientation of a corner as the pedestrian's heading after making a turn around a corner. As for the map shown in Figure 3, the black arrows represent corresponding corner's orientation, if a person walks in accordance with 1-2-3-4 or 1-2-5-6 like the brown line. S = {(corner1,south), (corner2,east), (corner3,north), (corner4,west), (corner5,north), (corner6,west)}. If the pedestrian walks along with , corner4, west)), but if corner2 was undetected and other corners' orientations are detected correctly, O = (o t 1 , o t 2 , o t 3 ) = ((corner, south) , (corner, north) , (corner, west)).
Sensors 2016, 16, 2030 4 of 20 In this paper, we define a characteristic scene as the context including its type and feature, where type can be corner, stairs, ramp etc. and the corresponding feature is the corner's orientation θ, the height of the stairs h and the orientation of the ramp δ, respectively. It should be noted that the contexts at different position with the same type and feature are considered as the different contexts. As we will show in Section 3, these contexts can be detected using sensors mounted on the smartphone.
For a specific environment, all contexts s can be prior surveyed offline and stored in a set  If we can match O to S, we will know the pedestrian's real trajectory and thus get the position pre-stored in the database, which can be used to calibrate PDR directly. In view of the Markov property of S, we use the HMM matching algorithm to match via the joint probability distribution of If we can match O to S, we will know the pedestrian's real trajectory and thus get the position pre-stored in the database, which can be used to calibrate PDR directly. In view of the Markov property of S, we use the HMM matching algorithm to match via the joint probability distribution of the sequence, in which the distance information calculated by PDR is also the key information, which will be explained in section 4. In this paper, we will take the corner as the example to illustrate the proposed model and algorithm. To summarize, the context-recognition-aided PDR localization method based on HMM can realize the PDR correction and inhibit the accumulation of positioning errors.

Context Recognition
As the aided approach in the proposed method, context recognition is the premise of the matching algorithm. There are some previous works in action detection to recognize many different contexts [6,[19][20][21], which analyze the signals of an accelerometer placed at different locations on the body to extract some discriminant characteristics of the time-domain or frequency-domain or its distribution by applying wavelet analysis, particle filters and other signal processing methods based on signal features [22]. Similarly, the contexts of stairs, ramps, and elevators can be distinguished by establishing the detection model of height and direction after training, evaluation and analysis using the samples from the pressure meters and the magnetometers in smartphones [6,[23][24][25]. For example, the pressure changes obviously and quickly in a short time if a person takes a lift to go up and down, compared to the obvious but slow change when they walk up and down the stairs. Moreover, if the smartphone is mounted on the pedestrian's foot in the same way shown in [6], steep ramps can be detected by foot's angle of inclination and the slow change of pressure. In addition, computer vision technology, which detects the pedestrian's motion image or characteristic objects in the surrounding environment as evidence of human posture or characteristic position [26,27] by extracting the key frames of user's life videos obtained by the wearable device, is a paramount way for context recognition [28].
In our paper, we present a turn detection method to recognize the context of corners to correct the estimated position of a person. Studies find that the action of turning with respect to walking straight has characteristic features, so the correctness of turn detection is very high. At the same time, corners are common indoors, which is conducive to matching the pedestrian's current position to a corner in the database.
When the pedestrian turns, the angular velocity undergoes a severe change compared with the normal walking process whose angular velocity is around 0. A random sample of the original angular velocity of one experimental subject is the blue line shown in Figure 4. the sequence, in which the distance information calculated by PDR is also the key information, which will be explained in section 4. In this paper, we will take the corner as the example to illustrate the proposed model and algorithm. To summarize, the context-recognition-aided PDR localization method based on HMM can realize the PDR correction and inhibit the accumulation of positioning errors.

Context Recognition
As the aided approach in the proposed method, context recognition is the premise of the matching algorithm. There are some previous works in action detection to recognize many different contexts [6,[19][20][21], which analyze the signals of an accelerometer placed at different locations on the body to extract some discriminant characteristics of the time-domain or frequency-domain or its distribution by applying wavelet analysis, particle filters and other signal processing methods based on signal features [22]. Similarly, the contexts of stairs, ramps, and elevators can be distinguished by establishing the detection model of height and direction after training, evaluation and analysis using the samples from the pressure meters and the magnetometers in smartphones [6,[23][24][25]. For example, the pressure changes obviously and quickly in a short time if a person takes a lift to go up and down, compared to the obvious but slow change when they walk up and down the stairs. Moreover, if the smartphone is mounted on the pedestrian's foot in the same way shown in [6], steep ramps can be detected by foot's angle of inclination and the slow change of pressure. In addition, computer vision technology, which detects the pedestrian's motion image or characteristic objects in the surrounding environment as evidence of human posture or characteristic position [26,27] by extracting the key frames of user's life videos obtained by the wearable device, is a paramount way for context recognition [28].
In our paper, we present a turn detection method to recognize the context of corners to correct the estimated position of a person. Studies find that the action of turning with respect to walking straight has characteristic features, so the correctness of turn detection is very high. At the same time, corners are common indoors, which is conducive to matching the pedestrian's current position to a corner in the database.
When the pedestrian turns, the angular velocity undergoes a severe change compared with the normal walking process whose angular velocity is around 0. A random sample of the original angular velocity of one experimental subject is the blue line shown in Figure 4. However, sometimes the change is not continuous as in the course of turns such as the 10th, 11th and 18th changes which are circled in the figure, so the corners could be recognized using the angular velocity within the time window. Meanwhile, the turn direction (left or right) can be tested depending on the sign (positive or negative) of the angular velocity if the mobile's position is known. Figure 5 plots a smartphone's position and its coordinate system, so the angular velocity  plots a smartphone's position and its coordinate system, so the angular velocity around the X-axis w x changes violently when turn happens, and w x is negative if turn left, and vice versa. The flow chart of the turn detection is presented in Figure 6. In Figure 6, th represents the angular velocity threshold which is a positive number, and "Symbol" stands for the turn symbol during the process of turning, which is 1 if turning right, and −1 if turning left. The choice of th is dependent on the statistical analysis of angular velocity collected by the XiaoMi 3 smartphone (XiaoMi, Beijing, China) after we turned 840 times with an angle of ±90° while walking straight. The mean value, variance and probability density function (PDF) are shown in Table 1 and Figure 7. The parameters of the sensors on the XiaoMi 3 are shown In Figure 6, th represents the angular velocity threshold which is a positive number, and "Symbol" stands for the turn symbol during the process of turning, which is 1 if turning right, and −1 if turning left. The choice of th is dependent on the statistical analysis of angular velocity collected by the XiaoMi 3 smartphone (XiaoMi, Beijing, China) after we turned 840 times with an angle of ±90° while walking straight. The mean value, variance and probability density function (PDF) are shown in Table 1 and Figure 7. The parameters of the sensors on the XiaoMi 3 are shown In Figure 6, th represents the angular velocity threshold which is a positive number, and "Symbol" stands for the turn symbol during the process of turning, which is 1 if turning right, and −1 if turning left. The choice of th is dependent on the statistical analysis of angular velocity collected by the XiaoMi 3 smartphone (XiaoMi, Beijing, China) after we turned 840 times with an angle of ±90 • while walking straight. The mean value, variance and probability density function (PDF) are shown in Table 1 and Figure 7. The parameters of the sensors on the XiaoMi 3 are shown in Table 2 [29,30]. It needs to be explained that the orientation sensor measuring the heading is not a real sensor but rather a software sensor which gets its values from combining accelerometer and magnetic field values and applying certain calculations [31]. in Table 2 [29,30]. It needs to be explained that the orientation sensor measuring the heading is not a real sensor but rather a software sensor which gets its values from combining accelerometer and magnetic field values and applying certain calculations [31].   The result indicates that 1 is a rational threshold for judging turning right and turning left, respectively, because it can detect the turn actions correctly and distinguish them from walking straight. To verify the proposed turn detection scheme, we executed turn tests containing turning left and turning right around a 90°corner during the normal walking process among 10 adults aged 23-25 years old for a total number of 100 tests. The experimental results whose percentage of correct detection is 100% demonstrate that the proposed detection scheme guarantees the recognition of corners. The detected result is the red line in Figure 4. In addition, the heading information after the turn process represents the corner's orientation. However, there are some limitations of our corner recognition method. For example, the mobile device must be fixed on pedestrian's body so that the absolute value of the angular velocity when turning is much greater than that while going straight. At the same time, the device's orientation with respect to the body has to be known, thus the measured heading can be used to match the exact corner in later steps. Secondly, pedestrians are not allowed to turn randomly except for the corners because we assume the pedestrian is located at a corner when a turn action is detected in our algorithm. At last, the time window will lead to the delay of deciding the end of a turn.
The result indicates that 1 is a rational threshold for judging turning right and turning left, respectively, because it can detect the turn actions correctly and distinguish them from walking straight. To verify the proposed turn detection scheme, we executed turn tests containing turning left and turning right around a 90 • corner during the normal walking process among 10 adults aged 23-25 years old for a total number of 100 tests. The experimental results whose percentage of correct detection is 100% demonstrate that the proposed detection scheme guarantees the recognition of corners. The detected result is the red line in Figure 4. In addition, the heading information after the turn process represents the corner's orientation. However, there are some limitations of our corner recognition method. For example, the mobile device must be fixed on pedestrian's body so that the absolute value of the angular velocity when turning is much greater than that while going straight. At the same time, the device's orientation with respect to the body has to be known, thus the measured heading can be used to match the exact corner in later steps. Secondly, pedestrians are not allowed to turn randomly except for the corners because we assume the pedestrian is located at a corner when a turn action is detected in our algorithm. At last, the time window will lead to the delay of deciding the end of a turn.
Based on this, using the corner recognition algorithm, we can match pedestrian's location to the corners with the same orientation in the database so as to get user's position when a turn occurs. However, different contexts may have the same features in complex situations and context recognition error exist, which lead to the mismatches in traditional map matching systems. To solve these problems, this paper puts forward the HMM matching algorithm to match the right context and definitely determine the pedestrian's position.

HMM Matching Algorithm
The matching algorithm based on the Hidden Markov Model (HMM) operates by matching the context information recognized online to the context pre-stored offline in the database. HMM is a statistical model [32], as shown in Figure 8. It is a ubiquitous tool for describing the probability distribution of an observable state sequence O = o t 1 , o t 2 . . . o t Q measured by sensors and the hidden state sequence S = s t 1 , . . . s t i . . . s t P which cannot be observed directly. Transitions between hidden states are governed by a transition probability a ij in A, while the probability of the observable state o k generated by hidden state s j can be described by the emission probability b jk in B. The target of HMM matching algorithm is to find out the real sequence of hidden states S given the sequence of observable states O. Based on this, using the corner recognition algorithm, we can match pedestrian's location to the corners with the same orientation in the database so as to get user's position when a turn occurs. However, different contexts may have the same features in complex situations and context recognition error exist, which lead to the mismatches in traditional map matching systems. To solve these problems, this paper puts forward the HMM matching algorithm to match the right context and definitely determine the pedestrian's position.

HMM Matching Algorithm
The matching algorithm based on the Hidden Markov Model (HMM) operates by matching the context information recognized online to the context pre-stored offline in the database. HMM is a statistical model [32], as shown in Figure 8. It is a ubiquitous tool for describing the probability distribution of an observable state sequence  

Transition probability matrix
Emission probability matrix

The HMM Matching Algorithm Model
The HMM matching algorithm model can be described with five elements [33], λ = [S,O,π,A,B] , which include two state sets and three probability matrixes. In this subsection, we take the corner as the example to illustrate the specific implication of these elements in the proposed method.

The HMM Matching Algorithm Model
The HMM matching algorithm model can be described with five elements [33], λ = [S,O,π,A,B], which include two state sets and three probability matrixes. In this subsection, we take the corner as the example to illustrate the specific implication of these elements in the proposed method. is composed of all possible observed state o and o is a context detection event that can be observed directly. Taking the corner as an example, o includes the detected corner and its orientation. The orientation of a corner has been illustrated in Section 2. Meanwhile, we define the orientation of the room as the heading after the pedestrian enters this room and the corridor's orientation may be east or west, according to the various walking routes by definition, as shown in Figure 9. Thus, the measured heading can decide whether the pedestrian is walking into or out of a room if we ignore one's turn actions in the room. From the above definition, a subset of corners can be matched by each turn action and its measured information.   Meanwhile, we define the orientation of the room as the heading after the pedestrian enters this room and the corridor's orientation may be east or west, according to the various walking routes by definition, as shown in Figure 9. Thus, the measured heading can decide whether the pedestrian is walking into or out of a room if we ignore one's turn actions in the room. From the above definition, a subset of corners can be matched by each turn action and its measured information.
3. Initial state probability matrix π π expresses the probability distribution of hidden states at the initial time t 1 . Supposing that the hidden state set is S = {s 1 , . . . , s k , . . . , s N }, π can be described as π = [p 1 , . . . , p k , . . . , p N ], in which p i ≥ 0 and N ∑ i=1 p i = 1. In the case of unknown starting point, the probability of every context is equal, i.e.,

Transition probability matrix A
A shows the transition probabilities among any two hidden states in HMM, where a ij = P(s j |s i ) means the probability that the state is s j at time t j under the condition of the state being s i at time t i (i < j). The transition probability satisfies a ij ≥ 0 and N ∑ j=1 a ij = 1, 1 ≤ i ≤ N.
In theory, the transition probability matrix is A shown as below if the map is Figure 3.
In practice, however, we should take into account of the corner recognition error to determine a ij . False detection of turn occurs easily in the vicinity of the angular velocity threshold which is measured by the gyroscope. Thus, the undetected rate of the turn is: where ∆ω is the maximal error of gyroscopes measured by large number of statistical experiments.
In this paper, we ignore the false alarms while walking on the straight paths, because the angular velocity is far less than the threshold in these cases. Afterwards, the relationship of any two hidden states can be expressed by three types: single-hop, multi-hop and self-hop. Single-hop means that the theoretical transition probability of two hidden states s i and s j is not 0, like 1-2 or 2-3 in Figure 3. Multi-hop indicates the miss detection must happen between two hidden states like 1-3 or 2-6, and self-hop means the hidden states are same at two continuous time point like 1-1 or 2-2. So, the practical transition probability is divided into three conditions. The single-hop's transition probability is: For the multi-hop, we assume the number of undetected corner is g, so its transition probability is: Then, the self-hop's transition probability is:

Emission probability matrix B
Emission probability b jk , which indicates the probability that the hidden state s j performs as the observable state o k , satisfies b jk ≥ 0. When we calculate B, it is necessary to consider with the probability distribution of the measurement errors. Next, we take the corner recognition for example to explain the computation of B.
If we assume that the maximal error of heading is ∆θ, it is obvious that the corner's orientation may be constrained wrongly when (φ i + 45 according to the PDR heading optimization algorithm mentioned in Section 2. Therefore, the orientation's error rate is: If the contexts s j pre-stored in the database have the same orientation with the context o k recognized online, b jk is: Conversely, if their orientation is different, b jk is: For example, in Figure 3, if {o 1 , o 2 , o 3 , o 4 } = {(corner1,north) (corner1,south), (corner1,west), (corner1,east)}, the emission probability matrix B connecting hidden states {s 1 , s 2 , s 3 , s 4 , s 5 , s 6 } = (corner1,south), (corner2,east), (corner3,north), (corner4,west), (corner5,north), (corner6,west)} is: Then, we can move on to the matching algorithm by the five elements mentioned above.

Matching Procedure Based on HMM
The basic problem solved by HMM matching algorithm is to determine the optimal hidden state sequence S * = s * t 1 . . . s * t i . . . s * t Q , according to a specific measured observable state sequence where S e = s e t 1 . . . s e t i . . . s e t Q is composed by random permutation using the contexts from S in the database: The length of S * may be shorter than the length of real hidden state sequence S = s t 1 . . . s t i . . . s t P because of miss detection of some contexts, but S * can represent S to some extent, where t i is the time index the pedestrian passed the context s t i . In addition, the distance between any two continuous observed states is also the key information that can be used in our proposed model as shown in Figure 1. We model cumulative errors of PDR, which is represented by In this way, the optimal sequence S * can be obtained by the five elements defined in Section 4.1. In our paper, we use the Viterbi algorithm to solve this issue [34,35]. At present, the Viterbi algorithm has two types: method of exhaustion and recursive algorithm [36]. Considering the high efficiency of the recursive algorithm mentioned in [37], we use the recursive algorithm in the proposed method.
At t 1 , for any possible hidden state s e t 1 P(s e t 1 , o m t 1 |λ ) = π(s e t 1 ) × b e t 1 m t 1 (15) where s e t 1 ∈ S, 1 ≤ e t 1 ≤ N. From t 2 , the recursive algorithm only needs to find the sequence S e t k * with largest probability among all sequences S e t k with the destination s e t k at time t k , as the red line shown in Figure 10, where s e t k ∈ S, 1 ≤ e t k ≤ N.
The probability P(S e t k * , O |λ ) is called the partial probability selected among probabilities calculated by Equation (14) and the optimal path reaches s e t k is named as the optimal route pointer ϕ(s e t k ) [33]: ϕ(s e t k ) = S e t k * = argmax S e t k P(S e t k , O |λ ) (17) where , ... Therefore, from t2, once recognizing a context, we will obtain the N most possible sequences , since the total number of hidden states is N. In this way, the algorithm is not restarted every time a measurement is received. Conversely, the paths and their associated probabilities from a previous iteration serve as input to the current iteration, along with the new measurements [37].
Last but not least, we need to verify which sequence is the pedestrian's real track * S among these N sequences in descending order, and pick the top two probabilities Pmax1 and Pmax2 as the candidate matching result. The metric for matching successfully is that the distinguished ratio Pmax1/Pmax2 has to exceed the threshold thp. If it is unable to reach the threshold, known as mismatch, it indicates that the result has a high probability of being false, so we do not determine the matching context and retain the current probabilities Therefore, from t 2 , once recognizing a context, we will obtain the N most possible sequences ϕ(s e t k ), 1 ≤ e t k ≤ N, since the total number of hidden states is N. In this way, the algorithm is not restarted every time a measurement is received. Conversely, the paths and their associated probabilities from a previous iteration serve as input to the current iteration, along with the new measurements [37].
Last but not least, we need to verify which sequence is the pedestrian's real track S * among these N sequences {ϕ(s 1 ) . . . ϕ(s N )}. We sort the probabilities P(S e t k * , O |λ ) in descending order, and pick the top two probabilities P max1 and P max2 as the candidate matching result. The metric for matching successfully is that the distinguished ratio P max1 /P max2 has to exceed the threshold th p . If it is unable to reach the threshold, known as mismatch, it indicates that the result has a high probability of being false, so we do not determine the matching context and retain the current probabilities P(S e t k * , O |λ ) and paths ϕ(s e t k ), waiting for the next recognition of contexts to recalculate. In contrast, if the result satisfies the metric, we suggest that the matching context is credible, and the position pre-stored in database can be used as the reference to get the start position or calibrate PDR. Therefore, the determination of the threshold is very important because it is closely related to the accuracy of the result, which will be discussed in Section 5.
To sum up, the HMM matching algorithm can rectify accumulated errors in PDR on the basis of inferring the start position by the matching context after context recognition using the sensors' data collected by the smartphone, so long as the database is known.

Experiments and Discussion
In this section, we conducted experiments to evaluate the proposed context-recognition-aided localization method based on HMM. The remainder of this section is organized as follows: Section 5.1 tests the reasonable value of output threshold th p mentioned in Section 4 which is an important parameter that guarantee all the experiments go smoothly. Section 5.2 verifies that the proposed model can determine the start point and Section 5.3 shows the improvement of positioning accuracy of the proposed model. Finally, in last subsection, we analyze the robustness of the model.
The following performance results are based on the data collected from a XiaoMi 3 smartphone mounted on the experimenter's waist, as shown in Figure 5. Nearly 60 tests were performed by three students (with heights of 1.65 m, 1.7 m, 1.73 m) walking at a normal speed (1.1 m/s, 1.2 m/s, 1.2 m/s on average, respectively) in two environments. One is part of the parking garage with six corners in the Beijing New Technology Base of the Chinese Academy of Sciences, which is approximately a 35.07 m × 57.62 m area, as shown in Figure 3. The other is a test environment with seven available rooms on the 8th floor, which has an area of 54.95 m × 16.8 m, located in the main building of our workplace, Academy of Opto-Electronics, Chinese Academy of Sciences, as shown in Figure 9. In the parking garage, the experimenters walked straight along the path and do not turn, unless they wanted to turn around the corner as indicated by the brown line in Figure 3. And as for the experiments on the 8th floor, we walked straight along the corridor and turned 90 • towards to the door when we wanted to enter a room. After taking a few steps following the room's orientation, we turned 180 • and walked for several steps before turning 90 • to guarantee that we are walking along the corridor again. In Figure 9, the brown line shows the trajectory if the pedestrian's route is room6-room5.

Determination of Threshold in HMM Algorithm
The threshold th p in the HMM algorithm is an essential parameter that determines if the matched context is the right result. Instinctively, some sequences' probabilities may be larger than the probability of the real sequence, if their contexts or paths' features are similar. Therefore, th p should not be too small to avoiding misjudgments. On the contrary, if th p is too large, P max1 /P max2 cannot exceed to th p resulting in a mismatch, even if P max1 is the probability of the right result. Therefore, we need to testify this impact and select a rational value of th p , for the purpose of ensuring the correct and fast determination of the matching context.
First, the three students mentioned above did 15 experiments to test the correctness of different thresholds. We turned around just two corners during a normal walk in the parking garage performed seven times, whose routes are 1-2, 2-3, 2-5, 3-4, 4-1, 5-6 and 6-1. For the 8th floor, we only entered two rooms eight times, whose routes are room7-room6, room7-room5, room7-room4, room7-room3, room6-room5, room6-room4 room5-room4 and room5-room3. Figure 11 presents the matching results, where matching correctly means that the matched result is the correct corner or room where pedestrians passed; mismatch means no result outputs because the ratio P max1 /P max2 is not greater than th p ; matching wrongly means the matched corner or room is wrong. The histogram manifests that the wrong matching matter occurs if the threshold is relatively small because of the similarity of some paths. When the threshold value grows, the rate of matching wrongly reduces and the mismatch rate rises correspondingly because the probability ratio Pmax1/Pmax2 cannot reach that high. This result confirms the impact of thp mentioned at the start of this subsection.
In practice, the number of contexts is not limited, so we recorded another 15 experiments performed by three people who walked at a constant speed in two environments respectively and every experiment involved four corners (1-2-3-4, 2-3-4-1, 2-5-6-1, 3-4-1-2, 4-1-2-3, 4-1-2-5, 5-6-1-2, 6-1-2-3) or four rooms (room7-room6-room5-room4, room7-room5-room4-room3, room7-room4-room3-room2, room6-room5-room4-room3, room6-room4-room3-room2, room6-room3-room2-room1, room5-room3-room2-room1). We recorded the number of contexts which experimenters passed by until the result satisfies the output threshold, regardless of its correctness, i.e., the probabilities ratio of two candidate matching results Pmax1/Pmax2 is larger than thp. The average number of contexts is shown in Figure 12. We can see that the number of contexts may be larger than 2, because when a mismatch happens, the HMM matching algorithm retains the past paths and probabilities as the feasible paths and the initial probabilities for the next calculation. Although the selection of 1.05 needs the least number of contexts, it has the probability of matching wrongly as shown in Figure 11, which affects the positioning accuracy significantly. Therefore, 1.15 is appropriate to ensure the matching correctness on the basis of few numbers of contexts, so it should be chosen as the ratio threshold in HMM algorithm in the following experiments. We can see that the number of contexts may be larger than 2, because when a mismatch happens, the HMM matching algorithm retains the past paths and probabilities as the feasible paths and the initial probabilities for the next calculation. Although the selection of 1.05 needs the least number of contexts, it has the probability of matching wrongly as shown in Figure 11, which affects the positioning accuracy significantly. Therefore, 1.15 is appropriate to ensure the matching correctness on the basis of few numbers of contexts, so it should be chosen as the ratio threshold in HMM algorithm in the following experiments.

Determination of the Starting Point
PDR invariably assumes a known initial position, so it is not an independent system and has to be used along with external sensors. Our method, however, can quickly seek the starting position of pedestrians by identifying several contexts in the case of unknown origin.
In this subsection, we conducted 15 tests in the two environments, respectively, in the same way as the second set of experiments described in Section 5.1. Besides the routes mentioned above, we added eight routes (room7-room6-room5-room3, room7-room6-room5-room2, room7-room6-room5-room1, room7-room5-room4-room2, room6-room5-room4-room2, room6-room5-room3-room2, room6-room4-room3-room1, room5-room4-room3-room2) on the 8th floor and one route (6-1-2-5) in the parking garage where some routes were walked twice. Our mission is to see the correctness of the matching result and how long it takes before recognizing the starting point. The results are shown in Table 3, in which 'Average Number of Contexts' means the number of contexts we passed by until the result outputs and it can represent the required time before we find the starting point. From the table, the HMM algorithm can get the starting position precisely in all experiments and requires at least two contexts. Moreover, the average number of contexts shows that users can find the starting point in garage faster than the 8th floor, because the distance between every two contexts differs greatly in parking garage compared with the 8th floor arranged by rooms compactly. This kind of difference of distance results in the severe difference of probabilities of all possible sequences calculated by Equations (14) and (16), so it can decide the result more quickly. In a word, the proposed method based on HMM is a quick and effective way to find the starting point, whose matching accuracy and efficiency is high.

Localization Accuracy
In further moving processes after determining the starting position, the proposed method corrects the PDR's positioning errors using the matched context. The performance results given in this subsection are based on data-collection experiments that account for a total of 291 meter-long and 67.8 meter-long trajectories in the garage and 8th floor, respectively. Three students walked at a normal speed (1.1 m/s, 1.2 m/s, 1.2 m/s on average, respectively) for a total of 13 times. The route in the parking garage is 6-1-2-3-4-1-2-5, and it is room7-room6-room5-room4-room3-room2-room1 on the 8th floor of the main building. Here, we compare the positioning errors of three schemes: PDR, PDR + Turn and HMM + PDR + Turn. PDR means the location is obtained by PDR method using the step detection and stride length estimation algorithm mentioned in section 2, but the orientation is the original data collected from smartphone directly without optimization by Equation (2). PDR + Turn optimizes the heading between two recognized corners to a unitary angle and calculated the pedestrian's position by Equations (1) and (2). HMM + PDR + Turn refers to the context-recognition-aided PDR localization method based on HMM we designed. The target of the comparison is to reveal the contribution of proposed model in the aspect of improving positioning accuracy. The trajectories and errors of one experiment walked by a student whose speed is 1.1 m/s are shown in Figures 13 and 14. The results suggest that the PDR totally missed the track because of the accumulated errors caused by the sensors' noise in the smartphone. After combining turn detection with PDR, the trajectory was more regular after adjustment of the angles, but a bias relative to the correct route was obvious sometimes. However, when the HMM algorithms were activated to use the matching context, we obtained almost a perfect elimination of the accumulative positioning errors. The positioning accuracy of the proposed method improved 40.56% at most, and remained stable. The results suggest that the PDR totally missed the track because of the accumulated errors caused by the sensors' noise in the smartphone. After combining turn detection with PDR, the trajectory was more regular after adjustment of the angles, but a bias relative to the correct route was obvious sometimes. However, when the HMM algorithms were activated to use the matching context, we obtained almost a perfect elimination of the accumulative positioning errors. The positioning accuracy of the proposed method improved 40.56% at most, and remained stable. The results suggest that the PDR totally missed the track because of the accumulated errors caused by the sensors' noise in the smartphone. After combining turn detection with PDR, the trajectory was more regular after adjustment of the angles, but a bias relative to the correct route was obvious sometimes. However, when the HMM algorithms were activated to use the matching context, we obtained almost a perfect elimination of the accumulative positioning errors. The positioning accuracy of the proposed method improved 40.56% at most, and remained stable.

Robustness of the Method
Though our experimental data show a very low false rate for turn recognition, we wanted to examine the robustness of the method when missed detections happen. In this subsection, we used the real data collected in the 13 experiments of Subsection 5.3 and simulated the failure of context recognition by randomly removing the first or the second detected event artificially from the event stream for testing its fault tolerance. In other words, we set the symbol (1 or −1) of one recognized corner mentioned in section 3 to 0, which is the symbol for walking straight. Table 4 compares the result of different false rates. We can see that despite the missed recognition of one context, it still maintains the high correctness, but requires more contexts to obtain the result, in which the miss recognition of the second context needed more time.

Robustness of the Method
Though our experimental data show a very low false rate for turn recognition, we wanted to examine the robustness of the method when missed detections happen. In this subsection, we used the real data collected in the 13 experiments of Section 5.3 and simulated the failure of context recognition by randomly removing the first or the second detected event artificially from the event stream for testing its fault tolerance. In other words, we set the symbol (1 or −1) of one recognized corner mentioned in Section 3 to 0, which is the symbol for walking straight. Table 4 compares the result of different false rates. We can see that despite the missed recognition of one context, it still maintains the high correctness, but requires more contexts to obtain the result, in which the miss recognition of the second context needed more time.  Figure 15 shows positioning errors of a simulated experiment, where the second recognized context is removed from the real data of the experiment shown in Figure 13a. We can see that the PDR is not affected by the context recognition. In PDR + Turn method, the heading between two recognized corners is constrained to a unitary angle based on PDR, so it causes the enormous errors when the missed context recognition happens. The errors using HMM + PDR + Turn are large before the correct matching because it uses the same heading optimization algorithm as PDR + Turn, but it is corrected immediately once the matching is successful, and keeps the same accuracy and stability with the method in the condition of zero false rate, no longer affected by the missed detection before.
To sum up, the context-recognition-aided PDR localization method based on HMM has the advantage of good robustness.

Conclusions
In indoor environments, PDR based on the smartphone cannot realize localization with high precision continuously and stably. In this paper, we design a matching localization model based on characteristic context which can be realized by electronic devices such as smartphones. We match the context information recognized online to the context pre-stored offline in the database and thus get the pedestrian's location. Compared to traditional map matching and fingerprint algorithms, this method needs less information which can be measured directly and adjusted quickly whenever the map changes, and it is more reliable because the geographical features are more stable than Wi-Fi or Bluetooth signals. In the proposed method, the Recursive Viterbi Algorithm is used to solve the right context sequence, which reduces the time complexity and saves on storage. In the experiment, we detect corners using our proposed detection method and take it as the example to validate the proposed model. The experimental results show that the proposed method can make up for the defects of the PDR individually, which determines the starting position correctly after recognizing a few contexts and compensates the drift of PDR using the matching context. Its positioning accuracy is greatly improved by 40.56% at most, with superior stability and robustness. In the future, we will research various available contexts and the PDR method based on devices with arbitrary posture.

Conclusions
In indoor environments, PDR based on the smartphone cannot realize localization with high precision continuously and stably. In this paper, we design a matching localization model based on characteristic context which can be realized by electronic devices such as smartphones. We match the context information recognized online to the context pre-stored offline in the database and thus get the pedestrian's location. Compared to traditional map matching and fingerprint algorithms, this method needs less information which can be measured directly and adjusted quickly whenever the map changes, and it is more reliable because the geographical features are more stable than Wi-Fi or Bluetooth signals. In the proposed method, the Recursive Viterbi Algorithm is used to solve the right context sequence, which reduces the time complexity and saves on storage. In the experiment, we detect corners using our proposed detection method and take it as the example to validate the proposed model. The experimental results show that the proposed method can make up for the defects of the PDR individually, which determines the starting position correctly after recognizing a few contexts and compensates the drift of PDR using the matching context. Its positioning accuracy is greatly improved by 40.56% at most, with superior stability and robustness. In the future, we will research various available contexts and the PDR method based on devices with arbitrary posture.