SlideShare a Scribd company logo
import re
import time
import math
# --- Parameter ---
FREQUENCY = 60 # (Hz)
DECIMAL = 3 # 2nd decimal place (About 70km)
ALPHA = 4.07 # Standard deviation of GPS measurement
'''
BETA value
'''
BETA = 1 # Exponential distribution parameter
# --- Structure ---
gps_data = [] # [(Latitude, Longitude) ...]
road_network = {} # {Edge ID: (From Node ID, To Node ID, Two Way, Speed
(m/s))}
road_list = [] # [(Edge ID, Segment ID, Latitude, Longitude, Status) ...] Status
0 - skip, 1 - do HMM
road_map = {} # {(Latitude(2nd decimal place), Longitude(2nd decimal
place)): [Edge ID, Segment ID, Latitude, Longitude ...])
ground_true = [] # (Edge, Traverse)
# --- Function ---
def deg2rad(d): # degree to radian
return d * math.pi / 180.0
EARTH_RADIUS_METER = 6378137.0
def spherical_distance(f, t): # caculate the spherical distance of two points
flat = deg2rad(f[0])
flon = deg2rad(f[1])
tlat = deg2rad(t[0])
tlon = deg2rad(t[1])
con = math.sin(flat) * math.sin(tlat)
con += math.cos(flat) * math.cos(tlat) * math.cos(flon - tlon)
return math.acos(con) * EARTH_RADIUS_METER # (m)
def route_distance(f, t):
'''
route algo
'''
return 0
def measure_probability(f, t):
return 1 / (math.sqrt(2 * math.pi) * ALPHA) * math.exp(-0.5 *
math.pow(spherical_distance(f, t) / ALPHA, 2))
def transition_probability(z1, z2, x1, x2):
return 1 / BETA * math.exp(-1 * (spherical_distance(z1, z2) - route_distance(x1,
x2)) / BETA)
'''
def viterbi(obs, states, start_p, trans_p, emit_p):
V = [{}]
path = {}
# Initialize base cases (t == 0)
for y in states:
V[0][y] = start_p[y] * emit_p[y][obs[0]]
path[y] = [y]
# Run Viterbi for t > 0
for t in range(1, len(obs)):
V.append({})
newpath = {}
for y in states:
(prob, state) = max((V[t-1][y0] * trans_p[y0][y] * emit_p[y][obs[t]], y0)
for y0 in states)
V[t][y] = prob
newpath[y] = path[state] + [y]
# Don't need to remember the old paths
path = newpath
n = 0 # if only one element is observed max is sought in the
initialization values
if len(obs)!=1:
n = t
print_dptable(V)
(prob, state) = max((V[n][y], y) for y in states)
return (prob, path[state])
'''
#====================================================================
=========================================#
# --- Parsing ---
print('Parsing...')
tStart = time.time() # (ms)
# [GPS data]
gps_data_file = open('gps_data.txt', 'r', encoding = 'UTF-8')
info = gps_data_file.readline() # [(Date (UTC), Time (UTC), Latitude, Longitude)
counter = 0
for line in gps_data_file:
counter += 1
if(counter == 60 / FREQUENCY):
temp = line.split()
gps_data.append((float(temp[2]), float(temp[3])))
counter = 0
print("GPS data (number): ", len(gps_data))
gps_data_file.close()
# [Road network data]
road_network_file = open('road_network.txt', 'r', encoding = 'UTF-8')
info = road_network_file.readline()
for line in road_network_file:
temp = line.split()
temp_dic_network = {int(temp[0]): ((int(temp[1]), int(temp[2]), int(temp[3]),
float(temp[4])))}
road_network.update(temp_dic_network) # (Edge ID, From Node ID, To
Node ID, Two Way, Speed (m/s))
for i in range(int(temp[5])):
temp_num_lati = float(re.sub('[^-.0-9]', '', temp[(i * 2 + 1) + 6])) #
Latitude
temp_num_longi = float(re.sub('[^-.0-9]', '', temp[(i * 2) + 6])) #
Longitude
# [Road Map]
if((round(temp_num_lati, DECIMAL), round(temp_num_longi, DECIMAL))
not in road_map):
temp_dic_map = {(round(temp_num_lati, DECIMAL),
round(temp_num_longi, DECIMAL)): [(int(temp[0]), i, temp_num_lati,
temp_num_longi)]}
road_map.update(temp_dic_map)
else:
road_map.get((round(temp_num_lati, DECIMAL),
round(temp_num_longi, DECIMAL))).append([int(temp[0]), i, temp_num_lati,
temp_num_longi])
# [Road List]
road_list.append([int(temp[0]), i, temp_num_lati, temp_num_longi], 0)
print("Road segment (number): ", len(road_list))
road_network_file.close()
# [Ground true data]
ground_true_file = open('ground_truth_route.txt', 'r', encoding = 'UTF-8')
info = ground_true_file.readline() # (Edge ID, Traversed From to To)
for line in ground_true_file:
temp = line.split()
ground_true.append((int(temp[0]), temp[1]))
print("Ground true (number): ", len(ground_true))
ground_true_file.close()
print('Elapsed time = ', round(time.time() - tStart, 2))
# --- Analysising ---
print('Analysising...')
tStart = time.time() # (ms)
V = [{}]
path = {}
# Need valid HMM states
# Initialize base cases (t == 0)
for y in road_list:
# Search road map
for i in range(3):
for j in range(3):
if ((round(y[0], DECIMAL) + i, round(y[1], DECIMAL) + j) in road_map):
temp = road_map.get(round(y[0], DECIMAL) + i, round(y[1],
DECIMAL) + j)
'''
Set status and count propability
'''
prev = (0, 0)
for t in range(len(gps_data)):
if(t == 0):
prev = gps_data[t]
elif(spherical_distance(prev, gps_data[t]) > 2 * ALPHA):
'''
do something
'''
prev = gps_data[t]
'''
1. Removing points that are within 2 * Standard Deviation of the previous point
2. HMM Breaks
2.1 More than (200m)
2.2 Route more than great circle (2000m)
2.3 Vehicle speed 3x in route or more than 50 m/s
'''
print('Elapsed time = ', round(time.time() - tStart, 2))
# --- Evaluation ---
'''
print('Evaluation...')
tStart = time.time() # (ms)
print('Elapsed time = ', round(time.time() - tStart, 2))
'''

More Related Content

What's hot

Noise detection from the signal matlab code, Signal Diagnosis
Noise detection from the signal matlab code, Signal Diagnosis Noise detection from the signal matlab code, Signal Diagnosis
Noise detection from the signal matlab code, Signal Diagnosis
Bharti Airtel Ltd.
 
ARM 7 LPC 2148 lecture
ARM 7 LPC 2148 lectureARM 7 LPC 2148 lecture
ARM 7 LPC 2148 lectureanishgoel
 
Lecture 15 data structures and algorithms
Lecture 15 data structures and algorithmsLecture 15 data structures and algorithms
Lecture 15 data structures and algorithmsAakash deep Singhal
 
K10692 control theory
K10692 control theoryK10692 control theory
K10692 control theory
saagar264
 
Script jantung copy
Script jantung   copyScript jantung   copy
Script jantung copy
Nurwahidah Abidin
 
TensorFlow Tutorial
TensorFlow TutorialTensorFlow Tutorial
TensorFlow Tutorial
NamHyuk Ahn
 
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
Dr. Volkan OBAN
 
Calculus III
Calculus IIICalculus III
Calculus III
Laurel Ayuyao
 
Derivatives Lesson Oct 14
Derivatives Lesson  Oct 14Derivatives Lesson  Oct 14
Derivatives Lesson Oct 14ingroy
 
Program implementation and testing
Program implementation and testingProgram implementation and testing
Program implementation and testing
abukky52
 
Py3k
Py3kPy3k
Quantum espresso G Vector distributon
Quantum espresso G Vector distributonQuantum espresso G Vector distributon
Quantum espresso G Vector distributonEric Pascolo
 
Mosaic plot in R.
Mosaic plot in R.Mosaic plot in R.
Mosaic plot in R.
Dr. Volkan OBAN
 
/Root/exam unidad1/muestraip red
/Root/exam unidad1/muestraip red/Root/exam unidad1/muestraip red
/Root/exam unidad1/muestraip redAntonioAlejoAquino
 
Finagle By Twitter Engineer @ Knoldus
Finagle By Twitter Engineer @ KnoldusFinagle By Twitter Engineer @ Knoldus
Finagle By Twitter Engineer @ Knoldus
Knoldus Inc.
 
bpftrace - Tracing Summit 2018
bpftrace - Tracing Summit 2018bpftrace - Tracing Summit 2018
bpftrace - Tracing Summit 2018
AlastairRobertson9
 

What's hot (19)

Noise detection from the signal matlab code, Signal Diagnosis
Noise detection from the signal matlab code, Signal Diagnosis Noise detection from the signal matlab code, Signal Diagnosis
Noise detection from the signal matlab code, Signal Diagnosis
 
ARM 7 LPC 2148 lecture
ARM 7 LPC 2148 lectureARM 7 LPC 2148 lecture
ARM 7 LPC 2148 lecture
 
Lecture 15 data structures and algorithms
Lecture 15 data structures and algorithmsLecture 15 data structures and algorithms
Lecture 15 data structures and algorithms
 
K10692 control theory
K10692 control theoryK10692 control theory
K10692 control theory
 
Script jantung copy
Script jantung   copyScript jantung   copy
Script jantung copy
 
TensorFlow Tutorial
TensorFlow TutorialTensorFlow Tutorial
TensorFlow Tutorial
 
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
Some R Examples[R table and Graphics] -Advanced Data Visualization in R (Some...
 
Calculus III
Calculus IIICalculus III
Calculus III
 
Derivatives Lesson Oct 14
Derivatives Lesson  Oct 14Derivatives Lesson  Oct 14
Derivatives Lesson Oct 14
 
Program implementation and testing
Program implementation and testingProgram implementation and testing
Program implementation and testing
 
Rkf
RkfRkf
Rkf
 
Py3k
Py3kPy3k
Py3k
 
Quantum espresso G Vector distributon
Quantum espresso G Vector distributonQuantum espresso G Vector distributon
Quantum espresso G Vector distributon
 
Auto
AutoAuto
Auto
 
Mosaic plot in R.
Mosaic plot in R.Mosaic plot in R.
Mosaic plot in R.
 
Network flow problems
Network flow problemsNetwork flow problems
Network flow problems
 
/Root/exam unidad1/muestraip red
/Root/exam unidad1/muestraip red/Root/exam unidad1/muestraip red
/Root/exam unidad1/muestraip red
 
Finagle By Twitter Engineer @ Knoldus
Finagle By Twitter Engineer @ KnoldusFinagle By Twitter Engineer @ Knoldus
Finagle By Twitter Engineer @ Knoldus
 
bpftrace - Tracing Summit 2018
bpftrace - Tracing Summit 2018bpftrace - Tracing Summit 2018
bpftrace - Tracing Summit 2018
 

Similar to Python hmm

Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
Yung-Yu Chen
 
Company_X_Data_Analyst_Challenge
Company_X_Data_Analyst_ChallengeCompany_X_Data_Analyst_Challenge
Company_X_Data_Analyst_ChallengeMark Yashar
 
Trees And More With Postgre S Q L
Trees And  More With  Postgre S Q LTrees And  More With  Postgre S Q L
Trees And More With Postgre S Q LPerconaPerformance
 
A scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ codeA scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ code
PVS-Studio LLC
 
TSP algorithm (Computational Thinking) Dropbox
TSP algorithm (Computational Thinking) DropboxTSP algorithm (Computational Thinking) Dropbox
TSP algorithm (Computational Thinking) DropboxSeb Sear
 
Questions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdfQuestions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdf
apexelectronices01
 
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...Revolution Analytics
 
PRACTICAL COMPUTING
PRACTICAL COMPUTINGPRACTICAL COMPUTING
PRACTICAL COMPUTING
Ramachendran Logarajah
 
The Uncertain Enterprise
The Uncertain EnterpriseThe Uncertain Enterprise
The Uncertain Enterprise
ClarkTony
 
Seg code
Seg codeSeg code
Seg code
wi7sonjoseph
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
Saurabh Singh
 
Frsa
FrsaFrsa
Frsa
_111
 
Please finish the codes in Graph.h class.#################### Vert.pdf
Please finish the codes in Graph.h class.#################### Vert.pdfPlease finish the codes in Graph.h class.#################### Vert.pdf
Please finish the codes in Graph.h class.#################### Vert.pdf
petercoiffeur18
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
ebinazer1
 
Senior design project code for PPG
Senior design project code for PPGSenior design project code for PPG
Senior design project code for PPG
FrankDin1
 
Coscup2021-rust-toturial
Coscup2021-rust-toturialCoscup2021-rust-toturial
Coscup2021-rust-toturial
Wayne Tsai
 
Fourier project presentation
Fourier project  presentationFourier project  presentation
Fourier project presentation
志璿 楊
 
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docxCOMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
TashiBhutia12
 
Easy GPS Tracker using Arduino and Python
Easy GPS Tracker using Arduino and PythonEasy GPS Tracker using Arduino and Python
Easy GPS Tracker using Arduino and Python
Núria Vilanova
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
rushabhshah600
 

Similar to Python hmm (20)

Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
Company_X_Data_Analyst_Challenge
Company_X_Data_Analyst_ChallengeCompany_X_Data_Analyst_Challenge
Company_X_Data_Analyst_Challenge
 
Trees And More With Postgre S Q L
Trees And  More With  Postgre S Q LTrees And  More With  Postgre S Q L
Trees And More With Postgre S Q L
 
A scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ codeA scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ code
 
TSP algorithm (Computational Thinking) Dropbox
TSP algorithm (Computational Thinking) DropboxTSP algorithm (Computational Thinking) Dropbox
TSP algorithm (Computational Thinking) Dropbox
 
Questions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdfQuestions has 4 parts.1st part Program to implement sorting algor.pdf
Questions has 4 parts.1st part Program to implement sorting algor.pdf
 
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...
R + Hadoop = Big Data Analytics. How Revolution Analytics' RHadoop Project Al...
 
PRACTICAL COMPUTING
PRACTICAL COMPUTINGPRACTICAL COMPUTING
PRACTICAL COMPUTING
 
The Uncertain Enterprise
The Uncertain EnterpriseThe Uncertain Enterprise
The Uncertain Enterprise
 
Seg code
Seg codeSeg code
Seg code
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
 
Frsa
FrsaFrsa
Frsa
 
Please finish the codes in Graph.h class.#################### Vert.pdf
Please finish the codes in Graph.h class.#################### Vert.pdfPlease finish the codes in Graph.h class.#################### Vert.pdf
Please finish the codes in Graph.h class.#################### Vert.pdf
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
 
Senior design project code for PPG
Senior design project code for PPGSenior design project code for PPG
Senior design project code for PPG
 
Coscup2021-rust-toturial
Coscup2021-rust-toturialCoscup2021-rust-toturial
Coscup2021-rust-toturial
 
Fourier project presentation
Fourier project  presentationFourier project  presentation
Fourier project presentation
 
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docxCOMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
COMPAPPABCA49085rFunrAP__Practical Number 9 & 10.docx
 
Easy GPS Tracker using Arduino and Python
Easy GPS Tracker using Arduino and PythonEasy GPS Tracker using Arduino and Python
Easy GPS Tracker using Arduino and Python
 
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
1sequences and sampling. Suppose we went to sample the x-axis from X.pdf
 

Recently uploaded

Memorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.pptMemorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.ppt
seri bangash
 
Digital Transformation and IT Strategy Toolkit and Templates
Digital Transformation and IT Strategy Toolkit and TemplatesDigital Transformation and IT Strategy Toolkit and Templates
Digital Transformation and IT Strategy Toolkit and Templates
Aurelien Domont, MBA
 
5 Things You Need To Know Before Hiring a Videographer
5 Things You Need To Know Before Hiring a Videographer5 Things You Need To Know Before Hiring a Videographer
5 Things You Need To Know Before Hiring a Videographer
ofm712785
 
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdfSearch Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Arihant Webtech Pvt. Ltd
 
What are the main advantages of using HR recruiter services.pdf
What are the main advantages of using HR recruiter services.pdfWhat are the main advantages of using HR recruiter services.pdf
What are the main advantages of using HR recruiter services.pdf
HumanResourceDimensi1
 
CADAVER AS OUR FIRST TEACHER anatomt in your.pptx
CADAVER AS OUR FIRST TEACHER anatomt in your.pptxCADAVER AS OUR FIRST TEACHER anatomt in your.pptx
CADAVER AS OUR FIRST TEACHER anatomt in your.pptx
fakeloginn69
 
What is the TDS Return Filing Due Date for FY 2024-25.pdf
What is the TDS Return Filing Due Date for FY 2024-25.pdfWhat is the TDS Return Filing Due Date for FY 2024-25.pdf
What is the TDS Return Filing Due Date for FY 2024-25.pdf
seoforlegalpillers
 
RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...
RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...
RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...
BBPMedia1
 
Exploring Patterns of Connection with Social Dreaming
Exploring Patterns of Connection with Social DreamingExploring Patterns of Connection with Social Dreaming
Exploring Patterns of Connection with Social Dreaming
Nicola Wreford-Howard
 
Brand Analysis for an artist named Struan
Brand Analysis for an artist named StruanBrand Analysis for an artist named Struan
Brand Analysis for an artist named Struan
sarahvanessa51503
 
Sustainability: Balancing the Environment, Equity & Economy
Sustainability: Balancing the Environment, Equity & EconomySustainability: Balancing the Environment, Equity & Economy
Sustainability: Balancing the Environment, Equity & Economy
Operational Excellence Consulting
 
Putting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxPutting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptx
Cynthia Clay
 
Maksym Vyshnivetskyi: PMO Quality Management (UA)
Maksym Vyshnivetskyi: PMO Quality Management (UA)Maksym Vyshnivetskyi: PMO Quality Management (UA)
Maksym Vyshnivetskyi: PMO Quality Management (UA)
Lviv Startup Club
 
Premium MEAN Stack Development Solutions for Modern Businesses
Premium MEAN Stack Development Solutions for Modern BusinessesPremium MEAN Stack Development Solutions for Modern Businesses
Premium MEAN Stack Development Solutions for Modern Businesses
SynapseIndia
 
一比一原版加拿大渥太华大学毕业证(uottawa毕业证书)如何办理
一比一原版加拿大渥太华大学毕业证(uottawa毕业证书)如何办理一比一原版加拿大渥太华大学毕业证(uottawa毕业证书)如何办理
一比一原版加拿大渥太华大学毕业证(uottawa毕业证书)如何办理
taqyed
 
falcon-invoice-discounting-a-premier-platform-for-investors-in-india
falcon-invoice-discounting-a-premier-platform-for-investors-in-indiafalcon-invoice-discounting-a-premier-platform-for-investors-in-india
falcon-invoice-discounting-a-premier-platform-for-investors-in-india
Falcon Invoice Discounting
 
RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...
RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...
RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...
BBPMedia1
 
ikea_woodgreen_petscharity_cat-alogue_digital.pdf
ikea_woodgreen_petscharity_cat-alogue_digital.pdfikea_woodgreen_petscharity_cat-alogue_digital.pdf
ikea_woodgreen_petscharity_cat-alogue_digital.pdf
agatadrynko
 
Introduction to Amazon company 111111111111
Introduction to Amazon company 111111111111Introduction to Amazon company 111111111111
Introduction to Amazon company 111111111111
zoyaansari11365
 
LA HUG - Video Testimonials with Chynna Morgan - June 2024
LA HUG - Video Testimonials with Chynna Morgan - June 2024LA HUG - Video Testimonials with Chynna Morgan - June 2024
LA HUG - Video Testimonials with Chynna Morgan - June 2024
Lital Barkan
 

Recently uploaded (20)

Memorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.pptMemorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.ppt
 
Digital Transformation and IT Strategy Toolkit and Templates
Digital Transformation and IT Strategy Toolkit and TemplatesDigital Transformation and IT Strategy Toolkit and Templates
Digital Transformation and IT Strategy Toolkit and Templates
 
5 Things You Need To Know Before Hiring a Videographer
5 Things You Need To Know Before Hiring a Videographer5 Things You Need To Know Before Hiring a Videographer
5 Things You Need To Know Before Hiring a Videographer
 
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdfSearch Disrupted Google’s Leaked Documents Rock the SEO World.pdf
Search Disrupted Google’s Leaked Documents Rock the SEO World.pdf
 
What are the main advantages of using HR recruiter services.pdf
What are the main advantages of using HR recruiter services.pdfWhat are the main advantages of using HR recruiter services.pdf
What are the main advantages of using HR recruiter services.pdf
 
CADAVER AS OUR FIRST TEACHER anatomt in your.pptx
CADAVER AS OUR FIRST TEACHER anatomt in your.pptxCADAVER AS OUR FIRST TEACHER anatomt in your.pptx
CADAVER AS OUR FIRST TEACHER anatomt in your.pptx
 
What is the TDS Return Filing Due Date for FY 2024-25.pdf
What is the TDS Return Filing Due Date for FY 2024-25.pdfWhat is the TDS Return Filing Due Date for FY 2024-25.pdf
What is the TDS Return Filing Due Date for FY 2024-25.pdf
 
RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...
RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...
RMD24 | Debunking the non-endemic revenue myth Marvin Vacquier Droop | First ...
 
Exploring Patterns of Connection with Social Dreaming
Exploring Patterns of Connection with Social DreamingExploring Patterns of Connection with Social Dreaming
Exploring Patterns of Connection with Social Dreaming
 
Brand Analysis for an artist named Struan
Brand Analysis for an artist named StruanBrand Analysis for an artist named Struan
Brand Analysis for an artist named Struan
 
Sustainability: Balancing the Environment, Equity & Economy
Sustainability: Balancing the Environment, Equity & EconomySustainability: Balancing the Environment, Equity & Economy
Sustainability: Balancing the Environment, Equity & Economy
 
Putting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxPutting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptx
 
Maksym Vyshnivetskyi: PMO Quality Management (UA)
Maksym Vyshnivetskyi: PMO Quality Management (UA)Maksym Vyshnivetskyi: PMO Quality Management (UA)
Maksym Vyshnivetskyi: PMO Quality Management (UA)
 
Premium MEAN Stack Development Solutions for Modern Businesses
Premium MEAN Stack Development Solutions for Modern BusinessesPremium MEAN Stack Development Solutions for Modern Businesses
Premium MEAN Stack Development Solutions for Modern Businesses
 
一比一原版加拿大渥太华大学毕业证(uottawa毕业证书)如何办理
一比一原版加拿大渥太华大学毕业证(uottawa毕业证书)如何办理一比一原版加拿大渥太华大学毕业证(uottawa毕业证书)如何办理
一比一原版加拿大渥太华大学毕业证(uottawa毕业证书)如何办理
 
falcon-invoice-discounting-a-premier-platform-for-investors-in-india
falcon-invoice-discounting-a-premier-platform-for-investors-in-indiafalcon-invoice-discounting-a-premier-platform-for-investors-in-india
falcon-invoice-discounting-a-premier-platform-for-investors-in-india
 
RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...
RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...
RMD24 | Retail media: hoe zet je dit in als je geen AH of Unilever bent? Heid...
 
ikea_woodgreen_petscharity_cat-alogue_digital.pdf
ikea_woodgreen_petscharity_cat-alogue_digital.pdfikea_woodgreen_petscharity_cat-alogue_digital.pdf
ikea_woodgreen_petscharity_cat-alogue_digital.pdf
 
Introduction to Amazon company 111111111111
Introduction to Amazon company 111111111111Introduction to Amazon company 111111111111
Introduction to Amazon company 111111111111
 
LA HUG - Video Testimonials with Chynna Morgan - June 2024
LA HUG - Video Testimonials with Chynna Morgan - June 2024LA HUG - Video Testimonials with Chynna Morgan - June 2024
LA HUG - Video Testimonials with Chynna Morgan - June 2024
 

Python hmm

  • 1. import re import time import math # --- Parameter --- FREQUENCY = 60 # (Hz) DECIMAL = 3 # 2nd decimal place (About 70km) ALPHA = 4.07 # Standard deviation of GPS measurement ''' BETA value ''' BETA = 1 # Exponential distribution parameter # --- Structure --- gps_data = [] # [(Latitude, Longitude) ...] road_network = {} # {Edge ID: (From Node ID, To Node ID, Two Way, Speed (m/s))} road_list = [] # [(Edge ID, Segment ID, Latitude, Longitude, Status) ...] Status 0 - skip, 1 - do HMM road_map = {} # {(Latitude(2nd decimal place), Longitude(2nd decimal place)): [Edge ID, Segment ID, Latitude, Longitude ...]) ground_true = [] # (Edge, Traverse) # --- Function --- def deg2rad(d): # degree to radian return d * math.pi / 180.0 EARTH_RADIUS_METER = 6378137.0 def spherical_distance(f, t): # caculate the spherical distance of two points flat = deg2rad(f[0]) flon = deg2rad(f[1]) tlat = deg2rad(t[0]) tlon = deg2rad(t[1]) con = math.sin(flat) * math.sin(tlat) con += math.cos(flat) * math.cos(tlat) * math.cos(flon - tlon) return math.acos(con) * EARTH_RADIUS_METER # (m)
  • 2. def route_distance(f, t): ''' route algo ''' return 0 def measure_probability(f, t): return 1 / (math.sqrt(2 * math.pi) * ALPHA) * math.exp(-0.5 * math.pow(spherical_distance(f, t) / ALPHA, 2)) def transition_probability(z1, z2, x1, x2): return 1 / BETA * math.exp(-1 * (spherical_distance(z1, z2) - route_distance(x1, x2)) / BETA) ''' def viterbi(obs, states, start_p, trans_p, emit_p): V = [{}] path = {} # Initialize base cases (t == 0) for y in states: V[0][y] = start_p[y] * emit_p[y][obs[0]] path[y] = [y] # Run Viterbi for t > 0 for t in range(1, len(obs)): V.append({}) newpath = {} for y in states: (prob, state) = max((V[t-1][y0] * trans_p[y0][y] * emit_p[y][obs[t]], y0) for y0 in states) V[t][y] = prob newpath[y] = path[state] + [y] # Don't need to remember the old paths path = newpath n = 0 # if only one element is observed max is sought in the
  • 3. initialization values if len(obs)!=1: n = t print_dptable(V) (prob, state) = max((V[n][y], y) for y in states) return (prob, path[state]) ''' #==================================================================== =========================================# # --- Parsing --- print('Parsing...') tStart = time.time() # (ms) # [GPS data] gps_data_file = open('gps_data.txt', 'r', encoding = 'UTF-8') info = gps_data_file.readline() # [(Date (UTC), Time (UTC), Latitude, Longitude) counter = 0 for line in gps_data_file: counter += 1 if(counter == 60 / FREQUENCY): temp = line.split() gps_data.append((float(temp[2]), float(temp[3]))) counter = 0 print("GPS data (number): ", len(gps_data)) gps_data_file.close() # [Road network data] road_network_file = open('road_network.txt', 'r', encoding = 'UTF-8') info = road_network_file.readline() for line in road_network_file: temp = line.split() temp_dic_network = {int(temp[0]): ((int(temp[1]), int(temp[2]), int(temp[3]), float(temp[4])))} road_network.update(temp_dic_network) # (Edge ID, From Node ID, To
  • 4. Node ID, Two Way, Speed (m/s)) for i in range(int(temp[5])): temp_num_lati = float(re.sub('[^-.0-9]', '', temp[(i * 2 + 1) + 6])) # Latitude temp_num_longi = float(re.sub('[^-.0-9]', '', temp[(i * 2) + 6])) # Longitude # [Road Map] if((round(temp_num_lati, DECIMAL), round(temp_num_longi, DECIMAL)) not in road_map): temp_dic_map = {(round(temp_num_lati, DECIMAL), round(temp_num_longi, DECIMAL)): [(int(temp[0]), i, temp_num_lati, temp_num_longi)]} road_map.update(temp_dic_map) else: road_map.get((round(temp_num_lati, DECIMAL), round(temp_num_longi, DECIMAL))).append([int(temp[0]), i, temp_num_lati, temp_num_longi]) # [Road List] road_list.append([int(temp[0]), i, temp_num_lati, temp_num_longi], 0) print("Road segment (number): ", len(road_list)) road_network_file.close() # [Ground true data] ground_true_file = open('ground_truth_route.txt', 'r', encoding = 'UTF-8') info = ground_true_file.readline() # (Edge ID, Traversed From to To) for line in ground_true_file: temp = line.split() ground_true.append((int(temp[0]), temp[1])) print("Ground true (number): ", len(ground_true)) ground_true_file.close() print('Elapsed time = ', round(time.time() - tStart, 2)) # --- Analysising --- print('Analysising...') tStart = time.time() # (ms)
  • 5. V = [{}] path = {} # Need valid HMM states # Initialize base cases (t == 0) for y in road_list: # Search road map for i in range(3): for j in range(3): if ((round(y[0], DECIMAL) + i, round(y[1], DECIMAL) + j) in road_map): temp = road_map.get(round(y[0], DECIMAL) + i, round(y[1], DECIMAL) + j) ''' Set status and count propability ''' prev = (0, 0) for t in range(len(gps_data)): if(t == 0): prev = gps_data[t] elif(spherical_distance(prev, gps_data[t]) > 2 * ALPHA): ''' do something ''' prev = gps_data[t] ''' 1. Removing points that are within 2 * Standard Deviation of the previous point 2. HMM Breaks 2.1 More than (200m) 2.2 Route more than great circle (2000m) 2.3 Vehicle speed 3x in route or more than 50 m/s ''' print('Elapsed time = ', round(time.time() - tStart, 2)) # --- Evaluation ---
  • 6. ''' print('Evaluation...') tStart = time.time() # (ms) print('Elapsed time = ', round(time.time() - tStart, 2)) '''