def Run_Algoritm(Path, Algorithm, Discretization_type, NumOfBins, NumOfNeg): ''' function that runs the algorithm that user choose and return the results of the user inputs and clean the files before that. :return:nothing ''' pre = PreProcessing() test = pd.read_csv(Path + '/test.csv') train = pd.read_csv(Path + '/train.csv') struct = pre.read_structure(Path + '/Structure.txt') pre.Clean_Data(train, struct, Discretization_type, NumOfBins) pre.Delete_Nan_Class_Row(test) pre.Fill_Nan_Values(test, struct) pre.Save_Data(train, Path, 'train') pre.Save_Data(test, Path, 'test') if Algorithm not in ['naive bayes classifier (our)', 'ID3 (our)']: runner = BuildAlgorithm() train, test = runner.Convert_Strings_To_Numbers(Path) return runner.Run(Algorithm, train, test, Path, NumOfNeg) else: process = Processing() model = process.Build_Model(Path, Algorithm, train) process.Save_Model(Path, model) train = pd.read_csv(Path + '/train.csv') pre.Delete_Nan_Class_Row(train) pre.Fill_Nan_Values(train, struct) return process.Running_Algorithm(Path, Algorithm, train, test)
def test_connect_to_processing(self): import Processing engine = self.connectivityFixture() outports = Connectors(engine, "multi1", Connector.Port, Connector.Out) processing = Processing.Processing("multi2", engine) self.assertEqual(3, outports > processing) self.assertEqual([], engine.controlConnections()) self.assertEqual([ ('multi1', 'OutPort1', 'multi2', 'InPort1'), ('multi1', 'OutPort2', 'multi2', 'InPort2'), ('multi1', 'OutPort3', 'multi2', 'InPort3'), ], engine.portConnections())
def getSpo2(self,numSeconds, samplerate): print "begin measure" startTime = wiringpi.millis() Spo2 = Sp2.Spo2Sensor(sampleAvg= 8,sampleRate=samplerate) newSample = False AFthreshold= 17 Spo2.enableAfull() Spo2.setFIFOAF(AFthreshold) interrupt = Button(7) while wiringpi.millis()-startTime < numSeconds*1000: interrupt.when_activated = Spo2.sampleAvailable() if Spo2.newSample == True: Spo2.readSample() Spo2.newSample = False print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%" print "Buffer IR: ", len(Spo2.buffer_ir) print "Buffer Red: ", len(Spo2.buffer_red) pro = pr.Processing() #get Red and Ir buffers self.IR = Spo2.buffer_ir self.Red = Spo2.buffer_red #Delay Signal to avoid start overshoot #self.Red = pro.delaySignal(self.Red) #self.IR = pro.delaySignal(self. IR) #Median filter to the signals self.IR = sp.medfilt(self.IR) self.Red = sp.medfilt(self.Red) #low pass filter at 60hz #self.IR = pro.NotchFilter(self.IR, 60,samplerate) #self.Red = pro.NotchFilter(self.Red, 60,samplerate) #lowpass filter at 6Hz: #self.IR = pro.lowPasFIRFilter(self.IR, 6,samplerate) #self.Red = pro.lowPasFIRFilter(self.Red, 6,samplerate) #Compute Spo2Value: self.Spo2Value = pro.calcSpO2(self.Red,self.IR) print "Spo2: ", Spo2Value, "%" #get AC componente to plot the signal: self.Red = pro.getACcomponent(self.Red) self.IR = pro.getACcomponent(self.IR) self.IR = pro.Normalize(self.IR)
def getSpo2read(self, numSeconds): print "begin SPO2 measure" startTime = wiringpi.millis() newSample = False interrupt = Button(7) while wiringpi.millis() - startTime < numSeconds * 1000: interrupt.when_activated = self.Spo2.sampleAvailable() if self.Spo2.newSample == True: self.Spo2.readSample() self.Spo2.newSample = False #print (wiringpi.millis()-startTime)/1000 print "Spo2 measure ready" pro = pr.Processing() #get Red and Ir buffers self.IR = self.Spo2.buffer_ir self.Red = self.Spo2.buffer_red # #Normalize Red and IR signals self.Red = pro.Normalize(self.Red) self.IR = pro.Normalize(self.IR) #Butterword 4th order bandpass filter .5-6Hz self.IR = pro.BPButterFilter(self.IR, 0.5, 4.0, self.samplerateSpo2, 4) self.Red = pro.BPButterFilter(self.Red, 0.5, 4.0, self.samplerateSpo2, 4) #fft filtered dignal self.IR_Filtered_FFT = spfft.fft(self.IR) self.Red_Filtered_FFT = spfft.fft(self.Red) #Mean filter widnow = 4 # self.IR = pro.movMean(self.IR,4) # self.Red = pro.movMean(self.Red,4) self.Red = sp.medfilt(self.Red, 3) * -1 self.IR = sp.medfilt(self.IR, 3) * -1 self.Spo2Value = pro.calcSpO2(self.Red, self.IR) print "Spo2: ", self.Spo2Value, "%" self.HR = pro.heartRateCalc(self.IR)
import numpy as np from Processing import * """ almost all of these functions are really boring, just setters, getters and maybe a couple basic find functions; thus i've not really commented on anything, although the reasons behind me setting my classes up this way can be found from within the documentation if you're curious """ pp = Processing() class Country: def __init__(self, country_name, nStates): self.country = country_name self.states = np.empty(nStates, dtype=object) def __str__(self): return str(self.country) + ' ' + str(len(self.states)) def setStates(self, state_objects): for i, z in enumerate(state_objects): self.states[i] = z def getStates(self): return self.states def findState(self, state): i = 0 val = None
def host(self): import Processing return Processing.Processing( self.__dict__["host"], self._engine, )
usbPath = "/media/pi/VIDEOS" localPath = "/home/pi/Documents/localVids" # Main fileNameList = [] duration = 0 startTime = 0 stopTime = 0 # Device Initialization x = di.DeviceInitialization() while (x == -1): x = di.DeviceInitialization() print("SETUP COMPLETE \n") while (True): # Recording duration, fileNameList = rc.Recording() #print("Done Recording") #print("in driver Duration : ",duration) #print("in driver FNL : ",fileNameList) # Processing vr = pro.Processing(fileNameList, duration) #print("verify processing return :",vr) print("Done Procesing") # Finish di.finishInitialization()
print("\n") print("OUTPUTS : ", outputA23_1, outputA23_2) if ((type(outputA23_1) == float) and (type(outputA23_2) == list)): print("UNIT TEST A2, A3 RECORDING STATUS : PASS") else: print("UNIT TEST A2, A3 RECORDING STATUS : FAIL") print("\n") # UNIT TEST A4 print("UNIT TEST A4 : PROCESSING") print("INPUTS : 1. fileNameList (list object) 2. duration (float object)") print("EXPECTED OUTPUT : True") print("\n") inputA4_1 = outputA23_2 inputA4_2 = outputA23_1 # declaration of output outputA4 = "" if ((type(inputA4_1) == list) and (type(inputA4_2) == float) and (len(inputA4_1) == 2) and (inputA4_2 >= 0)): outputA4 = Processing.Processing(inputA4_1, inputA4_2) else: print("A4 INPUT CHECK FAILED") print("\n") if (outputA4 == True): print("UNIT TEST A4 PROCESSING STATUS : PASS") elif (outputA4 == False): print("UNIT TEST A4 PROCESSING STATUS : FAIL") print("\n")
import telebot import config import random import geocoder import Processing import time import questions import os process = Processing.Processing() bot = telebot.TeleBot(config.TOKEN) leaderboard = { 'Jamil': 20, 'Dima': 11, 'Maria': 15, 'Kirill': 5, 'lamoureux': 9 } IMAGES = "images" saved_facts = [] arenas = 3 quotes = [ ('Прогресс приходит к тем, кто тренируется изо дня в день. Полагающие на секретные техники ни к чему не придут.', 'Морихэй Уэсиба'), ('Причина моего провала очевидна: я мало тренировался. И кроме того, я мало тренировался. И еще — я мало тренировался. Это если так, вкратце.', 'Харуки Мураками'), ('Разум всегда сдается первым, не тело. Секрет в том, чтобы заставить твой разум работать на тебя, а не против тебя.', 'Арнольд Шварценеггер')
def main(): pp = Processing() # unserialize our data ready for use the_data = pp.unserialize('australia.pickle') # create the Australia Country object to improve readability as we go through Australia = Country('Australia', len(the_data)) Australia.setStates(the_data) # the user is going to go through three main selection phases: # 1. selecting their states of interest # 2. selecting their divisions/electorates of interest # 3. selecting their party/parties of interest # thus, we must create three different linked lists to store # this information because we have no way of knowing how many # of any of the choices the user might be making - need extensibility states = DSALinkedList() divisions = DSALinkedList() parties = DSALinkedList() print("Please select your state(s):") for i, z in enumerate(Australia.getStates()): # for each state print('[' + str(i + 1) + ']' + z.getCode() + ' ', end=' ') # print the index+1 (so we start at # one and not zero), and print the label next to that number print() selection1 = input("Selection: ").split( ',') # user makes a selection and we split it on ',' because # we're assuming they've read the documentation and will of course input a nice comma seperated list if selection1[0] in {'a', 'A'}: # check if they've selected all, and if so... for i in Australia.getStates(): # for each state states.insertLast( i.getCode()) # insert the code (i.e. 'WA') into states list else: # otherwise they must've selected some subset of them all selection1 = [int(i) for i in selection1] for i in selection1: # so for each of their selection(s) states.insertLast(Australia.getStates()[ i - 1].getCode()) # insert the code on the selection-1 print() print(states) # show users the states they've selected to reassure them # now that we have the user's selected states, we can reduce the search space # and have them select which electorates they're interested in within each # of their selected states for state in states: # for each state in their selected states big_string = '' # sometimes there're A LOT of electorates (like for NSW/VIC) # so I've made use of a package called 'textwrap' which makes sure that when # there's a huge set of text in the terminal, it's formatted correctly and # not half on the end of one line and the start of the next - it takes one big # string as input, hence why I've made this here print() print("Please select electorate(s) from " + state + ':') for j, z in enumerate(Australia.findState(state).getElectorates() ): # for electorate in the selected state big_string += '[' + str(j + 1) + ']' + z.getDivName( ) + ' ' # append this to the big string for line in textwrap.wrap( big_string ): # for each correctly formatted line in this big string print(line) # print the line selection2 = input("Selection: ").split( ',') # user makes a selection and we split it on ',' because # we're assuming they've read the documentation and will of course input a nice comma seperated list if selection2[0] in {'a', 'A' }: # check if they've selected all, and if so... for k in Australia.findState(state).getElectorates( ): # for each of the state's electorates divisions.insertLast( k.getDivName()) # insert their name to the divisions list else: # otherwise they must've selected some subset of them all selection2 = [int(i) for i in selection2] for k in selection2: # so for each of their selection(s) divisions.insertLast( Australia.findState(state).getElectorates()[ k - 1].getDivName()) # insert that electorate to list print() print(divisions ) # show users the divisions they've selected to reassure them print() # now, at this point we've reduced the search space significantly again, considering # we might even be looking in a couple of one state's electorates, there might only be # a few parties to choose from; so we have to find what these possible parties are # that our user can choose from possible_parties = DSALinkedList( ) # empty list again because extensibility for i in states: # for each of the user's states x = Australia.findState(i) # set x to be that state object if x != None: # saftey check for j in divisions: # for each of the users divisions y = x.findElectorate(j) # check if it's within this state if y != None: # if it IS in this state (not None) for k in y.getParties( ): # then for each party in this division possible_parties.insertLast(k.getPartyName( )) # add them to the list of possible parties possible_parties = np.array(list( set(possible_parties))) # can't go from set-object to np-array # so have to briefly cast to a python inbuilt list - pls don't mark me down, surely this barely counts possible_parties = DSASorts().insertionSort( possible_parties) # sort this list using insertion sort # because after researching apparently a small array of strings is actually pretty quick to sort # using insertion sort, despite it being O(N^2), because len(50) is nothing for a modern CPU I think? # anyway, now we have the set of possible parties in which # the user can make a choice, again we use textwrap to format print("Please select your partie(s):") big_string = '' for i, z in enumerate(possible_parties): if z == '': z = 'NONE' big_string += '[' + str(i + 1) + ']' + z + ' ' for line in textwrap.wrap(big_string): print(line) # prints each nicely formated line to shell print() selection3 = input("Selection: ").split( ',') # user makes a selection and we split it on ',' because # we're assuming they've read the documentation and will of course input a nice comma seperated list if selection3[0] in {'a', 'A'}: # check if they've selected all, and if so... for i in possible_parties: # for each of the possible parties parties.insertLast( i) # insert the party's name into the selected parties list else: # otherwise they must've selected some subset of them all selection3 = [int(i) for i in selection3] for i in selection3: # so for each of their selection(s) parties.insertLast(possible_parties[ i - 1]) # insert each selected party into the parties list print() print(parties ) # show users the party/parties they've selected to reassure them print() print('=================================') print() # put the parties into an array so we can sort them efficiently parties_array = np.empty(len(parties), dtype=object) for i, z in enumerate(parties): parties_array[i] = z parties = DSASorts().insertionSort(parties_array) # sort them filtered = DSALinkedList( ) # empty linked list to store the filtered candidates we'll # be searching through; if you've come from "nomineeList.py" this would be the results # of all your filtering - your results - and they're sent to into a menu in processing classs for i in states: # for each state the user selected x = Australia.findState(i) # set it to current if x != None: # saftey check for j in divisions: # for each division selected by the user y = x.findElectorate(j) # try and find it within current state if y != None: # if it IS found (not None) for k in parties: # for each party selected by the user z = y.findParty( k) # try find the party within the electorate if z != None: # if you DO find the party for candidate in z.getCandidates( ): # look at each candidate in the party filtered.insertLast( candidate ) # and add them to our filtered list results = DSALinkedList() # empty list for our results # finally, we have to let the user input some sort of substring # and if it matches some part of the filtered candidates first name # or last name, then they need to be added to the results for processing ## NOTE: I interpretted this question "searching for a substring, starting # with the first character of last name" as: # 1. user enters substring # 2. you check if substring matches the last_name[0:len(substring)] # 3. if it doesn't then you check last_name[1:len(substring)], then last_name[2:len(substring)], etc # 4. if this yields no results then repeat process with first name # # this whole process is simply the 'in' keyword function in python so i've used that print("Who are you looking for: ") selection4 = input("Selection: ") for i in filtered: # for each candidate we've filtered down if selection4.lower() in i.getFname().lower() or selection4.lower( ) in i.getLname().lower(): # if substring is in f/lname results.insertLast(i) # add it to the results list # now we send all the necessary information in a nice neat package to be processed into # a menu where the user can choose to save this information as either printable output, # a csv file, a serialized file, or any combination of these actions pp2 = ResultsProcessing() # initiate our results processing class pp2.resultsMenu(results) # send data off to be processed into a menu # and once they exit out of the menu they'll return back here, a blank line will be printed # and they'll be sent back to the main menu to perform another process if they decide to print()
def main(): pp = Processing() the_data = pp.unserialize('australia.pickle') Australia = Country('Australia', len(the_data)) Australia.setStates(the_data) states = DSALinkedList() divisions = DSALinkedList() parties = DSALinkedList() print("Please select your state(s):") for i,z in enumerate(Australia.getStates()): print('['+str(i+1)+']'+z.getCode()+' ', end = ' ') print() selection1 = input("Selection: ").split(',') if selection1[0] in {'a', 'A'}: for i in Australia.getStates(): states.insertLast(i.getCode()) else: selection1 = [int(i) for i in selection1] for i in selection1: states.insertLast(Australia.getStates()[i-1].getCode()) print() print(states) for i in states: test = '' print() print("Please select electorate(s) from " + i + ':') for j,z in enumerate(Australia.findState(i).getElectorates()): test += '['+str(j+1)+']'+z.getDivName()+' ' for line in textwrap.wrap(test): print(line) selection2 = input("Selection: ").split(',') if selection2[0] in {'a', 'A'}: for k in Australia.findState(i).getElectorates(): divisions.insertLast(k.getDivName()) else: selection2 = [int(i) for i in selection2] for k in selection2: divisions.insertLast(Australia.findState(i).getElectorates()[k-1].getDivName()) print() print(divisions) print() possible_parties = DSALinkedList() for i in states: x = Australia.findState(i) if x != None: for j in divisions: y = x.findElectorate(j) if y != None: for k in y.getParties(): possible_parties.insertLast(k.getPartyName()) possible_parties = np.array(list(set(possible_parties))) # can't go from set-object to np-array, so have to briefly cast to Python list possible_parties = DSASorts().insertionSort(possible_parties) print("Please select your partie(s):") test = '' for i,z in enumerate(possible_parties): if z == '': z = 'NONE' test += '['+str(i+1)+']'+z+' ' for line in textwrap.wrap(test): print(line) print() selection3 = input("Selection: ").split(',') if selection3[0] in {'a', 'A'}: for i in possible_parties: parties.insertLast(i) else: selection3 = [int(i) for i in selection3] for i in selection3: parties.insertLast(possible_parties[i-1]) print() print(parties) print() print('=================================') print() parties_array = np.empty(len(parties), dtype = object) for i,z in enumerate(parties): parties_array[i] = z parties = DSASorts().insertionSort(parties_array) results = DSALinkedList() for i in states: x = Australia.findState(i) if x != None: for j in divisions: y = x.findElectorate(j) if y != None: for k in parties: z = y.findParty(k) if z != None: for candidate in z.getCandidates(): results.insertLast(candidate) pp2 = ResultsProcessing() pp2.resultsMenu(results) # and once they exit out of the menu they'll return back here, a blank line will be printed # and they'll be sent back to the main menu to perform another process if they decide to print()
bottomframe = Frame(root) bottomframe.pack(side='bottom') frame = Frame(root) frame.pack(side='bottom') # root.minsize(width=400,height=500) panelA = None panelB = None prg_bar = ttk.Progressbar(bottomframe,orient=HORIZONTAL,length = 200,mode='indeterminate') prg_bar.grid(row=1,columnspan=2,padx=10,pady=10) transform = ImageTransform.ImageTransform() segmentation = ImageSegmentaion.ImageSegmentation() processing = Processing.Processing(panelA,panelB,topframe,prg_bar) # Select image for feature matching def select_image(): # Declare global variables global panelA,panelB,img,im_canny,topframe,path,ballot_path,prg_bar # prg_bar.start(50) if len(path)>0 and len(ballot_path)>0: count = len([file for file in os.listdir(ballot_path) if file.endswith('.jpg')]) for file in os.listdir(ballot_path): if file.endswith('.jpg'): loc_path = ballot_path+'/'+file print('processing image: '+str(file)) if len(loc_path)>0:
def main(): pp = Processing() # unserialize our data ready for use the_data = pp.unserialize('australia.pickle') # create the Australia Country object to improve readability as we go through Australia = Country('Australia', len(the_data)) Australia.setStates(the_data) # difficult to find the total number of unique parties # in all our data easily, so instead it makes a lot more # sense to create a linked list and just store every party # in here as we iterate past it possible_parties = DSALinkedList() # empty linked list # this iterates through all parties, in all electorates, in all states for i in Australia.getStates(): for j in i.getElectorates(): for z in j.getParties(): possible_parties.insertLast(z.getPartyName( )) # and inserts the party into the empty linked list # now, there's of course going to be double ups, as multiple parties can exist # across multiple different electorates/states, so we need the unique set... possible_parties = np.array(list( set(possible_parties))) # can't go from set-object to np-array # so have to briefly cast to a python inbuilt list - pls don't mark me down, surely this barely counts possible_parties = DSASorts().insertionSort( possible_parties) # sort this list using insertion sort # because after researching apparently a small array of strings is actually pretty quick to sort # using insertion sort, despite it being O(N^2), because len(50) is nothing for a modern CPU I think? # anyway, now we have the full list of unique parties in which the user # can make their selection, but we need to show them their options! # when giving the user 50+ parties to choose from it was a lot of text and # it looked really messy in terminal, so I did a bit of googling and found # a package called 'textwrap' which makes everything look nice and not # half cross over lines - it takes one big long string as input so that's # why I've created this: long_string = '' print("Please select your party (or parties):") for i, z in enumerate(possible_parties): if z == '': z = 'NONE' long_string += '[' + str( i + 1) + ']' + z + ' ' # add the option to the long string for line in textwrap.wrap( long_string): # use text-wrap to wrap the long string print(line) # then print each nice formatted line to the user print() # now, the user can of course make multiple choices here so an array would # be suboptimal, a linked list is a much better way to store the information # since it can be appended to depending on the amount of selecitons our user makes parties = DSALinkedList() # empty list to hold user selection selection = input("Selection: ").split(',') if selection[0] in {'a', 'A'}: # if user selects (a/A)ll for i in possible_parties: # go through all possible parties parties.insertLast(i) # and select everything else: # otherwise they must've entered a nice comma seperated list # like the documentation says, DEFINITELY WOULDN'T BE ANY PROBLEMS HERE selection = [int(i) for i in selection] # so we convert their selctions from # strings to integer values for i in selection: # and then for each selection they've made parties.insertLast( possible_parties[i - 1]) # we index all possible parties # on this selection (i-1 because our selection list starts at 1 not 0), and # then we just append their selection to the linked list print( parties ) # show the user's their selections so they can panic if they misselected print() print("Please enter your margin:") selection = input("Value: ") # agaian, the user will definitely # enter a nice value between 0 and 1 which can be converted to a # float... right? right????? margin = float(selection) print(margin) # show user their selected margin print() # again, we have no idea how many marginal electorates we might find # so we need a linked list to store the data results = DSALinkedList() for i in Australia.getStates(): # for each state for j in i.getElectorates(): # for each electorate get_votes = DSALinkedList( ) # create an empty linked list to store the electorate's votes for k in j.getParties(): # for each party in the electorate get_votes.insertLast(k.getVotes( )) # append their votes to the electorate specific list # then we find the percentage difference that each party has with the most voted party in that electorate # here i could have used my own sorting method to sort the linked list and then use the last element # as the maximum, but considering it's one small calculation, for readability, to reduce code complexity, # and mainly because i really don't want to break my code at this point - i'm just going to leave it like this get_vote_pct = [(abs(l - max(get_votes)) / max(get_votes)) for l in get_votes] # now we have the percentage difference between votes, but # we have to see if they fall within the user's margin marginal_parties = DSALinkedList() for x, z in enumerate(get_vote_pct): if z == 0.0: # if there's no percentage difference this means this is the maximum voted party marginal_parties.insertLast( x) # so we insert its index into a list because # we're going to assume that we'll find a marginal match to go with it elif z != 0.0 and z <= margin: # and if we find a percentage difference within the margin marginal_parties.insertLast( x) # we have a match and add its index to the list too if len( marginal_parties ) == 1: # but if our list is only of len(1) it means we never # actually found a marginal match to go along with the maximum party, so do nothing pass else: # otherwise we have a >len(1) list, marginal parties, so we need to grab them for p in marginal_parties: # but we're only concerned with marginal parties that involve the parties that the # user had previously selected, so for each marginal party, if it's user selected... if j.getParties()[p].getPartyName() in parties: results.insertLast( j.getParties() [p]) # ... add it to the results list # now we send all the necessary information in a nice neat package to be processed into # a menu where the user can choose to save this information as either printable output, # a csv file, a serialized file, or any combination of these actions pp2 = ResultsProcessing() # initiate our results processing class pp2.marginalResultsMenu( Australia, parties, margin, results) # send data off to be processed into a menu # and once they exit out of the menu they'll return back here, a blank line will be printed # and they'll be sent back to the main menu to perform another process if they decide to print()