def run(self): count = 0 previous = {} # Used to keep track of previous predictions self.parent.sendPacket.value = True q = multiQueue() last = bciComms.discardTill(self.parent.pipeReceive, self.parent.endPacketRegex, self.parent.headerRegex) last = int(last) collecting = True while True: count += 1 last = bciComms.collectData(self.parent.pipeReceive, self.period, self.parent.headerRegex, self.parent.endPacketRegex, q, last) data = q.get() # Takes the raw data and decomposes it into a dict of the corresponding terms processed = bciComms.rawToDict(data) classWith = self.parent.trainingDataFormater.formatFrequencies(processed["Raw FFT"]) prediction = None accuracy = None try: prediction, accuracy = self.classifier.predict(classWith) except Exception: continue # Changed what predict returns accuracy = accuracy[prediction] if count * self.period < self.timeout and collecting: if not previous.has_key(prediction): previous[prediction] = 0.0 previous[prediction] += accuracy elif collecting: likely = sorted(previous, key=previous.get, reverse=True)[0] if previous[likely] < count * self.threshold: self.coms.txt.emit("None") else: self.coms.txt.emit(likely) previous = {} count = 0 collecting = False elif count * self.period < self.timeout and not collecting: self.coms.txt.emit("Robot Moving") elif not collecting: collecting = True count = 0 self.coms.txt.emit("")
def run(self): self.parent.sendPacket.value = True q = multiQueue() last = bciComms.discardTill(self.parent.pipeReceive, self.parent.endPacketRegex, self.parent.headerRegex) last = int(last) count = 0 priors = self.classifier.priors while True: newQuestion = self.runner.new last = bciComms.collectData(self.parent.pipeReceive, self.period, self.parent.headerRegex, self.parent.endPacketRegex, q, last) data = q.get() # A new question has not arrived if not newQuestion: continue count += 1 # Want to give the user a second to read the text and ignore the brain signals if count * self.period < 1.0: continue # Takes the raw data and decomposes it into a dict of the corresponding terms processed = bciComms.rawToDict(data) classWith = self.parent.trainingDataFormater.formatFrequencies(processed["Raw FFT"]) logging.info(processed["Raw FFT"]) probs = None try: _, probs = self.classifier.predict(classWith) except Exception: continue # Updating priors for k,v in probs.iteritems(): priors[k] *= v # Renormalizing s = sum(priors.values()) priors = {k: priors[k] / s for k in priors} print count # Emit prediction if time has exceeded 6 seconds or hit threshold highest = max(priors, key=lambda k: priors[k]) if count * self.period >= 6.0 or priors[highest] >= self.threshold: self.coms.txt.emit(highest) self.runner.new = False count = 0 priors = self.classifier.priors
def trainingScreen(self): """ Displays a training screen that displays arrows to different frequency lights and records the data within each of these periods. Saves this data in a JSON file """ window = drawWidget(self) # Creates a random ordering of the trials channels = [str(i) for i in self.settings["channels"].values() if not i == "None"] trials = self.settings["numTrials"] time = self.settings["trialLength"] bciData = {} for t in range(trials): print (t+1), "/", trials random.shuffle(channels) bciData[t] = {} for c in channels: # Setup param = self.settings["freqMap"][c] q = multiQueue() window.drawCrossTimed(0.4, 3, True) # Starting storing packets sent through the pipe when a # batch arriving from BCI2000 completes. This is signalled # by the last Signal(X,Y) received. self.sendPacket.value = True lastStamp = bciComms.discardTill(self.pipeReceive, self.endPacketRegex, self.headerRegex) lastStamp = int(lastStamp) collectProc = Process(target=bciComms.collectData, args=(self.pipeReceive, time, self.headerRegex, self.endPacketRegex, q, lastStamp)) collectProc.start() window.drawArrowTimed(param["x"], param["y"], 200, param["theta"], time, True) bciData[t][c] = q.get() self.writeFile(bciData[t][c], t, c) self.sendPacket.value = False # Write the training data to a file, and get the formated training data fName, _ = QtGui.QFileDialog.getSaveFileName(self, "Save the test data", "", "JSON (*.json)", "JSON (*.json)") # User didn't pick a filename, ask them again and if repeated return if fName == "": self.showMessage("You didn't select a file! Try again otherwise data is lost") fName, _ = QtGui.QFileDialog.getSaveFileName(self, "Save the test data", "", "JSON (*.json)", "JSON (*.json)") if fName == "": window.close() return formatedJson = None # List of frequencies collected on freqList = [int(x.split(" ")[0]) for x in channels] freqList.sort() with open(fName, "w") as f: formatedJson = bciComms.processTrainData(bciData, freqList, f) # Saves the training data to the instance field, trains the classifier and transitions to run screen self.trainingDataFormater = FormatJson(formatedJson, loadDict=True) if self.trainClassifier(): self.transitionToRun() window.close()