Advertisement
Guest User

Untitled

a guest
Nov 12th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.25 KB | None | 0 0
  1.  
  2. import pandas as pd
  3. import numpy as np
  4. import os.path
  5. import matplotlib.pyplot as plt
  6.  
  7. class Interface:
  8. def __init__(self):
  9. print("Welcome to Bacteria'R'us™\nTo return to main menu enter 'quit'")
  10. self.data = pd.DataFrame([])
  11. self.filename = None
  12. self.filterchosen = False
  13. self.bactchosen = False
  14. self.growchosen = False
  15. self.bactfilterList = []
  16. self.growfilterlist = []
  17. self.l = pd.DataFrame([])
  18.  
  19. def mainprompt(self):
  20. while True:
  21. print('Main menu\nYou have the following options:')
  22. print('1. Load data')
  23. print('2. Filter data')
  24. print('3. Display statistics')
  25. print('4. Generate plots')
  26. print('5. Quit')
  27. choice = input(">> Choose option\n")
  28.  
  29. if choice in ['5', '5.', 'Quit', 'quit', 'q', 'Q']:
  30. print("This instance of Bacteria'R'us™ has terminated.")
  31. print('The team behind wishes you a nice day')
  32. return (0)
  33. elif os.path.exists(choice) == True:
  34. self.data = self.dataLoad(choice)
  35. elif choice in ['1', '1.', 'Load data', 'Load Data', 'load data']:
  36. global filename
  37. filename = input(">>Enter datafile\n")
  38. if os.path.exists(filename) == True:
  39. self.data = self.dataLoad(filename)
  40. else:
  41. print('Invalid file path\n')
  42. elif choice in ['2', '2.', 'Filter data', 'Filter Data', 'filter data']:
  43. if self.data.empty == True:
  44. print('no data')
  45. else:
  46. self.filterchosen = True
  47. self.dataFilter()
  48. elif choice in ['3', '3.', 'Display statistics', 'Display Statistics', 'display statistics']:
  49. if self.data.empty == True:
  50. print('no data')
  51. else:
  52. self.dataStatistics()
  53. elif choice in ['4', '4.', 'Generate plots', 'Generate Plots', 'generate plots']:
  54. if self.data.empty == True:
  55. print('no data')
  56. else:
  57. self.plots()
  58. # make plot function
  59. else:
  60. print('Invalid option')
  61.  
  62. def dataLoad(self, filename):
  63. self.data = pd.read_csv(filename, sep=' ', names=['Temperature', 'Growth rate', 'Bacteria'])
  64. # the columns are named to evaluate conditions below
  65. Temp = np.array(self.data.iloc[:, 0])
  66. Growthrate = np.array(self.data.iloc[:, 1])
  67. Bact = np.array(self.data.iloc[:, 2])
  68. # a new matrix
  69. self.l = pd.DataFrame([])
  70. for i in range(len(Temp)):
  71. if Temp[i] < 10 or Temp[i] > 60:
  72. print('Data on line ' + str(
  73. i) + ' of file was omitted \nReason: temperature must be between 10 and 60 degrees')
  74. elif Growthrate[i] < 0:
  75. print('Data on line ' + str(i) + ' of file was omitted \nReason: Growth rate must be positive')
  76. elif Bact[i] not in [1, 2, 3, 4]:
  77. print('Data on line ' + str(i) + ' of file was omitted \nReason: Bacteria must be one of no. 1-4')
  78. else:
  79. self.l = self.l.append(self.data.iloc[i, :])
  80.  
  81. self.data = self.l
  82. print(self.data)
  83. print('\nThese are the data\n')
  84. return self.data
  85. #return self.l
  86.  
  87. def dataFilter(self):
  88. while True:
  89. if self.bactchosen:
  90. self.bactFilter()
  91. if self.growchosen:
  92. self.growFilter()
  93.  
  94. if not self.filterchosen:
  95. return
  96. afilter = input('Filter bacteria type or growth rate? ')
  97. if afilter in ['Bacteria', 'B', 'b']:
  98. self.bactchosen = True
  99. elif afilter in ['Growth', 'G', 'g']:
  100. self.growchosen = True
  101. elif afilter in ['Q', 'q', 'Quit', 'quit', 'r', 'R', 'Return', 'return']:
  102. self.bactchosen = False
  103. return
  104. else:
  105. print('incorrect option')
  106.  
  107. def bactFilter(self):
  108. while True:
  109. print("Bacteria filtered:", str(self.bactfilterList),
  110. "\nenter 'Return' for other filters or 'Quit' to exit to main")
  111. n = input('toggle bacterium number:(1-4)')
  112. if n in ['Q', 'q', 'Quit', 'quit', 'r', 'R', 'Return', 'return']:
  113. self.bactchosen = False
  114. if n in ['Q', 'q', 'Quit', 'quit']:
  115. self.filterchosen = False
  116. return
  117. elif n in []:
  118. self.bactchosen = False
  119. return
  120. elif n in ['1', '2', '3', '4', '1.0', '2.0', '3.0', '4.0']:
  121. if float(n) in self.bactfilterList:
  122. self.bactfilterList.remove(float(n))
  123. else:
  124. self.bactfilterList += [float(n)]
  125. self.l = pd.DataFrame([])
  126. length = len(np.array(self.data.iloc[:, 0]))
  127. for i in range(length):
  128. if self.data.iloc[i, 0] in self.bactfilterList:
  129. pass
  130. else:
  131. self.l = self.l.append(self.data.iloc[i, :])
  132. print(self.l)
  133. else:
  134. print('invalid number')
  135.  
  136. def growFilter(self):
  137. while True:
  138. print('growth rate filters:', str(self.growfilterlist))
  139. length = len(np.array(self.data.iloc[:, 0]))
  140. lower = input('enter lower bound(float)')
  141. if lower in ['Q', 'q', 'Quit', 'quit', 'r', 'R', 'Return', 'return']:
  142. self.growchosen = False
  143. if lower in ['Q', 'q', 'Quit', 'quit']:
  144. self.filterchosen = False
  145. return
  146. upper = input('enter upper bound(float)')
  147. if upper in ['Q', 'q', 'Quit', 'quit', 'r', 'R', 'Return', 'return']:
  148. self.growchosen = False
  149. if upper in ['Q', 'q', 'Quit', 'quit']:
  150. self.filterchosen = False
  151. print('quitted')
  152. return
  153. elif (lower == float) and (upper == float):
  154. # elif float(u) not float: #or (float(l) is not float):
  155. # print('range must be entered as float values')
  156. self.growfilterlist.append(lower)
  157. self.l=pd.DataFrame([])
  158. for i in range(length):
  159. if float(l) > float(self.data.iloc[i, 0]) or float(self.data.iloc[i, 1]) > float(u):
  160. pass
  161. else:
  162. self.l = self.l.append(self.data.iloc[i, :])
  163. print(self.l)
  164.  
  165. def dataStatistics(self):
  166. while True:
  167. print('Options:')
  168. print('1.’Mean Temperature’:\nMean (average) Temperature.')
  169. print('\n2.’Std Temperature’:\nStandard deviation of Temperature.')
  170. print('\n3.’Std Growth rate’:\nStandard deviation of Growth rate.')
  171. print('\n4.’Rows’:\nThe total number of rows in the data.')
  172. print('\n5.’Mean Cold Growth rate’:\nAverage Growth rate for Temperature below 20 degrees.')
  173. print('\n6.’Mean Hot Growth rate’:\nAverage Growth rate for Temperature above 50 degrees.')
  174. statistics = input("choose statistic:")
  175. result = 0
  176. if self.l.empty == True:
  177. print('Statistics can not be computed when all data is filtered')
  178. return
  179. if statistics in ['1', 'Mean Temperature', 'mean temperature', 'mean Temperature', 'mt', 'MT']:
  180. result = np.mean(np.array(self.l.iloc[:, 2]))
  181. print(result)
  182. elif statistics in ['2', 'Mean Growth rate', 'MGR', 'mgr']:
  183. result = np.mean(np.array(self.l.iloc[:, 1]))
  184. print(result)
  185. elif statistics in ['3', 'Std Temperature', 'ST', 'st']:
  186. result = np.std(np.array(self.l.iloc[:, 2]))
  187. print(result)
  188. elif statistics in ['4', 'Rows', 'rows', 'rs']:
  189. result = len(np.array(self.l.iloc[:, 0]))
  190. print(result)
  191. elif statistics in ['5', 'Mean Cold Growth Rate', 'mean cold growth rate', 'mcgr', 'MCGR']:
  192. Sum = 0
  193. n = 0
  194. for i in range(len(self.l.iloc[:, 1])):
  195. if self.l.iloc[i, 2] < 20:
  196. n += 1
  197. Sum += self.l.iloc[i, 1]
  198. if n <= 0:
  199. print('no data below 20 degrees found')
  200. else:
  201. result = Sum / n
  202. print(result)
  203. elif statistics in ['6', 'Mean Hot Growth Rate', 'mean hot growth rate', 'mhgr', 'MHGR']:
  204. Sum = 0
  205. n = 0
  206. for i in range(len(self.l.iloc[:, 1])):
  207. if self.l.iloc[i, 2] > 50:
  208. n += 1
  209. Sum += self.l.iloc[i, 1]
  210. if n <= 0:
  211. print('no data above 50 degrees found')
  212. else:
  213. result = Sum / n
  214. print(result)
  215. elif statistics in ['Q', 'q', 'Quit', 'quit', 'r', 'R', 'Return', 'return']:
  216. return
  217.  
  218. # enter rest
  219. else:
  220. print("not valid, retry or quit?")
  221.  
  222. def plots(self):
  223. plotchoice=input("What plots do you want to see? \nYou have the following options: \n1.Frequency of the Bacteria \n2.Growth Rate by Temperature")
  224. if plotchoice in ['1', 'Bacteria', 'bacteria','b','B']:
  225. measurements = [0,0,0,0]
  226. for i in range (len(self.l.iloc[:,0])):
  227. if self.l.iloc[i,0] == 1.0:
  228. measurements[0]+=1
  229. elif self.l.iloc[i,0] == 2.0:
  230. measurements[1]+=1
  231. elif self.l.iloc[i,0] == 3.0:
  232. measurements[2]+=1
  233. elif self.l.iloc[i,0] == 4.0:
  234. measurements[3]+=1
  235. objects = ('Salmonella \nenterica', 'Bacillus \ncereus', 'Listeria', 'Brochothrix \nthermosphacta')
  236. y_pos=np.arange(len(objects))
  237. plt.bar(y_pos, measurements, width=0.7, align='center', alpha=0.7)
  238. plt.xticks(y_pos, objects)
  239. plt.ylabel('Amount')
  240. plt.xlabel('Bacteria',fontdict=None, labelpad=None)
  241. plt.title('Frequency of the Bacteria')
  242. plt.show()
  243.  
  244. elif plotchoice in ['2','GT','gt','Gt','gT','G','g','Growth','growth','Temperature','temperature','Growth Temperature','Growth temperature','growth temperature']:
  245. bacttemp1=[]
  246. bacttemp2=[]
  247. bacttemp3=[]
  248. bacttemp4=[]
  249. bactgrowth1=[]
  250. bactgrowth2=[]
  251. bactgrowth3=[]
  252. bactgrowth4=[]
  253. length=len(self.l.iloc[:,0])
  254. for i in range(length):
  255. if self.l.iloc[i,0] == [1.0]:
  256. bacttemp1.append(self.l.iloc[i,2])
  257. bactgrowth1.append(self.l.iloc[i,1])
  258. elif self.l.iloc[i,0] == 2.0:
  259. bacttemp2.append(int(self.l.iloc[i,2]))
  260. bactgrowth2.append(self.l.iloc[i,1])
  261. elif self.l.iloc[i,0] == 3.0:
  262. bacttemp3.append(int(self.l.iloc[i,2]))
  263. bactgrowth3.append(self.l.iloc[i,1])
  264. elif self.l.iloc[i,0] == 4.0:
  265. bacttemp4.append(self.l.iloc[i,2])
  266. bactgrowth4.append(self.l.iloc[i,1])
  267. z1 = sorted(zip(bacttemp1,bactgrowth1))
  268. bacttemp1=[i[0] for i in z1]
  269. bactgrowth1=[i[1] for i in z1]
  270. z2 = sorted(zip(bacttemp2,bactgrowth2))
  271. bacttemp2=[i[0] for i in z2]
  272. bactgrowth2=[i[1] for i in z2]
  273. z3 = sorted(zip(bacttemp3,bactgrowth3))
  274. bacttemp3=[i[0] for i in z3]
  275. bactgrowth3=[i[1] for i in z3]
  276. z4 = sorted(zip(bacttemp4,bactgrowth4))
  277. bacttemp4=[i[0] for i in z4]
  278. bactgrowth4=[i[1] for i in z4]
  279. # setting up a graph showing the relation of the growth rate to the temperature for each type of bacteria
  280. plt.plot(bacttemp1, bactgrowth1, 'b-', label='Salmonella enterica')
  281. plt.plot(bacttemp2, bactgrowth2, 'r-', label='Bacillus cereus')
  282. plt.plot(bacttemp3, bactgrowth3, 'g-', label='Listeria')
  283. plt.plot(bacttemp4, bactgrowth4, 'm-', label='Brochothrix thermosphacta')
  284. plt.legend(loc='best') #'best' localisation makes sure that the legend won't cover the data
  285. plt.ylabel('Growth rate')
  286. plt.xlabel('Temperature')
  287. plt.title('Growth Rate by Temperature for different bacteria')
  288. plt.xlim(xmin=10.0, xmax=60.0)
  289. plt.ylim(ymin=0.0, ymax=1.0)
  290. plt.grid(True)
  291. plt.show()
  292.  
  293. if __name__ == '__main__':
  294. interface = Interface()
  295. interface.mainprompt()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement