In [13]:
# imports for notebook
import numpy as np
In [220]:
%%file choice.py
# -*- coding: ascii -*-
""" Exploring unit tests.
Simple code to implement a simple Markov transition function.
"""
__author__ = "Mike McFarlane (mike@mikemcfarlane.co.uk)"
__version__ = "$Revision: 0 $"
__date__ = "$Date: 11-04-14"
__copyright__ = "Copyright (c) Mike McFarlane 2014"
__license__ = "TBC"
import random
import numpy as np
import custom_exceptions as ce
def choice2(inArray):
""" Simple function to implement a Markov transition function.
"""
randNum = np.random.random()
cum = 0
sumVal = np.sum(inArray)
if not abs(sumVal - 1.0) < 1e-10:
#print "not a P array"
raise ce.MatrixError("Not a valid array")
else:
for count, i in enumerate(inArray):
cum += i
if cum >= randNum:
return count
if __name__ == '__main__':
print choice2([1])
In [221]:
%%file custom_exceptions.py
# -*- coding: ascii -*-
""" Exploring unit tests.
Custom exceptions classes for choice.py.
"""
__author__ = "Mike McFarlane (mike@mikemcfarlane.co.uk)"
__version__ = "$Revision: 0 $"
__date__ = "$Date: 11-04-14"
__copyright__ = "Copyright (c) Mike McFarlane 2014"
__license__ = "TBC"
class MatrixError(Exception):
""" Raised when wrong matrix error.
"""
pass
In [222]:
%%file choicetest_nosetests.py
# -*- coding: ascii -*-
""" Exploring unit tests.
Tests for nose for choice.py.
"""
__author__ = "Mike McFarlane (mike@mikemcfarlane.co.uk)"
__version__ = "$Revision: 0 $"
__date__ = "$Date: 11-04-14"
__copyright__ = "Copyright (c) Mike McFarlane 2014"
__license__ = "TBC"
import choice
def test_range():
assert choice.choice2([1]) >= 0
def test_bad_range():
assert choice.choice2([2]) >= 0
def test_large_range():
assert choice.choice2([0.1, 0.1, 0.2, 0.2, 0.2, 0.1, 0.09, 0.01]) >= 0
def test_large_bad_range():
assert choice.choice2([0.1, 0.1, 0.2, 0.2, 0.2, 0.1, 0.09, 0.1]) >= 0
In [76]:
%%file choicetest_unittest.py
# -*- coding: ascii -*-
""" Exploring unit tests.
Unit tests for unittest for choice.py.
"""
__author__ = "Mike McFarlane (mike@mikemcfarlane.co.uk)"
__version__ = "$Revision: 0 $"
__date__ = "$Date: 11-04-14"
__copyright__ = "Copyright (c) Mike McFarlane 2014"
__license__ = "TBC"
import choice
import unittest
import numpy as np
class RangeTests(unittest.TestCase):
def test_range(self):
a = choice.choice2([1])
b = 0
self.assertGreaterEqual(a, b)
def test_bad_range(self):
a = choice.choice2([2])
b = 0
self.assertGreaterEqual(a, b)
def test_large_range(self):
a = choice.choice2([0.1, 0.1, 0.2, 0.2, 0.2, 0.1, 0.09, 0.01])
b = 0
self.assertGreaterEqual(a, b)
def test_large_bad_range(self):
a = choice.choice2([0.1, 0.1, 0.2, 0.2, 0.2, 0.1, 0.09, 0.1])
b = 0
self.assertGreaterEqual(a, b)
def test_huge_matrix(self):
arraySize = 1000
array = np.random.random(arraySize)
arraySum = np.sum(array)
arrayNormalised = array / arraySum
testValue = choice.choice2(arrayNormalised)
result = 0
self.assertGreaterEqual(testValue, result)
def test_multirow_matrix(self):
a = choice.choice2([[0.5, 0.5], [0.5, 0.5]])
b = 0
self.assertGreaterEqual(a, b)
if __name__ == "__main__":
unittest.main()
In [74]:
!ls -la
In [225]:
import sys
if 'choice' in sys.modules:
print "Module present, will delete and import."
del(sys.modules['choice'])
import choice
print choice.__version__
print "1: ", choice.choice2([1])
print "2: ", choice.choice2([2])
print "3: ", choice.choice2([0.1, 0.1, 0.2, 0.2, 0.2, 0.1, 0.09, 0.01])
print "4: ", choice.choice2([0.1, 0.1, 0.2, 0.2, 0.2, 0.1, 0.09, 0.1])
In [227]:
!~/Library/Enthought/Canopy_64bit/User/bin/python choice.py
In [228]:
!~/Library/Enthought/Canopy_64bit/User/bin/nosetests -v choicetest_nosetests.py
In [77]:
!~/Library/Enthought/Canopy_64bit/User/bin/python choicetest_unittest.py
In [1]:
%%file Markov_tickles.py
# -*- coding: ascii -*-
""" NAO responds to being tickled.
"""
import time
import sys
import numpy as np
from naoqi import ALProxy
from naoqi import ALBroker
from naoqi import ALModule
NAO_IP = "mistcalf.local"
# Global variables to store module instances and proxies
MarkovTickle = None
class MarkovTickleModule():
""" Simple module for tickling NAO.
"""
# def __init__(self, name):
# """ Initialise module.
# """
# ALModule.__init__(self, name)
def markovChoice(self, inMatrix):
""" Chooses a value from a Markov transition matrix.
"""
randNum = np.random.random()
cum = 0
if round(np.sum(inMatrix)) != 1:
# print "This is not a p array."
raise ValueError
else:
for index, probability in enumerate(inMatrix):
cum += probability
if cum > randNum:
return index
def mainTask(self):
""" Temp main task.
"""
# Run forever
while True:
print ("Alive!")
print "I choose: ", self.markovChoice([0.25, 0.25, 0.25, 0.25])
time.sleep(1.0)
def main():
""" Main entry point
"""
myBroker = ALBroker("myBroker", "0.0.0.0", 0, NAO_IP, 9559)
global MarkovTickle
MarkovTickle = MarkovTickleModule("MarkovTickle")
print "Running, hit CTRL+C to stop script"
MarkovTickle.mainTask()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print "Interrupted by user, shutting down"
# stop any post tasks
# eg void ALModule::stop(const int& id)
try:
myBroker.shutdown()
except Exception, e:
print "Error shutting down broker: ", e
try:
sys.exit(0)
except Exception, e:
print "Error exiting system: ", e
if __name__ == "__main__":
main()
In [2]:
%%file Markov_tickles_unittest.py
# -*- coding: ascii -*-
""" Unit tests using unittest framework for Markov_tickles.py.
"""
#from Markov_tickles import MarkovTickleModule as mt
from Markov_tickles import MarkovTickleModule
import unittest
class ToMarkovChoiceGoodInput(unittest.TestCase):
""" Markov choice should give known result with known input.
"""
def setUp(self):
self.mt = MarkovTickleModule()
def testSmallMatrix(self):
a = self.mt.markovChoice([1])
b = 0
self.assertGreaterEqual(a, b)
def testLargeMatrix(self):
a = self.mt.markovChoice([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
b = 0
self.assertGreaterEqual(a, b)
class ToMarkovChoiceBadInput(unittest.TestCase):
""" Markov choice should give error if bad input.
"""
def setUp(self):
self.mt = MarkovTickleModule()
def testSmallMatrix(self):
a = self.mt.markovChoice([2])
b = 0
self.assertGreaterEqual(a, b)
def testLargeMatrix(self):
a = self.mt.markovChoice([0.9, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
b = 0
self.assertGreaterEqual(a, b)
if __name__ == "__main__":
unittest.main()
In [3]:
!python Markov_tickles_unittest.py
In [7]:
%%file Markov_tickles.py
# -*- coding: ascii -*-
""" NAO responds to being tickled.
"""
import time
import sys
import numpy as np
from naoqi import ALProxy
from naoqi import ALBroker
from naoqi import ALModule
NAO_IP = "mistcalf.local"
# Global variables to store module instances and proxies
MarkovTickle = None
class MarkovTickleModule(ALModule):
""" Simple module for tickling NAO.
"""
def __init__(self, name):
""" Initialise module.
"""
ALModule.__init__(self, name)
def markovChoice(self, inMatrix):
""" Chooses a value from a Markov transition matrix.
"""
randNum = np.random.random()
cum = 0
if round(np.sum(inMatrix)) != 1:
# print "This is not a p array."
raise ValueError
else:
for index, probability in enumerate(inMatrix):
cum += probability
if cum > randNum:
return index
def mainTask(self):
""" Temp main task.
"""
# Run forever
while True:
print ("Alive!")
print "I choose: ", self.markovChoice([0.25, 0.25, 0.25, 0.25])
time.sleep(1.0)
def main():
""" Main entry point
"""
myBroker = ALBroker("myBroker", "0.0.0.0", 0, NAO_IP, 9559)
global MarkovTickle
MarkovTickle = MarkovTickleModule("MarkovTickle")
print "Running, hit CTRL+C to stop script"
MarkovTickle.mainTask()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print "Interrupted by user, shutting down"
# stop any post tasks
# eg void ALModule::stop(const int& id)
try:
myBroker.shutdown()
except Exception, e:
print "Error shutting down broker: ", e
try:
sys.exit(0)
except Exception, e:
print "Error exiting system: ", e
if __name__ == "__main__":
main()
In [8]:
%%file Markov_tickles_unittest.py
# -*- coding: ascii -*-
""" Unit tests using unittest framework for Markov_tickles.py.
"""
#from Markov_tickles import MarkovTickleModule as mt
from Markov_tickles import MarkovTickleModule
import unittest
from naoqi import ALProxy
from naoqi import ALBroker
from naoqi import ALModule
NAO_IP = "mistcalf.local"
# Global variables to store module instances and proxies
MarkovTickle = None
class ToMarkovChoiceGoodInput(unittest.TestCase):
""" Markov choice should give known result with known input.
"""
# def setUp(self):
# self.mt = MarkovTickleModule("test")
global MarkovTickle
def testSmallMatrix(self):
a = MarkovTickle.markovChoice([1])
b = 0
self.assertGreaterEqual(a, b)
def testLargeMatrix(self):
a = MarkovTickle.markovChoice([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
b = 0
self.assertGreaterEqual(a, b)
class ToMarkovChoiceBadInput(unittest.TestCase):
""" Markov choice should give error if bad input.
"""
# def setUp(self):
# self.mt = MarkovTickleModule("test")
global MarkovTickle
def testSmallMatrix(self):
a = MarkovTickle.markovChoice([2])
b = 0
self.assertGreaterEqual(a, b)
def testLargeMatrix(self):
a = MarkovTickle.markovChoice([0.9, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
b = 0
self.assertGreaterEqual(a, b)
if __name__ == "__main__":
myBroker = ALBroker("myBroker", "0.0.0.0", 0, NAO_IP, 9559)
global MarkovTickle
MarkovTickle = MarkovTickleModule("MarkovTickle")
unittest.main()
myBroker.shutdown()
In [9]:
!python Markov_tickles_unittest.py
In [10]:
%%file Markov_tickles.py
# -*- coding: ascii -*-
""" NAO responds to being tickled.
"""
import time
import sys
import numpy as np
from naoqi import ALProxy
from naoqi import ALBroker
from naoqi import ALModule
NAO_IP = "mistcalf.local"
# Global variables to store module instances and proxies
MarkovTickle = None
class MarkovTickleModule(ALModule):
""" Simple module for tickling NAO.
"""
def __init__(self, name):
""" Initialise module.
"""
ALModule.__init__(self, name)
def markovChoice(self, inMatrix):
""" Chooses a value from a Markov transition matrix.
"""
randNum = np.random.random()
cum = 0
if round(np.sum(inMatrix)) != 1:
# print "This is not a p array."
raise ValueError
else:
for index, probability in enumerate(inMatrix):
cum += probability
if cum > randNum:
return index
def mainTask(self):
""" Temp main task.
"""
# Run forever
while True:
print ("Alive!")
print "I choose: ", self.markovChoice([0.25, 0.25, 0.25, 0.25])
time.sleep(1.0)
def main():
""" Main entry point
"""
myBroker = ALBroker("myBroker", "0.0.0.0", 0, NAO_IP, 9559)
global MarkovTickle
MarkovTickle = MarkovTickleModule("MarkovTickle")
print "Running, hit CTRL+C to stop script"
MarkovTickle.mainTask()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print "Interrupted by user, shutting down"
# stop any post tasks
# eg void ALModule::stop(const int& id)
try:
myBroker.shutdown()
except Exception, e:
print "Error shutting down broker: ", e
try:
sys.exit(0)
except Exception, e:
print "Error exiting system: ", e
if __name__ == "__main__":
main()
In [11]:
%%file Markov_tickles_unittest.py
# -*- coding: ascii -*-
""" Unit tests using unittest framework for Markov_tickles.py.
"""
#from Markov_tickles import MarkovTickleModule as mt
from Markov_tickles import MarkovTickleModule
import unittest
from naoqi import ALProxy
from naoqi import ALBroker
from naoqi import ALModule
NAO_IP = "mistcalf.local"
class ToMarkovChoiceGoodInput(unittest.TestCase):
""" Markov choice should give known result with known input.
"""
def setUp(self):
self.myBroker = ALBroker("myBroker", "0.0.0.0", 0, NAO_IP, 9559)
self.MarkovTickle = MarkovTickleModule("MarkovTickle")
def tearDown(self):
# self.MarkovTickle.dispose()
self.MarkovTickle = None
self.myBroker.shutdown()
def testSmallMatrix(self):
a = self.MarkovTickle.markovChoice([1])
b = 0
self.assertGreaterEqual(a, b)
def testLargeMatrix(self):
a = self.MarkovTickle.markovChoice([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
b = 0
self.assertGreaterEqual(a, b)
class ToMarkovChoiceBadInput(unittest.TestCase):
""" Markov choice should give error if bad input.
"""
def setUp(self):
self.myBroker = ALBroker("myBroker", "0.0.0.0", 0, NAO_IP, 9559)
self.MarkovTickle = MarkovTickleModule("MarkovTickle")
def tearDown(self):
# self.MarkovTickle.dispose()
self.MarkovTickle = None
self.myBroker.shutdown()
def testSmallMatrix(self):
a = self.MarkovTickle.markovChoice([2])
b = 0
self.assertGreaterEqual(a, b)
def testLargeMatrix(self):
a = self.MarkovTickle.markovChoice([0.9, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
b = 0
self.assertGreaterEqual(a, b)
if __name__ == "__main__":
unittest.main()
In [12]:
!python Markov_tickles_unittest.py
In [65]:
# Good matrix, huge. Create a large numpy array.
array = np.arange(0., 1., 0.01)
print array
In [66]:
# Or with random, then normalise.
arraySize = 1000
array = np.random.random(arraySize)
print array
array_sum = np.sum(array)
array_normalised = array / array_sum
print np.sum(array_normalised)
In [78]:
# Does choice return a good distribution over a large number of runs?
In [247]:
%%file many_choice_runs.py
# -*- coding: ascii -*-
""" Exploring unit tests.
Simple code to implement a simple Markov transition function.
And test it over many runs for even distribution.
"""
__author__ = "Mike McFarlane (mike@mikemcfarlane.co.uk)"
__version__ = "$Revision: 0 $"
__date__ = "$Date: 14-04-14"
__copyright__ = "Copyright (c) Mike McFarlane 2014"
__license__ = "TBC"
import random
import numpy as np
import custom_exceptions as ce
def choice2(inArray):
""" Simple function to implement a Markov transition function.
"""
randNum = np.random.random()
cum = 0
sumVal = np.sum(inArray)
if not abs(sumVal - 1.0) < 1e-10:
#print "not a P array"
raise ce.MatrixError("Not a valid array")
else:
for count, i in enumerate(inArray):
cum += i
if cum >= randNum:
return count
def main():
numRuns = 1000000
transitionMatrix = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
# Run choice function many times.
list = [choice2(transitionMatrix) for i in range(numRuns)]
# Generate histogram of result.
listHistogram, listBins = np.histogram(list)
print "listHistogram: ", listHistogram
#print "bins: ", listBins
listPercentage = [(x / float(numRuns))*100 for x in listHistogram]
print listPercentage
print np.sum(listPercentage)
if __name__ == '__main__':
main()
In [248]:
!python many_choice_runs.py
In [249]:
# Run code in ipnb for plot
import random
import numpy as np
import matplotlib.pyplot as plt
def choice2(inArray):
""" Simple function to implement a Markov transition function.
"""
randNum = np.random.random()
cum = 0
sumVal = np.sum(inArray)
if not abs(sumVal - 1.0) < 1e-10:
#print "not a P array"
raise ce.MatrixError("Not a valid array")
else:
for count, i in enumerate(inArray):
cum += i
if cum >= randNum:
return count
def main():
numRuns = 1000000
transitionMatrix = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
# Run choice function many times.
list = [choice2(transitionMatrix) for i in range(numRuns)]
# Generate histogram of result.
listHistogram, listBins = np.histogram(list)
print "listHistogram: ", listHistogram
listPercentage = [(x / float(numRuns)) * 100 for x in listHistogram]
print listPercentage
plt.plot(listPercentage)
plt.axis([0, 9, 0, 12])
main()
In [ ]: