updating latest

This commit is contained in:
2019-12-05 03:56:49 +00:00
parent b45c030c59
commit 6c84083c69
7 changed files with 124 additions and 43 deletions

View File

@@ -18,14 +18,14 @@ simNum = 15000
states = np.array(['L', 'w', 'W']) states = np.array(['L', 'w', 'W'])
# Possible sequences of events # Possible sequences of events
transitionName = np.array([['LL', 'Lw', 'LW'], transitionName = np.array(
['wL', 'ww', 'wW'], [['LL', 'Lw', 'LW'], ['wL', 'ww', 'wW'], ['WL', 'Ww', 'WW']]
['WL', 'Ww', 'WW']]) )
# Probabilities Matrix (transition matrix) # Probabilities Matrix (transition matrix)
transitionMatrix = np.array([[0.6, 0.1, 0.3], transitionMatrix = np.array(
[0.1, 0.7, 0.2], [[0.6, 0.1, 0.3], [0.1, 0.7, 0.2], [0.2, 0.2, 0.6]]
[0.2, 0.2, 0.6]]) )
# Starting state - Given as a list of probabilities of starting # Starting state - Given as a list of probabilities of starting
# in each state. To always start at the same state set one of them # in each state. To always start at the same state set one of them
@@ -69,9 +69,14 @@ class markov(object):
currentState: a string indicating the starting state currentState: a string indicating the starting state
steps: an integer determining how many steps (or times) to simulate""" steps: an integer determining how many steps (or times) to simulate"""
def __init__(self, states: np.array, transitionName: np.array, def __init__(
transitionMatrix: np.array, currentState: str, self,
steps: int): states: np.array,
transitionName: np.array,
transitionMatrix: np.array,
currentState: str,
steps: int,
):
super(markov, self).__init__() super(markov, self).__init__()
self.states = states self.states = states
self.list = list self.list = list
@@ -110,10 +115,11 @@ class markov(object):
# To calculate the probability of the stateList # To calculate the probability of the stateList
self.prob = 1 self.prob = 1
while i != self.steps: while i != self.steps:
import pdb; pdb.set_trace() # breakpoint 24e62119 //
if self.currentState == self.states[0]: if self.currentState == self.states[0]:
self.change = np.random.choice(self.transitionName[0], self.change = np.random.choice(
replace=True, self.transitionName[0], replace=True, p=transitionMatrix[0]
p=transitionMatrix[0]) )
if self.change == self.transitionName[0][0]: if self.change == self.transitionName[0][0]:
self.prob = self.prob * self.transitionMatrix[0][0] self.prob = self.prob * self.transitionMatrix[0][0]
self.stateList.append(self.states[0]) self.stateList.append(self.states[0])
@@ -127,9 +133,9 @@ class markov(object):
self.currentState = self.states[2] self.currentState = self.states[2]
self.stateList.append(self.states[2]) self.stateList.append(self.states[2])
elif self.currentState == self.states[1]: elif self.currentState == self.states[1]:
self.change = np.random.choice(self.transitionName[1], self.change = np.random.choice(
replace=True, self.transitionName[1], replace=True, p=transitionMatrix[1]
p=transitionMatrix[1]) )
if self.change == self.transitionName[1][0]: if self.change == self.transitionName[1][0]:
self.prob = self.prob * self.transitionMatrix[1][0] self.prob = self.prob * self.transitionMatrix[1][0]
self.currentState = self.states[0] self.currentState = self.states[0]
@@ -143,9 +149,9 @@ class markov(object):
self.currentState = self.states[2] self.currentState = self.states[2]
self.stateList.append(self.states[2]) self.stateList.append(self.states[2])
elif self.currentState == self.states[2]: elif self.currentState == self.states[2]:
self.change = np.random.choice(self.transitionName[2], self.change = np.random.choice(
replace=True, self.transitionName[2], replace=True, p=transitionMatrix[2]
p=transitionMatrix[2]) )
if self.change == self.transitionName[2][0]: if self.change == self.transitionName[2][0]:
self.prob = self.prob * self.transitionMatrix[2][0] self.prob = self.prob * self.transitionMatrix[2][0]
self.currentState = self.states[0] self.currentState = self.states[0]
@@ -161,8 +167,10 @@ class markov(object):
i += 1 i += 1
print(f'Path Markov Chain took in this iteration: {self.stateList}') print(f'Path Markov Chain took in this iteration: {self.stateList}')
print(f'End state after {self.steps} steps: {self.currentState}') print(f'End state after {self.steps} steps: {self.currentState}')
print(f'Probability of taking these exact steps in this order is:' print(
f' {self.prob:.2f} or {self.prob:.2%}\n') f'Probability of taking these exact steps in this order is:'
f' {self.prob:.2f} or {self.prob:.2%}\n'
)
return self.stateList return self.stateList
@@ -196,43 +204,69 @@ def main(*args, **kwargs):
if initial_dist is not None: if initial_dist is not None:
startingState = np.random.choice(states, p=initial_dist) startingState = np.random.choice(states, p=initial_dist)
for _ in itertools.repeat(None, simNum): for _ in itertools.repeat(None, simNum):
markovChain = markov(states, transitionName, markovChain = markov(
transitionMatrix, startingState, states,
stepTime) transitionName,
transitionMatrix,
startingState,
stepTime,
)
list_state.append(markovChain.forecast()) list_state.append(markovChain.forecast())
startingState = np.random.choice(states, p=initial_dist) startingState = np.random.choice(states, p=initial_dist)
else: else:
for _ in itertools.repeat(None, simNum): for _ in itertools.repeat(None, simNum):
markovChain = markov(states, transitionName, markovChain = markov(
transitionMatrix, startingState, states,
stepTime) transitionName,
transitionMatrix,
startingState,
stepTime,
)
list_state.append(markovChain.forecast()) list_state.append(markovChain.forecast())
else: else:
for _ in range(1, 2): for _ in range(1, 2):
list_state.append(markov(states, transitionName, list_state.append(
transitionMatrix, startingState, markov(
stepTime).forecast()) states,
transitionName,
transitionMatrix,
startingState,
stepTime,
).forecast()
)
for list in list_state: for list in list_state:
if(list[-1] == f'{endState!s}'): if list[-1] == f'{endState!s}':
print(f'SUCCESS - path ended in the requested state {endState!s}' print(
f':', list) f'SUCCESS - path ended in the requested state {endState!s}'
f':',
list,
)
count += 1 count += 1
else: else:
print(f'FAILURE - path did not end in the requested state' print(
f' {endState!s}:', list) f'FAILURE - path did not end in the requested state'
f' {endState!s}:',
list,
)
if setSim is False: if setSim is False:
simNum = 1 simNum = 1
print(f'\nTherefore the estimated probability of starting in' print(
f' {startingState} and finishing in {endState} after ' f'\nTherefore the estimated probability of starting in'
f'{stepTime} steps is ' f' {startingState} and finishing in {endState} after '
f'{(count / simNum):.2%}.\n' f'{stepTime} steps is '
f'This is calculated by number of success/total steps\n') f'{(count / simNum):.2%}.\n'
f'This is calculated by number of success/total steps\n'
)
if transition_matrix_step: if transition_matrix_step:
print(f'P_{stepTime} is: \n' print(
f'{markov.transition_matrix_step(transitionMatrix, stepTime)}\n') f'P_{stepTime} is: \n'
f'{markov.transition_matrix_step(transitionMatrix, stepTime)}\n'
)
if stat_dist: if stat_dist:
checker(initial_dist, 'initial distribution') checker(initial_dist, 'initial distribution')
print(f'Stat dist is {markov.stationary_dist(transitionMatrix,initial_dist, stepTime)}') print(
f'Stat dist is {markov.stationary_dist(transitionMatrix,initial_dist, stepTime)}'
)
if __name__ == '__main__': if __name__ == '__main__':

1
markov/requirements.txt Normal file
View File

@@ -0,0 +1 @@
numpy==1.17.4

View File

@@ -0,0 +1 @@
[" Let's check the latest updates from Highways England as of 19:57:07! \ud83d\ude93\ud83d\udea8", "There are currently no reported congestion incidents on the M62 \ud83e\udd14", "There are currently no reported accident incidents on the M62 \ud83e\udd14", "Hey Andy, maybe flying would be quicker? \ud83d\ude81"]

View File

@@ -6,6 +6,7 @@ import emoji
import random import random
import json import json
import os import os
from chromedriver_py import binary_path
class getTrafficInfo(object): class getTrafficInfo(object):
@@ -69,7 +70,10 @@ class getTrafficInfo(object):
options = webdriver.ChromeOptions() options = webdriver.ChromeOptions()
options.add_argument('headless') options.add_argument('headless')
# Start the Chromedriver # Start the Chromedriver
browser = webdriver.Chrome(options=options) browser = webdriver.Chrome(
executable_path=binary_path,
options=options,
)
browser.get(url) browser.get(url)
return browser return browser
else: else:

View File

@@ -0,0 +1,14 @@
aiohttp==3.6.2
async-timeout==3.0.1
attrs==19.3.0
certifi==2019.9.11
chardet==3.0.4
chromedriver-py==79.0.3945.16
emoji==0.5.4
idna==2.8
multidict==4.5.2
requests==2.22.0
selenium==3.141.0
slackclient==2.3.1
urllib3==1.25.7
yarl==1.3.0

View File

@@ -32,6 +32,7 @@ accidentMessage = None
congestionMessageStart = None congestionMessageStart = None
congestionMessageEnd = None congestionMessageEnd = None
accidentMessageStart = None accidentMessageStart = None
accidentMessageEnd = None accidentMessageEnd = None
messageTitle = data[0] messageTitle = data[0]

View File

@@ -0,0 +1,26 @@
import slack
@slack.RTMClient.run_on(event='message')
def say_hello(**payload):
data = payload['data']
web_client = payload['web_client']
rtm_client = payload['rtm_client']
if 'Hello' in data.get('text', []):
channel_id = data['channel']
thread_ts = data['ts']
user = data['user']
web_client.chat_postMessage(
channel=channel_id, text=f"Hi <@{user}>!", thread_ts=thread_ts
)
slack_token = (
'xoxp-2443045155-231150911092-792886570180-0cf573954c0eeb7f40c7'
'8bc6f5c959db'
)
# slack_token = os.environ["SLACK_API_TOKEN"]
rtm_client = slack.RTMClient(token=slack_token)
rtm_client.start()