Advertisement
Guest User

Untitled

a guest
Nov 14th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.36 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Nov 14 13:10:14 2019
  4.  
  5. @author: s194734, s194729, s193743
  6. """
  7. import numpy as np
  8. import os
  9. import matplotlib.pyplot as plt
  10.  
  11. #---------------------------------------------------------------------------
  12. #ITEMS
  13. xfilter=1
  14. filterOpt=["Enable", "Disable and reset"]
  15. menuItems=["Load data.","Filter Data.","Display Statistics.","Generate Plots.","Quit."]
  16. statisticItems=["Mean Temperature","Mean Growth rate","Std Temperature","Rows", "Mean Cold Growth rate","Mean Hot Growth rate"]
  17. filterItems=["Growth Rate Range","Temperature Range","Salmonella enterica","Bacillus cereus","Listeria","Brochothrix thermosphacta"]
  18. bacteriatypes=["Salmonella enterica","Bacillus cereus","Listeria","Brochothrix thermosphacta"]
  19. #---------------------------------------------------------------------------
  20. #Auxiliary  functions
  21.  
  22.  
  23. def count(a,b):
  24.     count = 0
  25.     for i in range(len(a)):
  26.         if a[i] == b:
  27.             count=count+1
  28.     return(count)
  29.    
  30. def inputString(prompt):                        #Prompt user to input a string
  31.     while True:
  32.         try:
  33.             string=str(input(prompt))
  34.             break
  35.         except ValueError:
  36.             pass
  37.     return string
  38.            
  39. def inputNumber(prompt):                    #Prompt user to input a number(int)
  40.     while True:
  41.         try:
  42.             num = int(input(prompt))
  43.             break
  44.         except ValueError:
  45.             pass
  46.     return num
  47.  
  48. def inputNumberFloat(prompt):                    #Prompt user to input a number(int)
  49.     while True:
  50.         try:
  51.             num = float(input(prompt))
  52.             break
  53.         except ValueError:
  54.             pass
  55.     return num
  56.  
  57.  
  58. def displayMenu():                                          #Main Menu
  59.     print("""Bacteria Data\n\nMENU-------------------- """)
  60.     if xfilter==1:
  61.         print("Filter disabled")
  62.     else: print("Filter enabled")
  63.     for i in range(5):
  64.         print("{:d}.  {:s}".format(i+1,menuItems[i]))
  65.     choice=0
  66.     while not(np.any(choice == np.arange(5)+1)):
  67.         choice = inputNumber("\n\nPlease choose a menu item: ")
  68.     return choice
  69.  
  70.  
  71. def displaySubMenu():                                       #Sub Menu
  72.     for i in range(len(statisticItems)):
  73.         print("{:d}. {:s}".format(i+1, statisticItems[i]))
  74.     choice = 0
  75.     while not (np.any(choice == np.arange(6)+1)):
  76.         choice = inputNumber("Please choose a statistic: ")
  77.     return choice-1
  78.  
  79. def displaySubMenu1():                                       #Sub Menu
  80.     for i in range(len(filterItems)):
  81.         print("{:d}. {:s}".format(i+1, filterItems[i]))
  82.     choice = 0
  83.     while not (np.any(choice == np.arange(6)+1)):
  84.         choice = inputNumber("Please choose a filter: ")
  85.     return choice-1
  86.  
  87. def displaySubMenu2():                                       #Sub Menu
  88.     for i in range(len(bacteriatypes)):
  89.         print("{:d}. {:s}".format(i+1, bacteriatypes[i]))
  90.     choice = 0
  91.     while not (np.any(choice == np.arange(4)+1)):
  92.         choice = inputNumber("Please choose a bacteria: ")
  93.     return choice-1
  94.  
  95. def displaySubMenu3():                                       #Sub Menu
  96.     for i in range(len(filterOpt)):
  97.         print("{:d}. {:s}".format(i+1, filterOpt[i]))
  98.     choice = 0
  99.     while not (np.any(choice == np.arange(2)+1)):
  100.         choice = inputNumber("Filter: ")
  101.     return choice-1
  102.  
  103. #DataLoad-----------------------------------------------------------
  104.  
  105. def dataLoad(filename):
  106.     if os.path.isfile(filename) == False:
  107.         print("Invalid path/filename")
  108.         return dataLoad(inputString("Enter file name or directory:\n>"))
  109.     else:
  110.         data = np.loadtxt(filename)
  111.         i = 0
  112.         while i in range(len(data)):
  113.             if data[i, 0] < 10 or data[i, 0] > 60:
  114.                 print("error in line", i, "temperature is out of range")
  115.             i += 1
  116.         i = 0
  117.         while i in range(len(data)):
  118.             if data[i, 1] < 0:
  119.                 print("error in line", i, "growth rate is not a negative number")
  120.             i += 1
  121.         i = 0
  122.         while i in range(len(data)):
  123.             if data[i, 2] > 4 or data[i, 2] < 1:
  124.                 print("error in line", i, "unrecognized bacteria ID number")
  125.             i += 1
  126.            
  127.         i = 0
  128.         while i in range(len(data)):
  129.             if data[i, 0] < 10 or data[i, 0] > 60:
  130.                 data = np.delete(data, i, 0)
  131.             i += 1
  132.         i = 0
  133.         while i in range(len(data)):
  134.             if data[i, 1] < 0:
  135.                 data = np.delete(data, i, 0)
  136.             i += 1
  137.         i = 0
  138.         while i in range(len(data)):
  139.             if data[i, 2] > 4 or data[i, 2] < 1:
  140.                 data = np.delete(data, i, 0)
  141.             i += 1
  142.         return data
  143.  
  144.  
  145.  
  146.  
  147. #DataStatisics-------------------------------------------------------
  148. def dataStatistics(dataf, statistic):
  149.     if statistic=="Mean Temperature":
  150.         result=np.mean(dataf[:,0])
  151.     elif statistic=="Mean Growth rate":
  152.         result=np.mean(dataf[:,1])
  153.     elif statistic=="Std Temperature":
  154.         T=dataf[:,0]
  155.         result=T.std(0)
  156.     elif statistic=="Std Growth rate":
  157.         G=dataf[:,1]
  158.         result=G.std(0)
  159.     elif statistic=="Rows":
  160.         numrows=len(dataf)
  161.         result=numrows
  162.     elif statistic=="Mean Cold Growth rate":
  163.         (x,y,z)=np.mean(dataf[dataf[:,0]<20],axis=0)
  164.         result=y
  165.     elif statistic=="Mean Hot Growth rate":
  166.         (x,y,z)=np.mean(dataf[dataf[:,0]>50],axis=0)
  167.         result=y
  168.     return result
  169.  
  170. #DataPlot---------------------------------------------------------------
  171.  
  172.  
  173. def dataPlot(dataf):
  174.     objects = ("Salmonella enterica","Bacillus cereus","Listeria","Brochothrix thermosphacta")
  175.     x = np.arange(len(objects))
  176.     Numbacteria=dataf[:,2]
  177.     y=np.array([])
  178.     for i in range(1,5):
  179.         y = np.hstack((y,count(Numbacteria,i))) #?
  180.     plt.bar(x, y, align="center", alpha=0.5)
  181.     plt.xticks(x, objects)
  182.     plt.xlabel("Type of bacteria")
  183.     plt.ylabel("Number per type")
  184.     plt.title("Number of bacteria")
  185.     plt.show()
  186.    
  187.     data1 = dataf[dataf[:, 2] == 1]
  188.     x = data1[:,0]
  189.     y = data1[:,1]
  190.     data1 = dataf[dataf[:, 2] == 2]
  191.     x2 = data1[:,0]
  192.     y2 = data1[:,1]
  193.     data1 = dataf[dataf[:, 2] == 3]
  194.     x3 = data1[:,0]
  195.     y3 = data1[:,1]
  196.     data1 = dataf[dataf[:, 2] == 4]
  197.     x4 = data1[:,0]
  198.     y4 = data1[:,1]
  199.     plt.plot(x, y,"or", label="Salmonela enterica") # Plot line graph of x and y
  200.     plt.plot(x2, y2,"*g", label="Bacillus cereus") # Plot line graph of x and y
  201.     plt.plot(x3, y3,"^y", label="Listeria") # Plot line graph of x and y
  202.     plt.plot(x4, y4,"sb", label="Brochothrix thermosphacta") # Plot line graph of x and y
  203.     plt.title("Growth rate by temperature") # Set the title of the graph
  204.     plt.xlabel("Temperature") # Set the x-axis label
  205.     plt.ylabel("Growth rate") # Set the y-axis label
  206.     plt.xlim([10, 60]) # Set the limits of the x-axis
  207.     plt.ylim([0, 1]) # Set the limits of the y-axis
  208.     plt.legend(bbox_to_anchor=(1,1.05))
  209.     plt.grid()
  210.     plt.show()
  211.    
  212.    
  213.        
  214.    
  215.    
  216.    
  217.  
  218.    
  219.  
  220.  
  221.  
  222. #Main Script-----------------------------------------------------------
  223. data=dataLoad(inputString("Enter file name or directory:\n>"))
  224. while True:
  225.     choice=displayMenu()
  226.     if choice==1:       #Load Data
  227.         print("\nLoad Data")
  228.         data=dataLoad(inputString("Enter file name or directory:\n>"))
  229.    
  230.     elif choice==2:      #End it later
  231.         print("\nFilter")
  232.         print("Filter activation")
  233.         xfilter=displaySubMenu3()
  234.        
  235.         if xfilter==1:
  236.             dataf=data
  237.         elif xfilter==0:
  238.             Filteropt=displaySubMenu1()
  239.             dataf=data
  240.             if Filteropt + 1 == 1:
  241.                 Min = inputNumberFloat("Minimum Value:\n")
  242.                 Max = inputNumberFloat("Maximum Value:\n")
  243.                 dataf = dataf[dataf[:, 1] > Min]
  244.                 dataf= dataf[dataf[:, 1] < Max]
  245.             elif Filteropt + 1 == 2:
  246.                 Min = inputNumberFloat("Minimum temperature:\n")
  247.                 Max = inputNumberFloat("Maximum temperature:\n")
  248.                 dataf = dataf[dataf[:, 0] > Min]
  249.                 dataf = dataf[dataf[:, 0] < Max]
  250.             elif Filteropt + 1 == 3:
  251.                 dataf = dataf[dataf[:, 2] == 1]
  252.             elif Filteropt + 1 == 4:
  253.                 dataf = dataf[dataf[:, 2] == 2]
  254.             elif Filteropt + 1 == 5:
  255.                 dataf = dataf[dataf[:, 2] == 3]
  256.             elif Filteropt + 1 == 6:
  257.                 dataf = dataf[dataf[:, 2] == 4]
  258.                
  259.            
  260.    
  261.     elif choice==3:    #Draw Plots
  262.         if xfilter==1:
  263.             print("\nStatistics")
  264.             print("Which statistic do you want to calcultate?\n")
  265.             statistic=statisticItems[displaySubMenu()]
  266.             dataStat=dataStatistics(data,statistic)
  267.             print(dataStat)
  268.             print("\n")
  269.         elif xfilter==0:
  270.             print("\nStatistics")
  271.             print("Which statistic do you want to calcultate?\n")
  272.             statistic=statisticItems[displaySubMenu()]
  273.             dataStat=dataStatistics(dataf,statistic)
  274.             print(dataStat)
  275.             print("\n")
  276.        
  277.        
  278.     elif choice==4:
  279.         if xfilter==1:
  280.             dataPlot(data)
  281.         elif xfilter==0:
  282.             dataPlot(dataf)
  283.     elif choice==5:
  284.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement